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.

418 lines
14 KiB

6 years ago
6 years ago
6 years ago
6 years ago
10 months ago
5 years ago
3 years ago
6 years ago
10 months 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. 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. // 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. whiteList := util.StringSplit(v.GetString("guard.white_list"), ",")
  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.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(append(ms.option.WhiteList, 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. ms.option.MaxParallelVacuumPerServer,
  134. topology.VolumeGrowStrategy.Threshold,
  135. ms.preallocateSize,
  136. )
  137. ms.ProcessGrowRequest()
  138. if !option.IsFollower {
  139. ms.startAdminScripts()
  140. }
  141. return ms
  142. }
  143. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  144. var raftServerName string
  145. ms.Topo.RaftServerAccessLock.Lock()
  146. if raftServer.raftServer != nil {
  147. ms.Topo.RaftServer = raftServer.raftServer
  148. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  149. glog.V(0).Infof("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  150. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", e.Value())).Inc()
  151. if ms.Topo.RaftServer.Leader() != "" {
  152. glog.V(0).Infof("[%s] %s becomes leader.", ms.Topo.RaftServer.Name(), ms.Topo.RaftServer.Leader())
  153. ms.Topo.LastLeaderChangeTime = time.Now()
  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. ms.Topo.LastLeaderChangeTime = time.Now()
  161. }
  162. ms.Topo.RaftServerAccessLock.Unlock()
  163. if ms.Topo.IsLeader() {
  164. glog.V(0).Infof("%s I am the leader!", raftServerName)
  165. } else {
  166. var raftServerLeader string
  167. ms.Topo.RaftServerAccessLock.RLock()
  168. if ms.Topo.RaftServer != nil {
  169. raftServerLeader = ms.Topo.RaftServer.Leader()
  170. } else if ms.Topo.HashicorpRaft != nil {
  171. raftServerName = ms.Topo.HashicorpRaft.String()
  172. raftServerLeaderAddr, _ := ms.Topo.HashicorpRaft.LeaderWithID()
  173. raftServerLeader = string(raftServerLeaderAddr)
  174. }
  175. ms.Topo.RaftServerAccessLock.RUnlock()
  176. glog.V(0).Infof("%s %s - is the leader.", raftServerName, raftServerLeader)
  177. }
  178. }
  179. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  180. return func(w http.ResponseWriter, r *http.Request) {
  181. if ms.Topo.IsLeader() {
  182. f(w, r)
  183. return
  184. }
  185. // get the current raft leader
  186. leaderAddr, _ := ms.Topo.MaybeLeader()
  187. raftServerLeader := leaderAddr.ToHttpAddress()
  188. if raftServerLeader == "" {
  189. f(w, r)
  190. return
  191. }
  192. targetUrl, err := url.Parse("http://" + raftServerLeader)
  193. if err != nil {
  194. writeJsonError(w, r, http.StatusInternalServerError,
  195. fmt.Errorf("Leader URL http://%s Parse Error: %v", raftServerLeader, err))
  196. return
  197. }
  198. // proxy to leader
  199. glog.V(4).Infoln("proxying to leader", raftServerLeader)
  200. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  201. director := proxy.Director
  202. proxy.Director = func(req *http.Request) {
  203. actualHost, err := security.GetActualRemoteHost(req)
  204. if err == nil {
  205. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  206. }
  207. director(req)
  208. }
  209. proxy.Transport = util_http.GetGlobalHttpClient().GetClientTransport()
  210. proxy.ServeHTTP(w, r)
  211. }
  212. }
  213. func (ms *MasterServer) startAdminScripts() {
  214. v := util.GetViper()
  215. adminScripts := v.GetString("master.maintenance.scripts")
  216. if adminScripts == "" {
  217. return
  218. }
  219. glog.V(0).Infof("adminScripts: %v", adminScripts)
  220. v.SetDefault("master.maintenance.sleep_minutes", 17)
  221. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  222. scriptLines := strings.Split(adminScripts, "\n")
  223. if !strings.Contains(adminScripts, "lock") {
  224. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  225. scriptLines = append(scriptLines, "unlock")
  226. }
  227. masterAddress := string(ms.option.Master)
  228. var shellOptions shell.ShellOptions
  229. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  230. shellOptions.Masters = &masterAddress
  231. shellOptions.Directory = "/"
  232. emptyFilerGroup := ""
  233. shellOptions.FilerGroup = &emptyFilerGroup
  234. commandEnv := shell.NewCommandEnv(&shellOptions)
  235. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  236. go commandEnv.MasterClient.KeepConnectedToMaster(context.Background())
  237. go func() {
  238. for {
  239. time.Sleep(time.Duration(sleepMinutes) * time.Minute)
  240. if ms.Topo.IsLeader() && ms.MasterClient.GetMaster(context.Background()) != "" {
  241. shellOptions.FilerAddress = ms.GetOneFiler(cluster.FilerGroupName(*shellOptions.FilerGroup))
  242. if shellOptions.FilerAddress == "" {
  243. continue
  244. }
  245. for _, line := range scriptLines {
  246. for _, c := range strings.Split(line, ";") {
  247. processEachCmd(reg, c, commandEnv)
  248. }
  249. }
  250. }
  251. }
  252. }()
  253. }
  254. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  255. cmds := reg.FindAllString(line, -1)
  256. if len(cmds) == 0 {
  257. return
  258. }
  259. args := make([]string, len(cmds[1:]))
  260. for i := range args {
  261. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  262. }
  263. cmd := cmds[0]
  264. for _, c := range shell.Commands {
  265. if c.Name() == cmd {
  266. if c.HasTag(shell.ResourceHeavy) {
  267. glog.Warningf("%s is resource heavy and should not run on master", cmd)
  268. continue
  269. }
  270. glog.V(0).Infof("executing: %s %v", cmd, args)
  271. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  272. glog.V(0).Infof("error: %v", err)
  273. }
  274. }
  275. }
  276. }
  277. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  278. var seq sequence.Sequencer
  279. v := util.GetViper()
  280. seqType := strings.ToLower(v.GetString(SequencerType))
  281. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  282. switch strings.ToLower(seqType) {
  283. case "snowflake":
  284. var err error
  285. snowflakeId := v.GetInt(SequencerSnowflakeId)
  286. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  287. if err != nil {
  288. glog.Error(err)
  289. seq = nil
  290. }
  291. case "raft":
  292. fallthrough
  293. default:
  294. seq = sequence.NewMemorySequencer()
  295. }
  296. return seq
  297. }
  298. func (ms *MasterServer) OnPeerUpdate(update *master_pb.ClusterNodeUpdate, startFrom time.Time) {
  299. ms.Topo.RaftServerAccessLock.RLock()
  300. defer ms.Topo.RaftServerAccessLock.RUnlock()
  301. if update.NodeType != cluster.MasterType || ms.Topo.HashicorpRaft == nil {
  302. return
  303. }
  304. glog.V(4).Infof("OnPeerUpdate: %+v", update)
  305. peerAddress := pb.ServerAddress(update.Address)
  306. peerName := string(peerAddress)
  307. if ms.Topo.HashicorpRaft.State() != hashicorpRaft.Leader {
  308. return
  309. }
  310. if update.IsAdd {
  311. raftServerFound := false
  312. for _, server := range ms.Topo.HashicorpRaft.GetConfiguration().Configuration().Servers {
  313. if string(server.ID) == peerName {
  314. raftServerFound = true
  315. }
  316. }
  317. if !raftServerFound {
  318. glog.V(0).Infof("adding new raft server: %s", peerName)
  319. ms.Topo.HashicorpRaft.AddVoter(
  320. hashicorpRaft.ServerID(peerName),
  321. hashicorpRaft.ServerAddress(peerAddress.ToGrpcAddress()), 0, 0)
  322. }
  323. } else {
  324. pb.WithMasterClient(false, peerAddress, ms.grpcDialOption, true, func(client master_pb.SeaweedClient) error {
  325. ctx, cancel := context.WithTimeout(context.TODO(), 15*time.Second)
  326. defer cancel()
  327. if _, err := client.Ping(ctx, &master_pb.PingRequest{Target: string(peerAddress), TargetType: cluster.MasterType}); err != nil {
  328. glog.V(0).Infof("master %s didn't respond to pings. remove raft server", peerName)
  329. if err := ms.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  330. _, err := client.RaftRemoveServer(context.Background(), &master_pb.RaftRemoveServerRequest{
  331. Id: peerName,
  332. Force: false,
  333. })
  334. return err
  335. }); err != nil {
  336. glog.Warningf("failed removing old raft server: %v", err)
  337. return err
  338. }
  339. } else {
  340. glog.V(0).Infof("master %s successfully responded to ping", peerName)
  341. }
  342. return nil
  343. })
  344. }
  345. }
  346. func (ms *MasterServer) Shutdown() {
  347. if ms.Topo == nil || ms.Topo.HashicorpRaft == nil {
  348. return
  349. }
  350. if ms.Topo.HashicorpRaft.State() == hashicorpRaft.Leader {
  351. ms.Topo.HashicorpRaft.LeadershipTransfer()
  352. }
  353. ms.Topo.HashicorpRaft.Shutdown()
  354. }
  355. func (ms *MasterServer) Reload() {
  356. glog.V(0).Infoln("Reload master server...")
  357. util.LoadConfiguration("security", false)
  358. v := util.GetViper()
  359. ms.guard.UpdateWhiteList(append(ms.option.WhiteList,
  360. util.StringSplit(v.GetString("guard.white_list"), ",")...),
  361. )
  362. }