volume.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package command
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/storage/types"
  5. "github.com/chrislusf/seaweedfs/weed/wdclient/penet"
  6. "net"
  7. "net/http"
  8. httppprof "net/http/pprof"
  9. "os"
  10. "runtime"
  11. "runtime/pprof"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/spf13/viper"
  16. "google.golang.org/grpc"
  17. "github.com/chrislusf/seaweedfs/weed/util/grace"
  18. "github.com/chrislusf/seaweedfs/weed/pb"
  19. "github.com/chrislusf/seaweedfs/weed/security"
  20. "github.com/chrislusf/seaweedfs/weed/util/httpdown"
  21. "google.golang.org/grpc/reflection"
  22. "github.com/chrislusf/seaweedfs/weed/glog"
  23. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  24. "github.com/chrislusf/seaweedfs/weed/server"
  25. stats_collect "github.com/chrislusf/seaweedfs/weed/stats"
  26. "github.com/chrislusf/seaweedfs/weed/storage"
  27. "github.com/chrislusf/seaweedfs/weed/util"
  28. )
  29. var (
  30. v VolumeServerOptions
  31. )
  32. type VolumeServerOptions struct {
  33. port *int
  34. publicPort *int
  35. folders []string
  36. folderMaxLimits []int
  37. idxFolder *string
  38. ip *string
  39. publicUrl *string
  40. bindIp *string
  41. masters *string
  42. idleConnectionTimeout *int
  43. dataCenter *string
  44. rack *string
  45. whiteList []string
  46. indexType *string
  47. diskType *string
  48. fixJpgOrientation *bool
  49. readRedirect *bool
  50. cpuProfile *string
  51. memProfile *string
  52. compactionMBPerSecond *int
  53. fileSizeLimitMB *int
  54. minFreeSpacePercents []float32
  55. pprof *bool
  56. preStopSeconds *int
  57. metricsHttpPort *int
  58. // pulseSeconds *int
  59. enableTcp *bool
  60. }
  61. func init() {
  62. cmdVolume.Run = runVolume // break init cycle
  63. v.port = cmdVolume.Flag.Int("port", 8080, "http listen port")
  64. v.publicPort = cmdVolume.Flag.Int("port.public", 0, "port opened to public")
  65. v.ip = cmdVolume.Flag.String("ip", util.DetectedHostAddress(), "ip or server name")
  66. v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
  67. v.bindIp = cmdVolume.Flag.String("ip.bind", "", "ip address to bind to")
  68. v.masters = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
  69. v.preStopSeconds = cmdVolume.Flag.Int("preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
  70. // v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
  71. v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
  72. v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
  73. v.rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
  74. v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|leveldbMedium|leveldbLarge] mode for memory~performance balance.")
  75. v.diskType = cmdVolume.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  76. v.fixJpgOrientation = cmdVolume.Flag.Bool("images.fix.orientation", false, "Adjust jpg orientation when uploading.")
  77. v.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
  78. v.cpuProfile = cmdVolume.Flag.String("cpuprofile", "", "cpu profile output file")
  79. v.memProfile = cmdVolume.Flag.String("memprofile", "", "memory profile output file")
  80. v.compactionMBPerSecond = cmdVolume.Flag.Int("compactionMBps", 0, "limit background compaction or copying speed in mega bytes per second")
  81. v.fileSizeLimitMB = cmdVolume.Flag.Int("fileSizeLimitMB", 256, "limit file size to avoid out of memory")
  82. v.pprof = cmdVolume.Flag.Bool("pprof", false, "enable pprof http handlers. precludes --memprofile and --cpuprofile")
  83. v.metricsHttpPort = cmdVolume.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  84. v.idxFolder = cmdVolume.Flag.String("dir.idx", "", "directory to store .idx files")
  85. v.enableTcp = cmdVolume.Flag.Bool("tcp", false, "<exprimental> enable tcp port")
  86. }
  87. var cmdVolume = &Command{
  88. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  89. Short: "start a volume server",
  90. Long: `start a volume server to provide storage spaces
  91. `,
  92. }
  93. var (
  94. volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  95. maxVolumeCounts = cmdVolume.Flag.String("max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured.")
  96. volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  97. minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly.")
  98. )
  99. func runVolume(cmd *Command, args []string) bool {
  100. util.LoadConfiguration("security", false)
  101. runtime.GOMAXPROCS(runtime.NumCPU())
  102. // If --pprof is set we assume the caller wants to be able to collect
  103. // cpu and memory profiles via go tool pprof
  104. if !*v.pprof {
  105. grace.SetupProfiling(*v.cpuProfile, *v.memProfile)
  106. }
  107. go stats_collect.StartMetricsServer(*v.metricsHttpPort)
  108. v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, *minFreeSpacePercent)
  109. return true
  110. }
  111. func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption, minFreeSpacePercent string) {
  112. // Set multiple folders and each folder's max volume count limit'
  113. v.folders = strings.Split(volumeFolders, ",")
  114. for _, folder := range v.folders {
  115. if err := util.TestFolderWritable(util.ResolvePath(folder)); err != nil {
  116. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  117. }
  118. }
  119. // set max
  120. maxCountStrings := strings.Split(maxVolumeCounts, ",")
  121. for _, maxString := range maxCountStrings {
  122. if max, e := strconv.Atoi(maxString); e == nil {
  123. v.folderMaxLimits = append(v.folderMaxLimits, max)
  124. } else {
  125. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  126. }
  127. }
  128. if len(v.folderMaxLimits) == 1 && len(v.folders) > 1 {
  129. for i := 0; i < len(v.folders)-1; i++ {
  130. v.folderMaxLimits = append(v.folderMaxLimits, v.folderMaxLimits[0])
  131. }
  132. }
  133. if len(v.folders) != len(v.folderMaxLimits) {
  134. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(v.folders), len(v.folderMaxLimits))
  135. }
  136. // set minFreeSpacePercent
  137. minFreeSpacePercentStrings := strings.Split(minFreeSpacePercent, ",")
  138. for _, freeString := range minFreeSpacePercentStrings {
  139. if value, e := strconv.ParseFloat(freeString, 32); e == nil {
  140. v.minFreeSpacePercents = append(v.minFreeSpacePercents, float32(value))
  141. } else {
  142. glog.Fatalf("The value specified in -minFreeSpacePercent not a valid value %s", freeString)
  143. }
  144. }
  145. if len(v.minFreeSpacePercents) == 1 && len(v.folders) > 1 {
  146. for i := 0; i < len(v.folders)-1; i++ {
  147. v.minFreeSpacePercents = append(v.minFreeSpacePercents, v.minFreeSpacePercents[0])
  148. }
  149. }
  150. if len(v.folders) != len(v.minFreeSpacePercents) {
  151. glog.Fatalf("%d directories by -dir, but only %d minFreeSpacePercent is set by -minFreeSpacePercent", len(v.folders), len(v.minFreeSpacePercents))
  152. }
  153. // set disk types
  154. var diskTypes []types.DiskType
  155. diskTypeStrings := strings.Split(*v.diskType, ",")
  156. for _, diskTypeString := range diskTypeStrings {
  157. diskTypes = append(diskTypes, types.ToDiskType(diskTypeString))
  158. }
  159. if len(diskTypes) == 1 && len(v.folders) > 1 {
  160. for i := 0; i < len(v.folders)-1; i++ {
  161. diskTypes = append(diskTypes, diskTypes[0])
  162. }
  163. }
  164. if len(v.folders) != len(diskTypes) {
  165. glog.Fatalf("%d directories by -dir, but only %d disk types is set by -disk", len(v.folders), len(diskTypes))
  166. }
  167. // security related white list configuration
  168. if volumeWhiteListOption != "" {
  169. v.whiteList = strings.Split(volumeWhiteListOption, ",")
  170. }
  171. if *v.ip == "" {
  172. *v.ip = util.DetectedHostAddress()
  173. glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
  174. }
  175. if *v.publicPort == 0 {
  176. *v.publicPort = *v.port
  177. }
  178. if *v.publicUrl == "" {
  179. *v.publicUrl = *v.ip + ":" + strconv.Itoa(*v.publicPort)
  180. }
  181. volumeMux := http.NewServeMux()
  182. publicVolumeMux := volumeMux
  183. if v.isSeparatedPublicPort() {
  184. publicVolumeMux = http.NewServeMux()
  185. }
  186. if *v.pprof {
  187. volumeMux.HandleFunc("/debug/pprof/", httppprof.Index)
  188. volumeMux.HandleFunc("/debug/pprof/cmdline", httppprof.Cmdline)
  189. volumeMux.HandleFunc("/debug/pprof/profile", httppprof.Profile)
  190. volumeMux.HandleFunc("/debug/pprof/symbol", httppprof.Symbol)
  191. volumeMux.HandleFunc("/debug/pprof/trace", httppprof.Trace)
  192. }
  193. volumeNeedleMapKind := storage.NeedleMapInMemory
  194. switch *v.indexType {
  195. case "leveldb":
  196. volumeNeedleMapKind = storage.NeedleMapLevelDb
  197. case "leveldbMedium":
  198. volumeNeedleMapKind = storage.NeedleMapLevelDbMedium
  199. case "leveldbLarge":
  200. volumeNeedleMapKind = storage.NeedleMapLevelDbLarge
  201. }
  202. masters := *v.masters
  203. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  204. *v.ip, *v.port, *v.publicUrl,
  205. v.folders, v.folderMaxLimits, v.minFreeSpacePercents, diskTypes,
  206. *v.idxFolder,
  207. volumeNeedleMapKind,
  208. strings.Split(masters, ","), 5, *v.dataCenter, *v.rack,
  209. v.whiteList,
  210. *v.fixJpgOrientation, *v.readRedirect,
  211. *v.compactionMBPerSecond,
  212. *v.fileSizeLimitMB,
  213. )
  214. // starting grpc server
  215. grpcS := v.startGrpcService(volumeServer)
  216. // starting public http server
  217. var publicHttpDown httpdown.Server
  218. if v.isSeparatedPublicPort() {
  219. publicHttpDown = v.startPublicHttpService(publicVolumeMux)
  220. if nil == publicHttpDown {
  221. glog.Fatalf("start public http service failed")
  222. }
  223. }
  224. // starting tcp server
  225. if *v.enableTcp {
  226. go v.startTcpService(volumeServer)
  227. go v.startUdpService(volumeServer)
  228. }
  229. // starting the cluster http server
  230. clusterHttpServer := v.startClusterHttpService(volumeMux)
  231. stopChan := make(chan bool)
  232. grace.OnInterrupt(func() {
  233. fmt.Println("volume server has be killed")
  234. // Stop heartbeats
  235. if !volumeServer.StopHeartbeat() {
  236. glog.V(0).Infof("stop send heartbeat and wait %d seconds until shutdown ...", *v.preStopSeconds)
  237. time.Sleep(time.Duration(*v.preStopSeconds) * time.Second)
  238. }
  239. shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
  240. stopChan <- true
  241. })
  242. select {
  243. case <-stopChan:
  244. }
  245. }
  246. func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server, grpcS *grpc.Server, volumeServer *weed_server.VolumeServer) {
  247. // firstly, stop the public http service to prevent from receiving new user request
  248. if nil != publicHttpDown {
  249. glog.V(0).Infof("stop public http server ... ")
  250. if err := publicHttpDown.Stop(); err != nil {
  251. glog.Warningf("stop the public http server failed, %v", err)
  252. }
  253. }
  254. glog.V(0).Infof("graceful stop cluster http server ... ")
  255. if err := clusterHttpServer.Stop(); err != nil {
  256. glog.Warningf("stop the cluster http server failed, %v", err)
  257. }
  258. glog.V(0).Infof("graceful stop gRPC ...")
  259. grpcS.GracefulStop()
  260. volumeServer.Shutdown()
  261. pprof.StopCPUProfile()
  262. }
  263. // check whether configure the public port
  264. func (v VolumeServerOptions) isSeparatedPublicPort() bool {
  265. return *v.publicPort != *v.port
  266. }
  267. func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
  268. grpcPort := *v.port + 10000
  269. grpcL, err := util.NewListener(*v.bindIp+":"+strconv.Itoa(grpcPort), 0)
  270. if err != nil {
  271. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  272. }
  273. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.volume"))
  274. volume_server_pb.RegisterVolumeServerServer(grpcS, vs)
  275. reflection.Register(grpcS)
  276. go func() {
  277. if err := grpcS.Serve(grpcL); err != nil {
  278. glog.Fatalf("start gRPC service failed, %s", err)
  279. }
  280. }()
  281. return grpcS
  282. }
  283. func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
  284. publicListeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.publicPort)
  285. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "public at", publicListeningAddress)
  286. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  287. if e != nil {
  288. glog.Fatalf("Volume server listener error:%v", e)
  289. }
  290. pubHttp := httpdown.HTTP{StopTimeout: 5 * time.Minute, KillTimeout: 5 * time.Minute}
  291. publicHttpDown := pubHttp.Serve(&http.Server{Handler: handler}, publicListener)
  292. go func() {
  293. if err := publicHttpDown.Wait(); err != nil {
  294. glog.Errorf("public http down wait failed, %v", err)
  295. }
  296. }()
  297. return publicHttpDown
  298. }
  299. func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
  300. var (
  301. certFile, keyFile string
  302. )
  303. if viper.GetString("https.volume.key") != "" {
  304. certFile = viper.GetString("https.volume.cert")
  305. keyFile = viper.GetString("https.volume.key")
  306. }
  307. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port)
  308. glog.V(0).Infof("Start Seaweed volume server %s at %s", util.Version(), listeningAddress)
  309. listener, e := util.NewListener(listeningAddress, time.Duration(*v.idleConnectionTimeout)*time.Second)
  310. if e != nil {
  311. glog.Fatalf("Volume server listener error:%v", e)
  312. }
  313. httpDown := httpdown.HTTP{
  314. KillTimeout: 5 * time.Minute,
  315. StopTimeout: 5 * time.Minute,
  316. CertFile: certFile,
  317. KeyFile: keyFile}
  318. clusterHttpServer := httpDown.Serve(&http.Server{Handler: handler}, listener)
  319. go func() {
  320. if e := clusterHttpServer.Wait(); e != nil {
  321. glog.Fatalf("Volume server fail to serve: %v", e)
  322. }
  323. }()
  324. return clusterHttpServer
  325. }
  326. func (v VolumeServerOptions) startTcpService(volumeServer *weed_server.VolumeServer) {
  327. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port+20000)
  328. glog.V(0).Infoln("Start Seaweed volume server", util.Version(), "TCP at", listeningAddress)
  329. listener, e := util.NewListener(listeningAddress, 0)
  330. if e != nil {
  331. glog.Fatalf("Volume server TCP on %s:%v", listeningAddress, e)
  332. }
  333. defer listener.Close()
  334. for {
  335. c, err := listener.Accept()
  336. if err != nil {
  337. fmt.Println(err)
  338. return
  339. }
  340. go volumeServer.HandleTcpConnection(c)
  341. }
  342. }
  343. func (v VolumeServerOptions) startUdpService(volumeServer *weed_server.VolumeServer) {
  344. listeningAddress := *v.bindIp + ":" + strconv.Itoa(*v.port+20001)
  345. listener, err := penet.Listen("", listeningAddress)
  346. if err != nil {
  347. glog.Fatalf("Volume server listen on %s:%v", listeningAddress, err)
  348. }
  349. defer listener.Close()
  350. for {
  351. conn, err := listener.Accept()
  352. if err == nil {
  353. go volumeServer.HandleUdpConnection(conn)
  354. } else if isTemporaryError(err) {
  355. continue
  356. } else {
  357. break
  358. }
  359. }
  360. }
  361. func isTemporaryError(err error) bool {
  362. if err != nil {
  363. if ne, y := err.(net.Error); y {
  364. return ne.Temporary()
  365. }
  366. }
  367. return false
  368. }