-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmain.go
240 lines (206 loc) · 5.65 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/cdnjs/tools/audit"
"github.com/cdnjs/tools/metrics"
"github.com/cdnjs/tools/sandbox"
"github.com/cdnjs/tools/sentry"
"cloud.google.com/go/pubsub"
"github.com/pkg/errors"
)
var (
PROJECT = os.Getenv("PROJECT")
SUBSCRIPTION = os.Getenv("SUBSCRIPTION")
)
func init() {
sentry.Init()
}
func main() {
ctx := context.Background()
client, err := pubsub.NewClient(ctx, PROJECT)
if err != nil {
log.Fatalf("could not create pubsub Client: %v", err)
}
sub := client.Subscription(SUBSCRIPTION)
sub.ReceiveSettings.Synchronous = true
sub.ReceiveSettings.MaxOutstandingMessages = 5
sub.ReceiveSettings.NumGoroutines = runtime.NumCPU()
if err := sandbox.Init(ctx); err != nil {
log.Fatalf("failed to init sandbox: %s", err)
}
for {
log.Printf("started consuming messages\n")
if err := consume(client, sub); err != nil {
log.Fatalf("could not pull messages: %s", err)
}
}
}
type Message struct {
OutgoingSignedURL string `json:"outgoingSignedURL"`
Tar string `json:"tar"`
Pkg string `json:"package"`
Version string `json:"version"`
Config *json.RawMessage `json:"config"`
}
func consume(client *pubsub.Client, sub *pubsub.Subscription) error {
ctx := context.Background()
err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
log.Printf("received message: %s\n", msg.Data)
msg.Ack()
if err := processMessage(ctx, msg.Data); err != nil {
log.Printf("failed to process message: %s\n", err)
}
})
if err != nil {
return errors.Wrap(err, "could not receive from subscription")
}
return nil
}
func processMessage(ctx context.Context, data []byte) error {
var message Message
if err := json.Unmarshal(data, &message); err != nil {
return errors.Wrap(err, "failed to parse")
}
inDir, outDir, err := sandbox.Setup()
if err != nil {
return errors.Wrap(err, "failed to setup sandbox")
}
defer os.RemoveAll(inDir)
defer os.RemoveAll(outDir)
if err := writeConfig(inDir, message.Config); err != nil {
return errors.Wrap(err, "failed to write configuration")
}
if err := download(inDir, message.Tar); err != nil {
return errors.Wrapf(err, "failed to download: %s", message.Tar)
}
name := fmt.Sprintf("%s_%s", message.Pkg, message.Version)
logs, err := sandbox.Run(ctx, name, inDir, outDir)
if err != nil {
return errors.Wrap(err, "failed to run sandbox")
}
log.Println("logs", len(logs), logs)
if err := audit.ProcessedVersion(ctx, message.Pkg, message.Version, logs); err != nil {
return errors.Wrap(err, "could not post audit")
}
if err := metrics.NewUpdateProccessed(); err != nil {
return errors.Wrap(err, "could not report metrics")
}
log.Printf("compressing %s\n", outDir)
var buff bytes.Buffer
if err := compress(outDir, &buff); err != nil {
return errors.Wrap(err, "failed to compress out dir")
}
log.Println("uploading")
if err := uploadToOutgoing(buff, message); err != nil {
return errors.Wrap(err, "failed to upload to outgoing bucket")
}
return nil
}
func uploadToOutgoing(content bytes.Buffer, msg Message) error {
r := bytes.NewReader(content.Bytes())
req, err := http.NewRequest("PUT", msg.OutgoingSignedURL, r)
if err != nil {
return errors.Wrap(err, "failed to create request")
}
encodedConfig := b64.StdEncoding.EncodeToString(*msg.Config)
req.Header.Set("x-goog-meta-package", msg.Pkg)
req.Header.Set("x-goog-meta-version", msg.Version)
req.Header.Set("x-goog-meta-config", encodedConfig)
res, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Wrap(err, "request failed")
}
if res.StatusCode != 200 {
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "could not read response body")
}
log.Printf("returned %s: %s\n", res.Status, string(bodyBytes))
} else {
log.Println("OK")
}
return nil
}
func writeConfig(dstDir string, config *json.RawMessage) error {
if err := ioutil.WriteFile(path.Join(dstDir, "config.json"), *config, 0644); err != nil {
return errors.Wrap(err, "could not write config file")
}
return nil
}
func download(dstDir string, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
dst, err := os.Create(path.Join(dstDir, "new-version.tgz"))
if err != nil {
return errors.Wrap(err, "could not write tmp file")
}
defer dst.Close()
_, err = io.Copy(dst, resp.Body)
return err
}
func compress(src string, buf io.Writer) error {
// tar > gzip > buf
zr := gzip.NewWriter(buf)
tw := tar.NewWriter(zr)
// walk through every file in the folder
err := filepath.Walk(src, func(file string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
// generate tar header
header, err := tar.FileInfoHeader(fi, file)
if err != nil {
return err
}
// remove the /tmp/out** prefix
relFile := strings.ReplaceAll(file, src, "")
// must provide real name
// (see https://golang.org/src/archive/tar/common.go?#L626)
header.Name = filepath.ToSlash(relFile)
// write header
if err := tw.WriteHeader(header); err != nil {
return err
}
// if not a dir, write file content
if !fi.IsDir() {
data, err := os.Open(file)
if err != nil {
return err
}
if _, err := io.Copy(tw, data); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
// produce tar
if err := tw.Close(); err != nil {
return err
}
// produce gzip
if err := zr.Close(); err != nil {
return err
}
return nil
}