master_server.go 9.1 KB

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