volume.go 14 KB

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