-
Notifications
You must be signed in to change notification settings - Fork 785
/
step_report_chart.go
382 lines (332 loc) · 9.93 KB
/
step_report_chart.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
package report
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/ghodss/yaml"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/cmd/helper"
"github.com/jenkins-x/jx/v2/pkg/cmd/opts"
"github.com/jenkins-x/jx/v2/pkg/cmd/opts/step"
"github.com/jenkins-x/jx/v2/pkg/cmd/templates"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/jenkins-x/jx/v2/pkg/versionstream"
"github.com/pkg/errors"
"github.com/spf13/cobra"
v1 "k8s.io/api/apps/v1"
)
var (
stepReportChartLong = templates.LongDesc(`Creates a report of all the images used in the charts in a version stream".`)
stepReportChartExample = templates.Examples(`
`)
)
var (
defaultChartReportName = "chart-images"
)
// ChartReport the report
type ChartReport struct {
Charts []*ChartData `json:"charts,omitempty"`
DuplicateImages []*DuplicateImageVersion `json:"duplicateImages,omitempty"`
}
// ChartData the image information
type ChartData struct {
Prefix string `json:"prefix,omitempty"`
Name string `json:"name,omitempty"`
RepoURL string `json:"url,omitempty"`
Version string `json:"version,omitempty"`
Images []string `json:"images,omitempty"`
}
// DuplicateImageVersion the duplicate images
type DuplicateImageVersion struct {
Image string
Versions map[string]string
}
// StepReportChartOptions contains the command line flags and other helper objects
type StepReportChartOptions struct {
StepReportOptions
VersionsDir string
ReportName string
FailOnDuplicate bool
Report ChartReport
}
// NewCmdStepReportChart Creates a new Command object
func NewCmdStepReportChart(commonOpts *opts.CommonOptions) *cobra.Command {
options := &StepReportChartOptions{
StepReportOptions: StepReportOptions{
StepOptions: step.StepOptions{
CommonOptions: commonOpts,
},
},
}
cmd := &cobra.Command{
Use: "chart",
Short: "Creates a report of all the images used in the charts in a version stream",
Long: stepReportChartLong,
Example: stepReportChartExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
options.StepReportOptions.AddReportFlags(cmd)
cmd.Flags().StringVarP(&options.VersionsDir, "dir", "d", "", "The dir of the version stream. If not specified it the version stream is cloned")
cmd.Flags().StringVarP(&options.ReportName, "name", "n", defaultChartReportName, "The name of the file to generate")
cmd.Flags().BoolVarP(&options.FailOnDuplicate, "fail-on-duplicate", "f", false, "If true lets fail the step if we have any duplicate")
return cmd
}
// Run generates the report
func (o *StepReportChartOptions) Run() error {
if o.VersionsDir == "" {
resolver, err := o.GetVersionResolver()
if err != nil {
return err
}
o.VersionsDir = resolver.VersionsDir
}
dir := filepath.Join(o.VersionsDir, "charts")
exists, err := util.DirExists(dir)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("directory does not exist %s", dir)
}
repoPrefixes, err := versionstream.GetRepositoryPrefixes(filepath.Join(dir, ".."))
if err != nil {
return err
}
report := &o.Report
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
name := info.Name()
chartsDir := filepath.Dir(path)
chartName := strings.TrimSuffix(name, filepath.Ext(name))
_, chartPrefix := filepath.Split(chartsDir)
if info.IsDir() || name == "repositories.yml" || !strings.HasSuffix(name, ".yml") {
return nil
}
v, err := versionstream.LoadStableVersionFile(path)
if err != nil {
return err
}
prefixInfos := repoPrefixes.URLsForPrefix(chartPrefix)
version := v.Version
if len(prefixInfos) == 0 {
log.Logger().Warnf("chart %s/%s does not have a repository URL for prefix in registries.yml", chartPrefix, chartName)
return nil
}
if version == "" {
log.Logger().Warnf("chart %s/%s does not have a version", chartPrefix, chartName)
return nil
}
chartRepo := prefixInfos[0]
log.Logger().Infof("found chart %s/%s in repo %s with version %s", chartPrefix, chartName, chartRepo, version)
chartInfo := &ChartData{
RepoURL: chartRepo,
Prefix: chartPrefix,
Name: chartName,
Version: version,
}
report.Charts = append(report.Charts, chartInfo)
err = o.processChart(chartInfo)
if err != nil {
return err
}
sort.Strings(chartInfo.Images)
cl := util.ColorInfo
log.Logger().Infof("chart %s/%s has images: %s", cl(chartInfo.Prefix), cl(chartInfo.Name), cl(strings.Join(chartInfo.Images, ", ")))
return nil
})
imagesDir := filepath.Join(o.VersionsDir, "docker")
SortChartData(report.Charts)
err = report.CalculateDuplicates(imagesDir)
if err != nil {
return errors.Wrapf(err, "failed to calculate duplicate images")
}
if o.OutputDir == "" {
o.OutputDir = "."
}
fileName := o.ReportName
if fileName != "" {
fileName += ".yml"
}
return o.OutputReport(report, fileName, o.OutputDir)
}
func (o *StepReportChartOptions) processChart(info *ChartData) error {
tmpDir, err := ioutil.TempDir("", "helm-"+info.Name+"-")
if err != nil {
return errors.Wrapf(err, "failed to create tempo dir")
}
chartDir := filepath.Join(tmpDir, "chart")
fullChart := fmt.Sprintf("%s/%s", info.Prefix, info.Name)
version := info.Version
// lets fetch the chart
err = o.RunCommandVerbose("helm", "fetch", "-d", chartDir, "--version", version, "--untar", "--repo", info.RepoURL, info.Name)
if err != nil {
return err
}
exists, err := util.DirExists(chartDir)
if err != nil {
return errors.Wrapf(err, "failed to check chart dir exists %s", chartDir)
}
if !exists {
return fmt.Errorf("should have fetched the chart %s version %s", fullChart, version)
}
output, err := o.GetCommandOutput(chartDir, "helm", "template", info.Name)
if err != nil {
return err
}
files := strings.Split(output, "---\n")
for _, text := range files {
if isEmptyTemplate(text) {
continue
}
err = o.processTemplate(info, text)
if err != nil {
return err
}
}
return nil
}
func (o *StepReportChartOptions) processTemplate(info *ChartData, text string) error {
data := map[string]interface{}{}
err := yaml.Unmarshal([]byte(text), &data)
if err != nil {
return errors.Wrapf(err, "failed to parse template for chart %s/%s for template: %s", info.Prefix, info.Name, text)
}
if util.GetMapValueAsStringViaPath(data, "kind") == "Deployment" {
d := v1.Deployment{}
err := yaml.Unmarshal([]byte(text), &d)
if err != nil {
return errors.Wrapf(err, "failed to parse Deployment template for chart %s/%s for template: %s", info.Prefix, info.Name, text)
}
containers := d.Spec.Template.Spec.Containers
if len(containers) == 0 {
log.Logger().Warnf("Deployment template %s for chart %s/%s has no containers", d.Name, info.Prefix, info.Name)
return nil
}
for _, c := range containers {
if c.Image != "" {
info.addImage(c.Image)
}
}
}
return nil
}
func isEmptyTemplate(text string) bool {
lines := strings.Split(text, "\n")
for _, line := range lines {
if strings.HasPrefix(line, "#") || strings.TrimSpace(line) == "" {
continue
}
return false
}
return true
}
// ImageMap used to map images to their versions
type ImageMap struct {
Images map[string]map[string]string
}
// AddImage adds a new image to the map
func (m *ImageMap) AddImage(name string, version string, from string) {
if m.Images == nil {
m.Images = map[string]map[string]string{}
}
versions := m.Images[name]
if versions == nil {
versions = map[string]string{}
m.Images[name] = versions
}
versions[version] = from
}
// DuplicateImages returns the duplicate images
func (m *ImageMap) DuplicateImages() []*DuplicateImageVersion {
answer := []*DuplicateImageVersion{}
for name, versions := range m.Images {
if len(versions) > 1 {
answer = append(answer, &DuplicateImageVersion{
Image: name,
Versions: versions,
})
}
}
return answer
}
// LoadImageMap loads the images from the given image stream dir
func LoadImageMap(imagesDir string) (ImageMap, error) {
m := ImageMap{}
err := filepath.Walk(imagesDir, func(path string, info os.FileInfo, err error) error {
name := info.Name()
if info.IsDir() || !strings.HasSuffix(name, ".yml") {
return nil
}
r, err := filepath.Rel(imagesDir, path)
if err != nil {
return errors.Wrapf(err, "failed to calculate relative path")
}
r = strings.TrimSuffix(r, ".yml")
v, err := versionstream.LoadStableVersionFile(path)
if err != nil {
log.Logger().Warnf("failed to parse image version file %s due to %s", path, err.Error())
return nil
}
m.AddImage(r, v.Version, "stream")
return nil
})
if err != nil {
return m, errors.Wrapf(err, "failed to walk images dir %s", imagesDir)
}
return m, nil
}
// CalculateDuplicates figures out if there are any duplicate image versions
func (r *ChartReport) CalculateDuplicates(imagesDir string) error {
m, err := LoadImageMap(imagesDir)
if err != nil {
return err
}
for _, chart := range r.Charts {
for _, image := range chart.Images {
image = strings.Trim(image, "docker.io/")
idx := strings.Index(image, ":")
if idx < 0 {
log.Logger().Warnf("image %s does not have a version", image)
continue
}
r := image[0:idx]
v := image[idx+1:]
m.AddImage(r, v, chart.Prefix+"/"+chart.Name+":"+chart.Version)
}
}
// now lets find the duplicates
r.DuplicateImages = m.DuplicateImages()
return nil
}
func (i *ChartData) addImage(image string) {
if util.StringArrayIndex(i.Images, image) < 0 {
i.Images = append(i.Images, image)
sort.Strings(i.Images)
}
}
type chartDataOrder []*ChartData
func (a chartDataOrder) Len() int { return len(a) }
func (a chartDataOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a chartDataOrder) Less(i, j int) bool {
r1 := a[i]
r2 := a[j]
n1 := r1.Prefix
n2 := r2.Prefix
if n1 != n2 {
return n1 < n2
}
v1 := r1.Name
v2 := r2.Name
return v1 < v2
}
// SortChartData sorts the charts in order
func SortChartData(items []*ChartData) {
sort.Sort(chartDataOrder(items))
}