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.

305 lines
9.4 KiB

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