volume.go 15 KB

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