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.

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