-
Notifications
You must be signed in to change notification settings - Fork 108
/
operator.go
404 lines (361 loc) · 13.1 KB
/
operator.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
396
397
398
399
400
401
402
403
404
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"runtime"
"strings"
monitoring "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1"
monclientv1 "github.com/coreos/prometheus-operator/pkg/client/versioned/typed/monitoring/v1"
ocpapi "github.com/openshift/api"
mcfgapi "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io"
"github.com/operator-framework/operator-sdk/pkg/k8sutil"
kubemetrics "github.com/operator-framework/operator-sdk/pkg/kube-metrics"
"github.com/operator-framework/operator-sdk/pkg/leader"
"github.com/operator-framework/operator-sdk/pkg/log/zap"
"github.com/operator-framework/operator-sdk/pkg/metrics"
sdkVersion "github.com/operator-framework/operator-sdk/version"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
kerr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/manager"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
"github.com/openshift/compliance-operator/pkg/apis"
compv1alpha1 "github.com/openshift/compliance-operator/pkg/apis/compliance/v1alpha1"
"github.com/openshift/compliance-operator/pkg/controller"
"github.com/openshift/compliance-operator/pkg/controller/common"
ctrlMetrics "github.com/openshift/compliance-operator/pkg/controller/metrics"
"github.com/openshift/compliance-operator/pkg/utils"
)
var operatorCmd = &cobra.Command{
Use: "operator",
Short: "The compliance-operator command",
Long: `An operator that issues compliance checks and their lifecycle.`,
Run: RunOperator,
}
func init() {
rootCmd.AddCommand(operatorCmd)
}
// Change below variables to serve metrics on different host or port.
var (
metricsHost = "0.0.0.0"
metricsServiceName = "metrics"
metricsPort int32 = 8383
operatorMetricsPort int32 = 8686
defaultProducts = []string{
"rhcos4",
"ocp4",
}
serviceMonitorBearerTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
serviceMonitorTLSCAFile = "/etc/prometheus/configmaps/serving-certs-ca-bundle/service-ca.crt"
serviceMonitorTLSServerName = "metrics.openshift-compliance.svc"
)
const (
defaultScanSettingsName = "default"
defaultAutoApplyScanSettingsName = "default-auto-apply"
// Run scan every day at 1am
defaultScanSettingsSchedule = "0 1 * * *"
)
func printVersion() {
log.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
log.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
log.Info(fmt.Sprintf("Version of operator-sdk: %v", sdkVersion.Version))
}
func RunOperator(cmd *cobra.Command, args []string) {
// Add the zap logger flag set to the CLI. The flag set must
// be added before calling pflag.Parse().
flags := cmd.Flags()
flags.AddFlagSet(zap.FlagSet())
// Add flags registered by imported packages (e.g. glog and
// controller-runtime)
flags.AddGoFlagSet(flag.CommandLine)
if err := flags.Parse(zap.FlagSet().Args()); err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse zap flagset: %v", zap.FlagSet().Args())
os.Exit(1)
}
// Use a zap logr.Logger implementation. If none of the zap
// flags are configured (or if the zap flag set is not being
// used), this defaults to a production zap logger.
//
// The logger instantiated here can be changed to any logger
// implementing the logr.Logger interface. This logger will
// be propagated through the whole operator, generating
// uniform and structured logs.
logf.SetLogger(zap.Logger())
printVersion()
namespace, err := k8sutil.GetWatchNamespace()
if err != nil {
log.Error(err, "Failed to get watch namespace")
os.Exit(1)
}
log.Info("Watching", "namespace", namespace)
// Force watch of compliance-operator-namespace so it gets added to the cache
if !strings.Contains(namespace, common.GetComplianceOperatorNamespace()) {
namespace = namespace + "," + common.GetComplianceOperatorNamespace()
}
options := manager.Options{
Namespace: namespace,
MetricsBindAddress: fmt.Sprintf("%s:%d", metricsHost, metricsPort),
}
namespaceList := strings.Split(namespace, ",")
// Add support for MultiNamespace set in WATCH_NAMESPACE (e.g ns1,ns2)
// Note that this is not intended to be used for excluding namespaces, this is better done via a Predicate
// Also note that you may face performance issues when using this with a high number of namespaces.
// More Info: https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg/cache#MultiNamespacedCacheBuilder
if strings.Contains(namespace, ",") {
options.Namespace = ""
options.NewCache = cache.MultiNamespacedCacheBuilder(namespaceList)
}
// Get a config to talk to the apiserver
cfg, err := config.GetConfig()
if err != nil {
log.Error(err, "")
os.Exit(1)
}
ctx := context.TODO()
// Become the leader before proceeding
err = leader.Become(ctx, "compliance-operator-lock")
if err != nil {
log.Error(err, "")
os.Exit(1)
}
kubeClient := kubernetes.NewForConfigOrDie(cfg)
monitoringClient := monclientv1.NewForConfigOrDie(cfg)
// Create a new Cmd to provide shared dependencies and start components
mgr, err := manager.New(cfg, options)
if err != nil {
log.Error(err, "")
os.Exit(1)
}
log.Info("Registering Components.")
mgrscheme := mgr.GetScheme()
// Setup Scheme for all resources
if err := apis.AddToScheme(mgrscheme); err != nil {
log.Error(err, "")
os.Exit(1)
}
if err := mcfgapi.Install(mgrscheme); err != nil {
log.Error(err, "")
os.Exit(1)
}
if err := ocpapi.Install(mgrscheme); err != nil {
log.Info("Couldn't install OCP API. This is not fatal though.")
log.Error(err, "")
}
// Index the ID field of Checks
if err := mgr.GetFieldIndexer().IndexField(ctx, &compv1alpha1.ComplianceCheckResult{}, compv1alpha1.ComplianceRemediationDependencyField, func(rawObj k8sruntime.Object) []string {
check, ok := rawObj.(*compv1alpha1.ComplianceCheckResult)
if !ok {
return []string{}
}
return []string{check.ID}
}); err != nil {
log.Error(err, "Error indexing the ID field of ComplianceCheckResult")
os.Exit(1)
}
met := ctrlMetrics.New()
if err := met.Register(); err != nil {
log.Error(err, "Error registering metrics")
os.Exit(1)
}
// Setup all Controllers
if err := controller.AddToManager(mgr, met); err != nil {
log.Error(err, "")
os.Exit(1)
}
// Add the Metrics Service
addMetrics(ctx, cfg, kubeClient, monitoringClient)
if err := ensureDefaultProfileBundles(ctx, mgr.GetClient(), namespaceList); err != nil {
log.Error(err, "Error creating default ProfileBundles.")
os.Exit(1)
}
if err := ensureDefaultScanSettings(ctx, mgr.GetClient(), namespaceList); err != nil {
log.Error(err, "Error creating default ScanSettings.")
os.Exit(1)
}
log.Info("Starting the Cmd.")
// Start the Cmd
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
log.Error(err, "Manager exited non-zero")
os.Exit(1)
}
}
// addMetrics will create the Services and Service Monitors to allow the operator export the metrics by using
// the Prometheus operator
func addMetrics(ctx context.Context, cfg *rest.Config, kClient *kubernetes.Clientset,
mClient *monclientv1.MonitoringV1Client) {
// Get the namespace the operator is currently deployed in.
operatorNs, err := k8sutil.GetOperatorNamespace()
if err != nil {
if errors.Is(err, k8sutil.ErrRunLocal) {
log.Info("Skipping CR metrics server creation; not running in a cluster.")
return
}
}
if err := serveCRMetrics(cfg, operatorNs); err != nil {
log.Info("Could not generate and serve custom resource metrics", "error", err.Error())
}
// Fetch the metrics service created during the deployment.
metricsService, err := kClient.CoreV1().Services(operatorNs).Get(ctx, metricsServiceName, metav1.GetOptions{})
if err != nil {
log.Error(err, "Error getting metrics service")
os.Exit(1)
}
if err := createServiceMonitor(ctx, cfg, mClient, operatorNs, metricsService); err != nil {
log.Error(err, "Error creating ServiceMonitor")
os.Exit(1)
}
}
func ensureDefaultProfileBundles(ctx context.Context, crclient client.Client, namespaceList []string) error {
pbimg := utils.GetComponentImage(utils.CONTENT)
var lastErr error
for _, prod := range defaultProducts {
for _, ns := range namespaceList {
pb := &compv1alpha1.ProfileBundle{
ObjectMeta: metav1.ObjectMeta{
Name: prod,
Namespace: ns,
},
Spec: compv1alpha1.ProfileBundleSpec{
ContentImage: pbimg,
ContentFile: fmt.Sprintf("ssg-%s-ds.xml", prod),
},
}
if err := ensureSupportedProfileBundle(ctx, crclient, pb); err != nil {
lastErr = err
}
}
}
return lastErr
}
func ensureSupportedProfileBundle(ctx context.Context, crclient client.Client, pb *compv1alpha1.ProfileBundle) error {
createErr := crclient.Create(ctx, pb)
if k8serrors.IsAlreadyExists(createErr) {
return crclient.Patch(ctx, pb, client.Merge)
} else if createErr != nil {
return createErr
}
return nil
}
func ensureDefaultScanSettings(ctx context.Context, crclient client.Client, namespaceList []string) error {
var lastErr error
for _, ns := range namespaceList {
d := &compv1alpha1.ScanSetting{
ObjectMeta: metav1.ObjectMeta{
Name: defaultScanSettingsName,
Namespace: ns,
},
ComplianceSuiteSettings: compv1alpha1.ComplianceSuiteSettings{
Schedule: defaultScanSettingsSchedule,
},
Roles: []string{
"worker",
"master",
},
}
derr := crclient.Create(ctx, d)
if !k8serrors.IsAlreadyExists(derr) {
lastErr = derr
}
a := &compv1alpha1.ScanSetting{
ObjectMeta: metav1.ObjectMeta{
Name: defaultAutoApplyScanSettingsName,
Namespace: ns,
},
ComplianceSuiteSettings: compv1alpha1.ComplianceSuiteSettings{
AutoApplyRemediations: true,
AutoUpdateRemediations: true,
Schedule: defaultScanSettingsSchedule,
},
Roles: []string{
"worker",
"master",
},
}
aerr := crclient.Create(ctx, a)
if !k8serrors.IsAlreadyExists(aerr) {
lastErr = aerr
}
}
return lastErr
}
// createServiceMonitor attempts to create a ServiceMonitor out of service, and updates it to include the controller
// metrics paths.
func createServiceMonitor(ctx context.Context, cfg *rest.Config, mClient *monclientv1.MonitoringV1Client,
namespace string, service *v1.Service) error {
ok, err := k8sutil.ResourceExists(discovery.NewDiscoveryClientForConfigOrDie(cfg),
"monitoring.coreos.com/v1", "ServiceMonitor")
if err != nil {
return err
}
if !ok {
log.Info("Install prometheus-operator in your cluster to create ServiceMonitor objects")
return nil
}
serviceMonitor := metrics.GenerateServiceMonitor(service)
for i := range serviceMonitor.Spec.Endpoints {
if serviceMonitor.Spec.Endpoints[i].Port == ctrlMetrics.ControllerMetricsServiceName {
serviceMonitor.Spec.Endpoints[i].Path = ctrlMetrics.HandlerPath
serviceMonitor.Spec.Endpoints[i].Scheme = "https"
serviceMonitor.Spec.Endpoints[i].BearerTokenFile = serviceMonitorBearerTokenFile
serviceMonitor.Spec.Endpoints[i].TLSConfig = &monitoring.TLSConfig{
CAFile: serviceMonitorTLSCAFile,
ServerName: serviceMonitorTLSServerName,
}
}
}
_, err = mClient.ServiceMonitors(namespace).Create(ctx, serviceMonitor, metav1.CreateOptions{})
if err != nil && !kerr.IsAlreadyExists(err) {
return err
}
if kerr.IsAlreadyExists(err) {
currentServiceMonitor, getErr := mClient.ServiceMonitors(namespace).Get(ctx, serviceMonitor.Name,
metav1.GetOptions{})
if getErr != nil {
return getErr
}
serviceMonitorCopy := currentServiceMonitor.DeepCopy()
serviceMonitorCopy.Spec = serviceMonitor.Spec
if _, updateErr := mClient.ServiceMonitors(namespace).Update(ctx, serviceMonitorCopy,
metav1.UpdateOptions{}); updateErr != nil {
return updateErr
}
}
return nil
}
// serveCRMetrics gets the Operator/CustomResource GVKs and generates metrics based on those types.
// It serves those metrics on "http://metricsHost:operatorMetricsPort".
func serveCRMetrics(cfg *rest.Config, operatorNs string) error {
// The function below returns a list of filtered operator/CR specific GVKs. For more control, override the GVK list below
// with your own custom logic. Note that if you are adding third party API schemas, probably you will need to
// customize this implementation to avoid permissions issues.
filteredGVK, err := k8sutil.GetGVKsFromAddToScheme(apis.AddToScheme)
if err != nil {
return err
}
// The metrics will be generated from the namespaces which are returned here.
// NOTE that passing nil or an empty list of namespaces in GenerateAndServeCRMetrics will result in an error.
ns, err := kubemetrics.GetNamespacesForMetrics(operatorNs)
if err != nil {
return err
}
// Generate and serve custom resource specific metrics.
err = kubemetrics.GenerateAndServeCRMetrics(cfg, ns, filteredGVK, metricsHost, operatorMetricsPort)
if err != nil {
return err
}
return nil
}