-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
kustomize.go
401 lines (342 loc) · 11.5 KB
/
kustomize.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
/*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package deploy
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/segmentio/textio"
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/build"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/color"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants"
deploy "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/kubectl"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/event"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/warnings"
)
var (
DefaultKustomizePath = "."
kustomizeFilePaths = []string{"kustomization.yaml", "kustomization.yml", "Kustomization"}
)
type patchPath struct {
Path string `yaml:"path"`
Patch string `yaml:"patch"`
}
type patchWrapper struct {
*patchPath
}
// kustomization is the content of a kustomization.yaml file.
type kustomization struct {
Bases []string `yaml:"bases"`
Resources []string `yaml:"resources"`
Patches []patchWrapper `yaml:"patches"`
PatchesStrategicMerge []string `yaml:"patchesStrategicMerge"`
CRDs []string `yaml:"crds"`
PatchesJSON6902 []patchJSON6902 `yaml:"patchesJson6902"`
ConfigMapGenerator []configMapGenerator `yaml:"configMapGenerator"`
SecretGenerator []secretGenerator `yaml:"secretGenerator"`
}
type patchJSON6902 struct {
Path string `yaml:"path"`
}
type configMapGenerator struct {
Files []string `yaml:"files"`
Env string `yaml:"env"`
Envs []string `yaml:"envs"`
}
type secretGenerator struct {
Files []string `yaml:"files"`
Env string `yaml:"env"`
Envs []string `yaml:"envs"`
}
// KustomizeDeployer deploys workflows using kustomize CLI.
type KustomizeDeployer struct {
*latest.KustomizeDeploy
kubectl deploy.CLI
useKubectl bool
insecureRegistries map[string]bool
BuildArgs []string
}
func NewKustomizeDeployer(runCtx *runcontext.RunContext) *KustomizeDeployer {
kubectl := deploy.CLI{
CLI: kubectl.NewFromRunContext(runCtx),
Flags: runCtx.Cfg.Deploy.KustomizeDeploy.Flags,
ForceDeploy: runCtx.Opts.Force,
}
var useKubectl bool
gt, err := kubectl.CompareVersionTo(context.Background(), 1, 14)
if err != nil {
logrus.Warnf("could not retrieve kubectl version: relying on standalone kustomize binary")
}
if gt == 1 {
useKubectl = true
}
return &KustomizeDeployer{
KustomizeDeploy: runCtx.Cfg.Deploy.KustomizeDeploy,
kubectl: kubectl,
useKubectl: useKubectl,
insecureRegistries: runCtx.InsecureRegistries,
BuildArgs: runCtx.Cfg.Deploy.KustomizeDeploy.BuildArgs,
}
}
// Labels returns the labels specific to kustomize.
func (k *KustomizeDeployer) Labels() map[string]string {
return map[string]string{
constants.Labels.Deployer: "kustomize",
}
}
// Deploy runs `kubectl apply` on the manifest generated by kustomize.
func (k *KustomizeDeployer) Deploy(ctx context.Context, out io.Writer, builds []build.Artifact, labellers []Labeller) *Result {
event.DeployInProgress()
manifests, err := k.renderManifests(ctx, out, builds, labellers)
if err != nil {
event.DeployFailed(err)
return NewDeployErrorResult(err)
}
if len(manifests) == 0 {
event.DeployComplete()
return NewDeploySuccessResult(nil)
}
namespaces, err := manifests.CollectNamespaces()
if err != nil {
event.DeployInfoEvent(fmt.Errorf("could not fetch deployed resource namespace. "+
"This might cause port-forward and deploy health-check to fail: %w", err))
}
if err := k.kubectl.Apply(ctx, textio.NewPrefixWriter(out, " - "), manifests); err != nil {
event.DeployFailed(err)
return NewDeployErrorResult(fmt.Errorf("kubectl error: %w", err))
}
event.DeployComplete()
return NewDeploySuccessResult(namespaces)
}
func (k *KustomizeDeployer) renderManifests(ctx context.Context, out io.Writer, builds []build.Artifact, labellers []Labeller) (deploy.ManifestList, error) {
if err := k.kubectl.CheckVersion(ctx); err != nil {
color.Default.Fprintln(out, "kubectl client version:", k.kubectl.Version(ctx))
color.Default.Fprintln(out, err)
}
manifests, err := k.readManifests(ctx)
if err != nil {
return nil, fmt.Errorf("reading manifests: %w", err)
}
if len(manifests) == 0 {
return nil, nil
}
manifests, err = manifests.ReplaceImages(builds)
if err != nil {
return nil, fmt.Errorf("replacing images in manifests: %w", err)
}
for _, transform := range manifestTransforms {
manifests, err = transform(manifests, builds, k.insecureRegistries)
if err != nil {
return nil, fmt.Errorf("unable to transform manifests: %w", err)
}
}
manifests, err = manifests.SetLabels(merge(k, labellers...))
if err != nil {
return nil, fmt.Errorf("setting labels in manifests: %w", err)
}
return manifests, nil
}
// Cleanup deletes what was deployed by calling Deploy.
func (k *KustomizeDeployer) Cleanup(ctx context.Context, out io.Writer) error {
manifests, err := k.readManifests(ctx)
if err != nil {
return fmt.Errorf("reading manifests: %w", err)
}
if err := k.kubectl.Delete(ctx, textio.NewPrefixWriter(out, " - "), manifests); err != nil {
return fmt.Errorf("delete: %w", err)
}
return nil
}
// Dependencies lists all the files that describe what needs to be deployed.
func (k *KustomizeDeployer) Dependencies() ([]string, error) {
deps := newStringSet()
for _, kustomizePath := range k.KustomizePaths {
depsForKustomization, err := dependenciesForKustomization(kustomizePath)
if err != nil {
return nil, err
}
deps.insert(depsForKustomization...)
}
return deps.toList(), nil
}
func (k *KustomizeDeployer) Render(ctx context.Context, out io.Writer, builds []build.Artifact, labellers []Labeller, filepath string) error {
manifests, err := k.renderManifests(ctx, out, builds, labellers)
if err != nil {
return err
}
manifestOut := out
if filepath != "" {
f, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return fmt.Errorf("opening file for writing manifests: %w", err)
}
defer f.Close()
f.WriteString(manifests.String() + "\n")
return nil
}
fmt.Fprintln(manifestOut, manifests.String())
return nil
}
// UnmarshalYAML implements JSON unmarshalling by reading an inline yaml fragment.
func (p *patchWrapper) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
pp := &patchPath{}
if err := unmarshal(&pp); err != nil {
var oldPathString string
if err := unmarshal(&oldPathString); err != nil {
return err
}
warnings.Printf("list of file paths deprecated: see https://github.com/kubernetes-sigs/kustomize/blob/master/docs/plugins/builtins.md#patchtransformer")
pp.Path = oldPathString
}
p.patchPath = pp
return nil
}
func dependenciesForKustomization(dir string) ([]string, error) {
var deps []string
path, err := findKustomizationConfig(dir)
if err != nil {
// No kustomization config found so assume it's remote and stop traversing
return deps, nil
}
buf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
content := kustomization{}
if err := yaml.Unmarshal(buf, &content); err != nil {
return nil, err
}
deps = append(deps, path)
candidates := append(content.Bases, content.Resources...)
for _, candidate := range candidates {
// If the file doesn't exist locally, we can assume it's a remote file and
// skip it, since we can't monitor remote files. Kustomize itself will
// handle invalid/missing files.
local, mode := pathExistsLocally(candidate, dir)
if !local {
continue
}
if mode.IsDir() {
candidateDeps, err := dependenciesForKustomization(filepath.Join(dir, candidate))
if err != nil {
return nil, err
}
deps = append(deps, candidateDeps...)
} else {
deps = append(deps, filepath.Join(dir, candidate))
}
}
deps = append(deps, util.AbsolutePaths(dir, content.PatchesStrategicMerge)...)
deps = append(deps, util.AbsolutePaths(dir, content.CRDs)...)
for _, patch := range content.Patches {
if patch.Path != "" {
deps = append(deps, filepath.Join(dir, patch.Path))
}
}
for _, jsonPatch := range content.PatchesJSON6902 {
deps = append(deps, filepath.Join(dir, jsonPatch.Path))
}
for _, generator := range content.ConfigMapGenerator {
deps = append(deps, util.AbsolutePaths(dir, generator.Files)...)
envs := generator.Envs
if generator.Env != "" {
envs = append(envs, generator.Env)
}
deps = append(deps, util.AbsolutePaths(dir, envs)...)
}
for _, generator := range content.SecretGenerator {
deps = append(deps, util.AbsolutePaths(dir, generator.Files)...)
envs := generator.Envs
if generator.Env != "" {
envs = append(envs, generator.Env)
}
deps = append(deps, util.AbsolutePaths(dir, envs)...)
}
return deps, nil
}
// A Kustomization config must be at the root of the directory. Kustomize will
// error if more than one of these files exists so order doesn't matter.
func findKustomizationConfig(dir string) (string, error) {
candidates := []string{"kustomization.yaml", "kustomization.yml", "Kustomization"}
for _, candidate := range candidates {
if local, _ := pathExistsLocally(candidate, dir); local {
return filepath.Join(dir, candidate), nil
}
}
return "", fmt.Errorf("no Kustomization configuration found in directory: %s", dir)
}
func pathExistsLocally(filename string, workingDir string) (bool, os.FileMode) {
path := filename
if !filepath.IsAbs(filename) {
path = filepath.Join(workingDir, filename)
}
if f, err := os.Stat(path); err == nil {
return true, f.Mode()
}
return false, 0
}
func (k *KustomizeDeployer) readManifests(ctx context.Context) (deploy.ManifestList, error) {
var manifests deploy.ManifestList
for _, kustomizePath := range k.KustomizePaths {
var out []byte
var err error
if k.useKubectl {
out, err = k.kubectl.Kustomize(ctx, buildCommandArgs(k.BuildArgs, kustomizePath))
} else {
cmd := exec.CommandContext(ctx, "kustomize", append([]string{"build"}, buildCommandArgs(k.BuildArgs, kustomizePath)...)...)
out, err = util.RunCmdOut(cmd)
}
if err != nil {
return nil, fmt.Errorf("kustomize build: %w", err)
}
if len(out) == 0 {
continue
}
manifests.Append(out)
}
return manifests, nil
}
func buildCommandArgs(buildArgs []string, kustomizePath string) []string {
var args []string
// args = append(args, "build")
if len(buildArgs) > 0 {
for _, v := range buildArgs {
parts := strings.Split(v, " ")
args = append(args, parts...)
}
}
if len(kustomizePath) > 0 {
args = append(args, kustomizePath)
}
return args
}
func IsKustomizationPath(path string) bool {
filename := filepath.Base(path)
for _, candidate := range kustomizeFilePaths {
if filename == candidate {
return true
}
}
return false
}