-
Notifications
You must be signed in to change notification settings - Fork 88
/
airgap.go
328 lines (277 loc) · 8.12 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
package main
import "C"
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/docker/distribution/reference"
"github.com/mholt/archiver"
"github.com/pkg/errors"
kotsv1beta1 "github.com/replicatedhq/kots/kotskinds/apis/kots/v1beta1"
kotsscheme "github.com/replicatedhq/kots/kotskinds/client/kotsclientset/scheme"
"github.com/replicatedhq/kots/pkg/pull"
"k8s.io/client-go/kubernetes/scheme"
)
type ImageRef struct {
Domain string
Name string
Tag string
Digest string
}
//export RewriteAndPushImageName
func RewriteAndPushImageName(imageFile, image, registryHost, registryOrg, username, password string) int {
imageRef, err := parseImageRef(image)
if err != nil {
fmt.Printf("failed to parse image %s: %s\n", image, err)
return 1
}
localImage := imageRefToString(imageRef, registryHost, registryOrg)
cmdArgs := []string{
"copy",
"--dest-tls-verify=false",
}
if len(username) > 0 && len(password) > 0 {
cmdArgs = append(cmdArgs, fmt.Sprintf("--dest-creds=%s:%s", username, password))
}
cmdArgs = append(cmdArgs,
fmt.Sprintf("oci-archive:%s", imageFile),
fmt.Sprintf("docker://%s", localImage),
)
cmd := exec.Command("skopeo", cmdArgs...)
cmdOutput, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("run failed with output: %s\n", cmdOutput)
return 1
}
return 0
}
func parseImageRef(image string) (*ImageRef, error) {
ref := &ImageRef{}
// named, err := reference.ParseNormalizedNamed(image)
parsed, err := reference.ParseAnyReference(image)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse image name %q", image)
}
if named, ok := parsed.(reference.Named); ok {
ref.Domain = reference.Domain(named)
ref.Name = named.Name()
} else {
return nil, errors.New(fmt.Sprintf("unsupported ref type: %T", parsed))
}
if tagged, ok := parsed.(reference.Tagged); ok {
ref.Tag = tagged.Tag()
} else if can, ok := parsed.(reference.Canonical); ok {
ref.Digest = can.Digest().String()
} else {
ref.Tag = "latest"
}
return ref, nil
}
func imageRefToString(ref *ImageRef, registryHost, registryOrg string) string {
pathParts := strings.Split(ref.Name, "/")
imageName := fmt.Sprintf("%s/%s", registryOrg, pathParts[len(pathParts)-1])
// there might be a way to do this with reference package too
if ref.Digest != "" {
return fmt.Sprintf("%s/%s@sha256:%s", registryHost, imageName, ref.Digest)
}
return fmt.Sprintf("%s/%s:%s", registryHost, imageName, ref.Tag)
}
//export PullFromAirgap
func PullFromAirgap(licenseData, airgapDir, downstream, outputFile, registryHost, registryNamesapce string) int {
workspace, err := ioutil.TempDir("", "kots-airgap")
if err != nil {
fmt.Printf("failed to create temp dir: %s\n", err)
return 1
}
defer os.RemoveAll(workspace)
// releaseDir is the contents of the release tar (yaml, no images)
releaseDir, err := extractAppRelease(workspace, airgapDir)
if err != nil {
fmt.Printf("failed to extract app release: %s\n", err)
return 1
}
kotsscheme.AddToScheme(scheme.Scheme)
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, _, err := decode([]byte(licenseData), nil, nil)
if err != nil {
fmt.Printf("failed to decode license data: %s\n", err.Error())
return 1
}
license := obj.(*kotsv1beta1.License)
licenseFile, err := ioutil.TempFile("", "kots")
if err != nil {
fmt.Printf("failed to create temp file: %s\n", err)
return 1
}
defer os.Remove(licenseFile.Name())
if err := ioutil.WriteFile(licenseFile.Name(), []byte(licenseData), 0644); err != nil {
fmt.Printf("failed to write license to temp file: %s\n", err.Error())
return 1
}
// pull to a tmp dir
tmpRoot, err := ioutil.TempDir("", "kots")
if err != nil {
fmt.Printf("failed to create temp root path: %s\n", err.Error())
return 1
}
defer os.RemoveAll(tmpRoot)
pullOptions := pull.PullOptions{
Downstreams: []string{downstream},
LocalPath: releaseDir,
LicenseFile: licenseFile.Name(),
ExcludeKotsKinds: true,
RootDir: tmpRoot,
ExcludeAdminConsole: true,
RewriteImages: pull.RewriteImages{
ImageFiles: filepath.Join(airgapDir, "images"),
Host: registryHost,
Namespace: registryNamesapce,
},
}
if _, err := pull.Pull(fmt.Sprintf("replicated://%s", license.Spec.AppSlug), pullOptions); err != nil {
fmt.Printf("failed to pull upstream: %s\n", err.Error())
return 1
}
// make an archive
tarGz := archiver.TarGz{
Tar: &archiver.Tar{
ImplicitTopLevelFolder: true,
},
}
// TODO: Rewrite images....
paths := []string{
filepath.Join(tmpRoot, "upstream"),
filepath.Join(tmpRoot, "base"),
filepath.Join(tmpRoot, "overlays"),
}
if err := tarGz.Archive(paths, outputFile); err != nil {
fmt.Printf("failed to write archive: %s", err.Error())
return 1
}
return 0
}
func downloadAirgapAchive(workspace string, airgapURL string) (string, error) {
resp, err := http.Get(airgapURL)
if err != nil {
return "", errors.Wrap(err, "failed to download file")
}
destDir := filepath.Join(workspace, "extracted-airgap")
if err := os.Mkdir(destDir, 0744); err != nil {
return "", errors.Wrap(err, "failed to create tmp dir")
}
if resp.StatusCode != http.StatusOK {
return "", errors.Wrapf(err, "unexpected status code: %v", resp.StatusCode)
}
defer resp.Body.Close()
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return "", errors.Wrapf(err, "unexpected status code: %v", resp.StatusCode)
}
defer gzipReader.Close()
tarReader := tar.NewReader(gzipReader)
for {
hdr, err := tarReader.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return "", errors.Wrap(err, "failed to expand archive")
}
if hdr.Typeflag != tar.TypeReg {
// we don't expat anything but files in our archives...
continue
}
fileName := filepath.Join(destDir, hdr.Name)
if err := os.MkdirAll(filepath.Dir(fileName), 0744); err != nil {
return "", errors.Wrapf(err, "failed to create path %q", filepath.Dir(fileName))
}
err = func() error { // func so we can defer close files... /shrug
fileWriter, err := os.Create(fileName)
if err != nil {
return errors.Wrapf(err, "failed to create file %q", fileName)
}
defer fileWriter.Close()
if _, err := io.Copy(fileWriter, tarReader); err != nil {
return errors.Wrapf(err, "failed to write file %q", fileName)
}
return nil
}()
if err != nil {
return "", err
}
}
return destDir, nil
}
func extractAppRelease(workspace string, airgapDir string) (string, error) {
files, err := ioutil.ReadDir(airgapDir)
if err != nil {
return "", errors.Wrapf(err, "failed to read airgap dir")
}
destDir := filepath.Join(workspace, "extracted-app-release")
if err := os.Mkdir(destDir, 0744); err != nil {
return "", errors.Wrap(err, "failed to create tmp dir")
}
numExtracted := 0
for _, file := range files {
if file.IsDir() { // TODO: support nested dirs?
continue
}
err := extractOneArchive(filepath.Join(airgapDir, file.Name()), destDir)
if err != nil {
fmt.Printf("ignoring file %q\n", file.Name())
continue
}
numExtracted++
}
if numExtracted == 0 {
return "", errors.New("no release found in airgap archive")
}
return destDir, nil
}
func extractOneArchive(tgzFile string, destDir string) error {
fileReader, err := os.Open(tgzFile)
if err != nil {
return errors.Wrap(err, "failed to open release file")
}
gzReader, err := gzip.NewReader(fileReader)
if err != nil {
return errors.Wrap(err, "failed to create gzip reader")
}
tarReader := tar.NewReader(gzReader)
for {
hdr, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "failed to read release tar")
}
if hdr.Typeflag != tar.TypeReg {
continue
}
err = func() error {
fileName := filepath.Join(destDir, hdr.Name)
fileWriter, err := os.Create(fileName)
if err != nil {
return errors.Wrapf(err, "failed to create file %q", hdr.Name)
}
defer fileWriter.Close()
_, err = io.Copy(fileWriter, tarReader)
if err != nil {
return errors.Wrapf(err, "failed to write file %q", hdr.Name)
}
return nil
}()
if err != nil {
return err
}
}
return nil
}