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.

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