-
Notifications
You must be signed in to change notification settings - Fork 90
/
upload.go
328 lines (284 loc) · 8.42 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package upload
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/manifoldco/promptui"
"github.com/pkg/errors"
kotsscheme "github.com/replicatedhq/kots/kotskinds/client/kotsclientset/scheme"
"github.com/replicatedhq/kots/pkg/auth"
"github.com/replicatedhq/kots/pkg/docker/registry"
"github.com/replicatedhq/kots/pkg/k8sutil"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/util"
"k8s.io/client-go/kubernetes/scheme"
)
type UploadOptions struct {
Namespace string
UpstreamURI string
ExistingAppSlug string
NewAppName string
RegistryOptions registry.RegistryOptions
Endpoint string
Silent bool
Deploy bool
SkipPreflights bool
updateCursor string
license *string
versionLabel string
}
func init() {
kotsscheme.AddToScheme(scheme.Scheme)
}
// Upload will upload the application version at path
// using the options in uploadOptions
func Upload(path string, uploadOptions UploadOptions) (string, error) {
license, err := findLicense(path)
if err != nil {
return "", errors.Wrap(err, "failed to find license")
}
uploadOptions.license = license
updateCursor, err := findUpdateCursor(path)
if err != nil {
return "", errors.Wrapf(err, "failed to find update cursor in %q. Please double check the path provided.", path)
}
if updateCursor == "" {
return "", errors.Errorf("no update cursor found in %q. Please double check the path provided.", path)
}
uploadOptions.updateCursor = updateCursor
archiveFilename, err := createUploadableArchive(path)
if err != nil {
return "", errors.Wrap(err, "failed to create uploadable archive")
}
defer os.Remove(archiveFilename)
// Make sure we have a name or slug
if uploadOptions.ExistingAppSlug == "" && uploadOptions.NewAppName == "" {
split := strings.Split(path, string(os.PathSeparator))
lastPathPart := ""
idx := 1
for lastPathPart == "" {
lastPathPart = split[len(split)-idx]
if lastPathPart == "" && len(split) > idx {
idx++
continue
}
break
}
appName, err := relentlesslyPromptForAppName(lastPathPart)
if err != nil {
return "", errors.Wrap(err, "failed to prompt for app name")
}
uploadOptions.NewAppName = appName
}
// Make sure we have an upstream URI
if uploadOptions.ExistingAppSlug == "" && uploadOptions.UpstreamURI == "" {
upstreamURI, err := promptForUpstreamURI()
if err != nil {
return "", errors.Wrap(err, "failed to prompt for upstream uri")
}
uploadOptions.UpstreamURI = upstreamURI
}
// Find the kotadm-api pod
log := logger.NewCLILogger()
if uploadOptions.Silent {
log.Silence()
}
log.ActionWithSpinner("Uploading local application to Admin Console")
// upload using http to the pod directly
req, err := createUploadRequest(archiveFilename, uploadOptions, fmt.Sprintf("%s/api/v1/upload", uploadOptions.Endpoint))
if err != nil {
log.FinishSpinnerWithError()
return "", errors.Wrap(err, "failed to create upload request")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.FinishSpinnerWithError()
return "", errors.Wrap(err, "failed to execute request")
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.FinishSpinnerWithError()
return "", errors.Errorf("unexpected status code: %d", resp.StatusCode)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.FinishSpinnerWithError()
return "", errors.Wrap(err, "failed to read response body")
}
type UploadResponse struct {
Slug string `json:"slug"`
}
var uploadResponse UploadResponse
if err := json.Unmarshal(b, &uploadResponse); err != nil {
log.FinishSpinnerWithError()
return "", errors.Wrap(err, "failed to unmarshal response")
}
log.FinishSpinner()
return uploadResponse.Slug, nil
}
func createUploadRequest(path string, uploadOptions UploadOptions, uri string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, errors.Wrap(err, "failed to open file")
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
archivePart, err := writer.CreateFormFile("file", filepath.Base(path))
if err != nil {
return nil, errors.Wrap(err, "failed to create form file")
}
_, err = io.Copy(archivePart, file)
if err != nil {
return nil, errors.Wrap(err, "failed to copy file to upload")
}
method := ""
if uploadOptions.ExistingAppSlug != "" {
method = "PUT"
metadata := map[string]interface{}{
"slug": uploadOptions.ExistingAppSlug,
"versionLabel": uploadOptions.versionLabel,
"updateCursor": uploadOptions.updateCursor,
"deploy": uploadOptions.Deploy,
"skipPreflights": uploadOptions.SkipPreflights,
// Intentionally not including registry info here. Updating settings should be its own thing.
}
b, err := json.Marshal(metadata)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal json")
}
metadataPart, err := writer.CreateFormField("metadata")
if err != nil {
return nil, errors.Wrap(err, "failed to add metadata")
}
if _, err := io.Copy(metadataPart, bytes.NewReader(b)); err != nil {
return nil, errors.Wrap(err, "failed to copy metadata")
}
} else {
method = "POST"
metadata := map[string]string{
"name": uploadOptions.NewAppName,
"versionLabel": uploadOptions.versionLabel,
"upstreamURI": uploadOptions.UpstreamURI,
"updateCursor": uploadOptions.updateCursor,
"registryEndpoint": uploadOptions.RegistryOptions.Endpoint,
"registryUsername": uploadOptions.RegistryOptions.Username,
"registryPassword": uploadOptions.RegistryOptions.Password,
"registryNamespace": uploadOptions.RegistryOptions.Namespace,
"deploy": strconv.FormatBool(uploadOptions.Deploy),
"skipPreflights": strconv.FormatBool(uploadOptions.SkipPreflights),
}
if uploadOptions.license != nil {
metadata["license"] = *uploadOptions.license
}
b, err := json.Marshal(metadata)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal json")
}
metadataPart, err := writer.CreateFormField("metadata")
if err != nil {
return nil, errors.Wrap(err, "failed to add metadata")
}
if _, err := io.Copy(metadataPart, bytes.NewReader(b)); err != nil {
return nil, errors.Wrap(err, "failed to copy metadata")
}
}
err = writer.Close()
if err != nil {
return nil, errors.Wrap(err, "failed to close writer")
}
clientset, err := k8sutil.GetClientset()
if err != nil {
return nil, errors.Wrap(err, "failed to get k8s clientset")
}
authSlug, err := auth.GetOrCreateAuthSlug(clientset, uploadOptions.Namespace)
if err != nil {
return nil, errors.Wrap(err, "failed to get auth slug")
}
req, err := http.NewRequest(method, uri, body)
if err != nil {
return nil, errors.Wrap(err, "failed to create new request")
}
req.Header.Set("Authorization", authSlug)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, nil
}
func relentlesslyPromptForAppName(defaultAppName string) (string, error) {
templates := &promptui.PromptTemplates{
Prompt: "{{ . | bold }} ",
Valid: "{{ . | green }} ",
Invalid: "{{ . | red }} ",
Success: "{{ . | bold }} ",
}
prompt := promptui.Prompt{
Label: "Application name:",
Templates: templates,
Default: defaultAppName,
Validate: func(input string) error {
if len(input) < 3 {
return errors.New("invalid app name")
}
return nil
},
AllowEdit: true,
}
for {
result, err := prompt.Run()
if err != nil {
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
continue
}
return result, nil
}
}
func promptForUpstreamURI() (string, error) {
templates := &promptui.PromptTemplates{
Prompt: "{{ . | bold }} ",
Valid: "{{ . | green }} ",
Invalid: "{{ . | red }} ",
Success: "{{ . | bold }} ",
}
supportedSchemes := map[string]interface{}{
"helm": nil,
"replicated": nil,
}
prompt := promptui.Prompt{
Label: "Upstream URI:",
Templates: templates,
Validate: func(input string) error {
if !util.IsURL(input) {
return errors.New("Please enter a URL")
}
u, err := url.ParseRequestURI(input)
if err != nil {
return errors.New("Invalid URL")
}
_, ok := supportedSchemes[u.Scheme]
if !ok {
return errors.New("Unsupported upstream type")
}
return nil
},
}
for {
result, err := prompt.Run()
if err != nil {
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
continue
}
return result, nil
}
}