-
Notifications
You must be signed in to change notification settings - Fork 88
/
upgrade.go
277 lines (240 loc) · 8.76 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
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"
registrytypes "github.com/replicatedhq/kots/pkg/docker/registry/types"
"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/logger"
"github.com/replicatedhq/kots/pkg/util"
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"`
DeployingRelease *UpgradeRelease `json:"deployingRelease,omitempty"`
Error string `json:"error,omitempty"`
}
type UpgradeRelease struct {
Sequence int64 `json:"sequence"`
Version string `json:"version"`
}
type UpgradeOptions struct {
AirgapBundle string
RegistryConfig kotsadmtypes.RegistryConfig
IsKurl bool
DisableImagePush bool
UpdateCheckEndpoint string
Namespace string
Debug bool
Deploy bool
DeployVersionLabel string
Wait bool
Silent bool
}
func Upgrade(appSlug string, options UpgradeOptions) (*UpgradeResponse, error) {
log := logger.NewCLILogger(os.Stdout)
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)
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: registrytypes.RegistryOptions{
Endpoint: options.RegistryConfig.OverrideRegistry,
Namespace: options.RegistryConfig.OverrideNamespace,
Username: options.RegistryConfig.Username,
Password: options.RegistryConfig.Password,
},
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 {
images, err = kotsadm.TagAndPushAppImagesFromPath(airgapRootDir, pushOptions)
if err != nil {
return nil, errors.Wrap(err, "failed to tag and push app images from path")
}
}
}
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 := util.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")
}
if ur.DeployingRelease != nil && ur.DeployingRelease.Version == "" {
ur.DeployingRelease = nil
}
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 deployed")
} else {
log.ActionWithoutSpinner("There are no application updates available, ensuring %s is deployed", options.DeployVersionLabel)
}
} else if options.Wait {
if options.Deploy {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner(fmt.Sprintf("There are currently %d updates available in the Admin Console, ensuring latest is deployed", ur.AvailableUpdates))
} else {
log.ActionWithoutSpinner("")
log.ActionWithoutSpinner(fmt.Sprintf("There are currently %d updates available in the Admin Console, ensuring %s is deployed", ur.AvailableUpdates, 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
}