-
Notifications
You must be signed in to change notification settings - Fork 33
/
state_of_the_world.go
241 lines (216 loc) · 10.4 KB
/
state_of_the_world.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
package controllers
import (
"context"
"fmt"
"strings"
"sync"
certmanagerv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
egv1alpha1 "github.com/envoyproxy/gateway/api/v1alpha1"
"github.com/go-logr/logr"
"github.com/google/go-cmp/cmp"
limitadorv1alpha1 "github.com/kuadrant/limitador-operator/api/v1alpha1"
"github.com/kuadrant/policy-machinery/controller"
"github.com/kuadrant/policy-machinery/machinery"
istioclientgoextensionv1alpha1 "istio.io/client-go/pkg/apis/extensions/v1alpha1"
istioclientnetworkingv1alpha3 "istio.io/client-go/pkg/apis/networking/v1alpha3"
istioclientgosecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/utils/env"
ctrlruntime "sigs.k8s.io/controller-runtime"
gwapiv1 "sigs.k8s.io/gateway-api/apis/v1"
kuadrantv1alpha1 "github.com/kuadrant/kuadrant-operator/api/v1alpha1"
kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1"
kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2"
"github.com/kuadrant/kuadrant-operator/pkg/envoygateway"
"github.com/kuadrant/kuadrant-operator/pkg/istio"
kuadrantgatewayapi "github.com/kuadrant/kuadrant-operator/pkg/library/gatewayapi"
"github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant"
)
var (
ConfigMapGroupKind = schema.GroupKind{Group: corev1.GroupName, Kind: "ConfigMap"}
operatorNamespace = env.GetString("OPERATOR_NAMESPACE", "")
)
//+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gatewayclasses,verbs=list;watch
func NewPolicyMachineryController(manager ctrlruntime.Manager, client *dynamic.DynamicClient, logger logr.Logger) *controller.Controller {
controllerOpts := []controller.ControllerOption{
controller.ManagedBy(manager),
controller.WithLogger(logger),
controller.WithClient(client),
controller.WithRunnable("kuadrant watcher", controller.Watch(&kuadrantv1beta1.Kuadrant{}, kuadrantv1beta1.KuadrantResource, metav1.NamespaceAll)),
controller.WithRunnable("dnspolicy watcher", controller.Watch(&kuadrantv1alpha1.DNSPolicy{}, kuadrantv1alpha1.DNSPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("tlspolicy watcher", controller.Watch(&kuadrantv1alpha1.TLSPolicy{}, kuadrantv1alpha1.TLSPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("authpolicy watcher", controller.Watch(&kuadrantv1beta2.AuthPolicy{}, kuadrantv1beta2.AuthPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("ratelimitpolicy watcher", controller.Watch(&kuadrantv1beta2.RateLimitPolicy{}, kuadrantv1beta2.RateLimitPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("topology configmap watcher", controller.Watch(&corev1.ConfigMap{}, controller.ConfigMapsResource, operatorNamespace, controller.FilterResourcesByLabel[*corev1.ConfigMap](fmt.Sprintf("%s=true", kuadrant.TopologyLabel)))),
controller.WithRunnable("limitador watcher", controller.Watch(&limitadorv1alpha1.Limitador{}, kuadrantv1beta1.LimitadorResource, metav1.NamespaceAll)),
controller.WithPolicyKinds(
kuadrantv1alpha1.DNSPolicyKind,
kuadrantv1alpha1.TLSPolicyKind,
kuadrantv1beta2.AuthPolicyKind,
kuadrantv1beta2.RateLimitPolicyKind,
),
controller.WithObjectKinds(
kuadrantv1beta1.KuadrantKind,
ConfigMapGroupKind,
kuadrantv1beta1.LimitadorKind,
),
controller.WithObjectLinks(
kuadrantv1beta1.LinkKuadrantToGatewayClasses,
kuadrantv1beta1.LinkKuadrantToLimitador,
),
controller.WithReconcile(buildReconciler(client)),
}
ok, err := kuadrantgatewayapi.IsGatewayAPIInstalled(manager.GetRESTMapper())
if err != nil || !ok {
logger.Info("gateway api is not installed, skipping watches and reconcilers", "err", err)
} else {
controllerOpts = append(controllerOpts,
controller.WithRunnable("gatewayclass watcher", controller.Watch(&gwapiv1.GatewayClass{}, controller.GatewayClassesResource, metav1.NamespaceAll)),
controller.WithRunnable("gateway watcher", controller.Watch(&gwapiv1.Gateway{}, controller.GatewaysResource, metav1.NamespaceAll)),
controller.WithRunnable("httproute watcher", controller.Watch(&gwapiv1.HTTPRoute{}, controller.HTTPRoutesResource, metav1.NamespaceAll)),
)
}
ok, err = envoygateway.IsEnvoyGatewayInstalled(manager.GetRESTMapper())
if err != nil || !ok {
logger.Info("envoygateway is not installed, skipping related watches and reconcilers", "err", err)
} else {
controllerOpts = append(controllerOpts,
controller.WithRunnable("envoypatchpolicy watcher", controller.Watch(&egv1alpha1.EnvoyPatchPolicy{}, envoygateway.EnvoyPatchPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("envoyextensionpolicy watcher", controller.Watch(&egv1alpha1.EnvoyExtensionPolicy{}, envoygateway.EnvoyExtensionPoliciesResource, metav1.NamespaceAll)),
controller.WithRunnable("envoysecuritypolicy watcher", controller.Watch(&egv1alpha1.SecurityPolicy{}, envoygateway.SecurityPoliciesResource, metav1.NamespaceAll)),
controller.WithObjectKinds(
envoygateway.EnvoyPatchPolicyGroupKind,
envoygateway.EnvoyExtensionPolicyGroupKind,
envoygateway.SecurityPolicyGroupKind,
),
// TODO: add object links
)
// TODO: add specific tasks to workflow
}
ok, err = istio.IsIstioInstalled(manager.GetRESTMapper())
if err != nil || !ok {
logger.Info("istio is not installed, skipping related watches and reconcilers", "err", err)
} else {
controllerOpts = append(controllerOpts,
controller.WithRunnable("envoyfilter watcher", controller.Watch(&istioclientnetworkingv1alpha3.EnvoyFilter{}, istio.EnvoyFiltersResource, metav1.NamespaceAll)),
controller.WithRunnable("wasmplugin watcher", controller.Watch(&istioclientgoextensionv1alpha1.WasmPlugin{}, istio.WasmPluginsResource, metav1.NamespaceAll)),
controller.WithRunnable("authorizationpolicy watcher", controller.Watch(&istioclientgosecurityv1beta1.AuthorizationPolicy{}, istio.AuthorizationPoliciesResource, metav1.NamespaceAll)),
controller.WithObjectKinds(
istio.EnvoyFilterGroupKind,
istio.WasmPluginGroupKind,
istio.AuthorizationPolicyGroupKind,
),
// TODO: add object links
)
// TODO: add istio specific tasks to workflow
}
ok, err = kuadrantgatewayapi.IsCertManagerInstalled(manager.GetRESTMapper(), logger)
if err != nil || !ok {
logger.Info("cert manager is not installed, skipping related watches and reconcilers", "err", err)
} else {
controllerOpts = append(controllerOpts,
controller.WithRunnable("certificate watcher", controller.Watch(&certmanagerv1.Certificate{}, CertManagerCertificatesResource, metav1.NamespaceAll)),
controller.WithRunnable("issuers watcher", controller.Watch(&certmanagerv1.Issuer{}, CertManagerIssuersResource, metav1.NamespaceAll)),
controller.WithRunnable("clusterissuers watcher", controller.Watch(&certmanagerv1.Certificate{}, CertMangerClusterIssuersResource, metav1.NamespaceAll)),
controller.WithObjectKinds(
CertManagerCertificateKind,
CertManagerIssuerKind,
CertManagerClusterIssuerKind,
),
// TODO: add object links
)
// TODO: add tls policy specific tasks to workflow
}
return controller.NewController(controllerOpts...)
}
func buildReconciler(client *dynamic.DynamicClient) controller.ReconcileFunc {
reconciler := &controller.Workflow{
Precondition: NewEventLogger().Log,
Tasks: []controller.ReconcileFunc{
NewTopologyFileReconciler(client, operatorNamespace).Reconcile,
},
}
return reconciler.Run
}
type TopologyFileReconciler struct {
Client *dynamic.DynamicClient
Namespace string
}
func NewTopologyFileReconciler(client *dynamic.DynamicClient, namespace string) *TopologyFileReconciler {
if namespace == "" {
panic("namespace must be specified and can not be a blank string")
}
return &TopologyFileReconciler{Client: client, Namespace: namespace}
}
func (r *TopologyFileReconciler) Reconcile(ctx context.Context, _ []controller.ResourceEvent, topology *machinery.Topology, _ error, _ *sync.Map) error {
logger := controller.LoggerFromContext(ctx).WithName("topology file")
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "topology",
Namespace: r.Namespace,
Labels: map[string]string{kuadrant.TopologyLabel: "true"},
},
Data: map[string]string{
"topology": topology.ToDot(),
},
}
unstructuredCM, err := controller.Destruct(cm)
if err != nil {
logger.Error(err, "failed to destruct topology configmap")
return err
}
existingTopologyConfigMaps := topology.Objects().Items(func(object machinery.Object) bool {
return object.GetName() == cm.GetName() && object.GetNamespace() == cm.GetNamespace() && object.GroupVersionKind().Kind == ConfigMapGroupKind.Kind
})
if len(existingTopologyConfigMaps) == 0 {
_, err := r.Client.Resource(controller.ConfigMapsResource).Namespace(cm.Namespace).Create(ctx, unstructuredCM, metav1.CreateOptions{})
if err != nil {
logger.Error(err, "failed to write topology configmap")
}
return err
}
if len(existingTopologyConfigMaps) > 1 {
logger.Info("multiple topology configmaps found, continuing but unexpected behaviour may occur")
}
existingTopologyConfigMap := existingTopologyConfigMaps[0].(controller.Object).(*controller.RuntimeObject)
cmTopology := existingTopologyConfigMap.Object.(*corev1.ConfigMap)
if d, found := cmTopology.Data["topology"]; !found || strings.Compare(d, cm.Data["topology"]) != 0 {
_, err := r.Client.Resource(controller.ConfigMapsResource).Namespace(cm.Namespace).Update(ctx, unstructuredCM, metav1.UpdateOptions{})
if err != nil {
logger.Error(err, "failed to update topology configmap")
}
return err
}
return nil
}
type EventLogger struct{}
func NewEventLogger() *EventLogger {
return &EventLogger{}
}
func (e *EventLogger) Log(ctx context.Context, resourceEvents []controller.ResourceEvent, _ *machinery.Topology, err error, _ *sync.Map) error {
logger := controller.LoggerFromContext(ctx).WithName("event logger")
for _, event := range resourceEvents {
// log the event
obj := event.OldObject
if obj == nil {
obj = event.NewObject
}
values := []any{
"type", event.EventType.String(),
"kind", obj.GetObjectKind().GroupVersionKind().Kind,
"namespace", obj.GetNamespace(),
"name", obj.GetName(),
}
if event.EventType == controller.UpdateEvent && logger.V(1).Enabled() {
values = append(values, "diff", cmp.Diff(event.OldObject, event.NewObject))
}
logger.Info("new event", values...)
if err != nil {
logger.Error(err, "error passed to reconcile")
}
}
return nil
}