/
gce.go
62 lines (50 loc) · 1.75 KB
/
gce.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"log"
"os"
"path/filepath"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
storage "google.golang.org/api/storage/v1"
)
const (
scope = storage.DevstorageFullControlScope
)
/**
* Uploads the file at the specified path to a GCS bucket as specified
* by the environment variable BUCKET_NAME
*
* @param { string } filePath - The path to the file to upload
* @param { *CommonMetadata } metaData - The cloud instance metadata
*/
func uploadToGcs(filePath string, metaData *CommonMetadata) {
var bucket = getBucket()
client, err := google.DefaultClient(context.Background(), scope)
if err != nil {
log.Fatal("Unable to establish default client for GCE.")
}
service, err := storage.New(client)
if err != nil {
log.Fatal("Unable to create storage service.")
}
file, err := os.Open(filePath)
if err != nil {
log.Printf("Error reading file at: ", filePath)
log.Fatal(err)
}
log.Printf("File: %s\n", filepath.Base(filePath))
// sanitize path to remove initial `/data` from filepath for upload
sanitizedPath := filePath[5:len(filePath)]
// object name is in the format of: <machine_hostname>-<instance_id>/path/to/upload/file
obj := &storage.Object{
Name: metaData.hostname + "-" + metaData.instance_id + sanitizedPath,
}
// SDK should use the Google service account for auth creds
result, err := service.Objects.Insert(bucket, obj).Media(file).Do()
if err != nil {
log.Printf("Error encountered. Unable to upload to GCS... ", err)
} else {
log.Printf("Successfully uploaded object:\n %v\n to GCS at location:\n %v\n\n", result.Name, result.SelfLink)
}
file.Close()
}