-
Notifications
You must be signed in to change notification settings - Fork 26
/
auth_config_status_updater.go
222 lines (181 loc) · 6.83 KB
/
auth_config_status_updater.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
package controllers
import (
"context"
"fmt"
"sort"
"strings"
api "github.com/kuadrant/authorino/api/v1beta1"
"github.com/kuadrant/authorino/pkg/log"
"github.com/kuadrant/authorino/pkg/utils"
"github.com/go-logr/logr"
k8score "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// AuthConfigStatusUpdater updates the status of a newly reconciled auth config
type AuthConfigStatusUpdater struct {
client.Client
Logger logr.Logger
StatusReport *StatusReportMap
LabelSelector labels.Selector
}
// +kubebuilder:rbac:groups=authorino.kuadrant.io,resources=authconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=coordination.k8s.io,resources=leases,verbs=get;list;create;update
func (u *AuthConfigStatusUpdater) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := u.Logger.WithValues("authconfig", req.NamespacedName)
authConfig := api.AuthConfig{}
if err := u.Get(ctx, req.NamespacedName, &authConfig); err != nil && !errors.IsNotFound(err) {
// could not get the resource but not because of a 404 Not found (some error must have happened)
return ctrl.Result{}, err
} else if errors.IsNotFound(err) || !Watched(&authConfig.ObjectMeta, u.LabelSelector) {
// could not find the resource: 404 Not found (resource must have been deleted)
// or the resource misses required labels (i.e. not to be watched by this controller)
// skip status update
return ctrl.Result{}, nil
} else {
// resource found and it is to be watched by this controller
// we need to update its status
if err := u.updateAuthConfigStatus(log.IntoContext(ctx, logger), req.String(), &authConfig); err != nil {
return ctrl.Result{Requeue: true}, nil
} else {
return ctrl.Result{}, nil
}
}
}
func (u *AuthConfigStatusUpdater) updateAuthConfigStatus(ctx context.Context, resourceId string, authConfig *api.AuthConfig) (err error) {
logger := log.FromContext(ctx)
var reason, message string
linkedHosts := []string{}
report, reportAvailable := u.StatusReport.Get(resourceId)
if reportAvailable {
reason = report.Reason
message = report.Message
linkedHosts = report.LinkedHosts
}
looseHosts := utils.SubtractSlice(authConfig.Spec.Hosts, linkedHosts)
// available
changed := updateStatusAvailable(authConfig, len(linkedHosts) > 0)
// ready
ready := len(looseHosts) == 0 && reason == api.StatusReasonReconciled
changed = updateStatusReady(authConfig, ready, reason, message) || changed
// summary
changed = updateStatusSummary(authConfig, linkedHosts) || changed
if !authConfig.Status.Ready() {
err = fmt.Errorf("resource not ready")
}
if !changed {
logger.V(1).Info("resource status did not change")
return // to save an update request
}
logger.V(1).Info("resource status changed", "authconfig/status", authConfig.Status)
if updateErr := u.Status().Update(ctx, authConfig); updateErr != nil {
logger.Error(updateErr, "failed to update the resource")
err = updateErr
return
}
logger.Info("resource status updated")
return
}
func (u *AuthConfigStatusUpdater) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&api.AuthConfig{}, builder.WithPredicates(LabelSelectorPredicate(u.LabelSelector))).
Complete(u)
}
func updateStatusConditions(currentConditions []api.Condition, newCondition api.Condition) ([]api.Condition, bool) {
newCondition.LastTransitionTime = metav1.Now()
if currentConditions == nil {
return []api.Condition{newCondition}, true
}
for i, condition := range currentConditions {
if condition.Type == newCondition.Type {
if condition.Status == newCondition.Status {
if condition.Reason == newCondition.Reason && condition.Message == newCondition.Message {
return currentConditions, false
}
newCondition.LastTransitionTime = condition.LastTransitionTime
}
res := make([]api.Condition, len(currentConditions))
copy(res, currentConditions)
res[i] = newCondition
return res, true
}
}
return append(currentConditions, newCondition), true
}
func updateStatusAvailable(authConfig *api.AuthConfig, available bool) (changed bool) {
status := k8score.ConditionFalse
reason := api.StatusReasonHostsNotLinked
message := "No hosts linked to the resource"
if available {
status = k8score.ConditionTrue
reason = api.StatusReasonHostsLinked
message = ""
}
authConfig.Status.Conditions, changed = updateStatusConditions(authConfig.Status.Conditions, api.Condition{
Type: api.StatusConditionAvailable,
Status: status,
Reason: reason,
Message: utils.CapitalizeString(message),
})
return
}
func updateStatusReady(authConfig *api.AuthConfig, ready bool, reason, message string) (changed bool) {
status := k8score.ConditionFalse
if ready {
status = k8score.ConditionTrue
reason = api.StatusReasonReconciled
message = ""
} else if reason == "" {
reason = api.StatusReasonUnknown
}
authConfig.Status.Conditions, changed = updateStatusConditions(authConfig.Status.Conditions, api.Condition{
Type: api.StatusConditionReady,
Status: status,
Reason: reason,
Message: utils.CapitalizeString(message),
})
return
}
func updateStatusSummary(authConfig *api.AuthConfig, newLinkedHosts []string) (changed bool) {
current := authConfig.Status.Summary
if len(newLinkedHosts) == 0 {
newLinkedHosts = []string{}
}
new := api.Summary{
Ready: authConfig.Status.Ready(),
HostsReady: newLinkedHosts,
NumHostsReady: fmt.Sprintf("%d/%d", len(newLinkedHosts), len(authConfig.Spec.Hosts)),
NumIdentitySources: int64(len(authConfig.Spec.Identity)),
NumMetadataSources: int64(len(authConfig.Spec.Metadata)),
NumAuthorizationPolicies: int64(len(authConfig.Spec.Authorization)),
NumResponseItems: int64(len(authConfig.Spec.Response)),
FestivalWristbandEnabled: issuingWristbands(authConfig),
}
currentLinkedHosts := current.HostsReady
sort.Strings(currentLinkedHosts)
sort.Strings(newLinkedHosts)
changed = new.Ready != current.Ready ||
new.NumHostsReady != current.NumHostsReady ||
strings.Join(currentLinkedHosts, ",") != strings.Join(newLinkedHosts, ",") ||
new.NumIdentitySources != current.NumIdentitySources ||
new.NumMetadataSources != current.NumMetadataSources ||
new.NumAuthorizationPolicies != current.NumAuthorizationPolicies ||
new.NumResponseItems != current.NumResponseItems ||
new.FestivalWristbandEnabled != current.FestivalWristbandEnabled
if changed {
authConfig.Status.Summary = new
}
return
}
func issuingWristbands(authConfig *api.AuthConfig) bool {
for _, responseConfig := range authConfig.Spec.Response {
if responseConfig.GetType() == api.ResponseWristband {
return true
}
}
return false
}