drupalsite_resources.go 49 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*


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 controllers

import (
	"context"
21
	"errors"
22
	"fmt"
23
	"io/ioutil"
24
	"math/rand"
25
	"strconv"
26
	"strings"
27
	"time"
28
29
30

	"github.com/asaskevich/govalidator"
	"github.com/go-logr/logr"
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
31
32
	buildv1 "github.com/openshift/api/build/v1"
	imagev1 "github.com/openshift/api/image/v1"
33
34
	routev1 "github.com/openshift/api/route/v1"
	webservicesv1a1 "gitlab.cern.ch/drupal/paas/drupalsite-operator/api/v1alpha1"
35
	appsv1 "k8s.io/api/apps/v1"
36
	batchv1 "k8s.io/api/batch/v1"
37
38
39
40
41
42
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/utils/pointer"
43
	controllerruntime "sigs.k8s.io/controller-runtime"
44
	"sigs.k8s.io/controller-runtime/pkg/client"
45
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
46
47
48
49
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

const (
50
	// finalizerStr string that is going to added to every DrupalSite created
51
52
	finalizerStr          = "controller.drupalsite.webservices.cern.ch"
	productionEnvironment = "production"
53
	routerShardLabel      = "drupal.cern.ch/router-shard"
54
	adminAnnotation       = "drupal.cern.ch/admin-custom-edit"
55
56
)

Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
57
var (
58
	// ImageRecipesRepo refers to the drupal runtime repo which contains the dockerfiles and other config data to build the images
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
59
	// Example: "https://gitlab.cern.ch/drupal/paas/drupal-runtime.git"
60
61
62
	ImageRecipesRepo string
	// ImageRecipesRepoRef refers to the branch (git ref) of the drupal runtime repo which contains the dockerfiles
	// and other config data to build the images
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
63
	// Example: "s2i"
64
65
66
	ImageRecipesRepoRef string
	// ClusterName is used in the Route's Host field
	ClusterName string
67
68
	// RouterShards is the list of all router shards available in the cluster - passed as a flag to the operator
	RouterShards strFlagList
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
69
70
)

71
72
73
74
75
76
77
78
79
80
81
type strFlagList []string

func (i *strFlagList) String() string {
	return strings.Join(*i, ",")
}

func (i *strFlagList) Set(value string) error {
	*i = append(*i, value)
	return nil
}

82
83
//validateSpec validates the spec against the DrupalSiteSpec definition
func validateSpec(drpSpec webservicesv1a1.DrupalSiteSpec) reconcileError {
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
	_, err := govalidator.ValidateStruct(drpSpec)
	if err != nil {
		return newApplicationError(err, ErrInvalidSpec)
	}
	return nil
}

func contains(a []string, x string) bool {
	for _, n := range a {
		if x == n {
			return true
		}
	}
	return false
}

// ensureSpecFinalizer ensures that the spec is valid, adding extra info if necessary, and that the finalizer is there,
// then returns if it needs to be updated.
102
func ensureSpecFinalizer(drp *webservicesv1a1.DrupalSite, log logr.Logger) (update bool) {
103
104
105
	if !controllerutil.ContainsFinalizer(drp, finalizerStr) {
		log.Info("Adding finalizer")
		controllerutil.AddFinalizer(drp, finalizerStr)
106
107
		update = true
	}
108
	update, specErr := assignRouterShard(drp)
109
110
	switch {
	case specErr != nil:
111
		log.Info(specErr.Error())
112
113
	case update:
		log.Info(fmt.Sprintf("Assigned router shard %v to a drupal site", drp.Spec.AssignedRouterShard))
114
	}
115
116
117
	return
}

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
func assignRouterShard(drp *webservicesv1a1.DrupalSite) (update bool, err reconcileError) {
	if drp.Spec.AssignedRouterShard != "" {
		return false, nil
	}
	if len(RouterShards) == 0 {
		return false, newApplicationError(errors.New("specify a valid list of available router shards with the --assignable-router-shard flag"), ErrInvalidSpec)
	}
	drp.Spec.AssignedRouterShard = randomStrElement(RouterShards)
	return true, nil
}

// randomStrElement returns a random element from the array. Panic if len(list) == 0
func randomStrElement(list []string) string {
	r := rand.New(rand.NewSource(time.Now().Unix()))
	return list[r.Intn(len(list))]
}

135
/*
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
136
137
ensureResources ensures the presence of all the resources that the DrupalSite needs to serve content, apart from the ingress Route.
This includes BuildConfigs/ImageStreams, DB, PVC, PHP/Nginx deployment + service, site install job.
138
*/
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
139
func (r *DrupalSiteReconciler) ensureResources(drp *webservicesv1a1.DrupalSite, log logr.Logger) (transientErr reconcileError) {
140
	ctx := context.TODO()
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
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

	// 1. BuildConfigs and ImageStreams

	if len(drp.Spec.Environment.ExtraConfigRepo) > 0 {
		if transientErr := r.ensureResourceX(ctx, drp, "is_s2i", log); transientErr != nil {
			return transientErr.Wrap("%v: for S2I SiteBuilder ImageStream")
		}
		if transientErr := r.ensureResourceX(ctx, drp, "bc_s2i", log); transientErr != nil {
			return transientErr.Wrap("%v: for S2I SiteBuilder BuildConfig")
		}
	}
	if transientErr := r.ensureResourceX(ctx, drp, "is_php", log); transientErr != nil {
		return transientErr.Wrap("%v: for PHP ImageStream")
	}
	if transientErr := r.ensureResourceX(ctx, drp, "is_nginx", log); transientErr != nil {
		return transientErr.Wrap("%v: for Nginx ImageStream")
	}
	if transientErr := r.ensureResourceX(ctx, drp, "bc_php", log); transientErr != nil {
		return transientErr.Wrap("%v: for PHP BuildConfig")
	}
	if transientErr := r.ensureResourceX(ctx, drp, "bc_nginx", log); transientErr != nil {
		return transientErr.Wrap("%v: for Nginx BuildConfig")
	}

	// 2. Data layer

167
168
169
170
171
	if transientErr := r.ensureResourceX(ctx, drp, "pvc_drupal", log); transientErr != nil {
		return transientErr.Wrap("%v: for Drupal PVC")
	}
	if transientErr := r.ensureResourceX(ctx, drp, "pvc_mysql", log); transientErr != nil {
		return transientErr.Wrap("%v: for MySQL PVC")
172
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
173
	if transientErr := r.ensureResourceX(ctx, drp, "dc_mysql", log); transientErr != nil {
174
175
		return transientErr.Wrap("%v: for Mysql DC")
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
176
	if transientErr := r.ensureResourceX(ctx, drp, "svc_mysql", log); transientErr != nil {
177
178
		return transientErr.Wrap("%v: for Mysql SVC")
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
179
180
181
	if transientErr := r.ensureResourceX(ctx, drp, "cm_mysql", log); transientErr != nil {
		return transientErr.Wrap("%v: for MySQL CM")
	}
182

Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
183
184
	// 3. Serving layer

185
	if transientErr := r.ensureResourceX(ctx, drp, "cm_php", log); transientErr != nil {
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
186
		return transientErr.Wrap("%v: for PHP-FPM CM")
187
	}
188
189
190
	if transientErr := r.ensureResourceX(ctx, drp, "cm_nginx", log); transientErr != nil {
		return transientErr.Wrap("%v: for Nginx CM")
	}
191
192
	if transientErr := r.ensureResourceX(ctx, drp, "dc_drupal", log); transientErr != nil {
		return transientErr.Wrap("%v: for Drupal DC")
193
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
194
	if transientErr := r.ensureResourceX(ctx, drp, "svc_nginx", log); transientErr != nil {
195
196
		return transientErr.Wrap("%v: for Nginx SVC")
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
197
198
199
200
201
202

	// 4. Ingress

	if transientErr := r.ensureResourceX(ctx, drp, "site_install_job", log); transientErr != nil {
		return transientErr.Wrap("%v: for site install Job")
	}
203
204
205
	return nil
}

Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
206
207
// ensureIngressResources ensures the presence of the Route to access the website from the outside world
func (r *DrupalSiteReconciler) ensureIngressResources(drp *webservicesv1a1.DrupalSite, log logr.Logger) (transientErr reconcileError) {
208
	ctx := context.TODO()
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
209
	if transientErr := r.ensureResourceX(ctx, drp, "route", log); transientErr != nil {
210
211
212
213
214
		return transientErr.Wrap("%v: for Route")
	}
	return nil
}

215
216
217
// labelsForDrupalSite returns the labels for selecting the resources
// belonging to the given drupalSite CR name.
func labelsForDrupalSite(name string) map[string]string {
218
	return map[string]string{"drupalSite": name}
219
220
}

Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
221
222
223
224
225
226
227
228
229
// TODO: Translate the `drupalVersion` -> {`PHP_BASE_VERSION`, `NGINX_VERSION`, `COMPOSER_VERSION`}
// Possibly an operator configmap
// see https://gitlab.cern.ch/drupal/paas/drupalsite-operator/-/issues/29
func phpBaseVersion(d *webservicesv1a1.DrupalSite) string { return "7.3.23-fpm-alpine3.12" }
func nginxVersion(d *webservicesv1a1.DrupalSite) string   { return "1.17.4" }

// baseImageReferenceToUse returns which base image to use, depending on whether the field `environment.ExtraConfigRepo` is set.
// If yes, the S2I buildconfig will be used; baseImageReferenceToUse returns the output of imageStreamForDrupalSiteBuilderS2I().
// Otherwise, returns the sitebuilder base
230
func baseImageReferenceToUse(d *webservicesv1a1.DrupalSite) corev1.ObjectReference {
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
231
	if len(d.Spec.Environment.ExtraConfigRepo) > 0 {
232
233
		return corev1.ObjectReference{
			Kind: "ImageStreamTag",
234
			Name: "drupal-site-builder-s2i-" + d.Name + ":" + d.Spec.DrupalVersion,
235
236
237
238
239
		}
	}
	return corev1.ObjectReference{
		Kind: "DockerImage",
		Name: "gitlab-registry.cern.ch/drupal/paas/drupal-runtime/site-builder-base:" + d.Spec.DrupalVersion,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
240
241
242
	}
}

243
244
245
246
247
248
249
250
251
// triggersForBuildConfigs defines build triggers to be configured for the Nginx and PHP buildConfigs based on the input
// field `environment.ExtraConfigRepo`
func triggersForBuildConfigs(d *webservicesv1a1.DrupalSite) buildv1.BuildTriggerPolicy {
	if len(d.Spec.Environment.ExtraConfigRepo) > 0 {
		return buildv1.BuildTriggerPolicy{
			Type: buildv1.ImageChangeBuildTriggerType,
			ImageChange: &buildv1.ImageChangeTrigger{
				From: &corev1.ObjectReference{
					Kind: "ImageStreamTag",
252
					Name: "drupal-site-builder-s2i-" + d.Name + ":" + d.Spec.DrupalVersion,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
253
254
				},
			},
255
256
257
258
		}
	}
	return buildv1.BuildTriggerPolicy{
		Type: buildv1.ConfigChangeBuildTriggerType,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
259
260
261
262
	}
}

// imageStreamForDrupalSiteBuilderS2I returns a ImageStream object for Drupal SiteBuilder S2I
263
264
265
266
267
268
269
270
271
func imageStreamForDrupalSiteBuilderS2I(currentobject *imagev1.ImageStream, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
272
273
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "site-builder"
274
275
276
277
278
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec.LookupPolicy.Local = true
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
279
280
281
}

// imageStreamForDrupalSitePHP returns a ImageStream object for Drupal PHP
282
283
284
285
286
287
288
289
290
291
292
func imageStreamForDrupalSitePHP(currentobject *imagev1.ImageStream, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
293
294
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "php"
295
296
297
298
299
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec.LookupPolicy.Local = true
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
300
301
302
}

// imageStreamForDrupalSiteNginx returns a ImageStream object for Drupal Nginx
303
304
305
306
307
308
309
310
311
312
313
func imageStreamForDrupalSiteNginx(currentobject *imagev1.ImageStream, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
314
315
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "nginx"
316
317
	for k, v := range ls {
		currentobject.Labels[k] = v
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
318
	}
319
320
	currentobject.Spec.LookupPolicy.Local = true
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
321
322
323
}

// buildConfigForDrupalSiteBuilderS2I returns a BuildConfig object for Drupal SiteBuilder S2I
324
325
326
327
328
329
330
331
332
333
334
func buildConfigForDrupalSiteBuilderS2I(currentobject *buildv1.BuildConfig, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
335
336
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "site-builder"
337
338
339
340
341
342
343
344
345
346
347
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec = buildv1.BuildConfigSpec{
		CommonSpec: buildv1.CommonSpec{
			CompletionDeadlineSeconds: pointer.Int64Ptr(1200),
			Source: buildv1.BuildSource{
				Git: &buildv1.GitBuildSource{
					// TODO: support branches https://gitlab.cern.ch/drupal/paas/drupalsite-operator/-/issues/28
					Ref: "master",
					URI: d.Spec.Environment.ExtraConfigRepo,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
348
				},
349
350
351
352
353
354
			},
			Strategy: buildv1.BuildStrategy{
				SourceStrategy: &buildv1.SourceBuildStrategy{
					From: corev1.ObjectReference{
						Kind: "DockerImage",
						Name: "gitlab-registry.cern.ch/drupal/paas/drupal-runtime/site-builder-base:" + d.Spec.DrupalVersion,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
355
356
357
					},
				},
			},
358
359
360
361
			Output: buildv1.BuildOutput{
				To: &corev1.ObjectReference{
					Kind: "ImageStreamTag",
					Name: currentobject.Name + ":" + d.Spec.DrupalVersion,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
362
363
364
				},
			},
		},
365
366
367
368
369
		Triggers: []buildv1.BuildTriggerPolicy{
			{
				Type: buildv1.ConfigChangeBuildTriggerType,
			},
		},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
370
	}
371
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
372
373
374
}

// buildConfigForDrupalSitePHP returns a BuildConfig object for Drupal PHP
375
376
377
378
379
380
381
382
383
384
385
func buildConfigForDrupalSitePHP(currentobject *buildv1.BuildConfig, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
386
387
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "php"
388
389
390
391
392
393
394
395
396
397
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec = buildv1.BuildConfigSpec{
		CommonSpec: buildv1.CommonSpec{
			CompletionDeadlineSeconds: pointer.Int64Ptr(1200),
			Source: buildv1.BuildSource{
				Git: &buildv1.GitBuildSource{
					Ref: ImageRecipesRepoRef,
					URI: ImageRecipesRepo,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
398
				},
399
400
401
402
403
				ContextDir: "images/php-fpm",
				Images: []buildv1.ImageSource{
					{
						From: baseImageReferenceToUse(d),
						Paths: []buildv1.ImageSourcePath{
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
404
							{
405
406
								SourcePath:     "/app/.",
								DestinationDir: "./images/php-fpm/drupal-files/",
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
407
408
409
410
							},
						},
					},
				},
411
412
413
414
415
416
417
418
419
420
421
422
423
424
			},
			Strategy: buildv1.BuildStrategy{
				DockerStrategy: &buildv1.DockerBuildStrategy{
					BuildArgs: []corev1.EnvVar{
						{
							Name:  "DRUPAL_VERSION",
							Value: d.Spec.DrupalVersion,
						},
					},
					Env: []corev1.EnvVar{
						{
							Name:  "SITE_BUILDER_DIR",
							Value: "drupal-files",
						},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
425
426
427
					},
				},
			},
428
429
430
431
432
			Output: buildv1.BuildOutput{
				To: &corev1.ObjectReference{
					Kind: "ImageStreamTag",
					Name: currentobject.Name + ":" + d.Spec.DrupalVersion,
				},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
433
434
			},
		},
435
436
437
		Triggers: []buildv1.BuildTriggerPolicy{
			triggersForBuildConfigs(d),
		},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
438
	}
439
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
440
441
442
}

// buildConfigForDrupalSiteNginx returns a BuildConfig object for Drupal Nginx
443
444
445
446
447
448
449
450
451
452
453
func buildConfigForDrupalSiteNginx(currentobject *buildv1.BuildConfig, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
454
455
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "nginx"
456
457
458
459
460
461
462
463
464
465
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec = buildv1.BuildConfigSpec{
		CommonSpec: buildv1.CommonSpec{
			CompletionDeadlineSeconds: pointer.Int64Ptr(1200),
			Source: buildv1.BuildSource{
				Git: &buildv1.GitBuildSource{
					Ref: ImageRecipesRepoRef,
					URI: ImageRecipesRepo,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
466
				},
467
468
469
470
471
				ContextDir: "images/nginx",
				Images: []buildv1.ImageSource{
					{
						From: baseImageReferenceToUse(d),
						Paths: []buildv1.ImageSourcePath{
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
472
							{
473
474
								SourcePath:     "/app/.",
								DestinationDir: "./images/nginx/drupal-files/",
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
475
476
477
478
							},
						},
					},
				},
479
480
481
482
483
484
485
486
487
488
489
490
491
492
			},
			Strategy: buildv1.BuildStrategy{
				DockerStrategy: &buildv1.DockerBuildStrategy{
					BuildArgs: []corev1.EnvVar{
						{
							Name:  "DRUPAL_VERSION",
							Value: d.Spec.DrupalVersion,
						},
					},
					Env: []corev1.EnvVar{
						{
							Name:  "SITE_BUILDER_DIR",
							Value: "drupal-files",
						},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
493
494
495
					},
				},
			},
496
497
498
499
500
			Output: buildv1.BuildOutput{
				To: &corev1.ObjectReference{
					Kind: "ImageStreamTag",
					Name: currentobject.Name + ":" + d.Spec.DrupalVersion,
				},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
501
502
			},
		},
503
504
505
		Triggers: []buildv1.BuildTriggerPolicy{
			triggersForBuildConfigs(d),
		},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
506
	}
507
	return nil
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
508
509
}

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// deploymentForDrupalSiteMySQL returns a Deployment object for MySQL
func deploymentForDrupalSiteMySQL(currentobject *appsv1.Deployment, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Spec.Template.ObjectMeta.Annotations = map[string]string{
			"mysql-configmap-version": "1",
		}
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
525
	ls := labelsForDrupalSite(d.Name)
526
	ls["app"] = "mysql"
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec.Replicas = pointer.Int32Ptr(1)
	currentobject.Spec.Selector = &metav1.LabelSelector{
		MatchLabels: ls,
	}
	currentobject.Spec.Template.ObjectMeta.Labels = ls

	currentobject.Spec.Template.Spec = corev1.PodSpec{
		Containers: []corev1.Container{{
			Image:           "mysql:5.7",
			Name:            "mysql",
			ImagePullPolicy: "IfNotPresent",
			Ports: []corev1.ContainerPort{{
				ContainerPort: 3306,
				Name:          "mysql",
				Protocol:      "TCP",
			}},
			Env: []corev1.EnvVar{
				{
					Name:  "MYSQL_DATABASE",
					Value: "drupal",
550
				},
551
552
553
554
555
556
557
				{
					Name: "MYSQL_ROOT_PASSWORD",
					ValueFrom: &corev1.EnvVarSource{
						SecretKeyRef: &corev1.SecretKeySelector{
							Key: "DB_PASSWORD",
							LocalObjectReference: corev1.LocalObjectReference{
								Name: "drupal-mysql-secret",
558
							},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
559
						},
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
					},
				},
			},
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      "mysql-persistent-storage",
					MountPath: "/var/lib/mysql",
				},
				{
					Name:      "config-volume",
					MountPath: "/etc/mysql/conf.d/mysql-config.cnf",
					SubPath:   "mysql-config.cnf",
				}},
		}},
		Volumes: []corev1.Volume{
			{
				Name: "mysql-persistent-storage",
				VolumeSource: corev1.VolumeSource{
					PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
						ClaimName: "mysql-pv-claim-" + d.Name,
					},
				},
			},
			{
				Name: "config-volume",
				VolumeSource: corev1.VolumeSource{
					ConfigMap: &corev1.ConfigMapVolumeSource{
						LocalObjectReference: corev1.LocalObjectReference{
							Name: "mysql-cm-" + d.Name,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
589
590
						},
					},
591
592
593
594
				},
			},
		},
	}
595
	return nil
596
597
}

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// deploymentForDrupalSite defines the server runtime deployment of a DrupalSite
func deploymentForDrupalSite(currentobject *appsv1.Deployment, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Annotations = map[string]string{
			"image.openshift.io/triggers": "[{\"from\":{\"kind\":\"ImageStreamTag\",\"name\":\"drupal-nginx-" + d.Name + ":" + d.Spec.DrupalVersion + "\",\"namespace\":\"" + d.Namespace + "\"},\"fieldPath\":\"spec.template.spec.containers[?(@.name==\"nginx\")].image\",\"pause\":\"false\"}, {\"from\":{\"kind\":\"ImageStreamTag\",\"name\":\"drupal-php-" + d.Name + ":" + d.Spec.DrupalVersion + "\",\"namespace\":\"" + d.Namespace + "\"},\"fieldPath\":\"spec.template.spec.containers[?(@.name==\"php-fpm\")].image\",\"pause\":\"false\"}]",
		}
		currentobject.Spec.Template.ObjectMeta.Annotations = map[string]string{
			"php-configmap-version":   "1",
			"nginx-configmap-version": "1",
		}
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
617
	ls := labelsForDrupalSite(d.Name)
618
	ls["app"] = "drupal"
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec.Replicas = pointer.Int32Ptr(1)
	currentobject.Spec.Selector = &metav1.LabelSelector{
		MatchLabels: ls,
	}
	currentobject.Spec.Template.ObjectMeta.Labels = ls

	currentobject.Spec.Template.Spec = corev1.PodSpec{
		Containers: []corev1.Container{{
			Image:           "drupal-nginx-" + d.Name + ":" + d.Spec.DrupalVersion,
			Name:            "nginx",
			ImagePullPolicy: "IfNotPresent",
			Ports: []corev1.ContainerPort{{
				ContainerPort: 8080,
				Name:          "nginx",
				Protocol:      "TCP",
			}},
			Env: []corev1.EnvVar{
				{
					Name:  "DRUPAL_SHARED_VOLUME",
					Value: "/drupal-data",
642
				},
643
644
645
646
647
648
			},
			EnvFrom: []corev1.EnvFromSource{
				{
					SecretRef: &corev1.SecretEnvSource{
						LocalObjectReference: corev1.LocalObjectReference{
							Name: "drupal-mysql-secret",
649
						},
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
650
					},
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
				},
			},
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      "drupal-directory-" + d.Name,
					MountPath: "/drupal-data",
				},
				{
					Name:      "nginx-config-volume",
					MountPath: "/etc/nginx/conf.d/default.conf",
					SubPath:   "default.conf",
				},
				{
					Name:      "empty-dir",
					MountPath: "/var/run/",
				},
			},
		},
			{
				Image:           "drupal-php-" + d.Name + ":" + d.Spec.DrupalVersion,
				Name:            "php-fpm",
				ImagePullPolicy: "IfNotPresent",
				Ports: []corev1.ContainerPort{{
					ContainerPort: 9000,
					Name:          "php-fpm",
					Protocol:      "TCP",
				}},
				Env: []corev1.EnvVar{
					{
						Name:  "DRUPAL_SHARED_VOLUME",
						Value: "/drupal-data",
					},
				},
				EnvFrom: []corev1.EnvFromSource{
					{
						SecretRef: &corev1.SecretEnvSource{
							LocalObjectReference: corev1.LocalObjectReference{
								Name: "drupal-mysql-secret",
689
690
							},
						},
691
					},
692
				},
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
				VolumeMounts: []corev1.VolumeMount{
					{
						Name:      "drupal-directory-" + d.Name,
						MountPath: "/drupal-data",
					},
					{
						Name:      "php-config-volume",
						MountPath: "/usr/local/etc/php-fpm.d/zz-docker.conf",
						SubPath:   "zz-docker.conf",
					},
					{
						Name:      "empty-dir",
						MountPath: "/var/run/",
					},
				},
			}},
		Volumes: []corev1.Volume{
			{
				Name: "drupal-directory-" + d.Name,
				VolumeSource: corev1.VolumeSource{
					PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
						ClaimName: "drupal-pv-claim-" + d.Name,
					},
				}},
			{
				Name: "php-config-volume",
				VolumeSource: corev1.VolumeSource{
					ConfigMap: &corev1.ConfigMapVolumeSource{
						LocalObjectReference: corev1.LocalObjectReference{
							Name: "php-fpm-cm-" + d.Name,
723
724
725
						},
					},
				},
726
727
728
729
730
731
732
			},
			{
				Name: "nginx-config-volume",
				VolumeSource: corev1.VolumeSource{
					ConfigMap: &corev1.ConfigMapVolumeSource{
						LocalObjectReference: corev1.LocalObjectReference{
							Name: "nginx-cm-" + d.Name,
Vineet Reddy Rajula's avatar
Vineet Reddy Rajula committed
733
734
735
736
						},
					},
				},
			},
737
738
739
740
			{
				Name:         "empty-dir",
				VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{}},
			},
741
742
		},
	}
