/
operator.go
464 lines (382 loc) · 12.5 KB
/
operator.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package decorators
import (
"fmt"
"sort"
"strings"
"github.com/itchyny/gojq"
"github.com/mitchellh/mapstructure"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/reference"
operatorsv1 "github.com/operator-framework/api/pkg/operators/v1"
operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/codec"
)
const (
newOperatorError = "cannot create new Operator: %s"
newComponentError = "cannot create new Component: %s"
componentLabelKeyError = "cannot generate component label key: %s"
// ComponentLabelKeyPrefix is the key prefix used for labels marking operator component resources.
ComponentLabelKeyPrefix = "operators.coreos.com/"
)
var (
csvGVK = operatorsv1alpha1.SchemeGroupVersion.WithKind(operatorsv1alpha1.ClusterServiceVersionKind)
componentConditionsJQ *gojq.Query
csvConditionsJQ *gojq.Query
)
func init() {
var err error
if componentConditionsJQ, err = gojq.Parse(".status.conditions"); err != nil {
panic(fmt.Errorf("failed to parse component conditions jq: %s", err))
}
if csvConditionsJQ, err = gojq.Parse(".status | [{\"type\": .phase, \"status\": \"True\", \"reason\": .reason, \"message\": .message, \"lastUpdateTime\": .lastUpdateTime,\"lastTransitionTime\": .lastTransitionTime}]"); err != nil {
panic(fmt.Errorf("failed to parse csv conditions jq: %s", err))
}
}
// OperatorNames returns a list of operator names extracted from the given labels.
func OperatorNames(labels map[string]string) (names []types.NamespacedName) {
for key := range labels {
if !strings.HasPrefix(key, ComponentLabelKeyPrefix) {
continue
}
names = append(names, types.NamespacedName{
Name: strings.TrimPrefix(key, ComponentLabelKeyPrefix),
})
}
return
}
type OperatorFactory interface {
// NewOperator returns an Operator decorator that wraps the given external Operator representation.
// An error is returned if the decorator cannon be instantiated.
NewOperator(external *operatorsv1.Operator) (*Operator, error)
// NewPackageOperator returns an Operator decorator for a package and install namespace.
NewPackageOperator(pkg, namespace string) (*Operator, error)
}
// schemedOperatorFactory is an OperatorFactory that instantiates Operator decorators with a shared scheme.
type schemedOperatorFactory struct {
scheme *runtime.Scheme
}
func (s *schemedOperatorFactory) NewOperator(external *operatorsv1.Operator) (*Operator, error) {
if external == nil {
return nil, fmt.Errorf(newOperatorError, "cannot create operator with nil external type")
}
return &Operator{
Operator: external.DeepCopy(),
scheme: s.scheme,
}, nil
}
// NewPackageOperator returns an Operator decorator for a package and install namespace.
// The decorator's name is in the form "<package>.<namespace>" and is truncated to a maximum length of 63 characters to abide by the label key character set and conventions (see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set).
func (s *schemedOperatorFactory) NewPackageOperator(pkg, namespace string) (*Operator, error) {
var name string
if namespace == corev1.NamespaceAll {
// No additional namespace qualifier to add
name = pkg
} else {
name = fmt.Sprintf("%s.%s", pkg, namespace)
}
o := &operatorsv1.Operator{}
o.SetName(name)
return s.NewOperator(o)
}
// NewSchemedOperatorFactory returns an OperatorFactory that supplies a scheme to all Operators it creates.
func NewSchemedOperatorFactory(scheme *runtime.Scheme) (OperatorFactory, error) {
if scheme == nil {
return nil, fmt.Errorf("cannot create factory with nil scheme")
}
return &schemedOperatorFactory{
scheme: scheme,
}, nil
}
// Operator decorates an external Operator and provides convenience methods for managing it.
type Operator struct {
*operatorsv1.Operator
scheme *runtime.Scheme
componentLabelKey string
}
// ComponentLabelKey returns the operator's completed component label key.
func (o *Operator) ComponentLabelKey() (string, error) {
if o.componentLabelKey != "" {
return o.componentLabelKey, nil
}
name := o.GetName()
if name == "" {
return "", fmt.Errorf(componentLabelKeyError, "empty name field")
}
if len(name) > 63 {
// Truncate
name = name[0:63]
// Remove trailing illegal characters
idx := len(name) - 1
for ; idx >= 0; idx-- {
lastChar := name[idx]
if lastChar != '.' && lastChar != '_' && lastChar != '-' {
break
}
}
// Just being defensive. This is unlikely to happen since the operator name should
// be compatible kubernetes naming constraints
if idx < 0 {
return "", fmt.Errorf(componentLabelKeyError, "unsupported name field")
}
// Update Label
name = name[0 : idx+1]
}
o.componentLabelKey = ComponentLabelKeyPrefix + name
return o.componentLabelKey, nil
}
// ComponentLabelSelector returns a LabelSelector that matches this operator's component label.
func (o *Operator) ComponentLabelSelector() (*metav1.LabelSelector, error) {
key, err := o.ComponentLabelKey()
if err != nil {
return nil, err
}
labelSelector := &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: key,
Operator: metav1.LabelSelectorOpExists,
},
},
}
return labelSelector, nil
}
// NonComponentLabelSelector returns a LabelSelector that matches resources that do not have this operator's component label.
func (o *Operator) NonComponentLabelSelector() (*metav1.LabelSelector, error) {
key, err := o.ComponentLabelKey()
if err != nil {
return nil, err
}
labelSelector := &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: key,
Operator: metav1.LabelSelectorOpDoesNotExist,
},
},
}
return labelSelector, nil
}
// ComponentSelector returns a Selector that matches this operator's component label.
func (o *Operator) ComponentSelector() (labels.Selector, error) {
labelSelector, err := o.ComponentLabelSelector()
if err != nil {
return nil, err
}
return metav1.LabelSelectorAsSelector(labelSelector)
}
// NonComponentSelector returns a Selector that matches resources that do not have this operator's component label.
func (o *Operator) NonComponentSelector() (labels.Selector, error) {
labelSelector, err := o.NonComponentLabelSelector()
if err != nil {
return nil, err
}
return metav1.LabelSelectorAsSelector(labelSelector)
}
// ResetComponents resets the component selector and references in the operator's status.
func (o *Operator) ResetComponents() error {
labelSelector, err := o.ComponentLabelSelector()
if err != nil {
return err
}
o.Status.Components = &operatorsv1.Components{
LabelSelector: labelSelector,
}
return nil
}
// AdoptComponent adds the operator's component label to the given component, returning true if the
// component label was added and false if it already existed.
func (o *Operator) AdoptComponent(component runtime.Object) (adopted bool, err error) {
var labelKey string
if labelKey, err = o.ComponentLabelKey(); err != nil {
return
}
var m metav1.Object
if m, err = meta.Accessor(component); err != nil {
return
}
labels := m.GetLabels()
if labels == nil {
labels = map[string]string{}
m.SetLabels(labels)
}
if _, ok := labels[labelKey]; !ok {
labels[labelKey] = ""
adopted = true
}
return
}
// DisownComponent removes the operator's component label from the given component, returning true if the
// component label was removed and false if it wasn't present.
func (o *Operator) DisownComponent(component runtime.Object) (disowned bool, err error) {
var labelKey string
if labelKey, err = o.ComponentLabelKey(); err != nil {
return
}
var m metav1.Object
if m, err = meta.Accessor(component); err != nil {
return
}
labels := m.GetLabels()
if len(labels) < 1 {
// Not a component
return
}
if _, ok := labels[labelKey]; ok {
disowned = true
}
delete(labels, labelKey)
m.SetLabels(labels)
return
}
// AddComponents adds the given components to the operator's status and returns an error
// if a component isn't associated with the operator by label.
// List type arguments are flattened to their nested elements before being added.
func (o *Operator) AddComponents(components ...runtime.Object) error {
selector, err := o.ComponentSelector()
if err != nil {
return err
}
var refs []operatorsv1.RichReference
for _, obj := range components {
// Unpack nested components
if nested, err := meta.ExtractList(obj); err == nil {
if err = o.AddComponents(nested...); err != nil {
return err
}
continue
}
component, err := NewComponent(obj, o.scheme)
if err != nil {
return err
}
if matches, err := component.Matches(selector); err != nil {
return err
} else if !matches {
return fmt.Errorf("cannot add component %s/%s/%s to Operator %s: component labels not selected by %s", component.GetKind(), component.GetNamespace(), component.GetName(), o.GetName(), selector.String())
}
ref, err := component.Reference()
if err != nil {
return err
}
refs = append(refs, *ref)
}
if o.Status.Components == nil {
if err := o.ResetComponents(); err != nil {
return err
}
}
o.Status.Components.Refs = append(o.Status.Components.Refs, refs...)
// Sort the component refs to so subsequent reconciles of the object do not change
// the status and result in an update to the object.
sort.SliceStable(o.Status.Components.Refs, func(i, j int) bool {
if o.Status.Components.Refs[i].Kind != o.Status.Components.Refs[j].Kind {
return o.Status.Components.Refs[i].Kind < o.Status.Components.Refs[j].Kind
}
if o.Status.Components.Refs[i].APIVersion != o.Status.Components.Refs[j].APIVersion {
return o.Status.Components.Refs[i].APIVersion < o.Status.Components.Refs[j].APIVersion
}
if o.Status.Components.Refs[i].Namespace != o.Status.Components.Refs[j].Namespace {
return o.Status.Components.Refs[i].Namespace < o.Status.Components.Refs[j].Namespace
}
return o.Status.Components.Refs[i].Name < o.Status.Components.Refs[j].Name
})
return nil
}
// SetComponents sets the component references in the operator's status to the given components.
func (o *Operator) SetComponents(components ...runtime.Object) error {
if err := o.ResetComponents(); err != nil {
return err
}
return o.AddComponents(components...)
}
type Component struct {
*unstructured.Unstructured
scheme *runtime.Scheme
}
// NewComponent returns a new Component instance.
func NewComponent(component runtime.Object, scheme *runtime.Scheme) (*Component, error) {
if component == nil {
return nil, fmt.Errorf(newComponentError, "nil component")
}
if scheme == nil {
return nil, fmt.Errorf(newComponentError, "nil scheme")
}
u := &unstructured.Unstructured{}
if err := scheme.Convert(component, u, nil); err != nil {
return nil, err
}
// GVK may have been lost from PartialObjectMetadata during conversion.
if gvk := component.GetObjectKind().GroupVersionKind(); gvk != schema.EmptyObjectKind.GroupVersionKind() {
u.SetGroupVersionKind(gvk)
}
c := &Component{
Unstructured: u,
scheme: scheme,
}
return c, nil
}
func (c *Component) Matches(selector labels.Selector) (matches bool, err error) {
m, err := meta.Accessor(c)
if err != nil {
return
}
matches = selector.Matches(labels.Set(m.GetLabels()))
return
}
func (c *Component) Reference() (ref *operatorsv1.RichReference, err error) {
truncated, err := c.truncatedReference()
if err != nil {
return
}
ref = &operatorsv1.RichReference{
ObjectReference: truncated,
}
query := componentConditionsJQ
switch c.GroupVersionKind() {
case csvGVK:
query = csvConditionsJQ
}
iter := query.Run(c.UnstructuredContent())
var out interface{}
for {
v, ok := iter.Next()
if !ok {
break
}
if err, ok = v.(error); ok {
return
}
out = v
}
var decoder *mapstructure.Decoder
decoder, err = mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
DecodeHook: codec.MetaTimeHookFunc(),
Result: &ref.Conditions,
})
if err != nil {
return
}
err = decoder.Decode(out)
return
}
func (c *Component) truncatedReference() (ref *corev1.ObjectReference, err error) {
ref, err = reference.GetReference(c.scheme, c.Unstructured)
if err != nil {
return
}
ref = &corev1.ObjectReference{
Kind: ref.Kind,
APIVersion: ref.APIVersion,
Namespace: ref.Namespace,
Name: ref.Name,
}
return
}