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.

349 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", 256, "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.folderMaxLimits) == 1 && len(v.folders) > 1 {
  120. for i := 0; i < len(v.folders)-1; i++ {
  121. v.folderMaxLimits = append(v.folderMaxLimits, v.folderMaxLimits[0])
  122. }
  123. }
  124. if len(v.folders) != len(v.folderMaxLimits) {
  125. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  126. }
  127. // set minFreeSpacePercent
  128. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  129. for _, freeString := range minFreeSpacePercentStrings {
  130. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  131. v.minFreeSpacePercents = append(v.minFreeSpacePercents, float32(value))
  132. } else {
  133. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  134. }
  135. }
  136. if len(v.minFreeSpacePercents) == 1 && len(v.folders) > 1 {
  137. for i := 0; i < len(v.folders)-1; i++ {
  138. v.minFreeSpacePercents = append(v.minFreeSpacePercents, v.minFreeSpacePercents[0])
  139. }
  140. }
  141. if len(v.folders) != len(v.minFreeSpacePercents) {
  142. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(v.minFreeSpacePercents))
  143. }
  144. // security related white list configuration
  145. if volumeWhiteListOption != "" {
  146. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  147. }
  148. if *v.ip == "" {
  149. *v.ip = util.DetectedHostAddress()
  150. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  151. }
  152. if *v.publicPort == 0 {
  153. *v.publicPort = *v.port
  154. }
  155. if *v.publicUrl == "" {
  156. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  157. }
  158. volumeMux := http.NewServeMux()
  159. publicVolumeMux := volumeMux
  160. if v.isSeparatedPublicPort() {
  161. publicVolumeMux = http.NewServeMux()
  162. }
  163. if *v.pprof {
  164. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  165. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  166. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  167. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  168. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  169. }
  170. volumeNeedleMapKind := storage.NeedleMapInMemory
  171. switch *v.indexType {
  172. case "leveldb":
  173. volumeNeedleMapKind = storage.NeedleMapLevelDb
  174. case "leveldbMedium":
  175. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  176. case "leveldbLarge":
  177. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  178. }
  179. masters := *v.masters
  180. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  181. *v.ip, *v.port, *v.publicUrl,
  182. v.folders, v.folderMaxLimits, v.minFreeSpacePercents,
  183. volumeNeedleMapKind,
  184. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  185. v.whiteList,
  186. *v.fixJpgOrientation, *v.readRedirect,
  187. *v.compactionMBPerSecond,
  188. *v.fileSizeLimitMB,
  189. )
  190. // starting grpc server
  191. grpcS := v.startGrpcService(volumeServer)
  192. // starting public http server
  193. var publicHttpDown httpdown.Server
  194. if v.isSeparatedPublicPort() {
  195. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  196. if nil == publicHttpDown {
  197. glog.Fatalf("start public http service failed")
  198. }
  199. }
  200. // starting the cluster http server
  201. clusterHttpServer := v.startClusterHttpService(volumeMux)
  202. stopChan := make(chan bool)
  203. grace.OnInterrupt(func() {
  204. fmt.Println("volume server has be killed")
  205. // Stop heartbeats
  206. if !volumeServer.StopHeartbeat() {
  207. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  208. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  209. }
  210. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  211. stopChan <- true
  212. })
  213. select {
  214. case <-stopChan:
  215. }
  216. }
  217. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  218. // firstly, stop the public http service to prevent from receiving new user request
  219. if nil != publicHttpDown {
  220. glog.V(0).Infof("stop public http server ... ")
  221. if err := publicHttpDown.Stop(); err != nil {
  222. glog.Warningf("stop the public http server failed, %v", err)
  223. }
  224. }
  225. glog.V(0).Infof("graceful stop cluster http server ... ")
  226. if err := clusterHttpServer.Stop(); err != nil {
  227. glog.Warningf("stop the cluster http server failed, %v", err)
  228. }
  229. glog.V(0).Infof("graceful stop gRPC ...")
  230. grpcS.GracefulStop()
  231. volumeServer.Shutdown()
  232. pprof.StopCPUProfile()
  233. }
  234. // check whether configure the public port
  235. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  236. return *v.publicPort != *v.port
  237. }
  238. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  239. grpcPort := *v.port + 10000
  240. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  241. if err != nil {
  242. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  243. }
  244. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  245. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  246. reflection.Register(grpcS)
  247. go func() {
  248. if err := grpcS.Serve(grpcL); err != nil {
  249. glog.Fatalf("start gRPC service failed, %s", err)
  250. }
  251. }()
  252. return grpcS
  253. }
  254. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  255. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  256. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  257. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  258. if e != nil {
  259. glog.Fatalf("Volume server listener error:%v", e)
  260. }
  261. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  262. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  263. go func() {
  264. if err := publicHttpDown.Wait(); err != nil {
  265. glog.Errorf("public http down wait failed, %v", err)
  266. }
  267. }()
  268. return publicHttpDown
  269. }
  270. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  271. var (
  272. certFile, keyFile string
  273. )
  274. if viper.GetString("https.volume.key") != "" {
  275. certFile = viper.GetString("https.volume.cert")
  276. keyFile = viper.GetString("https.volume.key")
  277. }
  278. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  279. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  280. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  281. if e != nil {
  282. glog.Fatalf("Volume server listener error:%v", e)
  283. }
  284. httpDown := httpdown.HTTP{
  285. KillTimeout: 5 * time.Minute,
  286. StopTimeout: 5 * time.Minute,
  287. CertFile: certFile,
  288. KeyFile: keyFile}
  289. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  290. go func() {
  291. if e := clusterHttpServer.Wait(); e != nil {
  292. glog.Fatalf("Volume server fail to serve: %v", e)
  293. }
  294. }()
  295. return clusterHttpServer
  296. }