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.

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