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.

310 lines
11 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
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
12 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
5 years ago
5 years ago
5 years ago
5 years ago
  1. package command
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "runtime"
  7. "runtime/pprof"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/chrislusf/seaweedfs/weed/util/grace"
  12. "github.com/spf13/viper"
  13. "google.golang.org/grpc"
  14. "github.com/chrislusf/seaweedfs/weed/pb"
  15. "github.com/chrislusf/seaweedfs/weed/security"
  16. "github.com/chrislusf/seaweedfs/weed/util/httpdown"
  17. "google.golang.org/grpc/reflection"
  18. "github.com/chrislusf/seaweedfs/weed/glog"
  19. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  20. "github.com/chrislusf/seaweedfs/weed/server"
  21. "github.com/chrislusf/seaweedfs/weed/storage"
  22. "github.com/chrislusf/seaweedfs/weed/util"
  23. )
  24. var (
  25. v VolumeServerOptions
  26. )
  27. type VolumeServerOptions struct {
  28. port *int
  29. publicPort *int
  30. folders []string
  31. folderMaxLimits []int
  32. ip *string
  33. publicUrl *string
  34. bindIp *string
  35. masters *string
  36. // pulseSeconds *int
  37. idleConnectionTimeout *int
  38. dataCenter *string
  39. rack *string
  40. whiteList []string
  41. indexType *string
  42. fixJpgOrientation *bool
  43. readRedirect *bool
  44. cpuProfile *string
  45. memProfile *string
  46. compactionMBPerSecond *int
  47. fileSizeLimitMB *int
  48. minFreeSpacePercent []float32
  49. }
  50. func init() {
  51. cmdVolume.Run = runVolume // break init cycle
  52. v.port = cmdVolume.Flag.Int("port", 8080, "http listen port")
  53. v.publicPort = cmdVolume.Flag.Int("port.public", 0, "port opened to public")
  54. v.ip = cmdVolume.Flag.String("ip", util.DetectedHostAddress(), "ip or server name")
  55. v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
  56. v.bindIp = cmdVolume.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
  57. v.masters = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
  58. // v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
  59. v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
  60. v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
  61. v.rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
  62. v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|leveldbMedium|leveldbLarge] mode for memory~performance balance.")
  63. v.fixJpgOrientation = cmdVolume.Flag.Bool("images.fix.orientation", false, "Adjust jpg orientation when uploading.")
  64. v.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
  65. v.cpuProfile = cmdVolume.Flag.String("cpuprofile", "", "cpu profile output file")
  66. v.memProfile = cmdVolume.Flag.String("memprofile", "", "memory profile output file")
  67. v.compactionMBPerSecond = cmdVolume.Flag.Int("compactionMBps", 0, "limit background compaction or copying speed in mega bytes per second")
  68. v.fileSizeLimitMB = cmdVolume.Flag.Int("fileSizeLimitMB", 256, "limit file size to avoid out of memory")
  69. }
  70. var cmdVolume = &Command{
  71. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  72. Short: "start a volume server",
  73. Long: `start a volume server to provide storage spaces
  74. `,
  75. }
  76. var (
  77. volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  78. maxVolumeCounts = cmdVolume.Flag.String("max", "7", "maximum numbers of volumes, count[,count]... If set to zero on non-windows OS, the limit will be auto configured.")
  79. volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  80. minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent ", "0", "minimum free disk space(in percents). If free disk space lower this value - all volumes marks as ReadOnly")
  81. )
  82. func runVolume(cmd *Command, args []string) bool {
  83. util.LoadConfiguration("security", false)
  84. runtime.GOMAXPROCS(runtime.NumCPU())
  85. grace.SetupProfiling(*v.cpuProfile, *v.memProfile)
  86. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, *minFreeSpacePercent)
  87. return true
  88. }
  89. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption, minFreeSpacePercent string) {
  90. // Set multiple folders and each folder's max volume count limit'
  91. v.folders = strings.Split(volumeFolders, ",")
  92. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  93. for _, maxString := range maxCountStrings {
  94. if max, e := strconv.Atoi(maxString); e == nil {
  95. v.folderMaxLimits = append(v.folderMaxLimits, max)
  96. } else {
  97. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  98. }
  99. }
  100. if len(v.folders) != len(v.folderMaxLimits) {
  101. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  102. }
  103. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  104. for _, freeString := range minFreeSpacePercentStrings {
  105. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  106. v.minFreeSpacePercent = append(v.minFreeSpacePercent, float32(value))
  107. } else {
  108. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  109. }
  110. }
  111. for _, folder := range v.folders {
  112. if err := util.TestFolderWritable(folder); err != nil {
  113. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  114. }
  115. }
  116. // security related white list configuration
  117. if volumeWhiteListOption != "" {
  118. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  119. }
  120. if *v.ip == "" {
  121. *v.ip = util.DetectedHostAddress()
  122. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  123. }
  124. if *v.publicPort == 0 {
  125. *v.publicPort = *v.port
  126. }
  127. if *v.publicUrl == "" {
  128. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  129. }
  130. volumeMux := http.NewServeMux()
  131. publicVolumeMux := volumeMux
  132. if v.isSeparatedPublicPort() {
  133. publicVolumeMux = http.NewServeMux()
  134. }
  135. volumeNeedleMapKind := storage.NeedleMapInMemory
  136. switch *v.indexType {
  137. case "leveldb":
  138. volumeNeedleMapKind = storage.NeedleMapLevelDb
  139. case "leveldbMedium":
  140. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  141. case "leveldbLarge":
  142. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  143. }
  144. masters := *v.masters
  145. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  146. *v.ip, *v.port, *v.publicUrl,
  147. v.folders, v.folderMaxLimits, v.minFreeSpacePercent,
  148. volumeNeedleMapKind,
  149. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  150. v.whiteList,
  151. *v.fixJpgOrientation, *v.readRedirect,
  152. *v.compactionMBPerSecond,
  153. *v.fileSizeLimitMB,
  154. )
  155. // starting grpc server
  156. grpcS := v.startGrpcService(volumeServer)
  157. // starting public http server
  158. var publicHttpDown httpdown.Server
  159. if v.isSeparatedPublicPort() {
  160. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  161. if nil == publicHttpDown {
  162. glog.Fatalf("start public http service failed")
  163. }
  164. }
  165. // starting the cluster http server
  166. clusterHttpServer := v.startClusterHttpService(volumeMux)
  167. stopChain := make(chan struct{})
  168. grace.OnInterrupt(func() {
  169. fmt.Println("volume server has be killed")
  170. var startTime time.Time
  171. // firstly, stop the public http service to prevent from receiving new user request
  172. if nil != publicHttpDown {
  173. startTime = time.Now()
  174. if err := publicHttpDown.Stop(); err != nil {
  175. glog.Warningf("stop the public http server failed, %v", err)
  176. }
  177. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  178. glog.V(0).Infof("stop public http server, elapsed %dms", delta)
  179. }
  180. startTime = time.Now()
  181. if err := clusterHttpServer.Stop(); err != nil {
  182. glog.Warningf("stop the cluster http server failed, %v", err)
  183. }
  184. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  185. glog.V(0).Infof("graceful stop cluster http server, elapsed [%d]", delta)
  186. startTime = time.Now()
  187. grpcS.GracefulStop()
  188. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  189. glog.V(0).Infof("graceful stop gRPC, elapsed [%d]", delta)
  190. startTime = time.Now()
  191. volumeServer.Shutdown()
  192. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  193. glog.V(0).Infof("stop volume server, elapsed [%d]", delta)
  194. pprof.StopCPUProfile()
  195. close(stopChain) // notify exit
  196. })
  197. select {
  198. case <-stopChain:
  199. }
  200. glog.Warningf("the volume server exit.")
  201. }
  202. // check whether configure the public port
  203. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  204. return *v.publicPort != *v.port
  205. }
  206. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  207. grpcPort := *v.port + 10000
  208. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  209. if err != nil {
  210. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  211. }
  212. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  213. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  214. reflection.Register(grpcS)
  215. go func() {
  216. if err := grpcS.Serve(grpcL); err != nil {
  217. glog.Fatalf("start gRPC service failed, %s", err)
  218. }
  219. }()
  220. return grpcS
  221. }
  222. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  223. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  224. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  225. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  226. if e != nil {
  227. glog.Fatalf("Volume server listener error:%v", e)
  228. }
  229. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  230. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  231. go func() {
  232. if err := publicHttpDown.Wait(); err != nil {
  233. glog.Errorf("public http down wait failed, %v", err)
  234. }
  235. }()
  236. return publicHttpDown
  237. }
  238. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  239. var (
  240. certFile, keyFile string
  241. )
  242. if viper.GetString("https.volume.key") != "" {
  243. certFile = viper.GetString("https.volume.cert")
  244. keyFile = viper.GetString("https.volume.key")
  245. }
  246. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  247. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  248. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  249. if e != nil {
  250. glog.Fatalf("Volume server listener error:%v", e)
  251. }
  252. httpDown := httpdown.HTTP{
  253. KillTimeout: 5 * time.Minute,
  254. StopTimeout: 5 * time.Minute,
  255. CertFile: certFile,
  256. KeyFile: keyFile}
  257. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  258. go func() {
  259. if e := clusterHttpServer.Wait(); e != nil {
  260. glog.Fatalf("Volume server fail to serve: %v", e)
  261. }
  262. }()
  263. return clusterHttpServer
  264. }