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.

337 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
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. // 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", 1024, "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", "8", "maximum numbers of volumes, count[,count]... If set to zero, 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", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes 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. for _, folder := range v.folders {
  100. if err := util.TestFolderWritable(util.ResolvePath(folder)); err != nil {
  101. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  102. }
  103. }
  104. // set max
  105. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  106. for _, maxString := range maxCountStrings {
  107. if max, e := strconv.Atoi(maxString); e == nil {
  108. v.folderMaxLimits = append(v.folderMaxLimits, max)
  109. } else {
  110. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  111. }
  112. }
  113. if len(v.folders) != len(v.folderMaxLimits) {
  114. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  115. }
  116. // set minFreeSpacePercent
  117. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  118. for _, freeString := range minFreeSpacePercentStrings {
  119. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  120. v.minFreeSpacePercents = append(v.minFreeSpacePercents, float32(value))
  121. } else {
  122. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  123. }
  124. }
  125. if len(v.minFreeSpacePercents) == 1 && len(v.folders) > 1 {
  126. for i := 0; i < len(v.folders)-1; i++ {
  127. v.minFreeSpacePercents = append(v.minFreeSpacePercents, v.minFreeSpacePercents[0])
  128. }
  129. }
  130. if len(v.folders) != len(v.minFreeSpacePercents) {
  131. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(v.minFreeSpacePercents))
  132. }
  133. // security related white list configuration
  134. if volumeWhiteListOption != "" {
  135. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  136. }
  137. if *v.ip == "" {
  138. *v.ip = util.DetectedHostAddress()
  139. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  140. }
  141. if *v.publicPort == 0 {
  142. *v.publicPort = *v.port
  143. }
  144. if *v.publicUrl == "" {
  145. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  146. }
  147. volumeMux := http.NewServeMux()
  148. publicVolumeMux := volumeMux
  149. if v.isSeparatedPublicPort() {
  150. publicVolumeMux = http.NewServeMux()
  151. }
  152. if *v.pprof {
  153. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  154. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  155. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  156. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  157. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  158. }
  159. volumeNeedleMapKind := storage.NeedleMapInMemory
  160. switch *v.indexType {
  161. case "leveldb":
  162. volumeNeedleMapKind = storage.NeedleMapLevelDb
  163. case "leveldbMedium":
  164. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  165. case "leveldbLarge":
  166. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  167. }
  168. masters := *v.masters
  169. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  170. *v.ip, *v.port, *v.publicUrl,
  171. v.folders, v.folderMaxLimits, v.minFreeSpacePercents,
  172. volumeNeedleMapKind,
  173. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  174. v.whiteList,
  175. *v.fixJpgOrientation, *v.readRedirect,
  176. *v.compactionMBPerSecond,
  177. *v.fileSizeLimitMB,
  178. )
  179. // starting grpc server
  180. grpcS := v.startGrpcService(volumeServer)
  181. // starting public http server
  182. var publicHttpDown httpdown.Server
  183. if v.isSeparatedPublicPort() {
  184. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  185. if nil == publicHttpDown {
  186. glog.Fatalf("start public http service failed")
  187. }
  188. }
  189. // starting the cluster http server
  190. clusterHttpServer := v.startClusterHttpService(volumeMux)
  191. stopChain := make(chan struct{})
  192. grace.OnInterrupt(func() {
  193. fmt.Println("volume server has be killed")
  194. var startTime time.Time
  195. // firstly, stop the public http service to prevent from receiving new user request
  196. if nil != publicHttpDown {
  197. startTime = time.Now()
  198. if err := publicHttpDown.Stop(); err != nil {
  199. glog.Warningf("stop the public http server failed, %v", err)
  200. }
  201. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  202. glog.V(0).Infof("stop public http server, elapsed %dms", delta)
  203. }
  204. startTime = time.Now()
  205. if err := clusterHttpServer.Stop(); err != nil {
  206. glog.Warningf("stop the cluster http server failed, %v", err)
  207. }
  208. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  209. glog.V(0).Infof("graceful stop cluster http server, elapsed [%d]", delta)
  210. startTime = time.Now()
  211. grpcS.GracefulStop()
  212. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  213. glog.V(0).Infof("graceful stop gRPC, elapsed [%d]", delta)
  214. startTime = time.Now()
  215. volumeServer.Shutdown()
  216. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  217. glog.V(0).Infof("stop volume server, elapsed [%d]", delta)
  218. pprof.StopCPUProfile()
  219. close(stopChain) // notify exit
  220. })
  221. select {
  222. case <-stopChain:
  223. }
  224. glog.Warningf("the volume server exit.")
  225. }
  226. // check whether configure the public port
  227. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  228. return *v.publicPort != *v.port
  229. }
  230. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  231. grpcPort := *v.port + 10000
  232. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  233. if err != nil {
  234. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  235. }
  236. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  237. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  238. reflection.Register(grpcS)
  239. go func() {
  240. if err := grpcS.Serve(grpcL); err != nil {
  241. glog.Fatalf("start gRPC service failed, %s", err)
  242. }
  243. }()
  244. return grpcS
  245. }
  246. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  247. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  248. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  249. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  250. if e != nil {
  251. glog.Fatalf("Volume server listener error:%v", e)
  252. }
  253. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  254. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  255. go func() {
  256. if err := publicHttpDown.Wait(); err != nil {
  257. glog.Errorf("public http down wait failed, %v", err)
  258. }
  259. }()
  260. return publicHttpDown
  261. }
  262. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  263. var (
  264. certFile, keyFile string
  265. )
  266. if viper.GetString("https.volume.key") != "" {
  267. certFile = viper.GetString("https.volume.cert")
  268. keyFile = viper.GetString("https.volume.key")
  269. }
  270. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  271. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  272. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  273. if e != nil {
  274. glog.Fatalf("Volume server listener error:%v", e)
  275. }
  276. httpDown := httpdown.HTTP{
  277. KillTimeout: 5 * time.Minute,
  278. StopTimeout: 5 * time.Minute,
  279. CertFile: certFile,
  280. KeyFile: keyFile}
  281. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  282. go func() {
  283. if e := clusterHttpServer.Wait(); e != nil {
  284. glog.Fatalf("Volume server fail to serve: %v", e)
  285. }
  286. }()
  287. return clusterHttpServer
  288. }