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.

395 lines
12 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).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  145. }
  146. })
  147. raftServerName = 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.Leader()
  152. go func() {
  153. for {
  154. select {
  155. case isLeader := <-leaderCh:
  156. leader := ms.Topo.HashicorpRaft.Leader()
  157. glog.V(0).Infof("is leader %+v change event: %+v => %+v", isLeader, prevLeader, leader)
  158. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", leader)).Inc()
  159. prevLeader = leader
  160. }
  161. }
  162. }()
  163. raftServerName = ms.Topo.HashicorpRaft.String()
  164. }
  165. ms.Topo.RaftServerAccessLock.Unlock()
  166. if ms.Topo.IsLeader() {
  167. glog.V(0).Infoln("[", raftServerName, "]", "I am the leader!")
  168. } else {
  169. ms.Topo.RaftServerAccessLock.RLock()
  170. if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  171. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "is the leader.")
  172. } else if ms.Topo.HashicorpRaft != nil && ms.Topo.HashicorpRaft.Leader() != "" {
  173. glog.V(0).Infoln("[", ms.Topo.HashicorpRaft.String(), "]", ms.Topo.HashicorpRaft.Leader(), "is the leader.")
  174. }
  175. ms.Topo.RaftServerAccessLock.RUnlock()
  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 := string(leaderAddr)
  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.Transport
  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()
  238. go func() {
  239. for {
  240. time.Sleep(time.Duration(sleepMinutes) * time.Minute)
  241. if ms.Topo.IsLeader() && ms.MasterClient.GetMaster() != "" {
  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 := strings.ToLower(cmds[0])
  265. for _, c := range shell.Commands {
  266. if c.Name() == cmd {
  267. glog.V(0).Infof("executing: %s %v", cmd, args)
  268. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  269. glog.V(0).Infof("error: %v", err)
  270. }
  271. }
  272. }
  273. }
  274. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  275. var seq sequence.Sequencer
  276. v := util.GetViper()
  277. seqType := strings.ToLower(v.GetString(SequencerType))
  278. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  279. switch strings.ToLower(seqType) {
  280. case "snowflake":
  281. var err error
  282. snowflakeId := v.GetInt(SequencerSnowflakeId)
  283. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  284. if err != nil {
  285. glog.Error(err)
  286. seq = nil
  287. }
  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. }