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.

270 lines
8.5 KiB

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