/
targetconfigcontroller.go
262 lines (228 loc) · 9.3 KB
/
targetconfigcontroller.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
package targetconfigcontroller
import (
"context"
"fmt"
"strings"
"time"
operatorv1 "github.com/openshift/api/operator/v1"
configv1informers "github.com/openshift/client-go/config/informers/externalversions/config/v1"
"github.com/openshift/cluster-etcd-operator/pkg/operator/health"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
"github.com/openshift/library-go/pkg/operator/resource/resourceread"
"github.com/openshift/library-go/pkg/operator/v1helpers"
corev1 "k8s.io/api/core/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
coreclientv1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"github.com/openshift/cluster-etcd-operator/pkg/etcdenvvar"
"github.com/openshift/cluster-etcd-operator/pkg/operator/ceohelpers"
"github.com/openshift/cluster-etcd-operator/pkg/operator/etcd_assets"
"github.com/openshift/cluster-etcd-operator/pkg/operator/operatorclient"
"github.com/openshift/cluster-etcd-operator/pkg/version"
)
type TargetConfigController struct {
targetImagePullSpec string
operatorImagePullSpec string
operatorClient v1helpers.StaticPodOperatorClient
kubeClient kubernetes.Interface
envVarGetter etcdenvvar.EnvVar
enqueueFn func()
quorumChecker ceohelpers.QuorumChecker
}
func NewTargetConfigController(
livenessChecker *health.MultiAlivenessChecker,
targetImagePullSpec, operatorImagePullSpec string,
operatorClient v1helpers.StaticPodOperatorClient,
kubeInformersForOpenshiftEtcdNamespace informers.SharedInformerFactory,
kubeInformersForNamespaces v1helpers.KubeInformersForNamespaces,
infrastructureInformer configv1informers.InfrastructureInformer,
networkInformer configv1informers.NetworkInformer,
masterNodeInformer cache.SharedIndexInformer,
kubeClient kubernetes.Interface,
envVarGetter etcdenvvar.EnvVar,
eventRecorder events.Recorder,
quorumChecker ceohelpers.QuorumChecker,
) factory.Controller {
c := &TargetConfigController{
targetImagePullSpec: targetImagePullSpec,
operatorImagePullSpec: operatorImagePullSpec,
operatorClient: operatorClient,
kubeClient: kubeClient,
envVarGetter: envVarGetter,
quorumChecker: quorumChecker,
}
syncCtx := factory.NewSyncContext("TargetConfigController", eventRecorder.WithComponentSuffix("target-config-controller"))
c.enqueueFn = func() {
syncCtx.Queue().Add(syncCtx.QueueKey())
}
envVarGetter.AddListener(c)
syncer := health.NewDefaultCheckingSyncWrapper(c.sync)
livenessChecker.Add("TargetConfigController", syncer)
return factory.New().WithSyncContext(syncCtx).ResyncEvery(time.Minute).WithInformers(
operatorClient.Informer(),
kubeInformersForNamespaces.InformersFor(operatorclient.TargetNamespace).Core().V1().Endpoints().Informer(),
kubeInformersForOpenshiftEtcdNamespace.Core().V1().ConfigMaps().Informer(),
kubeInformersForOpenshiftEtcdNamespace.Core().V1().Secrets().Informer(),
masterNodeInformer,
infrastructureInformer.Informer(),
networkInformer.Informer(),
).WithSync(syncer.Sync).ToController("TargetConfigController", syncCtx.Recorder())
}
func (c TargetConfigController) sync(ctx context.Context, syncCtx factory.SyncContext) error {
safe, err := c.quorumChecker.IsSafeToUpdateRevision()
if err != nil {
return fmt.Errorf("TargetConfigController can't evaluate whether quorum is safe: %w", err)
}
if !safe {
return fmt.Errorf("skipping TargetConfigController reconciliation due to insufficient quorum")
}
envVars := c.envVarGetter.GetEnvVars()
if len(envVars) == 0 {
return fmt.Errorf("TargetConfigController missing env var values")
}
operatorSpec, _, _, err := c.operatorClient.GetStaticPodOperatorState()
if err != nil {
return err
}
requeue, err := createTargetConfig(ctx, c, syncCtx.Recorder(), operatorSpec, envVars)
if err != nil {
return err
}
if requeue {
return fmt.Errorf("synthetic requeue request")
}
return nil
}
// createTargetConfig takes care of creation of valid resources in a fixed name. These are inputs to other control loops.
// returns whether to requeue and if an error happened when updating status. Normally it updates status itself.
func createTargetConfig(ctx context.Context, c TargetConfigController, recorder events.Recorder,
operatorSpec *operatorv1.StaticPodOperatorSpec, envVars map[string]string) (bool, error) {
var errors []error
contentReplacer, err := c.getSubstitutionReplacer(operatorSpec, c.targetImagePullSpec, c.operatorImagePullSpec, envVars)
if err != nil {
return false, err
}
_, _, err = c.manageStandardPod(ctx, contentReplacer, c.kubeClient.CoreV1(), recorder, operatorSpec)
if err != nil {
errors = append(errors, fmt.Errorf("%q: %v", "configmap/etcd-pod", err))
}
_, _, err = c.manageRecoveryPod(ctx, contentReplacer, c.kubeClient.CoreV1(), recorder, operatorSpec)
if err != nil {
errors = append(errors, fmt.Errorf("%q: %v", "configmap/restore-etcd-pod", err))
}
if len(errors) > 0 {
condition := operatorv1.OperatorCondition{
Type: "TargetConfigControllerDegraded",
Status: operatorv1.ConditionTrue,
Reason: "SynchronizationError",
Message: v1helpers.NewMultiLineAggregate(errors).Error(),
}
if _, _, err := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {
return true, err
}
return true, nil
}
condition := operatorv1.OperatorCondition{
Type: "TargetConfigControllerDegraded",
Status: operatorv1.ConditionFalse,
}
if _, _, err := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {
return true, err
}
return false, nil
}
func loglevelToZap(logLevel operatorv1.LogLevel) string {
switch logLevel {
case operatorv1.Debug, operatorv1.Trace, operatorv1.TraceAll:
return "debug"
default:
return "info"
}
}
func (c *TargetConfigController) getSubstitutionReplacer(operatorSpec *operatorv1.StaticPodOperatorSpec,
imagePullSpec, operatorImagePullSpec string, envVarMap map[string]string) (*strings.Replacer, error) {
var envVarLines []string
for _, k := range sets.StringKeySet(envVarMap).List() {
v := envVarMap[k]
envVarLines = append(envVarLines, fmt.Sprintf(" - name: %q", k))
envVarLines = append(envVarLines, fmt.Sprintf(" value: %q", v))
}
return strings.NewReplacer(
"${IMAGE}", imagePullSpec,
"${OPERATOR_IMAGE}", operatorImagePullSpec,
"${VERBOSITY}", loglevelToZap(operatorSpec.LogLevel),
"${LISTEN_ON_ALL_IPS}", "0.0.0.0", // TODO this needs updating to detect ipv6-ness
"${LOCALHOST_IP}", "127.0.0.1", // TODO this needs updating to detect ipv6-ness
"${COMPUTED_ENV_VARS}", strings.Join(envVarLines, "\n"), // lacks beauty, but it works
), nil
}
func (c *TargetConfigController) manageRecoveryPod(ctx context.Context, substitutionReplacer *strings.Replacer,
client coreclientv1.ConfigMapsGetter, recorder events.Recorder,
operatorSpec *operatorv1.StaticPodOperatorSpec) (*corev1.ConfigMap, bool, error) {
podBytes := etcd_assets.MustAsset("etcd/restore-pod.yaml")
substitutedPodString := substitutionReplacer.Replace(string(podBytes))
podConfigMap := resourceread.ReadConfigMapV1OrDie(etcd_assets.MustAsset("etcd/restore-pod-cm.yaml"))
podConfigMap.Data["pod.yaml"] = substitutedPodString
podConfigMap.Data["forceRedeploymentReason"] = operatorSpec.ForceRedeploymentReason
podConfigMap.Data["version"] = version.Get().String()
return resourceapply.ApplyConfigMap(ctx, client, recorder, podConfigMap)
}
func (c *TargetConfigController) manageStandardPod(ctx context.Context, substitutionReplacer *strings.Replacer,
client coreclientv1.ConfigMapsGetter, recorder events.Recorder,
operatorSpec *operatorv1.StaticPodOperatorSpec) (*corev1.ConfigMap, bool, error) {
podBytes := etcd_assets.MustAsset("etcd/pod.yaml")
substitutedPodString := substitutionReplacer.Replace(string(podBytes))
podConfigMap := resourceread.ReadConfigMapV1OrDie(etcd_assets.MustAsset("etcd/pod-cm.yaml"))
podConfigMap.Data["pod.yaml"] = substitutedPodString
podConfigMap.Data["forceRedeploymentReason"] = operatorSpec.ForceRedeploymentReason
podConfigMap.Data["version"] = version.Get().String()
return resourceapply.ApplyConfigMap(ctx, client, recorder, podConfigMap)
}
func (c *TargetConfigController) Enqueue() {
c.enqueueFn()
}
func (c *TargetConfigController) namespaceEventHandler() cache.ResourceEventHandler {
return cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
ns, ok := obj.(*corev1.Namespace)
if !ok {
c.Enqueue()
}
if ns.Name == ("openshift-etcd") {
c.Enqueue()
}
},
UpdateFunc: func(old, new interface{}) {
ns, ok := old.(*corev1.Namespace)
if !ok {
c.Enqueue()
}
if ns.Name == ("openshift-etcd") {
c.Enqueue()
}
},
DeleteFunc: func(obj interface{}) {
ns, ok := obj.(*corev1.Namespace)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %#v", obj))
return
}
ns, ok = tombstone.Obj.(*corev1.Namespace)
if !ok {
utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a Namespace %#v", obj))
return
}
}
if ns.Name == ("openshift-etcd") {
c.Enqueue()
}
},
}
}