/
observe_apiserver.go
283 lines (241 loc) · 13.6 KB
/
observe_apiserver.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
package apiserver
import (
"fmt"
"strings"
"github.com/imdario/mergo"
"k8s.io/klog/v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
configv1 "github.com/openshift/api/config/v1"
"github.com/openshift/library-go/pkg/operator/configobserver"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/resourcesynccontroller"
"github.com/openshift/cluster-kube-apiserver-operator/pkg/operator/configobservation"
"github.com/openshift/cluster-kube-apiserver-operator/pkg/operator/operatorclient"
)
const (
userServingCertPublicCertFile = "/etc/kubernetes/static-pod-certs/secrets/user-serving-cert/tls.crt"
userServingCertPrivateKeyFile = "/etc/kubernetes/static-pod-certs/secrets/user-serving-cert/tls.key"
namedUserServingCertResourceNameFormat = "user-serving-cert-%03d"
)
var namedUserServingCertResourceNames = []string{
fmt.Sprintf(namedUserServingCertResourceNameFormat, 0),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 1),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 2),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 3),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 4),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 5),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 6),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 7),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 8),
fmt.Sprintf(namedUserServingCertResourceNameFormat, 9),
}
var maxUserNamedCerts = len(namedUserServingCertResourceNames)
// syncActionRules rules define source resource names indexed by destination resource names.
// Empty value means to delete the destination.
type syncActionRules map[string]string
// resourceSyncFunc syncs a resource from the source location to the destination location.
type resourceSyncFunc func(destination, source resourcesynccontroller.ResourceLocation) error
// observeAPIServerConfigFunc observes configuration and returns the observedConfig and a map describing a list of
// resources to sync.
// It returns the observed config, sync rules and possibly an error. Nil sync rules mean to ignore all resources
// in case of error. Otherwise, resources are deleted by default and the returned sync rules are taken as overrides of that.
type observeAPIServerConfigFunc func(apiServer *configv1.APIServer, recorder events.Recorder, previouslyObservedConfig map[string]interface{}, listers *configobservation.Listers) (map[string]interface{}, syncActionRules, []error)
// ObserveUserClientCABundle returns an ObserveConfigFunc that observes a user managed certificate bundle containing
// signers that will be recognized for incoming client certificates in addition to the operator managed signers.
var ObserveUserClientCABundle configobserver.ObserveConfigFunc = (&apiServerObserver{
observerFunc: observeUserClientCABundle,
configPaths: [][]string{},
resourceNames: []string{"user-client-ca"},
resourceType: corev1.ConfigMap{},
}).observe
// ObserveNamedCertificates returns an ObserveConfigFunc that observes user managed TLS cert info for serving secure
// traffic to specific hostnames.
var ObserveNamedCertificates configobserver.ObserveConfigFunc = (&apiServerObserver{
observerFunc: observeNamedCertificates,
configPaths: [][]string{{"servingInfo", "namedCertificates"}},
resourceNames: namedUserServingCertResourceNames,
resourceType: corev1.Secret{},
}).observe
// observeUserClientCABundle observes a user managed ConfigMap containing a certificate bundle for the signers that will
// be recognized for incoming client certificates in addition to the operator managed signers.
func observeUserClientCABundle(apiServer *configv1.APIServer, recorder events.Recorder, previouslyObservedConfig map[string]interface{}, listers *configobservation.Listers) (map[string]interface{}, syncActionRules, []error) {
configMapName := apiServer.Spec.ClientCA.Name
if len(configMapName) == 0 {
return nil, nil, nil // previously observed resource (if any) should be deleted
}
// The user managed client CA bundle will be combined with other operator managed client CA bundles (by the target
// config controller) into a common client CA bundle managed by the operator. As such, since the user managed client
// CA bundle is never explicitly referenced in the kube-apiserver config, the returned observed config will always
// be empty.
return nil, syncActionRules{"user-client-ca": configMapName}, nil
}
// observeNamedCertificates observes user managed Secrets containing TLS cert info for serving secure traffic to
// specific hostnames.
func observeNamedCertificates(apiServer *configv1.APIServer, recorder events.Recorder, previouslyObservedConfig map[string]interface{}, listers *configobservation.Listers) (map[string]interface{}, syncActionRules, []error) {
var errs []error
observedConfig := map[string]interface{}{}
namedCertificates := apiServer.Spec.ServingCerts.NamedCertificates
if len(namedCertificates) > maxUserNamedCerts {
// TODO: This should be validation error, not operator error/event.
err := fmt.Errorf("spec.servingCerts.namedCertificates cannot have more than %d entries", maxUserNamedCerts)
recorder.Warningf("ObserveNamedCertificatesFailed", err.Error())
return previouslyObservedConfig, nil, append(errs, err)
}
// add the named cert info to the observed config. return the previously observed config on any error.
namedCertificatesPath := []string{"servingInfo", "namedCertificates"}
resourceSyncRules := syncActionRules{}
var observedNamedCertificates []interface{}
// these are always present in the config because we mint and rotate them ourselves.
observedNamedCertificates = append(observedNamedCertificates, map[string]interface{}{
"certFile": "/etc/kubernetes/static-pod-certs/secrets/localhost-serving-cert-certkey/tls.crt",
"keyFile": "/etc/kubernetes/static-pod-certs/secrets/localhost-serving-cert-certkey/tls.key"})
observedNamedCertificates = append(observedNamedCertificates, map[string]interface{}{
"certFile": "/etc/kubernetes/static-pod-certs/secrets/service-network-serving-certkey/tls.crt",
"keyFile": "/etc/kubernetes/static-pod-certs/secrets/service-network-serving-certkey/tls.key"})
observedNamedCertificates = append(observedNamedCertificates, map[string]interface{}{
"certFile": "/etc/kubernetes/static-pod-certs/secrets/external-loadbalancer-serving-certkey/tls.crt",
"keyFile": "/etc/kubernetes/static-pod-certs/secrets/external-loadbalancer-serving-certkey/tls.key"})
observedNamedCertificates = append(observedNamedCertificates, map[string]interface{}{
"certFile": "/etc/kubernetes/static-pod-certs/secrets/internal-loadbalancer-serving-certkey/tls.crt",
"keyFile": "/etc/kubernetes/static-pod-certs/secrets/internal-loadbalancer-serving-certkey/tls.key"})
observedNamedCertificates = append(observedNamedCertificates, map[string]interface{}{
"certFile": "/etc/kubernetes/static-pod-resources/secrets/localhost-recovery-serving-certkey/tls.crt",
"keyFile": "/etc/kubernetes/static-pod-resources/secrets/localhost-recovery-serving-certkey/tls.key"})
// specifiedNameToIndex has keys that are namedCertificate.Names and values that are the index they are used in.
// we use this to detect if the same name is specified multiple times and fail.
specifiedNameToIndex := map[string][]string{}
for index, namedCertificate := range namedCertificates {
observedNamedCertificate := map[string]interface{}{}
if len(namedCertificate.Names) > 0 {
if err := unstructured.SetNestedStringSlice(observedNamedCertificate, namedCertificate.Names, "names"); err != nil {
return previouslyObservedConfig, nil, append(errs, err)
}
}
for _, name := range namedCertificate.Names {
specifiedNameToIndex[name] = append(specifiedNameToIndex[name], fmt.Sprintf("%d", index))
}
sourceSecretName := namedCertificate.ServingCertificate.Name
if len(sourceSecretName) == 0 {
err := fmt.Errorf("spec.servingCerts.namedCertificates[%d].servingCertificate.name cannot be empty", index)
recorder.Warningf("ObserveNamedCertificatesFailed", err.Error())
return previouslyObservedConfig, nil, append(errs, err)
}
// check that secret exists and readable by operator
if _, err := listers.ConfigSecretLister().Secrets(operatorclient.GlobalUserSpecifiedConfigNamespace).Get(namedCertificate.ServingCertificate.Name); err != nil {
return previouslyObservedConfig, nil, append(errs, err)
}
// pick one of the available target resource names
targetSecretName := fmt.Sprintf(namedUserServingCertResourceNameFormat, index)
// add a sync rule to copy the user specified secret to the operator namespace
resourceSyncRules[targetSecretName] = sourceSecretName
// add the named certificate to the observed config
certFile := fmt.Sprintf("/etc/kubernetes/static-pod-certs/secrets/%s/tls.crt", targetSecretName)
if err := unstructured.SetNestedField(observedNamedCertificate, certFile, "certFile"); err != nil {
return previouslyObservedConfig, nil, append(errs, err)
}
keyFile := fmt.Sprintf("/etc/kubernetes/static-pod-certs/secrets/%s/tls.key", targetSecretName)
if err := unstructured.SetNestedField(observedNamedCertificate, keyFile, "keyFile"); err != nil {
return previouslyObservedConfig, nil, append(errs, err)
}
observedNamedCertificates = append(observedNamedCertificates, observedNamedCertificate)
}
for name, indexes := range specifiedNameToIndex {
if len(indexes) == 1 {
continue
}
errs = append(errs, fmt.Errorf("spec.servingCerts.namedCertificates[...].servingCertificate.name %q is used by other indexes: [%s]", name, strings.Join(indexes, ",")))
}
if len(observedNamedCertificates) > 0 {
if err := unstructured.SetNestedField(observedConfig, observedNamedCertificates, namedCertificatesPath...); err != nil {
return previouslyObservedConfig, nil, append(errs, err)
}
}
return observedConfig, resourceSyncRules, errs
}
type apiServerObserver struct {
observerFunc observeAPIServerConfigFunc
configPaths [][]string
resourceNames []string
resourceType interface{}
}
func (o *apiServerObserver) observe(genericListers configobserver.Listers, recorder events.Recorder, existingConfig map[string]interface{}) (map[string]interface{}, []error) {
listers := genericListers.(configobservation.Listers)
var errs []error
// pick the correct resource sync function
resourceSync := listers.ResourceSyncer().SyncSecret
if _, ok := o.resourceType.(corev1.ConfigMap); ok {
resourceSync = listers.ResourceSyncer().SyncConfigMap
}
previouslyObservedConfig, errs := extractPreviouslyObservedConfig(existingConfig, o.configPaths...)
apiServer, err := listers.APIServerLister().Get("cluster")
if errors.IsNotFound(err) {
// no error, just clear the observed config and observed resources
return nil, append(errs, syncObservedResources(resourceSync, deleteSyncRules(o.resourceNames...))...)
}
// if something went wrong, keep the previously observed config and resources
if err != nil {
klog.Warningf("error getting apiservers.%s/cluster: %v", configv1.GroupName, err)
return previouslyObservedConfig, append(errs, err)
}
observedConfig, observedResources, errs := o.observerFunc(apiServer, recorder, previouslyObservedConfig, &listers)
// if we get error during observation, skip the merging and return previous config and errors.
if len(errs) > 0 {
klog.Warningf("errors during apiservers.%s/cluster processing: %+v", configv1.GroupName, errs)
return previouslyObservedConfig, errs
}
// default to deleting previous resources, and then merge in observed resources rules
resourceSyncRules := deleteSyncRules(o.resourceNames...)
if err := mergo.Merge(&resourceSyncRules, &observedResources, mergo.WithOverride); err != nil {
klog.Warningf("merging resource sync rules failed: %v", err)
}
errs = append(errs, syncObservedResources(resourceSync, resourceSyncRules)...)
return observedConfig, errs
}
// deleteSyncRules generates resource sync rules to delete the resources, specified by names, from the
// operator namespace.
func deleteSyncRules(names ...string) syncActionRules {
resourceSyncRules := syncActionRules{}
for _, name := range names {
// empty string here means there is "from" anymore and we mark the "name" for deletion.
resourceSyncRules[name] = ""
}
return resourceSyncRules
}
// syncObservedResources copies or deletes resources, sources in GlobalUserSpecifiedConfigNamespace and destinations in OperatorNamespace namespace.
// Errors are collected, i.e. it's not failing on first error.
func syncObservedResources(syncResource resourceSyncFunc, syncRules syncActionRules) []error {
var errs []error
for to, from := range syncRules {
var source resourcesynccontroller.ResourceLocation
if len(from) > 0 {
source = resourcesynccontroller.ResourceLocation{Namespace: operatorclient.GlobalUserSpecifiedConfigNamespace, Name: from}
}
// if 'from' is empty, then it means we want to delete
destination := resourcesynccontroller.ResourceLocation{Namespace: operatorclient.TargetNamespace, Name: to}
if err := syncResource(destination, source); err != nil {
errs = append(errs, err)
}
}
return errs
}
// extractPreviouslyObservedConfig extracts the previously observed config from the existing config.
func extractPreviouslyObservedConfig(existing map[string]interface{}, paths ...[]string) (map[string]interface{}, []error) {
var errs []error
previous := map[string]interface{}{}
for _, fields := range paths {
value, found, err := unstructured.NestedFieldCopy(existing, fields...)
if !found {
continue
}
if err != nil {
errs = append(errs, err)
}
err = unstructured.SetNestedField(previous, value, fields...)
if err != nil {
errs = append(errs, err)
}
}
return previous, errs
}