filer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package command
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "os"
  10. "runtime"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/filer"
  15. "github.com/seaweedfs/seaweedfs/weed/glog"
  16. "github.com/seaweedfs/seaweedfs/weed/pb"
  17. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  18. "github.com/seaweedfs/seaweedfs/weed/security"
  19. weed_server "github.com/seaweedfs/seaweedfs/weed/server"
  20. stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
  21. "github.com/seaweedfs/seaweedfs/weed/util"
  22. "github.com/spf13/viper"
  23. "google.golang.org/grpc/credentials/tls/certprovider"
  24. "google.golang.org/grpc/credentials/tls/certprovider/pemfile"
  25. "google.golang.org/grpc/reflection"
  26. )
  27. var (
  28. f FilerOptions
  29. filerStartS3 *bool
  30. filerS3Options S3Options
  31. filerStartWebDav *bool
  32. filerWebDavOptions WebDavOption
  33. filerStartIam *bool
  34. filerIamOptions IamOptions
  35. )
  36. type FilerOptions struct {
  37. masters *pb.ServerDiscovery
  38. mastersString *string
  39. ip *string
  40. bindIp *string
  41. port *int
  42. portGrpc *int
  43. publicPort *int
  44. filerGroup *string
  45. collection *string
  46. defaultReplicaPlacement *string
  47. disableDirListing *bool
  48. maxMB *int
  49. dirListingLimit *int
  50. dataCenter *string
  51. rack *string
  52. enableNotification *bool
  53. disableHttp *bool
  54. cipher *bool
  55. metricsHttpPort *int
  56. saveToFilerLimit *int
  57. defaultLevelDbDirectory *string
  58. concurrentUploadLimitMB *int
  59. debug *bool
  60. debugPort *int
  61. localSocket *string
  62. showUIDirectoryDelete *bool
  63. downloadMaxMBps *int
  64. diskType *string
  65. allowedOrigins *string
  66. exposeDirectoryData *bool
  67. certProvider certprovider.Provider
  68. }
  69. func init() {
  70. cmdFiler.Run = runFiler // break init cycle
  71. f.mastersString = cmdFiler.Flag.String("master", "localhost:9333", "comma-separated master servers or a single DNS SRV record of at least 1 master server, prepended with dnssrv+")
  72. f.filerGroup = cmdFiler.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
  73. f.collection = cmdFiler.Flag.String("collection", "", "all data will be stored in this default collection")
  74. f.ip = cmdFiler.Flag.String("ip", util.DetectedHostAddress(), "filer server http listen ip address")
  75. f.bindIp = cmdFiler.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
  76. f.port = cmdFiler.Flag.Int("port", 8888, "filer server http listen port")
  77. f.portGrpc = cmdFiler.Flag.Int("port.grpc", 0, "filer server grpc listen port")
  78. f.publicPort = cmdFiler.Flag.Int("port.readonly", 0, "readonly port opened to public")
  79. f.defaultReplicaPlacement = cmdFiler.Flag.String("defaultReplicaPlacement", "", "default replication type. If not specified, use master setting.")
  80. f.disableDirListing = cmdFiler.Flag.Bool("disableDirListing", false, "turn off directory listing")
  81. f.maxMB = cmdFiler.Flag.Int("maxMB", 4, "split files larger than the limit")
  82. f.dirListingLimit = cmdFiler.Flag.Int("dirListLimit", 100000, "limit sub dir listing size")
  83. f.dataCenter = cmdFiler.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
  84. f.rack = cmdFiler.Flag.String("rack", "", "prefer to write to volumes in this rack")
  85. f.disableHttp = cmdFiler.Flag.Bool("disableHttp", false, "disable http request, only gRpc operations are allowed")
  86. f.cipher = cmdFiler.Flag.Bool("encryptVolumeData", false, "encrypt data on volume servers")
  87. f.metricsHttpPort = cmdFiler.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  88. f.saveToFilerLimit = cmdFiler.Flag.Int("saveToFilerLimit", 0, "files smaller than this limit will be saved in filer store")
  89. f.defaultLevelDbDirectory = cmdFiler.Flag.String("defaultStoreDir", ".", "if filer.toml is empty, use an embedded filer store in the directory")
  90. f.concurrentUploadLimitMB = cmdFiler.Flag.Int("concurrentUploadLimitMB", 128, "limit total concurrent upload size")
  91. f.debug = cmdFiler.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
  92. f.debugPort = cmdFiler.Flag.Int("debug.port", 6060, "http port for debugging")
  93. f.localSocket = cmdFiler.Flag.String("localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
  94. f.showUIDirectoryDelete = cmdFiler.Flag.Bool("ui.deleteDir", true, "enable filer UI show delete directory button")
  95. f.downloadMaxMBps = cmdFiler.Flag.Int("downloadMaxMBps", 0, "download max speed for each download request, in MB per second")
  96. f.diskType = cmdFiler.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  97. f.allowedOrigins = cmdFiler.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
  98. f.exposeDirectoryData = cmdFiler.Flag.Bool("exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
  99. // start s3 on filer
  100. filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
  101. filerS3Options.port = cmdFiler.Flag.Int("s3.port", 8333, "s3 server http listen port")
  102. filerS3Options.portHttps = cmdFiler.Flag.Int("s3.port.https", 0, "s3 server https listen port")
  103. filerS3Options.portGrpc = cmdFiler.Flag.Int("s3.port.grpc", 0, "s3 server grpc listen port")
  104. filerS3Options.domainName = cmdFiler.Flag.String("s3.domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
  105. filerS3Options.allowedOrigins = cmdFiler.Flag.String("s3.allowedOrigins", "*", "comma separated list of allowed origins")
  106. filerS3Options.dataCenter = cmdFiler.Flag.String("s3.dataCenter", "", "prefer to read and write to volumes in this data center")
  107. filerS3Options.tlsPrivateKey = cmdFiler.Flag.String("s3.key.file", "", "path to the TLS private key file")
  108. filerS3Options.tlsCertificate = cmdFiler.Flag.String("s3.cert.file", "", "path to the TLS certificate file")
  109. filerS3Options.config = cmdFiler.Flag.String("s3.config", "", "path to the config file")
  110. filerS3Options.auditLogConfig = cmdFiler.Flag.String("s3.auditLogConfig", "", "path to the audit log config file")
  111. filerS3Options.allowEmptyFolder = cmdFiler.Flag.Bool("s3.allowEmptyFolder", true, "allow empty folders")
  112. filerS3Options.allowDeleteBucketNotEmpty = cmdFiler.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
  113. filerS3Options.localSocket = cmdFiler.Flag.String("s3.localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
  114. // start webdav on filer
  115. filerStartWebDav = cmdFiler.Flag.Bool("webdav", false, "whether to start webdav gateway")
  116. filerWebDavOptions.port = cmdFiler.Flag.Int("webdav.port", 7333, "webdav server http listen port")
  117. filerWebDavOptions.collection = cmdFiler.Flag.String("webdav.collection", "", "collection to create the files")
  118. filerWebDavOptions.replication = cmdFiler.Flag.String("webdav.replication", "", "replication to create the files")
  119. filerWebDavOptions.disk = cmdFiler.Flag.String("webdav.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  120. filerWebDavOptions.tlsPrivateKey = cmdFiler.Flag.String("webdav.key.file", "", "path to the TLS private key file")
  121. filerWebDavOptions.tlsCertificate = cmdFiler.Flag.String("webdav.cert.file", "", "path to the TLS certificate file")
  122. filerWebDavOptions.cacheDir = cmdFiler.Flag.String("webdav.cacheDir", os.TempDir(), "local cache directory for file chunks")
  123. filerWebDavOptions.cacheSizeMB = cmdFiler.Flag.Int64("webdav.cacheCapacityMB", 0, "local cache capacity in MB")
  124. filerWebDavOptions.filerRootPath = cmdFiler.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
  125. // start iam on filer
  126. filerStartIam = cmdFiler.Flag.Bool("iam", false, "whether to start IAM service")
  127. filerIamOptions.ip = cmdFiler.Flag.String("iam.ip", *f.ip, "iam server http listen ip address")
  128. filerIamOptions.port = cmdFiler.Flag.Int("iam.port", 8111, "iam server http listen port")
  129. }
  130. func filerLongDesc() string {
  131. desc := `start a file server which accepts REST operation for any files.
  132. //create or overwrite the file, the directories /path/to will be automatically created
  133. POST /path/to/file
  134. //get the file content
  135. GET /path/to/file
  136. //create or overwrite the file, the filename in the multipart request will be used
  137. POST /path/to/
  138. //return a json format subdirectory and files listing
  139. GET /path/to/
  140. The configuration file "filer.toml" is read from ".", "$HOME/.seaweedfs/", "/usr/local/etc/seaweedfs/", or "/etc/seaweedfs/", in that order.
  141. If the "filer.toml" is not found, an embedded filer store will be created under "-defaultStoreDir".
  142. The example filer.toml configuration file can be generated by "weed scaffold -config=filer"
  143. Supported Filer Stores:
  144. `
  145. storeNames := make([]string, len(filer.Stores))
  146. for i, store := range filer.Stores {
  147. storeNames[i] = "\t" + store.GetName()
  148. }
  149. sort.Strings(storeNames)
  150. storeList := strings.Join(storeNames, "\n")
  151. return desc + storeList
  152. }
  153. var cmdFiler = &Command{
  154. UsageLine: "filer -port=8888 -master=<ip:port>[,<ip:port>]*",
  155. Short: "start a file server that points to a master server, or a list of master servers",
  156. Long: filerLongDesc(),
  157. }
  158. func runFiler(cmd *Command, args []string) bool {
  159. if *f.debug {
  160. go http.ListenAndServe(fmt.Sprintf(":%d", *f.debugPort), nil)
  161. }
  162. util.LoadConfiguration("security", false)
  163. go stats_collect.StartMetricsServer(*f.bindIp, *f.metricsHttpPort)
  164. filerAddress := pb.NewServerAddress(*f.ip, *f.port, *f.portGrpc).String()
  165. startDelay := time.Duration(2)
  166. if *filerStartS3 {
  167. filerS3Options.filer = &filerAddress
  168. filerS3Options.bindIp = f.bindIp
  169. filerS3Options.localFilerSocket = f.localSocket
  170. if *f.dataCenter != "" && *filerS3Options.dataCenter == "" {
  171. filerS3Options.dataCenter = f.dataCenter
  172. }
  173. go func(delay time.Duration) {
  174. time.Sleep(delay * time.Second)
  175. filerS3Options.startS3Server()
  176. }(startDelay)
  177. startDelay++
  178. }
  179. if *filerStartWebDav {
  180. filerWebDavOptions.filer = &filerAddress
  181. if *filerWebDavOptions.disk == "" {
  182. filerWebDavOptions.disk = f.diskType
  183. }
  184. go func(delay time.Duration) {
  185. time.Sleep(delay * time.Second)
  186. filerWebDavOptions.startWebDav()
  187. }(startDelay)
  188. startDelay++
  189. }
  190. if *filerStartIam {
  191. filerIamOptions.filer = &filerAddress
  192. filerIamOptions.masters = f.mastersString
  193. go func(delay time.Duration) {
  194. time.Sleep(delay * time.Second)
  195. filerIamOptions.startIamServer()
  196. }(startDelay)
  197. }
  198. f.masters = pb.ServerAddresses(*f.mastersString).ToServiceDiscovery()
  199. f.startFiler()
  200. return true
  201. }
  202. // GetCertificateWithUpdate Auto refreshing TSL certificate
  203. func (fo *FilerOptions) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  204. certs, err := fo.certProvider.KeyMaterial(context.Background())
  205. return &certs.Certs[0], err
  206. }
  207. func (fo *FilerOptions) startFiler() {
  208. defaultMux := http.NewServeMux()
  209. publicVolumeMux := defaultMux
  210. if *fo.publicPort != 0 {
  211. publicVolumeMux = http.NewServeMux()
  212. }
  213. if *fo.portGrpc == 0 {
  214. *fo.portGrpc = 10000 + *fo.port
  215. }
  216. if *fo.bindIp == "" {
  217. *fo.bindIp = *fo.ip
  218. }
  219. if *fo.allowedOrigins == "" {
  220. *fo.allowedOrigins = "*"
  221. }
  222. defaultLevelDbDirectory := util.ResolvePath(*fo.defaultLevelDbDirectory + "/filerldb2")
  223. filerAddress := pb.NewServerAddress(*fo.ip, *fo.port, *fo.portGrpc)
  224. fs, nfs_err := weed_server.NewFilerServer(defaultMux, publicVolumeMux, &weed_server.FilerOption{
  225. Masters: fo.masters,
  226. FilerGroup: *fo.filerGroup,
  227. Collection: *fo.collection,
  228. DefaultReplication: *fo.defaultReplicaPlacement,
  229. DisableDirListing: *fo.disableDirListing,
  230. MaxMB: *fo.maxMB,
  231. DirListingLimit: *fo.dirListingLimit,
  232. DataCenter: *fo.dataCenter,
  233. Rack: *fo.rack,
  234. DefaultLevelDbDir: defaultLevelDbDirectory,
  235. DisableHttp: *fo.disableHttp,
  236. Host: filerAddress,
  237. Cipher: *fo.cipher,
  238. SaveToFilerLimit: int64(*fo.saveToFilerLimit),
  239. ConcurrentUploadLimit: int64(*fo.concurrentUploadLimitMB) * 1024 * 1024,
  240. ShowUIDirectoryDelete: *fo.showUIDirectoryDelete,
  241. DownloadMaxBytesPs: int64(*fo.downloadMaxMBps) * 1024 * 1024,
  242. DiskType: *fo.diskType,
  243. AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
  244. })
  245. if nfs_err != nil {
  246. glog.Fatalf("Filer startup error: %v", nfs_err)
  247. }
  248. if *fo.publicPort != 0 {
  249. publicListeningAddress := util.JoinHostPort(*fo.bindIp, *fo.publicPort)
  250. glog.V(0).Infoln("Start Seaweed filer server", util.Version(), "public at", publicListeningAddress)
  251. publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0)
  252. if e != nil {
  253. glog.Fatalf("Filer server public listener error on port %d:%v", *fo.publicPort, e)
  254. }
  255. go func() {
  256. if e := http.Serve(publicListener, publicVolumeMux); e != nil {
  257. glog.Fatalf("Volume server fail to serve public: %v", e)
  258. }
  259. }()
  260. if localPublicListener != nil {
  261. go func() {
  262. if e := http.Serve(localPublicListener, publicVolumeMux); e != nil {
  263. glog.Errorf("Volume server fail to serve public: %v", e)
  264. }
  265. }()
  266. }
  267. }
  268. glog.V(0).Infof("Start Seaweed Filer %s at %s:%d", util.Version(), *fo.ip, *fo.port)
  269. filerListener, filerLocalListener, e := util.NewIpAndLocalListeners(
  270. *fo.bindIp, *fo.port,
  271. time.Duration(10)*time.Second,
  272. )
  273. if e != nil {
  274. glog.Fatalf("Filer listener error: %v", e)
  275. }
  276. // starting grpc server
  277. grpcPort := *fo.portGrpc
  278. grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*fo.bindIp, grpcPort, 0)
  279. if err != nil {
  280. glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
  281. }
  282. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.filer"))
  283. filer_pb.RegisterSeaweedFilerServer(grpcS, fs)
  284. reflection.Register(grpcS)
  285. if grpcLocalL != nil {
  286. go grpcS.Serve(grpcLocalL)
  287. }
  288. go grpcS.Serve(grpcL)
  289. httpS := &http.Server{Handler: defaultMux}
  290. if runtime.GOOS != "windows" {
  291. localSocket := *fo.localSocket
  292. if localSocket == "" {
  293. localSocket = fmt.Sprintf("/tmp/seaweedfs-filer-%d.sock", *fo.port)
  294. }
  295. if err := os.Remove(localSocket); err != nil && !os.IsNotExist(err) {
  296. glog.Fatalf("Failed to remove %s, error: %s", localSocket, err.Error())
  297. }
  298. go func() {
  299. // start on local unix socket
  300. filerSocketListener, err := net.Listen("unix", localSocket)
  301. if err != nil {
  302. glog.Fatalf("Failed to listen on %s: %v", localSocket, err)
  303. }
  304. httpS.Serve(filerSocketListener)
  305. }()
  306. }
  307. if viper.GetString("https.filer.key") != "" {
  308. certFile := viper.GetString("https.filer.cert")
  309. keyFile := viper.GetString("https.filer.key")
  310. caCertFile := viper.GetString("https.filer.ca")
  311. disbaleTlsVerifyClientCert := viper.GetBool("https.filer.disable_tls_verify_client_cert")
  312. pemfileOptions := pemfile.Options{
  313. CertFile: certFile,
  314. KeyFile: keyFile,
  315. RefreshDuration: security.CredRefreshingInterval,
  316. }
  317. if fo.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
  318. glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
  319. }
  320. caCertPool := x509.NewCertPool()
  321. if caCertFile != "" {
  322. caCertFile, err := os.ReadFile(caCertFile)
  323. if err != nil {
  324. glog.Fatalf("error reading CA certificate: %v", err)
  325. }
  326. caCertPool.AppendCertsFromPEM(caCertFile)
  327. }
  328. clientAuth := tls.NoClientCert
  329. if !disbaleTlsVerifyClientCert {
  330. clientAuth = tls.RequireAndVerifyClientCert
  331. }
  332. httpS.TLSConfig = &tls.Config{
  333. GetCertificate: fo.GetCertificateWithUpdate,
  334. ClientAuth: clientAuth,
  335. ClientCAs: caCertPool,
  336. }
  337. if filerLocalListener != nil {
  338. go func() {
  339. if err := httpS.ServeTLS(filerLocalListener, "", ""); err != nil {
  340. glog.Errorf("Filer Fail to serve: %v", e)
  341. }
  342. }()
  343. }
  344. if err := httpS.ServeTLS(filerListener, "", ""); err != nil {
  345. glog.Fatalf("Filer Fail to serve: %v", e)
  346. }
  347. } else {
  348. if filerLocalListener != nil {
  349. go func() {
  350. if err := httpS.Serve(filerLocalListener); err != nil {
  351. glog.Errorf("Filer Fail to serve: %v", e)
  352. }
  353. }()
  354. }
  355. if err := httpS.Serve(filerListener); err != nil {
  356. glog.Fatalf("Filer Fail to serve: %v", e)
  357. }
  358. }
  359. }