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.

311 lines
9.5 KiB

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
6 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
4 years ago
3 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httputil"
  6. "net/url"
  7. "os"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/chrislusf/raft"
  13. "github.com/gorilla/mux"
  14. "google.golang.org/grpc"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  17. "github.com/chrislusf/seaweedfs/weed/security"
  18. "github.com/chrislusf/seaweedfs/weed/sequence"
  19. "github.com/chrislusf/seaweedfs/weed/shell"
  20. "github.com/chrislusf/seaweedfs/weed/topology"
  21. "github.com/chrislusf/seaweedfs/weed/util"
  22. "github.com/chrislusf/seaweedfs/weed/wdclient"
  23. )
  24. const (
  25. SequencerType = "master.sequencer.type"
  26. SequencerEtcdUrls = "master.sequencer.sequencer_etcd_urls"
  27. SequencerSnowflakeId = "master.sequencer.sequencer_snowflake_id"
  28. )
  29. type MasterOption struct {
  30. Host string
  31. Port int
  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 []string) *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.Host, 0, "", 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 := fmt.Sprintf("%s:%d", ms.option.Host, ms.option.Port)
  193. var shellOptions shell.ShellOptions
  194. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  195. shellOptions.Masters = &masterAddress
  196. shellOptions.FilerHost, shellOptions.FilerPort, err = util.ParseHostPort(filerHostPort)
  197. shellOptions.FilerAddress = filerHostPort
  198. shellOptions.Directory = "/"
  199. if err != nil {
  200. glog.V(0).Infof("failed to parse master.filer.default = %s : %v\n", filerHostPort, err)
  201. return
  202. }
  203. commandEnv := shell.NewCommandEnv(shellOptions)
  204. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  205. go commandEnv.MasterClient.KeepConnectedToMaster()
  206. go func() {
  207. commandEnv.MasterClient.WaitUntilConnected()
  208. c := time.Tick(time.Duration(sleepMinutes) * time.Minute)
  209. for range c {
  210. if ms.Topo.IsLeader() {
  211. for _, line := range scriptLines {
  212. for _, c := range strings.Split(line, ";") {
  213. processEachCmd(reg, c, commandEnv)
  214. }
  215. }
  216. }
  217. }
  218. }()
  219. }
  220. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  221. cmds := reg.FindAllString(line, -1)
  222. if len(cmds) == 0 {
  223. return
  224. }
  225. args := make([]string, len(cmds[1:]))
  226. for i := range args {
  227. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  228. }
  229. cmd := strings.ToLower(cmds[0])
  230. for _, c := range shell.Commands {
  231. if c.Name() == cmd {
  232. glog.V(0).Infof("executing: %s %v", cmd, args)
  233. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  234. glog.V(0).Infof("error: %v", err)
  235. }
  236. }
  237. }
  238. }
  239. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  240. var seq sequence.Sequencer
  241. v := util.GetViper()
  242. seqType := strings.ToLower(v.GetString(SequencerType))
  243. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  244. switch strings.ToLower(seqType) {
  245. case "etcd":
  246. var err error
  247. urls := v.GetString(SequencerEtcdUrls)
  248. glog.V(0).Infof("[%s] : [%s]", SequencerEtcdUrls, urls)
  249. seq, err = sequence.NewEtcdSequencer(urls, option.MetaFolder)
  250. if err != nil {
  251. glog.Error(err)
  252. seq = nil
  253. }
  254. case "snowflake":
  255. var err error
  256. snowflakeId := v.GetInt(SequencerSnowflakeId)
  257. seq, err = sequence.NewSnowflakeSequencer(fmt.Sprintf("%s:%d", option.Host, option.Port), snowflakeId)
  258. if err != nil {
  259. glog.Error(err)
  260. seq = nil
  261. }
  262. default:
  263. seq = sequence.NewMemorySequencer()
  264. }
  265. return seq
  266. }