This repository has been archived by the owner on Jul 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
chaindescriber.go
319 lines (275 loc) · 9.72 KB
/
chaindescriber.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
package describe
import (
"fmt"
"sort"
"strings"
"github.com/golang/glog"
"github.com/gonum/graph"
"github.com/gonum/graph/encoding/dot"
"github.com/gonum/graph/path"
kapi "k8s.io/kubernetes/pkg/api"
utilerrors "k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/sets"
osgraph "github.com/openshift/origin/pkg/api/graph"
buildedges "github.com/openshift/origin/pkg/build/graph"
buildanalysis "github.com/openshift/origin/pkg/build/graph/analysis"
buildgraph "github.com/openshift/origin/pkg/build/graph/nodes"
"github.com/openshift/origin/pkg/client"
imageapi "github.com/openshift/origin/pkg/image/api"
imagegraph "github.com/openshift/origin/pkg/image/graph/nodes"
dotutil "github.com/openshift/origin/pkg/util/dot"
"github.com/openshift/origin/pkg/util/parallel"
)
// NotFoundErr is returned when the imageStreamTag (ist) of interest cannot
// be found in the graph. This doesn't mean though that the IST does not
// exist. A user may have an image stream without a build configuration
// pointing at it. In that case, the IST of interest simply doesn't have
// other dependant ists
type NotFoundErr string
func (e NotFoundErr) Error() string {
return fmt.Sprintf("couldn't find image stream tag: %q", string(e))
}
// ChainDescriber generates extended information about a chain of
// dependencies of an image stream
type ChainDescriber struct {
c client.BuildConfigsNamespacer
namespaces sets.String
outputFormat string
namer osgraph.Namer
}
// NewChainDescriber returns a new ChainDescriber
func NewChainDescriber(c client.BuildConfigsNamespacer, namespaces sets.String, out string) *ChainDescriber {
return &ChainDescriber{c: c, namespaces: namespaces, outputFormat: out, namer: namespacedFormatter{hideNamespace: true}}
}
// MakeGraph will create the graph of all build configurations and the image streams
// they point to via image change triggers in the provided namespace(s)
func (d *ChainDescriber) MakeGraph() (osgraph.Graph, error) {
g := osgraph.New()
loaders := []GraphLoader{}
for namespace := range d.namespaces {
glog.V(4).Infof("Loading build configurations from %q", namespace)
loaders = append(loaders, &bcLoader{namespace: namespace, lister: d.c})
}
loadingFuncs := []func() error{}
for _, loader := range loaders {
loadingFuncs = append(loadingFuncs, loader.Load)
}
if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
return g, utilerrors.NewAggregate(errs)
}
for _, loader := range loaders {
loader.AddToGraph(g)
}
buildedges.AddAllInputOutputEdges(g)
return g, nil
}
// Describe returns the output of the graph starting from the provided
// image stream tag (name:tag) in namespace. Namespace is needed here
// because image stream tags with the same name can be found across
// different namespaces.
func (d *ChainDescriber) Describe(ist *imageapi.ImageStreamTag, includeInputImages, reverse bool) (string, error) {
g, err := d.MakeGraph()
if err != nil {
return "", err
}
// Retrieve the imageStreamTag node of interest
istNode := g.Find(imagegraph.ImageStreamTagNodeName(ist))
if istNode == nil {
return "", NotFoundErr(fmt.Sprintf("%q", ist.Name))
}
markers := buildanalysis.FindCircularBuilds(g, d.namer)
if len(markers) > 0 {
for _, marker := range markers {
if strings.Contains(marker.Message, ist.Name) {
return marker.Message, nil
}
}
}
buildInputEdgeKinds := []string{buildedges.BuildTriggerImageEdgeKind}
if includeInputImages {
buildInputEdgeKinds = append(buildInputEdgeKinds, buildedges.BuildInputImageEdgeKind)
}
// Partition down to the subgraph containing the imagestreamtag of interest
var partitioned osgraph.Graph
if reverse {
partitioned = partitionReverse(g, istNode, buildInputEdgeKinds)
} else {
partitioned = partition(g, istNode, buildInputEdgeKinds)
}
switch strings.ToLower(d.outputFormat) {
case "dot":
data, err := dot.Marshal(partitioned, dotutil.Quote(ist.Name), "", " ", false)
if err != nil {
return "", err
}
return string(data), nil
case "":
return d.humanReadableOutput(partitioned, d.namer, istNode, reverse), nil
}
return "", fmt.Errorf("unknown specified format %q", d.outputFormat)
}
// partition the graph down to a subgraph starting from the given root
func partition(g osgraph.Graph, root graph.Node, buildInputEdgeKinds []string) osgraph.Graph {
// Filter out all but BuildConfig and ImageStreamTag nodes
nodeFn := osgraph.NodesOfKind(buildgraph.BuildConfigNodeKind, imagegraph.ImageStreamTagNodeKind)
// Filter out all but BuildInputImage and BuildOutput edges
edgeKinds := []string{}
edgeKinds = append(edgeKinds, buildInputEdgeKinds...)
edgeKinds = append(edgeKinds, buildedges.BuildOutputEdgeKind)
edgeFn := osgraph.EdgesOfKind(edgeKinds...)
sub := g.Subgraph(nodeFn, edgeFn)
// Filter out inbound edges to the IST of interest
edgeFn = osgraph.RemoveInboundEdges([]graph.Node{root})
sub = sub.Subgraph(nodeFn, edgeFn)
// Check all paths leading from the root node, collect any
// node found in them, and create the desired subgraph
desired := []graph.Node{root}
paths := path.DijkstraAllPaths(sub)
for _, node := range sub.Nodes() {
if node == root {
continue
}
path, _, _ := paths.Between(root, node)
if len(path) != 0 {
desired = append(desired, node)
}
}
return sub.SubgraphWithNodes(desired, osgraph.ExistingDirectEdge)
}
// partitionReverse the graph down to a subgraph starting from the given root
func partitionReverse(g osgraph.Graph, root graph.Node, buildInputEdgeKinds []string) osgraph.Graph {
// Filter out all but BuildConfig and ImageStreamTag nodes
nodeFn := osgraph.NodesOfKind(buildgraph.BuildConfigNodeKind, imagegraph.ImageStreamTagNodeKind)
// Filter out all but BuildInputImage and BuildOutput edges
edgeKinds := []string{}
edgeKinds = append(edgeKinds, buildInputEdgeKinds...)
edgeKinds = append(edgeKinds, buildedges.BuildOutputEdgeKind)
edgeFn := osgraph.EdgesOfKind(edgeKinds...)
sub := g.Subgraph(nodeFn, edgeFn)
// Filter out inbound edges to the IST of interest
edgeFn = osgraph.RemoveOutboundEdges([]graph.Node{root})
sub = sub.Subgraph(nodeFn, edgeFn)
// Check all paths leading from the root node, collect any
// node found in them, and create the desired subgraph
desired := []graph.Node{root}
paths := path.DijkstraAllPaths(sub)
for _, node := range sub.Nodes() {
if node == root {
continue
}
path, _, _ := paths.Between(node, root)
if len(path) != 0 {
desired = append(desired, node)
}
}
return sub.SubgraphWithNodes(desired, osgraph.ExistingDirectEdge)
}
// humanReadableOutput traverses the provided graph using DFS and outputs it
// in a human-readable format. It starts from the provided root, assuming it
// is an imageStreamTag node and continues to the rest of the graph handling
// only imageStreamTag and buildConfig nodes.
func (d *ChainDescriber) humanReadableOutput(g osgraph.Graph, f osgraph.Namer, root graph.Node, reverse bool) string {
if reverse {
g = g.EdgeSubgraph(osgraph.ReverseExistingDirectEdge)
}
var singleNamespace bool
if len(d.namespaces) == 1 && !d.namespaces.Has(kapi.NamespaceAll) {
singleNamespace = true
}
depth := map[graph.Node]int{
root: 0,
}
out := ""
dfs := &DepthFirst{
Visit: func(u, v graph.Node) {
depth[v] = depth[u] + 1
},
}
until := func(node graph.Node) bool {
var info string
switch t := node.(type) {
case *imagegraph.ImageStreamTagNode:
info = outputHelper(f.ResourceName(t), t.Namespace, singleNamespace)
case *buildgraph.BuildConfigNode:
info = outputHelper(f.ResourceName(t), t.BuildConfig.Namespace, singleNamespace)
default:
panic("this graph contains node kinds other than imageStreamTags and buildConfigs")
}
if depth[node] != 0 {
out += "\n"
}
out += fmt.Sprintf("%s", strings.Repeat("\t", depth[node]))
out += fmt.Sprintf("%s", info)
return false
}
dfs.Walk(g, root, until)
return out
}
// outputHelper returns resource/name in a single namespace, <namespace resource/name>
// in multiple namespaces
func outputHelper(info, namespace string, singleNamespace bool) string {
if singleNamespace {
return info
}
return fmt.Sprintf("<%s %s>", namespace, info)
}
// DepthFirst implements stateful depth-first graph traversal.
// Modifies behavior of visitor.DepthFirst to allow nodes to be visited multiple
// times as long as they're not in the current stack
type DepthFirst struct {
EdgeFilter func(graph.Edge) bool
Visit func(u, v graph.Node)
stack NodeStack
}
// Walk performs a depth-first traversal of the graph g starting from the given node
func (d *DepthFirst) Walk(g graph.Graph, from graph.Node, until func(graph.Node) bool) graph.Node {
return d.visit(g, from, until)
}
func (d *DepthFirst) visit(g graph.Graph, t graph.Node, until func(graph.Node) bool) graph.Node {
if until != nil && until(t) {
return t
}
d.stack.Push(t)
children := osgraph.ByID(g.From(t))
sort.Sort(children)
for _, n := range children {
if d.EdgeFilter != nil && !d.EdgeFilter(g.Edge(t, n)) {
continue
}
if d.visited(n.ID()) {
continue
}
if d.Visit != nil {
d.Visit(t, n)
}
result := d.visit(g, n, until)
if result != nil {
return result
}
}
d.stack.Pop()
return nil
}
func (d *DepthFirst) visited(id int) bool {
for _, n := range d.stack {
if n.ID() == id {
return true
}
}
return false
}
// NodeStack implements a LIFO stack of graph.Node.
// NodeStack is internal only in go 1.5.
type NodeStack []graph.Node
// Len returns the number of graph.Nodes on the stack.
func (s *NodeStack) Len() int { return len(*s) }
// Pop returns the last graph.Node on the stack and removes it
// from the stack.
func (s *NodeStack) Pop() graph.Node {
v := *s
v, n := v[:len(v)-1], v[len(v)-1]
*s = v
return n
}
// Push adds the node n to the stack at the last position.
func (s *NodeStack) Push(n graph.Node) { *s = append(*s, n) }