-
Notifications
You must be signed in to change notification settings - Fork 450
/
graph.go
315 lines (269 loc) · 10.1 KB
/
graph.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
// Copyright 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 graph
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-logr/logr"
gonumgraph "gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/graph/traverse"
certificatesv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
operationsv1alpha1 "github.com/gardener/gardener/pkg/apis/operations/v1alpha1"
seedmanagementv1alpha1 "github.com/gardener/gardener/pkg/apis/seedmanagement/v1alpha1"
)
// Interface is used to track resources dependencies.
type Interface interface {
// Setup registers the event handler functions for the various resource types.
Setup(ctx context.Context, c cache.Cache) error
// HasVertex returns true when the given vertex exists in the graph.
HasVertex(vertexType VertexType, vertexNamespace, vertexName string) bool
// HasPathFrom returns true when there is a path from <from> to <to>.
HasPathFrom(fromType VertexType, fromNamespace, fromName string, toType VertexType, toNamespace, toName string) bool
}
type graph struct {
lock sync.RWMutex
logger logr.Logger
client client.Client
graph *simple.DirectedGraph
vertices typeVertexMapping
}
var _ Interface = &graph{}
// New creates a new graph interface for tracking resource dependencies.
func New(logger logr.Logger, client client.Client) *graph {
return &graph{
logger: logger,
client: client,
graph: simple.NewDirectedGraph(),
vertices: make(typeVertexMapping),
}
}
func (g *graph) Setup(ctx context.Context, c cache.Cache) error {
for _, resource := range []struct {
obj client.Object
setupFn func(context.Context, cache.Informer) error
}{
{&gardencorev1beta1.BackupBucket{}, g.setupBackupBucketWatch},
{&gardencorev1beta1.BackupEntry{}, g.setupBackupEntryWatch},
{&operationsv1alpha1.Bastion{}, g.setupBastionWatch},
{&certificatesv1.CertificateSigningRequest{}, g.setupCertificateSigningRequestWatch},
{&gardencorev1beta1.ControllerInstallation{}, g.setupControllerInstallationWatch},
{&seedmanagementv1alpha1.ManagedSeed{}, g.setupManagedSeedWatch},
{&gardencorev1beta1.Project{}, g.setupProjectWatch},
{&gardencorev1beta1.SecretBinding{}, g.setupSecretBindingWatch},
{&gardencorev1beta1.Seed{}, g.setupSeedWatch},
{&corev1.ServiceAccount{}, g.setupServiceAccountWatch},
{&gardencorev1beta1.Shoot{}, g.setupShootWatch},
} {
informer, err := c.GetInformer(ctx, resource.obj)
if err != nil {
return err
}
if err := resource.setupFn(ctx, informer); err != nil {
return err
}
}
return nil
}
func (g *graph) HasVertex(vertexType VertexType, vertexNamespace, vertexName string) bool {
_, ok := g.getVertex(vertexType, vertexNamespace, vertexName)
return ok
}
func (g *graph) HasPathFrom(fromType VertexType, fromNamespace, fromName string, toType VertexType, toNamespace, toName string) bool {
start := time.Now()
defer func() {
metricPathCheckDuration.WithLabelValues(vertexTypes[fromType], vertexTypes[toType]).Observe(time.Since(start).Seconds())
}()
g.lock.RLock()
defer g.lock.RUnlock()
fromVertex, ok := g.getVertex(fromType, fromNamespace, fromName)
if !ok {
return false
}
toVertex, ok := g.getVertex(toType, toNamespace, toName)
if !ok {
return false
}
return (&traverse.DepthFirst{}).Walk(g.graph, fromVertex, func(n gonumgraph.Node) bool {
return n.ID() == toVertex.ID()
}) != nil
}
func (g *graph) getOrCreateVertex(vertexType VertexType, namespace, name string) *vertex {
if v, ok := g.getVertex(vertexType, namespace, name); ok {
return v
}
return g.createVertex(vertexType, namespace, name)
}
func (g *graph) getVertex(vertexType VertexType, namespace, name string) (*vertex, bool) {
v, ok := g.vertices[vertexType][namespace][name]
return v, ok
}
func (g *graph) createVertex(vertexType VertexType, namespace, name string) *vertex {
typedVertices, ok := g.vertices[vertexType]
if !ok {
typedVertices = namespaceVertexMapping{}
g.vertices[vertexType] = typedVertices
}
namespacedVertices, ok := typedVertices[namespace]
if !ok {
namespacedVertices = map[string]*vertex{}
typedVertices[namespace] = namespacedVertices
}
v := newVertex(vertexType, namespace, name, g.graph.NewNode().ID())
namespacedVertices[name] = v
g.graph.AddNode(v)
g.logger.Info(
"Added",
"vertex", fmt.Sprintf("%s (%d)", v, v.ID()),
)
return v
}
func (g *graph) deleteVertex(vertexType VertexType, namespace, name string) {
v, ok := g.getVertex(vertexType, namespace, name)
if !ok {
return
}
// Now, visit all neighbors of <v> and check if they can also be removed now that <v> will be removed.
verticesToRemove := []gonumgraph.Node{v}
// Neighbors to which <v> has an outgoing edge can also be removed if they do not have any outgoing edges (to other
// vertices) themselves and if they only have one incoming edge (which must be the edge from <v>).
g.visit(g.graph.From(v.ID()), func(neighbor gonumgraph.Node) {
if g.graph.From(neighbor.ID()).Len() == 0 && g.graph.To(neighbor.ID()).Len() == 1 {
verticesToRemove = append(verticesToRemove, neighbor)
}
})
// Neighbors from which <v> has an incoming edge can also be removed if they do not have any incoming edges (from
// other vertices) themselves and if they only have one outgoing edge (which must be the edge to <v>).
g.visit(g.graph.To(v.ID()), func(neighbor gonumgraph.Node) {
if g.graph.To(neighbor.ID()).Len() == 0 && g.graph.From(neighbor.ID()).Len() == 1 {
verticesToRemove = append(verticesToRemove, neighbor)
}
})
for _, v := range verticesToRemove {
g.removeVertex(v.(*vertex))
}
}
func (g *graph) deleteVertexIfIsolated(v *vertex) {
if g.graph.From(v.ID()).Len() == 0 && g.graph.To(v.ID()).Len() == 0 {
g.removeVertex(v)
}
}
func (g *graph) removeVertex(v *vertex) {
g.graph.RemoveNode(v.ID())
delete(g.vertices[v.vertexType][v.namespace], v.name)
if len(g.vertices[v.vertexType][v.namespace]) == 0 {
delete(g.vertices[v.vertexType], v.namespace)
}
g.logger.Info(
"Removed (with all associated edges)",
"vertex", fmt.Sprintf("%s (%d)", v, v.ID()),
)
}
func (g *graph) addEdge(from, to *vertex) {
g.graph.SetEdge(g.graph.NewEdge(from, to))
g.logger.Info(
"Added edge",
"from", fmt.Sprintf("%s (%d)", from, from.ID()),
"to", fmt.Sprintf("%s (%d)", to, to.ID()),
)
}
func (g *graph) deleteAllIncomingEdges(fromVertexType, toVertexType VertexType, toNamespace, toName string) {
to, ok := g.getVertex(toVertexType, toNamespace, toName)
if !ok {
return
}
// Now, visit all neighbors of <to> who have an incoming edge to <to> and check whether these vertices can be
// removed as well.
var (
verticesToRemove []gonumgraph.Node
edgesToRemove []gonumgraph.Edge
)
// Delete all edges from vertices of type <fromVertexType> to <to>. Neighbors from which <to> has an incoming edge
// can also be removed if they do not have any incoming edges (from other vertices) themselves and if they only have
// one outgoing edge (which must be the edge to <to>).
g.visit(g.graph.To(to.ID()), func(neighbor gonumgraph.Node) {
from, ok := neighbor.(*vertex)
if !ok || from.vertexType != fromVertexType {
return
}
if g.graph.To(neighbor.ID()).Len() == 0 && g.graph.From(neighbor.ID()).Len() == 1 {
verticesToRemove = append(verticesToRemove, neighbor)
} else {
edgesToRemove = append(edgesToRemove, g.graph.Edge(from.ID(), to.ID()))
}
})
for _, v := range verticesToRemove {
g.removeVertex(v.(*vertex))
}
for _, e := range edgesToRemove {
g.removeEdge(e)
}
// If <to> is now isolated, i.e., has neither incoming nor outgoing edges, then we can delete the vertex as well.
g.deleteVertexIfIsolated(to)
}
func (g *graph) deleteAllOutgoingEdges(fromVertexType VertexType, fromNamespace, fromName string, toVertexType VertexType) {
from, ok := g.getVertex(fromVertexType, fromNamespace, fromName)
if !ok {
return
}
// Now, visit all neighbors of <from> who have an outgoing edge from <from> and check whether these vertices can be
// removed as well.
var (
verticesToRemove []gonumgraph.Node
edgesToRemove []gonumgraph.Edge
)
// Delete all edges from <from> to vertices of type <toVertexType>. Neighbors to which <from> has an outgoing edge
// can also be removed if they do not have any outgoing edges (to other vertices) themselves and if they only have
// one incoming edge (which must be the edge from <from>).
g.visit(g.graph.From(from.ID()), func(neighbor gonumgraph.Node) {
to, ok := neighbor.(*vertex)
if !ok || to.vertexType != toVertexType {
return
}
if g.graph.From(neighbor.ID()).Len() == 0 && g.graph.To(neighbor.ID()).Len() == 1 {
verticesToRemove = append(verticesToRemove, neighbor)
} else {
edgesToRemove = append(edgesToRemove, g.graph.Edge(from.ID(), to.ID()))
}
})
for _, v := range verticesToRemove {
g.removeVertex(v.(*vertex))
}
for _, e := range edgesToRemove {
g.removeEdge(e)
}
// If <from> is now isolated, i.e., has neither incoming nor outgoing edges then we can delete the vertex as well.
g.deleteVertexIfIsolated(from)
}
func (g *graph) removeEdge(edge gonumgraph.Edge) {
g.graph.RemoveEdge(edge.From().ID(), edge.To().ID())
g.logger.Info(
"Removed edge",
"from", fmt.Sprintf("%s (%d)", edge.From(), edge.From().ID()),
"to", fmt.Sprintf("%s (%d)", edge.To(), edge.To().ID()),
)
}
func (g *graph) visit(nodes gonumgraph.Nodes, visitor func(gonumgraph.Node)) {
for nodes.Next() {
if node := nodes.Node(); node != nil {
visitor(node)
}
}
}