-
Notifications
You must be signed in to change notification settings - Fork 826
/
statefulset_reconciler.go
236 lines (218 loc) · 7.85 KB
/
statefulset_reconciler.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
/*
Copyright 2022 Seldon Technologies Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"fmt"
"github.com/banzaicloud/k8s-objectmatcher/patch"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"knative.dev/pkg/apis"
"sigs.k8s.io/controller-runtime/pkg/client"
mlopsv1alpha1 "github.com/seldonio/seldon-core/operator/v2/apis/mlops/v1alpha1"
"github.com/seldonio/seldon-core/operator/v2/controllers/reconcilers/common"
"github.com/seldonio/seldon-core/operator/v2/pkg/constants"
"github.com/seldonio/seldon-core/operator/v2/pkg/utils"
)
const (
StatefulSetReadyReason = "StatefulSet replicas matches desired replicas"
StatefulSetNotReadyReason = "StatefulSet replicas does not match desired replicas"
)
type ComponentStatefulSetReconciler struct {
common.ReconcilerConfig
Name string
StatefulSet *appsv1.StatefulSet
Annotator *patch.Annotator
}
func NewComponentStatefulSetReconciler(
name string,
common common.ReconcilerConfig,
meta metav1.ObjectMeta,
podSpec *v1.PodSpec,
volumeClaimTemplates []mlopsv1alpha1.PersistentVolumeClaim,
override *mlopsv1alpha1.OverrideSpec,
seldonConfigMeta metav1.ObjectMeta,
annotator *patch.Annotator,
) *ComponentStatefulSetReconciler {
labels := utils.MergeMaps(meta.Labels, seldonConfigMeta.Labels)
annotations := utils.MergeMaps(meta.Annotations, seldonConfigMeta.Annotations)
return &ComponentStatefulSetReconciler{
ReconcilerConfig: common,
Name: name,
StatefulSet: toStatefulSet(name, meta, podSpec, volumeClaimTemplates, override, labels, annotations),
Annotator: annotator,
}
}
func (s *ComponentStatefulSetReconciler) GetResources() []client.Object {
return []client.Object{s.StatefulSet}
}
func toStatefulSet(
name string,
meta metav1.ObjectMeta,
podSpec *v1.PodSpec,
volumeClaimTemplates []mlopsv1alpha1.PersistentVolumeClaim,
override *mlopsv1alpha1.OverrideSpec,
labels map[string]string,
annotations map[string]string,
) *appsv1.StatefulSet {
var replicas int32
if override != nil && override.Replicas != nil {
replicas = *override.Replicas
} else {
replicas = 1
}
metaLabels := utils.MergeMaps(map[string]string{constants.KubernetesNameLabelKey: name}, labels)
templateLabels := utils.MergeMaps(map[string]string{constants.KubernetesNameLabelKey: name}, labels)
ss := &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: meta.Namespace,
Labels: metaLabels,
Annotations: annotations,
},
Spec: appsv1.StatefulSetSpec{
ServiceName: name,
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{constants.KubernetesNameLabelKey: name},
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: templateLabels,
Annotations: common.CopyMap(annotations),
Name: name,
Namespace: meta.Namespace,
},
Spec: *podSpec,
},
PodManagementPolicy: appsv1.ParallelPodManagement,
},
}
// Add volume claim templates from internal resource
for _, vct := range volumeClaimTemplates {
ss.Spec.VolumeClaimTemplates = append(ss.Spec.VolumeClaimTemplates, v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: vct.Name,
},
Spec: vct.Spec,
})
}
return ss
}
func (s *ComponentStatefulSetReconciler) GetLabelSelector() string {
return fmt.Sprintf("%s=%s", constants.KubernetesNameLabelKey, s.Name)
}
func (s *ComponentStatefulSetReconciler) GetReplicas() (int32, error) {
found := &appsv1.StatefulSet{}
err := s.Client.Get(context.TODO(), types.NamespacedName{
Name: s.StatefulSet.GetName(),
Namespace: s.StatefulSet.GetNamespace(),
}, found)
if err != nil {
if errors.IsNotFound(err) {
return 0, nil
}
return 0, err
}
return found.Status.Replicas, nil
}
func (s *ComponentStatefulSetReconciler) getReconcileOperation() (constants.ReconcileOperation, error) {
found := &appsv1.StatefulSet{}
err := s.Client.Get(context.TODO(), types.NamespacedName{
Name: s.StatefulSet.GetName(),
Namespace: s.StatefulSet.GetNamespace(),
}, found)
if err != nil {
if errors.IsNotFound(err) {
return constants.ReconcileCreateNeeded, nil
}
return constants.ReconcileUnknown, err
}
opts := []patch.CalculateOption{
patch.IgnoreStatusFields(),
patch.IgnoreField("kind"),
patch.IgnoreField("apiVersion"),
patch.IgnoreField("metadata"),
patch.IgnoreVolumeClaimTemplateTypeMetaAndStatus(),
common.IgnoreVolumeClaimTemplateVolumeModel(),
}
patcherMaker := patch.NewPatchMaker(s.Annotator,
&patch.K8sStrategicMergePatcher{},
&patch.BaseJSONMergePatcher{},
)
patchResult, err := patcherMaker.Calculate(found, s.StatefulSet, opts...)
if err != nil {
return constants.ReconcileUnknown, err
}
s.StatefulSet.Status = found.Status
if patchResult.IsEmpty() {
// Update our version so we have Status which can be used
s.StatefulSet = found
return constants.ReconcileNoChange, nil
}
s.Logger.Info("stateful set difference", "diff", patchResult.String())
err = s.Annotator.SetLastAppliedAnnotation(s.StatefulSet)
if err != nil {
return constants.ReconcileUnknown, err
}
// Update resource version so we can do a client Update successfully
// This needs to be done after we annotate to also avoid false differences
s.StatefulSet.SetResourceVersion(found.ResourceVersion)
return constants.ReconcileUpdateNeeded, nil
}
func (s *ComponentStatefulSetReconciler) Reconcile() error {
logger := s.Logger.WithName("StatefulSetReconcile")
op, err := s.getReconcileOperation()
switch op {
case constants.ReconcileCreateNeeded:
logger.V(1).Info("StatefulSet Create", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
err = s.Client.Create(s.Ctx, s.StatefulSet)
if err != nil {
logger.Error(err, "Failed to create statefuleset", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
return err
}
case constants.ReconcileUpdateNeeded:
logger.V(1).Info("StatefulSet Update", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
err = s.Client.Update(s.Ctx, s.StatefulSet)
if err != nil {
logger.Error(err, "Failed to update statefuleset", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
return err
}
case constants.ReconcileNoChange:
err = nil
logger.V(1).Info("StatefulSet No Change", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
case constants.ReconcileUnknown:
if err != nil {
logger.Error(err, "Failed to get reconcile operation for statefulset", "Name", s.StatefulSet.GetName(), "Namespace", s.StatefulSet.GetNamespace())
return err
}
return err
}
return nil
}
func (s *ComponentStatefulSetReconciler) GetConditions() []*apis.Condition {
ready := s.StatefulSet.Status.ReadyReplicas >= s.StatefulSet.Status.Replicas
s.Logger.Info("Checking conditions for stateful set", "ready", ready, "replicas", s.StatefulSet.Status.Replicas, "availableReplicas", s.StatefulSet.Status.AvailableReplicas)
if conditionType, ok := mlopsv1alpha1.ConditionNameMap[s.Name]; ok {
if ready {
return []*apis.Condition{mlopsv1alpha1.CreateCondition(conditionType, ready, StatefulSetReadyReason)}
} else {
return []*apis.Condition{mlopsv1alpha1.CreateCondition(conditionType, ready, StatefulSetNotReadyReason)}
}
} else {
return []*apis.Condition{}
}
}