volume.go 16 KB

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