-
Notifications
You must be signed in to change notification settings - Fork 144
/
OpenShiftDSL.groovy
1848 lines (1615 loc) · 74.2 KB
/
OpenShiftDSL.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 com.openshift.jenkins.plugins
import com.cloudbees.groovy.cps.NonCPS
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.impl.BaseStandardCredentials
import com.openshift.jenkins.plugins.pipeline.OcAction
import com.openshift.jenkins.plugins.pipeline.OcContextInit
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import hudson.AbortException
import hudson.FilePath
import hudson.Util
import java.io.IOException
import java.lang.management.BufferPoolMXBean
import java.util.logging.Level
import java.util.logging.Logger
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException
import java.util.regex.Matcher;
import java.util.regex.Pattern
import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;
import org.jenkinsci.plugins.workflow.cps.CpsThread;
class OpenShiftDSL implements Serializable {
static final Logger LOGGER = Logger.getLogger(OpenShiftDSL.class.getName());
private org.jenkinsci.plugins.workflow.cps.CpsScript script
// Load the global config for OpenShift DSL
private transient OpenShift.DescriptorImpl config = new OpenShift.DescriptorImpl();
private int logLevel = 0; // Modified by calls to openshift.logLevel
private HashMap<String,Capabilities> nodeCapabilities = new HashMap<String,Capabilities>();
private String lockName = "";
/**
* Prints a log message to the Jenkins log, bypassing the echo step.
* @param s The message to log
*/
@NonCPS
public static void logToTaskListener(String s) {
CpsThread thread = CpsThread.current();
CpsFlowExecution execution = thread.getExecution();
try {
execution.getOwner().getListener().getLogger().println(s);
} catch (IOException e) {
LOGGER.log(Level.INFO, "logToTaskListener", e);
}
}
public OpenShiftDSL(org.jenkinsci.plugins.workflow.cps.CpsScript script) {
this.script = script
}
public synchronized Capabilities getCapabilities() {
String key = script.env.NODE_NAME
Capabilities caps = nodeCapabilities.get(key)
if (caps != null) {
return caps
} else {
caps = new Capabilities()
ArrayList<String> g = new ArrayList<String>();
g.add("get");
OcAction.OcActionResult versionCheck = (OcAction.OcActionResult)script._OcAction(buildCommonArgs("help", g, null, null));
LOGGER.log(Level.FINE, "getCapabilities return from oc help get " + versionCheck.out);
caps.ignoreNotFound = versionCheck.out.contains("--ignore-not-found")
nodeCapabilities.put(key, caps)
LOGGER.log(Level.FINE, "getCapabilities nodeCapabilities: " + nodeCapabilities);
return caps
}
}
private Context currentContext = null;
private static final Map<String,String> abbreviations = [
"svc" : "service",
"p" : "pod",
"po" : "pod",
"bc" : "buildconfig",
"is" : "imagestream",
"rc" : "replicationcontroller",
"dc" : "deploymentconfig" ]
enum ContextId implements Serializable {
WITH_CLUSTER("openshift.withCluster"), WITH_PROJECT("openshift.withProject"), WITH_CREDENTIALS("openshift.withCredentials")
private final String name;
ContextId(String name) {
this.@name = name;
}
@NonCPS
public String toString() {
return name;
}
}
private class Context implements Serializable {
protected final Context parent;
private final OcContextInit.Execution exec;
private String credentialsId;
private String serverUrl;
private String serverCertificateAuthorityPath;
private Boolean skipTLSVerify;
private String project;
private ContextId id;
private List<FilePath> destroyOnReturn = new ArrayList<FilePath>();
protected Context(Context parent, ContextId id) {
this.@parent = parent;
this.@id = id;
this.@exec = script._OcContextInit();
}
public <V> V run(Closure<V> body) {
if (destroyOnReturn == null) {
throw new IllegalStateException(this.getClass() + " has already been performed once and cannot be used again");
}
Context lastContext = currentContext;
currentContext = this;
try {
return body()
} finally {
currentContext = lastContext;
destroyOnReturn.each{ fp -> fp.delete() }
destroyOnReturn = null;
}
}
@NonCPS
public ContextId getContextId() {
return this.@id;
}
public String getToken() {
if (this.@credentialsId != null) {
// With the decoupling of jenkins sync and jenkins client plugins, the OpenshiftSyncClientToken class can now come from jenkins-sync-plugin
// In order to be able to use it, we now allow any token inheriting from BaseStandardCredentials that has a .getToken() method.
// If the passed token id does not point to a valid credential, ie an implementation having a .getToken() method, the call fails at runtime
// the same way as if the token id was invalid or not found.
BaseStandardCredentials tokenSecret = CredentialsProvider.findCredentialById(credentialsId, BaseStandardCredentials.class, script.$build(), Collections.emptyList());
if (tokenSecret != null) {
return tokenSecret.getToken();
}
// Otherwise, assume that this is a literal/direct token name
return this.@credentialsId;
}
// avoid asking outer contexts for credentials with withCluster("named") { withCluster ("https://...") { ... } }
if (this.@serverUrl == null && parent != null) {
return parent.getToken();
}
return script.readFile("/var/run/secrets/kubernetes.io/serviceaccount/token");
}
public void setCredentialsId(String credentialsId) {
this.@credentialsId = Util.fixEmptyAndTrim(credentialsId);
}
public String getProject() {
if (this.@project != null) {
return this.@project;
}
if (parent != null) {
return parent.getProject();
}
return script.readFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace");
}
public void setProject(String project) {
this.@project = Util.fixEmptyAndTrim(project);
}
public String getServerCertificateAuthorityPath() {
if (this.@serverCertificateAuthorityPath != null) {
return this.@serverCertificateAuthorityPath;
}
if (parent != null) {
return parent.getServerCertificateAuthorityPath();
}
// Assume we are running in an OpenShift pod with a service account mounted
return "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt";
}
public void setServerCertificateAuthorityContent(String serverCertificateAuthorityContent) {
serverCertificateAuthorityContent = Util.fixEmptyAndTrim(serverCertificateAuthorityContent);
if (serverCertificateAuthorityContent != null) {
/**
* The certificate authority content must be written to the agent's file
* system. It would be nice if we could set the name in an environment variable
* instead.
*/
FilePath ca = exec.getWorkspaceFilePath().createTextTempFile("serverca", ".crt", serverCertificateAuthorityContent, true);
destroyOnReturn.add(ca);
this.@serverCertificateAuthorityPath = ca.getRemote();
}
}
public String getServerUrl() {
if (this.@serverUrl != null) {
return this.@serverUrl;
}
if (parent != null) {
return parent.getServerUrl();
}
// fetching jenkins pipeline env from generic java without jenkins extensions
// proving more problematic ... leverage default patter in case System.getenv
// does not render desired result
return ClusterConfig.getHostClusterApiServerUrl(script.env.KUBERNETES_SERVICE_HOST, script.env.KUBERNETES_SERVICE_PORT_HTTPS);
}
public void setServerUrl(String serverUrl, boolean skipTLSVerify) {
this.@serverUrl = Util.fixEmptyAndTrim(serverUrl);
this.@skipTLSVerify = skipTLSVerify;
}
public boolean isSkipTLSVerify() {
if (this.@skipTLSVerify != null) {
return this.@skipTLSVerify;
}
if (parent != null) {
return parent.isSkipTLSVerify();
}
return false;
}
}
/**
* Returns true if the test context identifier is found within the context
*/
@NonCPS
private boolean contextContains(Context context, ContextId test) {
while (context != null) {
if (context.getContextId() == test) {
return true;
}
context = context.parent;
}
return false;
}
@NonCPS
private void dieIfWithin(ContextId me, Context context, ContextId... forbidden) throws AbortException {
for (ContextId forbid : forbidden) {
if (contextContains(context, forbid)) {
throw new AbortException(me.toString() + " cannot be used within a " + forbid.toString() + " closure body");
}
}
}
@NonCPS
// for checks in private methods where the public method used, to included in the exception message, is unclear
// or embedded
private void dieIfWithout(Context context, ContextId required, String verb) throws AbortException {
if (!contextContains(context, required)) {
verb == "" && (verb = "raw")
throw new AbortException("You have illegally attempted a " + verb + " command when not inside a " + required.toString() + " closure body")
}
}
@NonCPS
private void dieIfNotWithin(ContextId me, Context context, ContextId required) throws AbortException {
if (!contextContains(context, required)) {
throw new AbortException(me.toString() + " can only be used within a " + required.toString() + " closure body");
}
}
public void failUnless(b) {
b = (new Boolean(b)).booleanValue();
if (!b) {
// error is a Jenkins workflow-basic-step
error("Assertion failed")
}
}
public String project() {
if (currentContext != null)
return currentContext.getProject();
else
return null;
}
public String cluster() {
if (currentContext != null)
return currentContext.getServerUrl();
else
return null;
}
public boolean skipTLSVerify() {
if (currentContext != null)
return currentContext.isSkipTLSVerify();
else
return false;
}
public void setLockName(String lockName) {
this.lockName = lockName;
}
/**
* @param name The name can be a literal URL for the clusterName or,
* preferably, a Jenkins specific
* name of a clusterName configured in the global OpenShift configuration. The name can also
* be blank, which means we will default using the default clusterName hostname within a Pod.
* @param credentialId A literal OAuth token name OR the Jenkins specific identifier of a credential
* defined in the Jenkins credentials store.
*/
public <V> V withCluster(Object oname=null, Object ocredentialId=null, Closure<V> body) {
String name = toSingleString(oname);
String credentialId = toSingleString(ocredentialId);
Closure<V> guts = {
// Note that withCluster creates a new Context with null parent. This means that it does not allow
// operations search outside of its context for more broadly scoped information (i.e.
// in the DSL: withCredentials(y){ withCluster(...){ x } }, the operation x will not see the credential y.
// Therefore, to enforce DSL clarity, forbid withCluster from being wrapped.
dieIfWithin(ContextId.WITH_CLUSTER, currentContext, ContextId.WITH_PROJECT, ContextId.WITH_CREDENTIALS)
Context context = new Context(null, ContextId.WITH_CLUSTER);
// Determine if name is a URL or a clusterName name. It is treated as a URL if it is *not* found
// as a clusterName configuration name.
ClusterConfig cc = null;
// in case of restart during the middle of a job run using this global var, reinit this transient
// var
if (config == null) {
// this will initiate a load of the xml config file
config = new OpenShift.DescriptorImpl();
}
if (name != null) {
cc = config.getClusterConfig(name);
} else {
// See if a clusterName named "default" has been defined.
cc = config.getClusterConfig("default");
}
if (cc == null) {
// Presumably, a URL has been specified. If "insecure://..." is a prefix, https is used, but TLS
// verification is skipped.
if (name != null) {
boolean skipTLS = false;
if (name.startsWith("insecure://")) {
skipTLS = true;
name = "https://" + name.substring("insecure://".length());
}
context.setServerUrl(name, skipTLS);
}
} else {
context.setServerCertificateAuthorityContent(cc.getServerCertificateAuthority());
context.setCredentialsId(cc.credentialsId);
context.setProject(cc.defaultProject);
context.setServerUrl(cc.getServerUrl(), cc.isSkipTlsVerify());
}
if (credentialId != null) {
context.setCredentialsId(credentialId);
}
context.run {
body()
}
}
node {
if (lockName != null && lockName.size() > 0) {
// the lock step from the lockable resource plugin
// will dynamically create the lockable resource with the
// name "lockName" if it was not previously created.
// Our readme gets into the user having to maintain background
// perging of locks, etc.
// the lock is release by the lockable plugin when the closure
// exits
script.lock(lockName) {
guts();
}
} else {
guts();
}
}
}
public <V> V withProject(Object oprojectName=null, Closure<V> body) {
String projectName = toSingleString(oprojectName);
dieIfNotWithin(ContextId.WITH_PROJECT, currentContext, ContextId.WITH_CLUSTER)
Context context = new Context(currentContext, ContextId.WITH_PROJECT);
context.setProject(projectName);
return context.run {
body()
}
}
public <V> V withCredentials(Object ocredentialId=null, Closure<V> body) {
String credentialId = toSingleString(ocredentialId);
dieIfNotWithin(ContextId.WITH_CREDENTIALS, currentContext, ContextId.WITH_CLUSTER)
Context context = new Context(currentContext, ContextId.WITH_CREDENTIALS);
context.setCredentialsId(credentialId);
return context.run {
body()
}
}
// Will eventually be deprecated in favor of withCredentials
public <V> V doAs(Object ocredentialId=null, Closure<V> body) {
script.print("WARNING: doAs() is deprecated, use withCredentials() instead")
return withCredentials(ocredentialId, body)
}
public void logLevel(int v) {
this.@logLevel = v;
}
// All lowercase synonym for users familiar with --loglevel on CLI.
public void loglevel(int v) {
logLevel(v);
}
public void verbose (boolean v=true) {
logLevel(v?8:0)
}
private Map buildCommonArgs(Object overb, List verbArgs, Object[] ouserArgsArray, Object... ooverrideArgs) {
return buildCommonArgs(true, overb, verbArgs, ouserArgsArray, ooverrideArgs)
}
private Map buildCommonArgs(boolean getProject, Object overb, List verbArgs, Object[] ouserArgsArray, Object... ooverrideArgs) {
dieIfWithout(currentContext, ContextId.WITH_CLUSTER, overb);
String verb = toSingleString(overb);
String[] userArgsArray = toStringArray(ouserArgsArray);
String[] overrideArgs = toStringArray(ooverrideArgs);
String streamStdOutToConsolePrefix = null;
for (String arg : userArgsArray) {
String a = arg.trim();
if (a.equals("-f") || a.equals("--follow")) {
streamStdOutToConsolePrefix = verb;
break;
}
}
if (streamStdOutToConsolePrefix == null)
for (String arg : overrideArgs) {
String a = arg.trim();
if (a.equals("-f") || a.equals("--follow")) {
streamStdOutToConsolePrefix = verb;
break;
}
}
List optionsBase = [];
// Override args should come after all user arguments. This allows us to ensure
// certain behaviors (e.g. if we need to send -o=name).
if (overrideArgs != null) {
optionsBase.addAll(overrideArgs);
}
ArrayList<String> userArgsList = (userArgsArray==null)?new ArrayList<String>():Arrays.asList(userArgsArray);
Map args;
if (streamStdOutToConsolePrefix != null)
// These arguments will be mapped, by name, to the constructor parameters of OcAction
args = [
server:currentContext.getServerUrl(),
project:(getProject ? currentContext.getProject() : null),
skipTLSVerify: currentContext.isSkipTLSVerify(),
caPath: currentContext.getServerCertificateAuthorityPath(),
verb:verb,
verbArgs:verbArgs,
userArgs:userArgsList,
options:optionsBase,
token:currentContext.getToken(),
logLevel:logLevel,
streamStdOutToConsolePrefix:streamStdOutToConsolePrefix
]
else
args = [
server:currentContext.getServerUrl(),
project:(getProject ? currentContext.getProject() : null),
skipTLSVerify: currentContext.isSkipTLSVerify(),
caPath: currentContext.getServerCertificateAuthorityPath(),
verb:verb,
verbArgs:verbArgs,
userArgs:userArgsList,
options:optionsBase,
token:currentContext.getToken(),
logLevel:logLevel
]
return args;
}
/**
* Splits oc verb -o=name output into a list of qualified object names.
*/
public static ArrayList<String> splitNames(String out) {
String[] names = (out == null ? new String[0] : out.trim().split("\n"));
List<String> results = new ArrayList<String>();
for (int i = 0; i < names.length; i++) {
String name = names[i].trim();
if (! name.isEmpty()) {
// to simplify life, to account for new -o=name output for openshift unique api objs
// with group suffixes like deploymentconfig.apps.openshift.io, and chop off the "domain"
//TODO need to consider this path, along with the actual value of the "metadata.kind" field
// (it currently is still "DeploymentConfig" in 3.10) when we start seeing resources like
// "deploymentconfig.extensions.k8s.io"
String[] kind_name = name.split("/");
String kind = kind_name[0];
String[] kind_parts = kind.split("\\.");
if (kind_parts.length > 1 && kind_name.length > 1) {
String nm = kind_name[1];
results.add(kind_parts[0] + "/" + nm);
} else {
results.add(name);
}
}
}
return results;
}
@NonCPS
public HashMap serializableMap(String json) {
JsonSlurper js = new JsonSlurper();
Map m = js.parseText(json);
/**
* The Map produced by JsonSlurper is not serializable. If we return it to the user's DSL script and they store it in a global variable,
* the Jenkins CPS engine will attempt to serialize it before the next AsynchronousStepExecution. This leads to a
* exceptions like: java.io.NotSerializableException: groovy.json.internal.LazyMap
* To avoid this, everything we return to the user must be serializable -- transform the JsonSlurper into a serializable map.
* NonCPS methods may not call non-NonCPS methods and arguments/returns must be serializable.
* http://stackoverflow.com/questions/37864542/jenkins-pipeline-notserializableexception-groovy-json-internal-lazymap
*/
HashMap master = new HashMap(m);
Stack<HashMap> s = new Stack<HashMap>();
s.push(master);
while (s.size() > 0) {
HashMap target = s.pop();
for (Map.Entry e : target.entrySet()) {
if (e.getValue() instanceof Map) {
HashMap he = new HashMap((Map)e.getValue());
e.setValue(he);
s.push(he);
}
if (e.getValue() instanceof List) {
List l = (List)e.getValue();
for (int i = 0; i < l.size(); i++) {
Object o = l.get(i);
if (o instanceof Map) {
HashMap he = new HashMap((Map)o);
l.set(i, he);
s.push(he);
}
}
}
}
}
return master;
}
/**
* @param obj An OpenShift object modeled as a Map
* @return A Java List containing OpenShift objects. If the parameter models an OpenShift List,
* the object will be "unwrapped" and the resulting Java List will contain an entry for each item
* in the OpenShift List obj. If the obj is not a list, the return name will be a list with
* the obj as its only entry.
*/
@NonCPS
public ArrayList<HashMap> unwrapOpenShiftList(HashMap obj) {
ArrayList<HashMap> r = new ArrayList<HashMap>();
if (obj.kind != "List") {
r.add(obj);
} else {
if (obj.items == null) {
obj.items = new ArrayList();
} else {
r.addAll(obj.items);
}
}
return r;
}
/**
* @param obj An OpenShift object modeled as a Map or multiple OpenShift objects as List<Map>
* @return If the parameter is a List, it will be combined into a single OpenShift List model. Otherwise,
* the parameter will be returned unchanged.
*/
@NonCPS
public Object toSingleObject(Object obj) {
if (!(obj instanceof List)) {
return obj;
}
// Model an OpenShift List
HashMap m = new HashMap();
m.kind = "List";
m.apiVersion = "v1"
m.items = obj;
return m;
}
/**
* The select operation can be executed multiple ways:
* selector() // Selects all
* selector("pod") // Selects all of a name
* selector("dc", "jenkins") // selects a particular instance dc/jenkins
* selector("dc/jenkins") // selects a particular instance dc/jenkins
* selector(["dc/jenkins", "build/ruby1"]) // selects a particular list of resources
* selector("dc", [ alabel: 'avalue' ]) // Selects using label values
* When labels are used, the qualifier will be a map. In other cases, expect a String or null.
*/
public OpenShiftResourceSelector selector(Object kind = null, Object qualifier=null) {
OpenShiftResourceSelector selector = new OpenShiftResourceSelector("selector", kind, qualifier);
return selector;
}
private OpenShiftResourceSelector objectDefAction(String verb, Object obj, Object[] userArgs) {
dieIfWithout(currentContext, ContextId.WITH_CLUSTER, verb);
// if the obj is broken down to a parseable set of maps (typically as the result of an
// openshift.process call, we look to see if the namespace is specified for any of them
// or if they are not consistently the same namespace:
// no namespaces set: we make 1 invocation of the verb where we will use the current project stored in
// the context if it exists (traditional behavior)
// consistent namespace set: we make 1 invocation of the verb where we don't use the current project stored in
// the context and let oc and the obj json sort out where objects go
// inconsistent namespaces: we make an invocation of the verb for each object where will will not override the
// project if it is set but use the current project if it is not set
String namespace = null;
boolean found = false;
boolean consistent = true;
ArrayList objList = null;
if (obj instanceof List) {
objList = new ArrayList((List)obj);
for (Object obj2 : objList) {
if (obj2 instanceof Map) {
HashMap obj2Map = new HashMap((Map)obj2);
HashMap obj2MapMetadata = obj2Map.get("metadata");
if (obj2MapMetadata != null) {
Object ns = obj2MapMetadata.get("namespace");
// first time through the list, no
// consistency check
if (!found) {
found = true;
namespace = ns != null ? ns.toString() : null;
} else {
if (namespace == null && ns == null)
continue;
if (namespace != null && namespace.equals(ns))
continue;
consistent = false;
break;
}
}
}
}
}
Result r = new Result(verb);
HashMap<String, String> projectNames = null;
if (consistent) {
if (namespace == null || namespace.trim().length() == 0)
namespace = currentContext.getProject();
r = innerObjectDefAction(verb, obj, userArgs, namespace, r);
} else {
projectNames = new HashMap<String, String>();
for (int i=0; i < objList.size(); i++) {
Object obj2 = objList.get(i);
if (obj2 instanceof Map) {
HashMap obj2Map = new HashMap((Map)obj2);
HashMap obj2MapMetadata = obj2Map.get("metadata");
if (obj2MapMetadata != null) {
String ns = (String)obj2MapMetadata.get("namespace");
if (ns == null || ns.trim().length() == 0)
ns = currentContext.getProject();
String kind = obj2Map.get("kind");
abbreviations.containsKey(kind.toLowerCase().trim()) && (kind=abbreviations.get(kind.toLowerCase().trim()))
String name = obj2MapMetadata.get("name");
r = innerObjectDefAction(verb, obj2, userArgs, ns, r);
// add index in case same kind/name in diff projects
projectNames.put(kind.toLowerCase().trim()+"/"+name+i, ns);
}
}
}
}
r.failIf(verb + " returned an error");
OpenShiftResourceSelector selector = null;
ArrayList<String> nameList = OpenShiftDSL.splitNames(r.out);
if (projectNames != null) {
selector = new OpenShiftResourceSelector(r, nameList, projectNames);
} else {
selector = new OpenShiftResourceSelector(r, nameList);
}
return selector;
}
private Result innerObjectDefAction(String verb, Object obj, Object[] userArgs, String project, Result r) {
obj = toSingleObject(obj); // Combine a list of objects into a single OpenShift List model, if necessary.
if (obj instanceof Map) {
obj = JsonOutput.toJson(obj);
}
String s = obj.toString();
boolean markup = s.contains("{") || s.contains(":"); // does this look like json or yaml?
boolean httpref = s.toLowerCase().startsWith("http") && verb.equalsIgnoreCase("create"); // a create from a http or https raw.githubuser path
if (httpref) {
Map stepArgs = buildCommonArgs(verb, [ "-f", s ], userArgs, "-o=name");
if (project != null) {
stepArgs["project"] = project;
}
r.actions.add((OcAction.OcActionResult)script._OcAction(stepArgs));
} else if (markup) {
FilePath f = currentContext.exec.getWorkspaceFilePath().createTextTempFile(verb, ".markup", s, true);
try {
Map stepArgs = buildCommonArgs(verb, [ "-f", f.getRemote() ], userArgs, "-o=name");
stepArgs["reference"] = [ "${f.getRemote()}": s ]; // Store the markup content for reference in the result
if (project != null) {
stepArgs["project"] = project;
}
r.actions.add((OcAction.OcActionResult)script._OcAction(stepArgs));
} finally {
f.delete();
}
} else {
// looks like a subVerb was passed in (e.g. openshift.create("serviceaccount", "jenkins"))
Map stepArgs = buildCommonArgs(verb, [s], userArgs, "-o=name");
if (project != null) {
stepArgs["project"] = project;
}
r.actions.add((OcAction.OcActionResult)script._OcAction(stepArgs));
}
return r;
}
public OpenShiftResourceSelector create(Object obj,Object... args) {
return objectDefAction("create", obj, args);
}
public OpenShiftResourceSelector replace(Object obj,Object... args) {
return objectDefAction("replace", obj, args);
}
public OpenShiftResourceSelector apply(Object obj,Object... args) {
return objectDefAction("apply", obj, args);
}
public ArrayList<HashMap> process(Object obj,Object... oargs) throws AbortException {
String[] args = toStringArray(oargs);
if (obj instanceof Map) {
if (obj.kind != "Template") {
throw new AbortException("Expected Template object, but received: " + obj.toString());
}
// https://github.com/openshift/origin/issues/12277
Map template = new HashMap((Map)obj);
template.metadata.remove('namespace');
template.metadata.remove('selfLink');
obj = JsonOutput.toJson(template);
}
String s = obj.toString();
boolean markup = s.contains("{") || s.contains(":")
boolean httpref = s.toLowerCase().startsWith("http")
Result r = new Result("process")
if (httpref) {
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("process", ["-f", s ], args, "-o=json")));
r.failIf("process returned an error");
} else if (markup) { // does this look like json or yaml?
FilePath f = currentContext.exec.getWorkspaceFilePath().createTextTempFile("process", ".markup", s, true);
try {
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("process", ["-f", f.getRemote() ], args, "-o=json")));
r.failIf("process returned an error");
} finally {
f.delete();
}
} else {
// Otherwise, the obj parameter is assumed to be a template name
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("process", [s], args, "-o=json")));
r.failIf("process returned an error");
}
// Output should be JSON; unmarshall into a map and transform into a list of objects.
return unwrapOpenShiftList(serializableMap(r.out));
}
public Result patch(Object obj, Object opatch, Object... oargs) throws AbortException {
String patch = opatch.toString();
String[] args = toStringArray(oargs);
if (obj instanceof Map) {
obj = JsonOutput.toJson(obj);
}
String s = obj.toString();
boolean markup = s.contains("{") || s.contains(":")
boolean httpref = s.toLowerCase().startsWith("http")
Result r = new Result("patch")
if (httpref) {
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("patch", ["-f", s, "-p", patch ], args)));
r.failIf("patch returned an error");
} else if (markup) { // does this look like json or yaml?
FilePath f = currentContext.exec.getWorkspaceFilePath().createTextTempFile("patch", ".markup", s, true);
try {
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("patch", ["-f", f.getRemote(), "-p", patch ], args)));
r.failIf("patch returned an error");
} finally {
f.delete();
}
} else {
// Otherwise, the obj parameter is assumed to be a template name
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("patch", [s, "-p", patch], args)));
r.failIf("patch returned an error");
}
return r;
}
public Result newProject(Object oname, Object... oargs) {
String name = toSingleString(oname);
String[] args = toStringArray(oargs);
Result r = new Result("newProject");
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs(false, "new-project", [name], args, "--skip-config-write")));
r.failIf("new-project returned an error");
return r;
}
/**
* API calls with String parameters can receive normal Java strings
* or gstrings. In the DSl/groovy, gstrings are defined by using double quotes and
* include some interpolation. Methods within the API should
* accept either. To this end, accept any type of object and turn
* it into a string.
*/
@NonCPS
private static String toSingleString(Object o) {
if (o == null) {
return null;
}
return o.toString(); // convert from gstring if necessary
}
/**
* See details in toSingleString for rationale.
*/
@NonCPS
private static String[] toStringArray(Object[] args) {
if (args == null) {
return new String[0];
}
// Unpack a Groovy list as if it were an Array
// Enables openshift.run([ 'x', 'y' ])
if (args.length == 1 && args[0] instanceof List) {
args = ((List)args[0]).toArray();
}
String[] o = new String[args.length];
for (int i = 0; i < args.length; i++) {
o[i] = args[i].toString();
}
return o;
}
/**
* See details in toSingleString for rationale.
*/
@NonCPS
private static ArrayList<String> toStringList(List<Object> objects) {
ArrayList l = new ArrayList<String>();
if (objects != null) {
for (int i = 0; i < objects.size(); i++) {
l.add(objects.get(i).toString());
}
}
return l;
}
/**
* See details in toSingleString for rationale.
*/
@NonCPS
private static List<String> toStringList(Object[] objects) {
List<String> l = new ArrayList<String>();
if (objects != null) {
for (int i = 0; i < objects.length; i++) {
l.add(objects[i].toString());
}
}
return l;
}
public Result raw(Object... oargs) {
String[] args = toStringArray(oargs);
List<String> argsList = toStringList(oargs);
Result r = new Result("raw");
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("", argsList, null)));
r.failIf("raw command " + args + " returned an error");
return r;
}
public Result delete(Object obj,Object... args) {
OpenShiftResourceSelector deleteSelector = objectDefAction("delete", obj, args);
//NOTE: more groovy suckage ... I could not pass a OpenShiftResourceSelector, even
// though it extends Result, into the Result(Result) contructor
return new Result(deleteSelector.highLevelOperation, deleteSelector.actions);
}
public Result set(Object... oargs) {
String[] args = toStringArray(oargs);
Result r = new Result("set");
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("set", null, args)));
r.failIf("set returned an error");
return r;
}
private OpenShiftResourceSelector newAppAction(Object[] oargs) {
String[] args = toStringArray(oargs);
// so we first run with -o=json so we can examine the template processing results around
// namespaces; but this of course does not actually create the objects
//
// so we re-run with create on the returned json to effect the actual creation
Result r = new Result("newApp");
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs("new-app", null, args, "-o=json")));
r.failIf("new-app" + " returned an error");
ArrayList<HashMap> result = unwrapOpenShiftList(serializableMap(r.out));
return objectDefAction("create", result, new Object[0]);
}
private OpenShiftResourceSelector newObjectsAction(String operation, String verb, Object[] oargs) {
String[] args = toStringArray(oargs);
Result r = new Result(operation);
r.actions.add((OcAction.OcActionResult)script._OcAction(buildCommonArgs(verb, null, args, "-o=name")));
r.failIf(verb + " returned an error");
OpenShiftResourceSelector selector = new OpenShiftResourceSelector(r, OpenShiftDSL.splitNames(r.out));
return selector;
}
public OpenShiftResourceSelector newBuild(Object... args) {
return newObjectsAction("newBuild", "new-build", args);
}
public OpenShiftResourceSelector newApp(Object... args) {
return newAppAction(args);
}
public OpenShiftResourceSelector startBuild(Object... args) {
return newObjectsAction("startBuild", "start-build", args);
}
public boolean verifyService(String svcName) {
OpenShiftResourceSelector svcSel = this.selector("svc", svcName);
String ip = (String)svcSel.object().get("spec").get("clusterIP");
String port = (String)svcSel.object().get("spec").get("ports").get(0).get("port");
InetAddress inetAddress = null;
String hostAddress = null;
int i = 0;
while (i < 5) {
i++;
// ClusterIp is not present in headless services with selectors.
if (ip.trim() == "None"){
try{
inetAddress = InetAddress.getByName(svcName+"."+svcSel.project());
logToTaskListener("Connected to headless service " + svcName + " via port " + port + " with pod IP " + inetAddress.getHostAddress());
return true;
}
catch (UnknownHostException e){
logToTaskListener("UnknownHostException " + e.getMessage() + " connecting to service " + svcName);
LOGGER.log(Level.FINE, "verifyService", e);
try {
Thread.sleep(2500);
} catch (InterruptedException e1) {
}
}
} else {
InetSocketAddress address = new InetSocketAddress(ip, Integer.parseInt(port));
Socket socket = null;