s3storage.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // Fork from Thanos S3 Bucket support to reuse configuration options
  2. // Licensed under the Apache License 2.0
  3. // https://github.com/thanos-io/thanos/blob/main/pkg/objstore/s3/s3.go
  4. package storage
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/tls"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "strings"
  13. "time"
  14. "github.com/kubecost/cost-model/pkg/log"
  15. aws "github.com/aws/aws-sdk-go-v2/aws"
  16. awsconfig "github.com/aws/aws-sdk-go-v2/config"
  17. "github.com/minio/minio-go/v7"
  18. "github.com/minio/minio-go/v7/pkg/credentials"
  19. "github.com/minio/minio-go/v7/pkg/encrypt"
  20. "github.com/pkg/errors"
  21. "gopkg.in/yaml.v2"
  22. )
  23. type ctxKey int
  24. const (
  25. // DirDelim is the delimiter used to model a directory structure in an object store bucket.
  26. DirDelim = "/"
  27. // SSEKMS is the name of the SSE-KMS method for objectstore encryption.
  28. SSEKMS = "SSE-KMS"
  29. // SSEC is the name of the SSE-C method for objstore encryption.
  30. SSEC = "SSE-C"
  31. // SSES3 is the name of the SSE-S3 method for objstore encryption.
  32. SSES3 = "SSE-S3"
  33. // sseConfigKey is the context key to override SSE config. This feature is used by downstream
  34. // projects (eg. Cortex) to inject custom SSE config on a per-request basis. Future work or
  35. // refactoring can introduce breaking changes as far as the functionality is preserved.
  36. // NOTE: we're using a context value only because it's a very specific S3 option. If SSE will
  37. // be available to wider set of backends we should probably add a variadic option to Get() and Upload().
  38. sseConfigKey = ctxKey(0)
  39. )
  40. var DefaultConfig = S3Config{
  41. PutUserMetadata: map[string]string{},
  42. HTTPConfig: HTTPConfig{
  43. IdleConnTimeout: time.Duration(90 * time.Second),
  44. ResponseHeaderTimeout: time.Duration(2 * time.Minute),
  45. TLSHandshakeTimeout: time.Duration(10 * time.Second),
  46. ExpectContinueTimeout: time.Duration(1 * time.Second),
  47. MaxIdleConns: 100,
  48. MaxIdleConnsPerHost: 100,
  49. MaxConnsPerHost: 0,
  50. },
  51. PartSize: 1024 * 1024 * 64, // 64MB.
  52. }
  53. // Config stores the configuration for s3 bucket.
  54. type S3Config struct {
  55. Bucket string `yaml:"bucket"`
  56. Endpoint string `yaml:"endpoint"`
  57. Region string `yaml:"region"`
  58. AWSSDKAuth bool `yaml:"aws_sdk_auth"`
  59. AccessKey string `yaml:"access_key"`
  60. Insecure bool `yaml:"insecure"`
  61. SignatureV2 bool `yaml:"signature_version2"`
  62. SecretKey string `yaml:"secret_key"`
  63. PutUserMetadata map[string]string `yaml:"put_user_metadata"`
  64. HTTPConfig HTTPConfig `yaml:"http_config"`
  65. TraceConfig TraceConfig `yaml:"trace"`
  66. ListObjectsVersion string `yaml:"list_objects_version"`
  67. // PartSize used for multipart upload. Only used if uploaded object size is known and larger than configured PartSize.
  68. // NOTE we need to make sure this number does not produce more parts than 10 000.
  69. PartSize uint64 `yaml:"part_size"`
  70. SSEConfig SSEConfig `yaml:"sse_config"`
  71. STSEndpoint string `yaml:"sts_endpoint"`
  72. }
  73. // SSEConfig deals with the configuration of SSE for Minio. The following options are valid:
  74. // kmsencryptioncontext == https://docs.aws.amazon.com/kms/latest/developerguide/services-s3.html#s3-encryption-context
  75. type SSEConfig struct {
  76. Type string `yaml:"type"`
  77. KMSKeyID string `yaml:"kms_key_id"`
  78. KMSEncryptionContext map[string]string `yaml:"kms_encryption_context"`
  79. EncryptionKey string `yaml:"encryption_key"`
  80. }
  81. type TraceConfig struct {
  82. Enable bool `yaml:"enable"`
  83. }
  84. // HTTPConfig stores the http.Transport configuration for the s3 minio client.
  85. type HTTPConfig struct {
  86. IdleConnTimeout time.Duration `yaml:"idle_conn_timeout"`
  87. ResponseHeaderTimeout time.Duration `yaml:"response_header_timeout"`
  88. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  89. TLSHandshakeTimeout time.Duration `yaml:"tls_handshake_timeout"`
  90. ExpectContinueTimeout time.Duration `yaml:"expect_continue_timeout"`
  91. MaxIdleConns int `yaml:"max_idle_conns"`
  92. MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host"`
  93. MaxConnsPerHost int `yaml:"max_conns_per_host"`
  94. // Allow upstream callers to inject a round tripper
  95. Transport http.RoundTripper `yaml:"-"`
  96. }
  97. // DefaultTransport - this default transport is based on the Minio
  98. // DefaultTransport up until the following commit:
  99. // https://githus3.com/minio/minio-go/commit/008c7aa71fc17e11bf980c209a4f8c4d687fc884
  100. // The values have since diverged.
  101. func DefaultTransport(config S3Config) *http.Transport {
  102. return &http.Transport{
  103. Proxy: http.ProxyFromEnvironment,
  104. DialContext: (&net.Dialer{
  105. Timeout: 30 * time.Second,
  106. KeepAlive: 30 * time.Second,
  107. DualStack: true,
  108. }).DialContext,
  109. MaxIdleConns: config.HTTPConfig.MaxIdleConns,
  110. MaxIdleConnsPerHost: config.HTTPConfig.MaxIdleConnsPerHost,
  111. IdleConnTimeout: time.Duration(config.HTTPConfig.IdleConnTimeout),
  112. MaxConnsPerHost: config.HTTPConfig.MaxConnsPerHost,
  113. TLSHandshakeTimeout: time.Duration(config.HTTPConfig.TLSHandshakeTimeout),
  114. ExpectContinueTimeout: time.Duration(config.HTTPConfig.ExpectContinueTimeout),
  115. // A custom ResponseHeaderTimeout was introduced
  116. // to cover cases where the tcp connection works but
  117. // the server never answers. Defaults to 2 minutes.
  118. ResponseHeaderTimeout: time.Duration(config.HTTPConfig.ResponseHeaderTimeout),
  119. // Set this value so that the underlying transport round-tripper
  120. // doesn't try to auto decode the body of objects with
  121. // content-encoding set to `gzip`.
  122. //
  123. // Refer: https://golang.org/src/net/http/transport.go?h=roundTrip#L1843.
  124. DisableCompression: true,
  125. // #nosec It's up to the user to decide on TLS configs
  126. TLSClientConfig: &tls.Config{InsecureSkipVerify: config.HTTPConfig.InsecureSkipVerify},
  127. }
  128. }
  129. // S3Storage provides storage via S3
  130. type S3Storage struct {
  131. name string
  132. client *minio.Client
  133. defaultSSE encrypt.ServerSide
  134. putUserMetadata map[string]string
  135. partSize uint64
  136. listObjectsV1 bool
  137. }
  138. // parseConfig unmarshals a buffer into a Config with default HTTPConfig values.
  139. func parseConfig(conf []byte) (S3Config, error) {
  140. config := DefaultConfig
  141. if err := yaml.UnmarshalStrict(conf, &config); err != nil {
  142. return S3Config{}, err
  143. }
  144. return config, nil
  145. }
  146. // NewBucket returns a new Bucket using the provided s3 config values.
  147. func NewS3Storage(conf []byte) (*S3Storage, error) {
  148. log.Infof("Creating new S3 Storage...")
  149. config, err := parseConfig(conf)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return NewS3StorageWith(config)
  154. }
  155. // NewBucketWithConfig returns a new Bucket using the provided s3 config values.
  156. func NewS3StorageWith(config S3Config) (*S3Storage, error) {
  157. var chain []credentials.Provider
  158. log.Infof("New S3 Storage With Config: %+v", config)
  159. wrapCredentialsProvider := func(p credentials.Provider) credentials.Provider { return p }
  160. if config.SignatureV2 {
  161. wrapCredentialsProvider = func(p credentials.Provider) credentials.Provider {
  162. return &overrideSignerType{Provider: p, signerType: credentials.SignatureV2}
  163. }
  164. }
  165. if err := validate(config); err != nil {
  166. return nil, err
  167. }
  168. if config.AWSSDKAuth {
  169. chain = []credentials.Provider{
  170. wrapCredentialsProvider(&awsAuth{Region: config.Region}),
  171. }
  172. } else if config.AccessKey != "" {
  173. chain = []credentials.Provider{wrapCredentialsProvider(&credentials.Static{
  174. Value: credentials.Value{
  175. AccessKeyID: config.AccessKey,
  176. SecretAccessKey: config.SecretKey,
  177. SignerType: credentials.SignatureV4,
  178. },
  179. })}
  180. } else {
  181. chain = []credentials.Provider{
  182. wrapCredentialsProvider(&credentials.EnvAWS{}),
  183. wrapCredentialsProvider(&credentials.FileAWSCredentials{}),
  184. wrapCredentialsProvider(&credentials.IAM{
  185. Client: &http.Client{
  186. Transport: http.DefaultTransport,
  187. },
  188. Endpoint: config.STSEndpoint,
  189. }),
  190. }
  191. }
  192. // Check if a roundtripper has been set in the config
  193. // otherwise build the default transport.
  194. var rt http.RoundTripper
  195. if config.HTTPConfig.Transport != nil {
  196. rt = config.HTTPConfig.Transport
  197. } else {
  198. rt = DefaultTransport(config)
  199. }
  200. client, err := minio.New(config.Endpoint, &minio.Options{
  201. Creds: credentials.NewChainCredentials(chain),
  202. Secure: !config.Insecure,
  203. Region: config.Region,
  204. Transport: rt,
  205. })
  206. if err != nil {
  207. return nil, errors.Wrap(err, "initialize s3 client")
  208. }
  209. var sse encrypt.ServerSide
  210. if config.SSEConfig.Type != "" {
  211. switch config.SSEConfig.Type {
  212. case SSEKMS:
  213. // If the KMSEncryptionContext is a nil map the header that is
  214. // constructed by the encrypt.ServerSide object will be base64
  215. // encoded "nil" which is not accepted by AWS.
  216. if config.SSEConfig.KMSEncryptionContext == nil {
  217. config.SSEConfig.KMSEncryptionContext = make(map[string]string)
  218. }
  219. sse, err = encrypt.NewSSEKMS(config.SSEConfig.KMSKeyID, config.SSEConfig.KMSEncryptionContext)
  220. if err != nil {
  221. return nil, errors.Wrap(err, "initialize s3 client SSE-KMS")
  222. }
  223. case SSEC:
  224. key, err := ioutil.ReadFile(config.SSEConfig.EncryptionKey)
  225. if err != nil {
  226. return nil, err
  227. }
  228. sse, err = encrypt.NewSSEC(key)
  229. if err != nil {
  230. return nil, errors.Wrap(err, "initialize s3 client SSE-C")
  231. }
  232. case SSES3:
  233. sse = encrypt.NewSSE()
  234. default:
  235. sseErrMsg := errors.Errorf("Unsupported type %q was provided. Supported types are SSE-S3, SSE-KMS, SSE-C", config.SSEConfig.Type)
  236. return nil, errors.Wrap(sseErrMsg, "Initialize s3 client SSE Config")
  237. }
  238. }
  239. if config.ListObjectsVersion != "" && config.ListObjectsVersion != "v1" && config.ListObjectsVersion != "v2" {
  240. return nil, errors.Errorf("Initialize s3 client list objects version: Unsupported version %q was provided. Supported values are v1, v2", config.ListObjectsVersion)
  241. }
  242. bkt := &S3Storage{
  243. name: config.Bucket,
  244. client: client,
  245. defaultSSE: sse,
  246. putUserMetadata: config.PutUserMetadata,
  247. partSize: config.PartSize,
  248. listObjectsV1: config.ListObjectsVersion == "v1",
  249. }
  250. return bkt, nil
  251. }
  252. // Name returns the bucket name for s3.
  253. func (s3 *S3Storage) Name() string {
  254. return s3.name
  255. }
  256. // validate checks to see the config options are set.
  257. func validate(conf S3Config) error {
  258. if conf.Endpoint == "" {
  259. return errors.New("no s3 endpoint in config file")
  260. }
  261. if conf.AWSSDKAuth && conf.AccessKey != "" {
  262. return errors.New("aws_sdk_auth and access_key are mutually exclusive configurations")
  263. }
  264. if conf.AccessKey == "" && conf.SecretKey != "" {
  265. return errors.New("no s3 acccess_key specified while secret_key is present in config file; either both should be present in config or envvars/IAM should be used.")
  266. }
  267. if conf.AccessKey != "" && conf.SecretKey == "" {
  268. return errors.New("no s3 secret_key specified while access_key is present in config file; either both should be present in config or envvars/IAM should be used.")
  269. }
  270. if conf.SSEConfig.Type == SSEC && conf.SSEConfig.EncryptionKey == "" {
  271. return errors.New("encryption_key must be set if sse_config.type is set to 'SSE-C'")
  272. }
  273. if conf.SSEConfig.Type == SSEKMS && conf.SSEConfig.KMSKeyID == "" {
  274. return errors.New("kms_key_id must be set if sse_config.type is set to 'SSE-KMS'")
  275. }
  276. return nil
  277. }
  278. // FullPath returns the storage working path combined with the path provided
  279. func (s3 *S3Storage) FullPath(name string) string {
  280. name = s3.trimLeading(name)
  281. return name
  282. }
  283. // Get returns a reader for the given object name.
  284. func (s3 *S3Storage) Read(name string) ([]byte, error) {
  285. name = s3.trimLeading(name)
  286. log.Infof("S3Storage::Read(%s)", name)
  287. ctx := context.Background()
  288. return s3.getRange(ctx, name, 0, -1)
  289. }
  290. // Exists checks if the given object exists.
  291. func (s3 *S3Storage) Exists(name string) (bool, error) {
  292. name = s3.trimLeading(name)
  293. //log.Infof("S3Storage::Exists(%s)", name)
  294. ctx := context.Background()
  295. _, err := s3.client.StatObject(ctx, s3.name, name, minio.StatObjectOptions{})
  296. if err != nil {
  297. if s3.isDoesNotExist(err) {
  298. return false, nil
  299. }
  300. return false, errors.Wrap(err, "stat s3 object")
  301. }
  302. return true, nil
  303. }
  304. // Upload the contents of the reader as an object into the bucket.
  305. func (s3 *S3Storage) Write(name string, data []byte) error {
  306. name = s3.trimLeading(name)
  307. log.Infof("S3Storage::Write(%s)", name)
  308. ctx := context.Background()
  309. sse, err := s3.getServerSideEncryption(ctx)
  310. if err != nil {
  311. return err
  312. }
  313. var size int64 = int64(len(data))
  314. var partSize uint64 = 0
  315. r := bytes.NewReader(data)
  316. _, err = s3.client.PutObject(ctx, s3.name, name, r, int64(size), minio.PutObjectOptions{
  317. PartSize: partSize,
  318. ServerSideEncryption: sse,
  319. UserMetadata: s3.putUserMetadata,
  320. })
  321. if err != nil {
  322. return errors.Wrap(err, "upload s3 object")
  323. }
  324. return nil
  325. }
  326. // Attributes returns information about the specified object.
  327. func (s3 *S3Storage) Stat(name string) (*StorageInfo, error) {
  328. name = s3.trimLeading(name)
  329. //log.Infof("S3Storage::Stat(%s)", name)
  330. ctx := context.Background()
  331. objInfo, err := s3.client.StatObject(ctx, s3.name, name, minio.StatObjectOptions{})
  332. if err != nil {
  333. if s3.isDoesNotExist(err) {
  334. return nil, DoesNotExistError
  335. }
  336. return nil, err
  337. }
  338. return &StorageInfo{
  339. Name: s3.trimName(name),
  340. Size: objInfo.Size,
  341. ModTime: objInfo.LastModified,
  342. }, nil
  343. }
  344. // Delete removes the object with the given name.
  345. func (s3 *S3Storage) Remove(name string) error {
  346. name = s3.trimLeading(name)
  347. log.Infof("S3Storage::Remove(%s)", name)
  348. ctx := context.Background()
  349. return s3.client.RemoveObject(ctx, s3.name, name, minio.RemoveObjectOptions{})
  350. }
  351. func (s3 *S3Storage) List(path string) ([]*StorageInfo, error) {
  352. path = s3.trimLeading(path)
  353. log.Infof("S3Storage::List(%s)", path)
  354. ctx := context.Background()
  355. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  356. // object itself as one prefix item.
  357. if path != "" {
  358. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  359. }
  360. opts := minio.ListObjectsOptions{
  361. Prefix: path,
  362. Recursive: false,
  363. UseV1: s3.listObjectsV1,
  364. }
  365. var stats []*StorageInfo
  366. for object := range s3.client.ListObjects(ctx, s3.name, opts) {
  367. // Catch the error when failed to list objects.
  368. if object.Err != nil {
  369. return nil, object.Err
  370. }
  371. // This sometimes happens with empty buckets.
  372. if object.Key == "" {
  373. continue
  374. }
  375. // The s3 client can also return the directory itself in the ListObjects call above.
  376. if object.Key == path {
  377. continue
  378. }
  379. stats = append(stats, &StorageInfo{
  380. Name: s3.trimName(object.Key),
  381. Size: object.Size,
  382. ModTime: object.LastModified,
  383. })
  384. }
  385. return stats, nil
  386. }
  387. // trimLeading removes a leading / from the file name
  388. func (s3 *S3Storage) trimLeading(file string) string {
  389. if len(file) == 0 {
  390. return file
  391. }
  392. if file[0] == '/' {
  393. return file[1:]
  394. }
  395. return file
  396. }
  397. // trimName removes the leading directory prefix
  398. func (s3 *S3Storage) trimName(file string) string {
  399. slashIndex := strings.LastIndex(file, "/")
  400. if slashIndex < 0 {
  401. return file
  402. }
  403. name := file[slashIndex+1:]
  404. return name
  405. }
  406. // getServerSideEncryption returns the SSE to use.
  407. func (s3 *S3Storage) getServerSideEncryption(ctx context.Context) (encrypt.ServerSide, error) {
  408. if value := ctx.Value(sseConfigKey); value != nil {
  409. if sse, ok := value.(encrypt.ServerSide); ok {
  410. return sse, nil
  411. }
  412. return nil, errors.New("invalid SSE config override provided in the context")
  413. }
  414. return s3.defaultSSE, nil
  415. }
  416. // isDoesNotExist returns true if error means that object key is not found.
  417. func (s3 *S3Storage) isDoesNotExist(err error) bool {
  418. return minio.ToErrorResponse(errors.Cause(err)).Code == "NoSuchKey"
  419. }
  420. // isObjNotFound returns true if the error means that the object was not found
  421. func (s3 *S3Storage) isObjNotFound(err error) bool {
  422. return minio.ToErrorResponse(errors.Cause(err)).Code == "NotFoundObject"
  423. }
  424. func (s3 *S3Storage) getRange(ctx context.Context, name string, off, length int64) ([]byte, error) {
  425. sse, err := s3.getServerSideEncryption(ctx)
  426. if err != nil {
  427. return nil, err
  428. }
  429. opts := &minio.GetObjectOptions{ServerSideEncryption: sse}
  430. if length != -1 {
  431. if err := opts.SetRange(off, off+length-1); err != nil {
  432. return nil, err
  433. }
  434. } else if off > 0 {
  435. if err := opts.SetRange(off, 0); err != nil {
  436. return nil, err
  437. }
  438. }
  439. r, err := s3.client.GetObject(ctx, s3.name, name, *opts)
  440. if err != nil {
  441. if s3.isObjNotFound(err) {
  442. return nil, DoesNotExistError
  443. }
  444. return nil, err
  445. }
  446. // NotFoundObject error is revealed only after first Read. This does the initial GetRequest. Prefetch this here
  447. // for convenience.
  448. if _, err := r.Read(nil); err != nil {
  449. r.Close()
  450. if s3.isObjNotFound(err) {
  451. return nil, DoesNotExistError
  452. }
  453. return nil, errors.Wrap(err, "Read from S3 failed")
  454. }
  455. return ioutil.ReadAll(r)
  456. }
  457. // awsAuth retrieves credentials from the aws-sdk-go.
  458. type awsAuth struct {
  459. Region string
  460. creds aws.Credentials
  461. }
  462. // Retrieve retrieves the keys from the environment.
  463. func (a *awsAuth) Retrieve() (credentials.Value, error) {
  464. cfg, err := awsconfig.LoadDefaultConfig(context.TODO(), awsconfig.WithRegion(a.Region))
  465. if err != nil {
  466. return credentials.Value{}, errors.Wrap(err, "load AWS SDK config")
  467. }
  468. creds, err := cfg.Credentials.Retrieve(context.TODO())
  469. if err != nil {
  470. return credentials.Value{}, errors.Wrap(err, "retrieve AWS SDK credentials")
  471. }
  472. a.creds = creds
  473. return credentials.Value{
  474. AccessKeyID: creds.AccessKeyID,
  475. SecretAccessKey: creds.SecretAccessKey,
  476. SessionToken: creds.SessionToken,
  477. SignerType: credentials.SignatureV4,
  478. }, nil
  479. }
  480. // IsExpired returns if the credentials have been retrieved.
  481. func (a *awsAuth) IsExpired() bool {
  482. return a.creds.Expired()
  483. }
  484. type overrideSignerType struct {
  485. credentials.Provider
  486. signerType credentials.SignatureType
  487. }
  488. func (s *overrideSignerType) Retrieve() (credentials.Value, error) {
  489. v, err := s.Provider.Retrieve()
  490. if err != nil {
  491. return v, err
  492. }
  493. if !v.SignerType.IsAnonymous() {
  494. v.SignerType = s.signerType
  495. }
  496. return v, nil
  497. }