743
	return nil
744
745
}

746
// persistentVolumeClaimForMySQL returns a PVC object
747
748
749
750
func persistentVolumeClaimForMySQL(currentobject *corev1.PersistentVolumeClaim, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Spec = corev1.PersistentVolumeClaimSpec{
751
752
753
754
755
756
757
758
759
760
			// Selector: &metav1.LabelSelector{
			// 	MatchLabels: ls,
			// },
			StorageClassName: pointer.StringPtr("cephfs-no-backup"),
			AccessModes:      []corev1.PersistentVolumeAccessMode{"ReadWriteOnce"},
			Resources: corev1.ResourceRequirements{
				Requests: corev1.ResourceList{
					corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("5Gi"),
				},
			},
761
762
763
764
765
766
767
768
		}
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
769
	}
770
771
772
773
774
775
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "mysql"
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	return nil
776
777
}

778
// persistentVolumeClaimForDrupalSite returns a PVC object
779
780
781
782
func persistentVolumeClaimForDrupalSite(currentobject *corev1.PersistentVolumeClaim, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Spec = corev1.PersistentVolumeClaimSpec{
783
784
785
786
787
788
789
			// Selector: &metav1.LabelSelector{
			// 	MatchLabels: ls,
			// },
			StorageClassName: pointer.StringPtr("cephfs-no-backup"),
			AccessModes:      []corev1.PersistentVolumeAccessMode{"ReadWriteOnce"},
			Resources: corev1.ResourceRequirements{
				Requests: corev1.ResourceList{
790
					corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("10Gi"),
791
792
				},
			},
793
794
795
796
797
798
799
800
		}
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
801
	}
