master_server.go 9.2 KB

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