forked from operator-framework/operator-lifecycle-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
318 lines (260 loc) · 8.32 KB
/
helpers.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
package openshift
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
semver "github.com/blang/semver/v4"
configv1 "github.com/openshift/api/config/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/predicate"
operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/registry/resolver/projection"
)
func stripObject(obj client.Object) {
if obj == nil {
return
}
obj.SetResourceVersion("")
obj.SetUID("")
}
func watchName(name *string) predicate.Funcs {
return predicate.NewPredicateFuncs(func(object client.Object) bool {
return object.GetName() == *name
})
}
func conditionsEqual(a, b *configv1.ClusterOperatorStatusCondition) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.Type == b.Type && a.Status == b.Status && a.Message == b.Message && a.Reason == b.Reason
}
func versionsMatch(a []configv1.OperandVersion, b []configv1.OperandVersion) bool {
if len(a) != len(b) {
return false
}
counts := map[configv1.OperandVersion]int{}
for _, av := range a {
counts[av]++
}
for _, bv := range b {
remaining, ok := counts[bv]
if !ok {
return false
}
if remaining == 1 {
delete(counts, bv)
continue
}
counts[bv]--
}
return len(counts) < 1
}
type skews []skew
func (s skews) String() string {
msg := make([]string, len(s))
i, j := 0, len(s)-1
for _, sk := range s {
m := sk.String()
// Partial order: error skews first
if sk.err != nil {
msg[i] = m
i++
continue
}
msg[j] = m
j--
}
// it is safe to ignore the error here, with the assumption
// that we build each skew object only after verifying that the
// version string is parseable safely.
maxOCPVersion, _ := semver.ParseTolerant(s[0].maxOpenShiftVersion)
nextY := nextY(maxOCPVersion).String()
return fmt.Sprintf("ClusterServiceVersions blocking minor version upgrades to %s or higher:\n%s", nextY, strings.Join(msg, "\n"))
}
type skew struct {
namespace string
name string
maxOpenShiftVersion string
err error
}
func (s skew) String() string {
if s.err != nil {
return fmt.Sprintf("- %s/%s has invalid %s properties: %s", s.namespace, s.name, MaxOpenShiftVersionProperty, s.err)
}
return fmt.Sprintf("- maximum supported OCP version for %s/%s is %s", s.namespace, s.name, s.maxOpenShiftVersion)
}
type transientError struct {
error
}
// transientErrors returns the result of stripping all wrapped errors not of type transientError from the given error.
func transientErrors(err error) error {
return utilerrors.FilterOut(err, func(e error) bool {
return !errors.As(e, new(transientError))
})
}
func incompatibleOperators(ctx context.Context, cli client.Client) (skews, error) {
current, err := getCurrentRelease()
if err != nil {
return nil, err
}
if current == nil {
// Note: This shouldn't happen
return nil, fmt.Errorf("failed to determine current OpenShift Y-stream release")
}
csvList := &operatorsv1alpha1.ClusterServiceVersionList{}
if err := cli.List(ctx, csvList); err != nil {
return nil, &transientError{fmt.Errorf("failed to list ClusterServiceVersions: %w", err)}
}
var incompatible skews
for _, csv := range csvList.Items {
if csv.IsCopied() {
continue
}
s := skew{
name: csv.GetName(),
namespace: csv.GetNamespace(),
}
max, err := maxOpenShiftVersion(&csv)
if err != nil {
s.err = err
incompatible = append(incompatible, s)
continue
}
if max == nil || max.GTE(nextY(*current)) {
continue
}
s.maxOpenShiftVersion = fmt.Sprintf("%d.%d", max.Major, max.Minor)
incompatible = append(incompatible, s)
}
return incompatible, nil
}
type openshiftRelease struct {
version *semver.Version
mu sync.Mutex
}
var (
currentRelease = &openshiftRelease{}
)
const (
releaseEnvVar = "RELEASE_VERSION" // OpenShift's env variable for defining the current release
)
// getCurrentRelease thread safely retrieves the current version of OCP at the time of this operator starting.
// This is defined by an environment variable that our release manifests define (and get dynamically updated)
// by OCP. For the purposes of this package, that environment variable is a constant under the name of releaseEnvVar.
//
// Note: currentRelease is designed to be a singleton that only gets updated the first time that this function
// is called. As a result, all calls to this will return the same value even if the releaseEnvVar gets
// changed during runtime somehow.
func getCurrentRelease() (*semver.Version, error) {
currentRelease.mu.Lock()
defer currentRelease.mu.Unlock()
if currentRelease.version != nil {
/*
If the version is already set, we don't want to set it again as the currentRelease
is designed to be a singleton. If a new version is set, we are making an assumption
that this controller will be restarted and thus pull in the new version from the
environment into memory.
Note: sync.Once is not used here as it was difficult to reliably test without hitting
race conditions.
*/
return currentRelease.version, nil
}
// Get the raw version from the releaseEnvVar environment variable
raw, ok := os.LookupEnv(releaseEnvVar)
if !ok || raw == "" {
// No env var set, try again later
return nil, fmt.Errorf("desired release version missing from %v env variable", releaseEnvVar)
}
release, err := semver.ParseTolerant(raw)
if err != nil {
return nil, fmt.Errorf("cluster version has invalid desired release version: %w", err)
}
currentRelease.version = &release
return currentRelease.version, nil
}
func nextY(v semver.Version) semver.Version {
return semver.Version{Major: v.Major, Minor: v.Minor + 1} // Sets Y=Y+1
}
const (
MaxOpenShiftVersionProperty = "olm.maxOpenShiftVersion"
)
func maxOpenShiftVersion(csv *operatorsv1alpha1.ClusterServiceVersion) (*semver.Version, error) {
// Extract the property from the CSV's annotations if possible
annotation, ok := csv.GetAnnotations()[projection.PropertiesAnnotationKey]
if !ok {
return nil, nil
}
properties, err := projection.PropertyListFromPropertiesAnnotation(annotation)
if err != nil {
return nil, err
}
var max *string
for _, property := range properties {
if property.Type != MaxOpenShiftVersionProperty {
continue
}
if max != nil {
return nil, fmt.Errorf(`defining more than one "%s" property is not allowed`, MaxOpenShiftVersionProperty)
}
max = &property.Value
}
if max == nil {
return nil, nil
}
// Account for any additional quoting
value := strings.Trim(*max, "\"")
if value == "" {
// Handle "" separately, so parse doesn't treat it as a zero
return nil, fmt.Errorf(`value cannot be "" (an empty string)`)
}
version, err := semver.ParseTolerant(value)
if err != nil {
return nil, fmt.Errorf(`failed to parse "%s" as semver: %w`, value, err)
}
truncatedVersion := semver.Version{Major: version.Major, Minor: version.Minor}
if !version.EQ(truncatedVersion) {
return nil, fmt.Errorf("property %s must specify only <major>.<minor> version, got invalid value %s", MaxOpenShiftVersionProperty, version)
}
return &truncatedVersion, nil
}
func notCopiedSelector() (labels.Selector, error) {
requirement, err := labels.NewRequirement(operatorsv1alpha1.CopiedLabelKey, selection.DoesNotExist, nil)
if err != nil {
return nil, err
}
return labels.NewSelector().Add(*requirement), nil
}
func olmOperatorRelatedObjects(ctx context.Context, cli client.Client, namespace string) ([]configv1.ObjectReference, error) {
selector, err := notCopiedSelector()
if err != nil {
return nil, err
}
csvList := &operatorsv1alpha1.ClusterServiceVersionList{}
if err := cli.List(ctx, csvList, client.InNamespace(namespace), client.MatchingLabelsSelector{Selector: selector}); err != nil {
return nil, err
}
var refs []configv1.ObjectReference
for _, csv := range csvList.Items {
if csv.IsCopied() {
// Filter out copied CSVs that the label selector missed
continue
}
// TODO: Generalize ObjectReference generation
refs = append(refs, configv1.ObjectReference{
Group: operatorsv1alpha1.GroupName,
Resource: "clusterserviceversions",
Namespace: csv.GetNamespace(),
Name: csv.GetName(),
})
}
return refs, nil
}