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.

284 lines
8.8 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
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. 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. 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.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, 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. 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("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.bounedLeaderChan <- 1
  134. defer func() { <-ms.bounedLeaderChan }()
  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. }