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.

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