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.

304 lines
9.3 KiB

3 years ago
7 years ago
3 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
3 years ago
6 years ago
6 years ago
4 years ago
3 years ago
3 years ago
6 years ago
6 years ago
6 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/cluster"
  5. "github.com/chrislusf/seaweedfs/weed/pb"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/chrislusf/raft"
  15. "github.com/gorilla/mux"
  16. "google.golang.org/grpc"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  19. "github.com/chrislusf/seaweedfs/weed/security"
  20. "github.com/chrislusf/seaweedfs/weed/sequence"
  21. "github.com/chrislusf/seaweedfs/weed/shell"
  22. "github.com/chrislusf/seaweedfs/weed/topology"
  23. "github.com/chrislusf/seaweedfs/weed/util"
  24. "github.com/chrislusf/seaweedfs/weed/wdclient"
  25. )
  26. const (
  27. SequencerType = "master.sequencer.type"
  28. SequencerSnowflakeId = "master.sequencer.sequencer_snowflake_id"
  29. )
  30. type MasterOption struct {
  31. Master pb.ServerAddress
  32. MetaFolder string
  33. VolumeSizeLimitMB uint32
  34. VolumePreallocate bool
  35. // PulseSeconds int
  36. DefaultReplicaPlacement string
  37. GarbageThreshold float64
  38. WhiteList []string
  39. DisableHttp bool
  40. MetricsAddress string
  41. MetricsIntervalSec int
  42. IsFollower bool
  43. }
  44. type MasterServer struct {
  45. option *MasterOption
  46. guard *security.Guard
  47. preallocateSize int64
  48. Topo *topology.Topology
  49. vg *topology.VolumeGrowth
  50. vgCh chan *topology.VolumeGrowRequest
  51. boundedLeaderChan chan int
  52. // notifying clients
  53. clientChansLock sync.RWMutex
  54. clientChans map[string]chan *master_pb.KeepConnectedResponse
  55. grpcDialOption grpc.DialOption
  56. MasterClient *wdclient.MasterClient
  57. adminLocks *AdminLocks
  58. Cluster *cluster.Cluster
  59. }
  60. func NewMasterServer(r *mux.Router, option *MasterOption, peers []pb.ServerAddress) *MasterServer {
  61. v := util.GetViper()
  62. signingKey := v.GetString("jwt.signing.key")
  63. v.SetDefault("jwt.signing.expires_after_seconds", 10)
  64. expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
  65. readSigningKey := v.GetString("jwt.signing.read.key")
  66. v.SetDefault("jwt.signing.read.expires_after_seconds", 60)
  67. readExpiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
  68. v.SetDefault("master.replication.treat_replication_as_minimums", false)
  69. replicationAsMin := v.GetBool("master.replication.treat_replication_as_minimums")
  70. v.SetDefault("master.volume_growth.copy_1", 7)
  71. v.SetDefault("master.volume_growth.copy_2", 6)
  72. v.SetDefault("master.volume_growth.copy_3", 3)
  73. v.SetDefault("master.volume_growth.copy_other", 1)
  74. v.SetDefault("master.volume_growth.threshold", 0.9)
  75. var preallocateSize int64
  76. if option.VolumePreallocate {
  77. preallocateSize = int64(option.VolumeSizeLimitMB) * (1 << 20)
  78. }
  79. grpcDialOption := security.LoadClientTLS(v, "grpc.master")
  80. ms := &MasterServer{
  81. option: option,
  82. preallocateSize: preallocateSize,
  83. vgCh: make(chan *topology.VolumeGrowRequest, 1<<6),
  84. clientChans: make(map[string]chan *master_pb.KeepConnectedResponse),
  85. grpcDialOption: grpcDialOption,
  86. MasterClient: wdclient.NewMasterClient(grpcDialOption, cluster.MasterType, option.Master, "", peers),
  87. adminLocks: NewAdminLocks(),
  88. Cluster: cluster.NewCluster(),
  89. }
  90. ms.boundedLeaderChan = make(chan int, 16)
  91. seq := ms.createSequencer(option)
  92. if nil == seq {
  93. glog.Fatalf("create sequencer failed.")
  94. }
  95. ms.Topo = topology.NewTopology("topo", seq, uint64(ms.option.VolumeSizeLimitMB)*1024*1024, 5, replicationAsMin)
  96. ms.vg = topology.NewDefaultVolumeGrowth()
  97. glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
  98. ms.guard = security.NewGuard(ms.option.WhiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
  99. handleStaticResources2(r)
  100. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  101. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  102. if !ms.option.DisableHttp {
  103. r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
  104. r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
  105. r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
  106. r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
  107. r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
  108. r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
  109. r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
  110. r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
  111. /*
  112. r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
  113. r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
  114. r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
  115. */
  116. r.HandleFunc("/{fileId}", ms.redirectHandler)
  117. }
  118. ms.Topo.StartRefreshWritableVolumes(
  119. ms.grpcDialOption,
  120. ms.option.GarbageThreshold,
  121. v.GetFloat64("master.volume_growth.threshold"),
  122. ms.preallocateSize,
  123. )
  124. ms.ProcessGrowRequest()
  125. if !option.IsFollower {
  126. ms.startAdminScripts()
  127. }
  128. return ms
  129. }
  130. func (ms *MasterServer) SetRaftServer(raftServer *RaftServer) {
  131. ms.Topo.RaftServer = raftServer.raftServer
  132. ms.Topo.RaftServer.AddEventListener(raft.LeaderChangeEventType, func(e raft.Event) {
  133. glog.V(0).Infof("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  134. if ms.Topo.RaftServer.Leader() != "" {
  135. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  136. }
  137. })
  138. if ms.Topo.IsLeader() {
  139. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", "I am the leader!")
  140. } else {
  141. if ms.Topo.RaftServer.Leader() != "" {
  142. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "is the leader.")
  143. }
  144. }
  145. }
  146. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  147. return func(w http.ResponseWriter, r *http.Request) {
  148. if ms.Topo.IsLeader() {
  149. f(w, r)
  150. } else if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  151. ms.boundedLeaderChan <- 1
  152. defer func() { <-ms.boundedLeaderChan }()
  153. targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
  154. if err != nil {
  155. writeJsonError(w, r, http.StatusInternalServerError,
  156. fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
  157. return
  158. }
  159. glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
  160. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  161. director := proxy.Director
  162. proxy.Director = func(req *http.Request) {
  163. actualHost, err := security.GetActualRemoteHost(req)
  164. if err == nil {
  165. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  166. }
  167. director(req)
  168. }
  169. proxy.Transport = util.Transport
  170. proxy.ServeHTTP(w, r)
  171. } else {
  172. // handle requests locally
  173. f(w, r)
  174. }
  175. }
  176. }
  177. func (ms *MasterServer) startAdminScripts() {
  178. var err error
  179. v := util.GetViper()
  180. adminScripts := v.GetString("master.maintenance.scripts")
  181. glog.V(0).Infof("adminScripts:\n%v", adminScripts)
  182. if adminScripts == "" {
  183. return
  184. }
  185. v.SetDefault("master.maintenance.sleep_minutes", 17)
  186. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  187. v.SetDefault("master.filer.default", "localhost:8888")
  188. filerHostPort := v.GetString("master.filer.default")
  189. scriptLines := strings.Split(adminScripts, "\n")
  190. if !strings.Contains(adminScripts, "lock") {
  191. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  192. scriptLines = append(scriptLines, "unlock")
  193. }
  194. masterAddress := string(ms.option.Master)
  195. var shellOptions shell.ShellOptions
  196. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  197. shellOptions.Masters = &masterAddress
  198. shellOptions.FilerAddress = pb.ServerAddress(filerHostPort)
  199. shellOptions.Directory = "/"
  200. if err != nil {
  201. glog.V(0).Infof("failed to parse master.filer.default = %s : %v\n", filerHostPort, err)
  202. return
  203. }
  204. commandEnv := shell.NewCommandEnv(shellOptions)
  205. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  206. go commandEnv.MasterClient.KeepConnectedToMaster()
  207. go func() {
  208. commandEnv.MasterClient.WaitUntilConnected()
  209. c := time.Tick(time.Duration(sleepMinutes) * time.Minute)
  210. for range c {
  211. if ms.Topo.IsLeader() {
  212. for _, line := range scriptLines {
  213. for _, c := range strings.Split(line, ";") {
  214. processEachCmd(reg, c, commandEnv)
  215. }
  216. }
  217. }
  218. }
  219. }()
  220. }
  221. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  222. cmds := reg.FindAllString(line, -1)
  223. if len(cmds) == 0 {
  224. return
  225. }
  226. args := make([]string, len(cmds[1:]))
  227. for i := range args {
  228. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  229. }
  230. cmd := strings.ToLower(cmds[0])
  231. for _, c := range shell.Commands {
  232. if c.Name() == cmd {
  233. glog.V(0).Infof("executing: %s %v", cmd, args)
  234. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  235. glog.V(0).Infof("error: %v", err)
  236. }
  237. }
  238. }
  239. }
  240. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  241. var seq sequence.Sequencer
  242. v := util.GetViper()
  243. seqType := strings.ToLower(v.GetString(SequencerType))
  244. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  245. switch strings.ToLower(seqType) {
  246. case "snowflake":
  247. var err error
  248. snowflakeId := v.GetInt(SequencerSnowflakeId)
  249. seq, err = sequence.NewSnowflakeSequencer(string(option.Master), snowflakeId)
  250. if err != nil {
  251. glog.Error(err)
  252. seq = nil
  253. }
  254. default:
  255. seq = sequence.NewMemorySequencer()
  256. }
  257. return seq
  258. }