-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundle.go
391 lines (336 loc) · 9.4 KB
/
bundle.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package apiGatewayConfDeploy
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"strings"
"sync/atomic"
"time"
)
const (
blobStoreUri = "/blobs/{blobId}"
)
type bundleManagerInterface interface {
initializeBundleDownloading()
downloadBlobsWithCallback(blobs []string, callback func())
deleteBlobs(blobIds []string)
Close()
}
type bundleManager struct {
blobServerUrl string
dbMan dbManagerInterface
apiMan apiManagerInterface
concurrentDownloads int
markConfigFailedAfter time.Duration
bundleRetryDelay time.Duration
bundleCleanupDelay time.Duration
downloadQueue chan *DownloadRequest
isClosed *int32
workers []*BundleDownloader
client *http.Client
}
type blobServerResponse struct {
Id string `json:"id"`
Kind string `json:"kind"`
Self string `json:"self"`
SignedUrl string `json:"signedurl"`
SignedUrlExpiryTimestamp string `json:"signedurlexpirytimestamp"`
}
func (bm *bundleManager) initializeBundleDownloading() {
atomic.StoreInt32(bm.isClosed, 0)
bm.workers = make([]*BundleDownloader, bm.concurrentDownloads)
// create workers
for i := 0; i < bm.concurrentDownloads; i++ {
worker := BundleDownloader{
id: i + 1,
workChan: make(chan *DownloadRequest),
bm: bm,
}
bm.workers[i] = &worker
worker.Start()
}
}
func (bm *bundleManager) makeDownloadRequest(blobId string, b *BunchDownloadRequest) *DownloadRequest {
if blobId == "" {
return nil
}
markFailedAt := time.Now().Add(bm.markConfigFailedAfter)
retryIn := bm.bundleRetryDelay
maxBackOff := 5 * time.Minute
return &DownloadRequest{
blobServerURL: bm.blobServerUrl,
bm: bm,
blobId: blobId,
backoffFunc: createBackoff(retryIn, maxBackOff),
markFailedAt: markFailedAt,
client: bm.client,
bunchRequest: b,
}
}
// a blocking method to enqueue download requests
func (bm *bundleManager) enqueueRequest(r *DownloadRequest) {
if atomic.LoadInt32(bm.isClosed) == 1 {
return
}
if r != nil {
bm.downloadQueue <- r
}
}
func (bm *bundleManager) downloadBlobsWithCallback(blobs []string, callback func()) {
c := &BunchDownloadRequest{
bm: bm,
blobs: blobs,
attemptCounter: new(int32),
callback: callback,
}
c.download()
}
func (bm *bundleManager) Close() {
atomic.StoreInt32(bm.isClosed, 1)
close(bm.downloadQueue)
}
func (bm *bundleManager) deleteBlobs(blobs []string) {
for _, id := range blobs {
go bm.deleteBlobById(id)
}
}
// TODO add delete support
func (bm *bundleManager) deleteBlobById(blobId string) {
}
type BunchDownloadRequest struct {
bm *bundleManager
blobs []string
attemptCounter *int32
callback func()
}
func (b *BunchDownloadRequest) download() {
//remove empty Ids
var ids []string
for _, id := range b.blobs {
if id != "" {
ids = append(ids, id)
}
}
b.blobs = ids
log.Debugf("Attempt to download blobs, len: %v", len(b.blobs))
if len(b.blobs) == 0 && b.callback != nil {
go b.callback()
return
}
*b.attemptCounter = int32(len(b.blobs))
for _, id := range b.blobs {
req := b.bm.makeDownloadRequest(id, b)
go b.bm.enqueueRequest(req)
}
}
func (b *BunchDownloadRequest) downloadAttempted() {
if atomic.AddInt32(b.attemptCounter, -1) == 0 && b.callback != nil {
go b.callback()
}
}
type DownloadRequest struct {
bm *bundleManager
blobId string
backoffFunc func()
markFailedAt time.Time
blobServerURL string
client *http.Client
bunchRequest *BunchDownloadRequest
attempted bool
}
func (r *DownloadRequest) downloadBlob() error {
log.Debugf("starting bundle download attempt for blobId=%s", r.blobId)
var err error
defer r.markAttempted(&err)
if r.checkTimeout() {
return &timeoutError{
markFailedAt: r.markFailedAt,
}
}
cleanTempFile := func(file string) {
if os.Remove(file) != nil {
log.Warnf("Unable to remove temp file %s", file)
}
}
downloadedFile, err := downloadFromURI(r.client, r.blobServerURL, r.blobId)
if err != nil {
log.Errorf("Unable to download blob file blobId=%s err:%v", r.blobId, err)
if downloadedFile != "" {
go cleanTempFile(downloadedFile)
}
return err
}
err = r.bm.dbMan.updateLocalFsLocation(r.blobId, downloadedFile)
if err != nil {
log.Errorf("updateLocalFsLocation failed: blobId=%s", r.blobId)
if downloadedFile != "" {
go cleanTempFile(downloadedFile)
}
return err
}
log.Debugf("blod downloaded and inserted: blobId=%s filename=%s", r.blobId, downloadedFile)
return nil
}
func (r *DownloadRequest) checkTimeout() bool {
if !r.markFailedAt.IsZero() && time.Now().After(r.markFailedAt) {
r.markFailedAt = time.Time{}
log.Debugf("bundle download timeout. blobId=", r.blobId)
// TODO notify gateway of this failure
return true
}
return false
}
func (r *DownloadRequest) markAttempted(errp *error) {
if !r.attempted {
r.attempted = true
err := *errp
if r.bunchRequest != nil {
r.bunchRequest.downloadAttempted()
}
if err != nil {
//TODO: insert to DB as "attempted but unsuccessful"
}
}
}
func getBlobFilePath(blobId string) string {
return path.Join(bundlePath, base64.StdEncoding.EncodeToString([]byte(blobId)))
}
func getSignedURL(client *http.Client, blobServerURL string, blobId string) (string, error) {
blobUri, err := url.Parse(blobServerURL)
if err != nil {
log.Panicf("bad url value for config %s: %s", blobUri, err)
}
blobUri.Path += strings.Replace(blobStoreUri, "{blobId}", blobId, 1)
parameters := url.Values{}
parameters.Add("action", "GET")
blobUri.RawQuery = parameters.Encode()
uri := blobUri.String()
surl, err := getUriReaderWithAuth(client, uri)
if err != nil {
log.Errorf("Unable to get signed URL from BlobServer %s: %v", uri, err)
return "", err
}
defer surl.Close()
body, err := ioutil.ReadAll(surl)
if err != nil {
log.Errorf("Invalid response from BlobServer for {%s} error: {%v}", uri, err)
return "", err
}
res := blobServerResponse{}
err = json.Unmarshal(body, &res)
if err != nil {
log.Errorf("Invalid response from BlobServer for {%s} error: {%v}", uri, err)
return "", err
}
return res.SignedUrl, nil
}
// downloadFromURI involves retrieving the signed URL for the blob, and storing the resource locally
// after downloading the resource from GCS (via the signed URL)
func downloadFromURI(client *http.Client, blobServerURL string, blobId string) (tempFileName string, err error) {
var tempFile *os.File
uri, err := getSignedURL(client, blobServerURL, blobId)
if err != nil {
log.Errorf("Unable to get signed URL for blobId {%s}, error : {%v}", blobId, err)
return
}
tempFile, err = ioutil.TempFile(bundlePath, "blob")
if err != nil {
log.Errorf("Unable to create temp file: %v", err)
return
}
defer tempFile.Close()
tempFileName = tempFile.Name()
var confReader io.ReadCloser
confReader, err = getUriReaderWithAuth(client, uri)
if err != nil {
log.Errorf("Unable to retrieve Blob %s: %v", uri, err)
return
}
defer confReader.Close()
_, err = io.Copy(tempFile, confReader)
if err != nil {
log.Errorf("Unable to write Blob %s: %v", tempFileName, err)
return
}
log.Debugf("Blob %s downloaded to: %s", uri, tempFileName)
return
}
// retrieveBundle retrieves bundle data from a URI
func getUriReaderWithAuth(client *http.Client, uriString string) (io.ReadCloser, error) {
req, err := http.NewRequest("GET", uriString, nil)
if err != nil {
return nil, err
}
// add Auth
req.Header.Add("Authorization", getBearerToken())
res, err := client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
res.Body.Close()
return nil, fmt.Errorf("GET uri %s failed with status %d", uriString, res.StatusCode)
}
return res.Body, nil
}
type BundleDownloader struct {
id int
workChan chan *DownloadRequest
bm *bundleManager
}
func (w *BundleDownloader) Start() {
go func() {
log.Debugf("started bundle downloader %d", w.id)
for req := range w.bm.downloadQueue {
log.Debugf("starting download blobId=%s", req.blobId)
err := req.downloadBlob()
if err != nil {
// timeout
if _, ok := err.(*timeoutError); ok {
continue
}
go func(r *DownloadRequest, bm *bundleManager) {
r.backoffFunc()
bm.enqueueRequest(r)
}(req, w.bm)
}
}
log.Debugf("bundle downloader %d stopped", w.id)
}()
}
// simple doubling back-off
func createBackoff(retryIn, maxBackOff time.Duration) func() {
return func() {
log.Debugf("backoff called. will retry in %s.", retryIn)
time.Sleep(retryIn)
retryIn = retryIn * time.Duration(2)
if retryIn > maxBackOff {
retryIn = maxBackOff
}
}
}
type timeoutError struct {
markFailedAt time.Time
}
func (e *timeoutError) Error() string {
return fmt.Sprintf("Timeout. markFailedAt=%v", e.markFailedAt)
}