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.

288 lines
11 KiB

11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. package command
  2. import (
  3. "net/http"
  4. "os"
  5. "runtime"
  6. "runtime/pprof"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  13. "github.com/chrislusf/seaweedfs/weed/server"
  14. "github.com/chrislusf/seaweedfs/weed/storage"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. "github.com/gorilla/mux"
  17. "github.com/soheilhy/cmux"
  18. "google.golang.org/grpc/reflection"
  19. )
  20. type ServerOptions struct {
  21. cpuprofile *string
  22. }
  23. var (
  24. serverOptions ServerOptions
  25. filerOptions FilerOptions
  26. )
  27. func init() {
  28. cmdServer.Run = runServer // break init cycle
  29. }
  30. var cmdServer = &Command{
  31. UsageLine: "server -port=8080 -dir=/tmp -volume.max=5 -ip=server_name",
  32. Short: "start a server, including volume server, and automatically elect a master server",
  33. Long: `start both a volume server to provide storage spaces
  34. and a master server to provide volume=>location mapping service and sequence number of file ids
  35. This is provided as a convenient way to start both volume server and master server.
  36. The servers are exactly the same as starting them separately.
  37. So other volume servers can use this embedded master server also.
  38. Optionally, one filer server can be started. Logically, filer servers should not be in a cluster.
  39. They run with meta data on disk, not shared. So each filer server is different.
  40. `,
  41. }
  42. var (
  43. serverIp = cmdServer.Flag.String("ip", "localhost", "ip or server name")
  44. serverBindIp = cmdServer.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
  45. serverMaxCpu = cmdServer.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
  46. serverTimeout = cmdServer.Flag.Int("idleTimeout", 30, "connection idle seconds")
  47. serverDataCenter = cmdServer.Flag.String("dataCenter", "", "current volume server's data center name")
  48. serverRack = cmdServer.Flag.String("rack", "", "current volume server's rack name")
  49. serverWhiteListOption = cmdServer.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  50. serverPeers = cmdServer.Flag.String("master.peers", "", "all master nodes in comma separated ip:masterPort list")
  51. serverSecureKey = cmdServer.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
  52. serverGarbageThreshold = cmdServer.Flag.String("garbageThreshold", "0.3", "threshold to vacuum and reclaim spaces")
  53. masterPort = cmdServer.Flag.Int("master.port", 9333, "master server http listen port")
  54. masterMetaFolder = cmdServer.Flag.String("master.dir", "", "data directory to store meta data, default to same as -dir specified")
  55. masterVolumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
  56. masterVolumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
  57. masterDefaultReplicaPlacement = cmdServer.Flag.String("master.defaultReplicaPlacement", "000", "Default replication type if not specified.")
  58. volumePort = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
  59. volumePublicPort = cmdServer.Flag.Int("volume.port.public", 0, "volume server public port")
  60. volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  61. volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "7", "maximum numbers of volumes, count[,count]...")
  62. volumePulse = cmdServer.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
  63. volumeIndexType = cmdServer.Flag.String("volume.index", "memory", "Choose [memory|leveldb|boltdb|btree] mode for memory~performance balance.")
  64. volumeFixJpgOrientation = cmdServer.Flag.Bool("volume.images.fix.orientation", true, "Adjust jpg orientation when uploading.")
  65. volumeReadRedirect = cmdServer.Flag.Bool("volume.read.redirect", true, "Redirect moved or non-local volumes.")
  66. volumeServerPublicUrl = cmdServer.Flag.String("volume.publicUrl", "", "publicly accessible address")
  67. isStartingFiler = cmdServer.Flag.Bool("filer", false, "whether to start filer")
  68. serverWhiteList []string
  69. )
  70. func init() {
  71. serverOptions.cpuprofile = cmdServer.Flag.String("cpuprofile", "", "cpu profile output file")
  72. filerOptions.collection = cmdServer.Flag.String("filer.collection", "", "all data will be stored in this collection")
  73. filerOptions.port = cmdServer.Flag.Int("filer.port", 8888, "filer server http listen port")
  74. filerOptions.grpcPort = cmdServer.Flag.Int("filer.port.grpc", 0, "filer grpc server listen port, default to http port + 10000")
  75. filerOptions.publicPort = cmdServer.Flag.Int("filer.port.public", 0, "filer server public http listen port")
  76. filerOptions.defaultReplicaPlacement = cmdServer.Flag.String("filer.defaultReplicaPlacement", "", "Default replication type if not specified during runtime.")
  77. filerOptions.redirectOnRead = cmdServer.Flag.Bool("filer.redirectOnRead", false, "whether proxy or redirect to volume server during file GET request")
  78. filerOptions.disableDirListing = cmdServer.Flag.Bool("filer.disableDirListing", false, "turn off directory listing")
  79. filerOptions.maxMB = cmdServer.Flag.Int("filer.maxMB", 32, "split files larger than the limit")
  80. filerOptions.dirListingLimit = cmdServer.Flag.Int("filer.dirListLimit", 1000, "limit sub dir listing size")
  81. }
  82. func runServer(cmd *Command, args []string) bool {
  83. filerOptions.secretKey = serverSecureKey
  84. if *serverOptions.cpuprofile != "" {
  85. f, err := os.Create(*serverOptions.cpuprofile)
  86. if err != nil {
  87. glog.Fatal(err)
  88. }
  89. pprof.StartCPUProfile(f)
  90. defer pprof.StopCPUProfile()
  91. }
  92. if *filerOptions.redirectOnRead {
  93. *isStartingFiler = true
  94. }
  95. master := *serverIp + ":" + strconv.Itoa(*masterPort)
  96. filerOptions.ip = serverIp
  97. filerOptions.dataCenter = serverDataCenter
  98. if *filerOptions.defaultReplicaPlacement == "" {
  99. *filerOptions.defaultReplicaPlacement = *masterDefaultReplicaPlacement
  100. }
  101. if *volumePublicPort == 0 {
  102. *volumePublicPort = *volumePort
  103. }
  104. if *serverMaxCpu < 1 {
  105. *serverMaxCpu = runtime.NumCPU()
  106. }
  107. runtime.GOMAXPROCS(*serverMaxCpu)
  108. folders := strings.Split(*volumeDataFolders, ",")
  109. maxCountStrings := strings.Split(*volumeMaxDataVolumeCounts, ",")
  110. var maxCounts []int
  111. for _, maxString := range maxCountStrings {
  112. if max, e := strconv.Atoi(maxString); e == nil {
  113. maxCounts = append(maxCounts, max)
  114. } else {
  115. glog.Fatalf("The max specified in -max not a valid number %s", maxString)
  116. }
  117. }
  118. if len(folders) != len(maxCounts) {
  119. glog.Fatalf("%d directories by -dir, but only %d max is set by -max", len(folders), len(maxCounts))
  120. }
  121. for _, folder := range folders {
  122. if err := util.TestFolderWritable(folder); err != nil {
  123. glog.Fatalf("Check Data Folder(-dir) Writable %s : %s", folder, err)
  124. }
  125. }
  126. if *masterVolumeSizeLimitMB > 30*1000 {
  127. glog.Fatalf("masterVolumeSizeLimitMB should be less than 30000")
  128. }
  129. if *masterMetaFolder == "" {
  130. *masterMetaFolder = folders[0]
  131. }
  132. if err := util.TestFolderWritable(*masterMetaFolder); err != nil {
  133. glog.Fatalf("Check Meta Folder (-mdir=\"%s\") Writable: %s", *masterMetaFolder, err)
  134. }
  135. if *serverWhiteListOption != "" {
  136. serverWhiteList = strings.Split(*serverWhiteListOption, ",")
  137. }
  138. if *isStartingFiler {
  139. go func() {
  140. time.Sleep(1 * time.Second)
  141. filerOptions.start()
  142. }()
  143. }
  144. var raftWaitForMaster sync.WaitGroup
  145. var volumeWait sync.WaitGroup
  146. raftWaitForMaster.Add(1)
  147. volumeWait.Add(1)
  148. go func() {
  149. r := mux.NewRouter()
  150. ms := weed_server.NewMasterServer(r, *masterPort, *masterMetaFolder,
  151. *masterVolumeSizeLimitMB, *masterVolumePreallocate,
  152. *volumePulse, *masterDefaultReplicaPlacement, *serverGarbageThreshold,
  153. serverWhiteList, *serverSecureKey,
  154. )
  155. glog.V(0).Infoln("Start Seaweed Master", util.VERSION, "at", *serverIp+":"+strconv.Itoa(*masterPort))
  156. masterListener, e := util.NewListener(*serverBindIp+":"+strconv.Itoa(*masterPort), 0)
  157. if e != nil {
  158. glog.Fatalf("Master startup error: %v", e)
  159. }
  160. go func() {
  161. raftWaitForMaster.Wait()
  162. time.Sleep(100 * time.Millisecond)
  163. myAddress, peers := checkPeers(*serverIp, *masterPort, *serverPeers)
  164. raftServer := weed_server.NewRaftServer(r, peers, myAddress, *masterMetaFolder, ms.Topo, *volumePulse)
  165. ms.SetRaftServer(raftServer)
  166. volumeWait.Done()
  167. }()
  168. raftWaitForMaster.Done()
  169. // start grpc and http server
  170. m := cmux.New(masterListener)
  171. grpcL := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
  172. httpL := m.Match(cmux.Any())
  173. // Create your protocol servers.
  174. grpcS := util.NewGrpcServer()
  175. master_pb.RegisterSeaweedServer(grpcS, ms)
  176. reflection.Register(grpcS)
  177. httpS := &http.Server{Handler: r}
  178. go grpcS.Serve(grpcL)
  179. go httpS.Serve(httpL)
  180. if err := m.Serve(); err != nil {
  181. glog.Fatalf("master server failed to serve: %v", err)
  182. }
  183. }()
  184. volumeWait.Wait()
  185. time.Sleep(100 * time.Millisecond)
  186. if *volumePublicPort == 0 {
  187. *volumePublicPort = *volumePort
  188. }
  189. if *volumeServerPublicUrl == "" {
  190. *volumeServerPublicUrl = *serverIp + ":" + strconv.Itoa(*volumePublicPort)
  191. }
  192. isSeperatedPublicPort := *volumePublicPort != *volumePort
  193. volumeMux := http.NewServeMux()
  194. publicVolumeMux := volumeMux
  195. if isSeperatedPublicPort {
  196. publicVolumeMux = http.NewServeMux()
  197. }
  198. volumeNeedleMapKind := storage.NeedleMapInMemory
  199. switch *volumeIndexType {
  200. case "leveldb":
  201. volumeNeedleMapKind = storage.NeedleMapLevelDb
  202. case "boltdb":
  203. volumeNeedleMapKind = storage.NeedleMapBoltDb
  204. case "btree":
  205. volumeNeedleMapKind = storage.NeedleMapBtree
  206. }
  207. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  208. *serverIp, *volumePort, *volumeServerPublicUrl,
  209. folders, maxCounts,
  210. volumeNeedleMapKind,
  211. []string{master}, *volumePulse, *serverDataCenter, *serverRack,
  212. serverWhiteList, *volumeFixJpgOrientation, *volumeReadRedirect,
  213. )
  214. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "at", *serverIp+":"+strconv.Itoa(*volumePort))
  215. volumeListener, eListen := util.NewListener(
  216. *serverBindIp+":"+strconv.Itoa(*volumePort),
  217. time.Duration(*serverTimeout)*time.Second,
  218. )
  219. if eListen != nil {
  220. glog.Fatalf("Volume server listener error: %v", eListen)
  221. }
  222. if isSeperatedPublicPort {
  223. publicListeningAddress := *serverIp + ":" + strconv.Itoa(*volumePublicPort)
  224. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "public at", publicListeningAddress)
  225. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*serverTimeout)*time.Second)
  226. if e != nil {
  227. glog.Fatalf("Volume server listener error:%v", e)
  228. }
  229. go func() {
  230. if e := http.Serve(publicListener, publicVolumeMux); e != nil {
  231. glog.Fatalf("Volume server fail to serve public: %v", e)
  232. }
  233. }()
  234. }
  235. util.OnInterrupt(func() {
  236. volumeServer.Shutdown()
  237. pprof.StopCPUProfile()
  238. })
  239. if e := http.Serve(volumeListener, volumeMux); e != nil {
  240. glog.Fatalf("Volume server fail to serve:%v", e)
  241. }
  242. return true
  243. }