s3.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package loader
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/goamz/goamz/aws"
  10. "github.com/goamz/goamz/s3"
  11. "github.com/spf13/viper"
  12. )
  13. // S3 implements interface Loader, so it can be used in an mitmengine.Config struct when getting a
  14. // mitmengine.Processor.
  15. type S3 struct {
  16. configFileName string
  17. bucket *s3.Bucket
  18. }
  19. // NewS3Instance creates S3 struct from toml-styled configuration file (an implementation of a Loader)
  20. func NewS3Instance(configFileName string) (S3, error) {
  21. var s3Instance S3
  22. // Find and read the config file
  23. viper.SetConfigType("toml")
  24. // Viper is weird and only expects filenames with no extensions...
  25. viper.SetConfigName(strings.Replace(configFileName, ".toml", "", -1))
  26. viper.AddConfigPath("$GOPATH/src/github.com/cloudflare/mitmengine/loader")
  27. viper.AddConfigPath("$GOPATH/src/github.com/cloudflare/mitmengine/")
  28. viper.AddConfigPath("./")
  29. err := viper.ReadInConfig()
  30. if err != nil {
  31. return s3Instance, fmt.Errorf("fatal error config file: %s", err)
  32. }
  33. accessKey := viper.GetString("AccessKey")
  34. secretKey := viper.GetString("SecretKey")
  35. // If keys not in config file, read from environment variables
  36. if len(accessKey) == 0 {
  37. accessKey = os.Getenv("AWS_ACCESS_KEY_ID")
  38. }
  39. if len(secretKey) == 0 {
  40. secretKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
  41. }
  42. auth, err := aws.GetAuth(strings.TrimSpace(string(accessKey)), strings.TrimSpace(string(secretKey)), "", time.Time{})
  43. if err != nil {
  44. log.Fatal("could not be authorized by S3 server:", err)
  45. }
  46. s3Endpoint := viper.GetString("S3Endpoint")
  47. s3BucketEndpoint := viper.GetString("S3BucketEndpoint")
  48. region := aws.Region{
  49. S3Endpoint: s3Endpoint,
  50. S3BucketEndpoint: s3BucketEndpoint,
  51. }
  52. // use the bucket to pull fingerprint files
  53. bucketName := viper.GetString("BucketName")
  54. mitmBucket := s3.New(auth, region).Bucket(bucketName)
  55. if mitmBucket == nil {
  56. return s3Instance, fmt.Errorf("no bucket \"%s\" found at bucket endpoint %s", bucketName, s3BucketEndpoint)
  57. }
  58. return S3{
  59. configFileName: configFileName,
  60. bucket: mitmBucket,
  61. }, nil
  62. }
  63. // LoadFile implements the LoadFile function specified in Loader interface, as defined in loader.go
  64. func (s3 S3) LoadFile(fileName string) (io.ReadCloser, error) {
  65. reader, err := s3.bucket.GetReader(fileName)
  66. if err != nil {
  67. return nil, fmt.Errorf("could not read %s: %s", fileName, err)
  68. }
  69. return reader, nil
  70. }