forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildchain.go
451 lines (402 loc) · 12.8 KB
/
buildchain.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package buildchain
import (
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
dot "github.com/awalterschulze/gographviz"
"github.com/golang/glog"
"github.com/spf13/cobra"
buildapi "github.com/openshift/origin/pkg/build/api"
buildutil "github.com/openshift/origin/pkg/build/util"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
imageapi "github.com/openshift/origin/pkg/image/api"
)
const (
buildChainLong = `Output build dependencies of a specific image stream.
Supported output formats are json, dot, and ast. The default is set to json.
Tag and namespace are optional and if they are not specified, 'latest' and the
default namespace will be used respectively.`
buildChainExample = ` // Build dependency tree for the specified image stream and tag
$ openshift ex build-chain [image-stream]:[tag]
// Build dependency trees for all tags in the specified image stream
$ openshift ex build-chain [image-stream] --all-tags
// Build the dependency tree using tag 'latest' in 'testing' namespace
$ openshift ex build-chain [image-stream] -n testing
// Build the dependency tree and output it in DOT syntax
$ openshift ex build-chain [image-stream] -o dot
// Build dependency trees for all image streams in the current namespace
$ openshift ex build-chain
// Build dependency trees for all image streams across all namespaces
$ openshift ex build-chain --all`
)
// Node is a representation of an image stream inside a tree
type Node struct {
FullName string `json:"fullname"`
Tags []string `json:"tags,omitempty"`
Edges []*Edge `json:"edges,omitempty"`
Children []*Node `json:"children,omitempty"`
}
// String helps in dumping a tree in AST format
func (root *Node) String() string {
tree := ""
tree += root.FullName
for _, n := range root.Children {
tree += "(" + n.String() + ")"
}
return tree
}
// Edge represents a build configuration relationship
// between two nodes
//
// Note that this type has no relation with the dot.Edge
// type
type Edge struct {
FullName string `json:"fullname"`
To string `json:"to"`
}
// NewEdge adds a new edge on a parent node
//
// Note that this function has no relation
// with the dot.Edge type
func NewEdge(fullname, to string) *Edge {
return &Edge{
FullName: fullname,
To: to,
}
}
// NewCmdBuildChain implements the OpenShift experimental build-chain command
func NewCmdBuildChain(f *clientcmd.Factory, parentName, name string) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("%s [IMAGESTREAM:TAG | --all]", name),
Short: "Output build dependencies of a specific image stream",
Long: buildChainLong,
Example: buildChainExample,
Run: func(cmd *cobra.Command, args []string) {
err := RunBuildChain(f, cmd, args)
cmdutil.CheckErr(err)
},
}
cmd.Flags().Bool("all", false, "Build dependency trees for all image streams")
cmd.Flags().Bool("all-tags", false, "Build dependency trees for all tags of a specific image stream")
cmd.Flags().StringP("output", "o", "json", "Output format of dependency tree(s)")
return cmd
}
// RunBuildChain contains all the necessary functionality for the OpenShift
// experimental build-chain command
func RunBuildChain(f *clientcmd.Factory, cmd *cobra.Command, args []string) error {
all := cmdutil.GetFlagBool(cmd, "all")
allTags := cmdutil.GetFlagBool(cmd, "all-tags")
if len(args) > 1 ||
(len(args) == 1 && all) ||
(len(args) == 0 && allTags) ||
(all && allTags) {
return cmdutil.UsageError(cmd, "Must pass nothing, an ImageStream name:tag combination, or specify the --all flag")
}
oc, _, err := f.Clients()
if err != nil {
return err
}
// Retrieve namespace(s)
namespace := cmdutil.GetFlagString(cmd, "namespace")
if len(namespace) == 0 {
namespace, err = f.DefaultNamespace()
if err != nil {
return err
}
}
namespaces := make([]string, 0)
if all {
projectList, err := oc.Projects().List(labels.Everything(), fields.Everything())
if err != nil {
return err
}
for _, project := range projectList.Items {
glog.V(4).Infof("Found namespace %s", project.Name)
namespaces = append(namespaces, project.Name)
}
}
if len(namespaces) == 0 {
namespaces = append(namespaces, namespace)
}
// Get all build configurations
buildConfigList := make([]buildapi.BuildConfig, 0)
for _, namespace := range namespaces {
cfgList, err := oc.BuildConfigs(namespace).List(labels.Everything(), fields.Everything())
if err != nil {
return err
}
buildConfigList = append(buildConfigList, cfgList.Items...)
}
// Parse user input and validate specified image stream
streams := make(map[string][]string)
if !all && len(args) != 0 {
name, specifiedTag, err := parseTag(args[0])
if err != nil {
return err
}
// Validate the specified image stream
is, err := oc.ImageStreams(namespace).Get(name)
if err != nil {
return err
}
stream := join(namespace, name)
// Validate specified tag
tags := make([]string, 0)
exists := false
for tag := range is.Status.Tags {
tags = append(tags, tag)
if specifiedTag == tag {
exists = true
}
}
if !exists && !allTags {
// The specified tag isn't a part of our image stream
return fmt.Errorf("no tag %s exists in %s", specifiedTag, stream)
} else if !allTags {
// Use only the specified tag
tags = []string{specifiedTag}
}
// Set the specified stream as the only one to output dependencies for
streams[stream] = tags
} else {
streams = getStreams(buildConfigList)
}
if len(streams) == 0 {
return fmt.Errorf("no ImageStream available for building its dependency tree")
}
output := cmdutil.GetFlagString(cmd, "output")
for stream, tags := range streams {
for _, tag := range tags {
glog.V(4).Infof("Checking dependencies of stream %s tag %s", stream, tag)
root, err := findStreamDeps(stream, tag, buildConfigList)
if err != nil {
return err
}
// Check if the given image stream doesn't have any dependencies
if treeSize(root) < 2 {
glog.Infof("%s:%s has no dependencies\n", root.FullName, tag)
continue
}
switch output {
case "json":
jsonDump, err := json.MarshalIndent(root, "", "\t")
if err != nil {
return err
}
fmt.Println(string(jsonDump))
case "dot":
g := dot.NewGraph()
_, name, err := split(stream)
if err != nil {
return err
}
graphName := validDOT(name)
g.SetName(graphName)
// Directed graph since we illustrate dependencies
g.SetDir(true)
// Explicitly allow multiple pairs of edges between
// the same pair of nodes
g.SetStrict(false)
out, err := dotDump(root, g, graphName)
if err != nil {
return err
}
fmt.Println(out)
case "ast":
fmt.Println(root)
default:
return cmdutil.UsageError(cmd, "Wrong output format specified: %s", output)
}
}
}
return nil
}
// getStreams iterates over a given set of build configurations
// and extracts all the image streams which trigger a
// build when the image stream is updated
func getStreams(configs []buildapi.BuildConfig) map[string][]string {
glog.V(1).Infof("Scanning BuildConfigs")
avoidDuplicates := make(map[string][]string)
for _, cfg := range configs {
glog.V(1).Infof("Scanning BuildConfigs %v", cfg)
for _, tr := range cfg.Spec.Triggers {
glog.V(1).Infof("Scanning trigger %v", tr)
from := buildutil.GetImageStreamForStrategy(cfg.Spec.Strategy)
glog.V(1).Infof("Strategy from= %v", from)
if tr.ImageChange != nil && from != nil && from.Name != "" {
glog.V(1).Infof("found ICT with from %s kind %s", from.Name, from.Kind)
var name, tag string
switch from.Kind {
case "ImageStreamTag":
bits := strings.Split(from.Name, ":")
name = bits[0]
tag = bits[1]
default:
// ImageStreamImage and DockerImage are never updated and so never
// trigger builds.
continue
}
var stream string
switch from.Namespace {
case "":
stream = join(cfg.Namespace, name)
default:
stream = join(from.Namespace, name)
}
uniqueTag := true
for _, prev := range avoidDuplicates[stream] {
if prev == tag {
uniqueTag = false
break
}
}
glog.V(1).Infof("checking unique tag %v %s", uniqueTag, tag)
if uniqueTag {
avoidDuplicates[stream] = append(avoidDuplicates[stream], tag)
}
}
}
}
return avoidDuplicates
}
// findStreamDeps accepts an image stream and a list of build
// configurations and returns the dependency tree of the specified
// image stream
func findStreamDeps(stream, tag string, buildConfigList []buildapi.BuildConfig) (*Node, error) {
root := &Node{
FullName: stream,
Tags: []string{tag},
}
namespace, name, err := split(stream)
if err != nil {
return nil, err
}
// Search all build configurations in order to find the image
// streams depending on the specified image stream
var childNamespace, childName, childTag string
for _, cfg := range buildConfigList {
for _, tr := range cfg.Spec.Triggers {
from := buildutil.GetImageStreamForStrategy(cfg.Spec.Strategy)
if from == nil || from.Kind != "ImageStreamTag" || tr.ImageChange == nil {
continue
}
if cfg.Spec.Output.To == nil || len(cfg.Spec.Output.To.Name) == 0 {
// build has no output image, so the chain ends here.
continue
}
// Setup zeroed fields to their default values
if from.Namespace == "" {
from.Namespace = cfg.Namespace
}
fromTag := strings.Split(from.Name, ":")[1]
parentStream := namespace + "/" + name + ":" + tag
if buildutil.NameFromImageStream("", from, fromTag) == parentStream {
if cfg.Spec.Output.To.Kind == "ImageStreamTag" {
bits := strings.Split(cfg.Spec.Output.To.Name, ":")
if len(bits) != 2 {
return nil, fmt.Errorf("Invalid ImageStreamTag %s/%s does not contain a :tag", namespace, cfg.Spec.Output.To.Name)
}
childName = bits[0]
childTag = bits[1]
if cfg.Spec.Output.To.Namespace != "" {
childNamespace = cfg.Spec.Output.To.Namespace
} else {
childNamespace = cfg.Namespace
}
} else {
ref, err := imageapi.ParseDockerImageReference(cfg.Spec.Output.To.Name)
if err != nil {
return nil, err
}
childName = ref.Name
childTag = ref.Tag
childNamespace = cfg.Namespace
}
childStream := join(childNamespace, childName)
// Build all children and their dependency trees recursively
child, err := findStreamDeps(childStream, childTag, buildConfigList)
if err != nil {
return nil, err
}
// Add edge between root and child
cfgFullName := join(cfg.Namespace, cfg.Name)
root.Edges = append(root.Edges, NewEdge(cfgFullName, child.FullName))
// If the child depends on root via more than one tag, we have to make sure
// that only one single instance of the child will make it into root.Children
cont := false
for _, stream := range root.Children {
if stream.FullName == child.FullName {
// Just pass the tag along and discard the current child
stream.Tags = append(stream.Tags, child.Tags...)
cont = true
break
}
}
if cont {
// Do not append this child in root.Children. It's already in there
continue
}
root.Children = append(root.Children, child)
}
}
}
return root, nil
}
var once sync.Once
// dotDump dumps the given image stream tree in DOT syntax
func dotDump(root *Node, g *dot.Graph, graphName string) (string, error) {
if root == nil {
return "", nil
}
// Add current node
rootNamespace, rootName, err := split(root.FullName)
if err != nil {
return "", err
}
attrs := make(map[string]string)
for _, tag := range root.Tags {
setTag(tag, attrs)
}
var tag string
// Inject tag into root's name
once.Do(func() {
tag = root.Tags[0]
})
setLabel(rootName, rootNamespace, attrs, tag)
rootName = validDOT(rootName)
g.AddNode(graphName, rootName, attrs)
// Add edges between current node and its children
for _, child := range root.Children {
for _, edge := range root.Edges {
if child.FullName == edge.To {
_, childName, err := split(child.FullName)
if err != nil {
return "", err
}
childName = validDOT(childName)
edgeNamespace, edgeName, err := split(edge.FullName)
if err != nil {
return "", err
}
edgeName = validDOT(edgeName)
edgeAttrs := make(map[string]string)
setLabel(edgeName, edgeNamespace, edgeAttrs, "")
g.AddEdge(rootName, childName, true, edgeAttrs)
}
}
// Recursively add every child and their children as nodes
if _, err := dotDump(child, g, graphName); err != nil {
return "", err
}
}
dotOutput := g.String()
// Parse DOT output for validation
if _, err := dot.Parse([]byte(dotOutput)); err != nil {
return "", fmt.Errorf("cannot parse DOT output: %v", err)
}
return dotOutput, nil
}