-
Notifications
You must be signed in to change notification settings - Fork 149
/
fluxruntime.go
373 lines (300 loc) · 10.8 KB
/
fluxruntime.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
package server
import (
"context"
"errors"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/weaveworks/weave-gitops/core/clustersmngr"
coretypes "github.com/weaveworks/weave-gitops/core/server/types"
pb "github.com/weaveworks/weave-gitops/pkg/api/core"
"github.com/weaveworks/weave-gitops/pkg/server/auth"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/kustomize/kstatus/status"
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta2"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
)
const (
FluxNamespacePartOf = "flux"
)
var (
KustomizeNameKey = fmt.Sprintf("%s/name", kustomizev1.GroupVersion.Group)
KustomizeNamespaceKey = fmt.Sprintf("%s/namespace", kustomizev1.GroupVersion.Group)
HelmNameKey = fmt.Sprintf("%s/name", helmv2.GroupVersion.Group)
HelmNamespaceKey = fmt.Sprintf("%s/namespace", helmv2.GroupVersion.Group)
// ErrFluxNamespaceNotFound no flux namespace found
ErrFluxNamespaceNotFound = errors.New("could not find flux namespace in cluster")
// ErrListingDeployments no deployments found
ErrListingDeployments = errors.New("could not list deployments in namespace")
)
func (cs *coreServer) ListFluxRuntimeObjects(ctx context.Context, msg *pb.ListFluxRuntimeObjectsRequest) (*pb.ListFluxRuntimeObjectsResponse, error) {
respErrors := []*pb.ListError{}
clustersClient, err := cs.clustersManager.GetImpersonatedClient(ctx, auth.Principal(ctx))
if err != nil {
if merr, ok := err.(*multierror.Error); ok {
for _, err := range merr.Errors {
if cerr, ok := err.(*clustersmngr.ClientError); ok {
respErrors = append(respErrors, &pb.ListError{ClusterName: cerr.ClusterName, Message: cerr.Error()})
}
}
}
}
var results []*pb.Deployment
for clusterName, nss := range cs.clustersManager.GetClustersNamespaces() {
fluxNs := filterFluxNamespace(nss)
if fluxNs == nil {
respErrors = append(respErrors, &pb.ListError{ClusterName: clusterName, Namespace: "", Message: ErrFluxNamespaceNotFound.Error()})
continue
}
opts := client.MatchingLabels{
coretypes.PartOfLabel: FluxNamespacePartOf,
}
list := &appsv1.DeploymentList{}
if err := clustersClient.List(ctx, clusterName, list, opts, client.InNamespace(fluxNs.Name)); err != nil {
respErrors = append(respErrors, &pb.ListError{ClusterName: clusterName, Namespace: fluxNs.Name, Message: fmt.Sprintf("%s, %s", ErrListingDeployments.Error(), err)})
continue
}
for _, d := range list.Items {
r := &pb.Deployment{
Name: d.Name,
Namespace: d.Namespace,
Conditions: []*pb.Condition{},
ClusterName: clusterName,
Uid: string(d.GetUID()),
}
for _, cond := range d.Status.Conditions {
r.Conditions = append(r.Conditions, &pb.Condition{
Message: cond.Message,
Reason: cond.Reason,
Status: string(cond.Status),
Type: string(cond.Type),
})
}
for _, img := range d.Spec.Template.Spec.Containers {
r.Images = append(r.Images, img.Image)
}
results = append(results, r)
}
}
return &pb.ListFluxRuntimeObjectsResponse{Deployments: results, Errors: respErrors}, nil
}
func (cs *coreServer) ListFluxCrds(ctx context.Context, msg *pb.ListFluxCrdsRequest) (*pb.ListFluxCrdsResponse, error) {
clustersClient, err := cs.clustersManager.GetImpersonatedClient(ctx, auth.Principal(ctx))
if err != nil {
return nil, fmt.Errorf("error getting impersonating client: %w", err)
}
var results []*pb.Crd
respErrors := []*pb.ListError{}
opts := client.MatchingLabels{
coretypes.PartOfLabel: FluxNamespacePartOf,
}
list := &apiextensions.CustomResourceDefinitionList{}
if err := clustersClient.List(ctx, msg.ClusterName, list, opts); err != nil {
respErrors = append(respErrors, &pb.ListError{ClusterName: msg.ClusterName, Message: fmt.Sprintf("%s, %s", errors.New("could not list CRDs"), err)})
}
for _, d := range list.Items {
version := ""
if len(d.Spec.Versions) > 0 {
version = d.Spec.Versions[0].Name
}
r := &pb.Crd{
Name: &pb.Crd_Name{
Plural: d.Spec.Names.Plural,
Group: d.Spec.Group},
Version: version,
Kind: d.Spec.Names.Kind,
ClusterName: msg.ClusterName,
Uid: string(d.GetUID()),
}
results = append(results, r)
}
return &pb.ListFluxCrdsResponse{Crds: results, Errors: respErrors}, nil
}
func filterFluxNamespace(nss []v1.Namespace) *v1.Namespace {
for _, ns := range nss {
if val, ok := ns.Labels[coretypes.PartOfLabel]; ok && val == FluxNamespacePartOf {
return &ns
}
}
return nil
}
func (cs *coreServer) GetReconciledObjects(ctx context.Context, msg *pb.GetReconciledObjectsRequest) (*pb.GetReconciledObjectsResponse, error) {
clustersClient, err := cs.clustersManager.GetImpersonatedClientForCluster(ctx, auth.Principal(ctx), msg.ClusterName)
if err != nil {
return nil, fmt.Errorf("error getting impersonating client: %w", err)
}
var opts client.MatchingLabels
switch msg.AutomationKind {
case pb.FluxObjectKind_KindKustomization:
opts = client.MatchingLabels{
KustomizeNameKey: msg.AutomationName,
}
case pb.FluxObjectKind_KindHelmRelease:
opts = client.MatchingLabels{
HelmNameKey: msg.AutomationName,
}
default:
return nil, fmt.Errorf("unsupported application kind: %s", msg.AutomationKind.String())
}
result := []unstructured.Unstructured{}
checkDup := map[types.UID]bool{}
for _, gvk := range msg.Kinds {
listResult := unstructured.UnstructuredList{}
listResult.SetGroupVersionKind(schema.GroupVersionKind{
Group: gvk.Group,
Kind: gvk.Kind,
Version: gvk.Version,
})
if err := clustersClient.List(ctx, msg.ClusterName, &listResult, opts); err != nil {
if k8serrors.IsForbidden(err) {
// Our service account (or impersonated user) may not have the ability to see the resource in question,
// in the given namespace. We pretend it doesn't exist and keep looping.
// We need logging to make this error more visible.
continue
}
return nil, fmt.Errorf("listing unstructured object: %w", err)
}
for _, u := range listResult.Items {
uid := u.GetUID()
if !checkDup[uid] {
result = append(result, u)
checkDup[uid] = true
}
}
}
objects := []*pb.UnstructuredObject{}
for _, obj := range result {
res, err := status.Compute(&obj)
if err != nil {
return nil, fmt.Errorf("could not get status for %s: %w", obj.GetName(), err)
}
var images []string
switch obj.GetKind() {
case "Deployment":
images = getDeploymentPodContainerImages(obj.Object)
}
objects = append(objects, &pb.UnstructuredObject{
GroupVersionKind: &pb.GroupVersionKind{
Group: obj.GetObjectKind().GroupVersionKind().Group,
Version: obj.GetObjectKind().GroupVersionKind().GroupVersion().Version,
Kind: obj.GetKind(),
},
Name: obj.GetName(),
Namespace: obj.GetNamespace(),
Images: images,
Status: res.Status.String(),
Uid: string(obj.GetUID()),
Conditions: mapUnstructuredConditions(res),
ClusterName: msg.GetClusterName(),
})
}
return &pb.GetReconciledObjectsResponse{Objects: objects}, nil
}
func (cs *coreServer) GetChildObjects(ctx context.Context, msg *pb.GetChildObjectsRequest) (*pb.GetChildObjectsResponse, error) {
clustersClient, err := cs.clustersManager.GetImpersonatedClientForCluster(ctx, auth.Principal(ctx), msg.ClusterName)
if err != nil {
return nil, fmt.Errorf("error getting impersonating client: %w", err)
}
listResult := unstructured.UnstructuredList{}
listResult.SetGroupVersionKind(schema.GroupVersionKind{
Group: msg.GroupVersionKind.Group,
Version: msg.GroupVersionKind.Version,
Kind: msg.GroupVersionKind.Kind,
})
if err := clustersClient.List(ctx, msg.ClusterName, &listResult); err != nil {
return nil, fmt.Errorf("could not get unstructured object: %s", err)
}
objects := []*pb.UnstructuredObject{}
ItemsLoop:
for _, obj := range listResult.Items {
refs := obj.GetOwnerReferences()
if len(refs) == 0 {
// Ignore items without OwnerReference.
// for example: dev-weave-gitops-test-connection
continue ItemsLoop
}
for _, ref := range refs {
if ref.UID != types.UID(msg.ParentUid) {
// Assuming all owner references have the same parent UID,
// this is not the child we are looking for.
// Skip the rest of the operations in Items loops.
continue ItemsLoop
}
}
statusResult, err := status.Compute(&obj)
if err != nil {
return nil, fmt.Errorf("could not get status for %s: %w", obj.GetName(), err)
}
var images []string
switch obj.GetKind() {
case "Pod":
images = getPodContainerImages(obj.Object)
case "ReplicaSet":
replicasFound := status.GetIntField(obj.UnstructuredContent(), ".status.replicas", 0)
if replicasFound == 0 {
continue ItemsLoop
}
images = getReplicaSetPodContainerImages(obj.Object)
}
objects = append(objects, &pb.UnstructuredObject{
GroupVersionKind: &pb.GroupVersionKind{
Group: obj.GetObjectKind().GroupVersionKind().Group,
Version: obj.GetObjectKind().GroupVersionKind().GroupVersion().Version,
Kind: obj.GetKind(),
},
Images: images,
Name: obj.GetName(),
Namespace: obj.GetNamespace(),
Status: statusResult.Status.String(),
Uid: string(obj.GetUID()),
Conditions: mapUnstructuredConditions(statusResult),
ClusterName: msg.GetClusterName(),
})
}
return &pb.GetChildObjectsResponse{Objects: objects}, nil
}
func mapUnstructuredConditions(result *status.Result) []*pb.Condition {
conds := []*pb.Condition{}
if result.Status == status.CurrentStatus {
conds = append(conds, &pb.Condition{Type: "Ready", Status: "True", Message: result.Message})
}
return conds
}
func getContainerImages(containers []interface{}) []string {
images := []string{}
for _, item := range containers {
container, ok := item.(map[string]interface{})
if !ok {
continue
}
image, ok, _ := unstructured.NestedString(container, "image")
if ok {
images = append(images, image)
}
}
return images
}
func getPodContainerImages(obj map[string]interface{}) []string {
containers, _, _ := unstructured.NestedSlice(obj, "spec", "containers")
return getContainerImages(containers)
}
func getReplicaSetPodContainerImages(obj map[string]interface{}) []string {
containers, _, _ := unstructured.NestedSlice(
obj,
"spec", "template", "spec", "containers",
)
return getContainerImages(containers)
}
func getDeploymentPodContainerImages(obj map[string]interface{}) []string {
containers, _, _ := unstructured.NestedSlice(
obj,
"spec", "template", "spec", "containers",
)
return getContainerImages(containers)
}