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.

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