forked from openshift/origin
/
buildchain.go
395 lines (341 loc) · 11.5 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
package buildchain
import (
"encoding/json"
"fmt"
"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"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
imageapi "github.com/openshift/origin/pkg/image/api"
)
const longDescription = `Output build dependencies of a specific image repository.
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.
Examples:
# Build dependency tree for the specified image repository and tag
$ openshift ex build-chain [image-repository]:[tag]
# Build dependency trees for all tags in the specified image repository
$ openshift ex build-chain [image-repository] --all-tags
# Build the dependency tree using tag 'latest' in 'testing' namespace
$ openshift ex build-chain [image-repository] -n testing
# Build the dependency tree and output it in DOT syntax
$ openshift ex build-chain [image-repository] -o dot
# Build dependency trees for all image repositories in the current namespace
$ openshift ex build-chain
# Build dependency trees for all image repositories across all namespaces
$ openshift ex build-chain --all
`
// ImageRepo is a representation of a node inside a tree
type ImageRepo struct {
FullName string `json:"fullname"`
Tags []string `json:"tags,omitempty"`
Edges []*Edge `json:"edges,omitempty"`
Children []*ImageRepo `json:"children,omitempty"`
}
// String helps in dumping a tree in AST format
func (root *ImageRepo) 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 all the necessary functionality for the build-chain module
func NewCmdBuildChain(f *clientcmd.Factory, parentName, name string) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("%s [image-repository]:[tag]", name),
Short: "Output build dependencies of a specific image repository",
Long: longDescription,
Run: func(cmd *cobra.Command, args []string) {
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) {
usageError(cmd, "Must pass nothing, an image repository name:tag combination, or specify the --all flag")
}
osc, kc, err := f.Clients()
checkErr(err)
// Retrieve namespace(s)
namespace := cmdutil.GetFlagString(cmd, "namespace")
if len(namespace) == 0 {
namespace, err = f.DefaultNamespace()
checkErr(err)
}
namespaces := make([]string, 0)
if all {
nsList, err := kc.Namespaces().List(labels.Everything())
checkErr(err)
for _, ns := range nsList.Items {
namespaces = append(namespaces, ns.Name)
}
}
if len(namespaces) == 0 {
namespaces = append(namespaces, namespace)
}
// Get all build configurations
buildConfigList := make([]buildapi.BuildConfig, 0)
for _, namespace := range namespaces {
cfgList, err := osc.BuildConfigs(namespace).List(labels.Everything(), fields.Everything())
checkErr(err)
buildConfigList = append(buildConfigList, cfgList.Items...)
}
// Parse user input and validate specified image repository
repos := make(map[string][]string)
if !all && len(args) != 0 {
name, tag, err := parseTag(args[0])
checkErr(err)
// Validate the specified image repository
imgRepo, err := osc.ImageRepositories(namespace).Get(name)
checkErr(err)
tags := make([]string, 0)
if allTags {
for tag := range imgRepo.Tags {
tags = append(tags, tag)
}
}
if len(tags) == 0 {
tags = []string{tag}
}
repo := join(namespace, name)
// Set the specified repo as the only one to output dependencies for
repos[repo] = tags
} else {
// Get all image repositories from build configurations
repos = getRepos(buildConfigList)
// Make sure from now on that the --all flag is true
// since we are building dependency trees for every
// image repository available either in the current
// namespace or in every namespace
all = true
}
if len(repos) == 0 {
checkErr(fmt.Errorf("no image repository available for building its dependency tree"))
}
output := cmdutil.GetFlagString(cmd, "output")
for repo, tags := range repos {
for _, tag := range tags {
root, err := findRepoDeps(repo, tag, all, buildConfigList)
checkErr(err)
// Check if the given image repository 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")
checkErr(err)
fmt.Println(string(jsonDump))
case "dot":
g := dot.NewGraph()
_, name, err := split(repo)
checkErr(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)
fmt.Println(dotDump(root, g, graphName))
case "ast":
fmt.Println(root)
default:
usageError(cmd, "Wrong output format specified: %s", output)
}
}
}
},
}
cmd.Flags().Bool("all", false, "Build dependency trees for all image repositories")
cmd.Flags().Bool("all-tags", false, "Build dependency trees for all tags of a specific image repository")
cmd.Flags().StringP("output", "o", "json", "Output format of dependency tree(s)")
return cmd
}
// getRepos iterates over a given set of build configurations
// and extracts all the image repositories which trigger a
// build when the image repository is updated
func getRepos(configs []buildapi.BuildConfig) map[string][]string {
avoidDuplicates := make(map[string][]string)
for _, cfg := range configs {
for _, tr := range cfg.Triggers {
if tr.ImageChange != nil && tr.ImageChange.From.Name != "" {
var repo string
switch tr.ImageChange.From.Namespace {
case "":
repo = join(cfg.Namespace, tr.ImageChange.From.Name)
default:
repo = join(tr.ImageChange.From.Namespace, tr.ImageChange.From.Name)
}
var tag string
switch tr.ImageChange.Tag {
case "":
tag = "latest"
default:
tag = tr.ImageChange.Tag
}
uniqueTag := true
for _, prev := range avoidDuplicates[repo] {
if prev == tag {
uniqueTag = false
break
}
}
if uniqueTag {
avoidDuplicates[repo] = append(avoidDuplicates[repo], tag)
}
}
}
}
return avoidDuplicates
}
// findRepoDeps accepts an image repository and a list of build
// configurations and returns the dependency tree of the specified
// image repository
func findRepoDeps(repo, tag string, all bool, buildConfigList []buildapi.BuildConfig) (*ImageRepo, error) {
root := &ImageRepo{
FullName: repo,
Tags: []string{tag},
}
namespace, name, err := split(repo)
if err != nil {
return nil, err
}
// Search all build configurations in order to find the image
// repositories depending on the specified image repository
var childNamespace, childName, childTag string
for _, cfg := range buildConfigList {
for _, tr := range cfg.Triggers {
// Setup zeroed fields to their default values
if tr.ImageChange != nil && tr.ImageChange.From.Namespace == "" {
tr.ImageChange.From.Namespace = cfg.Namespace
}
if tr.ImageChange != nil && tr.ImageChange.Tag == "" {
tr.ImageChange.Tag = "latest"
}
if tr.ImageChange != nil &&
namespace == tr.ImageChange.From.Namespace &&
name == tr.ImageChange.From.Name &&
tag == tr.ImageChange.Tag {
// Either To & Tag or DockerImageReference will be used as output
if cfg.Parameters.Output.To != nil && cfg.Parameters.Output.To.Name != "" {
childName = cfg.Parameters.Output.To.Name
childTag = cfg.Parameters.Output.Tag
if cfg.Parameters.Output.To.Namespace != "" {
childNamespace = cfg.Parameters.Output.To.Namespace
} else {
childNamespace = cfg.Namespace
}
} else {
ref, err := imageapi.ParseDockerImageReference(cfg.Parameters.Output.DockerImageReference)
if err != nil {
return nil, err
}
childName = ref.Name
childTag = ref.Tag
childNamespace = cfg.Namespace
}
childRepo := join(childNamespace, childName)
// Build all children and their dependency trees recursively
child, err := findRepoDeps(childRepo, childTag, all, 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 _, repo := range root.Children {
if repo.FullName == child.FullName {
// Just pass the tag along and discard the current child
repo.Tags = append(repo.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 repository tree in DOT syntax
func dotDump(root *ImageRepo, g *dot.Graph, graphName string) string {
if root == nil {
return ""
}
// Add current node
rootNamespace, rootName, err := split(root.FullName)
checkErr(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)
checkErr(err)
childName = validDOT(childName)
edgeNamespace, edgeName, err := split(edge.FullName)
checkErr(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
dotDump(child, g, graphName)
}
dotOutput := g.String()
// Parse DOT output for validation
if _, err := dot.Parse([]byte(dotOutput)); err != nil {
checkErr(fmt.Errorf("cannot parse DOT output: %v\n", err))
}
return dotOutput
}