You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

404 lines
13 KiB

6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
9 months ago
5 years ago
3 years ago
6 years ago
9 months ago
6 years ago
6 years ago
6 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/httputil"
  7. "net/url"
  8. "os"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/seaweedfs/seaweedfs/weed/stats"
  14. "github.com/seaweedfs/seaweedfs/weed/cluster"
  15. "github.com/seaweedfs/seaweedfs/weed/pb"
  16. "github.com/gorilla/mux"
  17. hashicorpRaft "github.com/hashicorp/raft"
  18. "github.com/seaweedfs/raft"
  19. "google.golang.org/grpc"
  20. "github.com/seaweedfs/seaweedfs/weed/glog"
  21. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  22. "github.com/seaweedfs/seaweedfs/weed/security"
  23. "github.com/seaweedfs/seaweedfs/weed/sequence"
  24. "github.com/seaweedfs/seaweedfs/weed/shell"
  25. "github.com/seaweedfs/seaweedfs/weed/topology"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. "github.com/seaweedfs/seaweedfs/weed/wdclient"
  28. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  29. )
  30. const (
  31. SequencerType = "master.sequencer.type"
  32. SequencerSnowflakeId = "master.sequencer.sequencer_snowflake_id"
  33. )
  34. type MasterOption struct {
  35. Master pb.ServerAddress
  36. MetaFolder string
  37. VolumeSizeLimitMB uint32
  38. VolumePreallocate bool
  39. // PulseSeconds int
  40. DefaultReplicaPlacement string
  41. GarbageThreshold float64
  42. WhiteList []string
  43. DisableHttp bool
  44. MetricsAddress string
  45. MetricsIntervalSec int
  46. IsFollower bool
  47. }
  48. type MasterServer struct {
  49. master_pb.UnimplementedSeaweedServer
  50. option *MasterOption
  51. guard *security.Guard
  52. preallocateSize int64
  53. Topo *topology.Topology
  54. vg *topology.VolumeGrowth
  55. volumeGrowthRequestChan chan *topology.VolumeGrowRequest
  56. boundedLeaderChan chan int
  57. // notifying clients
  58. clientChansLock sync.RWMutex
  59. clientChans map[string]chan *master_pb.KeepConnectedResponse
  60. grpcDialOption grpc.DialOption
  61. MasterClient *wdclient.MasterClient
  62. adminLocks *AdminLocks
  63. Cluster *cluster.Cluster
  64. }
  65. func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.ServerAddress) *MasterServer {
  66. v := util.GetViper()
  67. signingKey := v.GetString("jwt.signing.key")
  68. v.SetDefault("jwt.signing.expires_after_seconds", 10)
  69. expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
  70. readSigningKey := v.GetString("jwt.signing.read.key")
  71. v.SetDefault("jwt.signing.read.expires_after_seconds", 60)
  72. readExpiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
  73. v.SetDefault("master.replication.treat_replication_as_minimums", false)
  74. replicationAsMin := v.GetBool("master.replication.treat_replication_as_minimums")
  75. v.SetDefault("master.volume_growth.copy_1", topology.VolumeGrowStrategy.Copy1Count)
  76. v.SetDefault("master.volume_growth.copy_2", topology.VolumeGrowStrategy.Copy2Count)
  77. v.SetDefault("master.volume_growth.copy_3", topology.VolumeGrowStrategy.Copy3Count)
  78. v.SetDefault("master.volume_growth.copy_other", topology.VolumeGrowStrategy.CopyOtherCount)
  79. v.SetDefault("master.volume_growth.threshold", topology.VolumeGrowStrategy.Threshold)
  80. topology.VolumeGrowStrategy.Copy1Count = v.GetUint32("master.volume_growth.copy_1")
  81. topology.VolumeGrowStrategy.Copy2Count = v.GetUint32("master.volume_growth.copy_2")
  82. topology.VolumeGrowStrategy.Copy3Count = v.GetUint32("master.volume_growth.copy_3")
  83. topology.VolumeGrowStrategy.CopyOtherCount = v.GetUint32("master.volume_growth.copy_other")
  84. topology.VolumeGrowStrategy.Threshold = v.GetFloat64("master.volume_growth.threshold")
  85. var preallocateSize int64
  86. if option.VolumePreallocate {
  87. preallocateSize = int64(option.VolumeSizeLimitMB) * (1 << 20)
  88. }
  89. grpcDialOption := security.LoadClientTLS(v, "grpc.master")
  90. ms := &MasterServer{
  91. option: option,
  92. preallocateSize: preallocateSize,
  93. volumeGrowthRequestChan: make(chan *topology.VolumeGrowRequest, 1<<6),
  94. clientChans: make(map[string]chan *master_pb.KeepConnectedResponse),
  95. grpcDialOption: grpcDialOption,
  96. MasterClient: wdclient.NewMasterClient(grpcDialOption, "", cluster.MasterType, option.Master, "", "", *pb.NewServiceDiscoveryFromMap(peers)),
  97. adminLocks: NewAdminLocks(),
  98. Cluster: cluster.NewCluster(),
  99. }
  100. ms.boundedLeaderChan = make(chan int, 16)
  101. ms.MasterClient.SetOnPeerUpdateFn(ms.OnPeerUpdate)
  102. seq := ms.createSequencer(option)
  103. if nil == seq {
  104. glog.Fatalf("create sequencer failed.")
  105. }
  106. ms.Topo = topology.NewTopology("topo", seq, uint64(ms.option.VolumeSizeLimitMB)*1024*1024, 5, replicationAsMin)
  107. ms.vg = topology.NewDefaultVolumeGrowth()
  108. glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
  109. ms.guard = security.NewGuard(ms.option.WhiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
  110. handleStaticResources2(r)
  111. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  112. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  113. if !ms.option.DisableHttp {
  114. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  115. r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
  116. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  117. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  118. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  119. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  120. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  121. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  122. r.HandleFunc("/collection/info", ms.guard.WhiteList(ms.collectionInfoHandler))
  123. /*
  124. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  125. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  126. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  127. */
  128. r.HandleFunc("/{fileId}", ms.redirectHandler)
  129. }
  130. ms.Topo.StartRefreshWritableVolumes(
  131. ms.grpcDialOption,
  132. ms.option.GarbageThreshold,
  133. topology.VolumeGrowStrategy.Threshold,
  134. ms.preallocateSize,
  135. )
  136. ms.ProcessGrowRequest()
  137. if !option.IsFollower {
  138. ms.startAdminScripts()
  139. }
  140. return ms
  141. }
  142. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  143. var raftServerName string
  144. ms.Topo.RaftServerAccessLock.Lock()
  145. if raftServer.raftServer != nil {
  146. ms.Topo.RaftServer = raftServer.raftServer
  147. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  148. glog.V(0).Infof("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  149. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", e.Value())).Inc()
  150. if ms.Topo.RaftServer.Leader() != "" {
  151. glog.V(0).Infof("[%s] %s becomes leader.", ms.Topo.RaftServer.Name(), ms.Topo.RaftServer.Leader())
  152. }
  153. })
  154. raftServerName = fmt.Sprintf("[%s]", ms.Topo.RaftServer.Name())
  155. } else if raftServer.RaftHashicorp != nil {
  156. ms.Topo.HashicorpRaft = raftServer.RaftHashicorp
  157. raftServerName = ms.Topo.HashicorpRaft.String()
  158. }
  159. ms.Topo.RaftServerAccessLock.Unlock()
  160. if ms.Topo.IsLeader() {
  161. glog.V(0).Infof("%s I am the leader!", raftServerName)
  162. } else {
  163. var raftServerLeader string
  164. ms.Topo.RaftServerAccessLock.RLock()
  165. if ms.Topo.RaftServer != nil {
  166. raftServerLeader = ms.Topo.RaftServer.Leader()
  167. } else if ms.Topo.HashicorpRaft != nil {
  168. raftServerName = ms.Topo.HashicorpRaft.String()
  169. raftServerLeaderAddr, _ := ms.Topo.HashicorpRaft.LeaderWithID()
  170. raftServerLeader = string(raftServerLeaderAddr)
  171. }
  172. ms.Topo.RaftServerAccessLock.RUnlock()
  173. glog.V(0).Infof("%s %s - is the leader.", raftServerName, raftServerLeader)
  174. }
  175. }
  176. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  177. return func(w http.ResponseWriter, r *http.Request) {
  178. if ms.Topo.IsLeader() {
  179. f(w, r)
  180. return
  181. }
  182. // get the current raft leader
  183. leaderAddr, _ := ms.Topo.MaybeLeader()
  184. raftServerLeader := leaderAddr.ToHttpAddress()
  185. if raftServerLeader == "" {
  186. f(w, r)
  187. return
  188. }
  189. ms.boundedLeaderChan <- 1
  190. defer func() { <-ms.boundedLeaderChan }()
  191. targetUrl, err := url.Parse("http://" + raftServerLeader)
  192. if err != nil {
  193. writeJsonError(w, r, http.StatusInternalServerError,
  194. fmt.Errorf("Leader URL http://%s Parse Error: %v", raftServerLeader, err))
  195. return
  196. }
  197. // proxy to leader
  198. glog.V(4).Infoln("proxying to leader", raftServerLeader)
  199. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  200. director := proxy.Director
  201. proxy.Director = func(req *http.Request) {
  202. actualHost, err := security.GetActualRemoteHost(req)
  203. if err == nil {
  204. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  205. }
  206. director(req)
  207. }
  208. proxy.Transport = util_http.GetGlobalHttpClient().GetClientTransport()
  209. proxy.ServeHTTP(w, r)
  210. }
  211. }
  212. func (ms *MasterServer) startAdminScripts() {
  213. v := util.GetViper()
  214. adminScripts := v.GetString("master.maintenance.scripts")
  215. if adminScripts == "" {
  216. return
  217. }
  218. glog.V(0).Infof("adminScripts: %v", adminScripts)
  219. v.SetDefault("master.maintenance.sleep_minutes", 17)
  220. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  221. scriptLines := strings.Split(adminScripts, "\n")
  222. if !strings.Contains(adminScripts, "lock") {
  223. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  224. scriptLines = append(scriptLines, "unlock")
  225. }
  226. masterAddress := string(ms.option.Master)
  227. var shellOptions shell.ShellOptions
  228. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  229. shellOptions.Masters = &masterAddress
  230. shellOptions.Directory = "/"
  231. emptyFilerGroup := ""
  232. shellOptions.FilerGroup = &emptyFilerGroup
  233. commandEnv := shell.NewCommandEnv(&shellOptions)
  234. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  235. go commandEnv.MasterClient.KeepConnectedToMaster(context.Background())
  236. go func() {
  237. for {
  238. time.Sleep(time.Duration(sleepMinutes) * time.Minute)
  239. if ms.Topo.IsLeader() && ms.MasterClient.GetMaster(context.Background()) != "" {
  240. shellOptions.FilerAddress = ms.GetOneFiler(cluster.FilerGroupName(*shellOptions.FilerGroup))
  241. if shellOptions.FilerAddress == "" {
  242. continue
  243. }
  244. for _, line := range scriptLines {
  245. for _, c := range strings.Split(line, ";") {
  246. processEachCmd(reg, c, commandEnv)
  247. }
  248. }
  249. }
  250. }
  251. }()
  252. }
  253. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  254. cmds := reg.FindAllString(line, -1)
  255. if len(cmds) == 0 {
  256. return
  257. }
  258. args := make([]string, len(cmds[1:]))
  259. for i := range args {
  260. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  261. }
  262. cmd := cmds[0]
  263. for _, c := range shell.Commands {
  264. if c.Name() == cmd {
  265. glog.V(0).Infof("executing: %s %v", cmd, args)
  266. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  267. glog.V(0).Infof("error: %v", err)
  268. }
  269. }
  270. }
  271. }
  272. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  273. var seq sequence.Sequencer
  274. v := util.GetViper()
  275. seqType := strings.ToLower(v.GetString(SequencerType))
  276. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  277. switch strings.ToLower(seqType) {
  278. case "snowflake":
  279. var err error
  280. snowflakeId := v.GetInt(SequencerSnowflakeId)
  281. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  282. if err != nil {
  283. glog.Error(err)
  284. seq = nil
  285. }
  286. case "raft":
  287. fallthrough
  288. default:
  289. seq = sequence.NewMemorySequencer()
  290. }
  291. return seq
  292. }
  293. func (ms *MasterServer) OnPeerUpdate(update *master_pb.ClusterNodeUpdate, startFrom time.Time) {
  294. ms.Topo.RaftServerAccessLock.RLock()
  295. defer ms.Topo.RaftServerAccessLock.RUnlock()
  296. if update.NodeType != cluster.MasterType || ms.Topo.HashicorpRaft == nil {
  297. return
  298. }
  299. glog.V(4).Infof("OnPeerUpdate: %+v", update)
  300. peerAddress := pb.ServerAddress(update.Address)
  301. peerName := string(peerAddress)
  302. if ms.Topo.HashicorpRaft.State() != hashicorpRaft.Leader {
  303. return
  304. }
  305. if update.IsAdd {
  306. raftServerFound := false
  307. for _, server := range ms.Topo.HashicorpRaft.GetConfiguration().Configuration().Servers {
  308. if string(server.ID) == peerName {
  309. raftServerFound = true
  310. }
  311. }
  312. if !raftServerFound {
  313. glog.V(0).Infof("adding new raft server: %s", peerName)
  314. ms.Topo.HashicorpRaft.AddVoter(
  315. hashicorpRaft.ServerID(peerName),
  316. hashicorpRaft.ServerAddress(peerAddress.ToGrpcAddress()), 0, 0)
  317. }
  318. } else {
  319. pb.WithMasterClient(false, peerAddress, ms.grpcDialOption, true, func(client master_pb.SeaweedClient) error {
  320. ctx, cancel := context.WithTimeout(context.TODO(), 15*time.Second)
  321. defer cancel()
  322. if _, err := client.Ping(ctx, &master_pb.PingRequest{Target: string(peerAddress), TargetType: cluster.MasterType}); err != nil {
  323. glog.V(0).Infof("master %s didn't respond to pings. remove raft server", peerName)
  324. if err := ms.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  325. _, err := client.RaftRemoveServer(context.Background(), &master_pb.RaftRemoveServerRequest{
  326. Id: peerName,
  327. Force: false,
  328. })
  329. return err
  330. }); err != nil {
  331. glog.Warningf("failed removing old raft server: %v", err)
  332. return err
  333. }
  334. } else {
  335. glog.V(0).Infof("master %s successfully responded to ping", peerName)
  336. }
  337. return nil
  338. })
  339. }
  340. }
  341. func (ms *MasterServer) Shutdown() {
  342. if ms.Topo == nil || ms.Topo.HashicorpRaft == nil {
  343. return
  344. }
  345. if ms.Topo.HashicorpRaft.State() == hashicorpRaft.Leader {
  346. ms.Topo.HashicorpRaft.LeadershipTransfer()
  347. }
  348. ms.Topo.HashicorpRaft.Shutdown()
  349. }