volume.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. enableTcp *bool // temporary toggle
  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. v.enableTcp = cmdVolume.Flag.Bool("enableTcp", false, "[experimental] toggle tcp port, running on 20000 + port")
  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]...")
  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. util.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 = "127.0.0.1"
  112. }
  113. if *v.publicPort == 0 {
  114. *v.publicPort = *v.port
  115. }
  116. if *v.publicUrl == "" {
  117. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  118. }
  119. volumeMux := http.NewServeMux()
  120. publicVolumeMux := volumeMux
  121. if v.isSeparatedPublicPort() {
  122. publicVolumeMux = http.NewServeMux()
  123. }
  124. volumeNeedleMapKind := storage.NeedleMapInMemory
  125. switch *v.indexType {
  126. case "leveldb":
  127. volumeNeedleMapKind = storage.NeedleMapLevelDb
  128. case "leveldbMedium":
  129. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  130. case "leveldbLarge":
  131. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  132. }
  133. masters := *v.masters
  134. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  135. *v.ip, *v.port, *v.publicUrl,
  136. v.folders, v.folderMaxLimits,
  137. volumeNeedleMapKind,
  138. strings.Split(masters, ","), *v.pulseSeconds, *v.dataCenter, *v.rack,
  139. v.whiteList,
  140. *v.fixJpgOrientation, *v.readRedirect,
  141. *v.compactionMBPerSecond,
  142. *v.fileSizeLimitMB,
  143. )
  144. // starting grpc server
  145. grpcS := v.startGrpcService(volumeServer)
  146. if v.enableTcp != nil && *v.enableTcp {
  147. go v.startTcpServer(volumeServer)
  148. }
  149. // starting public http server
  150. var publicHttpDown httpdown.Server
  151. if v.isSeparatedPublicPort() {
  152. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  153. if nil == publicHttpDown {
  154. glog.Fatalf("start public http service failed")
  155. }
  156. }
  157. // starting the cluster http server
  158. clusterHttpServer := v.startClusterHttpService(volumeMux)
  159. stopChain := make(chan struct{})
  160. util.OnInterrupt(func() {
  161. fmt.Println("volume server has be killed")
  162. var startTime time.Time
  163. // firstly, stop the public http service to prevent from receiving new user request
  164. if nil != publicHttpDown {
  165. startTime = time.Now()
  166. if err := publicHttpDown.Stop(); err != nil {
  167. glog.Warningf("stop the public http server failed, %v", err)
  168. }
  169. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  170. glog.V(0).Infof("stop public http server, elapsed %dms", delta)
  171. }
  172. startTime = time.Now()
  173. if err := clusterHttpServer.Stop(); err != nil {
  174. glog.Warningf("stop the cluster http server failed, %v", err)
  175. }
  176. delta := time.Now().Sub(startTime).Nanoseconds() / 1e6
  177. glog.V(0).Infof("graceful stop cluster http server, elapsed [%d]", delta)
  178. startTime = time.Now()
  179. grpcS.GracefulStop()
  180. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  181. glog.V(0).Infof("graceful stop gRPC, elapsed [%d]", delta)
  182. startTime = time.Now()
  183. volumeServer.Shutdown()
  184. delta = time.Now().Sub(startTime).Nanoseconds() / 1e6
  185. glog.V(0).Infof("stop volume server, elapsed [%d]", delta)
  186. pprof.StopCPUProfile()
  187. close(stopChain) // notify exit
  188. })
  189. select {
  190. case <-stopChain:
  191. }
  192. glog.Warningf("the volume server exit.")
  193. }
  194. // check whether configure the public port
  195. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  196. return *v.publicPort != *v.port
  197. }
  198. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  199. grpcPort := *v.port + 10000
  200. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  201. if err != nil {
  202. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  203. }
  204. grpcS := util.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  205. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  206. reflection.Register(grpcS)
  207. go func() {
  208. if err := grpcS.Serve(grpcL); err != nil {
  209. glog.Fatalf("start gRPC service failed, %s", err)
  210. }
  211. }()
  212. return grpcS
  213. }
  214. func (v VolumeServerOptions) startTcpServer(vs *weed_server.VolumeServer) {
  215. tcpPort := *v.port + 20000
  216. tcpL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(tcpPort), 0)
  217. if err != nil {
  218. glog.Fatalf("failed to listen on tcp port %d: %v", tcpPort, err)
  219. }
  220. defer tcpL.Close()
  221. for {
  222. c, err := tcpL.Accept()
  223. if err != nil {
  224. glog.V(0).Infof("accept tcp connection: %v", err)
  225. continue
  226. }
  227. go func() {
  228. if err := vs.HandleTcpConnection(c); err != nil {
  229. glog.V(0).Infof("handle tcp remote %s: %v", c.RemoteAddr(), err)
  230. return
  231. }
  232. }()
  233. }
  234. }
  235. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  236. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  237. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "public at", publicListeningAddress)
  238. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  239. if e != nil {
  240. glog.Fatalf("Volume server listener error:%v", e)
  241. }
  242. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  243. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  244. go func() {
  245. if err := publicHttpDown.Wait(); err != nil {
  246. glog.Errorf("public http down wait failed, %v", err)
  247. }
  248. }()
  249. return publicHttpDown
  250. }
  251. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  252. var (
  253. certFile, keyFile string
  254. )
  255. if viper.GetString("https.volume.key") != "" {
  256. certFile = viper.GetString("https.volume.cert")
  257. keyFile = viper.GetString("https.volume.key")
  258. }
  259. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  260. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.VERSION, listeningAddress)
  261. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  262. if e != nil {
  263. glog.Fatalf("Volume server listener error:%v", e)
  264. }
  265. httpDown := httpdown.HTTP{
  266. KillTimeout: 5 * time.Minute,
  267. StopTimeout: 5 * time.Minute,
  268. CertFile: certFile,
  269. KeyFile: keyFile}
  270. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  271. go func() {
  272. if e := clusterHttpServer.Wait(); e != nil {
  273. glog.Fatalf("Volume server fail to serve: %v", e)
  274. }
  275. }()
  276. return clusterHttpServer
  277. }