/
Kubernetes.groovy
641 lines (530 loc) · 22.2 KB
/
Kubernetes.groovy
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
/*
* Copyright (C) 2015 Original Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.pipeline
import com.cloudbees.groovy.cps.NonCPS
import org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar
import org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate
import org.csanchez.jenkins.plugins.kubernetes.PodEnvVar
import org.csanchez.jenkins.plugins.kubernetes.volumes.ConfigMapVolume
import org.csanchez.jenkins.plugins.kubernetes.volumes.EmptyDirVolume
import org.csanchez.jenkins.plugins.kubernetes.volumes.HostPathVolume
import org.csanchez.jenkins.plugins.kubernetes.volumes.NfsVolume
import org.csanchez.jenkins.plugins.kubernetes.volumes.PersistentVolumeClaim
import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume
import org.csanchez.jenkins.plugins.kubernetes.volumes.SecretVolume
import java.util.regex.Matcher
import java.util.regex.Pattern
class Kubernetes implements Serializable {
private org.jenkinsci.plugins.workflow.cps.CpsScript script
public final image
public Kubernetes(org.jenkinsci.plugins.workflow.cps.CpsScript script) {
this.script = script
this.image = new Image(this)
}
public Pod pod(String name = "jenkins-pod", String image = "", String serviceAccount = "", String workingDir = "/home/jenkins/workspace") {
Pod pod = new Pod(this)
pod.name = name
return pod
}
public Image image() {
return new Image(this)
}
public Image image(String name) {
return new NamedImage(this, name)
}
public static class Pod implements Serializable {
private final Kubernetes kubernetes
private String name
private List<ContainerTemplate> containers = new ArrayList<>()
private Map<String, String> envVars = new HashMap<>()
private List<PodVolume> volumes = new ArrayList<>()
private Map<String, String> labels = new HashMap<>()
private String serviceAccount
private String nodeSelector
private String workingDir = "/home/jenkins"
Pod(Kubernetes kubernetes) {
this.kubernetes = kubernetes
}
public Pod withName(String name) {
this.name = name
return this
}
@NonCPS
public Container withNewContainer() {
return new Container(this)
}
@NonCPS
private Container getFirstContainer() {
if (containers == null || containers.isEmpty()) {
return this.withNewContainer()
} else {
return new Container(this, containers.remove(0))
}
}
@NonCPS
public Pod withImage(String image) {
return getFirstContainer().withImage(image).done()
}
public Pod withEnvar(String key, String value) {
this.envVars.put(key, value)
return this
}
public Pod withSecret(String mountPath, String secretName) {
volumes.add(new SecretVolume(mountPath, secretName))
return this
}
public Pod withConfigMap(String mountPath, String configMapName) {
volumes.add(new ConfigMapVolume(mountPath, configMapName))
return this
}
public Pod withHostPath(String mountPath, String hostPath) {
volumes.add(new HostPathVolume(hostPath, mountPath))
return this
}
public Pod withVolumeClaim(String mountPath, String claimName, Boolean readOnly) {
volumes.add(new PersistentVolumeClaim(mountPath, claimName, readOnly))
return this
}
public Pod withNfs(String mountPath, String serverAddress, String serverPath, Boolean readOnly) {
volumes.add(new NfsVolume(serverAddress, serverPath, readOnly, mountPath))
return this
}
public Pod withEmptyDir(String mountPath, Boolean memory) {
volumes.add(new EmptyDirVolume(mountPath, memory))
return this
}
public Pod withServiceAccount(String serviceAccount) {
this.serviceAccount = serviceAccount
return this
}
public Pod nodeSelector(String nodeSelector) {
this.nodeSelector = nodeSelector
return this
}
public Pod workingDir(String workingDir) {
this.workingDir = workingDir
return this
}
public Pod withLabel(String name, String value) {
this.labels.put(name, value)
return this
}
public <V> V inside(def container = "", Closure<V> body) {
def label = "" + container + "${kubernetes.script.env.JOB_NAME}_${kubernetes.script.env.BUILD_NUMBER}".replaceAll('[^A-Za-z0-9]', '_')
List<PodEnvVar> podEnvVars = new ArrayList<>()
for (Map.Entry<String, String> entry : envVars.entrySet()) {
podEnvVars.add(new PodEnvVar(entry.getKey(), entry.getValue()))
}
kubernetes.script.podTemplate(name: name, label: label, containers: containers, envVars: podEnvVars, volumes: volumes, serviceAccount: serviceAccount, nodeSelector: nodeSelector, labels: labels) {
kubernetes.script.node(label) {
if (container != null && !container.isEmpty()) {
kubernetes.script.container(name: container) {
body()
}
} else if (containers.size() == 1) {
String name = containers.get(0).name
kubernetes.script.container(name: name) {
body()
}
} else {
body()
}
}
}
}
}
public static class Container implements Serializable {
private static final Pattern IMAGE_REGEX = Pattern.compile("(?:.+/)?(?<name>[^:]+)(?::.+)?")
private static final String FALLBACK_CONTAINER_NAME = "buildcnt"
private transient Pod pod
private String name
private String image
private Boolean privileged = false
private Boolean alwaysPullImage = false
private String workingDir = "/home/jenkins"
private String command = "/bin/sh -c"
private String args = "cat"
private Boolean ttyEnabled = true
private String resourceRequestCpu
private String resourceRequestMemory
private String resourceLimitCpu
private String resourceLimitMemory
private transient Map<String, String> envVars = new HashMap<>()
public Container (Pod pod) {
this.pod = pod
}
public Container (Pod pod, ContainerTemplate c) {
this(pod, c.name, c.image, c.alwaysPullImage, c.workingDir, c.command, c.args,
c.ttyEnabled, c.resourceRequestCpu, c.resourceRequestMemory,
c.resourceLimitCpu, c.resourceLimitMemory, c.envVars)
}
public Container(Pod pod, String name, String image, Boolean alwaysPullImage, Boolean privileged, String workingDir, String command, String args, Boolean ttyEnabled, String resourceRequestCpu, String resourceRequestMemory, String resourceLimitCpu, String resourceLimitMemory, Map<String, String> envVars) {
this.pod = pod
this.name = name
this.image = image
this.privileged = privileged
this.alwaysPullImage = alwaysPullImage
this.workingDir = workingDir
this.command = command
this.args = args
this.ttyEnabled = ttyEnabled
this.resourceRequestCpu = resourceRequestCpu
this.resourceRequestMemory = resourceRequestMemory
this.resourceLimitCpu = resourceLimitCpu
this.resourceLimitMemory = resourceLimitMemory
this.envVars = envVars
}
@NonCPS
public Container withName(String name) {
this.name = name
return this
}
@NonCPS
public Container withImage(String image) {
this.image = image
return this
}
@NonCPS
public Container withPrivileged(Boolean privileged) {
this.privileged = privileged
return this
}
@NonCPS
public Container withPrivileged() {
this.privileged = true
return this
}
@NonCPS
public Container withAlwaysPullImage(Boolean alwaysPullImage) {
this.alwaysPullImage = alwaysPullImage
return this
}
@NonCPS
public Container withAlwaysPullImage() {
this.alwaysPullImage = true
return this
}
@NonCPS
public Container withWorkingDir(String workingDir) {
this.workingDir = workingDir
return this
}
@NonCPS
public Container withCommand(String command) {
this.command = command
return this
}
@NonCPS
public Container withArgs(String args) {
this.args = args
return this
}
@NonCPS
public Container withTtyEnabled(Boolean ttyEnabled) {
this.ttyEnabled = ttyEnabled
return this
}
@NonCPS
public Container withTtyEnabled() {
this.ttyEnabled = true
return this
}
@NonCPS
public Container withTtyDisabled() {
this.ttyEnabled = false
return this
}
@NonCPS
public Container withResourceRequestCpu(String resourceRequestCpu) {
this.resourceRequestCpu
return this
}
@NonCPS
public Container withResourceRequestMemory(String resourceRequestMemory) {
this.resourceLimitMemory
return this
}
@NonCPS
public Container withResourceLimitCpu(String resourceLimitCpu) {
this.resourceLimitCpu = resourceLimitMemory
return this
}
@NonCPS
public Container withResourceLimitMemory(String resourceLimitMemory) {
this.resourceLimitMemory = resourceLimitMemory
return this
}
@NonCPS
public Container withEnvar(String key, String value) {
this.envVars.put(key, value)
return this
}
@NonCPS
private ContainerTemplate asTemplate() {
def containerEnvVars = new ArrayList<>()
for (Map.Entry<String, String> entry : envVars.entrySet()) {
containerEnvVars.add(new ContainerEnvVar(entry.getKey(), entry.getValue()))
}
String containerName = name != null && !name.isEmpty() ? name : imageName(image, FALLBACK_CONTAINER_NAME)
ContainerTemplate template = new ContainerTemplate(containerName, image)
template.setAlwaysPullImage(alwaysPullImage)
template.setCommand(command)
template.setArgs(args)
template.setTtyEnabled(ttyEnabled)
template.setEnvVars(containerEnvVars)
template.setPrivileged(privileged)
template.setResourceRequestCpu(resourceRequestCpu)
template.setResourceRequestMemory(resourceRequestMemory)
template.setResourceLimitCpu(resourceLimitCpu)
template.setResourceLimitMemory(resourceRequestMemory)
return template
}
@NonCPS
public Pod done() {
pod.containers.add(asTemplate())
return pod
}
//Just added for the shake of readability
@NonCPS
public Pod and() {
pod.containers.add(asTemplate())
return pod
}
@NonCPS
public <V> V inside(Closure<V> body) {
return done().inside(container: name, body)
}
/**
* Extracts the image name out of the full tag (removes repo and version).
* @param fullName The full name of the image.
* @param fallbackValue The fallback value to use.
* @return The image name, if found, the fallbackValue otherwise.
*/
@NonCPS //For reasons, beyond my understanding, this annotation needs to be here.
private static String imageName(String fullName, String fallbackValue) {
try {
Matcher matcher = IMAGE_REGEX.matcher(fullName)
if (!matcher.find()) {
return fallbackValue
}
String name = matcher.group("name")
return name != null && !name.isEmpty() ? name : fallbackValue
} catch (Throwable t) {
return fallbackValue
}
}
}
public class Image implements Serializable {
private final Kubernetes kubernetes
Image(Kubernetes kubernetes) {
this.kubernetes = kubernetes
}
//Shortcut to build
Pod build(String name, String path = ".", boolean rm = false, long timeout = 600000L) {
this.withName(name)
.build()
.withTimeout(timeout)
.removingIntermediate(rm)
.fromPath(path)
}
//Shortcut to tag
void tag(String name, String tag, String repo = "") {
this.withName(name)
.tag()
.inRepository(repo != null && !repo.isEmpty() ? repo : name)
.withTag(tag)
}
//Shortcut to push
void push(String name, String tagName = "latest", long timeout = 600000L) {
this.withName(name)
.push()
.withTimeout(timeout)
.withTag(tagName)
.toRegistry()
}
NamedImage withName(String name) {
return new NamedImage(kubernetes, name)
}
}
private static class NamedImage implements Serializable {
private final Kubernetes kubernetes
private final String name
NamedImage(Kubernetes kubernetes, String name) {
this.kubernetes = kubernetes
this.name = name
}
Pod toPod() {
return new Pod(kubernetes).withImage(name)
}
BuildImage build() {
return new BuildImage(kubernetes, name, false, 600000L, null, null, null, new ArrayList<String>())
}
PushImage push() {
return new PushImage(kubernetes, name, null, 600000L, null, null, null)
}
void tag() {
new TagImage(kubernetes, name, null, null, false, null, null, null)
}
}
private static class BuildImage implements Serializable {
private final Kubernetes kubernetes
private final String name
private final Boolean rm
private final long timeout
private final String username
private final String password
private final String email
private final List<String> ignorePatterns
BuildImage(Kubernetes kubernetes, String name, Boolean rm, long timeout, String username, String password, String email, List<String> ignorePatterns) {
this.kubernetes = kubernetes
this.name = name
this.rm = rm
this.timeout = timeout
this.username = username
this.password = password
this.email = email
this.ignorePatterns = ignorePatterns != null ? ignorePatterns : new ArrayList<String>()
}
BuildImage removingIntermediate() {
return removingIntermediate(true)
}
BuildImage removingIntermediate(Boolean rm) {
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, ignorePatterns)
}
BuildImage withTimeout(long timeout) {
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, ignorePatterns)
}
BuildImage withUsername(String username) {
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, ignorePatterns)
}
BuildImage withPassword(String password) {
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, ignorePatterns)
}
BuildImage withEmail(String email) {
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, ignorePatterns)
}
BuildImage ignoringPattern(String pattern) {
List<String> newIgnorePatterns = new ArrayList<>(ignorePatterns)
newIgnorePatterns.add(pattern)
return new BuildImage(kubernetes, name, rm, timeout, username, password, email, newIgnorePatterns)
}
Pod fromPath(String path) {
if (kubernetes.script.env.HOME != null) { // http://unix.stackexchange.com/a/123859/26736
// Already inside a node block.
kubernetes.script.buildImage(name: name, rm: rm, path: path, timeout: timeout, username: username, password: password, email: email, ignorePatterns: ignorePatterns)
} else {
kubernetes.script.node {
kubernetes.script.buildImage(name: name, rm: rm, path: path, timeout: timeout, username: username, password: password, email: email, ignorePatterns: ignorePatterns)
}
}
return new NamedImage(kubernetes, name).toPod()
}
}
private static class TagImage implements Serializable {
private final Kubernetes kubernetes
private final String name
private final String repo
private final String tagName
private final Boolean force
private final String username
private final String password
private final String email
TagImage(Kubernetes kubernetes, String name, String repo, String tagName, Boolean force, String username, String password, String email) {
this.kubernetes = kubernetes
this.name = name
this.repo = repo
this.tagName = tagName
this.force = force
this.username = username
this.password = password
this.email = email
}
TagImage inRepository(String repo) {
return new TagImage(kubernetes, name, repo, tagName, force, username, password, email)
}
TagImage force() {
return new TagImage(kubernetes, name, repo, tagName, true, username, password, email)
}
TagImage withUsername(String username) {
return new TagImage(kubernetes, name, repo, tagName, force, username, password, email)
}
TagImage withPassword(String password) {
return new TagImage(kubernetes, name, repo, tagName, force, username, password, email)
}
TagImage withEmail(String email) {
return new TagImage(kubernetes, name, repo, tagName, force, username, password, email)
}
void withTag(String tagName) {
if (kubernetes.script.env.HOME != null) { // http://unix.stackexchange.com/a/123859/26736
// Already inside a node block.
kubernetes.script.tagImage(name: name, repo: repo, tag: tagName, force: force, username: username, password: password, email: email)
} else {
kubernetes.script.node {
kubernetes.script.tagImage(name: name, repo: repo, tag: tagName, force: force, username: username, password: password, email: email)
}
}
}
}
private static class PushImage implements Serializable {
private final Kubernetes kubernetes
private final String name
private final String tagName
private final long timeout
private final String username
private final String password
private final String email
PushImage(Kubernetes kubernetes, String name, String tagName, long timeout, String username, String password, String email) {
this.kubernetes = kubernetes
this.name = name
this.tagName = tagName
this.timeout = timeout
this.username = username
this.password = password
this.email = email
}
PushImage force() {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
PushImage withTag(String tagName) {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
PushImage withTimeout(long timeout) {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
PushImage withUsername(String username) {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
PushImage withPassword(String password) {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
PushImage withEmail(String email) {
return new PushImage(kubernetes, name, tagName, timeout, username, password, email)
}
void toRegistry(String registry) {
if (kubernetes.script.env.HOME != null) { // http://unix.stackexchange.com/a/123859/26736
// Already inside a node block.
kubernetes.script.pushImage(name: name, tagName: tagName, timeout: timeout, registry: registry, username: username, password: password, email: email)
} else {
kubernetes.script.node {
kubernetes.script.pushImage(name: name, tagName: tagName, timeout: timeout, registry: registry, username: username, password: password, email: email)
}
}
}
void toRegistry() {
toRegistry('')
}
}
}