forked from kubevirt/hyperconverged-cluster-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssp.go
373 lines (307 loc) · 11.6 KB
/
ssp.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package operands
import (
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
cdiv1beta1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
sspv1beta2 "kubevirt.io/ssp-operator/api/v1beta2"
hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1"
"github.com/kubevirt/hyperconverged-cluster-operator/controllers/common"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/util"
hcoutil "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util"
)
const (
// This is initially set to 2 replicas, to maintain the behavior of the previous SSP operator.
// After SSP implements its defaulting webhook, we can change this to 0 replicas,
// and let the webhook set the default.
defaultTemplateValidatorReplicas = int32(2)
defaultCommonTemplatesNamespace = hcoutil.OpenshiftNamespace
dataImportCronTemplatesFileLocation = "./dataImportCronTemplates"
CDIImmediateBindAnnotation = "cdi.kubevirt.io/storage.bind.immediate.requested"
)
var (
// dataImportCronTemplateHardCodedMap are set of data import cron template configurations. The handler reads a list
// of data import cron templates from a local file and updates SSP with the up-to-date list
dataImportCronTemplateHardCodedMap map[string]hcov1beta1.DataImportCronTemplate
)
func init() {
if err := readDataImportCronTemplatesFromFile(); err != nil {
panic(fmt.Errorf("can't process the data import cron template file; %s; %w", err.Error(), err))
}
}
type sspHandler genericOperand
func newSspHandler(Client client.Client, Scheme *runtime.Scheme) *sspHandler {
return &sspHandler{
Client: Client,
Scheme: Scheme,
crType: "SSP",
setControllerReference: false,
hooks: &sspHooks{},
}
}
type sspHooks struct {
cache *sspv1beta2.SSP
dictStatuses []hcov1beta1.DataImportCronTemplateStatus
}
func (h *sspHooks) getFullCr(hc *hcov1beta1.HyperConverged) (client.Object, error) {
if h.cache == nil {
ssp, dictStatus, err := NewSSP(hc)
if err != nil {
return nil, err
}
h.cache = ssp
h.dictStatuses = dictStatus
}
return h.cache, nil
}
func (*sspHooks) getEmptyCr() client.Object { return &sspv1beta2.SSP{} }
func (*sspHooks) getConditions(cr runtime.Object) []metav1.Condition {
return osConditionsToK8s(cr.(*sspv1beta2.SSP).Status.Conditions)
}
func (*sspHooks) checkComponentVersion(cr runtime.Object) bool {
found := cr.(*sspv1beta2.SSP)
return checkComponentVersion(hcoutil.SspVersionEnvV, found.Status.ObservedVersion)
}
func (h *sspHooks) reset() {
h.cache = nil
h.dictStatuses = nil
}
func (*sspHooks) updateCr(req *common.HcoRequest, client client.Client, exists runtime.Object, required runtime.Object) (bool, bool, error) {
ssp, ok1 := required.(*sspv1beta2.SSP)
found, ok2 := exists.(*sspv1beta2.SSP)
if !ok1 || !ok2 {
return false, false, errors.New("can't convert to SSP")
}
if !reflect.DeepEqual(ssp.Spec, found.Spec) ||
!util.CompareLabels(ssp, found) {
if req.HCOTriggered {
req.Logger.Info("Updating existing SSP's Spec to new opinionated values")
} else {
req.Logger.Info("Reconciling an externally updated SSP's Spec to its opinionated values")
}
util.MergeLabels(&ssp.ObjectMeta, &found.ObjectMeta)
ssp.Spec.DeepCopyInto(&found.Spec)
err := client.Update(req.Ctx, found)
if err != nil {
return false, false, err
}
return true, !req.HCOTriggered, nil
}
return false, false, nil
}
func (h *sspHooks) justBeforeComplete(req *common.HcoRequest) {
if !reflect.DeepEqual(h.dictStatuses, req.Instance.Status.DataImportCronTemplates) {
req.Instance.Status.DataImportCronTemplates = h.dictStatuses
req.StatusDirty = true
}
}
func NewSSP(hc *hcov1beta1.HyperConverged, opts ...string) (*sspv1beta2.SSP, []hcov1beta1.DataImportCronTemplateStatus, error) {
templatesNamespace := defaultCommonTemplatesNamespace
if hc.Spec.CommonTemplatesNamespace != nil {
templatesNamespace = *hc.Spec.CommonTemplatesNamespace
}
applyDataImportSchedule(hc)
dataImportCronStatuses, err := getDataImportCronTemplates(hc)
if err != nil {
return nil, nil, err
}
var dataImportCronTemplates []hcov1beta1.DataImportCronTemplate
for _, dictStatus := range dataImportCronStatuses {
dataImportCronTemplates = append(dataImportCronTemplates, dictStatus.DataImportCronTemplate)
}
spec := sspv1beta2.SSPSpec{
TemplateValidator: &sspv1beta2.TemplateValidator{
Replicas: ptr.To(defaultTemplateValidatorReplicas),
},
CommonTemplates: sspv1beta2.CommonTemplates{
Namespace: templatesNamespace,
DataImportCronTemplates: hcoDictSliceToSSP(dataImportCronTemplates),
},
// NodeLabeller field is explicitly initialized to its zero-value,
// in order to future-proof from bugs if SSP changes it to pointer-type,
// causing nil pointers dereferences at the DeepCopyInto() below.
TLSSecurityProfile: hcoutil.GetClusterInfo().GetTLSSecurityProfile(hc.Spec.TLSSecurityProfile),
FeatureGates: &sspv1beta2.FeatureGates{},
}
if hc.Spec.FeatureGates.DeployVMConsoleProxy != nil {
spec.TokenGenerationService = &sspv1beta2.TokenGenerationService{
Enabled: *hc.Spec.FeatureGates.DeployVMConsoleProxy,
}
}
// Disable common-instancetypes deployment by SSP from 4.16, now handled by virt-operator
spec.FeatureGates.DeployCommonInstancetypes = ptr.To(false)
if hc.Spec.Infra.NodePlacement != nil {
spec.TemplateValidator.Placement = hc.Spec.Infra.NodePlacement.DeepCopy()
}
ssp := NewSSPWithNameOnly(hc)
ssp.Spec = spec
if err := applyPatchToSpec(hc, common.JSONPatchSSPAnnotationName, ssp); err != nil {
return nil, nil, err
}
return ssp, dataImportCronStatuses, nil
}
func NewSSPWithNameOnly(hc *hcov1beta1.HyperConverged, opts ...string) *sspv1beta2.SSP {
return &sspv1beta2.SSP{
ObjectMeta: metav1.ObjectMeta{
Name: "ssp-" + hc.Name,
Labels: getLabels(hc, hcoutil.AppComponentSchedule),
Namespace: getNamespace(hc.Namespace, opts),
},
}
}
var getDataImportCronTemplatesFileLocation = func() string {
return dataImportCronTemplatesFileLocation
}
func readDataImportCronTemplatesFromFile() error {
dataImportCronTemplateHardCodedMap = make(map[string]hcov1beta1.DataImportCronTemplate)
fileLocation := getDataImportCronTemplatesFileLocation()
err := util.ValidateManifestDir(fileLocation)
if err != nil {
return errors.Unwrap(err) // if not wrapped, then it's not an error that stops processing, and it returns nil
}
return filepath.Walk(fileLocation, func(filePath string, info fs.FileInfo, internalErr error) error {
if internalErr != nil {
return internalErr
}
if !info.IsDir() && path.Ext(info.Name()) == ".yaml" {
file, internalErr := os.Open(filePath)
if internalErr != nil {
logger.Error(internalErr, "Can't open the dataImportCronTemplate yaml file", "file name", filePath)
return internalErr
}
dataImportCronTemplateFromFile := make([]hcov1beta1.DataImportCronTemplate, 0)
internalErr = util.UnmarshalYamlFileToObject(file, &dataImportCronTemplateFromFile)
if internalErr != nil {
return internalErr
}
for _, dict := range dataImportCronTemplateFromFile {
dataImportCronTemplateHardCodedMap[dict.Name] = dict
}
}
return nil
})
}
func getDataImportCronTemplates(hc *hcov1beta1.HyperConverged) ([]hcov1beta1.DataImportCronTemplateStatus, error) {
crDicts, err := getDicMapFromCr(hc)
if err != nil {
return nil, err
}
var dictList []hcov1beta1.DataImportCronTemplateStatus
if hc.Spec.EnableCommonBootImageImport != nil && *hc.Spec.EnableCommonBootImageImport {
dictList = getCommonDicts(dictList, crDicts, hc)
}
dictList = getCustomDicts(dictList, crDicts)
sort.Sort(dataImportTemplateSlice(dictList))
return dictList, nil
}
func getCommonDicts(list []hcov1beta1.DataImportCronTemplateStatus, crDicts map[string]hcov1beta1.DataImportCronTemplate, hc *hcov1beta1.HyperConverged) []hcov1beta1.DataImportCronTemplateStatus {
for dictName, commonDict := range dataImportCronTemplateHardCodedMap {
targetDict := hcov1beta1.DataImportCronTemplateStatus{
DataImportCronTemplate: *commonDict.DeepCopy(),
Status: hcov1beta1.DataImportCronStatus{
CommonTemplate: true,
},
}
if crDict, found := crDicts[dictName]; found {
if !isDataImportCronTemplateEnabled(crDict) {
continue
}
// if the schedule is missing, copy from the common dict:
if len(crDict.Spec.Schedule) == 0 {
crDict.Spec.Schedule = targetDict.Spec.Schedule
}
targetDict.Spec = crDict.Spec.DeepCopy()
targetDict.ObjectMeta.Namespace = crDict.Namespace
targetDict.Status.Modified = true
} else if ns := hc.Spec.CommonBootImageNamespace; ns != nil && len(*ns) > 0 {
targetDict.ObjectMeta.Namespace = *ns
}
list = append(list, targetDict)
}
return list
}
func isDataImportCronTemplateEnabled(dict hcov1beta1.DataImportCronTemplate) bool {
annotationVal, found := dict.Annotations[hcoutil.DataImportCronEnabledAnnotation]
return !found || strings.ToLower(annotationVal) == "true"
}
func getCustomDicts(list []hcov1beta1.DataImportCronTemplateStatus, crDicts map[string]hcov1beta1.DataImportCronTemplate) []hcov1beta1.DataImportCronTemplateStatus {
for dictName, crDict := range crDicts {
if !isDataImportCronTemplateEnabled(crDict) {
continue
}
if _, isCommon := dataImportCronTemplateHardCodedMap[dictName]; !isCommon {
list = append(list, hcov1beta1.DataImportCronTemplateStatus{
DataImportCronTemplate: *crDict.DeepCopy(),
Status: hcov1beta1.DataImportCronStatus{
CommonTemplate: false,
},
})
}
}
return list
}
func getDicMapFromCr(hc *hcov1beta1.HyperConverged) (map[string]hcov1beta1.DataImportCronTemplate, error) {
dictMap := make(map[string]hcov1beta1.DataImportCronTemplate)
for _, dict := range hc.Spec.DataImportCronTemplates {
_, foundCustom := dictMap[dict.Name]
if foundCustom {
return nil, fmt.Errorf("%s DataImportCronTable is already defined", dict.Name)
}
dictMap[dict.Name] = dict
}
return dictMap, nil
}
func applyDataImportSchedule(hc *hcov1beta1.HyperConverged) {
if hc.Status.DataImportSchedule != "" {
overrideDataImportSchedule(hc.Status.DataImportSchedule)
}
}
func overrideDataImportSchedule(schedule string) {
for dictName := range dataImportCronTemplateHardCodedMap {
dict := dataImportCronTemplateHardCodedMap[dictName]
dict.Spec.Schedule = schedule
dataImportCronTemplateHardCodedMap[dictName] = dict
}
}
// implement sort.Interface
type dataImportTemplateSlice []hcov1beta1.DataImportCronTemplateStatus
func (d dataImportTemplateSlice) Len() int { return len(d) }
func (d dataImportTemplateSlice) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d dataImportTemplateSlice) Less(i, j int) bool { return d[i].Name < d[j].Name }
func hcoDictToSSP(hcoDict hcov1beta1.DataImportCronTemplate) sspv1beta2.DataImportCronTemplate {
spec := cdiv1beta1.DataImportCronSpec{}
if hcoDict.Spec != nil {
hcoDict.Spec.DeepCopyInto(&spec)
}
dict := sspv1beta2.DataImportCronTemplate{
ObjectMeta: *hcoDict.ObjectMeta.DeepCopy(),
Spec: spec,
}
if dict.Annotations == nil {
dict.Annotations = make(map[string]string)
}
if _, foundAnnotation := dict.Annotations[CDIImmediateBindAnnotation]; !foundAnnotation {
dict.Annotations[CDIImmediateBindAnnotation] = "true"
}
return dict
}
func hcoDictSliceToSSP(hcoDicts []hcov1beta1.DataImportCronTemplate) []sspv1beta2.DataImportCronTemplate {
if len(hcoDicts) == 0 {
return nil
}
res := make([]sspv1beta2.DataImportCronTemplate, len(hcoDicts))
for i, hcoDict := range hcoDicts {
res[i] = hcoDictToSSP(hcoDict)
}
return res
}