master_server.go 13 KB

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