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.

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