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.

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