master_server.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. vgLock sync.Mutex
  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. 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", option.Host, 0, "", peers),
  78. adminLocks: NewAdminLocks(),
  79. }
  80. ms.boundedLeaderChan = 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, 5, 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. handleStaticResources2(r)
  90. r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
  91. r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
  92. if !ms.option.DisableHttp {
  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("leader change event: %+v => %+v", e.PrevValue(), e.Value())
  116. if ms.Topo.RaftServer.Leader() != "" {
  117. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "becomes leader.")
  118. }
  119. })
  120. if ms.Topo.IsLeader() {
  121. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", "I am the leader!")
  122. } else {
  123. if ms.Topo.RaftServer.Leader() != "" {
  124. glog.V(0).Infoln("[", ms.Topo.RaftServer.Name(), "]", ms.Topo.RaftServer.Leader(), "is the leader.")
  125. }
  126. }
  127. }
  128. func (ms *MasterServer) proxyToLeader(f http.HandlerFunc) http.HandlerFunc {
  129. return func(w http.ResponseWriter, r *http.Request) {
  130. if ms.Topo.IsLeader() {
  131. f(w, r)
  132. } else if ms.Topo.RaftServer != nil && ms.Topo.RaftServer.Leader() != "" {
  133. ms.boundedLeaderChan <- 1
  134. defer func() { <-ms.boundedLeaderChan }()
  135. targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
  136. if err != nil {
  137. writeJsonError(w, r, http.StatusInternalServerError,
  138. fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
  139. return
  140. }
  141. glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
  142. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  143. director := proxy.Director
  144. proxy.Director = func(req *http.Request) {
  145. actualHost, err := security.GetActualRemoteHost(req)
  146. if err == nil {
  147. req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
  148. }
  149. director(req)
  150. }
  151. proxy.Transport = util.Transport
  152. proxy.ServeHTTP(w, r)
  153. } else {
  154. // drop it to the floor
  155. // writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
  156. }
  157. }
  158. }
  159. func (ms *MasterServer) startAdminScripts() {
  160. var err error
  161. v := util.GetViper()
  162. adminScripts := v.GetString("master.maintenance.scripts")
  163. glog.V(0).Infof("adminScripts:\n%v", adminScripts)
  164. if adminScripts == "" {
  165. return
  166. }
  167. v.SetDefault("master.maintenance.sleep_minutes", 17)
  168. sleepMinutes := v.GetInt("master.maintenance.sleep_minutes")
  169. v.SetDefault("master.filer.default", "localhost:8888")
  170. filerHostPort := v.GetString("master.filer.default")
  171. scriptLines := strings.Split(adminScripts, "\n")
  172. if !strings.Contains(adminScripts, "lock") {
  173. scriptLines = append(append([]string{}, "lock"), scriptLines...)
  174. scriptLines = append(scriptLines, "unlock")
  175. }
  176. masterAddress := fmt.Sprintf("%s:%d", ms.option.Host, ms.option.Port)
  177. var shellOptions shell.ShellOptions
  178. shellOptions.GrpcDialOption = security.LoadClientTLS(v, "grpc.master")
  179. shellOptions.Masters = &masterAddress
  180. shellOptions.FilerHost, shellOptions.FilerPort, err = util.ParseHostPort(filerHostPort)
  181. shellOptions.Directory = "/"
  182. if err != nil {
  183. glog.V(0).Infof("failed to parse master.filer.default = %s : %v\n", filerHostPort, err)
  184. return
  185. }
  186. commandEnv := shell.NewCommandEnv(shellOptions)
  187. reg, _ := regexp.Compile(`'.*?'|".*?"|\S+`)
  188. go commandEnv.MasterClient.KeepConnectedToMaster()
  189. go func() {
  190. commandEnv.MasterClient.WaitUntilConnected()
  191. c := time.Tick(time.Duration(sleepMinutes) * time.Minute)
  192. for range c {
  193. if ms.Topo.IsLeader() {
  194. for _, line := range scriptLines {
  195. for _, c := range strings.Split(line, ";") {
  196. processEachCmd(reg, c, commandEnv)
  197. }
  198. }
  199. }
  200. }
  201. }()
  202. }
  203. func processEachCmd(reg *regexp.Regexp, line string, commandEnv *shell.CommandEnv) {
  204. cmds := reg.FindAllString(line, -1)
  205. if len(cmds) == 0 {
  206. return
  207. }
  208. args := make([]string, len(cmds[1:]))
  209. for i := range args {
  210. args[i] = strings.Trim(string(cmds[1+i]), "\"'")
  211. }
  212. cmd := strings.ToLower(cmds[0])
  213. for _, c := range shell.Commands {
  214. if c.Name() == cmd {
  215. glog.V(0).Infof("executing: %s %v", cmd, args)
  216. if err := c.Do(args, commandEnv, os.Stdout); err != nil {
  217. glog.V(0).Infof("error: %v", err)
  218. }
  219. }
  220. }
  221. }
  222. func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer {
  223. var seq sequence.Sequencer
  224. v := util.GetViper()
  225. seqType := strings.ToLower(v.GetString(SequencerType))
  226. glog.V(1).Infof("[%s] : [%s]", SequencerType, seqType)
  227. switch strings.ToLower(seqType) {
  228. case "etcd":
  229. var err error
  230. urls := v.GetString(SequencerEtcdUrls)
  231. glog.V(0).Infof("[%s] : [%s]", SequencerEtcdUrls, urls)
  232. seq, err = sequence.NewEtcdSequencer(urls, option.MetaFolder)
  233. if err != nil {
  234. glog.Error(err)
  235. seq = nil
  236. }
  237. default:
  238. seq = sequence.NewMemorySequencer()
  239. }
  240. return seq
  241. }