802
803
804
805
806
807
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "drupal"
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	return nil
808
809
}

810
// serviceForDrupalSite returns a service object for Nginx
811
812
813
814
815
816
817
818
819
820
821
func serviceForDrupalSite(currentobject *corev1.Service, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
822
	ls := labelsForDrupalSite(d.Name)
823
	ls["app"] = "drupal"
824
825
	for k, v := range ls {
		currentobject.Labels[k] = v
826
	}
827
828
829
830
831
832
833
834
	currentobject.Spec.Selector = ls
	currentobject.Spec.Ports = []corev1.ServicePort{{
		TargetPort: intstr.FromInt(8080),
		Name:       "nginx",
		Port:       80,
		Protocol:   "TCP",
	}}
	return nil
835
836
}

837
// serviceForDrupalSiteMySQL returns a service object for MySQL
838
839
840
841
842
843
844
845
846
847
848
func serviceForDrupalSiteMySQL(currentobject *corev1.Service, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
849
	ls := labelsForDrupalSite(d.Name)
850
	ls["app"] = "mysql"
851
852
	for k, v := range ls {
		currentobject.Labels[k] = v
853
	}
854
855
856
857
858
859
860
861
	currentobject.Spec.Selector = ls
	currentobject.Spec.Ports = []corev1.ServicePort{{
		TargetPort: intstr.FromInt(3306),
		Name:       "mysql",
		Port:       3306,
		Protocol:   "TCP",
	}}
	return nil
862
863
}

