-
Notifications
You must be signed in to change notification settings - Fork 57
/
OpenShiftService.groovy
1452 lines (1343 loc) · 60.2 KB
/
OpenShiftService.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
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 org.ods.services
import com.cloudbees.groovy.cps.NonCPS
import groovy.json.JsonOutput
import groovy.json.JsonSlurperClassic
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
import org.ods.util.ILogger
import org.ods.util.IPipelineSteps
import org.ods.util.PodData
@SuppressWarnings(['ClassSize', 'MethodCount'])
@TypeChecked
class OpenShiftService {
static final String EXPORTED_TEMPLATE_FILE = 'template.yml'
static final String ROLLOUT_COMPLETE = 'complete'
static final String ROLLOUT_WAITING = 'waiting'
static final String DEPLOYMENTCONFIG_KIND = 'DeploymentConfig'
static final String DEPLOYMENT_KIND = 'Deployment'
private final IPipelineSteps steps
private final ILogger logger
OpenShiftService(IPipelineSteps steps, ILogger logger) {
this.steps = steps
this.logger = logger
}
static void createProject(IPipelineSteps steps, String name) {
steps.sh(
script: "oc new-project ${name}",
label: "Create new OpenShift project ${name}"
)
}
static void loginToExternalCluster(IPipelineSteps steps, String apiUrl, String apiToken) {
steps.sh(
script: "oc login ${apiUrl} --token=${apiToken} >& /dev/null",
label: "login to external cluster (${apiUrl})"
)
}
static String getApiUrl(IPipelineSteps steps) {
steps.sh(
script: 'oc whoami --show-server',
label: 'Get OpenShift API server URL',
returnStdout: true
).toString().trim()
}
static String getConsoleUrl(IPipelineSteps steps) {
String routeUrl = steps.sh(
script: 'oc whoami --show-console',
label: 'Get OpenShift Console URL',
returnStdout: true
)
if (!routeUrl) {
throw new RuntimeException ("Cannot get cluster console url!")
}
return routeUrl.trim()
}
static boolean tooManyEnvironments(IPipelineSteps steps, String projectId, Integer limit) {
steps.sh(
returnStdout: true,
script: "oc projects | grep '^\\s*${projectId}-' | wc -l",
label: "check ocp environment maximum for '${projectId}-*'"
).toString().trim().toInteger() >= limit
}
static boolean envExists(IPipelineSteps steps, String project) {
def exists = steps.sh(
script: "oc project ${project} &> /dev/null",
label: "Check if OpenShift project '${project}' exists",
returnStatus: true
) == 0
steps.echo("OpenShift project '${project}' ${exists ? 'exists' : 'does not exist'}")
exists
}
static String getApplicationDomain(IPipelineSteps steps) {
def routeUrl = getConsoleUrl(steps)
def routePrefixLength = routeUrl.indexOf('.')
if (routePrefixLength < 0) {
throw new RuntimeException ("Route does not contain a dot: ${routeUrl}")
}
def openShiftPublicHost = routeUrl[routePrefixLength+1..-1]
return openShiftPublicHost
}
static String getImageReference(IPipelineSteps steps, String project, String name, String tag) {
steps.sh(
returnStdout: true,
script: "oc -n ${project} get istag ${name}:${tag} -o jsonpath='{.image.dockerImageReference}'",
label: "Get image reference of ${name}:${tag}"
).toString().trim()
}
boolean imageExists(String project, String name, String tag) {
steps.sh(
returnStatus: true,
script: "oc -n ${project} get istag ${name}:${tag} &> /dev/null",
label: "Check existance of image ${name}:${tag}"
) == 0
}
boolean envExists(String project) {
envExists(steps, project)
}
String getApiUrl() {
getApiUrl(steps)
}
// helmUpgrade installs given "release" into "project" from the chart
// located in the working directory. If "withDiff" is true, a diff is
// performed beforehand.
@SuppressWarnings(['ParameterCount', 'LineLength'])
void helmUpgrade(
String project,
String release,
List<String> valuesFiles,
Map<String, String> values,
List<String> defaultFlags,
List<String> additionalFlags,
boolean withDiff) {
def upgradeFlags = defaultFlags.collect { it }
additionalFlags.collect { upgradeFlags << it }
valuesFiles.collect { upgradeFlags << "-f ${it}".toString() }
values.collect { k, v -> upgradeFlags << "--set ${k}=${v}".toString() }
if (withDiff) {
def diffFlags = upgradeFlags.findAll { it }
diffFlags << '--no-color'
diffFlags << '--three-way-merge'
diffFlags << '--normalize-manifests'
// diffFlags << '--detailed-exitcode'
steps.sh(
script: "HELM_DIFF_IGNORE_UNKNOWN_FLAGS=true helm -n ${project} secrets diff upgrade ${diffFlags.join(' ')} ${release} ./",
label: "Show diff explaining what helm upgrade would change for release ${release} in ${project}"
)
}
def failed = steps.sh(
script: "helm -n ${project} secrets upgrade ${upgradeFlags.join(' ')} ${release} ./",
label: "Upgrade Helm release ${release} in ${project}",
returnStatus: true
)
if (failed) {
throw new RuntimeException(
'Rollout Failed!. ' +
"Helm could not install the ${release} in ${project}"
)
}
}
@SuppressWarnings(['LineLength', 'ParameterCount'])
void tailorApply(String project, Map<String, String> target, String paramFile, List<String> params, List<String> preserve, String tailorPrivateKeyFile, boolean verify) {
def verifyFlag = verify ? '--verify' : ''
def tailorPrivateKeyFlag = tailorPrivateKeyFile ? "--private-key ${tailorPrivateKeyFile}" : ''
def selectorFlag = target.selector ? "--selector ${target.selector}" : ''
def excludeFlag = target.exclude ? "--exclude ${target.exclude}" : ''
def includeArg = target.include ?: ''
def paramFileFlag = paramFile ? "--param-file ${paramFile}" : ''
params << "ODS_OPENSHIFT_APP_DOMAIN=${getApplicationDomain()}".toString()
def paramFlags = params.collect { "--param ${it}" }.join(' ')
def preserveFlags = preserve.collect { "--preserve ${it}" }.join(' ')
doTailorApply(project, "${selectorFlag} ${excludeFlag} ${paramFlags} ${preserveFlags} ${paramFileFlag} ${tailorPrivateKeyFlag} ${verifyFlag} --ignore-unknown-parameters ${includeArg}")
}
void tailorExport(String project, String selector, Map<String, String> envParams, String targetFile) {
doTailorExport(project, "-l ${selector}", envParams, targetFile)
}
String rollout(String project, String kind, String name, int priorRevision, int timeoutMinutes) {
def revision = getRevision(project, kind, name)
if (revision > priorRevision) {
logger.info "Rollout of deployment for '${name}' has been triggered automatically."
} else {
if (kind == OpenShiftService.DEPLOYMENTCONFIG_KIND) {
startRollout(project, name, revision)
} else {
restartRollout(project, name, revision)
}
}
watchRollout(project, kind, name, timeoutMinutes)
}
// watchRollout watches the rollout of either a DeploymentConfig or a Deployment resource.
// It returns the name of the respective "pod manager", which is either a ReplicationController
// (in the case of kind=DeploymentConfig) or a ReplicaSet (for kind=Deployment).
String watchRollout(String project, String kind, String name, int timeoutMinutes) {
def podManagerKind = getPodManagerKind(kind)
try {
steps.timeout(time: timeoutMinutes) {
logger.startClocked("${name}-watch-rollout".toString())
doWatchRollout(project, kind, name)
logger.debugClocked("${name}-watch-rollout".toString(), (null as String))
}
} catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) {
def revision = getRevision(project, kind, name)
def podManagerName = getPodManagerName(project, kind, name, revision)
throw new RuntimeException(
'Rollout timed out. ' +
"Observed related event messages:\n${getRolloutEventMessages(project, podManagerKind, podManagerName)}"
)
}
def revision = getRevision(project, kind, name)
def podManagerName = getPodManagerName(project, kind, name, revision)
def rolloutStatus = getRolloutStatus(project, kind, podManagerName)
if (rolloutStatus != ROLLOUT_COMPLETE) {
throw new RuntimeException(
"Rollout #${revision} failed with status '${rolloutStatus}'. " +
"Observed related event messages:\n${getRolloutEventMessages(project, podManagerKind, podManagerName)}"
)
} else {
logger.info "Rollout #${revision} of ${kind} '${name}' successful."
}
podManagerName
}
int getRevision(String project, String kind, String name) {
String revision
if (kind == DEPLOYMENTCONFIG_KIND) {
revision = steps.sh(
script: "oc -n ${project} get ${kind}/${name} -o jsonpath='{.status.latestVersion}'",
label: "Get latest version of ${kind}/${name}",
returnStdout: true
).toString().trim()
} else {
def jsonPath = '{.metadata.annotations.deployment\\.kubernetes\\.io/revision}'
revision = steps.sh(
script: "oc -n ${project} get ${kind}/${name} -o jsonpath='${jsonPath}'",
label: "Get revision of ${kind}/${name}",
returnStdout: true
).toString().trim()
}
if (!revision.isInteger()) {
throw new RuntimeException(
"ERROR: Latest version of ${kind} '${name}' is not a number: '${revision}"
)
}
revision as int
}
// getRolloutStatus queries the state of the rollout for given kind/name.
// It returns either "complete" or some other (temporary) state, e.g. "waiting".
@TypeChecked(TypeCheckingMode.SKIP)
@SuppressWarnings('LineLength')
String getRolloutStatus(String project, String kind, String name) {
if (kind == DEPLOYMENTCONFIG_KIND) {
def jsonPath = '{.metadata.annotations.openshift\\.io/deployment\\.phase}'
return getJSONPath(project, 'rc', name, jsonPath).toLowerCase()
}
// Logic for Deployment resources is taken from:
// https://github.com/kubernetes/kubernetes/blob/2e57e54fa6a251826a14ed365a12c99faa3a93be/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollout_status.go#L89.
// However, we look at the ReplicaSetStatus because that will tell us if
// the specific rollout we're interested in is successful or not. It
// could be that some other process has trigger another rollout which
// cancelled "our" rollout.
// Documentation of the ReplicaSetStatus is at:
// https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#replicasetstatus-v1-apps
def rsJSON = getJSON(project, 'rs', name)
def status = rsJSON.status
if (!status.replicas) {
return ROLLOUT_WAITING // Deployment spec update not observed... (should never happen)
}
if (status.fullyLabeledReplicas < status.replicas) {
return ROLLOUT_WAITING // Not enough pods with matching labels yet
}
if (status.availableReplicas < status.replicas) {
return ROLLOUT_WAITING // Not enough pods available yet
}
ROLLOUT_COMPLETE // deployment successfully rolled out
}
void setImageTag(String project, String name, String sourceTag, String destinationTag) {
steps.sh(
script: "oc -n ${project} tag ${name}:${sourceTag} ${name}:${destinationTag}",
label: "Set tag ${destinationTag} on is/${name}"
)
}
boolean resourceExists(String project, String kind, String name) {
steps.sh(
script: "oc -n ${project} get ${kind}/${name} &> /dev/null",
returnStatus: true,
label: "Check existance of ${kind} ${name}"
) == 0
}
int startBuild(String project, String name, String dir) {
steps.sh(
script: "oc -n ${project} start-build ${name} --from-dir ${dir} ${logger.ocDebugFlag}",
label: "Start Openshift build ${name}",
returnStdout: true
).toString().trim()
return getLastBuildVersion(project, name)
}
String followBuild(String project, String name, int version) {
steps.sh(
script: "oc -n ${project} logs -f --version=${version} bc/${name}",
label: "Logs of Openshift build ${name}",
returnStdout: true
).toString().trim()
}
int getLastBuildVersion(String project, String name) {
def versionNumber = steps.sh(
returnStdout: true,
script: "oc -n ${project} get bc/${name} -o jsonpath='{.status.lastVersion}'",
label: "Get lastVersion of BuildConfig ${name}"
).toString().trim()
if (!versionNumber.isInteger()) {
throw new RuntimeException(
"ERROR: Last version of BuildConfig '${name}' is not a number: '${versionNumber}"
)
}
versionNumber as int
}
String getBuildStatus(String project, String buildId, int retries) {
def buildStatus = 'unknown'
for (def i = 0; i < retries; i++) {
buildStatus = checkForBuildStatus(project, buildId)
logger.debug ("Build: '${buildId}' - status: '${buildStatus}'")
if (buildStatus == 'complete') {
return buildStatus
}
// Wait 12 seconds before asking again. Sometimes the build finishes but the
// status is not set to "complete" immediately ...
steps.sleep(12)
}
return buildStatus
}
@SuppressWarnings('LineLength')
void patchBuildConfig(String project, String name, String tag, Map buildArgs, Map imageLabels) {
def odsImageLabels = []
for (def key : imageLabels.keySet()) {
odsImageLabels << """{"name": "${key}", "value": "${imageLabels[key]}"}"""
}
// Normally we want to replace the imageLabels, but in case they are not
// present yet, we need to add them this time.
def imageLabelsOp = 'replace'
def imageLabelsValue = steps.sh(
script: "oc -n ${project} get bc/${name} -o jsonpath='{.spec.output.imageLabels}'",
returnStdout: true,
label: 'Test existance of path .spec.output.imageLabels'
).toString().trim()
if (imageLabelsValue.length() == 0) {
imageLabelsOp = 'add'
}
def patches = [
'{"op": "replace", "path": "/spec/source", "value": {"type":"Binary"}}',
"""{"op": "replace", "path": "/spec/output/to/name", "value": "${name}:${tag}"}""",
"""{"op": "${imageLabelsOp}", "path": "/spec/output/imageLabels", "value": [
${odsImageLabels.join(',')}
]}""",
]
// Add build args
def buildArgsItems = []
for (def key : buildArgs.keySet()) {
def val = buildArgs[key]
buildArgsItems << """{"name": "${key}", "value": "${val}"}"""
}
if (buildArgsItems.size() > 0) {
def buildArgsPatch = """{"op": "replace", "path": "/spec/strategy/dockerStrategy/buildArgs", "value": [${buildArgsItems.join(',')}]}"""
patches << buildArgsPatch
}
steps.sh(
script: """oc -n ${project} patch bc ${name} --type=json --patch '[${patches.join(',')}]' ${logger.ocDebugFlag} """,
label: "Patch BuildConfig ${name}"
)
}
String getImageReference(String project, String name, String tag) {
getImageReference(steps, project, name, tag)
}
void importImageTagFromProject(
String project,
String name,
String sourceProject,
String sourceTag,
String targetTag) {
importImageFromProject(project, sourceProject, "${name}:${sourceTag}", "${name}:${targetTag}")
}
@SuppressWarnings('ParameterCount')
void importImageTagFromSourceRegistry(
String project,
String name,
String sourceRegistrySecret,
String sourceProject,
String sourceTag,
String targetTag) {
importImageFromSourceRegistry(
project, sourceRegistrySecret, sourceProject, "${name}:${sourceTag}", "${name}:${targetTag}"
)
}
void importImageShaFromProject(
String project,
String name,
String sourceProject,
String imageSha,
String imageTag) {
importImageFromProject(project, sourceProject, "${name}@${imageSha}", "${name}:${imageTag}")
}
@SuppressWarnings('ParameterCount')
void importImageShaFromSourceRegistry(
String project,
String name,
String sourceRegistrySecret,
String sourceProject,
String imageSha,
String imageTag) {
importImageFromSourceRegistry(
project, sourceRegistrySecret, sourceProject, "${name}@${imageSha}", "${name}:${imageTag}"
)
}
// Returns data about the pods (replicas) of the deployment.
// If not all pods are running until the retries are exhausted,
// an exception is thrown.
List<PodData> getPodDataForDeployment(String project, String kind, String podManagerName, int retries) {
if (kind in [DEPLOYMENTCONFIG_KIND, DEPLOYMENT_KIND]
&& getDesiredReplicas(project, kind, podManagerName) < 1) {
return retrieveImageData(project, kind, podManagerName)
}
def label = getPodLabelForPodManager(project, kind, podManagerName)
for (def i = 0; i < retries; i++) {
def podData = checkForPodData(project, label)
if (podData) {
return podData
}
steps.echo("Could not find 'running' pod(s) with label '${label}' - waiting")
steps.sleep(12)
}
throw new RuntimeException("Could not find 'running' pod(s) with label '${label}'")
}
// getResourcesForComponent returns a map in which each kind is mapped to a list of resources.
Map<String, List<String>> getResourcesForComponent(String project, List<String> kinds, String selector) {
def items = steps.sh(
script: """oc -n ${project} get ${kinds.join(',')} \
-l ${selector} \
-o template='{{range .items}}{{.kind}}:{{.metadata.name}} {{end}}'""",
returnStdout: true,
label: "Getting all ${kinds.join(',')} names for selector '${selector}'"
).toString().trim().tokenize(' ')
Map<String, List<String>> m = [:]
items.each {
def parts = it.split(':')
if (!m.containsKey(parts[0])) {
m[parts[0]] = []
}
m[parts[0]] << parts[1]
}
m
}
String getApplicationDomain() {
getApplicationDomain(steps)
}
// imageInfoForImageUrl expects an image URL like one of the following:
// 172.30.21.196:5000/foo/bar:2-3ec425bc
// 172.30.21.196:5000/foo/bar@sha256:eec4a4451a307bd1fa44bde6642077a3c2a722e0ad370c1c22fcebcd8d4efd33
// The registry part is optional.
//
// It returns a map with image parts:
// - registry (empty if not specified)
// - repository (= OpenShift project in case of image from ImageStream)
// - name (= ImageStream name in case of image from ImageStream)
Map<String, String> imageInfoForImageUrl(String url) {
def imageInfo = [:]
def urlParts = url.split('/').toList()
if (urlParts.size() < 2) {
logger.debug "Image URL ${url} does not define the repository explicitly."
imageInfo.repository = ''
} else {
imageInfo.repository = urlParts[-2]
}
if (urlParts.size() > 2) {
imageInfo.registry = urlParts[-3]
} else {
logger.debug "Image URL ${url} does not define the registry explicitly."
imageInfo.registry = ''
}
if (urlParts[-1].contains('@')) {
def shaParts = urlParts[-1].split('@').toList()
imageInfo.name = shaParts[0]
} else {
def tagParts = urlParts[-1].split(':').toList()
imageInfo.name = tagParts[0]
}
imageInfo
}
// imageInfoWithShaForImageStreamUrl expects an image URL like one of the following:
// 172.30.21.196:5000/foo/bar:2-3ec425bc
// 172.30.21.196:5000/foo/bar@sha256:eec4a4451a307bd1fa44bde6642077a3c2a722e0ad370c1c22fcebcd8d4efd33
// The registry part is optional.
//
// It returns a map with image parts:
// - registry (empty if not specified)
// - repository (= OpenShift project in case of image from ImageStream)
// - name (= ImageStream name in case of image from ImageStream)
// - sha (= sha256:<sha-identifier>)
// - shaStripped (= <sha-identifier>)
Map<String, String> imageInfoWithShaForImageStreamUrl(String imageStreamUrl) {
def urlParts = imageStreamUrl.split('/').toList()
if (urlParts.size() < 2) {
throw new RuntimeException(
"ERROR: Image URL ${imageStreamUrl} must have at least two parts (repository/reference)"
)
}
if (urlParts[-1].contains('@sha256:')) {
return imageInfoWithSha(urlParts)
}
// If the imageStreamUrl contains a tag, we resolve it to a SHA.
def tagParts = urlParts[-1].split(':')
if (tagParts.size() != 2) {
throw new RuntimeException(
"ERROR: Image reference ${urlParts[2]} does not consist of two parts (name:tag)"
)
}
def shaUrl = getImageReference(urlParts[-2], tagParts[0], tagParts[1])
imageInfoWithSha(shaUrl.split('/').toList())
}
List<Map<String, String>> getImagesOfDeployment(String project, String kind, String name) {
steps.sh(
script: "oc -n ${project} get ${kind} ${name} -o jsonpath='{.spec.template.spec.containers[*].image}'",
label: "Get container images for ${kind} ${name}",
returnStdout: true
).toString().trim().tokenize(' ').collect { imageInfoForImageUrl(it) }
}
String getOriginUrlFromBuildConfig(String project, String bcName) {
return steps.sh(
script: "oc -n ${project} get bc/${bcName} -o jsonpath='{.spec.source.git.uri}'",
returnStdout: true,
label: "Get origin from BuildConfig ${bcName}"
).toString().trim()
}
Map getPodDataForDeployments(String project, String kind, List<String> deploymentNames) {
Map pods = [:]
deploymentNames.each { name ->
Map pod = [:]
logger.debug("Verifying images of ${kind} '${name}'")
int revision = 0
try {
revision = getRevision(project, kind, name)
} catch (err) {
logger.debug("${kind} '${name}' does not exist!")
}
if (revision < 1) {
logger.debug("No revision of ${kind} '${name}' found")
} else {
def podManagerName = getPodManagerName(project, kind, name, revision)
def podData = getPodDataForDeployment(
project, kind, podManagerName, 5
)
// TODO: Once the orchestration pipeline can deal with multiple replicas,
// update this to return multiple pods.
pod = podData[0].toMap()
}
pods[name] = pod
}
pods
}
boolean areImageShasUpToDate(Map defData, Map podData) {
defData.containers.every { String containerName, String definedImage ->
verifyImageSha(containerName, definedImage, podData.containers[containerName].toString())
}
}
boolean verifyImageSha(String containerName, String definedImage, String actualImageRaw) {
logger.debug("Verifiying image of container '${containerName}' ...")
def runningImageSha = imageInfoWithShaForImageStreamUrl(actualImageRaw).sha
def definedImageSha = definedImage.split('@').last()
if (runningImageSha != definedImageSha) {
logger.debug(
"Container '${containerName}' is using image '${runningImageSha}' " +
"which differs from defined image '${definedImageSha}'."
)
return false
}
logger.debug("Container '${containerName}' is using defined image '${definedImageSha}'.")
true
}
// findOrCreateBuildConfig searches for a BuildConfig with "name" in "project",
// and if none is found, it creates one.
void findOrCreateBuildConfig(String project, String name, Map<String, String> labels = [:], String tag = "latest") {
if (!resourceExists(project, 'BuildConfig', name)) {
createBuildConfig(project, name, labels, tag)
}
}
// findOrCreateImageStream searches for a ImageStream with "name" in "project",
// and if none is found, it creates one.
void findOrCreateImageStream(String project, String name, Map<String, String> labels = [:]) {
if (!resourceExists(project, 'ImageStream', name)) {
createImageStream(project, name, labels)
}
}
/**
* Apply labels provided in <code>labels</code> to resources given in <code>resources</code> (format kind/name).
* The selection can be restricted to a project and also with a label selector given in <code>selector</code>.
* You can apply labels to all object kinds with <code>resources=all</code> and using a selector.
* If the label already exists, it will be overwritten.
* If the value for one label is the empty string, the label will be set with an empty string as value.
* If the value for one label is null, the label will be deleted from the selected resources.
*
* Allowed selector conditions are:
* <code>label=value</code>
* <code>label==value</code>
* <code>label!=value</code>
* More than one condition can be specified, separated by commas.
*
* @param project the project to apply the operation to. The current project, if null.
* @param resources the resources to apply the labels to, with format <code>kind[/name]</code>.
* @param labels a <code>Map</code> containing label keys and values.
* @param selector a comma-separated list of label conditions.
* @return the output of the shell script running the OpenShift client command.
* @throws IllegalArgumentException if no <code>resources</code> or no <code>labels</code> are provided.
*/
String labelResources(String project, String resources, Map<String, String> labels, String selector = null) {
if (!resources) {
throw new IllegalArgumentException('You must specify the resources to label')
}
if (!labels) {
throw new IllegalArgumentException('At least one label update is required')
}
def labelStr = labels.collect { key, value ->
def label = key
label += value == null ? '-' : "='${value}'"
return label
}.join(' ')
if (logger.getDebugMode()) {
logger.debug("Setting labels ${labelStr} to resources ${resources} selected by ${selector}")
}
def script = "oc label --overwrite ${resources} "
if (selector) {
script += "-l ${selector} "
}
if (project) {
script += "-n ${project} "
}
script += labelStr
def scriptLabel = "Set labels to ${resources}"
if (selector) {
scriptLabel += " selected by the following labels: ${selector}"
}
steps.sh(
script: script,
label: scriptLabel,
returnStdout: true
).toString().trim()
}
/**
* Mark the provided resource as paused.
* Generally used to pause rollouts for a <code>Deployment</code> or <code>DeploymentConfig</code>.
* No deployments will be triggered until rollouts are resumed.
* The resource can be specified with the syntax <code>type/resource</code> or <code>type resource</code>.
* For example, <code>dc/aDeploymentConfig</code> or <code>deployment aDeployment</code>.
*
* @param resource the resource to be paused.
* @param project the namespace of the resource. Default: <code>null</code> (the current project).
* @return the output of the shell script running the OpenShift client command.
* @throws IllegalArgumentException if no <code>resource</code> is provided.
*/
String pause(String resource, String project = null) {
if (!resource) {
throw new IllegalArgumentException('You must specify the resource to pause')
}
if (logger.getDebugMode()) {
logger.debug("Pausing ${resource}")
}
def script = "oc patch -p '{\"spec\":{\"paused\":true}}' ${resource}"
if (project) {
script += " -n ${project} "
}
def scriptLabel = "Pause ${resource}"
steps.sh(
script: script,
label: scriptLabel,
returnStdout: true
).toString().trim()
}
/**
* Apply the <code>pause</code> method to each resource provided.
*
* @param project the namespace where the resources exist.
* @param resources a <code>Map</code> with the resource names grouped by resource kind.
* @return a <code>List</code> or strings with the output of the <code>pause</code> method for each resource.
*/
List<String> bulkPause(String project, Map<String, List<String>> resources) {
return bulkApply(project, resources, this.&pause)
}
/**
* Apply the <code>pause</code> method to each resource of the given kinds and selected by the given selector.
*
* @param project the namespace where to locate the resources.
* @param kinds the kinds of resources we want to select.
* @param selector a label selector to select the resources.
* @return a <code>List</code> or strings with the output of the <code>pause</code> method for each resource found.
*/
List<String> bulkPause(String project, List<String> kinds, String selector) {
return bulkApply(project, kinds, selector, this.&pause)
}
/**
* Resume a paused resource.
* Generally used to resume rollouts for a <code>Deployment</code> or <code>DeploymentConfig</code>:
* A rollout will be immediately triggered, if the resource has changed while paused.
* Note that, if the state of the resource when resuming is exactly the same as the last time it was paused,
* no rollout will be triggered, no matter the changes it may have suffered while in paused state.
* The resource can be specified with the syntax <code>type/resource</code> or <code>type resource</code>.
* For example, <code>dc/aDeploymentConfig</code> or <code>deployment aDeployment</code>.
*
* @param resource the resource to be resumed.
* @param project the namespace of the resource. Default: <code>null</code> (the current project).
* @return the output of the shell script running the OpenShift client command.
* @throws IllegalArgumentException if no <code>resource</code> is provided.
*/
String resume(String resource, String project = null) {
if (!resource) {
throw new IllegalArgumentException('You must specify the resource to resume')
}
if (logger.getDebugMode()) {
logger.debug("Resuming ${resource}")
}
def script = "oc patch -p '{\"spec\":{\"paused\":false}}' ${resource}"
if (project) {
script += " -n ${project} "
}
def scriptLabel = "Resume ${resource}"
steps.sh(
script: script,
label: scriptLabel,
returnStdout: true
).toString().trim()
}
/**
* Apply the <code>resume</code> method to each resource provided.
*
* @param project the namespace where the resources exist.
* @param resources a <code>Map</code> with the resource names grouped by resource kind.
* @return a <code>List</code> or strings with the output of the <code>resume</code> method for each resource.
*/
List<String> bulkResume(String project, Map<String, List<String>> resources) {
return bulkApply(project, resources, this.&resume)
}
/**
* Apply the <code>resume</code> method to each resource of the given kinds and selected by the given selector.
*
* @param project the namespace where to locate the resources.
* @param kinds the kinds of resources we want to select.
* @param selector a label selector to select the resources.
* @return a <code>List</code> or strings with the output of the <code>resume</code> method for each resource found.
*/
List<String> bulkResume(String project, List<String> kinds, String selector) {
return bulkApply(project, kinds, selector, this.&resume)
}
/**
* Applies a patch to the given resource.
* If the path is specified, it must be the absolute path of some member belonging to the resource definition
* to which the patch is to be applied.
* If any suffix of the path does not exist, all the nested members in the path will be created.
* If the patch is null, the member specified by the path will be removed.
* (Note: This method cannot be used to delete a resource.
* Specifying both a null patch and a null path will raise an exception.)
* Otherwise, the patch will be performed by applying the following rules:
* Any members of the resource not present in the patch will be left untouched.
* Any member in the patch with non-null value and which does not appear in the resource will be added.
* For any members in the patch that also exist in the resource:
* If the value in the patch is <code>null</code>, the member in the resource will be removed.
* If the value in the patch is not a <code>Map</code>, it will replace the value in the resource.
* If the value in the patch is a <code>Map</code>, it will patch the value in the resource in a recursive fashion.
*
* Note that the <code>path</code> parameter is just a convenience.
* The same functionality can be obtained by nesting maps in the <code>patch</code>.
*
* @param resource the resource to patch, with syntax type/resource or type resource.
* @param patch a <code>Map</code> specifying the patch to apply.
* @param path the optional absolute path at which to apply the patch.
* @param project the namespace of the resource. Default: null (the current project).
* @return
*/
String patch(String resource, Map<String, ?> patch, String path = null, String project = null) {
if (!resource) {
throw new IllegalArgumentException('You must specify the resource to path')
}
if (path != null && !path.startsWith('/')) {
throw new IllegalArgumentException("The path must start with a slash. path == '${path}'")
}
if (patch == null && path == null) {
throw new IllegalArgumentException('You must specify either a patch or a path')
}
def fullPatch = patch
if (path) {
path.substring(1).split('/').reverseEach { member ->
fullPatch = [(member): fullPatch]
}
}
def jsonPatch = JsonOutput.toJson(fullPatch)
if (logger.getDebugMode()) {
def namespace = project ?: 'current'
logger.debug("Patching ${resource} in the ${namespace} project with ${jsonPatch}")
}
def script = "oc patch ${resource} --type='merge' -p '${jsonPatch}'"
if (project) {
script += " -n ${project}"
}
def scriptLabel = "Patch ${resource}"
steps.sh(
script: script,
label: scriptLabel,
returnStdout: true
).toString().trim()
}
/**
* Apply the <code>patch</code> method to each resource provided.
*
* @param project the namespace where the resources exist.
* @param resources a <code>Map</code> with the resource names grouped by resource kind.
* @param patch the patch to apply.
* @param path the optional absolute path at which to apply the patch.
* @return a <code>List</code> or strings with the output of the <code>patch</code> method for each resource.
*/
List<String> bulkPatch (
String project,
Map<String, List<String>> resources,
Map<String, ?> patch,
String path = null
) {
def results = []
resources.each { kind, names ->
names.each { name ->
results << this.patch("${kind}/${name}", patch, path, project)
}
}
return results
}
/**
* Apply the <code>patch</code> method to each resource of the given kinds and selected by the given selector.
*
* @param project the namespace where to locate the resources.
* @param kinds the kinds of resources we want to select.
* @param selector a label selector to select the resources.
* @param patch the patch to apply.
* @param path the optional absolute path at which to apply the patch.
* @return a <code>List</code> or strings with the output of the <code>patch</code> method for each resource found.
*/
List<String> bulkPatch (
String project,
List<String> kinds,
String selector,
Map<String, ?> patch,
String path = null
) {
def resources = getResourcesForComponent(project, kinds, selector)
return bulkPatch(project, resources, patch, path)
}
/**
* Apply the given closure to each resource provided.
*
* @param project the namespace where the resources exist.
* @param resources a <code>Map</code> with the resource names grouped by resource kind.
* @return a <code>List</code> or strings with the output of the given closure for each resource.
*/
//TODO Adapt it to admit arbitrary additional parameters to the closure
private List<String> bulkApply(String project, Map<String, List<String>> resources, Closure body) {
def results = []
resources.each { kind, names ->
names.each { name ->
results << body("${kind}/${name}", project)
}
}
return results
}
/**
* Apply the given closure to each resource of the given kinds and selected by the given selector.
*
* @param project the namespace where to locate the resources.
* @param kinds the kinds of resources we want to select.
* @param selector a label selector to select the resources.
* @return a <code>List</code> or strings with the output of the given closure for each resource found.
*/
//TODO Adapt it to admit arbitrary additional parameters to the closure
private List<String> bulkApply(String project, List<String> kinds, String selector, Closure body) {
def resources = getResourcesForComponent(project, kinds, selector)
return bulkApply(project, resources, body)
}
// getConfigMapData returns the data content of given ConfigMap.
Map getConfigMapData(String project, String name) {
getJSON(project, "ConfigMap", name).data as Map
}
private void createBuildConfig(String project, String name, Map<String, String> labels, String tag) {
logger.info "Creating BuildConfig ${name} in ${project} ... "
def bcYml = buildConfigBinaryYml(name, labels, tag)
createResource(project, bcYml)
}
private void createImageStream(String project, String name, Map<String, String> labels) {
logger.info "Creating ImageStream ${name} in ${project} ... "
def isYml = imageStreamYml(name, labels)
createResource(project, isYml)
}
@NonCPS
private String buildConfigBinaryYml(String name, Map<String,String> labels, String tag) {
"""\
apiVersion: build.openshift.io/v1
kind: BuildConfig
metadata:
labels: {${labels.collect { k, v -> "${k}: '${v}'" }.join(', ')}}
name: ${name}
spec:
failedBuildsHistoryLimit: 5
nodeSelector: null
output:
to:
kind: ImageStreamTag
name: ${name}:${tag}
postCommit: {}
resources:
limits:
cpu: '1'
memory: '2Gi'
requests:
cpu: '200m'
memory: '1Gi'
runPolicy: Serial
source:
type: Binary
binary: {}
strategy:
type: Docker
dockerStrategy: {}
successfulBuildsHistoryLimit: 5
""".stripIndent()
}
@NonCPS
private String imageStreamYml(String name, Map<String,String> labels) {
"""\
apiVersion: image.openshift.io/v1
kind: ImageStream
metadata:
labels: {${labels.collect { k, v -> "${k}: '${v}'" }.join(', ')}}
name: ${name}
spec:
lookupPolicy:
local: false
""".stripIndent()
}
private String createResource(String project, String yml) {
def filename = ".${UUID.randomUUID().toString()}.yml"
steps.writeFile(file: filename, text: yml)
steps.sh """
oc -n ${project} create -f ${filename};
rm ${filename}
"""
}
private String getJSONPath(String project, String kind, String name, String jsonPath) {