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.

322 lines
13 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
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"
  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. masterConfFile = cmdServer.Flag.String("master.conf", "/etc/weedfs/weedfs.conf", "xml configuration file")
  59. masterDefaultReplicaPlacement = cmdServer.Flag.String("master.defaultReplicaPlacement", "000", "Default replication type if not specified.")
  60. volumePort = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
  61. volumePublicPort = cmdServer.Flag.Int("volume.port.public", 0, "volume server public port")
  62. volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
  63. volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "7", "maximum numbers of volumes, count[,count]...")
  64. volumePulse = cmdServer.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
  65. volumeIndexType = cmdServer.Flag.String("volume.index", "memory", "Choose [memory|leveldb|boltdb] mode for memory~performance balance.")
  66. volumeFixJpgOrientation = cmdServer.Flag.Bool("volume.images.fix.orientation", true, "Adjust jpg orientation when uploading.")
  67. volumeReadRedirect = cmdServer.Flag.Bool("volume.read.redirect", true, "Redirect moved or non-local volumes.")
  68. volumeServerPublicUrl = cmdServer.Flag.String("volume.publicUrl", "", "publicly accessible address")
  69. volumeEnableBytesCache = cmdServer.Flag.Bool("volume.cache.enable", false, "direct cache instead of OS cache, cost more memory.")
  70. isStartingFiler = cmdServer.Flag.Bool("filer", false, "whether to start filer")
  71. serverWhiteList []string
  72. )
  73. func init() {
  74. serverOptions.cpuprofile = cmdServer.Flag.String("cpuprofile", "", "cpu profile output file")
  75. filerOptions.master = cmdServer.Flag.String("filer.master", "", "default to current master server")
  76. filerOptions.collection = cmdServer.Flag.String("filer.collection", "", "all data will be stored in this collection")
  77. filerOptions.port = cmdServer.Flag.Int("filer.port", 8888, "filer server http listen port")
  78. filerOptions.dir = cmdServer.Flag.String("filer.dir", "", "directory to store meta data, default to a 'filer' sub directory of what -dir is specified")
  79. filerOptions.defaultReplicaPlacement = cmdServer.Flag.String("filer.defaultReplicaPlacement", "", "Default replication type if not specified during runtime.")
  80. filerOptions.redirectOnRead = cmdServer.Flag.Bool("filer.redirectOnRead", false, "whether proxy or redirect to volume server during file GET request")
  81. filerOptions.disableDirListing = cmdServer.Flag.Bool("filer.disableDirListing", false, "turn off directory listing")
  82. filerOptions.confFile = cmdServer.Flag.String("filer.confFile", "", "json encoded filer conf file")
  83. filerOptions.maxMB = cmdServer.Flag.Int("filer.maxMB", 0, "split files larger than the limit")
  84. filerOptions.cassandra_server = cmdServer.Flag.String("filer.cassandra.server", "", "host[:port] of the cassandra server")
  85. filerOptions.cassandra_keyspace = cmdServer.Flag.String("filer.cassandra.keyspace", "seaweed", "keyspace of the cassandra server")
  86. filerOptions.redis_server = cmdServer.Flag.String("filer.redis.server", "", "host:port of the redis server, e.g., 127.0.0.1:6379")
  87. filerOptions.redis_password = cmdServer.Flag.String("filer.redis.password", "", "redis password in clear text")
  88. filerOptions.redis_database = cmdServer.Flag.Int("filer.redis.database", 0, "the database on the redis server")
  89. }
  90. func runServer(cmd *Command, args []string) bool {
  91. filerOptions.secretKey = serverSecureKey
  92. if *serverOptions.cpuprofile != "" {
  93. f, err := os.Create(*serverOptions.cpuprofile)
  94. if err != nil {
  95. glog.Fatal(err)
  96. }
  97. pprof.StartCPUProfile(f)
  98. defer pprof.StopCPUProfile()
  99. }
  100. if *filerOptions.redirectOnRead {
  101. *isStartingFiler = true
  102. }
  103. *filerOptions.master = *serverIp + ":" + strconv.Itoa(*masterPort)
  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 *masterMetaFolder == "" {
  133. *masterMetaFolder = folders[0]
  134. }
  135. if *isStartingFiler {
  136. if *filerOptions.dir == "" {
  137. *filerOptions.dir = *masterMetaFolder + "/filer"
  138. os.MkdirAll(*filerOptions.dir, 0700)
  139. }
  140. if err := util.TestFolderWritable(*filerOptions.dir); err != nil {
  141. glog.Fatalf("Check Mapping Meta Folder (-filer.dir=\"%s\") Writable: %s", *filerOptions.dir, err)
  142. }
  143. }
  144. if err := util.TestFolderWritable(*masterMetaFolder); err != nil {
  145. glog.Fatalf("Check Meta Folder (-mdir=\"%s\") Writable: %s", *masterMetaFolder, err)
  146. }
  147. if *serverWhiteListOption != "" {
  148. serverWhiteList = strings.Split(*serverWhiteListOption, ",")
  149. }
  150. if *isStartingFiler {
  151. go func() {
  152. time.Sleep(1 * time.Second)
  153. r := http.NewServeMux()
  154. _, nfs_err := weed_server.NewFilerServer(r, *serverBindIp, *filerOptions.port, *filerOptions.master, *filerOptions.dir, *filerOptions.collection,
  155. *filerOptions.defaultReplicaPlacement,
  156. *filerOptions.redirectOnRead, *filerOptions.disableDirListing,
  157. *filerOptions.confFile,
  158. *filerOptions.maxMB,
  159. *filerOptions.secretKey,
  160. *filerOptions.cassandra_server, *filerOptions.cassandra_keyspace,
  161. *filerOptions.redis_server, *filerOptions.redis_password, *filerOptions.redis_database,
  162. )
  163. if nfs_err != nil {
  164. glog.Fatalf("Filer startup error: %v", nfs_err)
  165. }
  166. glog.V(0).Infoln("Start Seaweed Filer", util.VERSION, "at port", strconv.Itoa(*filerOptions.port))
  167. filerListener, e := util.NewListener(
  168. ":"+strconv.Itoa(*filerOptions.port),
  169. time.Duration(10)*time.Second,
  170. )
  171. if e != nil {
  172. glog.Fatalf("Filer listener error: %v", e)
  173. }
  174. if e := http.Serve(filerListener, r); e != nil {
  175. glog.Fatalf("Filer Fail to serve: %v", e)
  176. }
  177. }()
  178. }
  179. var raftWaitForMaster sync.WaitGroup
  180. var volumeWait sync.WaitGroup
  181. raftWaitForMaster.Add(1)
  182. volumeWait.Add(1)
  183. go func() {
  184. r := mux.NewRouter()
  185. ms := weed_server.NewMasterServer(r, *masterPort, *masterMetaFolder,
  186. *masterVolumeSizeLimitMB, *masterVolumePreallocate,
  187. *volumePulse, *masterConfFile, *masterDefaultReplicaPlacement, *serverGarbageThreshold,
  188. serverWhiteList, *serverSecureKey,
  189. )
  190. glog.V(0).Infoln("Start Seaweed Master", util.VERSION, "at", *serverIp+":"+strconv.Itoa(*masterPort))
  191. masterListener, e := util.NewListener(*serverBindIp+":"+strconv.Itoa(*masterPort), 0)
  192. if e != nil {
  193. glog.Fatalf("Master startup error: %v", e)
  194. }
  195. go func() {
  196. raftWaitForMaster.Wait()
  197. time.Sleep(100 * time.Millisecond)
  198. myAddress := *serverIp + ":" + strconv.Itoa(*masterPort)
  199. var peers []string
  200. if *serverPeers != "" {
  201. peers = strings.Split(*serverPeers, ",")
  202. }
  203. raftServer := weed_server.NewRaftServer(r, peers, myAddress, *masterMetaFolder, ms.Topo, *volumePulse)
  204. ms.SetRaftServer(raftServer)
  205. volumeWait.Done()
  206. }()
  207. raftWaitForMaster.Done()
  208. // start grpc and http server
  209. m := cmux.New(masterListener)
  210. grpcL := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
  211. httpL := m.Match(cmux.Any())
  212. // Create your protocol servers.
  213. grpcS := grpc.NewServer()
  214. pb.RegisterSeaweedServer(grpcS, ms)
  215. reflection.Register(grpcS)
  216. httpS := &http.Server{Handler: r}
  217. go grpcS.Serve(grpcL)
  218. go httpS.Serve(httpL)
  219. if err := m.Serve(); err != nil {
  220. glog.Fatalf("master server failed to serve: %v", err)
  221. }
  222. }()
  223. volumeWait.Wait()
  224. time.Sleep(100 * time.Millisecond)
  225. if *volumePublicPort == 0 {
  226. *volumePublicPort = *volumePort
  227. }
  228. if *volumeServerPublicUrl == "" {
  229. *volumeServerPublicUrl = *serverIp + ":" + strconv.Itoa(*volumePublicPort)
  230. }
  231. isSeperatedPublicPort := *volumePublicPort != *volumePort
  232. volumeMux := http.NewServeMux()
  233. publicVolumeMux := volumeMux
  234. if isSeperatedPublicPort {
  235. publicVolumeMux = http.NewServeMux()
  236. }
  237. volumeNeedleMapKind := storage.NeedleMapInMemory
  238. switch *volumeIndexType {
  239. case "leveldb":
  240. volumeNeedleMapKind = storage.NeedleMapLevelDb
  241. case "boltdb":
  242. volumeNeedleMapKind = storage.NeedleMapBoltDb
  243. }
  244. volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
  245. *serverIp, *volumePort, *volumeServerPublicUrl,
  246. folders, maxCounts,
  247. volumeNeedleMapKind,
  248. *serverIp+":"+strconv.Itoa(*masterPort), *volumePulse, *serverDataCenter, *serverRack,
  249. serverWhiteList, *volumeFixJpgOrientation, *volumeReadRedirect,
  250. *volumeEnableBytesCache,
  251. )
  252. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "at", *serverIp+":"+strconv.Itoa(*volumePort))
  253. volumeListener, eListen := util.NewListener(
  254. *serverBindIp+":"+strconv.Itoa(*volumePort),
  255. time.Duration(*serverTimeout)*time.Second,
  256. )
  257. if eListen != nil {
  258. glog.Fatalf("Volume server listener error: %v", eListen)
  259. }
  260. if isSeperatedPublicPort {
  261. publicListeningAddress := *serverIp + ":" + strconv.Itoa(*volumePublicPort)
  262. glog.V(0).Infoln("Start Seaweed volume server", util.VERSION, "public at", publicListeningAddress)
  263. publicListener, e := util.NewListener(publicListeningAddress, time.Duration(*serverTimeout)*time.Second)
  264. if e != nil {
  265. glog.Fatalf("Volume server listener error:%v", e)
  266. }
  267. go func() {
  268. if e := http.Serve(publicListener, publicVolumeMux); e != nil {
  269. glog.Fatalf("Volume server fail to serve public: %v", e)
  270. }
  271. }()
  272. }
  273. OnInterrupt(func() {
  274. volumeServer.Shutdown()
  275. pprof.StopCPUProfile()
  276. })
  277. if e := http.Serve(volumeListener, volumeMux); e != nil {
  278. glog.Fatalf("Volume server fail to serve:%v", e)
  279. }
  280. return true
  281. }