gcsuploader.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package imguploader
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "path"
  9. "github.com/grafana/grafana/pkg/infra/log"
  10. "github.com/grafana/grafana/pkg/util"
  11. "golang.org/x/oauth2/google"
  12. )
  13. const (
  14. tokenUrl string = "https://www.googleapis.com/auth/devstorage.read_write" // #nosec
  15. uploadUrl string = "https://www.googleapis.com/upload/storage/v1/b/%s/o?uploadType=media&name=%s&predefinedAcl=publicRead"
  16. )
  17. type GCSUploader struct {
  18. keyFile string
  19. bucket string
  20. path string
  21. log log.Logger
  22. }
  23. func NewGCSUploader(keyFile, bucket, path string) *GCSUploader {
  24. return &GCSUploader{
  25. keyFile: keyFile,
  26. bucket: bucket,
  27. path: path,
  28. log: log.New("gcsuploader"),
  29. }
  30. }
  31. func (u *GCSUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) {
  32. fileName := util.GetRandomString(20) + ".png"
  33. key := path.Join(u.path, fileName)
  34. u.log.Debug("Opening key file ", u.keyFile)
  35. data, err := ioutil.ReadFile(u.keyFile)
  36. if err != nil {
  37. return "", err
  38. }
  39. u.log.Debug("Creating JWT conf")
  40. conf, err := google.JWTConfigFromJSON(data, tokenUrl)
  41. if err != nil {
  42. return "", err
  43. }
  44. u.log.Debug("Creating HTTP client")
  45. client := conf.Client(ctx)
  46. err = u.uploadFile(client, imageDiskPath, key)
  47. if err != nil {
  48. return "", err
  49. }
  50. return fmt.Sprintf("https://storage.googleapis.com/%s/%s", u.bucket, key), nil
  51. }
  52. func (u *GCSUploader) uploadFile(client *http.Client, imageDiskPath, key string) error {
  53. u.log.Debug("Opening image file ", imageDiskPath)
  54. fileReader, err := os.Open(imageDiskPath)
  55. if err != nil {
  56. return err
  57. }
  58. defer fileReader.Close()
  59. reqUrl := fmt.Sprintf(uploadUrl, u.bucket, key)
  60. u.log.Debug("Request URL: ", reqUrl)
  61. req, err := http.NewRequest("POST", reqUrl, fileReader)
  62. if err != nil {
  63. return err
  64. }
  65. req.Header.Add("Content-Type", "image/png")
  66. u.log.Debug("Sending POST request to GCS")
  67. resp, err := client.Do(req)
  68. if err != nil {
  69. return err
  70. }
  71. if resp.StatusCode != 200 {
  72. return fmt.Errorf("GCS response status code %d", resp.StatusCode)
  73. }
  74. return nil
  75. }