-
Notifications
You must be signed in to change notification settings - Fork 189
/
CpsScript.java
232 lines (206 loc) · 8.17 KB
/
CpsScript.java
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
/*
* The MIT License
*
* Copyright (c) 2013-2014, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.workflow.cps;
import com.cloudbees.groovy.cps.SerializableScript;
import groovy.lang.GroovyShell;
import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
import hudson.model.Queue;
import hudson.model.Run;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jenkinsci.plugins.workflow.cps.persistence.PersistIn;
import static org.jenkinsci.plugins.workflow.cps.persistence.PersistenceContext.*;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
/**
* The script of a workflow.
*
* Every {@link Script} we load in Pipeline execution derives from this subtype.
*
* @author Kohsuke Kawaguchi
*/
@PersistIn(PROGRAM)
public abstract class CpsScript extends SerializableScript {
private static final Logger LOGGER = Logger.getLogger(CpsScript.class.getName());
private static final String STEPS_VAR = "steps";
transient CpsFlowExecution execution;
/** Default constructor for {@link CpsFlowExecution}. */
public CpsScript() throws IOException {
// if the script is instantiated in workflow, automatically set up the contextual
// 'execution' object. This allows those scripts to invoke workflow steps without
// any special setup, making it easy to write reusable functions.
CpsThread c = CpsThread.current();
if (c!=null) {
execution = c.getExecution();
$initialize();
}
}
@SuppressWarnings("unchecked") // Binding
final void $initialize() throws IOException {
// TODO JENKINS-33353 could make this a GlobalVariable instead
getBinding().setVariable(STEPS_VAR, new DSL(execution.getOwner()));
}
/**
* We use DSL here to try invoke the step implementation, if there is Step implementation found it's handled or
* it's an error.
*
* <p>
* sandbox security execution relies on the assumption that CpsScript.invokeMethod() is safe for sandboxed code.
* That means we cannot let user-written script override this method, hence the final.
*/
@Override
public final Object invokeMethod(String name, Object args) {
// TODO probably better to call super method and only proceed here incase of MissingMethodException:
// if global variables are defined by that name, try to call it.
// the 'call' convention comes from Closure
GlobalVariable v = GlobalVariable.byName(name, $buildNoException());
if (v != null) {
try {
Object o = v.getValue(this);
return InvokerHelper.getMetaClass(o).invokeMethod(o, "call", args);
} catch (Exception x) {
throw new InvokerInvocationException(x);
}
}
// otherwise try Step impls.
DSL dsl = (DSL) getBinding().getVariable(STEPS_VAR);
return dsl.invokeMethod(name,args);
}
@Override
public Object getProperty(String property) {
try {
return super.getProperty(property);
} catch (MissingPropertyException mpe) {
// cf. CpsWhitelist.permitsMethod
Run<?,?> b = $buildNoException();
GlobalVariable v = GlobalVariable.byName(property, b);
if (v != null) {
try {
return v.getValue(this);
} catch (Exception x) {
throw new InvokerInvocationException(x);
}
}
if (b != null) {
try {
String value = EnvActionImpl.forRun(b).getProperty(property);
if (value != null) {
return value;
}
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
throw mpe;
}
}
public @CheckForNull Run<?,?> $build() throws IOException {
FlowExecutionOwner owner = execution.getOwner();
Queue.Executable qe = owner.getExecutable();
if (qe instanceof Run) {
return (Run) qe;
} else {
return null;
}
}
public @CheckForNull Run<?,?> $buildNoException() {
if (execution == null) {
// Still inside the WorkflowScript constructor, e.g. because getProperty is being called from a @Field.
// In such cases we do not expect to be able to use library variables, so just skip it.
return null;
}
try {
return $build();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
return null;
}
}
@Override
public Object evaluate(String script) throws CompilationFailedException {
// this might throw the magic CpsCallableInvocation to execute the script asynchronously
return $getShell().evaluate(script);
}
@Override
public Object evaluate(File file) throws CompilationFailedException, IOException {
return $getShell().evaluate(file);
}
@Override
public void run(File file, String[] arguments) throws CompilationFailedException, IOException {
$getShell().run(file,arguments);
}
/**
* Obtains the Groovy compiler to be used for compiling user script
* in the CPS-transformed and sandboxed manner.
*/
private GroovyShell $getShell() {
return CpsThreadGroup.current().getExecution().getShell();
}
protected Object readResolve() {
execution = CpsFlowExecution.PROGRAM_STATE_SERIALIZATION.get();
assert execution!=null;
return this;
}
@Override
public void println() {
invokeMethod("echo", "");
}
@Override
public void print(Object value) {
// TODO: handling 'print' correctly requires collapsing multiple adjacent print calls into one Step.
println(value);
}
@Override
public void println(Object value) {
invokeMethod("echo", String.valueOf(value));
}
@Override
public void printf(String format, Object value) {
print(DefaultGroovyMethods.sprintf(this/*not actually used*/, format, value));
}
@Override
public void printf(String format, Object[] values) {
print(DefaultGroovyMethods.sprintf(this/*not actually used*/, format, values));
}
/**
* Effectively overrides {@link DefaultGroovyStaticMethods#sleep(Object, long)}
* so that {@code SleepStep} works even in the bare form {@code sleep 5}.
*
* @see CpsClosure2#sleep(long)
*/
@Whitelisted
public Object sleep(long arg) {
return invokeMethod("sleep", arg);
}
private static final long serialVersionUID = 1L;
}