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.

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