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.

303 lines
9.2 KiB

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