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.

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