-
Notifications
You must be signed in to change notification settings - Fork 2
/
config_controller.go
71 lines (58 loc) · 2.13 KB
/
config_controller.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
package config
import (
"context"
"fmt"
"time"
"github.com/go-logr/logr"
configv1 "github.com/stolostron/hub-of-hubs-manager/pkg/apis/config/v1"
"github.com/stolostron/hub-of-hubs-manager/pkg/constants"
apierrors "k8s.io/apimachinery/pkg/api/errors"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
const (
requeuePeriodSeconds = 5
configName = "hub-of-hubs-config"
)
// AddConfigController creates a new instance of config controller and adds it to the manager.
func AddConfigController(mgr ctrl.Manager, log logr.Logger, config *configv1.Config) error {
if err := mgr.GetAPIReader().Get(context.Background(), client.ObjectKey{
Namespace: constants.HohSystemNamespace,
Name: configName,
}, config); err != nil {
return fmt.Errorf("failed to read config - %w", err)
}
hubOfHubsConfigCtrl := &hubOfHubsConfigController{
client: mgr.GetClient(),
log: log,
config: config,
}
configPredicate := predicate.NewPredicateFuncs(func(object client.Object) bool {
return object.GetNamespace() == constants.HohSystemNamespace && object.GetName() == configName
})
if err := ctrl.NewControllerManagedBy(mgr).
For(&configv1.Config{}).
WithEventFilter(configPredicate).
Complete(hubOfHubsConfigCtrl); err != nil {
return fmt.Errorf("failed to add config controller to manager - %w", err)
}
return nil
}
type hubOfHubsConfigController struct {
client client.Client
log logr.Logger
config *configv1.Config
}
func (c *hubOfHubsConfigController) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) {
reqLogger := c.log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
if err := c.client.Get(ctx, request.NamespacedName, c.config); apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
} else if err != nil {
reqLogger.Info(fmt.Sprintf("Reconciliation failed: %s", err))
return ctrl.Result{Requeue: true, RequeueAfter: requeuePeriodSeconds * time.Second},
fmt.Errorf("reconciliation failed: %w", err)
}
reqLogger.Info("Reconciliation complete.")
return ctrl.Result{}, nil
}