This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 204
/
install.go
546 lines (473 loc) · 16.6 KB
/
install.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
package action
import (
"context"
"errors"
"time"
"github.com/syndesisio/syndesis/install/operator/pkg"
"github.com/syndesisio/syndesis/install/operator/pkg/generator"
"github.com/syndesisio/syndesis/install/operator/pkg/openshift/serviceaccount"
"github.com/syndesisio/syndesis/install/operator/pkg/util"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
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"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"k8s.io/client-go/kubernetes"
"github.com/syndesisio/syndesis/install/operator/pkg/apis/syndesis/v1beta2"
"github.com/syndesisio/syndesis/install/operator/pkg/syndesis/clienttools"
"github.com/syndesisio/syndesis/install/operator/pkg/syndesis/configuration"
"github.com/syndesisio/syndesis/install/operator/pkg/syndesis/olm"
"github.com/syndesisio/syndesis/install/operator/pkg/syndesis/operation"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
const (
// SyndesisRouteName the base name for the Route to access Syndesis application
SyndesisRouteName = "syndesis"
// SyndesisPullSecret name of the Secret used to pull images from image registries that require authentication
SyndesisPullSecret = "syndesis-pull-secret"
)
// Install syndesis into the namespace, taking resources from the bundled template.
type installAction struct {
baseAction
}
func newInstallAction(mgr manager.Manager, clientTools *clienttools.ClientTools) SyndesisOperatorAction {
return &installAction{
newBaseAction(mgr, clientTools, "install"),
}
}
func (a *installAction) installResource(ctx context.Context, rtClient client.Client, syndesis *v1beta2.Syndesis, res unstructured.Unstructured) (*unstructured.Unstructured, error) {
operation.SetNamespaceAndOwnerReference(res, syndesis)
o, modificationType, err := util.CreateOrUpdate(ctx, rtClient, &res)
if err != nil {
if util.IsNoKindMatchError(err) {
gvk := res.GroupVersionKind()
if _, found := kindsReportedNotAvailable[gvk]; !found {
kindsReportedNotAvailable[gvk] = time.Now()
a.log.Info("optional custom resource definition is not installed.", "group", gvk.Group, "version", gvk.Version, "kind", gvk.Kind)
}
} else {
a.log.Info("failed to create or replace resource", "kind", res.GetKind(), "name", res.GetName(), "namespace", res.GetNamespace())
return nil, err
}
} else {
if modificationType != controllerutil.OperationResultNone {
a.log.Info("resource "+string(modificationType), "kind", res.GetKind(), "name", res.GetName(), "namespace", res.GetNamespace())
}
}
return o, nil
}
//
// Log the possible combination of values chosen for the db persistent volume claim
//
func (a *installAction) logResourcePersistentVolume(syndesis *v1beta2.Syndesis, componentName string, resourceVolume configuration.ResourcesWithPersistentVolume) {
if syndesisPhaseIs(syndesis, v1beta2.SyndesisPhaseInstalling) {
a.log.V(pkg.DEBUG_LOGGING_LVL).Info("Binding to persistent volume with criteria ",
"component", componentName,
"volume-access-mode", resourceVolume.VolumeAccessMode,
"volume-name", resourceVolume.VolumeName,
"storage-class", resourceVolume.VolumeStorageClass)
}
}
func (a *installAction) CanExecute(syndesis *v1beta2.Syndesis) bool {
return syndesisPhaseIs(syndesis,
v1beta2.SyndesisPhaseInstalling,
v1beta2.SyndesisPhaseInstalled,
v1beta2.SyndesisPhasePostUpgradeRun,
v1beta2.SyndesisPhaseStarting,
v1beta2.SyndesisPhaseStartupFailed,
)
}
var kindsReportedNotAvailable = map[schema.GroupVersionKind]time.Time{}
func (a *installAction) Execute(ctx context.Context, syndesis *v1beta2.Syndesis) error {
if syndesisPhaseIs(syndesis, v1beta2.SyndesisPhaseInstalling) {
a.log.Info("installing Syndesis resource", "name", syndesis.Name)
} else if syndesisPhaseIs(syndesis, v1beta2.SyndesisPhasePostUpgradeRun) {
a.log.Info("installing Syndesis resource for the first time after upgrading", "name", syndesis.Name)
}
resourcesThatShouldExist := map[types.UID]bool{}
rtClient, _ := a.clientTools.RuntimeClient()
// Load configuration to to use as context for generate pkg
config, err := configuration.GetProperties(ctx, configuration.TemplateConfig, a.clientTools, syndesis)
if err != nil {
a.log.Error(err, "Error occurred while initialising configuration")
return err
}
//
// Check for presence of route hostname as required for k8
//
if err := config.CheckRouteHostname(); err != nil {
return err
}
//
// Check for oauth secrets as required for k8
//
if err := config.CheckOAuthCredentialSecret(ctx, rtClient, syndesis); err != nil {
return err
}
// Check if an image secret exists, to be used to connect to registries that require authentication
secret := &corev1.Secret{}
err = rtClient.Get(ctx, types.NamespacedName{Namespace: syndesis.Namespace, Name: SyndesisPullSecret}, secret)
if err != nil {
if k8serrors.IsNotFound(err) {
secret = nil
} else {
return err
}
}
if secret != nil {
config.ImagePullSecrets = append(config.ImagePullSecrets, secret.Name)
}
serviceAccount, err := installServiceAccount(ctx, rtClient, syndesis, secret)
if err != nil {
return err
}
resourcesThatShouldExist[serviceAccount.GetUID()] = true
token, err := serviceaccount.GetServiceAccountToken(ctx, rtClient, serviceAccount.Name, syndesis.Namespace)
if err != nil {
a.log.Info("Unable to get service account token", "error message", err.Error())
return nil
}
config.OpenShiftOauthClientSecret = token
// Render the route resource...
all, err := generator.RenderDir("./route/", config)
if err != nil {
return err
}
routes, _ := util.SeperateStructuredAndUnstructured(a.scheme, all)
syndesisRoute, err := installSyndesisRoute(ctx, rtClient, syndesis, routes)
if err != nil {
a.log.Info("Unable to set route syndesis", "error message", err.Error())
return nil
}
if err := config.SetRoute(ctx, syndesisRoute.Host()); err != nil {
return err
}
resourcesThatShouldExist[syndesisRoute.Meta().GetUID()] = true
if err := config.SetConsoleLink(ctx, rtClient, syndesis, syndesisRoute.Host()); err != nil {
return err
}
// Render the remaining syndesis resources...
all, err = generator.RenderDir("./infrastructure/", config)
if err != nil {
return err
}
a.logResourcePersistentVolume(syndesis, "syndesis-meta", config.Syndesis.Components.Meta.Resources)
a.logResourcePersistentVolume(syndesis, "syndesis-prometheus", config.Syndesis.Components.Prometheus.Resources)
// Render the database resource if needed...
if syndesis.Spec.Components.Database.ExternalDbURL == "" {
dbResources, err := generator.RenderDir("./database/", config)
if err != nil {
return err
}
a.logResourcePersistentVolume(syndesis, "syndesis-db", config.Syndesis.Components.Database.Resources)
all = append(all, dbResources...)
}
// Link the image secret to service accounts
if secret != nil {
err = linkImageSecretToServiceAccounts(ctx, rtClient, syndesis, secret)
if err != nil {
return err
}
}
// Install the resources..
for _, res := range all {
o, err := a.installResource(ctx, rtClient, syndesis, res)
if err != nil {
return err // Fail-fast for core components
}
resourcesThatShouldExist[o.GetUID()] = true
}
addonsInfo := configuration.GetAddonsInfo(*config)
for _, addonInfo := range addonsInfo {
if !addonInfo.IsEnabled() {
continue
}
a.log.V(pkg.DEBUG_LOGGING_LVL).Info("Installing addon", "Name", addonInfo.Name())
if config.ApiServer.OlmSupport && addonInfo.GetOlmSpec() != nil && addonInfo.GetOlmSpec().Package != "" {
a.log.V(pkg.DEBUG_LOGGING_LVL).Info("Subscribing to OLM operator:", "Package", addonInfo.GetOlmSpec().Package, "Channel", addonInfo.GetOlmSpec().Channel)
//
// Using the operator hub is not mutually exclusive to loading the addon
// resources. Each addon should be tailored with conditionals to be
// compatible with using the operator hub or not, ie. operator installation
// should be delegated to the OLM & only if that's not possible should it
// be installed from syndesis' own resources.
//
err := olm.SubscribeOperator(ctx, a.clientTools, config, addonInfo.GetOlmSpec())
if err != nil {
a.log.Error(err, "A subscription to an OLM operator failed", "Addon Name", addonInfo.Name(), "Package", addonInfo.GetOlmSpec().Package)
continue
}
}
addonDir := "./addons/" + addonInfo.Name() + "/"
f, err := generator.GetAssetsFS().Open(addonDir)
if err != nil {
a.log.Error(err, "Unsupported addon configured", "addon", addonInfo.Name())
continue
}
f.Close()
resources, err := generator.RenderDir(addonDir, config)
if err != nil {
a.log.Error(err, "Rendering of addon resources failed", "addon", addonInfo.Name())
continue
}
//
// Install the resources of this addon
// If there is an error do NOT fail-fast but
// try and continue to install the other addons
//
for _, res := range resources {
o, err := a.installResource(ctx, rtClient, syndesis, res)
if err != nil {
a.log.Error(err, "Install of addon failed", "addon", addonInfo.Name())
break
}
resourcesThatShouldExist[o.GetUID()] = true
}
}
// Find resources which need to be deleted.
labelSelector, err := labels.Parse("owner=" + string(syndesis.GetUID()))
if err != nil {
panic(err)
}
options := client.ListOptions{
Namespace: syndesis.Namespace,
LabelSelector: labelSelector,
}
api, _ := a.clientTools.ApiClient()
err = ListAllTypesInChunks(ctx, api, rtClient, options, func(list []unstructured.Unstructured) error {
for _, res := range list {
if resourcesThatShouldExist[res.GetUID()] {
continue
}
if res.GetOwnerReferences() == nil || len(res.GetOwnerReferences()) == 0 {
continue
}
if res.GetOwnerReferences()[0].UID != syndesis.GetUID() {
continue
}
// Found a resource that should not exist!
err := rtClient.Delete(ctx, &res)
if err != nil {
if !k8serrors.IsNotFound(err) {
a.log.Error(err, "could not deleted", "kind", res.GetKind(), "name", res.GetName(), "namespace", res.GetNamespace())
}
} else {
a.log.Info("resource deleted", "kind", res.GetKind(), "name", res.GetName(), "namespace", res.GetNamespace())
}
}
return nil
})
if err != nil {
return err
}
addRouteAnnotation(syndesis, syndesisRoute)
target := syndesis.DeepCopy()
if syndesis.Status.Phase == v1beta2.SyndesisPhaseInstalling {
// Installation completed, set the next state
target.Status.Phase = v1beta2.SyndesisPhaseStarting
target.Status.Reason = v1beta2.SyndesisStatusReasonMissing
target.Status.Description = ""
_, _, err := util.CreateOrUpdate(ctx, rtClient, target, "kind", "apiVersion")
if err != nil {
return err
}
a.log.Info("Syndesis resource installed", "name", target.Name)
} else if syndesis.Status.Phase == v1beta2.SyndesisPhasePostUpgradeRun {
// Installation completed, set the next state
target.Status.Phase = v1beta2.SyndesisPhasePostUpgradeRunSucceed
target.Status.Reason = v1beta2.SyndesisStatusReasonMissing
target.Status.Description = ""
_, _, err := util.CreateOrUpdate(ctx, rtClient, target, "kind", "apiVersion")
if err != nil {
return err
}
a.log.Info("Syndesis resource installed after upgrading", "name", target.Name)
}
return nil
}
// ListAllTypesInChunks pages through set of API types
func ListAllTypesInChunks(ctx context.Context, api kubernetes.Interface, c client.Client, options client.ListOptions, handler func([]unstructured.Unstructured) error) error {
types, err := getTypes(api)
if err != nil {
return err
}
nextType:
for _, t := range types {
options := client.ListOptions{
Namespace: options.Namespace,
LabelSelector: options.LabelSelector,
Raw: &metav1.ListOptions{
TypeMeta: t,
Limit: 200,
},
}
list := unstructured.UnstructuredList{
Object: map[string]interface{}{
"apiVersion": t.APIVersion,
"kind": t.Kind,
},
}
err = util.ListInChunks(ctx, c, &options, &list, handler)
if err != nil {
if k8serrors.IsNotFound(err) ||
k8serrors.IsForbidden(err) ||
k8serrors.IsMethodNotSupported(err) {
continue nextType
}
return err
}
}
return nil
}
func getTypes(api kubernetes.Interface) ([]metav1.TypeMeta, error) {
resources, err := api.Discovery().ServerPreferredNamespacedResources()
if err != nil {
return nil, err
}
types := make([]metav1.TypeMeta, 0)
for _, resource := range resources {
for _, r := range resource.APIResources {
types = append(types, metav1.TypeMeta{
Kind: r.Kind,
APIVersion: resource.GroupVersion,
})
}
}
return types, nil
}
func installServiceAccount(ctx context.Context, cl client.Client, syndesis *v1beta2.Syndesis, secret *corev1.Secret) (*corev1.ServiceAccount, error) {
sa := newSyndesisServiceAccount()
if secret != nil {
linkImagePullSecret(sa, secret)
}
operation.SetNamespaceAndOwnerReference(sa, syndesis)
// We don't replace the service account if already present, to let Kubernetes generate its tokens
o, _, err := util.CreateOrUpdate(ctx, cl, sa)
if err != nil {
return nil, err
}
sa.SetUID(o.GetUID())
return sa, nil
}
func newSyndesisServiceAccount() *corev1.ServiceAccount {
sa := corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ServiceAccount",
},
ObjectMeta: metav1.ObjectMeta{
Name: "syndesis-oauth-client",
Labels: map[string]string{
"app": "syndesis",
},
Annotations: map[string]string{
"serviceaccounts.openshift.io/oauth-redirecturi.local": "https://localhost:4200",
"serviceaccounts.openshift.io/oauth-redirecturi.route": "https://",
"serviceaccounts.openshift.io/oauth-redirectreference.route": `{"kind": "OAuthRedirectReference", "apiVersion": "v1", "reference": {"kind": "Route","name": "syndesis"}}`,
},
},
}
return &sa
}
func addRouteAnnotation(syndesis *v1beta2.Syndesis, route Conduit) {
annotations := syndesis.ObjectMeta.Annotations
if annotations == nil {
annotations = make(map[string]string)
syndesis.ObjectMeta.Annotations = annotations
}
annotations["syndesis.io/applicationUrl"] = route.ExtractApplicationUrl()
}
func installSyndesisRoute(ctx context.Context, cl client.Client, syndesis *v1beta2.Syndesis, objects []runtime.Object) (Conduit, error) {
conduit, err := findSyndesisRoute(objects)
if err != nil {
return nil, err
}
ct := conduit.Target()
cm := conduit.Meta()
operation.SetNamespaceAndOwnerReference(ct, syndesis)
// We don't replace the route if already present, to let OpenShift generate its host
o, _, err := util.CreateOrUpdate(ctx, cl, ct)
if err != nil {
return nil, err
}
cm.SetUID(o.GetUID())
if len(conduit.Host()) > 0 {
return conduit, nil
}
// Let's try to get the route from cluster to check the host field
var key client.ObjectKey
if key, err = client.ObjectKeyFromObject(ct); err != nil {
return nil, err
}
err = cl.Get(ctx, key, ct)
if err != nil {
return nil, err
}
if len(conduit.Host()) == 0 {
return nil, errors.New("hostname still not present on syndesis route")
}
return conduit, nil
}
func findSyndesisRoute(resources []runtime.Object) (Conduit, error) {
for _, res := range resources {
if route, ok := isSyndesisRoute(res); ok {
return route, nil
}
}
return nil, errors.New("syndesis route not found")
}
func isSyndesisRoute(resource runtime.Object) (Conduit, bool) {
return ConduitWithName(resource, SyndesisRouteName)
}
func linkImageSecretToServiceAccounts(ctx context.Context, cl client.Client, syndesis *v1beta2.Syndesis, secret *corev1.Secret) error {
// Link the builder service account to the image pull/push secret if it exists
builder := &corev1.ServiceAccount{}
err := cl.Get(ctx, types.NamespacedName{Namespace: syndesis.Namespace, Name: "builder"}, builder)
if err != nil {
return err
}
linked := linkImagePullSecret(builder, secret)
linked = linkSecret(builder, secret.Name) || linked
if linked {
err = cl.Update(ctx, builder)
if err != nil {
return err
}
}
return nil
}
func linkImagePullSecret(sa *corev1.ServiceAccount, secret *corev1.Secret) bool {
exist := false
for _, s := range sa.ImagePullSecrets {
if s.Name == secret.Name {
exist = true
break
}
}
if !exist {
sa.ImagePullSecrets = append(sa.ImagePullSecrets, corev1.LocalObjectReference{
Name: secret.Name,
})
return true
}
return false
}
func linkSecret(sa *corev1.ServiceAccount, secret string) bool {
exist := false
for _, s := range sa.Secrets {
if s.Name == secret {
exist = true
break
}
}
if !exist {
sa.Secrets = append(sa.Secrets, corev1.ObjectReference{Namespace: sa.Namespace, Name: SyndesisPullSecret})
return true
}
return false
}