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.

298 lines
10 KiB

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