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.

150 lines
5.3 KiB

7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "fmt"
  4. "google.golang.org/grpc"
  5. "net/http"
  6. "net/http/httputil"
  7. "net/url"
  8. "sync"
  9. "github.com/chrislusf/raft"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  12. "github.com/chrislusf/seaweedfs/weed/security"
  13. "github.com/chrislusf/seaweedfs/weed/sequence"
  14. "github.com/chrislusf/seaweedfs/weed/topology"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. "github.com/gorilla/mux"
  17. "github.com/spf13/viper"
  18. )
  19. type MasterServer struct {
  20. port int
  21. metaFolder string
  22. volumeSizeLimitMB uint
  23. preallocate int64
  24. pulseSeconds int
  25. defaultReplicaPlacement string
  26. garbageThreshold float64
  27. guard *security.Guard
  28. Topo *topology.Topology
  29. vg *topology.VolumeGrowth
  30. vgLock sync.Mutex
  31. bounedLeaderChan chan int
  32. // notifying clients
  33. clientChansLock sync.RWMutex
  34. clientChans map[string]chan *master_pb.VolumeLocation
  35. grpcDialOpiton grpc.DialOption
  36. }
  37. func NewMasterServer(r *mux.Router, port int, metaFolder string,
  38. volumeSizeLimitMB uint,
  39. preallocate bool,
  40. pulseSeconds int,
  41. defaultReplicaPlacement string,
  42. garbageThreshold float64,
  43. whiteList []string,
  44. ) *MasterServer {
  45. v := viper.GetViper()
  46. signingKey := v.GetString("jwt.signing.key")
  47. var preallocateSize int64
  48. if preallocate {
  49. preallocateSize = int64(volumeSizeLimitMB) * (1 << 20)
  50. }
  51. ms := &MasterServer{
  52. port: port,
  53. volumeSizeLimitMB: volumeSizeLimitMB,
  54. preallocate: preallocateSize,
  55. pulseSeconds: pulseSeconds,
  56. defaultReplicaPlacement: defaultReplicaPlacement,
  57. garbageThreshold: garbageThreshold,
  58. clientChans: make(map[string]chan *master_pb.VolumeLocation),
  59. grpcDialOpiton: security.LoadClientTLS(v.Sub("grpc"), "master"),
  60. }
  61. ms.bounedLeaderChan = make(chan int, 16)
  62. seq := sequence.NewMemorySequencer()
  63. ms.Topo = topology.NewTopology("topo", seq, uint64(volumeSizeLimitMB)*1024*1024, pulseSeconds)
  64. ms.vg = topology.NewDefaultVolumeGrowth()
  65. glog.V(0).Infoln("Volume Size Limit is", volumeSizeLimitMB, "MB")
  66. ms.guard = security.NewGuard(whiteList, signingKey)
  67. handleStaticResources2(r)
  68. r.HandleFunc("/", ms.uiStatusHandler)
  69. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  70. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  71. r.HandleFunc("/dir/lookup", ms.proxyToLeader(ms.guard.WhiteList(ms.dirLookupHandler)))
  72. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  73. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  74. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  75. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  76. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  77. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  78. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  79. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  80. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  81. r.HandleFunc("/{fileId}", ms.proxyToLeader(ms.redirectHandler))
  82. ms.Topo.StartRefreshWritableVolumes(ms.grpcDialOpiton, garbageThreshold, ms.preallocate)
  83. return ms
  84. }
  85. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  86. ms.Topo.RaftServer = raftServer.raftServer
  87. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  88. glog.V(0).Infof("event: %+v", e)
  89. if ms.Topo.RaftServer.Leader() != "" {
  90. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  91. }
  92. })
  93. ms.Topo.RaftServer.AddEventListener(raft.StateChangeEventType, func(e raft.Event) {
  94. glog.V(0).Infof("state change: %+v", e)
  95. })
  96. if ms.Topo.IsLeader() {
  97. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", "I am the leader!")
  98. } else {
  99. if ms.Topo.RaftServer.Leader() != "" {
  100. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "is the leader.")
  101. }
  102. }
  103. }
  104. func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  105. return func(w http.ResponseWriter, r *http.Request) {
  106. if ms.Topo.IsLeader() {
  107. f(w, r)
  108. } else if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  109. ms.bounedLeaderChan <- 1
  110. defer func() { <-ms.bounedLeaderChan }()
  111. targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
  112. if err != nil {
  113. writeJsonError(w, r, http.StatusInternalServerError,
  114. fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
  115. return
  116. }
  117. glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
  118. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  119. director := proxy.Director
  120. proxy.Director = func(req *http.Request) {
  121. actualHost, err := security.GetActualRemoteHost(req)
  122. if err == nil {
  123. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  124. }
  125. director(req)
  126. }
  127. proxy.Transport = util.Transport
  128. proxy.ServeHTTP(w, r)
  129. } else {
  130. //drop it to the floor
  131. //writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
  132. }
  133. }
  134. }