-
Notifications
You must be signed in to change notification settings - Fork 88
/
rewrite.go
413 lines (356 loc) · 16 KB
/
rewrite.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package rewrite
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
reportingtypes "github.com/replicatedhq/kots/pkg/api/reporting/types"
"github.com/replicatedhq/kots/pkg/apparchive"
"github.com/replicatedhq/kots/pkg/base"
"github.com/replicatedhq/kots/pkg/crypto"
"github.com/replicatedhq/kots/pkg/downstream"
"github.com/replicatedhq/kots/pkg/image"
"github.com/replicatedhq/kots/pkg/k8sutil"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/midstream"
registrytypes "github.com/replicatedhq/kots/pkg/registry/types"
"github.com/replicatedhq/kots/pkg/rendered"
"github.com/replicatedhq/kots/pkg/store"
"github.com/replicatedhq/kots/pkg/upstream"
upstreamtypes "github.com/replicatedhq/kots/pkg/upstream/types"
kotsv1beta1 "github.com/replicatedhq/kotskinds/apis/kots/v1beta1"
)
type RewriteOptions struct {
RootDir string
UpstreamURI string
UpstreamPath string
Downstreams []string
K8sNamespace string
Silent bool
CreateAppDir bool
ExcludeKotsKinds bool
Installation *kotsv1beta1.Installation
License *kotsv1beta1.License
ConfigValues *kotsv1beta1.ConfigValues
ReportWriter io.Writer
CopyImages bool // can be false even if registry is not read-only
IsAirgap bool
RegistrySettings registrytypes.RegistrySettings
AppID string
AppSlug string
IsGitOps bool
AppSequence int64
ReportingInfo *reportingtypes.ReportingInfo
HTTPProxyEnvValue string
HTTPSProxyEnvValue string
NoProxyEnvValue string
}
func Rewrite(rewriteOptions RewriteOptions) error {
log := logger.NewCLILogger(os.Stdout)
if rewriteOptions.Silent {
log.Silence()
}
log.Initialize()
if rewriteOptions.ReportWriter == nil {
rewriteOptions.ReportWriter = ioutil.Discard
}
fetchOptions := &upstreamtypes.FetchOptions{
RootDir: rewriteOptions.RootDir,
LocalPath: rewriteOptions.UpstreamPath,
CurrentCursor: rewriteOptions.Installation.Spec.UpdateCursor,
CurrentVersionLabel: rewriteOptions.Installation.Spec.VersionLabel,
CurrentVersionIsRequired: rewriteOptions.Installation.Spec.IsRequired,
CurrentReplicatedRegistryDomain: rewriteOptions.Installation.Spec.ReplicatedRegistryDomain,
CurrentReplicatedProxyDomain: rewriteOptions.Installation.Spec.ReplicatedProxyDomain,
CurrentReplicatedChartNames: rewriteOptions.Installation.Spec.ReplicatedChartNames,
EncryptionKey: rewriteOptions.Installation.Spec.EncryptionKey,
License: rewriteOptions.License,
AppSequence: rewriteOptions.AppSequence,
AppSlug: rewriteOptions.AppSlug,
LocalRegistry: rewriteOptions.RegistrySettings,
ReportingInfo: rewriteOptions.ReportingInfo,
SkipCompatibilityCheck: true, // we're rewriting an existing version, no need to check for compatibility
}
log.ActionWithSpinner("Pulling upstream")
io.WriteString(rewriteOptions.ReportWriter, "Pulling upstream\n")
u, err := upstream.FetchUpstream(rewriteOptions.UpstreamURI, fetchOptions)
if err != nil {
log.FinishSpinnerWithError()
return errors.Wrap(err, "failed to load upstream")
}
clientset, err := k8sutil.GetClientset()
if err != nil {
return errors.Wrap(err, "failed to get k8s clientset")
}
writeUpstreamOptions := upstreamtypes.WriteOptions{
RootDir: rewriteOptions.RootDir,
CreateAppDir: rewriteOptions.CreateAppDir,
IncludeAdminConsole: false,
PreserveInstallation: true,
IsOpenShift: k8sutil.IsOpenShift(clientset),
IsGKEAutopilot: k8sutil.IsGKEAutopilot(clientset),
IsAirgap: rewriteOptions.IsAirgap,
KotsadmID: k8sutil.GetKotsadmID(clientset),
AppID: rewriteOptions.AppID,
}
if err = upstream.WriteUpstream(u, writeUpstreamOptions); err != nil {
log.FinishSpinnerWithError()
return errors.Wrap(err, "failed to write upstream")
}
log.FinishSpinner()
renderOptions := base.RenderOptions{
SplitMultiDocYAML: true,
Namespace: rewriteOptions.K8sNamespace,
RegistrySettings: rewriteOptions.RegistrySettings,
ExcludeKotsKinds: rewriteOptions.ExcludeKotsKinds,
Log: log,
AppSlug: rewriteOptions.AppSlug,
Sequence: rewriteOptions.AppSequence,
IsAirgap: rewriteOptions.IsAirgap,
}
log.ActionWithSpinner("Rendering KOTS custom resources")
io.WriteString(rewriteOptions.ReportWriter, "Rendering KOTS custom resources\n")
renderedKotsKindsMap, err := base.RenderKotsKinds(u, &renderOptions)
if err != nil {
log.FinishSpinnerWithError()
return errors.Wrap(err, "failed to render upstream")
}
renderedKotsKinds, err := kotsutil.KotsKindsFromMap(renderedKotsKindsMap)
if err != nil {
log.FinishSpinnerWithError()
return errors.Wrap(err, "failed to load rendered kotskinds from map")
}
log.FinishSpinner()
log.ActionWithSpinner("Creating base")
io.WriteString(rewriteOptions.ReportWriter, "Creating base\n")
commonBase, helmBases, err := base.RenderUpstream(u, &renderOptions, renderedKotsKinds)
if err != nil {
return errors.Wrap(err, "failed to render upstream")
}
errorFiles := []base.BaseFile{}
errorFiles = append(errorFiles, base.PrependBaseFilesPath(commonBase.ListErrorFiles(), commonBase.Path)...)
for _, helmBase := range helmBases {
errorFiles = append(errorFiles, base.PrependBaseFilesPath(helmBase.ListErrorFiles(), helmBase.Path)...)
}
if ff := errorFiles; len(ff) > 0 {
files := make([]kotsv1beta1.InstallationYAMLError, 0, len(ff))
for _, f := range ff {
file := kotsv1beta1.InstallationYAMLError{
Path: f.Path,
}
if f.Error != nil {
file.Error = f.Error.Error()
}
files = append(files, file)
}
renderedKotsKinds.Installation.Spec.YAMLErrors = files
if err := apparchive.SaveInstallation(&renderedKotsKinds.Installation, u.GetUpstreamDir(writeUpstreamOptions)); err != nil {
return errors.Wrap(err, "failed to save installation")
}
}
writeBaseOptions := base.WriteOptions{
BaseDir: u.GetBaseDir(writeUpstreamOptions),
SkippedDir: u.GetSkippedDir(writeUpstreamOptions),
Overwrite: true,
ExcludeKotsKinds: rewriteOptions.ExcludeKotsKinds,
IsHelmBase: false,
}
if err := commonBase.WriteBase(writeBaseOptions); err != nil {
return errors.Wrap(err, "failed to write common base")
}
for _, helmBase := range helmBases {
helmBaseCopy := helmBase.DeepCopy()
// strip namespace. helm render takes care of injecting the namespace
helmBaseCopy.SetNamespace("")
writeBaseOptions := base.WriteOptions{
BaseDir: u.GetBaseDir(writeUpstreamOptions),
SkippedDir: u.GetSkippedDir(writeUpstreamOptions),
Overwrite: true,
ExcludeKotsKinds: rewriteOptions.ExcludeKotsKinds,
IsHelmBase: true,
}
if err := helmBaseCopy.WriteBase(writeBaseOptions); err != nil {
return errors.Wrapf(err, "failed to write helm base %s", helmBaseCopy.Path)
}
}
log.FinishSpinner()
log.ActionWithSpinner("Creating midstreams")
io.WriteString(rewriteOptions.ReportWriter, "Creating midstreams\n")
builder, _, err := base.NewConfigContextTemplateBuilder(u, &renderOptions)
if err != nil {
return errors.Wrap(err, "failed to create new config context template builder")
}
if err := crypto.InitFromString(rewriteOptions.Installation.Spec.EncryptionKey); err != nil {
return errors.Wrap(err, "failed to create cipher from installation spec")
}
identityConfig, err := upstream.LoadIdentityConfig(u.GetUpstreamDir(writeUpstreamOptions))
if err != nil {
return errors.Wrap(err, "failed to load identity config")
}
var v1Beta1HelmCharts []*kotsv1beta1.HelmChart
if renderedKotsKinds.V1Beta1HelmCharts != nil {
for _, v1Beta1Chart := range renderedKotsKinds.V1Beta1HelmCharts.Items {
kc := v1Beta1Chart
v1Beta1HelmCharts = append(v1Beta1HelmCharts, &kc)
}
}
commonWriteMidstreamOptions := midstream.WriteOptions{
AppSlug: rewriteOptions.AppSlug,
IsGitOps: rewriteOptions.IsGitOps,
IsOpenShift: k8sutil.IsOpenShift(clientset),
Builder: *builder,
HTTPProxyEnvValue: rewriteOptions.HTTPProxyEnvValue,
HTTPSProxyEnvValue: rewriteOptions.HTTPSProxyEnvValue,
NoProxyEnvValue: rewriteOptions.NoProxyEnvValue,
NewHelmCharts: v1Beta1HelmCharts,
License: rewriteOptions.License,
RenderedKotsKinds: renderedKotsKinds,
IdentityConfig: identityConfig,
UpstreamDir: u.GetUpstreamDir(writeUpstreamOptions),
Log: log,
}
// the UseHelmInstall map blocks visibility into charts and subcharts when searching for private images
// any chart name listed here will be skipped when writing midstream kustomization.yaml and pullsecret.yaml
// when using Helm Install, each chart gets it's own kustomization and pullsecret yaml and MUST be skipped when processing higher level directories!
// for writing Common Midstream, every chart and subchart is in this map as Helm Midstreams will be processed later in the code
commonWriteMidstreamOptions.UseHelmInstall = map[string]bool{}
for _, v := range v1Beta1HelmCharts {
chartBaseName := v.GetDirName()
commonWriteMidstreamOptions.UseHelmInstall[chartBaseName] = v.Spec.UseHelmInstall
if v.Spec.UseHelmInstall {
subcharts, err := base.FindHelmSubChartsFromBase(writeBaseOptions.BaseDir, chartBaseName)
if err != nil {
return errors.Wrapf(err, "failed to find subcharts for parent chart %s", chartBaseName)
}
for _, subchart := range subcharts.SubCharts {
commonWriteMidstreamOptions.UseHelmInstall[subchart] = v.Spec.UseHelmInstall
}
}
}
processImageOptions := image.ProcessImageOptions{
AppSlug: rewriteOptions.AppSlug,
Namespace: rewriteOptions.K8sNamespace,
RewriteImages: rewriteOptions.RegistrySettings.Hostname != "",
RegistrySettings: rewriteOptions.RegistrySettings,
CopyImages: rewriteOptions.CopyImages,
RootDir: rewriteOptions.RootDir,
IsAirgap: rewriteOptions.IsAirgap,
AirgapRoot: "",
AirgapBundle: "",
PushImages: rewriteOptions.RegistrySettings.Hostname != "",
CreateAppDir: false,
ReportWriter: rewriteOptions.ReportWriter,
}
writeMidstreamOptions := commonWriteMidstreamOptions
writeMidstreamOptions.MidstreamDir = filepath.Join(u.GetOverlaysDir(writeUpstreamOptions), "midstream")
writeMidstreamOptions.BaseDir = filepath.Join(u.GetBaseDir(writeUpstreamOptions), commonBase.Path)
writeMidstreamOptions.ProcessImageOptions = processImageOptions
writeMidstreamOptions.Base = commonBase
m, err := midstream.WriteMidstream(writeMidstreamOptions)
if err != nil {
return errors.Wrap(err, "failed to write common midstream")
}
helmMidstreams := []midstream.Midstream{}
for _, helmBase := range helmBases {
// we must look at the current chart for private images, but must ignore subcharts
// to do this, we remove only the current helmBase name from the UseHelmInstall map to unblock visibility into the chart directory
// this ensures only the current chart resources are added to kustomization.yaml and pullsecret.yaml
// chartName := strings.Split(helmBase.Path, "/")[len(strings.Split(helmBase.Path, "/"))-1]
// copy the bool setting in the map to restore it after this process loop
previousUseHelmInstall := writeMidstreamOptions.UseHelmInstall[helmBase.Path]
writeMidstreamOptions.UseHelmInstall[helmBase.Path] = false
helmBaseCopy := helmBase.DeepCopy()
processImageOptionsCopy := processImageOptions
processImageOptionsCopy.Namespace = helmBaseCopy.Namespace
processImageOptionsCopy.CopyImages = false // don't copy images more than once
writeMidstreamOptions.MidstreamDir = filepath.Join(u.GetOverlaysDir(writeUpstreamOptions), "midstream", helmBaseCopy.Path)
writeMidstreamOptions.BaseDir = filepath.Join(u.GetBaseDir(writeUpstreamOptions), helmBaseCopy.Path)
writeMidstreamOptions.ProcessImageOptions = processImageOptionsCopy
writeMidstreamOptions.Base = helmBaseCopy
helmMidstream, err := midstream.WriteMidstream(writeMidstreamOptions)
if err != nil {
return errors.Wrapf(err, "failed to write helm midstream %s", helmBase.Path)
}
// add this chart back into UseHelmInstall to make sure it's not processed again
writeMidstreamOptions.UseHelmInstall[helmBase.Path] = previousUseHelmInstall
helmMidstreams = append(helmMidstreams, *helmMidstream)
}
writeV1Beta2HelmChartsOpts := apparchive.WriteV1Beta2HelmChartsOptions{
Upstream: u,
WriteUpstreamOptions: writeUpstreamOptions,
RenderOptions: &renderOptions,
ProcessImageOptions: processImageOptions,
KotsKinds: renderedKotsKinds,
Clientset: clientset,
}
if err := apparchive.WriteV1Beta2HelmCharts(writeV1Beta2HelmChartsOpts); err != nil {
return errors.Wrap(err, "failed to write helm v1beta2 charts")
}
if err := writeDownstreams(rewriteOptions, u.GetOverlaysDir(writeUpstreamOptions), m, helmMidstreams, log); err != nil {
return errors.Wrap(err, "failed to write downstreams")
}
if err := store.GetStore().UpdateAppVersionInstallationSpec(rewriteOptions.AppID, rewriteOptions.AppSequence, renderedKotsKinds.Installation); err != nil {
return errors.Wrap(err, "failed to update installation spec")
}
// installation spec gets updated during the process, ensure the map has the latest version
installationBytes, err := os.ReadFile(filepath.Join(u.GetUpstreamDir(writeUpstreamOptions), "userdata", "installation.yaml"))
if err != nil {
return errors.Wrap(err, "failed to read installation file")
}
renderedKotsKindsMap["userdata/installation.yaml"] = installationBytes
if err := kotsutil.WriteKotsKinds(renderedKotsKindsMap, u.GetKotsKindsDir(writeUpstreamOptions)); err != nil {
return errors.Wrap(err, "failed to write kots base")
}
if err := rendered.WriteRenderedApp(&rendered.WriteOptions{
BaseDir: u.GetBaseDir(writeUpstreamOptions),
OverlaysDir: u.GetOverlaysDir(writeUpstreamOptions),
RenderedDir: u.GetRenderedDir(writeUpstreamOptions),
Downstreams: rewriteOptions.Downstreams,
KustomizeBinPath: renderedKotsKinds.GetKustomizeBinaryPath(),
HelmDir: u.GetHelmDir(writeUpstreamOptions),
Log: log,
KotsKinds: renderedKotsKinds,
ProcessImageOptions: processImageOptions,
Clientset: clientset,
}); err != nil {
return errors.Wrap(err, "failed to write rendered")
}
log.FinishSpinner()
return nil
}
func writeDownstreams(options RewriteOptions, overlaysDir string, m *midstream.Midstream, helmMidstreams []midstream.Midstream, log *logger.CLILogger) error {
for _, downstreamName := range options.Downstreams {
log.ActionWithSpinner("Creating downstream %q", downstreamName)
io.WriteString(options.ReportWriter, fmt.Sprintf("Creating downstream %q\n", downstreamName))
d, err := downstream.CreateDownstream(m)
if err != nil {
return errors.Wrapf(err, "failed to create downstream %s", downstreamName)
}
writeDownstreamOptions := downstream.WriteOptions{
DownstreamDir: filepath.Join(overlaysDir, "downstreams", downstreamName),
MidstreamDir: filepath.Join(overlaysDir, "midstream"),
}
if err := d.WriteDownstream(writeDownstreamOptions); err != nil {
return errors.Wrapf(err, "failed to write downstream %s", downstreamName)
}
for _, mid := range helmMidstreams {
helmMidstream := mid
d, err := downstream.CreateDownstream(&helmMidstream)
if err != nil {
return errors.Wrapf(err, "failed to create downstream %s for midstream %s", downstreamName, mid.Base.Path)
}
writeDownstreamOptions := downstream.WriteOptions{
DownstreamDir: filepath.Join(overlaysDir, "downstreams", downstreamName, mid.Base.Path),
MidstreamDir: filepath.Join(overlaysDir, "midstream", mid.Base.Path),
}
if err := d.WriteDownstream(writeDownstreamOptions); err != nil {
return errors.Wrapf(err, "failed to write downstream %s for midstream %s", downstreamName, mid.Base.Path)
}
}
log.FinishSpinner()
}
return nil
}