-
Notifications
You must be signed in to change notification settings - Fork 90
/
airgap.go
551 lines (454 loc) · 15.2 KB
/
airgap.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package handlers
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"sync"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/airgap"
"github.com/replicatedhq/kots/pkg/automation"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/store"
"github.com/replicatedhq/kots/pkg/util"
)
type CreateAppFromAirgapRequest struct {
RegistryHost string `json:"registryHost"`
Namespace string `json:"namespace"`
Username string `json:"username"`
Password string `json:"password"`
IsReadOnly bool `json:"isReadOnly"`
}
type CreateAppFromAirgapResponse struct {
}
type UpdateAppFromAirgapRequest struct {
AppID string `json:"appId"`
}
type UpdateAppFromAirgapResponse struct {
}
type AirgapBundleProgressResponse struct {
Progress float64 `json:"progress"`
}
type AirgapBundleExistsResponse struct {
Exists bool `json:"exists"`
}
type GetAirgapUploadConfigResponse struct {
SimultaneousUploads int `json:"simultaneousUploads"`
}
var uploadedAirgapBundleChunks = map[string]struct{}{}
var chunkLock sync.Mutex
var fileLock sync.Mutex
func (h *Handler) GetAirgapInstallStatus(w http.ResponseWriter, r *http.Request) {
appID, err := store.GetStore().GetAppIDFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(errors.Wrapf(err, "failed to app for slug %s", mux.Vars(r)["appSlug"]))
w.WriteHeader(http.StatusInternalServerError)
return
}
status, err := store.GetStore().GetAirgapInstallStatus(appID)
if err != nil {
logger.Error(errors.Wrapf(err, "failed to get install status for app %s", mux.Vars(r)["appSlug"]))
w.WriteHeader(500)
return
}
JSON(w, 200, status)
}
func (h *Handler) ResetAirgapInstallStatus(w http.ResponseWriter, r *http.Request) {
appID, err := store.GetStore().GetAppIDFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
err = store.GetStore().ResetAirgapInstallInProgress(appID)
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (h *Handler) GetAirgapUploadConfig(w http.ResponseWriter, r *http.Request) {
response := GetAirgapUploadConfigResponse{}
i, _ := strconv.Atoi(os.Getenv("AIRGAP_UPLOAD_PARALLELISM"))
if i > 0 {
response.SimultaneousUploads = i
} else {
response.SimultaneousUploads = 3
}
JSON(w, http.StatusOK, response)
}
func (h *Handler) CheckAirgapBundleChunk(w http.ResponseWriter, r *http.Request) {
resumableIdentifier := r.FormValue("resumableIdentifier")
resumableChunkNumber := r.FormValue("resumableChunkNumber")
resumableTotalChunks := r.FormValue("resumableTotalChunks")
if resumableIdentifier == "" || resumableChunkNumber == "" {
logger.Error(errors.New("missing resumable upload parameters"))
w.WriteHeader(http.StatusBadRequest)
return
}
chunkNumber, err := strconv.ParseInt(resumableChunkNumber, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse chunk number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
totalChunks, err := strconv.ParseInt(resumableTotalChunks, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
chunkKey := getChunkKey(resumableIdentifier, chunkNumber)
if !isChunkPresent(chunkKey) {
w.WriteHeader(http.StatusNoContent) // instead of 404 to avoid unwarranted notices in browser consoles
return
}
if chunkNumber%25 == 0 {
logger.Infof("checking chunk %d / %d. chunk key: %s", chunkNumber, totalChunks, chunkKey)
}
JSON(w, http.StatusOK, "")
}
func (h *Handler) UploadAirgapBundleChunk(w http.ResponseWriter, r *http.Request) {
resumableIdentifier := r.FormValue("resumableIdentifier")
resumableTotalChunks := r.FormValue("resumableTotalChunks")
resumableTotalSize := r.FormValue("resumableTotalSize")
resumableChunkNumber := r.FormValue("resumableChunkNumber")
resumableChunkSize := r.FormValue("resumableChunkSize")
totalChunks, err := strconv.ParseInt(resumableTotalChunks, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
totalSize, err := strconv.ParseInt(resumableTotalSize, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total size as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
chunkNumber, err := strconv.ParseInt(resumableChunkNumber, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse chunk number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
chunkSize, err := strconv.ParseInt(resumableChunkSize, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse chunk size as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
// read chunk data
airgapBundleChunk, _, err := r.FormFile("file")
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer airgapBundleChunk.Close()
airgapBundlePath := getAirgapBundlePath(resumableIdentifier)
func() {
// create airgap bundle file if not exists
fileLock.Lock()
defer fileLock.Unlock()
_, err = os.Stat(airgapBundlePath)
if os.IsNotExist(err) {
// this is a new upload. assume only one upload can happen at a time and free up some ephemeral storage.
cleanupTempAirgapBundles()
f, err := os.Create(airgapBundlePath)
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
if err := f.Truncate(totalSize); err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
} else if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}()
airgapBundle, err := os.OpenFile(airgapBundlePath, os.O_RDWR, 0644)
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer airgapBundle.Close()
chunkOffset := (chunkNumber - 1) * chunkSize
if _, err := airgapBundle.Seek(chunkOffset, 0); err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if _, err := io.Copy(airgapBundle, airgapBundleChunk); err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
chunkKey := getChunkKey(resumableIdentifier, chunkNumber)
addUploadedChank(chunkKey)
if chunkNumber%25 == 0 {
logger.Infof("written chunk number %d / %d. bundle id: %s", chunkNumber, totalChunks, resumableIdentifier)
}
// check if upload is complete
uploadComplete := isUploadComplete(resumableIdentifier, totalChunks)
if uploadComplete {
logger.Infof("bundle upload complete. bundle id: %s", resumableIdentifier)
}
JSON(w, http.StatusOK, "")
}
func (h *Handler) AirgapBundleProgress(w http.ResponseWriter, r *http.Request) {
identifier := mux.Vars(r)["identifier"]
totalChunksStr := mux.Vars(r)["totalChunks"]
totalChunks, err := strconv.ParseInt(totalChunksStr, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
uploadProgress := getUploadProgress(identifier, totalChunks)
airgapBundleProgressResponse := AirgapBundleProgressResponse{
Progress: uploadProgress,
}
JSON(w, http.StatusOK, airgapBundleProgressResponse)
}
func (h *Handler) AirgapBundleExists(w http.ResponseWriter, r *http.Request) {
identifier := mux.Vars(r)["identifier"]
totalChunksStr := mux.Vars(r)["totalChunks"]
totalChunks, err := strconv.ParseInt(totalChunksStr, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
uploadComplete := isUploadComplete(identifier, totalChunks)
airgapBundleExistsResponse := AirgapBundleExistsResponse{
Exists: uploadComplete,
}
JSON(w, http.StatusOK, airgapBundleExistsResponse)
}
func (h *Handler) UpdateAppFromAirgap(w http.ResponseWriter, r *http.Request) {
updateAppFromAirgapRequest := UpdateAppFromAirgapRequest{}
if err := json.NewDecoder(r.Body).Decode(&updateAppFromAirgapRequest); err != nil {
logger.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
a, err := store.GetStore().GetApp(updateAppFromAirgapRequest.AppID)
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
identifier := mux.Vars(r)["identifier"]
airgapBundlePath := getAirgapBundlePath(identifier)
totalChunksStr := mux.Vars(r)["totalChunks"]
totalChunks, err := strconv.ParseInt(totalChunksStr, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
// this is to avoid a race condition where the UI polls the task status before it is set by the goroutine
if err := store.GetStore().SetTaskStatus("update-download", "Processing...", "running"); err != nil {
logger.Error(errors.Wrap(err, "failed to set task status"))
w.WriteHeader(http.StatusInternalServerError)
return
}
go func() {
if err := airgap.UpdateAppFromAirgap(a, airgapBundlePath, false, false); err != nil {
logger.Error(errors.Wrap(err, "failed to update app from airgap bundle"))
// if NoRetry is set, we stll want to clean up immediately
cause := errors.Cause(err)
if err, ok := cause.(util.ActionableError); !ok || !err.NoRetry {
return
}
}
if err := cleanUp(identifier, totalChunks); err != nil {
logger.Error(errors.Wrap(err, "failed to clean up"))
}
}()
updateAppFromAirgapResponse := UpdateAppFromAirgapResponse{}
JSON(w, http.StatusAccepted, updateAppFromAirgapResponse)
}
func (h *Handler) CreateAppFromAirgap(w http.ResponseWriter, r *http.Request) {
createAppFromAirgapRequest := CreateAppFromAirgapRequest{}
if err := json.NewDecoder(r.Body).Decode(&createAppFromAirgapRequest); err != nil {
logger.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
pendingApp, err := store.GetStore().GetPendingAirgapUploadApp()
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var registryHost, namespace, username, password string
var isReadOnly bool
registryHost, username, password, err = kotsutil.GetKurlRegistryCreds()
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// if found kurl registry creds, use kurl registry
if registryHost != "" {
namespace = pendingApp.Slug
} else {
registryHost = createAppFromAirgapRequest.RegistryHost
namespace = createAppFromAirgapRequest.Namespace
username = createAppFromAirgapRequest.Username
password = createAppFromAirgapRequest.Password
isReadOnly = createAppFromAirgapRequest.IsReadOnly
}
identifier := mux.Vars(r)["identifier"]
airgapBundlePath := getAirgapBundlePath(identifier)
totalChunksStr := mux.Vars(r)["totalChunks"]
totalChunks, err := strconv.ParseInt(totalChunksStr, 10, 64)
if err != nil {
logger.Error(errors.Wrap(err, "failed to parse total chunks number as integer"))
w.WriteHeader(http.StatusBadRequest)
return
}
go func() {
createAppOpts := airgap.CreateAirgapAppOpts{
PendingApp: pendingApp,
AirgapPath: airgapBundlePath,
RegistryHost: registryHost,
RegistryNamespace: namespace,
RegistryUsername: username,
RegistryPassword: password,
RegistryIsReadOnly: isReadOnly,
IsAutomated: false,
SkipPreflights: false,
}
if err := airgap.CreateAppFromAirgap(createAppOpts); err != nil {
logger.Error(errors.Wrap(err, "failed to create app from airgap bundle"))
// if NoRetry is set, we stll want to clean up immediately
cause := errors.Cause(err)
if err, ok := cause.(util.ActionableError); !ok || !err.NoRetry {
return
}
}
if err := cleanUp(identifier, totalChunks); err != nil {
logger.Error(errors.Wrap(err, "failed to clean up"))
}
}()
createAppFromAirgapResponse := CreateAppFromAirgapResponse{}
JSON(w, http.StatusAccepted, createAppFromAirgapResponse)
}
func getChunkKey(uploadedFileIdentifier string, chunkNumber int64) string {
return fmt.Sprintf("%s_part_%d", uploadedFileIdentifier, chunkNumber)
}
func getAirgapBundlePath(uploadedFileIdentifier string) string {
return filepath.Join(os.TempDir(), fmt.Sprintf("%s.chunks.airgap", uploadedFileIdentifier))
}
func cleanupTempAirgapBundles() {
glob := filepath.Join(os.TempDir(), "*.chunks.airgap")
files, err := filepath.Glob(glob)
if err != nil {
logger.Error(errors.Wrap(err, "failed to list temp airgap bundles"))
return
}
for _, file := range files {
err := os.Remove(file)
if err != nil {
logger.Error(errors.Wrap(err, "failed to delete temp airgap bundle"))
}
}
}
func addUploadedChank(chunkKey string) {
chunkLock.Lock()
defer chunkLock.Unlock()
uploadedAirgapBundleChunks[chunkKey] = struct{}{}
}
func isChunkPresent(chunkKey string) bool {
chunkLock.Lock()
defer chunkLock.Unlock()
_, ok := uploadedAirgapBundleChunks[chunkKey]
return ok
}
func getUploadProgress(uploadedFileIdentifier string, totalChunks int64) float64 {
chunkLock.Lock()
defer chunkLock.Unlock()
var numOfUploadedChunks int64 = 0
var i int64
for i = 1; i <= totalChunks; i++ {
chunkKey := getChunkKey(uploadedFileIdentifier, i)
if _, ok := uploadedAirgapBundleChunks[chunkKey]; ok {
numOfUploadedChunks++
}
}
return float64(numOfUploadedChunks) / float64(totalChunks)
}
func isUploadComplete(uploadedFileIdentifier string, totalChunks int64) bool {
chunkLock.Lock()
defer chunkLock.Unlock()
isUploadComplete := true
var i int64
for i = 1; i <= totalChunks; i++ {
chunkKey := getChunkKey(uploadedFileIdentifier, i)
if _, ok := uploadedAirgapBundleChunks[chunkKey]; !ok {
isUploadComplete = false
}
}
return isUploadComplete
}
func cleanUp(uploadedFileIdentifier string, totalChunks int64) error {
chunkLock.Lock()
defer chunkLock.Unlock()
var i int64
for i = 1; i <= totalChunks; i++ {
chunkKey := getChunkKey(uploadedFileIdentifier, i)
delete(uploadedAirgapBundleChunks, chunkKey)
}
airgapBundlePath := getAirgapBundlePath(uploadedFileIdentifier)
if err := os.RemoveAll(airgapBundlePath); err != nil {
return errors.Wrap(err, "failed to remove airgap bundle")
}
return nil
}
func (h *Handler) UploadInitialAirgapApp(w http.ResponseWriter, r *http.Request) {
if err := requireValidKOTSToken(w, r); err != nil {
logger.Error(errors.Wrap(err, "failed to validate token"))
return
}
appSlug := r.FormValue("appSlug")
archiveFile, archiveHeader, err := r.FormFile("appArchive")
if err != nil {
logger.Error(errors.Wrap(err, "failed to get form file reader"))
w.WriteHeader(http.StatusInternalServerError)
return
}
defer archiveFile.Close()
appArchive, err := ioutil.ReadAll(archiveFile)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get read form file"))
w.WriteHeader(http.StatusInternalServerError)
return
}
files := map[string][]byte{
archiveHeader.Filename: appArchive,
}
err = automation.AirgapInstall(appSlug, files)
if err != nil {
logger.Error(errors.Wrap(err, "failed to install app"))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}