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.

396 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
6 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
12 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"
  9. "runtime/pprof"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/spf13/viper"
  14. "google.golang.org/grpc"
  15. "github.com/chrislusf/seaweedfs/weed/util/grace"
  16. "github.com/chrislusf/seaweedfs/weed/pb"
  17. "github.com/chrislusf/seaweedfs/weed/security"
  18. "github.com/chrislusf/seaweedfs/weed/util/httpdown"
  19. "google.golang.org/grpc/reflection"
  20. "github.com/chrislusf/seaweedfs/weed/glog"
  21. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  22. "github.com/chrislusf/seaweedfs/weed/server"
  23. stats_collect "github.com/chrislusf/seaweedfs/weed/stats"
  24. "github.com/chrislusf/seaweedfs/weed/storage"
  25. "github.com/chrislusf/seaweedfs/weed/util"
  26. )
  27. var (
  28. v VolumeServerOptions
  29. )
  30. type VolumeServerOptions struct {
  31. port *int
  32. publicPort *int
  33. folders []string
  34. folderMaxLimits []int
  35. idxFolder *string
  36. ip *string
  37. publicUrl *string
  38. bindIp *string
  39. masters *string
  40. idleConnectionTimeout *int
  41. dataCenter *string
  42. rack *string
  43. whiteList []string
  44. indexType *string
  45. diskType *string
  46. fixJpgOrientation *bool
  47. readRedirect *bool
  48. cpuProfile *string
  49. memProfile *string
  50. compactionMBPerSecond *int
  51. fileSizeLimitMB *int
  52. minFreeSpacePercents []float32
  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")
  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.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
  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.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.")
  96. )
  97. func runVolume(cmd *Command, args []string) bool {
  98. util.LoadConfiguration("security", false)
  99. runtime.GOMAXPROCS(runtime.NumCPU())
  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. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, *minFreeSpacePercent)
  107. return true
  108. }
  109. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption, minFreeSpacePercent string) {
  110. // Set multiple folders and each folder's max volume count limit'
  111. v.folders = strings.Split(volumeFolders, ",")
  112. for _, folder := range v.folders {
  113. if err := util.TestFolderWritable(util.ResolvePath(folder)); err != nil {
  114. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  115. }
  116. }
  117. // set max
  118. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  119. for _, maxString := range maxCountStrings {
  120. if max, e := strconv.Atoi(maxString); e == nil {
  121. v.folderMaxLimits = append(v.folderMaxLimits, max)
  122. } else {
  123. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  124. }
  125. }
  126. if len(v.folderMaxLimits) == 1 && len(v.folders) > 1 {
  127. for i := 0; i < len(v.folders)-1; i++ {
  128. v.folderMaxLimits = append(v.folderMaxLimits, v.folderMaxLimits[0])
  129. }
  130. }
  131. if len(v.folders) != len(v.folderMaxLimits) {
  132. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  133. }
  134. // set minFreeSpacePercent
  135. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  136. for _, freeString := range minFreeSpacePercentStrings {
  137. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  138. v.minFreeSpacePercents = append(v.minFreeSpacePercents, float32(value))
  139. } else {
  140. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  141. }
  142. }
  143. if len(v.minFreeSpacePercents) == 1 && len(v.folders) > 1 {
  144. for i := 0; i < len(v.folders)-1; i++ {
  145. v.minFreeSpacePercents = append(v.minFreeSpacePercents, v.minFreeSpacePercents[0])
  146. }
  147. }
  148. if len(v.folders) != len(v.minFreeSpacePercents) {
  149. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(v.minFreeSpacePercents))
  150. }
  151. // set disk types
  152. var diskTypes []types.DiskType
  153. diskTypeStrings := strings.Split(*v.diskType, ",")
  154. for _, diskTypeString := range diskTypeStrings {
  155. diskTypes = append(diskTypes, types.ToDiskType(diskTypeString))
  156. }
  157. if len(diskTypes) == 1 && len(v.folders) > 1 {
  158. for i := 0; i < len(v.folders)-1; i++ {
  159. diskTypes = append(diskTypes, diskTypes[0])
  160. }
  161. }
  162. if len(v.folders) != len(diskTypes) {
  163. glog.Fatalf("%d directories by -dir, but only %d disk types is set by -disk", len(v.folders), len(diskTypes))
  164. }
  165. // security related white list configuration
  166. if volumeWhiteListOption != "" {
  167. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  168. }
  169. if *v.ip == "" {
  170. *v.ip = util.DetectedHostAddress()
  171. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  172. }
  173. if *v.publicPort == 0 {
  174. *v.publicPort = *v.port
  175. }
  176. if *v.publicUrl == "" {
  177. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  178. }
  179. volumeMux := http.NewServeMux()
  180. publicVolumeMux := volumeMux
  181. if v.isSeparatedPublicPort() {
  182. publicVolumeMux = http.NewServeMux()
  183. }
  184. if *v.pprof {
  185. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  186. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  187. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  188. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  189. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  190. }
  191. volumeNeedleMapKind := storage.NeedleMapInMemory
  192. switch *v.indexType {
  193. case "leveldb":
  194. volumeNeedleMapKind = storage.NeedleMapLevelDb
  195. case "leveldbMedium":
  196. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  197. case "leveldbLarge":
  198. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  199. }
  200. masters := *v.masters
  201. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  202. *v.ip, *v.port, *v.publicUrl,
  203. v.folders, v.folderMaxLimits, v.minFreeSpacePercents, diskTypes,
  204. *v.idxFolder,
  205. volumeNeedleMapKind,
  206. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  207. v.whiteList,
  208. *v.fixJpgOrientation, *v.readRedirect,
  209. *v.compactionMBPerSecond,
  210. *v.fileSizeLimitMB,
  211. )
  212. // starting grpc server
  213. grpcS := v.startGrpcService(volumeServer)
  214. // starting public http server
  215. var publicHttpDown httpdown.Server
  216. if v.isSeparatedPublicPort() {
  217. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  218. if nil == publicHttpDown {
  219. glog.Fatalf("start public http service failed")
  220. }
  221. }
  222. // starting tcp server
  223. if *v.enableTcp {
  224. go v.startTcpService(volumeServer)
  225. }
  226. // starting the cluster http server
  227. clusterHttpServer := v.startClusterHttpService(volumeMux)
  228. stopChan := make(chan bool)
  229. grace.OnInterrupt(func() {
  230. fmt.Println("volume server has be killed")
  231. // Stop heartbeats
  232. if !volumeServer.StopHeartbeat() {
  233. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  234. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  235. }
  236. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  237. stopChan <- true
  238. })
  239. select {
  240. case <-stopChan:
  241. }
  242. }
  243. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  244. // firstly, stop the public http service to prevent from receiving new user request
  245. if nil != publicHttpDown {
  246. glog.V(0).Infof("stop public http server ... ")
  247. if err := publicHttpDown.Stop(); err != nil {
  248. glog.Warningf("stop the public http server failed, %v", err)
  249. }
  250. }
  251. glog.V(0).Infof("graceful stop cluster http server ... ")
  252. if err := clusterHttpServer.Stop(); err != nil {
  253. glog.Warningf("stop the cluster http server failed, %v", err)
  254. }
  255. glog.V(0).Infof("graceful stop gRPC ...")
  256. grpcS.GracefulStop()
  257. volumeServer.Shutdown()
  258. pprof.StopCPUProfile()
  259. }
  260. // check whether configure the public port
  261. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  262. return *v.publicPort != *v.port
  263. }
  264. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  265. grpcPort := *v.port + 10000
  266. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  267. if err != nil {
  268. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  269. }
  270. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  271. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  272. reflection.Register(grpcS)
  273. go func() {
  274. if err := grpcS.Serve(grpcL); err != nil {
  275. glog.Fatalf("start gRPC service failed, %s", err)
  276. }
  277. }()
  278. return grpcS
  279. }
  280. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  281. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  282. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  283. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  284. if e != nil {
  285. glog.Fatalf("Volume server listener error:%v", e)
  286. }
  287. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  288. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  289. go func() {
  290. if err := publicHttpDown.Wait(); err != nil {
  291. glog.Errorf("public http down wait failed, %v", err)
  292. }
  293. }()
  294. return publicHttpDown
  295. }
  296. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  297. var (
  298. certFile, keyFile string
  299. )
  300. if viper.GetString("https.volume.key") != "" {
  301. certFile = viper.GetString("https.volume.cert")
  302. keyFile = viper.GetString("https.volume.key")
  303. }
  304. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  305. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  306. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  307. if e != nil {
  308. glog.Fatalf("Volume server listener error:%v", e)
  309. }
  310. httpDown := httpdown.HTTP{
  311. KillTimeout: 5 * time.Minute,
  312. StopTimeout: 5 * time.Minute,
  313. CertFile: certFile,
  314. KeyFile: keyFile}
  315. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  316. go func() {
  317. if e := clusterHttpServer.Wait(); e != nil {
  318. glog.Fatalf("Volume server fail to serve: %v", e)
  319. }
  320. }()
  321. return clusterHttpServer
  322. }
  323. func (v VolumeServerOptions) startTcpService(volumeServer *weed_server.VolumeServer) {
  324. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port+20000)
  325. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "tcp at", listeningAddress)
  326. listener, e := util.NewListener(listeningAddress, 0)
  327. if e != nil {
  328. glog.Fatalf("Volume server listener error on %s:%v", listeningAddress, e)
  329. }
  330. defer listener.Close()
  331. for {
  332. c, err := listener.Accept()
  333. if err != nil {
  334. fmt.Println(err)
  335. return
  336. }
  337. go volumeServer.HandleTcpConnection(c)
  338. }
  339. }