-
Notifications
You must be signed in to change notification settings - Fork 87
/
upgrade.go
292 lines (252 loc) · 8.88 KB
/
upgrade.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
package upstream
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/auth"
"github.com/replicatedhq/kots/pkg/docker/registry"
"github.com/replicatedhq/kots/pkg/k8sutil"
"github.com/replicatedhq/kots/pkg/kotsadm"
kotsadmtypes "github.com/replicatedhq/kots/pkg/kotsadm/types"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
kustomizetypes "sigs.k8s.io/kustomize/api/types"
)
type UpgradeResponse struct {
Success bool `json:"success"`
AvailableUpdates int64 `json:"availableUpdates"`
CurrentRelease *UpgradeRelease `json:"currentRelease,omitempty"`
AvailableReleases []UpgradeRelease `json:"availableReleases,omitempty"`
Error string `json:"error,omitempty"`
}
type UpgradeRelease struct {
Sequence int64 `json:"sequence"`
Version string `json:"version"`
}
type UpgradeOptions struct {
AirgapBundle string
RegistryEndpoint string
RegistryNamespace string
RegistryUsername string
RegistryPassword string
IsKurl bool
DisableImagePush bool
UpdateCheckEndpoint string
Namespace string
Debug bool
Deploy bool
DeployVersionLabel string
Silent bool
}
func Upgrade(appSlug string, options UpgradeOptions) (*UpgradeResponse, error) {
log := logger.NewCLILogger()
if options.Silent {
log.Silence()
}
airgapPath := ""
var images []kustomizetypes.Image
if options.AirgapBundle != "" {
airgapRootDir, err := ioutil.TempDir("", "kotsadm-airgap")
if err != nil {
return nil, errors.Wrap(err, "failed to create temp dir")
}
defer os.RemoveAll(airgapRootDir)
registryEndpoint := options.RegistryEndpoint
registryNamespace := options.RegistryNamespace
registryUsername := options.RegistryUsername
registryPassword := options.RegistryPassword
if registryNamespace == "" {
// check if it's provided as part of the registry endpoint
parts := strings.Split(registryEndpoint, "/")
if len(parts) > 1 {
registryEndpoint = parts[0]
registryNamespace = strings.Join(parts[1:], "/")
}
}
if registryNamespace == "" {
if options.IsKurl {
registryNamespace = appSlug
}
}
if registryEndpoint == "" && options.IsKurl {
registryEndpoint, registryUsername, registryPassword, err = kotsutil.GetKurlRegistryCreds()
if err != nil {
return nil, errors.Wrap(err, "failed to get kURL registry info")
}
}
airgapPath = airgapRootDir
err = kotsadm.ExtractAppAirgapArchive(options.AirgapBundle, airgapRootDir, options.DisableImagePush, os.Stdout)
if err != nil {
return nil, errors.Wrap(err, "failed to extract images")
}
pushOptions := kotsadmtypes.PushImagesOptions{
Registry: registry.RegistryOptions{
Endpoint: registryEndpoint,
Namespace: registryNamespace,
Username: registryUsername,
Password: registryPassword,
},
ProgressWriter: os.Stdout,
}
if options.DisableImagePush {
images, err = kotsadm.GetImagesFromBundle(options.AirgapBundle, pushOptions)
if err != nil {
return nil, errors.Wrap(err, "failed to get images from bundle")
}
} else {
imagesRootDir := filepath.Join(airgapRootDir, "images")
images, err = kotsadm.TagAndPushAppImagesFromPath(imagesRootDir, pushOptions)
if err != nil {
return nil, errors.Wrap(err, "failed to list image formats")
}
}
}
if airgapPath == "" {
log.ActionWithSpinner("Checking for application updates")
} else {
log.ActionWithSpinner("Uploading application update")
}
contentType := "application/json"
var requestBody io.Reader
if airgapPath == "" {
requestBody = strings.NewReader("{}")
} else {
buffer := &bytes.Buffer{}
writer := multipart.NewWriter(buffer)
if err := createPartFromFile(writer, airgapPath, "airgap.yaml"); err != nil {
return nil, errors.Wrap(err, "failed to create part from airgap.yaml")
}
if err := createPartFromFile(writer, airgapPath, "app.tar.gz"); err != nil {
return nil, errors.Wrap(err, "failed to create part from app.tar.gz")
}
b, err := json.Marshal(images)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal images data")
}
err = ioutil.WriteFile(filepath.Join(airgapPath, "images.json"), b, 0644)
if err != nil {
return nil, errors.Wrap(err, "failed to write images data")
}
if err := createPartFromFile(writer, airgapPath, "images.json"); err != nil {
return nil, errors.Wrap(err, "failed to create part from images.json")
}
err = writer.Close()
if err != nil {
return nil, errors.Wrap(err, "failed to close multi-part writer")
}
contentType = writer.FormDataContentType()
requestBody = buffer
}
clientset, err := k8sutil.GetClientset()
if err != nil {
return nil, errors.Wrap(err, "failed to get k8s clientset")
}
authSlug, err := auth.GetOrCreateAuthSlug(clientset, options.Namespace)
if err != nil {
log.FinishSpinnerWithError()
log.Info("Unable to authenticate to the Admin Console running in the %s namespace. Ensure you have read access to secrets in this namespace and try again.", options.Namespace)
if options.Debug {
return nil, errors.Wrap(err, "failed to get kotsadm auth slug")
}
os.Exit(2) // not returning error here as we don't want to show the entire stack trace to normal users
}
newReq, err := http.NewRequest("POST", options.UpdateCheckEndpoint, requestBody)
if err != nil {
log.FinishSpinnerWithError()
return nil, errors.Wrap(err, "failed to create update check request")
}
newReq.Header.Add("Content-Type", contentType)
newReq.Header.Add("Authorization", authSlug)
resp, err := http.DefaultClient.Do(newReq)
if err != nil {
log.FinishSpinnerWithError()
return nil, errors.Wrap(err, "failed to check for updates")
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.FinishSpinnerWithError()
return nil, errors.Wrap(err, "failed to read server response")
}
if resp.StatusCode == 404 {
log.FinishSpinnerWithError()
return nil, errors.Errorf("The application %s was not found in the cluster in the specified namespace", appSlug)
} else if resp.StatusCode != 200 {
log.FinishSpinnerWithError()
if len(b) != 0 {
log.Error(errors.New(string(b)))
}
return nil, errors.Errorf("Unexpected response from the API: %d", resp.StatusCode)
}
ur := UpgradeResponse{}
if err := json.Unmarshal(b, &ur); err != nil {
return nil, errors.Wrap(err, "failed to parse response")
}
log.FinishSpinner()
if options.Deploy || options.DeployVersionLabel != "" {
if airgapPath != "" {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner("Update has been uploaded and is being deployed")
return &ur, nil
}
if ur.AvailableUpdates == 0 {
log.ActionWithoutSpinner("")
if options.Deploy {
log.ActionWithoutSpinner("There are no application updates available, ensuring latest is marked as deployed")
} else {
log.ActionWithoutSpinner("There are no application updates available, ensuring %s is marked as deployed", options.DeployVersionLabel)
}
} else if options.Deploy {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner(fmt.Sprintf("There are currently %d updates available in the Admin Console, when the latest release is downloaded, it will be deployed", ur.AvailableUpdates))
} else {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner(fmt.Sprintf("There are currently %d updates available in the Admin Console, when the release with the %s version label is downloaded, it will be deployed", ur.AvailableUpdates, options.DeployVersionLabel))
}
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner("To access the Admin Console, run kubectl kots admin-console --namespace %s", options.Namespace)
log.ActionWithoutSpinner("")
return &ur, nil
}
if airgapPath != "" {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner("Update has been uploaded")
} else {
if ur.AvailableUpdates == 0 {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner("There are no application updates available")
} else {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner(fmt.Sprintf("There are currently %d updates available in the Admin Console", ur.AvailableUpdates))
}
}
if !options.IsKurl {
log.ActionWithoutSpinner("To access the Admin Console, run kubectl kots admin-console --namespace %s", options.Namespace)
log.ActionWithoutSpinner("")
}
return &ur, nil
}
func createPartFromFile(partWriter *multipart.Writer, path string, fileName string) error {
file, err := os.Open(filepath.Join(path, fileName))
if err != nil {
return errors.Wrap(err, "failed to open file")
}
defer file.Close()
part, err := partWriter.CreateFormFile(fileName, fileName)
if err != nil {
return errors.Wrap(err, "failed to create form file")
}
_, err = io.Copy(part, file)
if err != nil {
return errors.Wrap(err, "failed to copy file to upload")
}
return nil
}