-
Notifications
You must be signed in to change notification settings - Fork 188
/
Copy pathkustomization_generator.go
280 lines (234 loc) · 6.73 KB
/
kustomization_generator.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
/*
Copyright 2020 The Flux 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 controllers
import (
"crypto/sha1"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/krusty"
kustypes "sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/yaml"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
)
const (
kustomizationFileName = "kustomization.yaml"
transformerFileName = "kustomization-gc-labels.yaml"
)
type KustomizeGenerator struct {
kustomization kustomizev1.Kustomization
}
func NewGenerator(kustomization kustomizev1.Kustomization) *KustomizeGenerator {
return &KustomizeGenerator{
kustomization: kustomization,
}
}
func (kg *KustomizeGenerator) WriteFile(dirPath string) (string, error) {
kfile := filepath.Join(dirPath, kustomizationFileName)
checksum, err := kg.checksum(dirPath)
if err != nil {
return "", err
}
if err := kg.generateLabelTransformer(checksum, dirPath); err != nil {
return "", err
}
data, err := ioutil.ReadFile(kfile)
if err != nil {
return "", err
}
kus := kustypes.Kustomization{
TypeMeta: kustypes.TypeMeta{
APIVersion: kustypes.KustomizationVersion,
Kind: kustypes.KustomizationKind,
},
}
if err := yaml.Unmarshal(data, &kus); err != nil {
return "", err
}
if len(kus.Transformers) == 0 {
kus.Transformers = []string{transformerFileName}
} else {
var exists bool
for _, transformer := range kus.Transformers {
if transformer == transformerFileName {
exists = true
break
}
}
if !exists {
kus.Transformers = append(kus.Transformers, transformerFileName)
}
}
if kg.kustomization.Spec.TargetNamespace != "" {
kus.Namespace = kg.kustomization.Spec.TargetNamespace
}
for _, image := range kg.kustomization.Spec.Images {
newImage := kustypes.Image{
Name: image.Name,
NewName: image.NewName,
NewTag: image.NewTag,
}
if exists, index := checkKustomizeImageExists(kus.Images, image.Name); exists {
kus.Images[index] = newImage
} else {
kus.Images = append(kus.Images, newImage)
}
}
kd, err := yaml.Marshal(kus)
if err != nil {
return "", err
}
return checksum, ioutil.WriteFile(kfile, kd, os.ModePerm)
}
func checkKustomizeImageExists(images []kustypes.Image, imageName string) (bool, int) {
for i, image := range images {
if imageName == image.Name {
return true, i
}
}
return false, -1
}
func (kg *KustomizeGenerator) generateKustomization(dirPath string) error {
fs := filesys.MakeFsOnDisk()
kfile := filepath.Join(dirPath, kustomizationFileName)
scan := func(base string) ([]string, error) {
var paths []string
uf := kunstruct.NewKunstructuredFactoryImpl()
err := fs.Walk(base, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == base {
return nil
}
if info.IsDir() {
// If a sub-directory contains an existing kustomization file add the
// directory as a resource and do not decend into it.
for _, kfilename := range konfig.RecognizedKustomizationFileNames() {
if fs.Exists(filepath.Join(path, kfilename)) {
paths = append(paths, path)
return filepath.SkipDir
}
}
return nil
}
extension := filepath.Ext(path)
if !containsString([]string{".yaml", ".yml"}, extension) {
return nil
}
fContents, err := fs.ReadFile(path)
if err != nil {
return err
}
if _, err := uf.SliceFromBytes(fContents); err != nil {
return fmt.Errorf("failed to decode Kubernetes YAML from %s: %w", path, err)
}
paths = append(paths, path)
return nil
})
return paths, err
}
if _, err := os.Stat(kfile); err != nil {
abs, err := filepath.Abs(dirPath)
if err != nil {
return err
}
files, err := scan(abs)
if err != nil {
return err
}
f, err := fs.Create(kfile)
if err != nil {
return err
}
f.Close()
kus := kustypes.Kustomization{
TypeMeta: kustypes.TypeMeta{
APIVersion: kustypes.KustomizationVersion,
Kind: kustypes.KustomizationKind,
},
}
var resources []string
for _, file := range files {
resources = append(resources, strings.Replace(file, abs, ".", 1))
}
kus.Resources = resources
kd, err := yaml.Marshal(kus)
if err != nil {
return err
}
return ioutil.WriteFile(kfile, kd, os.ModePerm)
}
return nil
}
func (kg *KustomizeGenerator) checksum(dirPath string) (string, error) {
if err := kg.generateKustomization(dirPath); err != nil {
return "", fmt.Errorf("kustomize create failed: %w", err)
}
fs := filesys.MakeFsOnDisk()
opt := krusty.MakeDefaultOptions()
opt.LoadRestrictions = kustypes.LoadRestrictionsNone
opt.DoLegacyResourceSort = true
k := krusty.MakeKustomizer(fs, opt)
m, err := k.Run(dirPath)
if err != nil {
return "", fmt.Errorf("kustomize build failed: %w", err)
}
resources, err := m.AsYaml()
if err != nil {
return "", fmt.Errorf("kustomize build failed: %w", err)
}
return fmt.Sprintf("%x", sha1.Sum(resources)), nil
}
func (kg *KustomizeGenerator) generateLabelTransformer(checksum, dirPath string) error {
labels := selectorLabels(kg.kustomization.GetName(), kg.kustomization.GetNamespace())
// add checksum label only if GC is enabled
if kg.kustomization.Spec.Prune {
labels = gcLabels(kg.kustomization.GetName(), kg.kustomization.GetNamespace(), checksum)
}
var lt = struct {
ApiVersion string `json:"apiVersion" yaml:"apiVersion"`
Kind string `json:"kind" yaml:"kind"`
Metadata struct {
Name string `json:"name" yaml:"name"`
} `json:"metadata" yaml:"metadata"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
FieldSpecs []kustypes.FieldSpec `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"`
}{
ApiVersion: "builtin",
Kind: "LabelTransformer",
Metadata: struct {
Name string `json:"name" yaml:"name"`
}{
Name: kg.kustomization.GetName(),
},
Labels: labels,
FieldSpecs: []kustypes.FieldSpec{
{Path: "metadata/labels", CreateIfNotPresent: true},
},
}
data, err := yaml.Marshal(lt)
if err != nil {
return err
}
labelsFile := filepath.Join(dirPath, transformerFileName)
if err := ioutil.WriteFile(labelsFile, data, os.ModePerm); err != nil {
return err
}
return nil
}