s3.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. metricsHttpIp *string
  46. allowEmptyFolder *bool
  47. allowDeleteBucketNotEmpty *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.metricsHttpIp = cmdS3.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
  72. s3StandaloneOptions.allowEmptyFolder = cmdS3.Flag.Bool("allowEmptyFolder", true, "allow empty folders")
  73. s3StandaloneOptions.allowDeleteBucketNotEmpty = cmdS3.Flag.Bool("allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
  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.LoadSecurityConfiguration()
  155. switch {
  156. case *s3StandaloneOptions.metricsHttpIp != "":
  157. // noting to do, use s3StandaloneOptions.metricsHttpIp
  158. case *s3StandaloneOptions.bindIp != "":
  159. *s3StandaloneOptions.metricsHttpIp = *s3StandaloneOptions.bindIp
  160. }
  161. go stats_collect.StartMetricsServer(*s3StandaloneOptions.metricsHttpIp, *s3StandaloneOptions.metricsHttpPort)
  162. return s3StandaloneOptions.startS3Server()
  163. }
  164. // GetCertificateWithUpdate Auto refreshing TSL certificate
  165. func (s3opt *S3Options) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  166. certs, err := s3opt.certProvider.KeyMaterial(context.Background())
  167. if certs == nil {
  168. return nil, err
  169. }
  170. return &certs.Certs[0], err
  171. }
  172. func (s3opt *S3Options) startS3Server() bool {
  173. filerAddress := pb.ServerAddress(*s3opt.filer)
  174. filerBucketsPath := "/buckets"
  175. filerGroup := ""
  176. grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
  177. // metrics read from the filer
  178. var metricsAddress string
  179. var metricsIntervalSec int
  180. for {
  181. err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  182. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  183. if err != nil {
  184. return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
  185. }
  186. filerBucketsPath = resp.DirBuckets
  187. filerGroup = resp.FilerGroup
  188. metricsAddress, metricsIntervalSec = resp.MetricsAddress, int(resp.MetricsIntervalSec)
  189. glog.V(0).Infof("S3 read filer buckets dir: %s", filerBucketsPath)
  190. return nil
  191. })
  192. if err != nil {
  193. glog.V(0).Infof("wait to connect to filer %s grpc address %s", *s3opt.filer, filerAddress.ToGrpcAddress())
  194. time.Sleep(time.Second)
  195. } else {
  196. glog.V(0).Infof("connected to filer %s grpc address %s", *s3opt.filer, filerAddress.ToGrpcAddress())
  197. break
  198. }
  199. }
  200. go stats_collect.LoopPushingMetric("s3", stats_collect.SourceName(uint32(*s3opt.port)), metricsAddress, metricsIntervalSec)
  201. router := mux.NewRouter().SkipClean(true)
  202. var localFilerSocket string
  203. if s3opt.localFilerSocket != nil {
  204. localFilerSocket = *s3opt.localFilerSocket
  205. }
  206. s3ApiServer, s3ApiServer_err := s3api.NewS3ApiServer(router, &s3api.S3ApiServerOption{
  207. Filer: filerAddress,
  208. Port: *s3opt.port,
  209. Config: *s3opt.config,
  210. DomainName: *s3opt.domainName,
  211. AllowedOrigins: strings.Split(*s3opt.allowedOrigins, ","),
  212. BucketsPath: filerBucketsPath,
  213. GrpcDialOption: grpcDialOption,
  214. AllowEmptyFolder: *s3opt.allowEmptyFolder,
  215. AllowDeleteBucketNotEmpty: *s3opt.allowDeleteBucketNotEmpty,
  216. LocalFilerSocket: localFilerSocket,
  217. DataCenter: *s3opt.dataCenter,
  218. FilerGroup: filerGroup,
  219. })
  220. if s3ApiServer_err != nil {
  221. glog.Fatalf("S3 API Server startup error: %v", s3ApiServer_err)
  222. }
  223. httpS := &http.Server{Handler: router}
  224. if *s3opt.portGrpc == 0 {
  225. *s3opt.portGrpc = 10000 + *s3opt.port
  226. }
  227. if *s3opt.bindIp == "" {
  228. *s3opt.bindIp = "localhost"
  229. }
  230. if runtime.GOOS != "windows" {
  231. localSocket := *s3opt.localSocket
  232. if localSocket == "" {
  233. localSocket = fmt.Sprintf("/tmp/seaweedfs-s3-%d.sock", *s3opt.port)
  234. }
  235. if err := os.Remove(localSocket); err != nil && !os.IsNotExist(err) {
  236. glog.Fatalf("Failed to remove %s, error: %s", localSocket, err.Error())
  237. }
  238. go func() {
  239. // start on local unix socket
  240. s3SocketListener, err := net.Listen("unix", localSocket)
  241. if err != nil {
  242. glog.Fatalf("Failed to listen on %s: %v", localSocket, err)
  243. }
  244. httpS.Serve(s3SocketListener)
  245. }()
  246. }
  247. listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.port)
  248. s3ApiListener, s3ApiLocalListener, err := util.NewIpAndLocalListeners(*s3opt.bindIp, *s3opt.port, time.Duration(10)*time.Second)
  249. if err != nil {
  250. glog.Fatalf("S3 API Server listener on %s error: %v", listenAddress, err)
  251. }
  252. if len(*s3opt.auditLogConfig) > 0 {
  253. s3err.InitAuditLog(*s3opt.auditLogConfig)
  254. if s3err.Logger != nil {
  255. defer s3err.Logger.Close()
  256. }
  257. }
  258. // starting grpc server
  259. grpcPort := *s3opt.portGrpc
  260. grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0)
  261. if err != nil {
  262. glog.Fatalf("s3 failed to listen on grpc port %d: %v", grpcPort, err)
  263. }
  264. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.s3"))
  265. s3_pb.RegisterSeaweedS3Server(grpcS, s3ApiServer)
  266. reflection.Register(grpcS)
  267. if grpcLocalL != nil {
  268. go grpcS.Serve(grpcLocalL)
  269. }
  270. go grpcS.Serve(grpcL)
  271. if *s3opt.tlsPrivateKey != "" {
  272. pemfileOptions := pemfile.Options{
  273. CertFile: *s3opt.tlsCertificate,
  274. KeyFile: *s3opt.tlsPrivateKey,
  275. RefreshDuration: security.CredRefreshingInterval,
  276. }
  277. if s3opt.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
  278. glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
  279. }
  280. caCertPool := x509.NewCertPool()
  281. if *s3Options.tlsCACertificate != "" {
  282. // load CA certificate file and add it to list of client CAs
  283. caCertFile, err := ioutil.ReadFile(*s3opt.tlsCACertificate)
  284. if err != nil {
  285. glog.Fatalf("error reading CA certificate: %v", err)
  286. }
  287. caCertPool.AppendCertsFromPEM(caCertFile)
  288. }
  289. clientAuth := tls.NoClientCert
  290. if *s3Options.tlsVerifyClientCert {
  291. clientAuth = tls.RequireAndVerifyClientCert
  292. }
  293. httpS.TLSConfig = &tls.Config{
  294. GetCertificate: s3opt.GetCertificateWithUpdate,
  295. ClientAuth: clientAuth,
  296. ClientCAs: caCertPool,
  297. }
  298. err = security.FixTlsConfig(util.GetViper(), httpS.TLSConfig)
  299. if err != nil {
  300. glog.Fatalf("error with tls config: %v", err)
  301. }
  302. if *s3opt.portHttps == 0 {
  303. glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", util.Version(), *s3opt.port)
  304. if s3ApiLocalListener != nil {
  305. go func() {
  306. if err = httpS.ServeTLS(s3ApiLocalListener, "", ""); err != nil {
  307. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  308. }
  309. }()
  310. }
  311. if err = httpS.ServeTLS(s3ApiListener, "", ""); err != nil {
  312. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  313. }
  314. } else {
  315. glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", util.Version(), *s3opt.portHttps)
  316. s3ApiListenerHttps, s3ApiLocalListenerHttps, _ := util.NewIpAndLocalListeners(
  317. *s3opt.bindIp, *s3opt.portHttps, time.Duration(10)*time.Second)
  318. if s3ApiLocalListenerHttps != nil {
  319. go func() {
  320. if err = httpS.ServeTLS(s3ApiLocalListenerHttps, "", ""); err != nil {
  321. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  322. }
  323. }()
  324. }
  325. go func() {
  326. if err = httpS.ServeTLS(s3ApiListenerHttps, "", ""); err != nil {
  327. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  328. }
  329. }()
  330. }
  331. }
  332. if *s3opt.tlsPrivateKey == "" || *s3opt.portHttps > 0 {
  333. glog.V(0).Infof("Start Seaweed S3 API Server %s at http port %d", util.Version(), *s3opt.port)
  334. if s3ApiLocalListener != nil {
  335. go func() {
  336. if err = httpS.Serve(s3ApiLocalListener); err != nil {
  337. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  338. }
  339. }()
  340. }
  341. if err = httpS.Serve(s3ApiListener); err != nil {
  342. glog.Fatalf("S3 API Server Fail to serve: %v", err)
  343. }
  344. }
  345. return true
  346. }