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.

277 lines
8.6 KiB

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