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.

153 lines
5.3 KiB

6 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. httpReadOnly bool,
  45. ) *MasterServer {
  46. v := viper.GetViper()
  47. signingKey := v.GetString("jwt.signing.key")
  48. var preallocateSize int64
  49. if preallocate {
  50. preallocateSize = int64(volumeSizeLimitMB) * (1 << 20)
  51. }
  52. ms := &MasterServer{
  53. port: port,
  54. volumeSizeLimitMB: volumeSizeLimitMB,
  55. preallocate: preallocateSize,
  56. pulseSeconds: pulseSeconds,
  57. defaultReplicaPlacement: defaultReplicaPlacement,
  58. garbageThreshold: garbageThreshold,
  59. clientChans: make(map[string]chan *master_pb.VolumeLocation),
  60. grpcDialOpiton: security.LoadClientTLS(v.Sub("grpc"), "master"),
  61. }
  62. ms.bounedLeaderChan = make(chan int, 16)
  63. seq := sequence.NewMemorySequencer()
  64. ms.Topo = topology.NewTopology("topo", seq, uint64(volumeSizeLimitMB)*1024*1024, pulseSeconds)
  65. ms.vg = topology.NewDefaultVolumeGrowth()
  66. glog.V(0).Infoln("Volume Size Limit is", volumeSizeLimitMB, "MB")
  67. ms.guard = security.NewGuard(whiteList, signingKey)
  68. handleStaticResources2(r)
  69. r.HandleFunc("/", ms.uiStatusHandler)
  70. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  71. if (!httpReadOnly) {
  72. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  73. r.HandleFunc("/dir/lookup", ms.proxyToLeader(ms.guard.WhiteList(ms.dirLookupHandler)))
  74. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  75. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  76. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  77. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  78. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  79. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  80. }
  81. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  82. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  83. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  84. r.HandleFunc("/{fileId}", ms.proxyToLeader(ms.redirectHandler))
  85. ms.Topo.StartRefreshWritableVolumes(ms.grpcDialOpiton, garbageThreshold, ms.preallocate)
  86. return ms
  87. }
  88. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  89. ms.Topo.RaftServer = raftServer.raftServer
  90. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  91. glog.V(0).Infof("event: %+v", e)
  92. if ms.Topo.RaftServer.Leader() != "" {
  93. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  94. }
  95. })
  96. ms.Topo.RaftServer.AddEventListener(raft.StateChangeEventType, func(e raft.Event) {
  97. glog.V(0).Infof("state change: %+v", e)
  98. })
  99. if ms.Topo.IsLeader() {
  100. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", "I am the leader!")
  101. } else {
  102. if ms.Topo.RaftServer.Leader() != "" {
  103. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "is the leader.")
  104. }
  105. }
  106. }
  107. func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  108. return func(w http.ResponseWriter, r *http.Request) {
  109. if ms.Topo.IsLeader() {
  110. f(w, r)
  111. } else if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  112. ms.bounedLeaderChan <- 1
  113. defer func() { <-ms.bounedLeaderChan }()
  114. targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
  115. if err != nil {
  116. writeJsonError(w, r, http.StatusInternalServerError,
  117. fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
  118. return
  119. }
  120. glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
  121. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  122. director := proxy.Director
  123. proxy.Director = func(req *http.Request) {
  124. actualHost, err := security.GetActualRemoteHost(req)
  125. if err == nil {
  126. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  127. }
  128. director(req)
  129. }
  130. proxy.Transport = util.Transport
  131. proxy.ServeHTTP(w, r)
  132. } else {
  133. //drop it to the floor
  134. //writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
  135. }
  136. }
  137. }