-
Notifications
You must be signed in to change notification settings - Fork 2
/
upload.go
309 lines (275 loc) · 8.05 KB
/
upload.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
/*
Copyright (c) Edgeless Systems GmbH
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/edgelesssys/uplosi/aws"
"github.com/edgelesssys/uplosi/azure"
"github.com/edgelesssys/uplosi/config"
"github.com/edgelesssys/uplosi/gcp"
"github.com/edgelesssys/uplosi/openstack"
"github.com/spf13/cobra"
"golang.org/x/mod/semver"
)
const (
configName = "uplosi.conf"
configDir = "uplosi.conf.d"
)
func newUploadCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "upload <image>",
Short: "Upload an image to a cloud provider",
Args: cobra.ExactArgs(1),
RunE: runUpload,
}
cmd.Flags().BoolP("increment-version", "i", false, "increment version number after upload")
cmd.Flags().StringSlice("enable-variant-glob", []string{"*"}, "list of variant name globs to enable")
cmd.Flags().StringSlice("disable-variant-glob", nil, "list of variant name globs to disable")
cmd.Flags().StringP("config", "c", "", fmt.Sprintf("path to directory %s and %s resides in", configName, configDir))
return cmd
}
func runUpload(cmd *cobra.Command, args []string) error {
logger := log.New(cmd.ErrOrStderr(), "", log.LstdFlags)
imagePath := args[0]
flags, err := parseUploadFlags(cmd)
if err != nil {
return fmt.Errorf("parsing flags: %w", err)
}
conf, err := parseConfigFiles(flags.configPath)
if err != nil {
return fmt.Errorf("parsing config files: %w", err)
}
versionFiles := map[string][]byte{}
versionFileLookup := func(name string) ([]byte, error) {
if _, ok := versionFiles[name]; !ok {
ver, err := os.ReadFile(name)
if err != nil {
return nil, fmt.Errorf("reading version file: %w", err)
}
versionFiles[name] = ver
}
return versionFiles[name], nil
}
allRefs := []string{}
err = conf.ForEach(
func(name string, cfg config.Config) error {
refs, err := uploadVariant(cmd.Context(), imagePath, name, cfg, logger)
if err != nil {
return err
}
allRefs = append(allRefs, refs...)
return nil
},
versionFileLookup,
func(name string) bool {
return filterGlobAny(flags.enableVariantGlobs, name)
},
func(name string) bool {
return !filterGlobAny(flags.disableVariantGlobs, name)
},
)
if err != nil {
return fmt.Errorf("uploading variants: %w", err)
}
for _, ref := range allRefs {
fmt.Println(ref)
}
if !flags.incrementVersion {
return nil
}
if len(versionFiles) == 0 {
return errors.New("increment-version flag set but no version files found")
}
for versionFileName, version := range versionFiles {
newVer, err := incrementSemver(strings.TrimSpace(string(version)))
if err != nil {
return fmt.Errorf("incrementing semver: %w", err)
}
if err := writeVersionFile(versionFileName, []byte(newVer)); err != nil {
return fmt.Errorf("writing version file: %w", err)
}
}
return nil
}
func uploadVariant(ctx context.Context, imagePath, variant string, config config.Config, logger *log.Logger) ([]string, error) {
var prepper Prepper
var upload Uploader
var err error
if len(variant) > 0 {
log.Println("Uploading variant", variant)
}
switch strings.ToLower(config.Provider) {
case "aws":
prepper = &aws.Prepper{}
upload, err = aws.NewUploader(config, logger)
if err != nil {
return nil, fmt.Errorf("creating aws uploader: %w", err)
}
case "azure":
prepper = &azure.Prepper{}
upload, err = azure.NewUploader(config, logger)
if err != nil {
return nil, fmt.Errorf("creating azure uploader: %w", err)
}
case "gcp":
prepper = &gcp.Prepper{}
upload, err = gcp.NewUploader(config, logger)
if err != nil {
return nil, fmt.Errorf("creating gcp uploader: %w", err)
}
case "openstack":
prepper = &openstack.Prepper{}
upload, err = openstack.NewUploader(config, logger)
if err != nil {
return nil, fmt.Errorf("creating openstack uploader: %w", err)
}
default:
return nil, fmt.Errorf("unknown provider: %s", config.Provider)
}
tmpDir, err := os.MkdirTemp("", "uplosi-")
if err != nil {
return nil, fmt.Errorf("creating temp dir: %w", err)
}
defer os.RemoveAll(tmpDir)
imagePath, err = prepper.Prepare(ctx, imagePath, tmpDir)
if err != nil {
return nil, fmt.Errorf("preparing image: %w", err)
}
image, err := os.Open(imagePath)
if err != nil {
return nil, fmt.Errorf("opening image: %w", err)
}
defer image.Close()
imageFi, err := image.Stat()
if err != nil {
return nil, fmt.Errorf("getting image stats: %w", err)
}
refs, err := upload.Upload(ctx, image, imageFi.Size())
if err != nil {
return nil, fmt.Errorf("uploading image: %w", err)
}
return refs, nil
}
type uploadFlags struct {
incrementVersion bool
enableVariantGlobs []string
disableVariantGlobs []string
configPath string
}
func parseUploadFlags(cmd *cobra.Command) (*uploadFlags, error) {
incrementVersion, err := cmd.Flags().GetBool("increment-version")
if err != nil {
return nil, fmt.Errorf("getting increment-version flag: %w", err)
}
enableVariantGlobs, err := cmd.Flags().GetStringSlice("enable-variant-glob")
if err != nil {
return nil, fmt.Errorf("getting enable-variant-glob flag: %w", err)
}
disableVariantGlobs, err := cmd.Flags().GetStringSlice("disable-variant-glob")
if err != nil {
return nil, fmt.Errorf("getting disable-variant-glob flag: %w", err)
}
configPath, err := cmd.Flags().GetString("config")
if err != nil {
return nil, fmt.Errorf("getting config flag: %w", err)
}
return &uploadFlags{
incrementVersion: incrementVersion,
enableVariantGlobs: enableVariantGlobs,
disableVariantGlobs: disableVariantGlobs,
configPath: configPath,
}, nil
}
func filterGlobAny(globs []string, name string) bool {
for _, glob := range globs {
if ok, _ := filepath.Match(glob, name); ok {
return true
}
}
return false
}
func readTOMLFile(path string, data any) error {
configFile, err := os.OpenFile(path, os.O_RDONLY, os.ModeAppend)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer configFile.Close()
if _, err := toml.NewDecoder(configFile).Decode(data); err != nil {
return fmt.Errorf("decoding file: %w", err)
}
return nil
}
func writeVersionFile(path string, data []byte) error {
versionFile, err := os.OpenFile(path, os.O_WRONLY, os.ModeAppend)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer versionFile.Close()
if _, err := versionFile.Write(data); err != nil {
return fmt.Errorf("writing file: %w", err)
}
return nil
}
type Prepper interface {
Prepare(ctx context.Context, imagePath, tmpDir string) (string, error)
}
type Uploader interface {
Upload(ctx context.Context, image io.ReadSeeker, size int64) (refs []string, retErr error)
}
func parseConfigFiles(configPath string) (*config.ConfigFile, error) {
configLocation := path.Join(configPath, configName)
configDirLocation := path.Join(configPath, configDir)
var conf config.ConfigFile
if err := readTOMLFile(configLocation, &conf); err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
dirEntries, err := os.ReadDir(configDirLocation)
if os.IsNotExist(err) {
return &conf, nil
}
if err != nil {
return nil, fmt.Errorf("reading config dir: %w", err)
}
for _, dirEntry := range dirEntries {
var cfgOverlay config.ConfigFile
if dirEntry.IsDir() {
continue
}
if filepath.Ext(dirEntry.Name()) != ".conf" {
continue
}
if err := readTOMLFile(filepath.Join(configDir, dirEntry.Name()), &cfgOverlay); err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
if err := conf.Merge(cfgOverlay); err != nil {
return nil, fmt.Errorf("merging config: %w", err)
}
}
return &conf, nil
}
func incrementSemver(version string) (string, error) {
canonical := strings.TrimPrefix(semver.Canonical("v"+version), "v")
parts := strings.Split(canonical, ".")
if len(parts) != 3 {
return "", fmt.Errorf("splitting canonical version: %s, %v", canonical, parts)
}
patch := parts[2]
patchNum, err := strconv.Atoi(patch)
if err != nil {
return "", fmt.Errorf("converting patch number: %w", err)
}
patchNum++
return fmt.Sprintf("%s.%s.%d", parts[0], parts[1], patchNum), nil
}