grafana/pkg/components/imguploader/gcsuploader.go

97 lines
1.9 KiB
Go
Raw Normal View History

2017-08-04 16:46:26 -05:00
package imguploader
import (
2017-08-06 10:04:38 -05:00
"context"
"errors"
2017-08-04 17:53:23 -05:00
"fmt"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/util"
2017-08-06 10:04:38 -05:00
"golang.org/x/oauth2/google"
2017-08-04 17:53:23 -05:00
"io/ioutil"
2017-08-06 10:04:38 -05:00
"net/http"
"os"
2017-08-04 16:46:26 -05:00
)
2017-08-06 10:04:38 -05:00
type GCSUploader struct {
2017-08-04 17:53:23 -05:00
keyFile string
bucket string
log log.Logger
2017-08-04 16:46:26 -05:00
}
2017-08-06 10:04:38 -05:00
func NewGCSUploader(keyFile, bucket string) *GCSUploader {
return &GCSUploader{
2017-08-04 17:53:23 -05:00
keyFile: keyFile,
bucket: bucket,
2017-08-06 10:04:38 -05:00
log: log.New("gcsuploader"),
2017-08-04 17:53:23 -05:00
}
2017-08-04 16:46:26 -05:00
}
2017-08-06 10:04:38 -05:00
func (u *GCSUploader) Upload(imageDiskPath string) (string, error) {
key := util.GetRandomString(20) + ".png"
2017-08-04 16:46:26 -05:00
2017-08-06 10:04:38 -05:00
log.Debug("Opening key file ", u.keyFile)
ctx := context.Background()
data, err := ioutil.ReadFile(u.keyFile)
2017-08-04 17:53:23 -05:00
if err != nil {
return "", err
}
2017-08-04 16:46:26 -05:00
2017-08-06 10:04:38 -05:00
log.Debug("Creating JWT conf")
2017-08-04 16:46:26 -05:00
2017-08-07 08:17:16 -05:00
conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/devstorage.read_write")
2017-08-04 17:53:23 -05:00
if err != nil {
return "", err
}
2017-08-04 16:46:26 -05:00
2017-08-06 10:04:38 -05:00
log.Debug("Creating HTTP client")
2017-08-04 16:46:26 -05:00
2017-08-06 10:04:38 -05:00
client := conf.Client(ctx)
2017-08-04 16:46:26 -05:00
2017-08-06 10:04:38 -05:00
err = u.uploadFile(client, imageDiskPath, key)
if err != nil {
2017-08-04 17:53:23 -05:00
return "", err
}
2017-08-04 16:46:26 -05:00
2017-08-04 17:53:23 -05:00
return fmt.Sprintf("https://storage.googleapis.com/%s/%s", u.bucket, key), nil
2017-08-04 16:46:26 -05:00
}
2017-08-06 10:04:38 -05:00
func (u *GCSUploader) uploadFile(client *http.Client, imageDiskPath, key string) error {
log.Debug("Opening image file ", imageDiskPath)
fileReader, err := os.Open(imageDiskPath)
if err != nil {
return err
}
reqUrl := fmt.Sprintf(
"https://www.googleapis.com/upload/storage/v1/b/%s/o?uploadType=media&name=%s&predefinedAcl=publicRead",
u.bucket,
key,
)
log.Debug("Request URL: ", reqUrl)
req, err := http.NewRequest("POST", reqUrl, fileReader)
if err != nil {
return err
}
req.Header.Add("Content-Type", "image/png")
log.Debug("Sending POST request to GCS")
resp, err := client.Do(req)
if err != nil {
return err
}
log.Debug("GCS API response header", resp.Header)
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("GCS response status code %d", resp.StatusCode))
}
return nil
}