master_server.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/chrislusf/raft"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  17. "github.com/chrislusf/seaweedfs/weed/security"
  18. "github.com/chrislusf/seaweedfs/weed/sequence"
  19. "github.com/chrislusf/seaweedfs/weed/shell"
  20. "github.com/chrislusf/seaweedfs/weed/topology"
  21. "github.com/chrislusf/seaweedfs/weed/util"
  22. "github.com/chrislusf/seaweedfs/weed/wdclient"
  23. "github.com/gorilla/mux"
  24. "github.com/spf13/viper"
  25. "google.golang.org/grpc"
  26. )
  27. const (
  28. SequencerType = "master.sequencer.type"
  29. SequencerEtcdUrls = "master.sequencer.sequencer_etcd_urls"
  30. )
  31. type MasterOption struct {
  32. Port int
  33. MetaFolder string
  34. VolumeSizeLimitMB uint
  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. }
  44. type MasterServer struct {
  45. option *MasterOption
  46. guard *security.Guard
  47. preallocateSize int64
  48. Topo *topology.Topology
  49. vg *topology.VolumeGrowth
  50. vgLock sync.Mutex
  51. bounedLeaderChan chan int
  52. // notifying clients
  53. clientChansLock sync.RWMutex
  54. clientChans map[string]chan *master_pb.VolumeLocation
  55. grpcDialOption grpc.DialOption
  56. MasterClient *wdclient.MasterClient
  57. }
  58. func NewMasterServer(r *mux.Router, option *MasterOption, peers []string) *MasterServer {
  59. v := viper.GetViper()
  60. signingKey := v.GetString("jwt.signing.key")
  61. v.SetDefault("jwt.signing.expires_after_seconds", 10)
  62. expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
  63. readSigningKey := v.GetString("jwt.signing.read.key")
  64. v.SetDefault("jwt.signing.read.expires_after_seconds", 60)
  65. readExpiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
  66. var preallocateSize int64
  67. if option.VolumePreallocate {
  68. preallocateSize = int64(option.VolumeSizeLimitMB) * (1 << 20)
  69. }
  70. grpcDialOption := security.LoadClientTLS(v.Sub("grpc"), "master")
  71. ms := &MasterServer{
  72. option: option,
  73. preallocateSize: preallocateSize,
  74. clientChans: make(map[string]chan *master_pb.VolumeLocation),
  75. grpcDialOption: grpcDialOption,
  76. MasterClient: wdclient.NewMasterClient(context.Background(), grpcDialOption, "master", peers),
  77. }
  78. ms.bounedLeaderChan = make(chan int, 16)
  79. seq := ms.createSequencer(option)
  80. if nil == seq {
  81. glog.Fatalf("create sequencer failed.")
  82. }
  83. ms.Topo = topology.NewTopology("topo", seq, uint64(ms.option.VolumeSizeLimitMB)*1024*1024, ms.option.PulseSeconds)
  84. ms.vg = topology.NewDefaultVolumeGrowth()
  85. glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
  86. ms.guard = security.NewGuard(ms.option.WhiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
  87. if !ms.option.DisableHttp {
  88. handleStaticResources2(r)
  89. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  90. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  91. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  92. r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
  93. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  94. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  95. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  96. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  97. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  98. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  99. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  100. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  101. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  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 := viper.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(viper.Sub("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 := viper.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. }