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.

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