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.

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