-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcs.go
99 lines (73 loc) · 1.66 KB
/
gcs.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
"log"
"path/filepath"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
)
type gcsClient struct {
gcs *storage.Client
config config
parser *chunksParser
}
func (c *gcsClient) createClient(config config) {
client, err := storage.NewClient(config.Context)
if err != nil {
log.Fatalf("Failed to create GCS client; %v", err)
}
c.gcs = client
c.config = config
}
func (c *gcsClient) close() {
err := c.gcs.Close()
if err != nil {
log.Fatal(err)
}
}
func (c *gcsClient) downloadAndProcessChunks() {
c.parser = &chunksParser{
LokiAddress: c.config.LokiAddress,
}
bucket := c.gcs.Bucket(c.config.BucketName)
query := &storage.Query{Prefix: ""}
err := query.SetAttrSelection([]string{"Name", "Updated"})
if err != nil {
log.Fatal(err)
}
objs := bucket.Objects(c.config.Context, query)
for {
attrs, err := objs.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
path := c.saveChunk(bucket, attrs.Name)
c.parser.ParseAndSaveChunk(path)
}
}
func (c *gcsClient) saveChunk(bucket *storage.BucketHandle, name string) string {
obj, err := bucket.Object(name).NewReader(c.config.Context)
if err != nil {
log.Fatal(err)
}
file, err := ioutil.ReadAll(obj)
defer obj.Close()
if err != nil {
log.Fatal(err)
}
hasher := md5.New()
hasher.Write([]byte(name))
path := filepath.FromSlash(c.config.ChunksPath + hex.EncodeToString(hasher.Sum(nil)))
err = ioutil.WriteFile(path, file, 0644)
if err != nil {
log.Fatalf("cannot write chunk: %v", err)
} else {
log.Printf("chunk %v saved successfully\n", name)
}
return path
}