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.

393 lines
14 KiB

5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 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
5 years ago
5 years ago
5 years ago
5 years ago
13 years ago
5 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. readRedirect *bool
  47. cpuProfile *string
  48. memProfile *string
  49. compactionMBPerSecond *int
  50. fileSizeLimitMB *int
  51. minFreeSpacePercents []float32
  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.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
  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.pprof = cmdVolume.Flag.Bool("pprof", false, "enable pprof http handlers. precludes --memprofile and --cpuprofile")
  80. v.metricsHttpPort = cmdVolume.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  81. v.idxFolder = cmdVolume.Flag.String("dir.idx", "", "directory to store .idx files")
  82. v.enableTcp = cmdVolume.Flag.Bool("tcp", false, "<exprimental> enable tcp port")
  83. }
  84. var cmdVolume = &Command{
  85. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  86. Short: "start a volume server",
  87. Long: `start a volume server to provide storage spaces
  88. `,
  89. }
  90. var (
  91. volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  92. maxVolumeCounts = cmdVolume.Flag.String("max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured.")
  93. volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  94. minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly.")
  95. )
  96. func runVolume(cmd *Command, args []string) bool {
  97. util.LoadConfiguration("security", false)
  98. // If --pprof is set we assume the caller wants to be able to collect
  99. // cpu and memory profiles via go tool pprof
  100. if !*v.pprof {
  101. grace.SetupProfiling(*v.cpuProfile, *v.memProfile)
  102. }
  103. go stats_collect.StartMetricsServer(*v.metricsHttpPort)
  104. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, *minFreeSpacePercent)
  105. return true
  106. }
  107. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption, minFreeSpacePercent string) {
  108. // Set multiple folders and each folder's max volume count limit'
  109. v.folders = strings.Split(volumeFolders, ",")
  110. for _, folder := range v.folders {
  111. if err := util.TestFolderWritable(util.ResolvePath(folder)); err != nil {
  112. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  113. }
  114. }
  115. // set max
  116. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  117. for _, maxString := range maxCountStrings {
  118. if max, e := strconv.Atoi(maxString); e == nil {
  119. v.folderMaxLimits = append(v.folderMaxLimits, max)
  120. } else {
  121. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  122. }
  123. }
  124. if len(v.folderMaxLimits) == 1 && len(v.folders) > 1 {
  125. for i := 0; i < len(v.folders)-1; i++ {
  126. v.folderMaxLimits = append(v.folderMaxLimits, v.folderMaxLimits[0])
  127. }
  128. }
  129. if len(v.folders) != len(v.folderMaxLimits) {
  130. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  131. }
  132. // set minFreeSpacePercent
  133. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  134. for _, freeString := range minFreeSpacePercentStrings {
  135. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  136. v.minFreeSpacePercents = append(v.minFreeSpacePercents, float32(value))
  137. } else {
  138. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  139. }
  140. }
  141. if len(v.minFreeSpacePercents) == 1 && len(v.folders) > 1 {
  142. for i := 0; i < len(v.folders)-1; i++ {
  143. v.minFreeSpacePercents = append(v.minFreeSpacePercents, v.minFreeSpacePercents[0])
  144. }
  145. }
  146. if len(v.folders) != len(v.minFreeSpacePercents) {
  147. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(v.minFreeSpacePercents))
  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. if volumeWhiteListOption != "" {
  165. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  166. }
  167. if *v.ip == "" {
  168. *v.ip = util.DetectedHostAddress()
  169. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  170. }
  171. if *v.publicPort == 0 {
  172. *v.publicPort = *v.port
  173. }
  174. if *v.publicUrl == "" {
  175. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  176. }
  177. volumeMux := http.NewServeMux()
  178. publicVolumeMux := volumeMux
  179. if v.isSeparatedPublicPort() {
  180. publicVolumeMux = http.NewServeMux()
  181. }
  182. if *v.pprof {
  183. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  184. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  185. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  186. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  187. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  188. }
  189. volumeNeedleMapKind := storage.NeedleMapInMemory
  190. switch *v.indexType {
  191. case "leveldb":
  192. volumeNeedleMapKind = storage.NeedleMapLevelDb
  193. case "leveldbMedium":
  194. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  195. case "leveldbLarge":
  196. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  197. }
  198. masters := *v.masters
  199. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  200. *v.ip, *v.port, *v.publicUrl,
  201. v.folders, v.folderMaxLimits, v.minFreeSpacePercents, diskTypes,
  202. *v.idxFolder,
  203. volumeNeedleMapKind,
  204. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  205. v.whiteList,
  206. *v.fixJpgOrientation, *v.readRedirect,
  207. *v.compactionMBPerSecond,
  208. *v.fileSizeLimitMB,
  209. )
  210. // starting grpc server
  211. grpcS := v.startGrpcService(volumeServer)
  212. // starting public http server
  213. var publicHttpDown httpdown.Server
  214. if v.isSeparatedPublicPort() {
  215. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  216. if nil == publicHttpDown {
  217. glog.Fatalf("start public http service failed")
  218. }
  219. }
  220. // starting tcp server
  221. if *v.enableTcp {
  222. go v.startTcpService(volumeServer)
  223. }
  224. // starting the cluster http server
  225. clusterHttpServer := v.startClusterHttpService(volumeMux)
  226. stopChan := make(chan bool)
  227. grace.OnInterrupt(func() {
  228. fmt.Println("volume server has be killed")
  229. // Stop heartbeats
  230. if !volumeServer.StopHeartbeat() {
  231. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  232. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  233. }
  234. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  235. stopChan <- true
  236. })
  237. select {
  238. case <-stopChan:
  239. }
  240. }
  241. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  242. // firstly, stop the public http service to prevent from receiving new user request
  243. if nil != publicHttpDown {
  244. glog.V(0).Infof("stop public http server ... ")
  245. if err := publicHttpDown.Stop(); err != nil {
  246. glog.Warningf("stop the public http server failed, %v", err)
  247. }
  248. }
  249. glog.V(0).Infof("graceful stop cluster http server ... ")
  250. if err := clusterHttpServer.Stop(); err != nil {
  251. glog.Warningf("stop the cluster http server failed, %v", err)
  252. }
  253. glog.V(0).Infof("graceful stop gRPC ...")
  254. grpcS.GracefulStop()
  255. volumeServer.Shutdown()
  256. pprof.StopCPUProfile()
  257. }
  258. // check whether configure the public port
  259. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  260. return *v.publicPort != *v.port
  261. }
  262. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  263. grpcPort := *v.port + 10000
  264. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  265. if err != nil {
  266. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  267. }
  268. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  269. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  270. reflection.Register(grpcS)
  271. go func() {
  272. if err := grpcS.Serve(grpcL); err != nil {
  273. glog.Fatalf("start gRPC service failed, %s", err)
  274. }
  275. }()
  276. return grpcS
  277. }
  278. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  279. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  280. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  281. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  282. if e != nil {
  283. glog.Fatalf("Volume server listener error:%v", e)
  284. }
  285. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  286. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  287. go func() {
  288. if err := publicHttpDown.Wait(); err != nil {
  289. glog.Errorf("public http down wait failed, %v", err)
  290. }
  291. }()
  292. return publicHttpDown
  293. }
  294. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  295. var (
  296. certFile, keyFile string
  297. )
  298. if viper.GetString("https.volume.key") != "" {
  299. certFile = viper.GetString("https.volume.cert")
  300. keyFile = viper.GetString("https.volume.key")
  301. }
  302. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  303. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  304. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  305. if e != nil {
  306. glog.Fatalf("Volume server listener error:%v", e)
  307. }
  308. httpDown := httpdown.HTTP{
  309. KillTimeout: 5 * time.Minute,
  310. StopTimeout: 5 * time.Minute,
  311. CertFile: certFile,
  312. KeyFile: keyFile}
  313. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  314. go func() {
  315. if e := clusterHttpServer.Wait(); e != nil {
  316. glog.Fatalf("Volume server fail to serve: %v", e)
  317. }
  318. }()
  319. return clusterHttpServer
  320. }
  321. func (v VolumeServerOptions) startTcpService(volumeServer *weed_server.VolumeServer) {
  322. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port+20000)
  323. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "tcp at", listeningAddress)
  324. listener, e := util.NewListener(listeningAddress, 0)
  325. if e != nil {
  326. glog.Fatalf("Volume server listener error on %s:%v", listeningAddress, e)
  327. }
  328. defer listener.Close()
  329. for {
  330. c, err := listener.Accept()
  331. if err != nil {
  332. fmt.Println(err)
  333. return
  334. }
  335. go volumeServer.HandleTcpConnection(c)
  336. }
  337. }