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.

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