forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_controller.go
1387 lines (1239 loc) · 51.8 KB
/
build_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
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package build
import (
"fmt"
"strings"
"sync"
"time"
"github.com/golang/glog"
metrics "github.com/openshift/origin/pkg/build/metrics/prometheus"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apimachinery/pkg/util/wait"
kexternalcoreinformers "k8s.io/client-go/informers/core/v1"
kexternalclientset "k8s.io/client-go/kubernetes"
kexternalcoreclient "k8s.io/client-go/kubernetes/typed/core/v1"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
v1lister "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/kubernetes/pkg/api/legacyscheme"
kapi "k8s.io/kubernetes/pkg/apis/core"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"github.com/openshift/origin/pkg/api/meta"
buildapi "github.com/openshift/origin/pkg/build/apis/build"
"github.com/openshift/origin/pkg/build/apis/build/validation"
buildclient "github.com/openshift/origin/pkg/build/client"
builddefaults "github.com/openshift/origin/pkg/build/controller/build/defaults"
buildoverrides "github.com/openshift/origin/pkg/build/controller/build/overrides"
"github.com/openshift/origin/pkg/build/controller/common"
"github.com/openshift/origin/pkg/build/controller/policy"
"github.com/openshift/origin/pkg/build/controller/strategy"
buildinformer "github.com/openshift/origin/pkg/build/generated/informers/internalversion/build/internalversion"
buildinternalclient "github.com/openshift/origin/pkg/build/generated/internalclientset"
buildlister "github.com/openshift/origin/pkg/build/generated/listers/build/internalversion"
buildgenerator "github.com/openshift/origin/pkg/build/generator"
buildutil "github.com/openshift/origin/pkg/build/util"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
imageinformers "github.com/openshift/origin/pkg/image/generated/informers/internalversion/image/internalversion"
imagelister "github.com/openshift/origin/pkg/image/generated/listers/image/internalversion"
)
const (
maxRetries = 15
// maxExcerptLength is the maximum length of the LogSnippet on a build.
maxExcerptLength = 5
)
// resourceTriggerQueue tracks a set of resource keys to trigger when another object changes.
type resourceTriggerQueue struct {
lock sync.Mutex
queue map[string][]string
}
// newResourceTriggerQueue creates a resourceTriggerQueue.
func newResourceTriggerQueue() *resourceTriggerQueue {
return &resourceTriggerQueue{
queue: make(map[string][]string),
}
}
// Add ensures resource will be returned the next time any of on are invoked
// on Pop().
func (q *resourceTriggerQueue) Add(resource string, on []string) {
q.lock.Lock()
defer q.lock.Unlock()
for _, key := range on {
q.queue[key] = append(q.queue[key], resource)
}
}
func (q *resourceTriggerQueue) Remove(resource string, on []string) {
q.lock.Lock()
defer q.lock.Unlock()
for _, key := range on {
resources := q.queue[key]
newResources := make([]string, 0, len(resources))
for _, existing := range resources {
if existing == resource {
continue
}
newResources = append(newResources, existing)
}
q.queue[key] = newResources
}
}
func (q *resourceTriggerQueue) Pop(key string) []string {
q.lock.Lock()
defer q.lock.Unlock()
resources := q.queue[key]
delete(q.queue, key)
return resources
}
// BuildController watches builds and synchronizes them with their
// corresponding build pods. It is also responsible for resolving image
// stream references in the Build to docker images prior to invoking the pod.
// The build controller late binds image stream references so that users can
// create a build config before they create the image stream (or before
// an image is pushed to a tag) which allows actions to converge. It also
// allows multiple Build objects to directly reference images created by another
// Build, acting as a simple dependency graph for a logical multi-image build
// that reuses many individual Builds.
//
// Like other controllers that do "on behalf of" image resolution, the controller
// resolves the reference which allows users to see what image ID corresponds to a tag
// simply by requesting resolution. This is consistent with other image policy in the
// system (image tag references in deployments, triggers, and image policy). The only
// leaked image information is the ID which is considered acceptable. Secrets are also
// resolved, allowing a user in the same namespace to in theory infer the presence of
// a secret or make it usable by a build - but this is identical to our existing model
// where a service account determines access to secrets used in pods.
type BuildController struct {
buildPatcher buildclient.BuildPatcher
buildLister buildlister.BuildLister
buildConfigGetter buildlister.BuildConfigLister
buildDeleter buildclient.BuildDeleter
podClient kexternalcoreclient.PodsGetter
kubeClient kclientset.Interface
buildQueue workqueue.RateLimitingInterface
imageStreamQueue *resourceTriggerQueue
buildConfigQueue workqueue.RateLimitingInterface
buildStore buildlister.BuildLister
secretStore v1lister.SecretLister
podStore v1lister.PodLister
imageStreamStore imagelister.ImageStreamLister
podInformer cache.SharedIndexInformer
buildInformer cache.SharedIndexInformer
buildStoreSynced func() bool
podStoreSynced func() bool
secretStoreSynced func() bool
imageStreamStoreSynced func() bool
runPolicies []policy.RunPolicy
createStrategy buildPodCreationStrategy
buildDefaults builddefaults.BuildDefaults
buildOverrides buildoverrides.BuildOverrides
recorder record.EventRecorder
}
// BuildControllerParams is the set of parameters needed to
// create a new BuildController
type BuildControllerParams struct {
BuildInformer buildinformer.BuildInformer
BuildConfigInformer buildinformer.BuildConfigInformer
ImageStreamInformer imageinformers.ImageStreamInformer
PodInformer kexternalcoreinformers.PodInformer
SecretInformer kexternalcoreinformers.SecretInformer
KubeClientInternal kclientset.Interface
KubeClientExternal kexternalclientset.Interface
BuildClientInternal buildinternalclient.Interface
DockerBuildStrategy *strategy.DockerBuildStrategy
SourceBuildStrategy *strategy.SourceBuildStrategy
CustomBuildStrategy *strategy.CustomBuildStrategy
BuildDefaults builddefaults.BuildDefaults
BuildOverrides buildoverrides.BuildOverrides
}
// NewBuildController creates a new BuildController.
func NewBuildController(params *BuildControllerParams) *BuildController {
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(params.KubeClientExternal.Core().RESTClient()).Events("")})
buildClient := buildclient.NewClientBuildClient(params.BuildClientInternal)
buildLister := params.BuildInformer.Lister()
buildConfigGetter := params.BuildConfigInformer.Lister()
c := &BuildController{
buildPatcher: buildClient,
buildLister: buildLister,
buildConfigGetter: buildConfigGetter,
buildDeleter: buildClient,
secretStore: params.SecretInformer.Lister(),
podClient: params.KubeClientExternal.Core(),
kubeClient: params.KubeClientInternal,
podInformer: params.PodInformer.Informer(),
podStore: params.PodInformer.Lister(),
buildInformer: params.BuildInformer.Informer(),
buildStore: params.BuildInformer.Lister(),
imageStreamStore: params.ImageStreamInformer.Lister(),
createStrategy: &typeBasedFactoryStrategy{
dockerBuildStrategy: params.DockerBuildStrategy,
sourceBuildStrategy: params.SourceBuildStrategy,
customBuildStrategy: params.CustomBuildStrategy,
},
buildDefaults: params.BuildDefaults,
buildOverrides: params.BuildOverrides,
buildQueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
imageStreamQueue: newResourceTriggerQueue(),
buildConfigQueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
recorder: eventBroadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: "build-controller"}),
runPolicies: policy.GetAllRunPolicies(buildLister, buildClient),
}
c.podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
UpdateFunc: c.podUpdated,
DeleteFunc: c.podDeleted,
})
c.buildInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.buildAdded,
UpdateFunc: c.buildUpdated,
DeleteFunc: c.buildDeleted,
})
params.ImageStreamInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.imageStreamAdded,
UpdateFunc: c.imageStreamUpdated,
})
c.buildStoreSynced = c.buildInformer.HasSynced
c.podStoreSynced = c.podInformer.HasSynced
c.secretStoreSynced = params.SecretInformer.Informer().HasSynced
c.imageStreamStoreSynced = params.ImageStreamInformer.Informer().HasSynced
return c
}
// Run begins watching and syncing.
func (bc *BuildController) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer bc.buildQueue.ShutDown()
defer bc.buildConfigQueue.ShutDown()
// Wait for the controller stores to sync before starting any work in this controller.
if !cache.WaitForCacheSync(stopCh, bc.buildStoreSynced, bc.podStoreSynced, bc.secretStoreSynced, bc.imageStreamStoreSynced) {
utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
return
}
glog.Infof("Starting build controller")
for i := 0; i < workers; i++ {
go wait.Until(bc.buildWorker, time.Second, stopCh)
}
for i := 0; i < workers; i++ {
go wait.Until(bc.buildConfigWorker, time.Second, stopCh)
}
metrics.IntializeMetricsCollector(bc.buildLister)
<-stopCh
glog.Infof("Shutting down build controller")
}
func (bc *BuildController) buildWorker() {
for {
if quit := bc.buildWork(); quit {
return
}
}
}
// buildWork gets the next build from the buildQueue and invokes handleBuild on it
func (bc *BuildController) buildWork() bool {
key, quit := bc.buildQueue.Get()
if quit {
return true
}
defer bc.buildQueue.Done(key)
build, err := bc.getBuildByKey(key.(string))
if err != nil {
bc.handleBuildError(err, key)
return false
}
if build == nil {
return false
}
err = bc.handleBuild(build)
bc.handleBuildError(err, key)
return false
}
func (bc *BuildController) buildConfigWorker() {
for {
if quit := bc.buildConfigWork(); quit {
return
}
}
}
// buildConfigWork gets the next build config from the buildConfigQueue and invokes handleBuildConfig on it
func (bc *BuildController) buildConfigWork() bool {
key, quit := bc.buildConfigQueue.Get()
if quit {
return true
}
defer bc.buildConfigQueue.Done(key)
namespace, name, err := parseBuildConfigKey(key.(string))
if err != nil {
utilruntime.HandleError(err)
return false
}
err = bc.handleBuildConfig(namespace, name)
bc.handleBuildConfigError(err, key)
return false
}
func parseBuildConfigKey(key string) (string, string, error) {
parts := strings.SplitN(key, "/", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid build config key: %s", key)
}
return parts[0], parts[1], nil
}
// handleBuild retrieves the build's corresponding pod and calls the appropriate
// handle function based on the build's current state. Each handler returns a buildUpdate
// object that includes any updates that need to be made on the build.
func (bc *BuildController) handleBuild(build *buildapi.Build) error {
if shouldIgnore(build) {
return nil
}
glog.V(4).Infof("Handling build %s", buildDesc(build))
pod, podErr := bc.podStore.Pods(build.Namespace).Get(buildapi.GetBuildPodName(build))
// Technically the only error that is returned from retrieving the pod is the
// NotFound error so this check should not be needed, but leaving here in case
// that changes in the future.
if podErr != nil && !errors.IsNotFound(podErr) {
return podErr
}
var update *buildUpdate
var err, updateErr error
switch {
case shouldCancel(build):
update, err = bc.cancelBuild(build)
case build.Status.Phase == buildapi.BuildPhaseNew:
update, err = bc.handleNewBuild(build, pod)
case build.Status.Phase == buildapi.BuildPhasePending,
build.Status.Phase == buildapi.BuildPhaseRunning:
update, err = bc.handleActiveBuild(build, pod)
case buildutil.IsBuildComplete(build):
update, err = bc.handleCompletedBuild(build, pod)
}
if update != nil && !update.isEmpty() {
updateErr = bc.updateBuild(build, update, pod)
}
if err != nil {
return err
}
if updateErr != nil {
return updateErr
}
return nil
}
// shouldIgnore returns true if a build should be ignored by the controller.
// These include pipeline builds as well as builds that are in a terminal state.
// However if the build is either complete or failed and its completion timestamp
// has not been set, then it returns false so that the build's completion timestamp
// gets updated.
func shouldIgnore(build *buildapi.Build) bool {
// If pipeline build, do nothing.
// These builds are processed/updated/etc by the jenkins sync plugin
if build.Spec.Strategy.JenkinsPipelineStrategy != nil {
glog.V(4).Infof("Ignoring build %s with jenkins pipeline strategy", buildDesc(build))
return true
}
// If a build is in a terminal state, ignore it; unless it is in a succeeded or failed
// state and its completion time or logsnippet is not set, then we should at least attempt to set its
// completion time and logsnippet if possible because the build pod may have put the build in
// this state and it would have not set the completion timestamp or logsnippet data.
if buildutil.IsBuildComplete(build) {
switch build.Status.Phase {
case buildapi.BuildPhaseComplete:
if build.Status.CompletionTimestamp == nil {
return false
}
case buildapi.BuildPhaseFailed:
if build.Status.CompletionTimestamp == nil || len(build.Status.LogSnippet) == 0 {
return false
}
}
glog.V(4).Infof("Ignoring build %s in completed state", buildDesc(build))
return true
}
return false
}
// shouldCancel returns true if a build is active and its cancellation flag is set
func shouldCancel(build *buildapi.Build) bool {
return !buildutil.IsBuildComplete(build) && build.Status.Cancelled
}
// cancelBuild deletes a build pod and returns an update to mark the build as cancelled
func (bc *BuildController) cancelBuild(build *buildapi.Build) (*buildUpdate, error) {
glog.V(4).Infof("Cancelling build %s", buildDesc(build))
podName := buildapi.GetBuildPodName(build)
err := bc.podClient.Pods(build.Namespace).Delete(podName, &metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return nil, fmt.Errorf("could not delete build pod %s/%s to cancel build %s: %v", build.Namespace, podName, buildDesc(build), err)
}
return transitionToPhase(buildapi.BuildPhaseCancelled, buildapi.StatusReasonCancelledBuild, buildapi.StatusMessageCancelledBuild), nil
}
// handleNewBuild will check whether policy allows running the new build and if so, creates a pod
// for the build and returns an update to move it to the Pending phase
func (bc *BuildController) handleNewBuild(build *buildapi.Build, pod *v1.Pod) (*buildUpdate, error) {
// If a pod was found, and it was created after the build was created, it
// means that the build is active and its status should be updated
if pod != nil {
//TODO: Use a better way to determine whether the pod corresponds to the build (maybe using the owner field)
if !pod.CreationTimestamp.Before(&build.CreationTimestamp) {
return bc.handleActiveBuild(build, pod)
}
// If a pod was created before the current build, move the build to error
return transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonBuildPodExists, buildapi.StatusMessageBuildPodExists), nil
}
runPolicy := policy.ForBuild(build, bc.runPolicies)
if runPolicy == nil {
return nil, fmt.Errorf("unable to determine build policy for %s", buildDesc(build))
}
// The runPolicy decides whether to execute this build or not.
if run, err := runPolicy.IsRunnable(build); err != nil || !run {
return nil, err
}
return bc.createBuildPod(build)
}
// createPodSpec creates a pod spec for the given build, with all references already resolved.
func (bc *BuildController) createPodSpec(build *buildapi.Build) (*v1.Pod, error) {
if build.Spec.Output.To != nil {
build.Status.OutputDockerImageReference = build.Spec.Output.To.Name
}
// ensure the build object the pod sees starts with a clean set of reasons/messages,
// rather than inheriting the potential "invalidoutputreference" message from the current
// build state. Otherwise when the pod attempts to update the build (e.g. with the git
// revision information), it will re-assert the stale reason/message.
build.Status.Reason = ""
build.Status.Message = ""
// Invoke the strategy to create a build pod.
podSpec, err := bc.createStrategy.CreateBuildPod(build)
if err != nil {
if strategy.IsFatal(err) {
return nil, &strategy.FatalError{Reason: fmt.Sprintf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)}
}
return nil, fmt.Errorf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)
}
if err := bc.buildDefaults.ApplyDefaults(podSpec); err != nil {
return nil, fmt.Errorf("failed to apply build defaults for build %s/%s: %v", build.Namespace, build.Name, err)
}
if err := bc.buildOverrides.ApplyOverrides(podSpec); err != nil {
return nil, fmt.Errorf("failed to apply build overrides for build %s/%s: %v", build.Namespace, build.Name, err)
}
// Handle resolving ValueFrom references in build environment variables
if err := common.ResolveValueFrom(podSpec, bc.kubeClient); err != nil {
return nil, err
}
return podSpec, nil
}
// resolveImageSecretAsReference returns a LocalObjectReference to a secret that should
// be able to push/pull at the image location.
// Note that we are using controller level permissions to resolve the secret,
// meaning users could theoretically define a build that references an imagestream they cannot
// see, and 1) get the docker image reference of that imagestream and 2) a reference to a secret
// associated with a service account that can push to that location. However they still cannot view the secret,
// and ability to use a service account implies access to its secrets, so this is considered safe.
// Furthermore it's necessary to enable triggered builds since a triggered build is not "requested"
// by a particular user, so there are no user permissions to validate against in that case.
func (bc *BuildController) resolveImageSecretAsReference(build *buildapi.Build, imagename string) (*kapi.LocalObjectReference, error) {
serviceAccount := build.Spec.ServiceAccount
if len(serviceAccount) == 0 {
serviceAccount = buildutil.BuilderServiceAccountName
}
builderSecrets, err := buildgenerator.FetchServiceAccountSecrets(bc.kubeClient.Core(), bc.kubeClient.Core(), build.Namespace, serviceAccount)
if err != nil {
return nil, fmt.Errorf("Error getting push/pull secrets for service account %s/%s: %v", build.Namespace, serviceAccount, err)
}
pushSecret := buildutil.FindDockerSecretAsReference(builderSecrets, imagename)
if pushSecret == nil {
glog.V(4).Infof("No secrets found for pushing or pulling image named %s for build %s/%s", imagename, build.Namespace, build.Name)
}
return pushSecret, nil
}
// resourceName creates a string that can be used to uniquely key the provided resource.
func resourceName(namespace, name string) string {
return namespace + "/" + name
}
var (
// errInvalidImageReferences is a marker error for when a build contains invalid object
// reference names.
errInvalidImageReferences = fmt.Errorf("one or more image references were invalid")
// errNoIntegratedRegistry is a marker error for when the output image points to a registry
// that cannot be resolved.
errNoIntegratedRegistry = fmt.Errorf("the integrated registry is not configured")
)
// unresolvedImageStreamReferences finds all image stream references in the provided
// mutator that need to be resolved prior to the resource being accepted and returns
// them as an array of "namespace/name" strings. If any references are invalid, an error
// is returned.
func unresolvedImageStreamReferences(m meta.ImageReferenceMutator, defaultNamespace string) ([]string, error) {
var streams []string
fn := func(ref *kapi.ObjectReference) error {
switch ref.Kind {
case "ImageStreamImage":
namespace := ref.Namespace
if len(namespace) == 0 {
namespace = defaultNamespace
}
name, _, ok := imageapi.SplitImageStreamImage(ref.Name)
if !ok {
return errInvalidImageReferences
}
streams = append(streams, resourceName(namespace, name))
case "ImageStreamTag":
namespace := ref.Namespace
if len(namespace) == 0 {
namespace = defaultNamespace
}
name, _, ok := imageapi.SplitImageStreamTag(ref.Name)
if !ok {
return errInvalidImageReferences
}
streams = append(streams, resourceName(namespace, name))
}
return nil
}
errs := m.Mutate(fn)
if len(errs) > 0 {
return nil, errInvalidImageReferences
}
return streams, nil
}
// resolveImageStreamLocation transforms the provided reference into a string pointing to the integrated registry,
// or returns an error.
func resolveImageStreamLocation(ref *kapi.ObjectReference, lister imagelister.ImageStreamLister, defaultNamespace string) (string, error) {
namespace := ref.Namespace
if len(namespace) == 0 {
namespace = defaultNamespace
}
var (
name string
tag string
)
switch ref.Kind {
case "ImageStreamImage":
var ok bool
name, _, ok = imageapi.SplitImageStreamImage(ref.Name)
if !ok {
return "", errInvalidImageReferences
}
// for backwards compatibility, image stream images will be resolved to the :latest tag
tag = imageapi.DefaultImageTag
case "ImageStreamTag":
var ok bool
name, tag, ok = imageapi.SplitImageStreamTag(ref.Name)
if !ok {
return "", errInvalidImageReferences
}
case "ImageStream":
name = ref.Name
}
stream, err := lister.ImageStreams(namespace).Get(name)
if err != nil {
if errors.IsNotFound(err) {
return "", err
}
return "", fmt.Errorf("the referenced output image stream %s/%s could not be found: %v", namespace, name, err)
}
// TODO: this check will not work if the admin installs the registry without restarting the controller, because
// only a relist from the API server will correct the empty value here (no watch events are sent)
if len(stream.Status.DockerImageRepository) == 0 {
return "", errNoIntegratedRegistry
}
repo, err := imageapi.ParseDockerImageReference(stream.Status.DockerImageRepository)
if err != nil {
return "", fmt.Errorf("the referenced output image stream does not represent a valid reference name: %v", err)
}
repo.ID = ""
repo.Tag = tag
return repo.Exact(), nil
}
func resolveImageStreamImage(ref *kapi.ObjectReference, lister imagelister.ImageStreamLister, defaultNamespace string) (*kapi.ObjectReference, error) {
namespace := ref.Namespace
if len(namespace) == 0 {
namespace = defaultNamespace
}
name, imageID, ok := imageapi.SplitImageStreamImage(ref.Name)
if !ok {
return nil, errInvalidImageReferences
}
stream, err := lister.ImageStreams(namespace).Get(name)
if err != nil {
if errors.IsNotFound(err) {
return nil, err
}
return nil, fmt.Errorf("the referenced image stream %s/%s could not be found: %v", namespace, name, err)
}
event, err := imageapi.ResolveImageID(stream, imageID)
if err != nil {
return nil, err
}
if len(event.DockerImageReference) == 0 {
return nil, fmt.Errorf("the referenced image stream image %s/%s does not have a pull spec", namespace, ref.Name)
}
return &kapi.ObjectReference{Kind: "DockerImage", Name: event.DockerImageReference}, nil
}
func resolveImageStreamTag(ref *kapi.ObjectReference, lister imagelister.ImageStreamLister, defaultNamespace string) (*kapi.ObjectReference, error) {
namespace := ref.Namespace
if len(namespace) == 0 {
namespace = defaultNamespace
}
name, tag, ok := imageapi.SplitImageStreamTag(ref.Name)
if !ok {
return nil, errInvalidImageReferences
}
stream, err := lister.ImageStreams(namespace).Get(name)
if err != nil {
if errors.IsNotFound(err) {
return nil, err
}
return nil, fmt.Errorf("the referenced image stream %s/%s could not be found: %v", namespace, name, err)
}
if newRef, ok := imageapi.ResolveLatestTaggedImage(stream, tag); ok {
return &kapi.ObjectReference{Kind: "DockerImage", Name: newRef}, nil
}
return nil, fmt.Errorf("the referenced image stream tag %s/%s does not exist", namespace, ref.Name)
}
// resolveOutputDockerImageReference updates the output spec to a docker image reference.
func (bc *BuildController) resolveOutputDockerImageReference(build *buildapi.Build) error {
ref := build.Spec.Output.To
if ref == nil || ref.Name == "" {
return nil
}
switch ref.Kind {
case "ImageStream", "ImageStreamTag":
newRef, err := resolveImageStreamLocation(ref, bc.imageStreamStore, build.Namespace)
if err != nil {
return err
}
*ref = kapi.ObjectReference{Kind: "DockerImage", Name: newRef}
return nil
default:
return nil
}
}
// resolveImageReferences resolves references to Docker images computed from the build.Spec. It will update
// the output spec as well if it has not already been updated.
func (bc *BuildController) resolveImageReferences(build *buildapi.Build, update *buildUpdate) error {
m := meta.NewBuildMutator(build)
// get a list of all unresolved references to add to the cache
streams, err := unresolvedImageStreamReferences(m, build.Namespace)
if err != nil {
return err
}
if len(streams) == 0 {
glog.V(5).Infof("Build %s contains no unresolved image references", build.Name)
return nil
}
// build references are level driven, so we queue here to ensure we get notified if
// we are racing against updates in the image stream store
buildKey := resourceName(build.Namespace, build.Name)
bc.imageStreamQueue.Add(buildKey, streams)
// resolve the output image reference
if err := bc.resolveOutputDockerImageReference(build); err != nil {
// If we cannot resolve the output reference, the output image stream
// may not yet exist. The build should remain in the new state and show the
// reason that it is still in the new state.
update.setReason(buildapi.StatusReasonInvalidOutputReference)
update.setMessage(buildapi.StatusMessageInvalidOutputRef)
if err == errNoIntegratedRegistry {
e := fmt.Errorf("an image stream cannot be used as build output because the integrated Docker registry is not configured")
bc.recorder.Eventf(build, kapi.EventTypeWarning, "InvalidOutput", "Error starting build: %v", e)
}
return err
}
// resolve the remaining references
errs := m.Mutate(func(ref *kapi.ObjectReference) error {
switch ref.Kind {
case "ImageStreamImage":
newRef, err := resolveImageStreamImage(ref, bc.imageStreamStore, build.Namespace)
if err != nil {
return err
}
*ref = *newRef
case "ImageStreamTag":
newRef, err := resolveImageStreamTag(ref, bc.imageStreamStore, build.Namespace)
if err != nil {
return err
}
*ref = *newRef
}
return nil
})
if len(errs) > 0 {
update.setReason(buildapi.StatusReasonInvalidImageReference)
update.setMessage(buildapi.StatusMessageInvalidImageRef)
return errs.ToAggregate()
}
// we have resolved all images, and will not need any further notifications
bc.imageStreamQueue.Remove(buildKey, streams)
return nil
}
// createBuildPod creates a new pod to run a build
func (bc *BuildController) createBuildPod(build *buildapi.Build) (*buildUpdate, error) {
update := &buildUpdate{}
// image reference resolution requires a copy of the build
var err error
// TODO: Rename this to buildCopy
build = build.DeepCopy()
// Resolve all Docker image references to valid values.
if err := bc.resolveImageReferences(build, update); err != nil {
// if we're waiting for an image stream to exist, we will get an update via the
// trigger, and thus don't need to be requeued.
if hasError(err, errors.IsNotFound, field.NewErrorTypeMatcher(field.ErrorTypeNotFound)) {
return update, nil
}
return update, err
}
// Set the pushSecret that will be needed by the build to push the image to the registry
// at the end of the build.
pushSecret := build.Spec.Output.PushSecret
// Only look up a push secret if the user hasn't explicitly provided one.
if build.Spec.Output.PushSecret == nil && build.Spec.Output.To != nil && len(build.Spec.Output.To.Name) > 0 {
var err error
pushSecret, err = bc.resolveImageSecretAsReference(build, build.Spec.Output.To.Name)
if err != nil {
update.setReason(buildapi.StatusReasonCannotRetrieveServiceAccount)
update.setMessage(buildapi.StatusMessageCannotRetrieveServiceAccount)
return update, err
}
}
build.Spec.Output.PushSecret = pushSecret
// Set the pullSecret that will be needed by the build to pull the base/builder image.
var pullSecret *kapi.LocalObjectReference
var imageName string
switch {
case build.Spec.Strategy.SourceStrategy != nil:
pullSecret = build.Spec.Strategy.SourceStrategy.PullSecret
imageName = build.Spec.Strategy.SourceStrategy.From.Name
case build.Spec.Strategy.DockerStrategy != nil:
pullSecret = build.Spec.Strategy.DockerStrategy.PullSecret
if build.Spec.Strategy.DockerStrategy.From != nil {
imageName = build.Spec.Strategy.DockerStrategy.From.Name
}
case build.Spec.Strategy.CustomStrategy != nil:
pullSecret = build.Spec.Strategy.CustomStrategy.PullSecret
imageName = build.Spec.Strategy.CustomStrategy.From.Name
}
// Only look up a pull secret if the user hasn't explicitly provided one and
// we have a base/builder image (Docker builds may not have one).
if pullSecret == nil && len(imageName) != 0 {
var err error
pullSecret, err = bc.resolveImageSecretAsReference(build, imageName)
if err != nil {
update.setReason(buildapi.StatusReasonCannotRetrieveServiceAccount)
update.setMessage(buildapi.StatusMessageCannotRetrieveServiceAccount)
return update, err
}
if pullSecret != nil {
switch {
case build.Spec.Strategy.SourceStrategy != nil:
build.Spec.Strategy.SourceStrategy.PullSecret = pullSecret
case build.Spec.Strategy.DockerStrategy != nil:
build.Spec.Strategy.DockerStrategy.PullSecret = pullSecret
case build.Spec.Strategy.CustomStrategy != nil:
build.Spec.Strategy.CustomStrategy.PullSecret = pullSecret
}
}
}
// look up the secrets needed to pull any source input images.
for i, s := range build.Spec.Source.Images {
if s.PullSecret != nil {
continue
}
imageInputPullSecret, err := bc.resolveImageSecretAsReference(build, s.From.Name)
if err != nil {
update.setReason(buildapi.StatusReasonCannotRetrieveServiceAccount)
update.setMessage(buildapi.StatusMessageCannotRetrieveServiceAccount)
return update, err
}
build.Spec.Source.Images[i].PullSecret = imageInputPullSecret
}
if build.Spec.Strategy.CustomStrategy != nil {
buildgenerator.UpdateCustomImageEnv(build.Spec.Strategy.CustomStrategy, build.Spec.Strategy.CustomStrategy.From.Name)
}
// Create the build pod spec
buildPod, err := bc.createPodSpec(build)
if err != nil {
switch err.(type) {
case common.ErrEnvVarResolver:
update = transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonUnresolvableEnvironmentVariable, fmt.Sprintf("%v, %v", buildapi.StatusMessageUnresolvableEnvironmentVariable, err.Error()))
default:
update.setReason(buildapi.StatusReasonCannotCreateBuildPodSpec)
update.setMessage(buildapi.StatusMessageCannotCreateBuildPodSpec)
}
// If an error occurred when creating the pod spec, it likely means
// that the build is something we don't understand. For example, it could
// have a strategy that we don't recognize. It will remain in New state
// and be updated with the reason that it is still in New
// The error will be logged, but will not be returned to the caller
// to be retried. The reason is that there's really no external factor
// that could cause the pod creation to fail; therefore no reason
// to immediately retry processing the build.
//
// A scenario where this would happen is that we've introduced a
// new build strategy in the master, but the old version of the controller
// is still running. We don't want the old controller to move the
// build to the error phase and we don't want it to keep actively retrying.
utilruntime.HandleError(err)
return update, nil
}
glog.V(4).Infof("Pod %s/%s for build %s is about to be created", build.Namespace, buildPod.Name, buildDesc(build))
if _, err := bc.podClient.Pods(build.Namespace).Create(buildPod); err != nil {
if errors.IsAlreadyExists(err) {
bc.recorder.Eventf(build, kapi.EventTypeWarning, "FailedCreate", "Pod already exists: %s/%s", buildPod.Namespace, buildPod.Name)
glog.V(4).Infof("Build pod %s/%s for build %s already exists", build.Namespace, buildPod.Name, buildDesc(build))
// If the existing pod was created before this build, switch to the Error state.
existingPod, err := bc.podClient.Pods(build.Namespace).Get(buildPod.Name, metav1.GetOptions{})
if err == nil && existingPod.CreationTimestamp.Before(&build.CreationTimestamp) {
update = transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonBuildPodExists, buildapi.StatusMessageBuildPodExists)
return update, nil
}
return nil, nil
}
// Log an event if the pod is not created (most likely due to quota denial).
bc.recorder.Eventf(build, kapi.EventTypeWarning, "FailedCreate", "Error creating: %v", err)
update.setReason(buildapi.StatusReasonCannotCreateBuildPod)
update.setMessage(buildapi.StatusMessageCannotCreateBuildPod)
return update, fmt.Errorf("failed to create build pod: %v", err)
}
glog.V(4).Infof("Created pod %s/%s for build %s", build.Namespace, buildPod.Name, buildDesc(build))
update = transitionToPhase(buildapi.BuildPhasePending, "", "")
if pushSecret != nil {
update.setPushSecret(*pushSecret)
}
update.setPodNameAnnotation(buildPod.Name)
if build.Spec.Output.To != nil {
update.setOutputRef(build.Spec.Output.To.Name)
}
return update, nil
}
// handleActiveBuild handles a build in either pending or running state
func (bc *BuildController) handleActiveBuild(build *buildapi.Build, pod *v1.Pod) (*buildUpdate, error) {
if pod == nil {
pod = bc.findMissingPod(build)
if pod == nil {
glog.V(4).Infof("Failed to find the build pod for build %s. Moving it to Error state", buildDesc(build))
return transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonBuildPodDeleted, buildapi.StatusMessageBuildPodDeleted), nil
}
}
podPhase := pod.Status.Phase
var update *buildUpdate
// Pods don't report running until initcontainers are done, but from a build's perspective
// the pod is running as soon as the first init container has run.
if build.Status.Phase == buildapi.BuildPhasePending || build.Status.Phase == buildapi.BuildPhaseNew {
for _, initContainer := range pod.Status.InitContainerStatuses {
if initContainer.Name == strategy.GitCloneContainer && initContainer.State.Running != nil {
podPhase = v1.PodRunning
}
}
}
switch podPhase {
case v1.PodPending:
if build.Status.Phase != buildapi.BuildPhasePending {
update = transitionToPhase(buildapi.BuildPhasePending, "", "")
}
if secret := build.Spec.Output.PushSecret; secret != nil && build.Status.Reason != buildapi.StatusReasonMissingPushSecret {
if _, err := bc.secretStore.Secrets(build.Namespace).Get(secret.Name); err != nil && errors.IsNotFound(err) {
glog.V(4).Infof("Setting reason for pending build to %q due to missing secret for %s", build.Status.Reason, buildDesc(build))
update = transitionToPhase(buildapi.BuildPhasePending, buildapi.StatusReasonMissingPushSecret, buildapi.StatusMessageMissingPushSecret)
}
}
case v1.PodRunning:
if build.Status.Phase != buildapi.BuildPhaseRunning {
update = transitionToPhase(buildapi.BuildPhaseRunning, "", "")
if pod.Status.StartTime != nil {
update.setStartTime(*pod.Status.StartTime)
}
}
case v1.PodSucceeded:
if build.Status.Phase != buildapi.BuildPhaseComplete {
update = transitionToPhase(buildapi.BuildPhaseComplete, "", "")
}
if len(pod.Status.ContainerStatuses) == 0 {
// no containers in the pod means something went terribly wrong, so the build
// should be set to an error state
glog.V(2).Infof("Setting build %s to error state because its pod has no containers", buildDesc(build))
update = transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonNoBuildContainerStatus, buildapi.StatusMessageNoBuildContainerStatus)
} else {
for _, info := range pod.Status.ContainerStatuses {
if info.State.Terminated != nil && info.State.Terminated.ExitCode != 0 {
glog.V(2).Infof("Setting build %s to error state because a container in its pod has non-zero exit code", buildDesc(build))
update = transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonFailedContainer, buildapi.StatusMessageFailedContainer)
break
}
}
}
case v1.PodFailed:
if build.Status.Phase != buildapi.BuildPhaseFailed {
// If a DeletionTimestamp has been set, it means that the pod will
// soon be deleted. The build should be transitioned to the Error phase.
if pod.DeletionTimestamp != nil {
update = transitionToPhase(buildapi.BuildPhaseError, buildapi.StatusReasonBuildPodDeleted, buildapi.StatusMessageBuildPodDeleted)
} else {
update = transitionToPhase(buildapi.BuildPhaseFailed, buildapi.StatusReasonGenericBuildFailed, buildapi.StatusMessageGenericBuildFailed)
}
}
}
return update, nil
}
// handleCompletedBuild will only be called on builds that are already in a terminal phase. It is used to setup the
// completion timestamp and failure logsnippet as needed.
func (bc *BuildController) handleCompletedBuild(build *buildapi.Build, pod *v1.Pod) (*buildUpdate, error) {
update := &buildUpdate{}
setBuildCompletionData(build, pod, update)
return update, nil
}
// updateBuild is the single place where any update to a build is done in the build controller.
// It will check that the update is valid, peform any necessary processing such as calling HandleBuildCompletion,
// and apply the buildUpdate object as a patch.
func (bc *BuildController) updateBuild(build *buildapi.Build, update *buildUpdate, pod *v1.Pod) error {
stateTransition := false
// Check whether we are transitioning to a different build phase
if update.phase != nil && (*update.phase) != build.Status.Phase {
stateTransition = true
} else if build.Status.Phase == buildapi.BuildPhaseFailed && update.completionTime != nil {
// Treat a failed->failed update as a state transition when the completionTime is getting
// updated. This will cause an event to be emitted and completion processing to trigger.
// We get into this state when the pod updates the phase through the build/details subresource.
// The phase, reason, and message are set, but no event has been emitted about the failure,
// and the policy has not been given a chance to start the next build if one is waiting to
// start.
update.setPhase(buildapi.BuildPhaseFailed)
stateTransition = true
}