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.

227 lines
7.4 KiB

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