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.

410 lines
13 KiB

6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
3 years ago
6 years ago
6 years ago
4 years ago
3 years ago
3 years 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
2 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. )
  29. const (
  30. SequencerType = "master.sequencer.type"
  31. SequencerSnowflakeId = "master.sequencer.sequencer_snowflake_id"
  32. )
  33. type MasterOption struct {
  34. Master pb.ServerAddress
  35. MetaFolder string
  36. VolumeSizeLimitMB uint32
  37. VolumePreallocate bool
  38. // PulseSeconds int
  39. DefaultReplicaPlacement string
  40. GarbageThreshold float64
  41. WhiteList []string
  42. DisableHttp bool
  43. MetricsAddress string
  44. MetricsIntervalSec int
  45. IsFollower bool
  46. }
  47. type MasterServer struct {
  48. master_pb.UnimplementedSeaweedServer
  49. option *MasterOption
  50. guard *security.Guard
  51. preallocateSize int64
  52. Topo *topology.Topology
  53. vg *topology.VolumeGrowth
  54. vgCh chan *topology.VolumeGrowRequest
  55. boundedLeaderChan chan int
  56. // notifying clients
  57. clientChansLock sync.RWMutex
  58. clientChans map[string]chan *master_pb.KeepConnectedResponse
  59. grpcDialOption grpc.DialOption
  60. MasterClient *wdclient.MasterClient
  61. adminLocks *AdminLocks
  62. Cluster *cluster.Cluster
  63. }
  64. func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.ServerAddress) *MasterServer {
  65. v := util.GetViper()
  66. signingKey := v.GetString("jwt.signing.key")
  67. v.SetDefault("jwt.signing.expires_after_seconds", 10)
  68. expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
  69. readSigningKey := v.GetString("jwt.signing.read.key")
  70. v.SetDefault("jwt.signing.read.expires_after_seconds", 60)
  71. readExpiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
  72. v.SetDefault("master.replication.treat_replication_as_minimums", false)
  73. replicationAsMin := v.GetBool("master.replication.treat_replication_as_minimums")
  74. v.SetDefault("master.volume_growth.copy_1", 7)
  75. v.SetDefault("master.volume_growth.copy_2", 6)
  76. v.SetDefault("master.volume_growth.copy_3", 3)
  77. v.SetDefault("master.volume_growth.copy_other", 1)
  78. v.SetDefault("master.volume_growth.threshold", 0.9)
  79. var preallocateSize int64
  80. if option.VolumePreallocate {
  81. preallocateSize = int64(option.VolumeSizeLimitMB) * (1 << 20)
  82. }
  83. grpcDialOption := security.LoadClientTLS(v, "grpc.master")
  84. ms := &MasterServer{
  85. option: option,
  86. preallocateSize: preallocateSize,
  87. vgCh: make(chan *topology.VolumeGrowRequest, 1<<6),
  88. clientChans: make(map[string]chan *master_pb.KeepConnectedResponse),
  89. grpcDialOption: grpcDialOption,
  90. MasterClient: wdclient.NewMasterClient(grpcDialOption, "", cluster.MasterType, option.Master, "", "", peers),
  91. adminLocks: NewAdminLocks(),
  92. Cluster: cluster.NewCluster(),
  93. }
  94. ms.boundedLeaderChan = make(chan int, 16)
  95. ms.MasterClient.SetOnPeerUpdateFn(ms.OnPeerUpdate)
  96. seq := ms.createSequencer(option)
  97. if nil == seq {
  98. glog.Fatalf("create sequencer failed.")
  99. }
  100. ms.Topo = topology.NewTopology("topo", seq, uint64(ms.option.VolumeSizeLimitMB)*1024*1024, 5, replicationAsMin)
  101. ms.vg = topology.NewDefaultVolumeGrowth()
  102. glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
  103. ms.guard = security.NewGuard(ms.option.WhiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
  104. handleStaticResources2(r)
  105. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  106. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  107. if !ms.option.DisableHttp {
  108. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  109. r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
  110. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  111. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  112. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  113. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  114. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  115. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  116. /*
  117. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  118. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  119. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  120. */
  121. r.HandleFunc("/{fileId}", ms.redirectHandler)
  122. }
  123. ms.Topo.StartRefreshWritableVolumes(
  124. ms.grpcDialOption,
  125. ms.option.GarbageThreshold,
  126. v.GetFloat64("master.volume_growth.threshold"),
  127. ms.preallocateSize,
  128. )
  129. ms.ProcessGrowRequest()
  130. if !option.IsFollower {
  131. ms.startAdminScripts()
  132. }
  133. return ms
  134. }
  135. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  136. var raftServerName string
  137. ms.Topo.RaftServerAccessLock.Lock()
  138. if raftServer.raftServer != nil {
  139. ms.Topo.RaftServer = raftServer.raftServer
  140. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  141. glog.V(0).Infof("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  142. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", e.Value())).Inc()
  143. if ms.Topo.RaftServer.Leader() != "" {
  144. glog.V(0).Infof("[%s] %s becomes leader.", ms.Topo.RaftServer.Name(), ms.Topo.RaftServer.Leader())
  145. }
  146. })
  147. raftServerName = fmt.Sprintf("[%s]", ms.Topo.RaftServer.Name())
  148. } else if raftServer.RaftHashicorp != nil {
  149. ms.Topo.HashicorpRaft = raftServer.RaftHashicorp
  150. leaderCh := raftServer.RaftHashicorp.LeaderCh()
  151. prevLeader, _ := ms.Topo.HashicorpRaft.LeaderWithID()
  152. raftServerName = ms.Topo.HashicorpRaft.String()
  153. go func() {
  154. for {
  155. select {
  156. case isLeader := <-leaderCh:
  157. ms.Topo.RaftServerAccessLock.RLock()
  158. leader, _ := ms.Topo.HashicorpRaft.LeaderWithID()
  159. ms.Topo.RaftServerAccessLock.RUnlock()
  160. glog.V(0).Infof("is leader %+v change event: %+v => %+v", isLeader, prevLeader, leader)
  161. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", leader)).Inc()
  162. prevLeader = leader
  163. }
  164. }
  165. }()
  166. }
  167. ms.Topo.RaftServerAccessLock.Unlock()
  168. if ms.Topo.IsLeader() {
  169. glog.V(0).Infof("%s I am the leader!", raftServerName)
  170. } else {
  171. var raftServerLeader string
  172. ms.Topo.RaftServerAccessLock.RLock()
  173. if ms.Topo.RaftServer != nil {
  174. raftServerLeader = ms.Topo.RaftServer.Leader()
  175. } else if ms.Topo.HashicorpRaft != nil {
  176. raftServerName = ms.Topo.HashicorpRaft.String()
  177. raftServerLeaderAddr, _ := ms.Topo.HashicorpRaft.LeaderWithID()
  178. raftServerLeader = string(raftServerLeaderAddr)
  179. }
  180. ms.Topo.RaftServerAccessLock.RUnlock()
  181. glog.V(0).Infof("%s %s - is the leader.", raftServerName, raftServerLeader)
  182. }
  183. }
  184. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  185. return func(w http.ResponseWriter, r *http.Request) {
  186. if ms.Topo.IsLeader() {
  187. f(w, r)
  188. return
  189. }
  190. // get the current raft leader
  191. leaderAddr, _ := ms.Topo.MaybeLeader()
  192. raftServerLeader := string(leaderAddr)
  193. if raftServerLeader == "" {
  194. f(w, r)
  195. return
  196. }
  197. ms.boundedLeaderChan <- 1
  198. defer func() { <-ms.boundedLeaderChan }()
  199. targetUrl, err := url.Parse("http://" + raftServerLeader)
  200. if err != nil {
  201. writeJsonError(w, r, http.StatusInternalServerError,
  202. fmt.Errorf("Leader URL http://%s Parse Error: %v", raftServerLeader, err))
  203. return
  204. }
  205. // proxy to leader
  206. glog.V(4).Infoln("proxying to leader", raftServerLeader)
  207. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  208. director := proxy.Director
  209. proxy.Director = func(req *http.Request) {
  210. actualHost, err := security.GetActualRemoteHost(req)
  211. if err == nil {
  212. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  213. }
  214. director(req)
  215. }
  216. proxy.Transport = util.Transport
  217. proxy.ServeHTTP(w, r)
  218. }
  219. }
  220. func (ms *MasterServer) startAdminScripts() {
  221. v := util.GetViper()
  222. adminScripts := v.GetString("master.maintenance.scripts")
  223. if adminScripts == "" {
  224. return
  225. }
  226. glog.V(0).Infof("adminScripts: %v", adminScripts)
  227. v.SetDefault("master.maintenance.sleep_minutes", 17)
  228. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  229. scriptLines := strings.Split(adminScripts, "\n")
  230. if !strings.Contains(adminScripts, "lock") {
  231. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  232. scriptLines = append(scriptLines, "unlock")
  233. }
  234. masterAddress := string(ms.option.Master)
  235. var shellOptions shell.ShellOptions
  236. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  237. shellOptions.Masters = &masterAddress
  238. shellOptions.Directory = "/"
  239. emptyFilerGroup := ""
  240. shellOptions.FilerGroup = &emptyFilerGroup
  241. commandEnv := shell.NewCommandEnv(&shellOptions)
  242. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  243. go commandEnv.MasterClient.KeepConnectedToMaster()
  244. go func() {
  245. for {
  246. time.Sleep(time.Duration(sleepMinutes) * time.Minute)
  247. if ms.Topo.IsLeader() && ms.MasterClient.GetMaster() != "" {
  248. shellOptions.FilerAddress = ms.GetOneFiler(cluster.FilerGroupName(*shellOptions.FilerGroup))
  249. if shellOptions.FilerAddress == "" {
  250. continue
  251. }
  252. for _, line := range scriptLines {
  253. for _, c := range strings.Split(line, ";") {
  254. processEachCmd(reg, c, commandEnv)
  255. }
  256. }
  257. }
  258. }
  259. }()
  260. }
  261. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  262. cmds := reg.FindAllString(line, -1)
  263. if len(cmds) == 0 {
  264. return
  265. }
  266. args := make([]string, len(cmds[1:]))
  267. for i := range args {
  268. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  269. }
  270. cmd := strings.ToLower(cmds[0])
  271. for _, c := range shell.Commands {
  272. if c.Name() == cmd {
  273. glog.V(0).Infof("executing: %s %v", cmd, args)
  274. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  275. glog.V(0).Infof("error: %v", err)
  276. }
  277. }
  278. }
  279. }
  280. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  281. var seq sequence.Sequencer
  282. v := util.GetViper()
  283. seqType := strings.ToLower(v.GetString(SequencerType))
  284. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  285. switch strings.ToLower(seqType) {
  286. case "snowflake":
  287. var err error
  288. snowflakeId := v.GetInt(SequencerSnowflakeId)
  289. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  290. if err != nil {
  291. glog.Error(err)
  292. seq = nil
  293. }
  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. }