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.

339 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
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. "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", 10, "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. stopChan := make(chan bool)
  194. grace.OnInterrupt(func() {
  195. fmt.Println("volume server has be killed")
  196. // Stop heartbeats
  197. if !volumeServer.StopHeartbeat() {
  198. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  199. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  200. }
  201. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  202. stopChan <- true
  203. })
  204. select {
  205. case <-stopChan:
  206. }
  207. }
  208. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  209. // firstly, stop the public http service to prevent from receiving new user request
  210. if nil != publicHttpDown {
  211. glog.V(0).Infof("stop public http server ... ")
  212. if err := publicHttpDown.Stop(); err != nil {
  213. glog.Warningf("stop the public http server failed, %v", err)
  214. }
  215. }
  216. glog.V(0).Infof("graceful stop cluster http server ... ")
  217. if err := clusterHttpServer.Stop(); err != nil {
  218. glog.Warningf("stop the cluster http server failed, %v", err)
  219. }
  220. glog.V(0).Infof("graceful stop gRPC ...")
  221. grpcS.GracefulStop()
  222. volumeServer.Shutdown()
  223. pprof.StopCPUProfile()
  224. }
  225. // check whether configure the public port
  226. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  227. return *v.publicPort != *v.port
  228. }
  229. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  230. grpcPort := *v.port + 10000
  231. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  232. if err != nil {
  233. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  234. }
  235. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  236. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  237. reflection.Register(grpcS)
  238. go func() {
  239. if err := grpcS.Serve(grpcL); err != nil {
  240. glog.Fatalf("start gRPC service failed, %s", err)
  241. }
  242. }()
  243. return grpcS
  244. }
  245. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  246. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  247. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  248. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  249. if e != nil {
  250. glog.Fatalf("Volume server listener error:%v", e)
  251. }
  252. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  253. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  254. go func() {
  255. if err := publicHttpDown.Wait(); err != nil {
  256. glog.Errorf("public http down wait failed, %v", err)
  257. }
  258. }()
  259. return publicHttpDown
  260. }
  261. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  262. var (
  263. certFile, keyFile string
  264. )
  265. if viper.GetString("https.volume.key") != "" {
  266. certFile = viper.GetString("https.volume.cert")
  267. keyFile = viper.GetString("https.volume.key")
  268. }
  269. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  270. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  271. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  272. if e != nil {
  273. glog.Fatalf("Volume server listener error:%v", e)
  274. }
  275. httpDown := httpdown.HTTP{
  276. KillTimeout: 5 * time.Minute,
  277. StopTimeout: 5 * time.Minute,
  278. CertFile: certFile,
  279. KeyFile: keyFile}
  280. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  281. go func() {
  282. if e := clusterHttpServer.Wait(); e != nil {
  283. glog.Fatalf("Volume server fail to serve: %v", e)
  284. }
  285. }()
  286. return clusterHttpServer
  287. }