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.

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