s3_sessions.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package s3_backend
  2. import (
  3. "fmt"
  4. "sync"
  5. "github.com/aws/aws-sdk-go/aws"
  6. "github.com/aws/aws-sdk-go/aws/credentials"
  7. "github.com/aws/aws-sdk-go/aws/session"
  8. "github.com/aws/aws-sdk-go/service/s3"
  9. "github.com/aws/aws-sdk-go/service/s3/s3iface"
  10. )
  11. var (
  12. s3Sessions = make(map[string]s3iface.S3API)
  13. sessionsLock sync.RWMutex
  14. )
  15. func getSession(region string) (s3iface.S3API, bool) {
  16. sessionsLock.RLock()
  17. defer sessionsLock.RUnlock()
  18. sess, found := s3Sessions[region]
  19. return sess, found
  20. }
  21. func createSession(awsAccessKeyId, awsSecretAccessKey, region, endpoint string) (s3iface.S3API, error) {
  22. sessionsLock.Lock()
  23. defer sessionsLock.Unlock()
  24. if t, found := s3Sessions[region]; found {
  25. return t, nil
  26. }
  27. config := &aws.Config{
  28. Region: aws.String(region),
  29. Endpoint: aws.String(endpoint),
  30. }
  31. if awsAccessKeyId != "" && awsSecretAccessKey != "" {
  32. config.Credentials = credentials.NewStaticCredentials(awsAccessKeyId, awsSecretAccessKey, "")
  33. }
  34. sess, err := session.NewSession(config)
  35. if err != nil {
  36. return nil, fmt.Errorf("create aws session in region %s: %v", region, err)
  37. }
  38. t := s3.New(sess)
  39. s3Sessions[region] = t
  40. return t, nil
  41. }
  42. func deleteFromS3(sess s3iface.S3API, sourceBucket string, sourceKey string) (err error) {
  43. _, err = sess.DeleteObject(&s3.DeleteObjectInput{
  44. Bucket: aws.String(sourceBucket),
  45. Key: aws.String(sourceKey),
  46. })
  47. return err
  48. }