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
/
pipeline.go
546 lines (491 loc) · 14.5 KB
/
pipeline.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
package app
import (
"fmt"
"regexp"
"sort"
"strings"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
kuval "k8s.io/apimachinery/pkg/util/validation"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/validation"
extensions "k8s.io/kubernetes/pkg/apis/extensions"
deploy "github.com/openshift/origin/pkg/apps/apis/apps"
build "github.com/openshift/origin/pkg/build/apis/build"
"github.com/openshift/origin/pkg/generate"
image "github.com/openshift/origin/pkg/image/apis/image"
route "github.com/openshift/origin/pkg/route/apis/route"
"github.com/openshift/origin/pkg/util/docker/dockerfile"
)
// A PipelineBuilder creates Pipeline instances.
type PipelineBuilder interface {
To(string) PipelineBuilder
NewBuildPipeline(string, *ImageRef, *SourceRepository, bool) (*Pipeline, error)
NewImagePipeline(string, *ImageRef) (*Pipeline, error)
}
// NewPipelineBuilder returns a PipelineBuilder using name as a base name. A
// PipelineBuilder always creates pipelines with unique names, so that the
// actual name of a pipeline (Pipeline.Name) might differ from the base name.
// The pipelines created with a PipelineBuilder will have access to the given
// environment. The boolean outputDocker controls whether builds will output to
// an image stream tag or docker image reference.
func NewPipelineBuilder(name string, environment Environment, dockerStrategyOptions *build.DockerStrategyOptions, outputDocker bool) PipelineBuilder {
return &pipelineBuilder{
nameGenerator: NewUniqueNameGenerator(name),
environment: environment,
outputDocker: outputDocker,
dockerStrategyOptions: dockerStrategyOptions,
}
}
type pipelineBuilder struct {
nameGenerator UniqueNameGenerator
environment Environment
outputDocker bool
to string
dockerStrategyOptions *build.DockerStrategyOptions
}
func (pb *pipelineBuilder) To(name string) PipelineBuilder {
pb.to = name
return pb
}
// NewBuildPipeline creates a new pipeline with components that are expected to
// be built.
func (pb *pipelineBuilder) NewBuildPipeline(from string, input *ImageRef, sourceRepository *SourceRepository, binary bool) (*Pipeline, error) {
strategy, source, err := StrategyAndSourceForRepository(sourceRepository, input)
if err != nil {
return nil, fmt.Errorf("can't build %q: %v", from, err)
}
var name string
output := &ImageRef{
OutputImage: true,
AsImageStream: !pb.outputDocker,
}
if len(pb.to) > 0 {
outputImageRef, err := image.ParseDockerImageReference(pb.to)
if err != nil {
return nil, err
}
output.Reference = outputImageRef
name, err = pb.nameGenerator.Generate(NameSuggestions{source, output, input})
if err != nil {
return nil, err
}
} else {
name, err = pb.nameGenerator.Generate(NameSuggestions{source, input})
if err != nil {
return nil, err
}
output.Reference = image.DockerImageReference{
Name: name,
Tag: image.DefaultImageTag,
}
}
source.Name = name
// Append any exposed ports from Dockerfile to input image
if sourceRepository.GetStrategy() == generate.StrategyDocker && sourceRepository.Info() != nil {
node := sourceRepository.Info().Dockerfile.AST()
ports := dockerfile.LastExposedPorts(node)
if len(ports) > 0 {
if input.Info == nil {
input.Info = &image.DockerImage{
Config: &image.DockerConfig{},
}
}
input.Info.Config.ExposedPorts = map[string]struct{}{}
for _, p := range ports {
input.Info.Config.ExposedPorts[p] = struct{}{}
}
}
}
if input != nil {
// TODO: assumes that build doesn't change the image metadata. In the future
// we could get away with deferred generation possibly.
output.Info = input.Info
}
build := &BuildRef{
Source: source,
Input: input,
Strategy: strategy,
Output: output,
Env: pb.environment,
DockerStrategyOptions: pb.dockerStrategyOptions,
Binary: binary,
}
return &Pipeline{
Name: name,
From: from,
InputImage: input,
Image: output,
Build: build,
}, nil
}
// NewImagePipeline creates a new pipeline with components that are not expected
// to be built.
func (pb *pipelineBuilder) NewImagePipeline(from string, input *ImageRef) (*Pipeline, error) {
name, err := pb.nameGenerator.Generate(input)
if err != nil {
return nil, err
}
input.ObjectName = name
return &Pipeline{
Name: name,
From: from,
Image: input,
}, nil
}
// Pipeline holds components.
type Pipeline struct {
Name string
From string
InputImage *ImageRef
Build *BuildRef
Image *ImageRef
Deployment *DeploymentConfigRef
Labels map[string]string
}
// NeedsDeployment sets the pipeline for deployment.
func (p *Pipeline) NeedsDeployment(env Environment, labels map[string]string, asTest bool) error {
if p.Deployment != nil {
return nil
}
p.Deployment = &DeploymentConfigRef{
Name: p.Name,
Images: []*ImageRef{
p.Image,
},
Env: env,
Labels: labels,
AsTest: asTest,
}
return nil
}
// Objects converts all the components in the pipeline into runtime objects.
func (p *Pipeline) Objects(accept, objectAccept Acceptor) (Objects, error) {
objects := Objects{}
if p.InputImage != nil && p.InputImage.AsImageStream && accept.Accept(p.InputImage) {
repo, err := p.InputImage.ImageStream()
if err != nil {
return nil, err
}
if objectAccept.Accept(repo) {
objects = append(objects, repo)
}
}
if p.Image != nil && p.Image.AsImageStream && accept.Accept(p.Image) {
repo, err := p.Image.ImageStream()
if err != nil {
return nil, err
}
if objectAccept.Accept(repo) {
objects = append(objects, repo)
}
}
if p.Build != nil && accept.Accept(p.Build) {
build, err := p.Build.BuildConfig()
if err != nil {
return nil, err
}
if objectAccept.Accept(build) {
objects = append(objects, build)
}
if p.Build.Source != nil && p.Build.Source.SourceImage != nil && p.Build.Source.SourceImage.AsImageStream && accept.Accept(p.Build.Source.SourceImage) {
srcImage, err := p.Build.Source.SourceImage.ImageStream()
if err != nil {
return nil, err
}
if objectAccept.Accept(srcImage) {
objects = append(objects, srcImage)
}
}
}
if p.Deployment != nil && accept.Accept(p.Deployment) {
dc, err := p.Deployment.DeploymentConfig()
if err != nil {
return nil, err
}
if objectAccept.Accept(dc) {
objects = append(objects, dc)
}
}
return objects, nil
}
// PipelineGroup is a group of Pipelines.
type PipelineGroup []*Pipeline
// Reduce squashes all common components from the pipelines.
func (g PipelineGroup) Reduce() error {
var deployment *DeploymentConfigRef
for _, p := range g {
if p.Deployment == nil || p.Deployment == deployment {
continue
}
if deployment == nil {
deployment = p.Deployment
} else {
deployment.Images = append(deployment.Images, p.Deployment.Images...)
deployment.Env = NewEnvironment(deployment.Env, p.Deployment.Env)
p.Deployment = deployment
}
}
return nil
}
func (g PipelineGroup) String() string {
s := []string{}
for _, p := range g {
s = append(s, p.From)
}
return strings.Join(s, "+")
}
// MakeSimpleName strips any non-alphanumeric characters out of a string and returns
// either an empty string or a string which is valid for most Kubernetes resources.
func MakeSimpleName(name string) string {
name = strings.ToLower(name)
name = invalidServiceChars.ReplaceAllString(name, "")
name = strings.TrimFunc(name, func(r rune) bool { return r == '-' })
if len(name) > kuval.DNS1035LabelMaxLength {
name = name[:kuval.DNS1035LabelMaxLength]
}
return name
}
var invalidServiceChars = regexp.MustCompile("[^-a-z0-9]")
func makeValidServiceName(name string) (string, string) {
if len(validation.ValidateServiceName(name, false)) == 0 {
return name, ""
}
name = MakeSimpleName(name)
if len(name) == 0 {
return "", "service-"
}
return name, ""
}
type sortablePorts []kapi.ContainerPort
func (s sortablePorts) Len() int { return len(s) }
func (s sortablePorts) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortablePorts) Less(i, j int) bool {
return s[i].ContainerPort < s[j].ContainerPort
}
// portName returns a unique key for the given port and protocol which can be
// used as a service port name.
func portName(port int, protocol kapi.Protocol) string {
if protocol == "" {
protocol = kapi.ProtocolTCP
}
return strings.ToLower(fmt.Sprintf("%d-%s", port, protocol))
}
// GenerateService creates a simple service for the provided elements.
func GenerateService(meta metav1.ObjectMeta, selector map[string]string) *kapi.Service {
name, generateName := makeValidServiceName(meta.Name)
svc := &kapi.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
GenerateName: generateName,
Labels: meta.Labels,
},
Spec: kapi.ServiceSpec{
Selector: selector,
},
}
return svc
}
// AllContainerPorts creates a sorted list of all ports in all provided containers.
func AllContainerPorts(containers ...kapi.Container) []kapi.ContainerPort {
var ports []kapi.ContainerPort
for _, container := range containers {
ports = append(ports, container.Ports...)
}
sort.Sort(sortablePorts(ports))
return ports
}
// UniqueContainerToServicePorts creates one service port for each unique container port.
func UniqueContainerToServicePorts(ports []kapi.ContainerPort) []kapi.ServicePort {
var result []kapi.ServicePort
svcPorts := map[string]struct{}{}
for _, p := range ports {
name := portName(int(p.ContainerPort), p.Protocol)
_, exists := svcPorts[name]
if exists {
continue
}
svcPorts[name] = struct{}{}
result = append(result, kapi.ServicePort{
Name: name,
Port: p.ContainerPort,
Protocol: p.Protocol,
TargetPort: intstr.FromInt(int(p.ContainerPort)),
})
}
return result
}
// AddServices sets up services for the provided objects.
func AddServices(objects Objects, firstPortOnly bool) Objects {
svcs := []runtime.Object{}
for _, o := range objects {
switch t := o.(type) {
case *deploy.DeploymentConfig:
svc := addServiceInternal(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Selector, firstPortOnly)
if svc != nil {
svcs = append(svcs, svc)
}
case *extensions.DaemonSet:
svc := addServiceInternal(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
if svc != nil {
svcs = append(svcs, svc)
}
}
}
return append(objects, svcs...)
}
// addServiceInternal utility used by AddServices to create services for multiple types.
func addServiceInternal(containers []kapi.Container, objectMeta metav1.ObjectMeta, selector map[string]string, firstPortOnly bool) *kapi.Service {
ports := UniqueContainerToServicePorts(AllContainerPorts(containers...))
if len(ports) == 0 {
return nil
}
if firstPortOnly {
ports = ports[:1]
}
svc := GenerateService(objectMeta, selector)
svc.Spec.Ports = ports
return svc
}
// AddRoutes sets up routes for the provided objects.
func AddRoutes(objects Objects) Objects {
routes := []runtime.Object{}
for _, o := range objects {
switch t := o.(type) {
case *kapi.Service:
routes = append(routes, &route.Route{
ObjectMeta: metav1.ObjectMeta{
Name: t.Name,
Labels: t.Labels,
},
Spec: route.RouteSpec{
To: route.RouteTargetReference{
Name: t.Name,
},
},
})
}
}
return append(objects, routes...)
}
type acceptNew struct{}
// AcceptNew only accepts runtime.Objects with an empty resource version.
var AcceptNew Acceptor = acceptNew{}
// Accept accepts any kind of object.
func (acceptNew) Accept(from interface{}) bool {
_, meta, err := objectMetaData(from)
if err != nil {
return false
}
if len(meta.GetResourceVersion()) > 0 {
return false
}
return true
}
type acceptUnique struct {
typer runtime.ObjectTyper
objects map[string]struct{}
}
// Accept accepts any kind of object it hasn't accepted before.
func (a *acceptUnique) Accept(from interface{}) bool {
obj, meta, err := objectMetaData(from)
if err != nil {
return false
}
gvk, _, err := a.typer.ObjectKinds(obj)
if err != nil {
return false
}
key := fmt.Sprintf("%s/%s/%s", gvk[0].Kind, meta.GetNamespace(), meta.GetName())
_, exists := a.objects[key]
if exists {
return false
}
a.objects[key] = struct{}{}
return true
}
// NewAcceptUnique creates an acceptor that only accepts unique objects by kind
// and name.
func NewAcceptUnique(typer runtime.ObjectTyper) Acceptor {
return &acceptUnique{
typer: typer,
objects: map[string]struct{}{},
}
}
func objectMetaData(raw interface{}) (runtime.Object, metav1.Object, error) {
obj, ok := raw.(runtime.Object)
if !ok {
return nil, nil, fmt.Errorf("%#v is not a runtime.Object", raw)
}
meta, err := meta.Accessor(obj)
if err != nil {
return nil, nil, err
}
return obj, meta, nil
}
type acceptBuildConfigs struct {
typer runtime.ObjectTyper
}
// Accept accepts BuildConfigs and ImageStreams.
func (a *acceptBuildConfigs) Accept(from interface{}) bool {
obj, _, err := objectMetaData(from)
if err != nil {
return false
}
gvk, _, err := a.typer.ObjectKinds(obj)
if err != nil {
return false
}
gk := gvk[0].GroupKind()
return build.IsKindOrLegacy("BuildConfig", gk) || image.IsKindOrLegacy("ImageStream", gk)
}
// NewAcceptBuildConfigs creates an acceptor accepting BuildConfig objects
// and ImageStreams objects.
func NewAcceptBuildConfigs(typer runtime.ObjectTyper) Acceptor {
return &acceptBuildConfigs{
typer: typer,
}
}
// Acceptors is a list of acceptors that behave like a single acceptor.
// All acceptors must accept an object for it to be accepted.
type Acceptors []Acceptor
// Accept iterates through all acceptors and determines whether the object
// should be accepted.
func (aa Acceptors) Accept(from interface{}) bool {
for _, a := range aa {
if !a.Accept(from) {
return false
}
}
return true
}
type acceptAll struct{}
// AcceptAll accepts all objects.
var AcceptAll Acceptor = acceptAll{}
// Accept accepts everything.
func (acceptAll) Accept(_ interface{}) bool {
return true
}
// Objects is a set of runtime objects.
type Objects []runtime.Object
// Acceptor is an interface for accepting objects.
type Acceptor interface {
Accept(from interface{}) bool
}
type acceptFirst struct {
handled map[interface{}]struct{}
}
// NewAcceptFirst returns a new Acceptor.
func NewAcceptFirst() Acceptor {
return &acceptFirst{make(map[interface{}]struct{})}
}
// Accept accepts any object it hasn't accepted before.
func (s *acceptFirst) Accept(from interface{}) bool {
if _, ok := s.handled[from]; ok {
return false
}
s.handled[from] = struct{}{}
return true
}