864
// routeForDrupalSite returns a route object
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
func routeForDrupalSite(currentobject *routev1.Route, d *webservicesv1a1.DrupalSite) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
	ls := labelsForDrupalSite(d.Name)
	ls["app"] = "drupal"
	ls[routerShardLabel] = d.Spec.AssignedRouterShard

Konstantinos Samaras-Tsakiris's avatar
Konstantinos Samaras-Tsakiris committed
880
881
	env := ""
	if d.Spec.Environment.Name != productionEnvironment {
882
883
		env = d.Spec.Environment.Name + "."
	}
884
885
886
887
888
889
890
891
892
893

	for k, v := range ls {
		currentobject.Labels[k] = v
	}
	currentobject.Spec = routev1.RouteSpec{
		Host: env + d.Name + "." + ClusterName + ".cern.ch",
		To: routev1.RouteTargetReference{
			Kind:   "Service",
			Name:   "drupal-" + d.Name,
			Weight: pointer.Int32Ptr(100),
894
		},
895
896
		Port: &routev1.RoutePort{
			TargetPort: intstr.FromInt(8080),
897
898
		},
	}
899
	return nil
900
901
}

902
// jobForDrupalSiteDrush returns a job object thats runs drush
903
func jobForDrupalSiteDrush(currentobject *batchv1.Job, d *webservicesv1a1.DrupalSite) error {
904
	ls := labelsForDrupalSite(d.Name)
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
		currentobject.Labels = map[string]string{}
		currentobject.Spec.Template.ObjectMeta = metav1.ObjectMeta{
			Labels: ls,
		}
		currentobject.Spec.Template.Spec = corev1.PodSpec{
			InitContainers: []corev1.Container{{
				Image:           "bash",
				Name:            "pvc-init",
				ImagePullPolicy: "IfNotPresent",
				Command:         []string{"bash", "-c", "mkdir -p $DRUPAL_SHARED_VOLUME/{files,private,modules,themes}"},
				Env: []corev1.EnvVar{
					{
						Name:  "DRUPAL_SHARED_VOLUME",
						Value: "/drupal-data",
					},
922
				},
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
				VolumeMounts: []corev1.VolumeMount{{
					Name:      "drupal-directory-" + d.Name,
					MountPath: "/drupal-data",
				}},
			}},
			RestartPolicy: "Never",
			Containers: []corev1.Container{{
				Image:           "drupal-php-" + d.Name + ":" + d.Spec.DrupalVersion,
				Name:            "drush",
				ImagePullPolicy: "Always",
				Command:         siteInstallJobForDrupalSite(),
				Env: []corev1.EnvVar{
					{
						Name:  "DRUPAL_SHARED_VOLUME",
						Value: "/drupal-data",
					},
				},
				EnvFrom: []corev1.EnvFromSource{
					{
						SecretRef: &corev1.SecretEnvSource{
							LocalObjectReference: corev1.LocalObjectReference{
								Name: "drupal-mysql-secret",
945
946
							},
						},
947
					},
948
				},
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
				VolumeMounts: []corev1.VolumeMount{{
					Name:      "drupal-directory-" + d.Name,
					MountPath: "/drupal-data",
				}},
			}},
			Volumes: []corev1.Volume{{
				Name: "drupal-directory-" + d.Name,
				VolumeSource: corev1.VolumeSource{
					PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
						ClaimName: "drupal-pv-claim-" + d.Name,
					},
				},
			}},
		}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
	ls["app"] = "drush"
	for k, v := range ls {
		currentobject.Labels[k] = v
971
	}
