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.

288 lines
8.9 KiB

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