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.

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