forked from operator-framework/operator-sdk
/
csv_updaters.go
325 lines (287 loc) · 9.25 KB
/
csv_updaters.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
// Copyright 2018 The Operator-SDK Authors
//
// 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 catalog
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"github.com/operator-framework/operator-sdk/pkg/k8sutil"
"github.com/ghodss/yaml"
olmapiv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
olminstall "github.com/operator-framework/operator-lifecycle-manager/pkg/controller/install"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
)
// CSVUpdater is an interface for any data that can be in a CSV, which will be
// set to the corresponding field on Apply().
type CSVUpdater interface {
// Apply applies a data update to a CSV argument.
Apply(*olmapiv1alpha1.ClusterServiceVersion) error
}
type updaterStore struct {
installStrategy *InstallStrategyUpdate
crds *CustomResourceDefinitionsUpdate
almExamples *ALMExamplesUpdate
}
func NewUpdaterStore() *updaterStore {
return &updaterStore{
installStrategy: &InstallStrategyUpdate{
&olminstall.StrategyDetailsDeployment{},
},
crds: &CustomResourceDefinitionsUpdate{
&olmapiv1alpha1.CustomResourceDefinitions{},
make(map[string]struct{}),
},
almExamples: &ALMExamplesUpdate{},
}
}
// Apply iteratively calls each stored CSVUpdater's Apply() method.
func (s *updaterStore) Apply(csv *olmapiv1alpha1.ClusterServiceVersion) error {
updaters := []CSVUpdater{s.installStrategy, s.crds, s.almExamples}
for _, updater := range updaters {
if err := updater.Apply(csv); err != nil {
return err
}
}
return nil
}
func getKindfromYAML(yamlData []byte) (string, error) {
var temp struct {
Kind string
}
if err := yaml.Unmarshal(yamlData, &temp); err != nil {
return "", err
}
return temp.Kind, nil
}
func (s *updaterStore) AddToUpdater(yamlSpec []byte, kind string) (found bool, err error) {
found = true
switch kind {
case "Role":
err = s.AddRole(yamlSpec)
case "ClusterRole":
err = s.AddClusterRole(yamlSpec)
case "Deployment":
err = s.AddDeploymentSpec(yamlSpec)
case "CustomResourceDefinition":
// All CRD's present will be 'owned'.
err = s.AddOwnedCRD(yamlSpec)
default:
found = false
}
return found, err
}
type InstallStrategyUpdate struct {
*olminstall.StrategyDetailsDeployment
}
func (store *updaterStore) AddRole(yamlDoc []byte) error {
role := &rbacv1.Role{}
if err := yaml.Unmarshal(yamlDoc, role); err != nil {
return err
}
perm := olminstall.StrategyDeploymentPermissions{
ServiceAccountName: role.ObjectMeta.Name,
Rules: role.Rules,
}
store.installStrategy.Permissions = append(store.installStrategy.Permissions, perm)
return nil
}
func (store *updaterStore) AddClusterRole(yamlDoc []byte) error {
clusterRole := &rbacv1.ClusterRole{}
if err := yaml.Unmarshal(yamlDoc, clusterRole); err != nil {
return err
}
perm := olminstall.StrategyDeploymentPermissions{
ServiceAccountName: clusterRole.ObjectMeta.Name,
Rules: clusterRole.Rules,
}
store.installStrategy.ClusterPermissions = append(store.installStrategy.ClusterPermissions, perm)
return nil
}
const olmTNMeta = "metadata.annotations['olm.targetNamespaces']"
func (store *updaterStore) AddDeploymentSpec(yamlDoc []byte) error {
dep := &appsv1.Deployment{}
if err := yaml.Unmarshal(yamlDoc, dep); err != nil {
return err
}
setWatchNamespacesEnv(dep)
// Make sure "olm.targetNamespaces" is referenced somewhere in dep,
// and emit a warning of not.
if !depHasOLMNamespaces(dep) {
log.Warnf(`No WATCH_NAMESPACE environment variable nor reference to "%s"`+
` detected in operator Deployment. For OLM compatibility, your operator`+
` MUST watch namespaces defined in "%s"`, olmTNMeta, olmTNMeta)
}
depSpec := olminstall.StrategyDeploymentSpec{
Name: dep.ObjectMeta.Name,
Spec: dep.Spec,
}
store.installStrategy.DeploymentSpecs = append(store.installStrategy.DeploymentSpecs, depSpec)
return nil
}
// setWatchNamespacesEnv sets WATCH_NAMESPACE to olmTNString in dep if
// WATCH_NAMESPACE exists in a pod spec container's env list.
func setWatchNamespacesEnv(dep *appsv1.Deployment) {
overwriteContainerEnvVar(dep, k8sutil.WatchNamespaceEnvVar, newEnvVar(k8sutil.WatchNamespaceEnvVar, olmTNMeta))
}
func overwriteContainerEnvVar(dep *appsv1.Deployment, name string, ev corev1.EnvVar) {
for _, c := range dep.Spec.Template.Spec.Containers {
for i := 0; i < len(c.Env); i++ {
if c.Env[i].Name == name {
c.Env[i] = ev
}
}
}
}
func newEnvVar(name, fieldPath string) corev1.EnvVar {
return corev1.EnvVar{
Name: name,
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: fieldPath,
},
},
}
}
// OLM places the set of target namespaces for the operator in
// "metadata.annotations['olm.targetNamespaces']". This value should be
// referenced in either:
// - The Deployment's pod spec WATCH_NAMESPACE env variable.
// - Some other Deployment pod spec field.
func depHasOLMNamespaces(dep *appsv1.Deployment) bool {
b, err := dep.Spec.Template.Marshal()
if err != nil {
// Something is wrong with the deployment manifest, not with CLI inputs.
log.Fatalf("marshal Deployment spec: %v", err)
}
return bytes.Index(b, []byte(olmTNMeta)) != -1
}
func (u *InstallStrategyUpdate) Apply(csv *olmapiv1alpha1.ClusterServiceVersion) (err error) {
// Get install strategy from csv. Default to a deployment strategy if none found.
var strat olminstall.Strategy
if csv.Spec.InstallStrategy.StrategyName == "" {
csv.Spec.InstallStrategy.StrategyName = olminstall.InstallStrategyNameDeployment
strat = &olminstall.StrategyDetailsDeployment{}
} else {
var resolver *olminstall.StrategyResolver
strat, err = resolver.UnmarshalStrategy(csv.Spec.InstallStrategy)
if err != nil {
return err
}
}
switch s := strat.(type) {
case *olminstall.StrategyDetailsDeployment:
// Update permissions and deployments.
u.updatePermissions(s)
u.updateClusterPermissions(s)
u.updateDeploymentSpecs(s)
default:
return fmt.Errorf("install strategy (%v) of unknown type", strat)
}
// Re-serialize permissions into csv strategy.
updatedStrat, err := json.Marshal(strat)
if err != nil {
return err
}
csv.Spec.InstallStrategy.StrategySpecRaw = updatedStrat
return nil
}
func (u *InstallStrategyUpdate) updatePermissions(strat *olminstall.StrategyDetailsDeployment) {
if len(u.Permissions) != 0 {
strat.Permissions = u.Permissions
}
}
func (u *InstallStrategyUpdate) updateClusterPermissions(strat *olminstall.StrategyDetailsDeployment) {
if len(u.ClusterPermissions) != 0 {
strat.ClusterPermissions = u.ClusterPermissions
}
}
func (u *InstallStrategyUpdate) updateDeploymentSpecs(strat *olminstall.StrategyDetailsDeployment) {
if len(u.DeploymentSpecs) != 0 {
strat.DeploymentSpecs = u.DeploymentSpecs
}
}
type CustomResourceDefinitionsUpdate struct {
*olmapiv1alpha1.CustomResourceDefinitions
crKinds map[string]struct{}
}
func (store *updaterStore) AddOwnedCRD(yamlDoc []byte) error {
crd := &apiextv1beta1.CustomResourceDefinition{}
if err := yaml.Unmarshal(yamlDoc, crd); err != nil {
return err
}
store.crds.Owned = append(store.crds.Owned, olmapiv1alpha1.CRDDescription{
Name: crd.ObjectMeta.Name,
Version: crd.Spec.Version,
Kind: crd.Spec.Names.Kind,
})
store.crds.crKinds[crd.Spec.Names.Kind] = struct{}{}
return nil
}
// Apply updates csv's "owned" CRDDescriptions. "required" CRDDescriptions are
// left as-is, since they are user-defined values.
func (u *CustomResourceDefinitionsUpdate) Apply(csv *olmapiv1alpha1.ClusterServiceVersion) error {
set := make(map[string]olmapiv1alpha1.CRDDescription)
for _, csvDesc := range csv.Spec.CustomResourceDefinitions.Owned {
set[csvDesc.Name] = csvDesc
}
du := u.DeepCopy()
for i, uDesc := range u.Owned {
if csvDesc, ok := set[uDesc.Name]; ok {
csvDesc.Name = uDesc.Name
csvDesc.Version = uDesc.Version
csvDesc.Kind = uDesc.Kind
du.Owned[i] = csvDesc
}
}
csv.Spec.CustomResourceDefinitions.Owned = du.Owned
return nil
}
type ALMExamplesUpdate struct {
crs []string
}
func (store *updaterStore) AddCR(yamlDoc []byte) error {
if len(yamlDoc) == 0 {
return nil
}
crBytes, err := yaml.YAMLToJSON(yamlDoc)
if err != nil {
return err
}
store.almExamples.crs = append(store.almExamples.crs, string(crBytes))
return nil
}
func (u *ALMExamplesUpdate) Apply(csv *olmapiv1alpha1.ClusterServiceVersion) error {
if len(u.crs) == 0 {
return nil
}
if csv.GetAnnotations() == nil {
csv.SetAnnotations(make(map[string]string))
}
sb := &strings.Builder{}
sb.WriteString(`[`)
for i, example := range u.crs {
sb.WriteString(example)
if i < len(u.crs)-1 {
sb.WriteString(`,`)
}
}
sb.WriteString(`]`)
csv.GetAnnotations()["alm-examples"] = sb.String()
return nil
}