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.

367 lines
12 KiB

7 years ago
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
9 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/stats"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/chrislusf/seaweedfs/weed/cluster"
  15. "github.com/chrislusf/seaweedfs/weed/pb"
  16. "github.com/chrislusf/raft"
  17. "github.com/gorilla/mux"
  18. hashicorpRaft "github.com/hashicorp/raft"
  19. "google.golang.org/grpc"
  20. "github.com/chrislusf/seaweedfs/weed/glog"
  21. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  22. "github.com/chrislusf/seaweedfs/weed/security"
  23. "github.com/chrislusf/seaweedfs/weed/sequence"
  24. "github.com/chrislusf/seaweedfs/weed/shell"
  25. "github.com/chrislusf/seaweedfs/weed/topology"
  26. "github.com/chrislusf/seaweedfs/weed/util"
  27. "github.com/chrislusf/seaweedfs/weed/wdclient"
  28. )
  29. const (
  30. SequencerType = "master.sequencer.type"
  31. SequencerSnowflakeId = "master.sequencer.sequencer_snowflake_id"
  32. RaftServerRemovalTime = 72 * time.Hour
  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. vgCh chan *topology.VolumeGrowRequest
  56. boundedLeaderChan chan int
  57. onPeerUpdatDoneCn chan string
  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", 7)
  77. v.SetDefault("master.volume_growth.copy_2", 6)
  78. v.SetDefault("master.volume_growth.copy_3", 3)
  79. v.SetDefault("master.volume_growth.copy_other", 1)
  80. v.SetDefault("master.volume_growth.threshold", 0.9)
  81. var preallocateSize int64
  82. if option.VolumePreallocate {
  83. preallocateSize = int64(option.VolumeSizeLimitMB) * (1 << 20)
  84. }
  85. grpcDialOption := security.LoadClientTLS(v, "grpc.master")
  86. ms := &MasterServer{
  87. option: option,
  88. preallocateSize: preallocateSize,
  89. vgCh: make(chan *topology.VolumeGrowRequest, 1<<6),
  90. clientChans: make(map[string]chan *master_pb.KeepConnectedResponse),
  91. grpcDialOption: grpcDialOption,
  92. MasterClient: wdclient.NewMasterClient(grpcDialOption, cluster.MasterType, option.Master, "", peers),
  93. adminLocks: NewAdminLocks(),
  94. Cluster: cluster.NewCluster(),
  95. }
  96. ms.boundedLeaderChan = make(chan int, 16)
  97. ms.onPeerUpdatDoneCn = make(chan string)
  98. ms.MasterClient.OnPeerUpdate = ms.OnPeerUpdate
  99. seq := ms.createSequencer(option)
  100. if nil == seq {
  101. glog.Fatalf("create sequencer failed.")
  102. }
  103. ms.Topo = topology.NewTopology("topo", seq, uint64(ms.option.VolumeSizeLimitMB)*1024*1024, 5, replicationAsMin)
  104. ms.vg = topology.NewDefaultVolumeGrowth()
  105. glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
  106. ms.guard = security.NewGuard(ms.option.WhiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
  107. handleStaticResources2(r)
  108. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  109. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  110. if !ms.option.DisableHttp {
  111. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  112. r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
  113. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  114. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  115. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  116. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  117. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  118. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  119. /*
  120. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  121. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  122. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  123. */
  124. r.HandleFunc("/{fileId}", ms.redirectHandler)
  125. }
  126. ms.Topo.StartRefreshWritableVolumes(
  127. ms.grpcDialOption,
  128. ms.option.GarbageThreshold,
  129. v.GetFloat64("master.volume_growth.threshold"),
  130. ms.preallocateSize,
  131. )
  132. ms.ProcessGrowRequest()
  133. if !option.IsFollower {
  134. ms.startAdminScripts()
  135. }
  136. return ms
  137. }
  138. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  139. var raftServerName string
  140. if raftServer.raftServer != nil {
  141. ms.Topo.RaftServer = raftServer.raftServer
  142. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  143. glog.V(0).Infof("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  144. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", e.Value())).Inc()
  145. if ms.Topo.RaftServer.Leader() != "" {
  146. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  147. }
  148. })
  149. raftServerName = ms.Topo.RaftServer.Name()
  150. } else if raftServer.RaftHashicorp != nil {
  151. ms.Topo.HashicorpRaft = raftServer.RaftHashicorp
  152. leaderCh := raftServer.RaftHashicorp.LeaderCh()
  153. prevLeader := ms.Topo.HashicorpRaft.Leader()
  154. go func() {
  155. for {
  156. select {
  157. case isLeader := <-leaderCh:
  158. leader := ms.Topo.HashicorpRaft.Leader()
  159. glog.V(0).Infof("is leader %+v change event: %+v => %+v", isLeader, prevLeader, leader)
  160. stats.MasterLeaderChangeCounter.WithLabelValues(fmt.Sprintf("%+v", leader)).Inc()
  161. prevLeader = leader
  162. }
  163. }
  164. }()
  165. raftServerName = ms.Topo.HashicorpRaft.String()
  166. }
  167. if ms.Topo.IsLeader() {
  168. glog.V(0).Infoln("[", raftServerName, "]", "I am the leader!")
  169. } else {
  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. }
  176. }
  177. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  178. return func(w http.ResponseWriter, r *http.Request) {
  179. if ms.Topo.IsLeader() {
  180. f(w, r)
  181. } else if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  182. ms.boundedLeaderChan <- 1
  183. defer func() { <-ms.boundedLeaderChan }()
  184. targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
  185. if err != nil {
  186. writeJsonError(w, r, http.StatusInternalServerError,
  187. fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
  188. return
  189. }
  190. glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
  191. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  192. director := proxy.Director
  193. proxy.Director = func(req *http.Request) {
  194. actualHost, err := security.GetActualRemoteHost(req)
  195. if err == nil {
  196. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  197. }
  198. director(req)
  199. }
  200. proxy.Transport = util.Transport
  201. proxy.ServeHTTP(w, r)
  202. } else {
  203. // handle requests locally
  204. f(w, r)
  205. }
  206. }
  207. }
  208. func (ms *MasterServer) startAdminScripts() {
  209. v := util.GetViper()
  210. adminScripts := v.GetString("master.maintenance.scripts")
  211. if adminScripts == "" {
  212. return
  213. }
  214. glog.V(0).Infof("adminScripts: %v", adminScripts)
  215. v.SetDefault("master.maintenance.sleep_minutes", 17)
  216. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  217. scriptLines := strings.Split(adminScripts, "\n")
  218. if !strings.Contains(adminScripts, "lock") {
  219. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  220. scriptLines = append(scriptLines, "unlock")
  221. }
  222. masterAddress := string(ms.option.Master)
  223. var shellOptions shell.ShellOptions
  224. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  225. shellOptions.Masters = &masterAddress
  226. shellOptions.Directory = "/"
  227. commandEnv := shell.NewCommandEnv(&shellOptions)
  228. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  229. go commandEnv.MasterClient.KeepConnectedToMaster()
  230. go func() {
  231. commandEnv.MasterClient.WaitUntilConnected()
  232. for {
  233. time.Sleep(time.Duration(sleepMinutes) * time.Minute)
  234. if ms.Topo.IsLeader() {
  235. shellOptions.FilerAddress = ms.GetOneFiler()
  236. if shellOptions.FilerAddress == "" {
  237. continue
  238. }
  239. for _, line := range scriptLines {
  240. for _, c := range strings.Split(line, ";") {
  241. processEachCmd(reg, c, commandEnv)
  242. }
  243. }
  244. }
  245. }
  246. }()
  247. }
  248. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  249. cmds := reg.FindAllString(line, -1)
  250. if len(cmds) == 0 {
  251. return
  252. }
  253. args := make([]string, len(cmds[1:]))
  254. for i := range args {
  255. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  256. }
  257. cmd := strings.ToLower(cmds[0])
  258. for _, c := range shell.Commands {
  259. if c.Name() == cmd {
  260. glog.V(0).Infof("executing: %s %v", cmd, args)
  261. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  262. glog.V(0).Infof("error: %v", err)
  263. }
  264. }
  265. }
  266. }
  267. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  268. var seq sequence.Sequencer
  269. v := util.GetViper()
  270. seqType := strings.ToLower(v.GetString(SequencerType))
  271. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  272. switch strings.ToLower(seqType) {
  273. case "snowflake":
  274. var err error
  275. snowflakeId := v.GetInt(SequencerSnowflakeId)
  276. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  277. if err != nil {
  278. glog.Error(err)
  279. seq = nil
  280. }
  281. default:
  282. seq = sequence.NewMemorySequencer()
  283. }
  284. return seq
  285. }
  286. func (ms *MasterServer) OnPeerUpdate(update *master_pb.ClusterNodeUpdate) {
  287. glog.V(0).Infof("OnPeerUpdate: %+v", update)
  288. if update.NodeType != cluster.MasterType || ms.Topo.HashicorpRaft == nil {
  289. return
  290. }
  291. peerAddress := pb.ServerAddress(update.Address)
  292. if update.IsAdd {
  293. if ms.Topo.HashicorpRaft.State() == hashicorpRaft.Leader {
  294. glog.V(0).Infof("adding new raft server: %s", peerAddress.String())
  295. ms.Topo.HashicorpRaft.AddVoter(
  296. hashicorpRaft.ServerID(peerAddress.String()),
  297. hashicorpRaft.ServerAddress(peerAddress.ToGrpcAddress()), 0, 0)
  298. }
  299. ms.onPeerUpdatDoneCn <- string(peerAddress)
  300. } else if ms.Topo.HashicorpRaft.State() == hashicorpRaft.Leader {
  301. go func(peerName string) {
  302. for {
  303. select {
  304. case peerDone := <-ms.onPeerUpdatDoneCn:
  305. if peerName == peerDone {
  306. return
  307. }
  308. case <-time.After(RaftServerRemovalTime):
  309. glog.V(0).Infof("removing old raft server: %s", peerName)
  310. if _, err := ms.RaftRemoveServer(context.Background(), &master_pb.RaftRemoveServerRequest{
  311. Id: peerName,
  312. }); err != nil {
  313. glog.Warningf("failed removing old raft server: %v", err)
  314. }
  315. return
  316. }
  317. }
  318. }(string(peerAddress))
  319. }
  320. }