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.

295 lines
9.8 KiB

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