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.

155 lines
5.5 KiB

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