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.

327 lines
11 KiB

5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
13 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package command
  2. import (
  3. "fmt"
  4. "net/http"
  5. httppprof "net/http/pprof"
  6. "os"
  7. "runtime"
  8. "runtime/pprof"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/spf13/viper"
  13. "google.golang.org/grpc"
  14. "github.com/chrislusf/seaweedfs/weed/util/grace"
  15. "github.com/chrislusf/seaweedfs/weed/pb"
  16. "github.com/chrislusf/seaweedfs/weed/security"
  17. "github.com/chrislusf/seaweedfs/weed/util/httpdown"
  18. "google.golang.org/grpc/reflection"
  19. "github.com/chrislusf/seaweedfs/weed/glog"
  20. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  21. "github.com/chrislusf/seaweedfs/weed/server"
  22. "github.com/chrislusf/seaweedfs/weed/storage"
  23. "github.com/chrislusf/seaweedfs/weed/util"
  24. )
  25. var (
  26. v VolumeServerOptions
  27. )
  28. type VolumeServerOptions struct {
  29. port *int
  30. publicPort *int
  31. folders []string
  32. folderMaxLimits []int
  33. ip *string
  34. publicUrl *string
  35. bindIp *string
  36. masters *string
  37. idleConnectionTimeout *int
  38. dataCenter *string
  39. rack *string
  40. whiteList []string
  41. indexType *string
  42. readRedirect *bool
  43. cpuProfile *string
  44. memProfile *string
  45. compactionMBPerSecond *int
  46. fileSizeLimitMB *int
  47. minFreeSpacePercent []float32
  48. pprof *bool
  49. // pulseSeconds *int
  50. }
  51. func init() {
  52. cmdVolume.Run = runVolume // break init cycle
  53. v.port = cmdVolume.Flag.Int("port", 8080, "http listen port")
  54. v.publicPort = cmdVolume.Flag.Int("port.public", 0, "port opened to public")
  55. v.ip = cmdVolume.Flag.String("ip", util.DetectedHostAddress(), "ip or server name")
  56. v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
  57. v.bindIp = cmdVolume.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
  58. v.masters = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
  59. // v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
  60. v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
  61. v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
  62. v.rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
  63. v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|leveldbMedium|leveldbLarge] mode for memory~performance balance.")
  64. v.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
  65. v.cpuProfile = cmdVolume.Flag.String("cpuprofile", "", "cpu profile output file")
  66. v.memProfile = cmdVolume.Flag.String("memprofile", "", "memory profile output file")
  67. v.compactionMBPerSecond = cmdVolume.Flag.Int("compactionMBps", 0, "limit background compaction or copying speed in mega bytes per second")
  68. v.fileSizeLimitMB = cmdVolume.Flag.Int("fileSizeLimitMB", 256, "limit file size to avoid out of memory")
  69. v.pprof = cmdVolume.Flag.Bool("pprof", false, "enable pprof http handlers. precludes --memprofile and --cpuprofile")
  70. }
  71. var cmdVolume = &Command{
  72. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  73. Short: "start a volume server",
  74. Long: `start a volume server to provide storage spaces
  75. `,
  76. }
  77. var (
  78. volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  79. maxVolumeCounts = cmdVolume.Flag.String("max", "7", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured.")
  80. volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  81. minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "0", "minimum free disk space(in percents). Low disk space will mark all volumes as ReadOnly.")
  82. )
  83. func runVolume(cmd *Command, args []string) bool {
  84. util.LoadConfiguration("security", false)
  85. runtime.GOMAXPROCS(runtime.NumCPU())
  86. // If --pprof is set we assume the caller wants to be able to collect
  87. // cpu and memory profiles via go tool pprof
  88. if !*v.pprof {
  89. grace.SetupProfiling(*v.cpuProfile, *v.memProfile)
  90. }
  91. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, *minFreeSpacePercent)
  92. return true
  93. }
  94. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption, minFreeSpacePercent string) {
  95. // Set multiple folders and each folder's max volume count limit'
  96. v.folders = strings.Split(volumeFolders, ",")
  97. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  98. for _, maxString := range maxCountStrings {
  99. if max, e := strconv.Atoi(maxString); e == nil {
  100. v.folderMaxLimits = append(v.folderMaxLimits, max)
  101. } else {
  102. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  103. }
  104. }
  105. if len(v.folders) != len(v.folderMaxLimits) {
  106. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  107. }
  108. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  109. for _, freeString := range minFreeSpacePercentStrings {
  110. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  111. v.minFreeSpacePercent = append(v.minFreeSpacePercent, float32(value))
  112. } else {
  113. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  114. }
  115. }
  116. if len(v.folders) != len(v.minFreeSpacePercent) {
  117. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  118. }
  119. for _, folder := range v.folders {
  120. if err := util.TestFolderWritable(folder); err != nil {
  121. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  122. }
  123. }
  124. // security related white list configuration
  125. if volumeWhiteListOption != "" {
  126. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  127. }
  128. if *v.ip == "" {
  129. *v.ip = util.DetectedHostAddress()
  130. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  131. }
  132. if *v.publicPort == 0 {
  133. *v.publicPort = *v.port
  134. }
  135. if *v.publicUrl == "" {
  136. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  137. }
  138. volumeMux := http.NewServeMux()
  139. publicVolumeMux := volumeMux
  140. if v.isSeparatedPublicPort() {
  141. publicVolumeMux = http.NewServeMux()
  142. }
  143. if *v.pprof {
  144. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  145. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  146. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  147. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  148. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  149. }
  150. volumeNeedleMapKind := storage.NeedleMapInMemory
  151. switch *v.indexType {
  152. case "leveldb":
  153. volumeNeedleMapKind = storage.NeedleMapLevelDb
  154. case "leveldbMedium":
  155. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  156. case "leveldbLarge":
  157. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  158. }
  159. masters := *v.masters
  160. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  161. *v.ip, *v.port, *v.publicUrl,
  162. v.folders, v.folderMaxLimits, v.minFreeSpacePercent,
  163. volumeNeedleMapKind,
  164. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  165. v.whiteList,
  166. *v.readRedirect,
  167. *v.compactionMBPerSecond,
  168. *v.fileSizeLimitMB,
  169. )
  170. // starting grpc server
  171. grpcS := v.startGrpcService(volumeServer)
  172. // starting public http server
  173. var publicHttpDown httpdown.Server
  174. if v.isSeparatedPublicPort() {
  175. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  176. if nil == publicHttpDown {
  177. glog.Fatalf("start public http service failed")
  178. }
  179. }
  180. // starting the cluster http server
  181. clusterHttpServer := v.startClusterHttpService(volumeMux)
  182. stopChain := make(chan struct{})
  183. grace.OnInterrupt(func() {
  184. fmt.Println("volume server has be killed")
  185. var startTime time.Time
  186. // firstly, stop the public http service to prevent from receiving new user request
  187. if nil != publicHttpDown {
  188. startTime = time.Now()
  189. if err := publicHttpDown.Stop(); err != nil {
  190. glog.Warningf("stop the public http server failed, %v", err)
  191. }
  192. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  193. glog.V(0).Infof("stop public http server, elapsed %dms", delta)
  194. }
  195. startTime = time.Now()
  196. if err := clusterHttpServer.Stop(); err != nil {
  197. glog.Warningf("stop the cluster http server failed, %v", err)
  198. }
  199. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  200. glog.V(0).Infof("graceful stop cluster http server, elapsed [%d]", delta)
  201. startTime = time.Now()
  202. grpcS.GracefulStop()
  203. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  204. glog.V(0).Infof("graceful stop gRPC, elapsed [%d]", delta)
  205. startTime = time.Now()
  206. volumeServer.Shutdown()
  207. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  208. glog.V(0).Infof("stop volume server, elapsed [%d]", delta)
  209. pprof.StopCPUProfile()
  210. close(stopChain) // notify exit
  211. })
  212. select {
  213. case <-stopChain:
  214. }
  215. glog.Warningf("the volume server exit.")
  216. }
  217. // check whether configure the public port
  218. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  219. return *v.publicPort != *v.port
  220. }
  221. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  222. grpcPort := *v.port + 10000
  223. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  224. if err != nil {
  225. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  226. }
  227. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  228. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  229. reflection.Register(grpcS)
  230. go func() {
  231. if err := grpcS.Serve(grpcL); err != nil {
  232. glog.Fatalf("start gRPC service failed, %s", err)
  233. }
  234. }()
  235. return grpcS
  236. }
  237. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  238. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  239. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  240. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  241. if e != nil {
  242. glog.Fatalf("Volume server listener error:%v", e)
  243. }
  244. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  245. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  246. go func() {
  247. if err := publicHttpDown.Wait(); err != nil {
  248. glog.Errorf("public http down wait failed, %v", err)
  249. }
  250. }()
  251. return publicHttpDown
  252. }
  253. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  254. var (
  255. certFile, keyFile string
  256. )
  257. if viper.GetString("https.volume.key") != "" {
  258. certFile = viper.GetString("https.volume.cert")
  259. keyFile = viper.GetString("https.volume.key")
  260. }
  261. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  262. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  263. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  264. if e != nil {
  265. glog.Fatalf("Volume server listener error:%v", e)
  266. }
  267. httpDown := httpdown.HTTP{
  268. KillTimeout: 5 * time.Minute,
  269. StopTimeout: 5 * time.Minute,
  270. CertFile: certFile,
  271. KeyFile: keyFile}
  272. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  273. go func() {
  274. if e := clusterHttpServer.Wait(); e != nil {
  275. glog.Fatalf("Volume server fail to serve: %v", e)
  276. }
  277. }()
  278. return clusterHttpServer
  279. }