972
	return nil
973
974
}

975
976
977
978
979
980
981
982
983
984
985
986
// updateConfigMapForPHPFPM ensures a configMaps object to configure PHP, if not present. Else configmap object is updated and a new rollout is triggered
func updateConfigMapForPHPFPM(ctx context.Context, currentobject *corev1.ConfigMap, d *webservicesv1a1.DrupalSite, c client.Client) error {
	if currentobject.CreationTimestamp.IsZero() {
		addOwnerRefToObject(currentobject, asOwner(d))
	}
	if currentobject.Labels == nil {
		currentobject.Labels = map[string]string{}
	}
	if len(currentobject.GetAnnotations()[adminAnnotation]) > 0 {
		// Do nothing
		return nil
	}
987
	ls := labelsForDrupalSite(d.Name)
988
	ls["app"] = "php"
989
990
991
	for k, v := range ls {
		currentobject.Labels[k] = v
	}
992

993
994
995
	configPath := "/tmp/qos-" + string(d.Spec.Environment.QoSClass) + "/php-fpm.conf"

	content, err := ioutil.ReadFile(configPath)
996
	if err != nil {
997
		return newApplicationError(fmt.Errorf("reading PHP-FPM configMap failed: %w", err), ErrFilesystemIO)
998
999
	}

1000
	// Upstream PHP docker images use zz-docker.conf for configuration and this file gets loaded last (because of 'zz*') and overrides the default configuration loaded from www.conf