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.

290 lines
9.6 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
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/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. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  162. glog.V(0).Infof("stop public http server, elapsed %dms", delta)
  163. }
  164. startTime = time.Now()
  165. if err := clusterHttpServer.Stop(); err != nil {
  166. glog.Warningf("stop the cluster http server failed, %v", err)
  167. }
  168. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  169. glog.V(0).Infof("graceful stop cluster http server, elapsed [%d]", delta)
  170. startTime = time.Now()
  171. grpcS.GracefulStop()
  172. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  173. glog.V(0).Infof("graceful stop gRPC, elapsed [%d]", delta)
  174. startTime = time.Now()
  175. volumeServer.Shutdown()
  176. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  177. glog.V(0).Infof("stop volume server, elapsed [%d]", delta)
  178. pprof.StopCPUProfile()
  179. close(stopChain) // notify exit
  180. })
  181. select {
  182. case <-stopChain:
  183. }
  184. glog.Warningf("the volume server exit.")
  185. }
  186. // check whether configure the public port
  187. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  188. return *v.publicPort != *v.port
  189. }
  190. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  191. grpcPort := *v.port + 10000
  192. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  193. if err != nil {
  194. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  195. }
  196. grpcS := util.NewGrpcServer(security.LoadServerTLS(viper.Sub("grpc"), "volume"))
  197. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  198. reflection.Register(grpcS)
  199. go func() {
  200. if err := grpcS.Serve(grpcL); err != nil {
  201. glog.Fatalf("start gRPC service failed, %s", err)
  202. }
  203. }()
  204. return grpcS
  205. }
  206. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  207. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  208. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "public at", publicListeningAddress)
  209. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  210. if e != nil {
  211. glog.Fatalf("Volume server listener error:%v", e)
  212. }
  213. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  214. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  215. go func() {
  216. if err := publicHttpDown.Wait(); err != nil {
  217. glog.Errorf("public http down wait failed, %v", err)
  218. }
  219. }()
  220. return publicHttpDown
  221. }
  222. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  223. var (
  224. certFile, keyFile string
  225. )
  226. if viper.GetString("https.volume.key") != "" {
  227. certFile = viper.GetString("https.volume.cert")
  228. keyFile = viper.GetString("https.volume.key")
  229. }
  230. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  231. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.VERSION, listeningAddress)
  232. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  233. if e != nil {
  234. glog.Fatalf("Volume server listener error:%v", e)
  235. }
  236. httpDown := httpdown.HTTP{
  237. KillTimeout: 5 * time.Minute,
  238. StopTimeout: 5 * time.Minute,
  239. CertFile: certFile,
  240. KeyFile: keyFile}
  241. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  242. go func() {
  243. if e := clusterHttpServer.Wait(); e != nil {
  244. glog.Fatalf("Volume server fail to serve: %v", e)
  245. }
  246. }()
  247. return clusterHttpServer
  248. }