This repository has been archived by the owner on Jul 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
factory.go
513 lines (452 loc) · 18.1 KB
/
factory.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
package factory
import (
"fmt"
"time"
"github.com/golang/glog"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
kerrors "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
kclient "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client/cache"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client/record"
"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
kutil "github.com/GoogleCloudPlatform/kubernetes/pkg/util"
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
buildapi "github.com/openshift/origin/pkg/build/api"
buildclient "github.com/openshift/origin/pkg/build/client"
buildcontroller "github.com/openshift/origin/pkg/build/controller"
strategy "github.com/openshift/origin/pkg/build/controller/strategy"
buildutil "github.com/openshift/origin/pkg/build/util"
osclient "github.com/openshift/origin/pkg/client"
controller "github.com/openshift/origin/pkg/controller"
imageapi "github.com/openshift/origin/pkg/image/api"
)
const maxRetries = 60
// limitedLogAndRetry stops retrying after maxTimeout, failing the build.
func limitedLogAndRetry(buildupdater buildclient.BuildUpdater, maxTimeout time.Duration) controller.RetryFunc {
return func(obj interface{}, err error, retries controller.Retry) bool {
build := obj.(*buildapi.Build)
if time.Since(retries.StartTimestamp.Time) < maxTimeout {
glog.V(4).Infof("Retrying Build %s/%s with error: %v", build.Namespace, build.Name, err)
return true
}
build.Status.Phase = buildapi.BuildPhaseFailed
build.Status.Message = err.Error()
now := kutil.Now()
build.Status.CompletionTimestamp = &now
glog.V(3).Infof("Giving up retrying Build %s/%s: %v", build.Namespace, build.Name, err)
kutil.HandleError(err)
if err := buildupdater.Update(build.Namespace, build); err != nil {
// retry update, but only on error other than NotFound
return !kerrors.IsNotFound(err)
}
return false
}
}
// BuildControllerFactory constructs BuildController objects
type BuildControllerFactory struct {
OSClient osclient.Interface
KubeClient kclient.Interface
BuildUpdater buildclient.BuildUpdater
DockerBuildStrategy *strategy.DockerBuildStrategy
SourceBuildStrategy *strategy.SourceBuildStrategy
CustomBuildStrategy *strategy.CustomBuildStrategy
// Stop may be set to allow controllers created by this factory to be terminated.
Stop <-chan struct{}
}
// Create constructs a BuildController
func (factory *BuildControllerFactory) Create() controller.RunnableController {
queue := cache.NewFIFO(cache.MetaNamespaceKeyFunc)
cache.NewReflector(&buildLW{client: factory.OSClient}, &buildapi.Build{}, queue, 2*time.Minute).Run()
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(factory.KubeClient.Events(""))
client := ControllerClient{factory.KubeClient, factory.OSClient}
buildController := &buildcontroller.BuildController{
BuildUpdater: factory.BuildUpdater,
ImageStreamClient: client,
PodManager: client,
BuildStrategy: &typeBasedFactoryStrategy{
DockerBuildStrategy: factory.DockerBuildStrategy,
SourceBuildStrategy: factory.SourceBuildStrategy,
CustomBuildStrategy: factory.CustomBuildStrategy,
},
Recorder: eventBroadcaster.NewRecorder(kapi.EventSource{Component: "build-controller"}),
}
return &controller.RetryController{
Queue: queue,
RetryManager: controller.NewQueueRetryManager(
queue,
cache.MetaNamespaceKeyFunc,
limitedLogAndRetry(factory.BuildUpdater, 30*time.Minute),
kutil.NewTokenBucketRateLimiter(1, 10)),
Handle: func(obj interface{}) error {
build := obj.(*buildapi.Build)
return buildController.HandleBuild(build)
},
}
}
// CreateDeleteController constructs a BuildDeleteController
func (factory *BuildControllerFactory) CreateDeleteController() controller.RunnableController {
client := ControllerClient{factory.KubeClient, factory.OSClient}
queue := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, nil)
cache.NewReflector(&buildDeleteLW{client, queue}, &buildapi.Build{}, queue, 5*time.Minute).Run()
buildDeleteController := &buildcontroller.BuildDeleteController{
PodManager: client,
}
return &controller.RetryController{
Queue: queue,
RetryManager: controller.NewQueueRetryManager(
queue,
cache.MetaNamespaceKeyFunc,
controller.RetryNever,
kutil.NewTokenBucketRateLimiter(1, 10)),
Handle: func(obj interface{}) error {
deltas := obj.(cache.Deltas)
for _, delta := range deltas {
if delta.Type == cache.Deleted {
return buildDeleteController.HandleBuildDeletion(delta.Object.(*buildapi.Build))
}
}
return nil
},
}
}
// BuildPodControllerFactory construct BuildPodController objects
type BuildPodControllerFactory struct {
OSClient osclient.Interface
KubeClient kclient.Interface
BuildUpdater buildclient.BuildUpdater
// Stop may be set to allow controllers created by this factory to be terminated.
Stop <-chan struct{}
buildStore cache.Store
}
// Create constructs a BuildPodController
func (factory *BuildPodControllerFactory) Create() controller.RunnableController {
factory.buildStore = cache.NewStore(cache.MetaNamespaceKeyFunc)
cache.NewReflector(&buildLW{client: factory.OSClient}, &buildapi.Build{}, factory.buildStore, 2*time.Minute).Run()
queue := cache.NewFIFO(cache.MetaNamespaceKeyFunc)
cache.NewReflector(&podLW{client: factory.KubeClient}, &kapi.Pod{}, queue, 2*time.Minute).Run()
client := ControllerClient{factory.KubeClient, factory.OSClient}
buildPodController := &buildcontroller.BuildPodController{
BuildStore: factory.buildStore,
BuildUpdater: factory.BuildUpdater,
PodManager: client,
}
return &controller.RetryController{
Queue: queue,
RetryManager: controller.NewQueueRetryManager(
queue,
cache.MetaNamespaceKeyFunc,
func(obj interface{}, err error, retries controller.Retry) bool {
pod := obj.(*kapi.Pod)
if retries.Count < maxRetries {
glog.V(3).Infof("Retrying BuildPod update event %s/%s: %v", pod.Namespace, pod.Name, err)
return true
}
glog.V(3).Infof("Giving up retrying BuildPod update event %s/%s: %v", pod.Namespace, pod.Name, err)
kutil.HandleError(err)
return false
},
kutil.NewTokenBucketRateLimiter(1, 10)),
Handle: func(obj interface{}) error {
pod := obj.(*kapi.Pod)
return buildPodController.HandlePod(pod)
},
}
}
// CreateDeleteController constructs a BuildPodDeleteController
func (factory *BuildPodControllerFactory) CreateDeleteController() controller.RunnableController {
client := ControllerClient{factory.KubeClient, factory.OSClient}
queue := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, nil)
cache.NewReflector(&buildPodDeleteLW{client, queue}, &kapi.Pod{}, queue, 5*time.Minute).Run()
buildPodDeleteController := &buildcontroller.BuildPodDeleteController{
BuildStore: factory.buildStore,
BuildUpdater: factory.BuildUpdater,
}
return &controller.RetryController{
Queue: queue,
RetryManager: controller.NewQueueRetryManager(
queue,
cache.MetaNamespaceKeyFunc,
controller.RetryNever,
kutil.NewTokenBucketRateLimiter(1, 10)),
Handle: func(obj interface{}) error {
deltas := obj.(cache.Deltas)
for _, delta := range deltas {
if delta.Type == cache.Deleted {
return buildPodDeleteController.HandleBuildPodDeletion(delta.Object.(*kapi.Pod))
}
}
return nil
},
}
}
// ImageChangeControllerFactory can create an ImageChangeController which obtains ImageStreams
// from a queue populated from a watch of all ImageStreams.
type ImageChangeControllerFactory struct {
Client osclient.Interface
BuildConfigInstantiator buildclient.BuildConfigInstantiator
// Stop may be set to allow controllers created by this factory to be terminated.
Stop <-chan struct{}
}
// Create creates a new ImageChangeController which is used to trigger builds when a new
// image is available
func (factory *ImageChangeControllerFactory) Create() controller.RunnableController {
queue := cache.NewFIFO(cache.MetaNamespaceKeyFunc)
cache.NewReflector(&imageStreamLW{factory.Client}, &imageapi.ImageStream{}, queue, 2*time.Minute).Run()
store := cache.NewStore(cache.MetaNamespaceKeyFunc)
cache.NewReflector(&buildConfigLW{client: factory.Client}, &buildapi.BuildConfig{}, store, 2*time.Minute).Run()
imageChangeController := &buildcontroller.ImageChangeController{
BuildConfigStore: store,
BuildConfigInstantiator: factory.BuildConfigInstantiator,
Stop: factory.Stop,
}
return &controller.RetryController{
Queue: queue,
RetryManager: controller.NewQueueRetryManager(
queue,
cache.MetaNamespaceKeyFunc,
func(obj interface{}, err error, retries controller.Retry) bool {
imageStream := obj.(*imageapi.ImageStream)
if _, isFatal := err.(buildcontroller.ImageChangeControllerFatalError); isFatal {
glog.V(3).Infof("Will not retry fatal error for ImageStream update event %s/%s: %v", imageStream.Namespace, imageStream.Name, err)
kutil.HandleError(err)
return false
}
if maxRetries > retries.Count {
glog.V(3).Infof("Giving up retrying ImageStream update event %s/%s: %v", imageStream.Namespace, imageStream.Name, err)
kutil.HandleError(err)
return false
}
glog.V(4).Infof("Retrying ImageStream update event %s/%s: %v", imageStream.Namespace, imageStream.Name, err)
return true
},
kutil.NewTokenBucketRateLimiter(1, 10),
),
Handle: func(obj interface{}) error {
imageRepo := obj.(*imageapi.ImageStream)
return imageChangeController.HandleImageRepo(imageRepo)
},
}
}
// podEnumerator allows a cache.Poller to enumerate items in an api.PodList
type podEnumerator struct {
*kapi.PodList
}
// Len returns the number of items in the pod list.
func (pe *podEnumerator) Len() int {
if pe.PodList == nil {
return 0
}
return len(pe.Items)
}
// Get returns the item (and ID) with the particular index.
func (pe *podEnumerator) Get(index int) interface{} {
return &pe.Items[index]
}
type typeBasedFactoryStrategy struct {
DockerBuildStrategy *strategy.DockerBuildStrategy
SourceBuildStrategy *strategy.SourceBuildStrategy
CustomBuildStrategy *strategy.CustomBuildStrategy
}
func (f *typeBasedFactoryStrategy) CreateBuildPod(build *buildapi.Build) (*kapi.Pod, error) {
var pod *kapi.Pod
var err error
switch build.Spec.Strategy.Type {
case buildapi.DockerBuildStrategyType:
pod, err = f.DockerBuildStrategy.CreateBuildPod(build)
case buildapi.SourceBuildStrategyType:
pod, err = f.SourceBuildStrategy.CreateBuildPod(build)
case buildapi.CustomBuildStrategyType:
pod, err = f.CustomBuildStrategy.CreateBuildPod(build)
default:
return nil, fmt.Errorf("no supported build strategy defined for Build %s/%s with type %s", build.Namespace, build.Name, build.Spec.Strategy.Type)
}
if pod != nil {
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[buildapi.BuildAnnotation] = build.Name
}
return pod, err
}
// panicIfStopped panics with the provided object if the channel is closed
func panicIfStopped(ch <-chan struct{}, message interface{}) {
select {
case <-ch:
panic(message)
default:
}
}
// podLW is a ListWatcher implementation for Pods.
type podLW struct {
client kclient.Interface
}
// List lists all Pods that have a build label.
func (lw *podLW) List() (runtime.Object, error) {
sel, _ := labels.Parse(buildapi.BuildLabel)
return lw.client.Pods(kapi.NamespaceAll).List(sel, fields.Everything())
}
// Watch watches all Pods that have a build label.
func (lw *podLW) Watch(resourceVersion string) (watch.Interface, error) {
sel, _ := labels.Parse(buildapi.BuildLabel)
return lw.client.Pods(kapi.NamespaceAll).Watch(sel, fields.Everything(), resourceVersion)
}
// buildLW is a ListWatcher implementation for Builds.
type buildLW struct {
client osclient.Interface
}
// List lists all Builds.
func (lw *buildLW) List() (runtime.Object, error) {
return lw.client.Builds(kapi.NamespaceAll).List(labels.Everything(), fields.Everything())
}
// Watch watches all Builds.
func (lw *buildLW) Watch(resourceVersion string) (watch.Interface, error) {
return lw.client.Builds(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)
}
// buildDeleteLW is a ListWatcher implementation that watches for builds being deleted
type buildDeleteLW struct {
ControllerClient
store cache.Store
}
// List returns an empty list but adds delete events to the store for all Builds that have been deleted but still have pods.
func (lw *buildDeleteLW) List() (runtime.Object, error) {
glog.V(5).Info("Checking for deleted builds")
sel, _ := labels.Parse(buildapi.BuildLabel)
podList, err := lw.KubeClient.Pods(kapi.NamespaceAll).List(sel, fields.Everything())
if err != nil {
glog.V(4).Infof("Failed to find any pods due to error %v", err)
return nil, err
}
for _, pod := range podList.Items {
if len(pod.Labels[buildapi.BuildLabel]) == 0 {
continue
}
glog.V(5).Infof("Found build pod %s/%s", pod.Namespace, pod.Name)
build, err := lw.Client.Builds(pod.Namespace).Get(pod.Labels[buildapi.BuildLabel])
if err != nil && !kerrors.IsNotFound(err) {
glog.V(4).Infof("Error getting build for pod %s/%s: %v", pod.Namespace, pod.Name, err)
return nil, err
}
if err != nil && kerrors.IsNotFound(err) {
build = nil
}
if build == nil {
deletedBuild := &buildapi.Build{
ObjectMeta: kapi.ObjectMeta{
Name: pod.Labels[buildapi.BuildLabel],
Namespace: pod.Namespace,
},
}
glog.V(4).Infof("No build found for build pod %s/%s, deleting pod", pod.Namespace, pod.Name)
err := lw.store.Delete(deletedBuild)
if err != nil {
glog.V(4).Infof("Error queuing delete event: %v", err)
}
} else {
glog.V(5).Infof("Found build %s/%s for pod %s", build.Namespace, build.Name, pod.Name)
}
}
return &buildapi.BuildList{}, nil
}
// Watch watches all Builds.
func (lw *buildDeleteLW) Watch(resourceVersion string) (watch.Interface, error) {
//return lw.client.Client.Builds(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)
return lw.Client.Builds(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)
}
// buildConfigLW is a ListWatcher implementation for BuildConfigs.
type buildConfigLW struct {
client osclient.Interface
}
// List lists all BuildConfigs.
func (lw *buildConfigLW) List() (runtime.Object, error) {
return lw.client.BuildConfigs(kapi.NamespaceAll).List(labels.Everything(), fields.Everything())
}
// Watch watches all BuildConfigs.
func (lw *buildConfigLW) Watch(resourceVersion string) (watch.Interface, error) {
return lw.client.BuildConfigs(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)
}
// imageStreamLW is a ListWatcher for ImageStreams.
type imageStreamLW struct {
client osclient.Interface
}
// List lists all ImageStreams.
func (lw *imageStreamLW) List() (runtime.Object, error) {
return lw.client.ImageStreams(kapi.NamespaceAll).List(labels.Everything(), fields.Everything())
}
// Watch watches all ImageStreams.
func (lw *imageStreamLW) Watch(resourceVersion string) (watch.Interface, error) {
return lw.client.ImageStreams(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)
}
// buildPodDeleteLW is a ListWatcher implementation that watches for Pods(that are associated with a Build) being deleted
type buildPodDeleteLW struct {
ControllerClient
store cache.Store
}
// List lists all Pods associated with a Build.
func (lw *buildPodDeleteLW) List() (runtime.Object, error) {
glog.V(5).Info("Checking for deleted build pods")
buildList, err := lw.Client.Builds(kapi.NamespaceAll).List(labels.Everything(), fields.Everything())
if err != nil {
glog.V(4).Infof("Failed to find any builds due to error %v", err)
return nil, err
}
for _, build := range buildList.Items {
glog.V(5).Infof("Found build %s/%s", build.Namespace, build.Name)
if buildutil.IsBuildComplete(&build) {
glog.V(5).Infof("Ignoring build %s/%s because it is complete", build.Namespace, build.Name)
continue
}
pod, err := lw.KubeClient.Pods(build.Namespace).Get(buildutil.GetBuildPodName(&build))
if err != nil && !kerrors.IsNotFound(err) {
glog.V(4).Infof("Error getting pod for build %s/%s: %v", build.Namespace, build.Name, err)
return nil, err
}
if (err != nil && kerrors.IsNotFound(err)) || pod.Labels[buildapi.BuildLabel] != build.Name {
pod = nil
}
if pod == nil {
deletedPod := &kapi.Pod{
ObjectMeta: kapi.ObjectMeta{
Name: buildutil.GetBuildPodName(&build),
Namespace: build.Namespace,
},
}
glog.V(4).Infof("No build pod found for build %s/%s, sending delete event for build pod", build.Namespace, build.Name)
err := lw.store.Delete(deletedPod)
if err != nil {
glog.V(4).Infof("Error queuing delete event: %v", err)
}
} else {
glog.V(5).Infof("Found build pod %s/%s for build %s", pod.Namespace, pod.Name, build.Name)
}
}
return &kapi.PodList{}, nil
}
// Watch watches all Pods that have a build label, for deletion
func (lw *buildPodDeleteLW) Watch(resourceVersion string) (watch.Interface, error) {
sel, _ := labels.Parse(buildapi.BuildLabel)
return lw.KubeClient.Pods(kapi.NamespaceAll).Watch(sel, fields.Everything(), resourceVersion)
}
// ControllerClient implements the common interfaces needed for build controllers
type ControllerClient struct {
KubeClient kclient.Interface
Client osclient.Interface
}
// CreatePod creates a pod using the Kubernetes client.
func (c ControllerClient) CreatePod(namespace string, pod *kapi.Pod) (*kapi.Pod, error) {
return c.KubeClient.Pods(namespace).Create(pod)
}
// DeletePod destroys a pod using the Kubernetes client.
func (c ControllerClient) DeletePod(namespace string, pod *kapi.Pod) error {
return c.KubeClient.Pods(namespace).Delete(pod.Name, nil)
}
// GetPod gets a pod using the Kubernetes client.
func (c ControllerClient) GetPod(namespace, name string) (*kapi.Pod, error) {
return c.KubeClient.Pods(namespace).Get(name)
}
// GetImageStream retrieves an image repository by namespace and name
func (c ControllerClient) GetImageStream(namespace, name string) (*imageapi.ImageStream, error) {
return c.Client.ImageStreams(namespace).Get(name)
}