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.

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