-
Notifications
You must be signed in to change notification settings - Fork 36
/
component_dependency_update_controller.go
620 lines (564 loc) · 23.9 KB
/
component_dependency_update_controller.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
547
548
549
550
551
552
553
554
555
556
557
558
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
Copyright 2021-2023 Red Hat, Inc.
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"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"text/template"
"time"
l "github.com/konflux-ci/build-service/pkg/logs"
applicationapi "github.com/redhat-appstudio/application-api/api/v1alpha1"
releaseapi "github.com/redhat-appstudio/release-service/api/v1alpha1"
tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"golang.org/x/exp/slices"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"knative.dev/pkg/apis"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
contextTimeout = 300 * time.Second
// PipelineRunTypeLabelName contains the type of the PipelineRunType
PipelineRunTypeLabelName = "pipelines.appstudio.openshift.io/type"
// PipelineRunBuildType is the type denoting a build PipelineRun.
PipelineRunBuildType = "build"
// PacEventTypeAnnotationName represents the current event type
PacEventTypeAnnotationName = "pipelinesascode.tekton.dev/event-type"
PacEventPushType = "push"
ImageUrlParamName = "IMAGE_URL"
ImageDigestParamName = "IMAGE_DIGEST"
NudgeProcessedAnnotationName = "build.appstudio.openshift.io/component-nudge-processed"
NudgeFinalizer = "build.appstudio.openshift.io/build-nudge-finalizer"
FailureCountAnnotationName = "build.appstudio.openshift.io/build-nudge-failures"
NudgeFilesAnnotationName = "build.appstudio.openshift.io/build-nudge-files"
ComponentNudgedEventType = "ComponentNudged"
ComponentNudgeFailedEventType = "ComponentNudgeFailed"
MaxAttempts = 3
KubeApiUpdateMaxAttempts = 5
FailureRetryTime = time.Minute * 5 // We retry after 5 minutes on failure
)
// The amount of time we wait before attempting to update the component, to try and avoid contention issues
// This is not a constant so tests don't have to wait
var delayTime = time.Second * 10
// ComponentDependencyUpdateReconciler reconciles a PipelineRun object
type ComponentDependencyUpdateReconciler struct {
client.Client
ApiReader client.Reader
Scheme *runtime.Scheme
EventRecorder record.EventRecorder
UpdateFunction UpdateComponentDependenciesFunction
}
type BuildResult struct {
BuiltImageRepository string
BuiltImageTag string
Digest string
DistributionRepositories []string
FileMatches string
Component *applicationapi.Component
}
// SetupController creates a new Integration reconciler and adds it to the Manager.
func (r *ComponentDependencyUpdateReconciler) SetupWithManager(manager ctrl.Manager) error {
return setupControllerWithManager(manager, r)
}
// setupControllerWithManager sets up the controller with the Manager which monitors new PipelineRuns and filters
// out pipelines we don't need
func setupControllerWithManager(manager ctrl.Manager, reconciler *ComponentDependencyUpdateReconciler) error {
return ctrl.NewControllerManagedBy(manager).
For(&tektonapi.PipelineRun{}, builder.WithPredicates(predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
new, ok := e.Object.(*tektonapi.PipelineRun)
if !ok {
return false
}
return IsBuildPushPipelineRun(new)
},
UpdateFunc: func(e event.UpdateEvent) bool {
new, ok := e.ObjectNew.(*tektonapi.PipelineRun)
if !ok {
return false
}
if !IsBuildPushPipelineRun(new) {
return false
}
// Ensure we have not finished processing
if new.ObjectMeta.Annotations != nil && new.ObjectMeta.Annotations[NudgeProcessedAnnotationName] != "" {
return false
}
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
GenericFunc: func(e event.GenericEvent) bool {
return true
},
})).
Complete(reconciler)
}
type UpdateComponentDependenciesFunction = func(ctx context.Context, client client.Client, scheme *runtime.Scheme, eventRecorder record.EventRecorder, downstreamComponents []applicationapi.Component, result *BuildResult) (immediateRetry bool, err error)
var DefaultUpdateFunction = DefaultDependenciesUpdate
// +kubebuilder:rbac:groups=appstudio.redhat.com,resources=components,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=appstudio.redhat.com,resources=components/status,verbs=get;list;watch
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns,verbs=get;list;watch;create;update;patch;delete;deletecollection
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns/finalizers,verbs=update
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
func (r *ComponentDependencyUpdateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, contextTimeout)
defer cancel()
log := ctrllog.FromContext(ctx).WithName("ComponentNudge")
ctx = ctrllog.IntoContext(ctx, log)
pipelineRun := &tektonapi.PipelineRun{}
err := r.Get(ctx, req.NamespacedName, pipelineRun)
if err != nil {
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
log.Error(err, "Failed to get pipelineRun")
return ctrl.Result{}, err
}
if pipelineRun.CreationTimestamp.Add(delayTime).After(time.Now()) {
// These objects are super contested at creation, we just wait 10s before attempting anything
return ctrl.Result{RequeueAfter: delayTime}, nil
}
component, err := GetComponentFromPipelineRun(r.Client, ctx, pipelineRun)
if err != nil || component == nil {
log.Error(err, "failed to get component")
// In case the component was deleted while running the pipeline
if controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) {
patch := client.MergeFrom(pipelineRun.DeepCopy())
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
return ctrl.Result{}, err
}
if len(component.Spec.BuildNudgesRef) == 0 {
log.Info(fmt.Sprintf("component %s has no BuildNudgesRef set", component.Name))
// In case the nudge was removed while running the pipeline
if controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) {
patch := client.MergeFrom(pipelineRun.DeepCopy())
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
return ctrl.Result{}, nil
}
log.Info("reconciling PipelineRun")
if pipelineRun.IsDone() || pipelineRun.Status.CompletionTime != nil || pipelineRun.DeletionTimestamp != nil {
result, err := r.verifyUpToDate(ctx, pipelineRun)
if err != nil {
return reconcile.Result{}, err
} else if result != nil {
return *result, nil
}
log.Info("PipelineRun complete")
if controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) || pipelineRun.Annotations == nil || pipelineRun.Annotations[NudgeProcessedAnnotationName] == "" {
log.Info("running renovate job")
// Pipeline run is done and we have not cleared the finalizer yet
// We need to perform our nudge
patch := client.MergeFrom(pipelineRun.DeepCopy())
return r.handleCompletedBuild(ctx, pipelineRun, component, patch)
}
} else if !controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) {
result, err := r.verifyUpToDate(ctx, pipelineRun)
if err != nil || result != nil {
return *result, err
}
log.Info("adding finalizer for component nudge")
// We add a finalizer to make sure we see the run before it is deleted
// As tekton results should aggressivly delete when pruning is enabled
patch := client.MergeFrom(pipelineRun.DeepCopy())
controllerutil.AddFinalizer(pipelineRun, NudgeFinalizer)
err = r.Client.Patch(ctx, pipelineRun, patch)
if err == nil {
return reconcile.Result{}, nil
} else if errors.IsConflict(err) {
log.Error(err, "failed to add finalizer due to conflict, retrying in one second")
return reconcile.Result{RequeueAfter: time.Second}, nil
} else {
log.Error(err, "failed to add finalizer")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
func (r *ComponentDependencyUpdateReconciler) verifyUpToDate(ctx context.Context, pipelineRun *tektonapi.PipelineRun) (*ctrl.Result, error) {
// These objects are so heavily contented that we always grab the latest copy from the
// API server and verify we are up-to-date
currentPipelineRun := &tektonapi.PipelineRun{}
err := r.ApiReader.Get(ctx, types.NamespacedName{Namespace: pipelineRun.Namespace, Name: pipelineRun.Name}, currentPipelineRun)
if err != nil {
return nil, err
}
if currentPipelineRun.ResourceVersion != pipelineRun.ResourceVersion {
ctrllog.FromContext(ctx).Info("returning early as resource is out of date")
return &ctrl.Result{RequeueAfter: time.Second}, nil
}
return nil, nil
}
// handleCompletedBuild will perform a 'nudge' updating dependent downstream components.
// This will involve creating a PR updating their references to our images to the newly produced image
func (r *ComponentDependencyUpdateReconciler) handleCompletedBuild(ctx context.Context, pipelineRun *tektonapi.PipelineRun, updatedComponent *applicationapi.Component, patch client.Patch) (ctrl.Result, error) {
log := ctrllog.FromContext(ctx)
success := pipelineRun.Status.GetCondition(apis.ConditionSucceeded).IsTrue()
if !success {
log.Info("not performing nudge as pipeline failed")
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
// find the image and digest we want to update to
image := ""
digest := ""
for _, r := range pipelineRun.Status.Results {
if r.Name == ImageDigestParamName {
digest = r.Value.StringVal
} else if r.Name == ImageUrlParamName {
image = r.Value.StringVal
}
}
// Failure to find is a permanent error, so remove the finalizer
if image == "" {
log.Error(fmt.Errorf("unable to find %s param on PipelineRun, not performing nudge", ImageUrlParamName), "no image url result")
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
if digest == "" {
log.Error(fmt.Errorf("unable to find %s param on PipelineRun, not performing nudge", ImageDigestParamName), "no image digest result")
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
tag := ""
repo := image
index := strings.LastIndex(image, ":")
if index != -1 {
repo = image[0:index]
tag = image[index+1:]
}
// find any configurations for files to nudge in
if pipelineRun.Annotations == nil {
pipelineRun.Annotations = map[string]string{}
}
nudgeFiles := pipelineRun.Annotations[NudgeFilesAnnotationName]
if nudgeFiles == "" {
nudgeFiles = ".*Dockerfile.*, .*.yaml, .*Containerfile.*"
}
components := applicationapi.ComponentList{}
err := r.Client.List(ctx, &components, client.InNamespace(pipelineRun.Namespace))
if err != nil {
log.Error(err, "failed to list components in namespace")
return ctrl.Result{}, err
}
// Now look for distribution repositories
// We do this by looking through ReleasePlanAdmission objects
retryTime := FailureRetryTime
immediateRetry := false
toUpdate := []applicationapi.Component{}
distibutionRepositories := []string{}
releasePlanAdmissions := releaseapi.ReleasePlanAdmissionList{}
err = r.Client.List(ctx, &releasePlanAdmissions)
if err != nil {
return ctrl.Result{}, err
}
for _, admission := range releasePlanAdmissions.Items {
log.Info("found ReleaseAdmissionPlan", "plan", admission.Name, "origin", admission.Spec.Origin)
if admission.Spec.Origin == pipelineRun.Namespace && admission.Spec.Data != nil {
log.Info("considering ReleaseAdmissionPlan", "plan", admission.Name, "origin", admission.Spec.Origin)
data := struct {
Mapping struct {
Components []struct {
Name string
Repository string
}
}
}{}
err := json.Unmarshal(admission.Spec.Data.Raw, &data)
if err != nil {
log.Error(err, fmt.Sprintf("unable to parse ReleasePlanAdmission %s/%s", admission.Namespace, admission.Name))
}
for _, compMapping := range data.Mapping.Components {
log.Info("considering Component", "plan", admission.Name, "origin", admission.Spec.Origin)
if compMapping.Name == updatedComponent.Name {
log.Info("added distribution repo", "repo", compMapping.Repository)
distibutionRepositories = append(distibutionRepositories, compMapping.Repository)
registryRedhatMapping := mapToRegistryRedhatIo(compMapping.Repository)
if registryRedhatMapping != "" {
distibutionRepositories = append(distibutionRepositories, registryRedhatMapping)
}
}
}
}
}
for i := range components.Items {
comp := components.Items[i]
if slices.Contains(updatedComponent.Spec.BuildNudgesRef, comp.Name) {
toUpdate = append(toUpdate, comp)
}
}
var nudgeErr error
immediateRetry, nudgeErr = r.UpdateFunction(ctx, r.Client, r.Scheme, r.EventRecorder, toUpdate, &BuildResult{BuiltImageRepository: repo, BuiltImageTag: tag, Digest: digest, Component: updatedComponent, DistributionRepositories: distibutionRepositories, FileMatches: nudgeFiles})
if nudgeErr != nil {
componentDesc := ""
for _, comp := range toUpdate {
if componentDesc != "" {
componentDesc += ", "
}
componentDesc += comp.Namespace + "/" + comp.Name
}
log.Error(nudgeErr, fmt.Sprintf("component update of components %s as a result of a build of %s failed", componentDesc, updatedComponent.Name), l.Audit, "true")
if pipelineRun.Annotations == nil {
pipelineRun.Annotations = map[string]string{}
}
existing := pipelineRun.Annotations[FailureCountAnnotationName]
if existing == "" {
existing = "0"
}
failureCount, err := strconv.Atoi(existing)
if err != nil {
log.Error(err, "failed to parse retry count, not retrying")
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
failureCount = failureCount + 1
pipelineRun.Annotations[FailureCountAnnotationName] = strconv.Itoa(failureCount)
r.EventRecorder.Event(updatedComponent, corev1.EventTypeWarning, ComponentNudgeFailedEventType, fmt.Sprintf("component update failed as a result of a build for %s, retry %d/%d", updatedComponent.Name, failureCount, MaxAttempts))
if failureCount >= MaxAttempts {
// We are at the failure limit, nothing much we can do
log.Info("not retrying as max failure limit has been reached", l.Audit, "true")
return r.removePipelineFinalizer(ctx, pipelineRun, patch)
}
log.Info(fmt.Sprintf("failed to update component dependencies, retry %d/%d", failureCount, MaxAttempts))
err = r.Client.Patch(ctx, pipelineRun, patch)
if err != nil {
// If we fail to update just return and let requeue handle it
// We can't really do anything else
// This does mean components may get nudged a second time, but it is idempotent anyway
return ctrl.Result{}, err
}
if immediateRetry {
return reconcile.Result{RequeueAfter: time.Millisecond}, nil
} else {
return reconcile.Result{RequeueAfter: retryTime * time.Duration(failureCount)}, nil
}
}
_, err = r.removePipelineFinalizer(ctx, pipelineRun, patch)
if err != nil {
return ctrl.Result{}, err
}
// Now we need to look for 'stale' pipelines.
// These are defined as pipelines that are younger than this one, that target the same component.
// If there are two pushes very close together variances in pipeline run times may mean that the
// older one finishes last. In this case we want to mark the older one as already nudged and remove
// the finalizer.
pipelines := tektonapi.PipelineRunList{}
err = r.Client.List(ctx, &pipelines, client.InNamespace(pipelineRun.Namespace), client.MatchingLabels{PipelineRunTypeLabelName: PipelineRunBuildType, ComponentNameLabelName: updatedComponent.Name})
if err != nil {
// I don't think we want to retry this, it should be really rare anyway
// and would require an even more complex label based state machine.
log.Error(err, "failed to check for stale pipeline runs, this operation will not be retried", l.Audit, "true")
return ctrl.Result{}, nil
}
var finalizerError error
for i := range pipelines.Items {
possiblyStalePr := pipelines.Items[i]
if possiblyStalePr.Annotations == nil || possiblyStalePr.Annotations[PacEventTypeAnnotationName] != PacEventPushType || possiblyStalePr.Name == pipelineRun.Name {
continue
}
if possiblyStalePr.Status.CompletionTime == nil && possiblyStalePr.CreationTimestamp.Before(&pipelineRun.CreationTimestamp) {
log.Info(fmt.Sprintf("marking PipelineRun %s as nudged, as it is stale", possiblyStalePr.Name))
if possiblyStalePr.Annotations == nil {
possiblyStalePr.Annotations = map[string]string{}
}
_, err := r.removePipelineFinalizer(ctx, &possiblyStalePr, patch)
if err != nil {
finalizerError = err
log.Error(err, "failed to update stale pipeline run", l.Audit, "true")
}
}
}
return ctrl.Result{}, finalizerError
}
// removePipelineFinalizer will remove the finalizer, and add an annotation to indicate we are done with this pipeline run
// We can't use just the presence or absence of the finalizer, as there is some situations where we might not have seen the
// run until it is completed, e.g. if the controller was down.
func (r *ComponentDependencyUpdateReconciler) removePipelineFinalizer(ctx context.Context, pipelineRun *tektonapi.PipelineRun, patch client.Patch) (ctrl.Result, error) {
if pipelineRun.Annotations == nil {
pipelineRun.Annotations = map[string]string{}
}
pipelineRun.Annotations[NudgeProcessedAnnotationName] = "true"
controllerutil.RemoveFinalizer(pipelineRun, NudgeFinalizer)
err := r.Client.Patch(ctx, pipelineRun, patch)
if err != nil {
if !errors.IsConflict(err) {
log := ctrllog.FromContext(ctx)
// We don't log/fire events on conflicts, they are part of normal operation,
// especially as these are highly contended objects
log.Error(err, "unable to remove pipeline run finalizer")
r.EventRecorder.Event(pipelineRun, corev1.EventTypeWarning, ComponentNudgedEventType, fmt.Sprintf("failed to remove finalizer from %s", pipelineRun.Name))
}
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func IsBuildPushPipelineRun(object client.Object) bool {
if pipelineRun, ok := object.(*tektonapi.PipelineRun); ok {
// Ensure the PipelineRun belongs to a Component
if pipelineRun.Labels == nil || pipelineRun.Labels[ComponentNameLabelName] == "" {
// PipelineRun does not belong to a Component
return false
}
if pipelineRun.Labels != nil && pipelineRun.Annotations != nil {
if pipelineRun.Labels[PipelineRunTypeLabelName] == PipelineRunBuildType && pipelineRun.Annotations[PacEventTypeAnnotationName] == PacEventPushType {
return true
}
}
}
return false
}
// GetComponentFromPipelineRun loads from the cluster the Component referenced in the given PipelineRun. If the PipelineRun doesn't
// specify a Component we return nil, if the component is not specified we return an error
func GetComponentFromPipelineRun(c client.Client, ctx context.Context, pipelineRun *tektonapi.PipelineRun) (*applicationapi.Component, error) {
if componentName, found := pipelineRun.Labels[ComponentNameLabelName]; found {
component := &applicationapi.Component{}
err := c.Get(ctx, types.NamespacedName{
Namespace: pipelineRun.Namespace,
Name: componentName,
}, component)
if err != nil {
return nil, err
}
return component, nil
}
return nil, nil
}
func DefaultDependenciesUpdate(ctx context.Context, client client.Client, scheme *runtime.Scheme, eventRecorder record.EventRecorder, downstreamComponents []applicationapi.Component, result *BuildResult) (immediateRetry bool, err error) {
log := ctrllog.FromContext(ctx)
log.Info(fmt.Sprintf("reading github installations for %d components", len(downstreamComponents)))
slug, installationsToUpdate, err := GetGithubInstallationsForComponents(ctx, client, eventRecorder, downstreamComponents)
if err != nil || slug == "" {
return false, err
}
log.Info("creating renovate job")
err = CreateRenovaterPipeline(ctx, client, scheme, result.Component.Namespace, installationsToUpdate, slug, true, generateRenovateConfigForNudge, result)
return false, err
}
func generateRenovateConfigForNudge(slug string, repositories []renovateRepository, context interface{}) (string, error) {
buildResult := context.(*BuildResult)
repositoriesData, _ := json.Marshal(repositories)
fileMatchParts := strings.Split(buildResult.FileMatches, ",")
for i := range fileMatchParts {
fileMatchParts[i] = strings.TrimSpace(fileMatchParts[i])
}
fileMatch, err := json.Marshal(fileMatchParts)
if err != nil {
return "", err
}
body := `
{{with $root := .}}
module.exports = {
platform: "github",
username: "{{.Slug}}[bot]",
gitAuthor:"{{.Slug}} <123456+{{.Slug}}[bot]@users.noreply.github.com>",
onboarding: false,
requireConfig: "ignored",
repositories: {{.Repositories}},
enabledManagers: "regex",
customManagers: [
{
"fileMatch": {{.FileMatches}},
"customType": "regex",
"datasourceTemplate": "docker",
"matchStrings": [
"{{.BuiltImageRepository}}(:.*)?@(?<currentDigest>sha256:[a-f0-9]+)"
{{range .DistributionRepositories}},"{{.}}(:.*)?@(?<currentDigest>sha256:[a-f0-9]+)"{{end}}
],
"currentValueTemplate": "{{.BuiltImageTag}}",
"depNameTemplate": "{{.BuiltImageRepository}}",
}
],
registryAliases: {
{{range $index, $repo := .DistributionRepositories}}{{if $index}},{{end}}
"{{$repo}}": "{{$.BuiltImageRepository}}"{{end}}
},
packageRules: [
{
matchPackagePatterns: ["*"],
enabled: false
},
{
"matchPackageNames": ["{{.BuiltImageRepository}}", {{range .DistributionRepositories}},"{{.}}"{{end}}],
groupName: "Component Update {{.ComponentName}}",
branchName: "rhtap/component-updates/{{.ComponentName}}",
commitMessageTopic: "{{.ComponentName}}",
prFooter: "To execute skipped test pipelines write comment ` + "`/ok-to-test`" + `",
recreateWhen: "always",
rebaseWhen: "behind-base-branch",
enabled: true,
followTag: "{{.BuiltImageTag}}"
}
],
forkProcessing: "enabled",
dependencyDashboard: false
}
{{end}}
`
data := struct {
Slug string
ComponentName string
Repositories string
BuiltImageRepository string
BuiltImageTag string
Digest string
DistributionRepositories []string
FileMatches string
}{
Slug: slug,
ComponentName: buildResult.Component.Name,
Repositories: string(repositoriesData),
BuiltImageRepository: buildResult.BuiltImageRepository,
BuiltImageTag: buildResult.BuiltImageTag,
Digest: buildResult.Digest,
DistributionRepositories: buildResult.DistributionRepositories,
FileMatches: string(fileMatch),
}
tmpl, err := template.New("renovate").Parse(body)
if err != nil {
return "", err
}
build := strings.Builder{}
err = tmpl.Execute(&build, data)
if err != nil {
return "", err
}
return build.String(), nil
}
// See https://issues.redhat.com/browse/KFLUXBUGS-1233
// This will map repsitories of the form 'quay.io/redhat-prod/foo----bar' to 'registry.redhat.io/foo/bar'
func mapToRegistryRedhatIo(repo string) string {
regex, err := regexp.Compile(`^quay.io/redhat-prod/(.*)----(.*)$`)
if err != nil {
return ""
}
results := regex.FindStringSubmatch(repo)
if results == nil {
return ""
}
return "registry.redhat.io/" + results[1] + "/" + results[2]
}