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.

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