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.

300 lines
9.1 KiB

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