-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
app.go
434 lines (395 loc) · 10.8 KB
/
app.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
package app
import (
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"net/url"
"reflect"
"strconv"
"strings"
"github.com/pborman/uuid"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/conversion"
"k8s.io/kubernetes/pkg/runtime"
buildapi "github.com/openshift/origin/pkg/build/api"
deployapi "github.com/openshift/origin/pkg/deploy/api"
"github.com/openshift/origin/pkg/generate/git"
imageapi "github.com/openshift/origin/pkg/image/api"
"github.com/openshift/origin/pkg/util"
)
const (
volumeNameInfix = "volume"
)
// NameSuggester is an object that can suggest a name for itself
type NameSuggester interface {
SuggestName() (string, bool)
}
// NameSuggestions suggests names from a collection of NameSuggesters
type NameSuggestions []NameSuggester
// SuggestName suggests a name given a collection of NameSuggesters
func (s NameSuggestions) SuggestName() (string, bool) {
for i := range s {
if s[i] == nil {
continue
}
if name, ok := s[i].SuggestName(); ok {
return name, true
}
}
return "", false
}
// Generated is a list of runtime objects
type Generated struct {
Items []runtime.Object
}
// WithType extracts a list of runtime objects with the specified type
func (g *Generated) WithType(slicePtr interface{}) bool {
found := false
v, err := conversion.EnforcePtr(slicePtr)
if err != nil || v.Kind() != reflect.Slice {
// This should not happen at runtime.
panic("need ptr to slice")
}
t := v.Type().Elem()
for i := range g.Items {
obj := reflect.ValueOf(g.Items[i]).Elem()
if !obj.Type().ConvertibleTo(t) {
continue
}
found = true
v.Set(reflect.Append(v, obj.Convert(t)))
}
return found
}
func nameFromGitURL(url *url.URL) (string, bool) {
if url == nil {
return "", false
}
// from path
if name, ok := git.NameFromRepositoryURL(url); ok {
return name, true
}
// TODO: path is questionable
if len(url.Host) > 0 {
// from host with port
if host, _, err := net.SplitHostPort(url.Host); err == nil {
return host, true
}
// from host without port
return url.Host, true
}
return "", false
}
// SourceRef is a reference to a build source
type SourceRef struct {
URL *url.URL
Ref string
Dir string
Name string
ContextDir string
Secrets []buildapi.SecretBuildSource
SourceImage *ImageRef
ImageSourcePath string
ImageDestPath string
DockerfileContents string
Binary bool
}
func urlWithoutRef(url url.URL) string {
url.Fragment = ""
return url.String()
}
// SuggestName returns a name derived from the source URL
func (r *SourceRef) SuggestName() (string, bool) {
if r == nil {
return "", false
}
if len(r.Name) > 0 {
return r.Name, true
}
return nameFromGitURL(r.URL)
}
// BuildSource returns an OpenShift BuildSource from the SourceRef
func (r *SourceRef) BuildSource() (*buildapi.BuildSource, []buildapi.BuildTriggerPolicy) {
triggers := []buildapi.BuildTriggerPolicy{
{
Type: buildapi.GitHubWebHookBuildTriggerType,
GitHubWebHook: &buildapi.WebHookTrigger{
Secret: GenerateSecret(20),
},
},
{
Type: buildapi.GenericWebHookBuildTriggerType,
GenericWebHook: &buildapi.WebHookTrigger{
Secret: GenerateSecret(20),
},
},
}
source := &buildapi.BuildSource{}
source.Secrets = r.Secrets
if len(r.DockerfileContents) != 0 {
source.Dockerfile = &r.DockerfileContents
}
if r.URL != nil {
source.Git = &buildapi.GitBuildSource{
URI: urlWithoutRef(*r.URL),
Ref: r.Ref,
}
source.ContextDir = r.ContextDir
}
if r.Binary {
source.Binary = &buildapi.BinaryBuildSource{}
}
if r.SourceImage != nil {
objRef := r.SourceImage.ObjectReference()
imgSrc := buildapi.ImageSource{}
imgSrc.From = objRef
imgSrc.Paths = []buildapi.ImageSourcePath{
{
SourcePath: r.ImageSourcePath,
DestinationDir: r.ImageDestPath,
},
}
triggers = append(triggers, buildapi.BuildTriggerPolicy{
Type: buildapi.ImageChangeBuildTriggerType,
ImageChange: &buildapi.ImageChangeTrigger{
From: &objRef,
},
})
source.Images = []buildapi.ImageSource{imgSrc}
}
return source, triggers
}
// BuildStrategyRef is a reference to a build strategy
type BuildStrategyRef struct {
IsDockerBuild bool
Base *ImageRef
}
// BuildStrategy builds an OpenShift BuildStrategy from a BuildStrategyRef
func (s *BuildStrategyRef) BuildStrategy(env Environment) (*buildapi.BuildStrategy, []buildapi.BuildTriggerPolicy) {
if s.IsDockerBuild {
var triggers []buildapi.BuildTriggerPolicy
strategy := &buildapi.DockerBuildStrategy{
Env: env.List(),
}
if s.Base != nil {
ref := s.Base.ObjectReference()
strategy.From = &ref
triggers = s.Base.BuildTriggers()
}
return &buildapi.BuildStrategy{
DockerStrategy: strategy,
}, triggers
}
return &buildapi.BuildStrategy{
SourceStrategy: &buildapi.SourceBuildStrategy{
From: s.Base.ObjectReference(),
Env: env.List(),
},
}, s.Base.BuildTriggers()
}
// BuildRef is a reference to a build configuration
type BuildRef struct {
Source *SourceRef
Input *ImageRef
Strategy *BuildStrategyRef
Output *ImageRef
Env Environment
}
// BuildConfig creates a buildConfig resource from the build configuration reference
func (r *BuildRef) BuildConfig() (*buildapi.BuildConfig, error) {
name, ok := NameSuggestions{r.Source, r.Output}.SuggestName()
if !ok {
return nil, fmt.Errorf("unable to suggest a name for this BuildConfig from %q", r.Source.URL)
}
var source *buildapi.BuildSource
triggers := []buildapi.BuildTriggerPolicy{}
if r.Source != nil {
source, triggers = r.Source.BuildSource()
}
if source == nil {
source = &buildapi.BuildSource{}
}
strategy := &buildapi.BuildStrategy{}
strategyTriggers := []buildapi.BuildTriggerPolicy{}
if r.Strategy != nil {
strategy, strategyTriggers = r.Strategy.BuildStrategy(r.Env)
}
output, err := r.Output.BuildOutput()
if err != nil {
return nil, err
}
if source.Binary == nil {
configChangeTrigger := buildapi.BuildTriggerPolicy{
Type: buildapi.ConfigChangeBuildTriggerType,
}
triggers = append(triggers, configChangeTrigger)
triggers = append(triggers, strategyTriggers...)
}
return &buildapi.BuildConfig{
ObjectMeta: kapi.ObjectMeta{
Name: name,
},
Spec: buildapi.BuildConfigSpec{
Triggers: triggers,
BuildSpec: buildapi.BuildSpec{
Source: *source,
Strategy: *strategy,
Output: *output,
},
},
}, nil
}
// DeploymentConfigRef is a reference to a deployment configuration
type DeploymentConfigRef struct {
Name string
Images []*ImageRef
Env Environment
Labels map[string]string
AsTest bool
}
// DeploymentConfig creates a deploymentConfig resource from the deployment configuration reference
//
// TODO: take a pod template spec as argument
func (r *DeploymentConfigRef) DeploymentConfig() (*deployapi.DeploymentConfig, error) {
if len(r.Name) == 0 {
suggestions := NameSuggestions{}
for i := range r.Images {
suggestions = append(suggestions, r.Images[i])
}
name, ok := suggestions.SuggestName()
if !ok {
return nil, fmt.Errorf("unable to suggest a name for this DeploymentConfig")
}
r.Name = name
}
selector := map[string]string{
"deploymentconfig": r.Name,
}
if len(r.Labels) > 0 {
if err := util.MergeInto(selector, r.Labels, 0); err != nil {
return nil, err
}
}
triggers := []deployapi.DeploymentTriggerPolicy{
// By default, always deploy on change
{
Type: deployapi.DeploymentTriggerOnConfigChange,
},
}
annotations := make(map[string]string)
template := kapi.PodSpec{}
for i := range r.Images {
c, containerTriggers, err := r.Images[i].DeployableContainer()
if err != nil {
return nil, err
}
triggers = append(triggers, containerTriggers...)
template.Containers = append(template.Containers, *c)
if cmd, ok := r.Images[i].Command(); ok {
imageapi.SetContainerImageEntrypointAnnotation(annotations, c.Name, cmd)
}
}
// Create EmptyDir volumes for all container volume mounts
for _, c := range template.Containers {
for _, v := range c.VolumeMounts {
template.Volumes = append(template.Volumes, kapi.Volume{
Name: v.Name,
VolumeSource: kapi.VolumeSource{
EmptyDir: &kapi.EmptyDirVolumeSource{Medium: kapi.StorageMediumDefault},
},
})
}
}
for i := range template.Containers {
template.Containers[i].Env = append(template.Containers[i].Env, r.Env.List()...)
}
return &deployapi.DeploymentConfig{
ObjectMeta: kapi.ObjectMeta{
Name: r.Name,
},
Spec: deployapi.DeploymentConfigSpec{
Replicas: 1,
Test: r.AsTest,
Selector: selector,
Template: &kapi.PodTemplateSpec{
ObjectMeta: kapi.ObjectMeta{
Labels: selector,
Annotations: annotations,
},
Spec: template,
},
Triggers: triggers,
},
}, nil
}
// GenerateSecret generates a random secret string
func GenerateSecret(n int) string {
n = n * 3 / 4
b := make([]byte, n)
read, _ := rand.Read(b)
if read != n {
return uuid.NewRandom().String()
}
return base64.URLEncoding.EncodeToString(b)
}
// ContainerPortsFromString extracts sets of port specifications from a comma-delimited string. Each segment
// must be a single port number (container port) or a colon delimited pair of ports (container port and host port).
func ContainerPortsFromString(portString string) ([]kapi.ContainerPort, error) {
ports := []kapi.ContainerPort{}
for _, s := range strings.Split(portString, ",") {
port, ok := checkPortSpecSegment(s)
if !ok {
return nil, fmt.Errorf("%q is not valid: you must specify one (container) or two (container:host) port numbers", s)
}
ports = append(ports, port)
}
return ports, nil
}
func checkPortSpecSegment(s string) (port kapi.ContainerPort, ok bool) {
if strings.Contains(s, ":") {
pair := strings.Split(s, ":")
if len(pair) != 2 {
return
}
container, err := strconv.Atoi(pair[0])
if err != nil {
return
}
host, err := strconv.Atoi(pair[1])
if err != nil {
return
}
return kapi.ContainerPort{ContainerPort: container, HostPort: host}, true
}
container, err := strconv.Atoi(s)
if err != nil {
return
}
return kapi.ContainerPort{ContainerPort: container}, true
}
// LabelsFromSpec turns a set of specs NAME=VALUE or NAME- into a map of labels,
// a remove label list, or an error.
func LabelsFromSpec(spec []string) (map[string]string, []string, error) {
labels := map[string]string{}
var remove []string
for _, labelSpec := range spec {
if strings.Index(labelSpec, "=") != -1 {
parts := strings.Split(labelSpec, "=")
if len(parts) != 2 {
return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)
}
labels[parts[0]] = parts[1]
} else if strings.HasSuffix(labelSpec, "-") {
remove = append(remove, labelSpec[:len(labelSpec)-1])
} else {
return nil, nil, fmt.Errorf("unknown label spec: %s", labelSpec)
}
}
for _, removeLabel := range remove {
if _, found := labels[removeLabel]; found {
return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command")
}
}
return labels, remove, nil
}