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.

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