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.

383 lines
14 KiB

5 years ago
6 years ago
6 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
12 years ago
5 years ago
4 years ago
4 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
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/pprof"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  12. "github.com/spf13/viper"
  13. "google.golang.org/grpc"
  14. "github.com/seaweedfs/seaweedfs/weed/util/grace"
  15. "github.com/seaweedfs/seaweedfs/weed/pb"
  16. "github.com/seaweedfs/seaweedfs/weed/security"
  17. "github.com/seaweedfs/seaweedfs/weed/util/httpdown"
  18. "google.golang.org/grpc/reflection"
  19. "github.com/seaweedfs/seaweedfs/weed/glog"
  20. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  21. weed_server "github.com/seaweedfs/seaweedfs/weed/server"
  22. stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
  23. "github.com/seaweedfs/seaweedfs/weed/storage"
  24. "github.com/seaweedfs/seaweedfs/weed/util"
  25. )
  26. var (
  27. v VolumeServerOptions
  28. )
  29. type VolumeServerOptions struct {
  30. port *int
  31. portGrpc *int
  32. publicPort *int
  33. folders []string
  34. folderMaxLimits []int32
  35. idxFolder *string
  36. ip *string
  37. publicUrl *string
  38. bindIp *string
  39. mastersString *string
  40. masters []pb.ServerAddress
  41. idleConnectionTimeout *int
  42. dataCenter *string
  43. rack *string
  44. whiteList []string
  45. indexType *string
  46. diskType *string
  47. fixJpgOrientation *bool
  48. readMode *string
  49. cpuProfile *string
  50. memProfile *string
  51. compactionMBPerSecond *int
  52. fileSizeLimitMB *int
  53. concurrentUploadLimitMB *int
  54. concurrentDownloadLimitMB *int
  55. pprof *bool
  56. preStopSeconds *int
  57. metricsHttpPort *int
  58. // pulseSeconds *int
  59. inflightUploadDataTimeout *time.Duration
  60. }
  61. func init() {
  62. cmdVolume.Run = runVolume // break init cycle
  63. v.port = cmdVolume.Flag.Int("port", 8080, "http listen port")
  64. v.portGrpc = cmdVolume.Flag.Int("port.grpc", 0, "grpc listen port")
  65. v.publicPort = cmdVolume.Flag.Int("port.public", 0, "port opened to public")
  66. v.ip = cmdVolume.Flag.String("ip", util.DetectedHostAddress(), "ip or server name, also used as identifier")
  67. v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
  68. v.bindIp = cmdVolume.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
  69. v.mastersString = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
  70. v.preStopSeconds = cmdVolume.Flag.Int("preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
  71. // v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
  72. v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
  73. v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
  74. v.rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
  75. v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|leveldbMedium|leveldbLarge] mode for memory~performance balance.")
  76. v.diskType = cmdVolume.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  77. v.fixJpgOrientation = cmdVolume.Flag.Bool("images.fix.orientation", false, "Adjust jpg orientation when uploading.")
  78. v.readMode = cmdVolume.Flag.String("readMode", "proxy", "[local|proxy|redirect] how to deal with non-local volume: 'not found|proxy to remote node|redirect volume location'.")
  79. v.cpuProfile = cmdVolume.Flag.String("cpuprofile", "", "cpu profile output file")
  80. v.memProfile = cmdVolume.Flag.String("memprofile", "", "memory profile output file")
  81. v.compactionMBPerSecond = cmdVolume.Flag.Int("compactionMBps", 0, "limit background compaction or copying speed in mega bytes per second")
  82. v.fileSizeLimitMB = cmdVolume.Flag.Int("fileSizeLimitMB", 256, "limit file size to avoid out of memory")
  83. v.concurrentUploadLimitMB = cmdVolume.Flag.Int("concurrentUploadLimitMB", 256, "limit total concurrent upload size")
  84. v.concurrentDownloadLimitMB = cmdVolume.Flag.Int("concurrentDownloadLimitMB", 256, "limit total concurrent download size")
  85. v.pprof = cmdVolume.Flag.Bool("pprof", false, "enable pprof http handlers. precludes --memprofile and --cpuprofile")
  86. v.metricsHttpPort = cmdVolume.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  87. v.idxFolder = cmdVolume.Flag.String("dir.idx", "", "directory to store .idx files")
  88. v.inflightUploadDataTimeout = cmdVolume.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "inflight upload data wait timeout of volume servers")
  89. }
  90. var cmdVolume = &Command{
  91. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  92. Short: "start a volume server",
  93. Long: `start a volume server to provide storage spaces
  94. `,
  95. }
  96. var (
  97. volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  98. maxVolumeCounts = cmdVolume.Flag.String("max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
  99. volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  100. minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
  101. minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
  102. )
  103. func runVolume(cmd *Command, args []string) bool {
  104. util.LoadConfiguration("security", false)
  105. // If --pprof is set we assume the caller wants to be able to collect
  106. // cpu and memory profiles via go tool pprof
  107. if !*v.pprof {
  108. grace.SetupProfiling(*v.cpuProfile, *v.memProfile)
  109. }
  110. go stats_collect.StartMetricsServer(*v.metricsHttpPort)
  111. minFreeSpaces := util.MustParseMinFreeSpace(*minFreeSpace, *minFreeSpacePercent)
  112. v.masters = pb.ServerAddresses(*v.mastersString).ToAddresses()
  113. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, minFreeSpaces)
  114. return true
  115. }
  116. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption string, minFreeSpaces []util.MinFreeSpace) {
  117. // Set multiple folders and each folder's max volume count limit'
  118. v.folders = strings.Split(volumeFolders, ",")
  119. for _, folder := range v.folders {
  120. if err := util.TestFolderWritable(util.ResolvePath(folder)); err != nil {
  121. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  122. }
  123. }
  124. // set max
  125. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  126. for _, maxString := range maxCountStrings {
  127. if max, e := strconv.ParseInt(maxString, 10, 64); e == nil {
  128. v.folderMaxLimits = append(v.folderMaxLimits, int32(max))
  129. } else {
  130. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  131. }
  132. }
  133. if len(v.folderMaxLimits) == 1 && len(v.folders) > 1 {
  134. for i := 0; i < len(v.folders)-1; i++ {
  135. v.folderMaxLimits = append(v.folderMaxLimits, v.folderMaxLimits[0])
  136. }
  137. }
  138. if len(v.folders) != len(v.folderMaxLimits) {
  139. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  140. }
  141. if len(minFreeSpaces) == 1 && len(v.folders) > 1 {
  142. for i := 0; i < len(v.folders)-1; i++ {
  143. minFreeSpaces = append(minFreeSpaces, minFreeSpaces[0])
  144. }
  145. }
  146. if len(v.folders) != len(minFreeSpaces) {
  147. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(minFreeSpaces))
  148. }
  149. // set disk types
  150. var diskTypes []types.DiskType
  151. diskTypeStrings := strings.Split(*v.diskType, ",")
  152. for _, diskTypeString := range diskTypeStrings {
  153. diskTypes = append(diskTypes, types.ToDiskType(diskTypeString))
  154. }
  155. if len(diskTypes) == 1 && len(v.folders) > 1 {
  156. for i := 0; i < len(v.folders)-1; i++ {
  157. diskTypes = append(diskTypes, diskTypes[0])
  158. }
  159. }
  160. if len(v.folders) != len(diskTypes) {
  161. glog.Fatalf("%d directories by -dir, but only %d disk types is set by -disk", len(v.folders), len(diskTypes))
  162. }
  163. // security related white list configuration
  164. v.whiteList = util.StringSplit(volumeWhiteListOption, ",")
  165. if *v.ip == "" {
  166. *v.ip = util.DetectedHostAddress()
  167. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  168. }
  169. if *v.bindIp == "" {
  170. *v.bindIp = *v.ip
  171. }
  172. if *v.publicPort == 0 {
  173. *v.publicPort = *v.port
  174. }
  175. if *v.portGrpc == 0 {
  176. *v.portGrpc = 10000 + *v.port
  177. }
  178. if *v.publicUrl == "" {
  179. *v.publicUrl = util.JoinHostPort(*v.ip, *v.publicPort)
  180. }
  181. volumeMux := http.NewServeMux()
  182. publicVolumeMux := volumeMux
  183. if v.isSeparatedPublicPort() {
  184. publicVolumeMux = http.NewServeMux()
  185. }
  186. if *v.pprof {
  187. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  188. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  189. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  190. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  191. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  192. }
  193. volumeNeedleMapKind := storage.NeedleMapInMemory
  194. switch *v.indexType {
  195. case "leveldb":
  196. volumeNeedleMapKind = storage.NeedleMapLevelDb
  197. case "leveldbMedium":
  198. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  199. case "leveldbLarge":
  200. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  201. }
  202. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  203. *v.ip, *v.port, *v.portGrpc, *v.publicUrl,
  204. v.folders, v.folderMaxLimits, minFreeSpaces, diskTypes,
  205. *v.idxFolder,
  206. volumeNeedleMapKind,
  207. v.masters, 5, *v.dataCenter, *v.rack,
  208. v.whiteList,
  209. *v.fixJpgOrientation, *v.readMode,
  210. *v.compactionMBPerSecond,
  211. *v.fileSizeLimitMB,
  212. int64(*v.concurrentUploadLimitMB)*1024*1024,
  213. int64(*v.concurrentDownloadLimitMB)*1024*1024,
  214. *v.inflightUploadDataTimeout,
  215. )
  216. // starting grpc server
  217. grpcS := v.startGrpcService(volumeServer)
  218. // starting public http server
  219. var publicHttpDown httpdown.Server
  220. if v.isSeparatedPublicPort() {
  221. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  222. if nil == publicHttpDown {
  223. glog.Fatalf("start public http service failed")
  224. }
  225. }
  226. // starting the cluster http server
  227. clusterHttpServer := v.startClusterHttpService(volumeMux)
  228. stopChan := make(chan bool)
  229. grace.OnInterrupt(func() {
  230. fmt.Println("volume server has been killed")
  231. // Stop heartbeats
  232. if !volumeServer.StopHeartbeat() {
  233. volumeServer.SetStopping()
  234. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  235. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  236. }
  237. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  238. stopChan <- true
  239. })
  240. select {
  241. case <-stopChan:
  242. }
  243. }
  244. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  245. // firstly, stop the public http service to prevent from receiving new user request
  246. if nil != publicHttpDown {
  247. glog.V(0).Infof("stop public http server ... ")
  248. if err := publicHttpDown.Stop(); err != nil {
  249. glog.Warningf("stop the public http server failed, %v", err)
  250. }
  251. }
  252. glog.V(0).Infof("graceful stop cluster http server ... ")
  253. if err := clusterHttpServer.Stop(); err != nil {
  254. glog.Warningf("stop the cluster http server failed, %v", err)
  255. }
  256. glog.V(0).Infof("graceful stop gRPC ...")
  257. grpcS.GracefulStop()
  258. volumeServer.Shutdown()
  259. pprof.StopCPUProfile()
  260. }
  261. // check whether configure the public port
  262. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  263. return *v.publicPort != *v.port
  264. }
  265. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  266. grpcPort := *v.portGrpc
  267. grpcL, err := util.NewListener(util.JoinHostPort(*v.bindIp, grpcPort), 0)
  268. if err != nil {
  269. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  270. }
  271. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  272. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  273. reflection.Register(grpcS)
  274. go func() {
  275. if err := grpcS.Serve(grpcL); err != nil {
  276. glog.Fatalf("start gRPC service failed, %s", err)
  277. }
  278. }()
  279. return grpcS
  280. }
  281. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  282. publicListeningAddress := util.JoinHostPort(*v.bindIp, *v.publicPort)
  283. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  284. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  285. if e != nil {
  286. glog.Fatalf("Volume server listener error:%v", e)
  287. }
  288. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  289. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  290. go func() {
  291. if err := publicHttpDown.Wait(); err != nil {
  292. glog.Errorf("public http down wait failed, %v", err)
  293. }
  294. }()
  295. return publicHttpDown
  296. }
  297. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  298. var (
  299. certFile, keyFile string
  300. )
  301. if viper.GetString("https.volume.key") != "" {
  302. certFile = viper.GetString("https.volume.cert")
  303. keyFile = viper.GetString("https.volume.key")
  304. }
  305. listeningAddress := util.JoinHostPort(*v.bindIp, *v.port)
  306. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  307. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  308. if e != nil {
  309. glog.Fatalf("Volume server listener error:%v", e)
  310. }
  311. httpDown := httpdown.HTTP{
  312. KillTimeout: time.Minute,
  313. StopTimeout: 30 * time.Second,
  314. CertFile: certFile,
  315. KeyFile: keyFile}
  316. httpS := &http.Server{Handler: handler}
  317. if viper.GetString("https.volume.ca") != "" {
  318. clientCertFile := viper.GetString("https.volume.ca")
  319. httpS.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
  320. }
  321. clusterHttpServer := httpDown.Serve(httpS, listener)
  322. go func() {
  323. if e := clusterHttpServer.Wait(); e != nil {
  324. glog.Fatalf("Volume server fail to serve: %v", e)
  325. }
  326. }()
  327. return clusterHttpServer
  328. }