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.

372 lines
12 KiB

8 months ago
5 years ago
8 months ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
8 months ago
4 years ago
  1. package command
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. "strings"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  15. "google.golang.org/grpc/credentials/tls/certprovider"
  16. "google.golang.org/grpc/credentials/tls/certprovider/pemfile"
  17. "google.golang.org/grpc/reflection"
  18. "github.com/seaweedfs/seaweedfs/weed/pb"
  19. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  20. "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
  21. "github.com/seaweedfs/seaweedfs/weed/security"
  22. "github.com/gorilla/mux"
  23. "github.com/seaweedfs/seaweedfs/weed/glog"
  24. "github.com/seaweedfs/seaweedfs/weed/s3api"
  25. stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. )
  28. var (
  29. s3StandaloneOptions S3Options
  30. )
  31. type S3Options struct {
  32. filer *string
  33. bindIp *string
  34. port *int
  35. portHttps *int
  36. portGrpc *int
  37. config *string
  38. domainName *string
  39. allowedOrigins *string
  40. tlsPrivateKey *string
  41. tlsCertificate *string
  42. tlsCACertificate *string
  43. tlsVerifyClientCert *bool
  44. metricsHttpPort *int
  45. allowEmptyFolder *bool
  46. allowDeleteBucketNotEmpty *bool
  47. allowListRecursive *bool
  48. auditLogConfig *string
  49. localFilerSocket *string
  50. dataCenter *string
  51. localSocket *string
  52. certProvider certprovider.Provider
  53. }
  54. func init() {
  55. cmdS3.Run = runS3 // break init cycle
  56. s3StandaloneOptions.filer = cmdS3.Flag.String("filer", "localhost:8888", "filer server address")
  57. s3StandaloneOptions.bindIp = cmdS3.Flag.String("ip.bind", "", "ip address to bind to. Default to localhost.")
  58. s3StandaloneOptions.port = cmdS3.Flag.Int("port", 8333, "s3 server http listen port")
  59. s3StandaloneOptions.portHttps = cmdS3.Flag.Int("port.https", 0, "s3 server https listen port")
  60. s3StandaloneOptions.portGrpc = cmdS3.Flag.Int("port.grpc", 0, "s3 server grpc listen port")
  61. s3StandaloneOptions.domainName = cmdS3.Flag.String("domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
  62. s3StandaloneOptions.allowedOrigins = cmdS3.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
  63. s3StandaloneOptions.dataCenter = cmdS3.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
  64. s3StandaloneOptions.config = cmdS3.Flag.String("config", "", "path to the config file")
  65. s3StandaloneOptions.auditLogConfig = cmdS3.Flag.String("auditLogConfig", "", "path to the audit log config file")
  66. s3StandaloneOptions.tlsPrivateKey = cmdS3.Flag.String("key.file", "", "path to the TLS private key file")
  67. s3StandaloneOptions.tlsCertificate = cmdS3.Flag.String("cert.file", "", "path to the TLS certificate file")
  68. s3StandaloneOptions.tlsCACertificate = cmdS3.Flag.String("cacert.file", "", "path to the TLS CA certificate file")
  69. s3StandaloneOptions.tlsVerifyClientCert = cmdS3.Flag.Bool("tlsVerifyClientCert", false, "whether to verify the client's certificate")
  70. s3StandaloneOptions.metricsHttpPort = cmdS3.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  71. s3StandaloneOptions.allowEmptyFolder = cmdS3.Flag.Bool("allowEmptyFolder", true, "allow empty folders")
  72. s3StandaloneOptions.allowDeleteBucketNotEmpty = cmdS3.Flag.Bool("allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
  73. s3StandaloneOptions.allowListRecursive = cmdS3.Flag.Bool("allowListRecursive", false, "allows recursive listing of directories by prefix on the side of the filer store with SQL")
  74. s3StandaloneOptions.localFilerSocket = cmdS3.Flag.String("localFilerSocket", "", "local filer socket path")
  75. s3StandaloneOptions.localSocket = cmdS3.Flag.String("localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
  76. }
  77. var cmdS3 = &Command{
  78. UsageLine: "s3 [-port=8333] [-filer=<ip:port>] [-config=</path/to/config.json>]",
  79. Short: "start a s3 API compatible server that is backed by a filer",
  80. Long: `start a s3 API compatible server that is backed by a filer.
  81. By default, you can use any access key and secret key to access the S3 APIs.
  82. To enable credential based access, create a config.json file similar to this:
  83. {
  84. "identities": [
  85. {
  86. "name": "anonymous",
  87. "actions": [
  88. "Read"
  89. ]
  90. },
  91. {
  92. "name": "some_admin_user",
  93. "credentials": [
  94. {
  95. "accessKey": "some_access_key1",
  96. "secretKey": "some_secret_key1"
  97. }
  98. ],
  99. "actions": [
  100. "Admin",
  101. "Read",
  102. "List",
  103. "Tagging",
  104. "Write"
  105. ]
  106. },
  107. {
  108. "name": "some_read_only_user",
  109. "credentials": [
  110. {
  111. "accessKey": "some_access_key2",
  112. "secretKey": "some_secret_key2"
  113. }
  114. ],
  115. "actions": [
  116. "Read"
  117. ]
  118. },
  119. {
  120. "name": "some_normal_user",
  121. "credentials": [
  122. {
  123. "accessKey": "some_access_key3",
  124. "secretKey": "some_secret_key3"
  125. }
  126. ],
  127. "actions": [
  128. "Read",
  129. "List",
  130. "Tagging",
  131. "Write"
  132. ]
  133. },
  134. {
  135. "name": "user_limited_to_bucket1",
  136. "credentials": [
  137. {
  138. "accessKey": "some_access_key4",
  139. "secretKey": "some_secret_key4"
  140. }
  141. ],
  142. "actions": [
  143. "Read:bucket1",
  144. "List:bucket1",
  145. "Tagging:bucket1",
  146. "Write:bucket1"
  147. ]
  148. }
  149. ]
  150. }
  151. `,
  152. }
  153. func runS3(cmd *Command, args []string) bool {
  154. util.LoadConfiguration("security", false)
  155. go stats_collect.StartMetricsServer(*s3StandaloneOptions.bindIp, *s3StandaloneOptions.metricsHttpPort)
  156. return s3StandaloneOptions.startS3Server()
  157. }
  158. // GetCertificateWithUpdate Auto refreshing TSL certificate
  159. func (S3opt *S3Options) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  160. certs, err := S3opt.certProvider.KeyMaterial(context.Background())
  161. return &certs.Certs[0], err
  162. }
  163. func (s3opt *S3Options) startS3Server() bool {
  164. filerAddress := pb.ServerAddress(*s3opt.filer)
  165. filerBucketsPath := "/buckets"
  166. filerGroup := ""
  167. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  168. // metrics read from the filer
  169. var metricsAddress string
  170. var metricsIntervalSec int
  171. for {
  172. err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  173. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  174. if err != nil {
  175. return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
  176. }
  177. filerBucketsPath = resp.DirBuckets
  178. filerGroup = resp.FilerGroup
  179. metricsAddress, metricsIntervalSec = resp.MetricsAddress, int(resp.MetricsIntervalSec)
  180. glog.V(0).Infof("S3 read filer buckets dir: %s", filerBucketsPath)
  181. return nil
  182. })
  183. if err != nil {
  184. glog.V(0).Infof("wait to connect to filer %s grpc address %s", *s3opt.filer, filerAddress.ToGrpcAddress())
  185. time.Sleep(time.Second)
  186. } else {
  187. glog.V(0).Infof("connected to filer %s grpc address %s", *s3opt.filer, filerAddress.ToGrpcAddress())
  188. break
  189. }
  190. }
  191. go stats_collect.LoopPushingMetric("s3", stats_collect.SourceName(uint32(*s3opt.port)), metricsAddress, metricsIntervalSec)
  192. router := mux.NewRouter().SkipClean(true)
  193. var localFilerSocket string
  194. if s3opt.localFilerSocket != nil {
  195. localFilerSocket = *s3opt.localFilerSocket
  196. }
  197. s3ApiServer, s3ApiServer_err := s3api.NewS3ApiServer(router, &s3api.S3ApiServerOption{
  198. Filer: filerAddress,
  199. Port: *s3opt.port,
  200. Config: *s3opt.config,
  201. DomainName: *s3opt.domainName,
  202. AllowedOrigins: strings.Split(*s3opt.allowedOrigins, ","),
  203. BucketsPath: filerBucketsPath,
  204. GrpcDialOption: grpcDialOption,
  205. AllowEmptyFolder: *s3opt.allowEmptyFolder,
  206. AllowDeleteBucketNotEmpty: *s3opt.allowDeleteBucketNotEmpty,
  207. AllowListRecursive: *s3opt.allowListRecursive,
  208. LocalFilerSocket: localFilerSocket,
  209. DataCenter: *s3opt.dataCenter,
  210. FilerGroup: filerGroup,
  211. })
  212. if s3ApiServer_err != nil {
  213. glog.Fatalf("S3 API Server startup error: %v", s3ApiServer_err)
  214. }
  215. httpS := &http.Server{Handler: router}
  216. if *s3opt.portGrpc == 0 {
  217. *s3opt.portGrpc = 10000 + *s3opt.port
  218. }
  219. if *s3opt.bindIp == "" {
  220. *s3opt.bindIp = "localhost"
  221. }
  222. if runtime.GOOS != "windows" {
  223. localSocket := *s3opt.localSocket
  224. if localSocket == "" {
  225. localSocket = fmt.Sprintf("/tmp/seaweedfs-s3-%d.sock", *s3opt.port)
  226. }
  227. if err := os.Remove(localSocket); err != nil && !os.IsNotExist(err) {
  228. glog.Fatalf("Failed to remove %s, error: %s", localSocket, err.Error())
  229. }
  230. go func() {
  231. // start on local unix socket
  232. s3SocketListener, err := net.Listen("unix", localSocket)
  233. if err != nil {
  234. glog.Fatalf("Failed to listen on %s: %v", localSocket, err)
  235. }
  236. httpS.Serve(s3SocketListener)
  237. }()
  238. }
  239. listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.port)
  240. s3ApiListener, s3ApiLocalListener, err := util.NewIpAndLocalListeners(*s3opt.bindIp, *s3opt.port, time.Duration(10)*time.Second)
  241. if err != nil {
  242. glog.Fatalf("S3 API Server listener on %s error: %v", listenAddress, err)
  243. }
  244. if len(*s3opt.auditLogConfig) > 0 {
  245. s3err.InitAuditLog(*s3opt.auditLogConfig)
  246. if s3err.Logger != nil {
  247. defer s3err.Logger.Close()
  248. }
  249. }
  250. // starting grpc server
  251. grpcPort := *s3opt.portGrpc
  252. grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0)
  253. if err != nil {
  254. glog.Fatalf("s3 failed to listen on grpc port %d: %v", grpcPort, err)
  255. }
  256. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.s3"))
  257. s3_pb.RegisterSeaweedS3Server(grpcS, s3ApiServer)
  258. reflection.Register(grpcS)
  259. if grpcLocalL != nil {
  260. go grpcS.Serve(grpcLocalL)
  261. }
  262. go grpcS.Serve(grpcL)
  263. if *s3opt.tlsPrivateKey != "" {
  264. pemfileOptions := pemfile.Options{
  265. CertFile: *s3opt.tlsCertificate,
  266. KeyFile: *s3opt.tlsPrivateKey,
  267. RefreshDuration: security.CredRefreshingInterval,
  268. }
  269. if s3opt.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
  270. glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
  271. }
  272. caCertPool := x509.NewCertPool()
  273. if *s3Options.tlsCACertificate != "" {
  274. // load CA certificate file and add it to list of client CAs
  275. caCertFile, err := ioutil.ReadFile(*s3opt.tlsCACertificate)
  276. if err != nil {
  277. glog.Fatalf("error reading CA certificate: %v", err)
  278. }
  279. caCertPool.AppendCertsFromPEM(caCertFile)
  280. }
  281. clientAuth := tls.NoClientCert
  282. if *s3Options.tlsVerifyClientCert {
  283. clientAuth = tls.RequireAndVerifyClientCert
  284. }
  285. httpS.TLSConfig = &tls.Config{
  286. GetCertificate: s3opt.GetCertificateWithUpdate,
  287. ClientAuth: clientAuth,
  288. ClientCAs: caCertPool,
  289. }
  290. if *s3opt.portHttps == 0 {
  291. glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", util.Version(), *s3opt.port)
  292. if s3ApiLocalListener != nil {
  293. go func() {
  294. if err = httpS.ServeTLS(s3ApiLocalListener, "", ""); err != nil {
  295. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  296. }
  297. }()
  298. }
  299. if err = httpS.ServeTLS(s3ApiListener, "", ""); err != nil {
  300. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  301. }
  302. } else {
  303. glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", util.Version(), *s3opt.portHttps)
  304. s3ApiListenerHttps, s3ApiLocalListenerHttps, _ := util.NewIpAndLocalListeners(
  305. *s3opt.bindIp, *s3opt.portHttps, time.Duration(10)*time.Second)
  306. if s3ApiLocalListenerHttps != nil {
  307. go func() {
  308. if err = httpS.ServeTLS(s3ApiLocalListenerHttps, "", ""); err != nil {
  309. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  310. }
  311. }()
  312. }
  313. go func() {
  314. if err = httpS.ServeTLS(s3ApiListenerHttps, "", ""); err != nil {
  315. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  316. }
  317. }()
  318. }
  319. }
  320. if *s3opt.tlsPrivateKey == "" || *s3opt.portHttps > 0 {
  321. glog.V(0).Infof("Start Seaweed S3 API Server %s at http port %d", util.Version(), *s3opt.port)
  322. if s3ApiLocalListener != nil {
  323. go func() {
  324. if err = httpS.Serve(s3ApiLocalListener); err != nil {
  325. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  326. }
  327. }()
  328. }
  329. if err = httpS.Serve(s3ApiListener); err != nil {
  330. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  331. }
  332. }
  333. return true
  334. }