master_server.go 8.5 KB

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