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.

370 lines
13 KiB

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