forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
806 lines (738 loc) · 31.4 KB
/
generator.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
package generator
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/golang/glog"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/unversioned"
kclient "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/credentialprovider"
kvalidation "k8s.io/kubernetes/pkg/util/validation"
buildapi "github.com/openshift/origin/pkg/build/api"
buildutil "github.com/openshift/origin/pkg/build/util"
"github.com/openshift/origin/pkg/cmd/admin/policy"
"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
imageapi "github.com/openshift/origin/pkg/image/api"
"github.com/openshift/origin/pkg/util/namer"
)
// GeneratorFatalError represents a fatal error while generating a build.
// An operation that fails because of a fatal error should not be retried.
type GeneratorFatalError struct {
// Reason the fatal error occurred
Reason string
}
// Error returns the error string for this fatal error
func (e GeneratorFatalError) Error() string {
return fmt.Sprintf("fatal error generating Build from BuildConfig: %s", e.Reason)
}
// IsFatal returns true if err is a fatal error
func IsFatal(err error) bool {
_, isFatal := err.(GeneratorFatalError)
return isFatal
}
// BuildGenerator is a central place responsible for generating new Build objects
// from BuildConfigs and other Builds.
type BuildGenerator struct {
Client GeneratorClient
DefaultServiceAccountName string
ServiceAccounts kclient.ServiceAccountsNamespacer
Secrets kclient.SecretsNamespacer
}
// GeneratorClient is the API client used by the generator
type GeneratorClient interface {
GetBuildConfig(ctx kapi.Context, name string) (*buildapi.BuildConfig, error)
UpdateBuildConfig(ctx kapi.Context, buildConfig *buildapi.BuildConfig) error
GetBuild(ctx kapi.Context, name string) (*buildapi.Build, error)
CreateBuild(ctx kapi.Context, build *buildapi.Build) error
GetImageStream(ctx kapi.Context, name string) (*imageapi.ImageStream, error)
GetImageStreamImage(ctx kapi.Context, name string) (*imageapi.ImageStreamImage, error)
GetImageStreamTag(ctx kapi.Context, name string) (*imageapi.ImageStreamTag, error)
}
// Client is an implementation of the GeneratorClient interface
type Client struct {
GetBuildConfigFunc func(ctx kapi.Context, name string) (*buildapi.BuildConfig, error)
UpdateBuildConfigFunc func(ctx kapi.Context, buildConfig *buildapi.BuildConfig) error
GetBuildFunc func(ctx kapi.Context, name string) (*buildapi.Build, error)
CreateBuildFunc func(ctx kapi.Context, build *buildapi.Build) error
GetImageStreamFunc func(ctx kapi.Context, name string) (*imageapi.ImageStream, error)
GetImageStreamImageFunc func(ctx kapi.Context, name string) (*imageapi.ImageStreamImage, error)
GetImageStreamTagFunc func(ctx kapi.Context, name string) (*imageapi.ImageStreamTag, error)
}
// GetBuildConfig retrieves a named build config
func (c Client) GetBuildConfig(ctx kapi.Context, name string) (*buildapi.BuildConfig, error) {
return c.GetBuildConfigFunc(ctx, name)
}
// UpdateBuildConfig updates a named build config
func (c Client) UpdateBuildConfig(ctx kapi.Context, buildConfig *buildapi.BuildConfig) error {
return c.UpdateBuildConfigFunc(ctx, buildConfig)
}
// GetBuild retrieves a build
func (c Client) GetBuild(ctx kapi.Context, name string) (*buildapi.Build, error) {
return c.GetBuildFunc(ctx, name)
}
// CreateBuild creates a new build
func (c Client) CreateBuild(ctx kapi.Context, build *buildapi.Build) error {
return c.CreateBuildFunc(ctx, build)
}
// GetImageStream retrieves a named image stream
func (c Client) GetImageStream(ctx kapi.Context, name string) (*imageapi.ImageStream, error) {
return c.GetImageStreamFunc(ctx, name)
}
// GetImageStreamImage retrieves an image stream image
func (c Client) GetImageStreamImage(ctx kapi.Context, name string) (*imageapi.ImageStreamImage, error) {
return c.GetImageStreamImageFunc(ctx, name)
}
// GetImageStreamTag retrieves and image stream tag
func (c Client) GetImageStreamTag(ctx kapi.Context, name string) (*imageapi.ImageStreamTag, error) {
return c.GetImageStreamTagFunc(ctx, name)
}
type streamRef struct {
ref *kapi.ObjectReference
tag string
}
// FetchServiceAccountSecrets retrieves the Secrets used for pushing and pulling
// images from private Docker registries.
func (g *BuildGenerator) FetchServiceAccountSecrets(namespace, serviceAccount string) ([]kapi.Secret, error) {
var result []kapi.Secret
sa, err := g.ServiceAccounts.ServiceAccounts(namespace).Get(serviceAccount)
if err != nil {
return result, fmt.Errorf("Error getting push/pull secrets for service account %s/%s: %v", namespace, serviceAccount, err)
}
for _, ref := range sa.Secrets {
secret, err := g.Secrets.Secrets(namespace).Get(ref.Name)
if err != nil {
continue
}
result = append(result, *secret)
}
return result, nil
}
// findImageChangeTrigger finds an image change trigger that has a from that matches the passed in ref
// if no match is found but there is an image change trigger with a null from, that trigger is returned
func findImageChangeTrigger(bc *buildapi.BuildConfig, ref *kapi.ObjectReference) *buildapi.ImageChangeTrigger {
if ref == nil {
return nil
}
for _, trigger := range bc.Spec.Triggers {
if trigger.Type != buildapi.ImageChangeBuildTriggerType {
continue
}
imageChange := trigger.ImageChange
triggerRef := imageChange.From
if triggerRef == nil {
triggerRef = buildutil.GetInputReference(bc.Spec.Strategy)
if triggerRef == nil || triggerRef.Kind != "ImageStreamTag" {
continue
}
}
triggerNs := triggerRef.Namespace
if triggerNs == "" {
triggerNs = bc.Namespace
}
refNs := ref.Namespace
if refNs == "" {
refNs = bc.Namespace
}
if triggerRef.Name == ref.Name && triggerNs == refNs {
return imageChange
}
}
return nil
}
func describeBuildRequest(request *buildapi.BuildRequest) string {
desc := fmt.Sprintf("BuildConfig: %s/%s", request.Namespace, request.Name)
if request.Revision != nil {
desc += fmt.Sprintf(", Revision: %#v", request.Revision.Git)
}
if request.TriggeredByImage != nil {
desc += fmt.Sprintf(", TriggeredBy: %s/%s with stream: %s/%s",
request.TriggeredByImage.Kind, request.TriggeredByImage.Name,
request.From.Kind, request.From.Name)
}
if request.LastVersion != nil {
desc += fmt.Sprintf(", LastVersion: %d", *request.LastVersion)
}
return desc
}
// updateBuildEnv updates the strategy environment
// This will replace the existing variable definitions with provided env
func updateBuildEnv(strategy *buildapi.BuildStrategy, env []kapi.EnvVar) {
var buildEnv *[]kapi.EnvVar
switch {
case strategy.SourceStrategy != nil:
buildEnv = &strategy.SourceStrategy.Env
case strategy.DockerStrategy != nil:
buildEnv = &strategy.DockerStrategy.Env
case strategy.CustomStrategy != nil:
buildEnv = &strategy.CustomStrategy.Env
}
newEnv := []kapi.EnvVar{}
for _, e := range *buildEnv {
exists := false
for _, n := range env {
if e.Name == n.Name {
exists = true
break
}
}
if !exists {
newEnv = append(newEnv, e)
}
}
newEnv = append(newEnv, env...)
*buildEnv = newEnv
}
// Instantiate returns a new Build object based on a BuildRequest object
func (g *BuildGenerator) Instantiate(ctx kapi.Context, request *buildapi.BuildRequest) (*buildapi.Build, error) {
glog.V(4).Infof("Generating Build from %s", describeBuildRequest(request))
bc, err := g.Client.GetBuildConfig(ctx, request.Name)
if err != nil {
return nil, err
}
if buildutil.IsPaused(bc) {
return nil, errors.NewBadRequest(fmt.Sprintf("can't instantiate from BuildConfig %s/%s: BuildConfig is paused", bc.Namespace, bc.Name))
}
if err := g.checkLastVersion(bc, request.LastVersion); err != nil {
return nil, errors.NewBadRequest(err.Error())
}
if err := g.updateImageTriggers(ctx, bc, request.From, request.TriggeredByImage); err != nil {
if _, ok := err.(errors.APIStatus); ok {
return nil, err
}
return nil, errors.NewInternalError(err)
}
newBuild, err := g.generateBuildFromConfig(ctx, bc, request.Revision, request.Binary)
if err != nil {
if _, ok := err.(errors.APIStatus); ok {
return nil, err
}
return nil, errors.NewInternalError(err)
}
// Add labels and annotations from the buildrequest. Existing
// label/annotations will take precedence because we don't want system
// annotations/labels (eg buildname) to get stomped on.
newBuild.Annotations = policy.MergeMaps(request.Annotations, newBuild.Annotations)
newBuild.Labels = policy.MergeMaps(request.Labels, newBuild.Labels)
// Copy build trigger information to the build object.
newBuild.Spec.TriggeredBy = request.TriggeredBy
if len(request.Env) > 0 {
updateBuildEnv(&newBuild.Spec.Strategy, request.Env)
}
glog.V(4).Infof("Build %s/%s has been generated from %s/%s BuildConfig", newBuild.Namespace, newBuild.ObjectMeta.Name, bc.Namespace, bc.ObjectMeta.Name)
// need to update the BuildConfig because LastVersion and possibly
// LastTriggeredImageID changed
if err := g.Client.UpdateBuildConfig(ctx, bc); err != nil {
glog.V(4).Infof("Failed to update BuildConfig %s/%s so no Build will be created", bc.Namespace, bc.Name)
return nil, err
}
// Ideally we would create the build *before* updating the BC to ensure
// that we don't set the LastTriggeredImageID on the BC and then fail to
// create the corresponding build, however doing things in that order
// allows for a race condition in which two builds get kicked off. Doing
// it in this order ensures that we catch the race while updating the BC.
return g.createBuild(ctx, newBuild)
}
// checkBuildConfigLastVersion will return an error if the BuildConfig's LastVersion doesn't match the passed in lastVersion
// when lastVersion is not nil
func (g *BuildGenerator) checkLastVersion(bc *buildapi.BuildConfig, lastVersion *int64) error {
if lastVersion != nil && bc.Status.LastVersion != *lastVersion {
glog.V(2).Infof("Aborting version triggered build for BuildConfig %s/%s because the BuildConfig LastVersion (%d) does not match the requested LastVersion (%d)", bc.Namespace, bc.Name, bc.Status.LastVersion, *lastVersion)
return fmt.Errorf("the LastVersion(%v) on build config %s/%s does not match the build request LastVersion(%d)",
bc.Status.LastVersion, bc.Namespace, bc.Name, *lastVersion)
}
return nil
}
// updateImageTriggers sets the LastTriggeredImageID on all the ImageChangeTriggers on the BuildConfig and
// updates the From reference of the strategy if the strategy uses an ImageStream or ImageStreamTag reference
func (g *BuildGenerator) updateImageTriggers(ctx kapi.Context, bc *buildapi.BuildConfig, from, triggeredBy *kapi.ObjectReference) error {
var requestTrigger *buildapi.ImageChangeTrigger
if from != nil {
requestTrigger = findImageChangeTrigger(bc, from)
}
if requestTrigger != nil && triggeredBy != nil && requestTrigger.LastTriggeredImageID == triggeredBy.Name {
glog.V(2).Infof("Aborting imageid triggered build for BuildConfig %s/%s with imageid %s because the BuildConfig already matches this imageid", bc.Namespace, bc.Name, triggeredBy.Name)
return fmt.Errorf("build config %s/%s has already instantiated a build for imageid %s", bc.Namespace, bc.Name, triggeredBy.Name)
}
// Update last triggered image id for all image change triggers
for _, trigger := range bc.Spec.Triggers {
if trigger.Type != buildapi.ImageChangeBuildTriggerType {
continue
}
// Use the requested image id for the trigger that caused the build, otherwise resolve to the latest
if triggeredBy != nil && trigger.ImageChange == requestTrigger {
trigger.ImageChange.LastTriggeredImageID = triggeredBy.Name
continue
}
triggerImageRef := trigger.ImageChange.From
if triggerImageRef == nil {
triggerImageRef = buildutil.GetInputReference(bc.Spec.Strategy)
}
if triggerImageRef == nil {
glog.Warningf("Could not get ImageStream reference for default ImageChangeTrigger on BuildConfig %s/%s", bc.Namespace, bc.Name)
continue
}
image, err := g.resolveImageStreamReference(ctx, *triggerImageRef, bc.Namespace)
if err != nil {
// If the trigger is for the strategy from ref, return an error
if trigger.ImageChange.From == nil {
return err
}
// Otherwise, warn that an error occurred, but continue
glog.Warningf("Could not resolve trigger reference for build config %s/%s: %#v", bc.Namespace, bc.Name, triggerImageRef)
}
trigger.ImageChange.LastTriggeredImageID = image
}
return nil
}
// Clone returns clone of a Build
func (g *BuildGenerator) Clone(ctx kapi.Context, request *buildapi.BuildRequest) (*buildapi.Build, error) {
glog.V(4).Infof("Generating build from build %s/%s", request.Namespace, request.Name)
build, err := g.Client.GetBuild(ctx, request.Name)
if err != nil {
return nil, err
}
var buildConfig *buildapi.BuildConfig
if build.Status.Config != nil {
buildConfig, err = g.Client.GetBuildConfig(ctx, build.Status.Config.Name)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
if buildutil.IsPaused(buildConfig) {
return nil, errors.NewInternalError(&GeneratorFatalError{fmt.Sprintf("can't instantiate from BuildConfig %s/%s: BuildConfig is paused", buildConfig.Namespace, buildConfig.Name)})
}
}
newBuild := generateBuildFromBuild(build, buildConfig)
glog.V(4).Infof("Build %s/%s has been generated from Build %s/%s", newBuild.Namespace, newBuild.ObjectMeta.Name, build.Namespace, build.ObjectMeta.Name)
buildTriggerCauses := []buildapi.BuildTriggerCause{}
newBuild.Spec.TriggeredBy = append(buildTriggerCauses,
buildapi.BuildTriggerCause{
Message: "Manually triggered",
},
)
// need to update the BuildConfig because LastVersion changed
if buildConfig != nil {
if err := g.Client.UpdateBuildConfig(ctx, buildConfig); err != nil {
glog.V(4).Infof("Failed to update BuildConfig %s/%s so no Build will be created", buildConfig.Namespace, buildConfig.Name)
return nil, err
}
}
return g.createBuild(ctx, newBuild)
}
// createBuild is responsible for validating build object and saving it and returning newly created object
func (g *BuildGenerator) createBuild(ctx kapi.Context, build *buildapi.Build) (*buildapi.Build, error) {
if !kapi.ValidNamespace(ctx, &build.ObjectMeta) {
return nil, errors.NewConflict(buildapi.Resource("build"), build.Namespace, fmt.Errorf("Build.Namespace does not match the provided context"))
}
kapi.FillObjectMetaSystemFields(ctx, &build.ObjectMeta)
err := g.Client.CreateBuild(ctx, build)
if err != nil {
return nil, err
}
return g.Client.GetBuild(ctx, build.Name)
}
// generateBuildFromConfig generates a build definition based on the current imageid
// from any ImageStream that is associated to the BuildConfig by From reference in
// the Strategy, or uses the Image field of the Strategy. If binary is provided, override
// the current build strategy with a binary artifact for this specific build.
// Takes a BuildConfig to base the build on, and an optional SourceRevision to build.
func (g *BuildGenerator) generateBuildFromConfig(ctx kapi.Context, bc *buildapi.BuildConfig, revision *buildapi.SourceRevision, binary *buildapi.BinaryBuildSource) (*buildapi.Build, error) {
serviceAccount := bc.Spec.ServiceAccount
if len(serviceAccount) == 0 {
serviceAccount = g.DefaultServiceAccountName
}
if len(serviceAccount) == 0 {
serviceAccount = bootstrappolicy.BuilderServiceAccountName
}
// Need to copy the buildConfig here so that it doesn't share pointers with
// the build object which could be (will be) modified later.
obj, _ := kapi.Scheme.Copy(bc)
bcCopy := obj.(*buildapi.BuildConfig)
build := &buildapi.Build{
Spec: buildapi.BuildSpec{
CommonSpec: buildapi.CommonSpec{
ServiceAccount: serviceAccount,
Source: bcCopy.Spec.Source,
Strategy: bcCopy.Spec.Strategy,
Output: bcCopy.Spec.Output,
Revision: revision,
Resources: bcCopy.Spec.Resources,
PostCommit: bcCopy.Spec.PostCommit,
CompletionDeadlineSeconds: bcCopy.Spec.CompletionDeadlineSeconds,
NodeSelector: bcCopy.Spec.NodeSelector,
},
},
ObjectMeta: kapi.ObjectMeta{
Labels: bcCopy.Labels,
},
Status: buildapi.BuildStatus{
Phase: buildapi.BuildPhaseNew,
Config: &kapi.ObjectReference{
Kind: "BuildConfig",
Name: bc.Name,
Namespace: bc.Namespace,
},
},
}
if binary != nil {
build.Spec.Source.Git = nil
build.Spec.Source.Binary = binary
if build.Spec.Source.Dockerfile != nil && binary.AsFile == "Dockerfile" {
build.Spec.Source.Dockerfile = nil
}
} else {
// must explicitly set this because we copied the source values from the buildconfig.
build.Spec.Source.Binary = nil
}
build.Name = getNextBuildName(bc)
if build.Annotations == nil {
build.Annotations = make(map[string]string)
}
build.Annotations[buildapi.BuildNumberAnnotation] = strconv.FormatInt(bc.Status.LastVersion, 10)
build.Annotations[buildapi.BuildConfigAnnotation] = bcCopy.Name
if build.Labels == nil {
build.Labels = make(map[string]string)
}
build.Labels[buildapi.BuildConfigLabelDeprecated] = buildapi.LabelValue(bcCopy.Name)
build.Labels[buildapi.BuildConfigLabel] = buildapi.LabelValue(bcCopy.Name)
build.Labels[buildapi.BuildRunPolicyLabel] = string(bc.Spec.RunPolicy)
builderSecrets, err := g.FetchServiceAccountSecrets(bc.Namespace, serviceAccount)
if err != nil {
return nil, err
}
if build.Spec.Output.PushSecret == nil {
build.Spec.Output.PushSecret = g.resolveImageSecret(ctx, builderSecrets, build.Spec.Output.To, bc.Namespace)
}
strategyImageChangeTrigger := getStrategyImageChangeTrigger(bc)
// Resolve image source if present
for i, sourceImage := range build.Spec.Source.Images {
if sourceImage.PullSecret == nil {
sourceImage.PullSecret = g.resolveImageSecret(ctx, builderSecrets, &sourceImage.From, bc.Namespace)
}
var sourceImageSpec string
// if the imagesource matches the strategy from, and we have a trigger for the strategy from,
// use the imageid from the trigger rather than resolving it.
if strategyFrom := buildutil.GetInputReference(bc.Spec.Strategy); reflect.DeepEqual(sourceImage.From, *strategyFrom) &&
strategyImageChangeTrigger != nil {
sourceImageSpec = strategyImageChangeTrigger.LastTriggeredImageID
} else {
refImageChangeTrigger := getImageChangeTriggerForRef(bc, &sourceImage.From)
// if there is no trigger associated with this imagesource, resolve the imagesource reference now.
// otherwise use the imageid from the imagesource trigger.
if refImageChangeTrigger == nil {
sourceImageSpec, err = g.resolveImageStreamReference(ctx, sourceImage.From, bc.Namespace)
if err != nil {
return nil, err
}
} else {
sourceImageSpec = refImageChangeTrigger.LastTriggeredImageID
}
}
sourceImage.From.Kind = "DockerImage"
sourceImage.From.Name = sourceImageSpec
sourceImage.From.Namespace = ""
build.Spec.Source.Images[i] = sourceImage
}
// If the Build is using a From reference instead of a resolved image, we need to resolve that From
// reference to a valid image so we can run the build. Builds do not consume ImageStream references,
// only image specs.
var image string
if strategyImageChangeTrigger != nil {
image = strategyImageChangeTrigger.LastTriggeredImageID
}
switch {
case build.Spec.Strategy.SourceStrategy != nil:
if image == "" {
image, err = g.resolveImageStreamReference(ctx, build.Spec.Strategy.SourceStrategy.From, build.Status.Config.Namespace)
if err != nil {
return nil, err
}
}
build.Spec.Strategy.SourceStrategy.From = kapi.ObjectReference{
Kind: "DockerImage",
Name: image,
}
if build.Spec.Strategy.SourceStrategy.RuntimeImage != nil {
runtimeImageName, err := g.resolveImageStreamReference(ctx, *build.Spec.Strategy.SourceStrategy.RuntimeImage, build.Status.Config.Namespace)
if err != nil {
return nil, err
}
build.Spec.Strategy.SourceStrategy.RuntimeImage = &kapi.ObjectReference{
Kind: "DockerImage",
Name: runtimeImageName,
}
}
if build.Spec.Strategy.SourceStrategy.PullSecret == nil {
// we have 3 different variations:
// 1) builder and runtime images use the same secret => use builder image secret
// 2) builder and runtime images use different secrets => use builder image secret
// 3) builder doesn't need a secret but runtime image requires it => use runtime image secret
// The case when both of the images don't use secret (equals to nil) is covered by the first variant.
pullSecret := g.resolveImageSecret(ctx, builderSecrets, &build.Spec.Strategy.SourceStrategy.From, bc.Namespace)
if pullSecret == nil {
pullSecret = g.resolveImageSecret(ctx, builderSecrets, build.Spec.Strategy.SourceStrategy.RuntimeImage, bc.Namespace)
}
build.Spec.Strategy.SourceStrategy.PullSecret = pullSecret
}
case build.Spec.Strategy.DockerStrategy != nil &&
build.Spec.Strategy.DockerStrategy.From != nil:
if image == "" {
image, err = g.resolveImageStreamReference(ctx, *build.Spec.Strategy.DockerStrategy.From, build.Status.Config.Namespace)
if err != nil {
return nil, err
}
}
build.Spec.Strategy.DockerStrategy.From = &kapi.ObjectReference{
Kind: "DockerImage",
Name: image,
}
if build.Spec.Strategy.DockerStrategy.PullSecret == nil {
build.Spec.Strategy.DockerStrategy.PullSecret = g.resolveImageSecret(ctx, builderSecrets, build.Spec.Strategy.DockerStrategy.From, bc.Namespace)
}
case build.Spec.Strategy.CustomStrategy != nil:
if image == "" {
image, err = g.resolveImageStreamReference(ctx, build.Spec.Strategy.CustomStrategy.From, build.Status.Config.Namespace)
if err != nil {
return nil, err
}
}
build.Spec.Strategy.CustomStrategy.From = kapi.ObjectReference{
Kind: "DockerImage",
Name: image,
}
if build.Spec.Strategy.CustomStrategy.PullSecret == nil {
build.Spec.Strategy.CustomStrategy.PullSecret = g.resolveImageSecret(ctx, builderSecrets, &build.Spec.Strategy.CustomStrategy.From, bc.Namespace)
}
updateCustomImageEnv(build.Spec.Strategy.CustomStrategy, image)
}
return build, nil
}
// resolveImageStreamReference looks up the ImageStream[Tag/Image] and converts it to a
// docker pull spec that can be used in an Image field.
func (g *BuildGenerator) resolveImageStreamReference(ctx kapi.Context, from kapi.ObjectReference, defaultNamespace string) (string, error) {
var namespace string
if len(from.Namespace) != 0 {
namespace = from.Namespace
} else {
namespace = defaultNamespace
}
glog.V(4).Infof("Resolving ImageStreamReference %s of Kind %s in namespace %s", from.Name, from.Kind, namespace)
switch from.Kind {
case "ImageStreamImage":
imageStreamImage, err := g.Client.GetImageStreamImage(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
err = resolveError(from.Kind, namespace, from.Name, err)
glog.V(2).Info(err)
return "", err
}
image := imageStreamImage.Image
glog.V(4).Infof("Resolved ImageStreamReference %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "ImageStreamTag":
imageStreamTag, err := g.Client.GetImageStreamTag(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
err = resolveError(from.Kind, namespace, from.Name, err)
glog.V(2).Info(err)
return "", err
}
image := imageStreamTag.Image
glog.V(4).Infof("Resolved ImageStreamTag %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "DockerImage":
return from.Name, nil
default:
return "", fmt.Errorf("Unknown From Kind %s", from.Kind)
}
}
// resolveImageStreamDockerRepository looks up the ImageStream[Tag/Image] and converts it to a
// the docker repository reference with no tag information
func (g *BuildGenerator) resolveImageStreamDockerRepository(ctx kapi.Context, from kapi.ObjectReference, defaultNamespace string) (string, error) {
namespace := defaultNamespace
if len(from.Namespace) > 0 {
namespace = from.Namespace
}
glog.V(4).Infof("Resolving ImageStreamReference %s of Kind %s in namespace %s", from.Name, from.Kind, namespace)
switch from.Kind {
case "ImageStreamImage":
imageStreamImage, err := g.Client.GetImageStreamImage(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
err = resolveError(from.Kind, namespace, from.Name, err)
glog.V(2).Info(err)
return "", err
}
image := imageStreamImage.Image
glog.V(4).Infof("Resolved ImageStreamReference %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "ImageStreamTag":
name := strings.Split(from.Name, ":")[0]
is, err := g.Client.GetImageStream(kapi.WithNamespace(ctx, namespace), name)
if err != nil {
err = resolveError("ImageStream", namespace, from.Name, err)
glog.V(2).Info(err)
return "", err
}
image, err := imageapi.DockerImageReferenceForStream(is)
if err != nil {
glog.V(2).Infof("Error resolving Docker image reference for %s/%s: %v", namespace, name, err)
return "", err
}
glog.V(4).Infof("Resolved ImageStreamTag %s/%s to repository %s", namespace, from.Name, image)
return image.String(), nil
case "DockerImage":
return from.Name, nil
default:
return "", fmt.Errorf("Unknown From Kind %s", from.Kind)
}
}
// resolveImageSecret looks up the Secrets provided by the Service Account and
// attempt to find a best match for given image.
func (g *BuildGenerator) resolveImageSecret(ctx kapi.Context, secrets []kapi.Secret, imageRef *kapi.ObjectReference, buildNamespace string) *kapi.LocalObjectReference {
if len(secrets) == 0 || imageRef == nil {
return nil
}
emptyKeyring := credentialprovider.BasicDockerKeyring{}
// Get the image pull spec from the image stream reference
imageSpec, err := g.resolveImageStreamDockerRepository(ctx, *imageRef, buildNamespace)
if err != nil {
glog.V(2).Infof("Unable to resolve the image name for %s/%s: %v", buildNamespace, imageRef, err)
return nil
}
for _, secret := range secrets {
keyring, err := credentialprovider.MakeDockerKeyring([]kapi.Secret{secret}, &emptyKeyring)
if err != nil {
glog.V(2).Infof("Unable to make the Docker keyring for %s/%s secret: %v", secret.Name, secret.Namespace, err)
continue
}
if _, found := keyring.Lookup(imageSpec); found {
return &kapi.LocalObjectReference{Name: secret.Name}
}
}
glog.V(4).Infof("No secrets found for pushing or pulling the %s %s/%s", imageRef.Kind, buildNamespace, imageRef.Name)
return nil
}
func resolveError(kind string, namespace string, name string, err error) error {
msg := fmt.Sprintf("Error resolving %s %s in namespace %s: %v", kind, name, namespace, err)
return &errors.StatusError{unversioned.Status{
Status: unversioned.StatusFailure,
Code: errors.StatusUnprocessableEntity,
Reason: unversioned.StatusReasonInvalid,
Message: msg,
Details: &unversioned.StatusDetails{
Kind: kind,
Name: name,
Causes: []unversioned.StatusCause{{
Field: "from",
Message: msg,
}},
},
}}
}
// getNextBuildName returns name of the next build and increments BuildConfig's LastVersion.
func getNextBuildName(buildConfig *buildapi.BuildConfig) string {
buildConfig.Status.LastVersion++
return fmt.Sprintf("%s-%d", buildConfig.Name, buildConfig.Status.LastVersion)
}
// For a custom build strategy, update base image env variable reference with the new image.
// If no env variable reference exists, create a new env variable.
func updateCustomImageEnv(strategy *buildapi.CustomBuildStrategy, newImage string) {
if strategy.Env == nil {
strategy.Env = make([]kapi.EnvVar, 1)
strategy.Env[0] = kapi.EnvVar{Name: buildapi.CustomBuildStrategyBaseImageKey, Value: newImage}
} else {
found := false
for i := range strategy.Env {
glog.V(4).Infof("Checking env variable %s %s", strategy.Env[i].Name, strategy.Env[i].Value)
if strategy.Env[i].Name == buildapi.CustomBuildStrategyBaseImageKey {
found = true
strategy.Env[i].Value = newImage
glog.V(4).Infof("Updated env variable %s to %s", strategy.Env[i].Name, strategy.Env[i].Value)
break
}
}
if !found {
strategy.Env = append(strategy.Env, kapi.EnvVar{Name: buildapi.CustomBuildStrategyBaseImageKey, Value: newImage})
}
}
}
// generateBuildFromBuild creates a new build based on a given Build.
func generateBuildFromBuild(build *buildapi.Build, buildConfig *buildapi.BuildConfig) *buildapi.Build {
obj, _ := kapi.Scheme.Copy(build)
buildCopy := obj.(*buildapi.Build)
newBuild := &buildapi.Build{
Spec: buildCopy.Spec,
ObjectMeta: kapi.ObjectMeta{
Name: getNextBuildNameFromBuild(buildCopy, buildConfig),
Labels: buildCopy.ObjectMeta.Labels,
Annotations: buildCopy.ObjectMeta.Annotations,
},
Status: buildapi.BuildStatus{
Phase: buildapi.BuildPhaseNew,
Config: buildCopy.Status.Config,
},
}
// TODO remove/update this when we support cloning binary builds
newBuild.Spec.Source.Binary = nil
if newBuild.Annotations == nil {
newBuild.Annotations = make(map[string]string)
}
newBuild.Annotations[buildapi.BuildCloneAnnotation] = build.Name
if buildConfig != nil {
newBuild.Annotations[buildapi.BuildNumberAnnotation] = strconv.FormatInt(buildConfig.Status.LastVersion, 10)
} else {
// builds without a buildconfig don't have build numbers.
delete(newBuild.Annotations, buildapi.BuildNumberAnnotation)
}
// if they exist, Jenkins reporting annotations must be removed when cloning.
delete(newBuild.Annotations, buildapi.BuildJenkinsStatusJSONAnnotation)
delete(newBuild.Annotations, buildapi.BuildJenkinsLogURLAnnotation)
delete(newBuild.Annotations, buildapi.BuildJenkinsBuildURIAnnotation)
// remove the BuildPodNameAnnotation for good measure.
delete(newBuild.Annotations, buildapi.BuildPodNameAnnotation)
return newBuild
}
// getNextBuildNameFromBuild returns name of the next build with random uuid added at the end
func getNextBuildNameFromBuild(build *buildapi.Build, buildConfig *buildapi.BuildConfig) string {
var buildName string
if buildConfig != nil {
return getNextBuildName(buildConfig)
}
// for builds created by hand, append a timestamp when cloning/rebuilding them
// because we don't have a sequence number to bump.
buildName = build.Name
// remove the old timestamp if we're cloning a build that is itself a clone.
if matched, _ := regexp.MatchString(`^.+-\d{10}$`, buildName); matched {
nameElems := strings.Split(buildName, "-")
buildName = strings.Join(nameElems[:len(nameElems)-1], "-")
}
suffix := fmt.Sprintf("%v", unversioned.Now().UnixNano())
if len(suffix) > 10 {
suffix = suffix[len(suffix)-10:]
}
return namer.GetName(buildName, suffix, kvalidation.DNS1123SubdomainMaxLength)
}
// getStrategyImageChangeTrigger returns the ImageChangeTrigger that corresponds to the BuildConfig's strategy
func getStrategyImageChangeTrigger(bc *buildapi.BuildConfig) *buildapi.ImageChangeTrigger {
for _, trigger := range bc.Spec.Triggers {
if trigger.Type == buildapi.ImageChangeBuildTriggerType && trigger.ImageChange.From == nil {
return trigger.ImageChange
}
}
return nil
}
// getImageChangeTriggerForRef returns the ImageChangeTrigger that is triggered by a change to
// the provided object reference, if any
func getImageChangeTriggerForRef(bc *buildapi.BuildConfig, ref *kapi.ObjectReference) *buildapi.ImageChangeTrigger {
if ref == nil || ref.Kind != "ImageStreamTag" {
return nil
}
for _, trigger := range bc.Spec.Triggers {
if trigger.Type == buildapi.ImageChangeBuildTriggerType && trigger.ImageChange.From != nil &&
trigger.ImageChange.From.Name == ref.Name && trigger.ImageChange.From.Namespace == ref.Namespace {
return trigger.ImageChange
}
}
return nil
}