/
BuildTriggerStep.java
350 lines (313 loc) · 14.8 KB
/
BuildTriggerStep.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
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
package org.jenkinsci.plugins.workflow.support.steps.build;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.Functions;
import hudson.Util;
import hudson.model.AutoCompletionCandidates;
import hudson.model.Describable;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemVisitor;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.PasswordParameterDefinition;
import hudson.model.PasswordParameterValue;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import hudson.util.Secret;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.structs.describable.CustomDescribableModel;
import org.jenkinsci.plugins.structs.describable.DescribableModel;
import org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.steps.Step;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepDescriptor;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.jenkinsci.plugins.workflow.util.StaplerReferer;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
public class BuildTriggerStep extends Step {
private final String job;
private List<ParameterValue> parameters;
private boolean wait = true;
private boolean waitForStart = false;
private boolean propagate = true;
private Integer quietPeriod;
@DataBoundConstructor
public BuildTriggerStep(String job) {
this.job = job;
}
public String getJob() {
return job;
}
public List<ParameterValue> getParameters() {
return parameters;
}
@DataBoundSetter public void setParameters(List<ParameterValue> parameters) {
this.parameters = parameters;
}
public boolean getWait() {
return wait;
}
@DataBoundSetter public void setWait(boolean wait) {
this.wait = wait;
}
public boolean getWaitForStart() {
return waitForStart;
}
@DataBoundSetter public void setWaitForStart(boolean waitForStart) {
this.waitForStart = waitForStart;
}
public Integer getQuietPeriod() {
return quietPeriod;
}
@DataBoundSetter public void setQuietPeriod(Integer quietPeriod) {
this.quietPeriod = quietPeriod;
}
public boolean isPropagate() {
return propagate;
}
@DataBoundSetter public void setPropagate(boolean propagate) {
this.propagate = propagate;
}
@Override
public StepExecution start(StepContext context) {
return new BuildTriggerStepExecution(this, context);
}
@Extension
public static class DescriptorImpl extends StepDescriptor implements CustomDescribableModel {
// Note: This is necessary because the JSON format of the parameters produced by config.jelly when
// using the snippet generator does not match what would be neccessary for databinding to work automatically.
// Only called via the snippet generator.
@Override public Step newInstance(@Nullable StaplerRequest req, @NonNull JSONObject formData) throws FormException {
BuildTriggerStep step = (BuildTriggerStep) super.newInstance(req, formData);
// Cf. ParametersDefinitionProperty._doBuild:
Object parameter = formData.get("parameter");
JSONArray params = parameter != null ? JSONArray.fromObject(parameter) : null;
if (params != null) {
Job<?,?> context = StaplerReferer.findItemFromRequest(Job.class);
Job<?,?> job = Jenkins.get().getItem(step.getJob(), context, Job.class);
if (job != null) {
ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class);
if (pdp != null) {
List<ParameterValue> values = new ArrayList<>();
for (Object o : params) {
JSONObject jo = (JSONObject) o;
String name = jo.getString("name");
ParameterDefinition d = pdp.getParameterDefinition(name);
if (d == null) {
throw new IllegalArgumentException("No such parameter definition: " + name);
}
ParameterValue parameterValue;
if (d instanceof PasswordParameterDefinition) {
parameterValue = req.bindJSON(PasswordParameterValue.class, jo);
parameterValue.setDescription(d.getDescription());
} else {
parameterValue = d.createValue(req, jo);
}
if (parameterValue != null) {
values.add(parameterValue);
} else {
throw new IllegalArgumentException("Cannot retrieve the parameter value: " + name);
}
}
step.setParameters(values);
}
}
}
return step;
}
/**
* Compatibility hack for JENKINS-62305. Only affects runtime behavior of the step, not the snippet generator.
* Ideally, password parameters would not be used at all with this step, but there was no documentation or
* runtime warnings for this usage previously and so it is relatively common.
*/
@NonNull
@Override
public Map<String, Object> customInstantiate(@NonNull Map<String, Object> map) {
if (DescribableModel.of(PasswordParameterValue.class).getParameter("value").getErasedType() != Secret.class) {
return map;
}
return copyMapReplacingEntry(map, "parameters", List.class, parameters -> parameters.stream()
.map(parameter -> {
if (parameter instanceof UninstantiatedDescribable) {
UninstantiatedDescribable ud = (UninstantiatedDescribable) parameter;
if (ud.getSymbol().equals("password")) {
Map<String, Object> newArguments = copyMapReplacingEntry(ud.getArguments(), "value", String.class, Secret::fromString);
return ud.withArguments(newArguments);
}
}
return parameter;
})
.collect(Collectors.toList())
);
}
@NonNull
@Override
public UninstantiatedDescribable customUninstantiate(@NonNull UninstantiatedDescribable step) {
Map<String, Object> newStepArgs = copyMapReplacingEntry(step.getArguments(), "parameters", List.class, parameters -> parameters.stream()
.map(parameter -> {
if (parameter instanceof UninstantiatedDescribable) {
UninstantiatedDescribable ud = (UninstantiatedDescribable) parameter;
if (ud.getSymbol().equals("password")) {
Map<String, Object> newParamArgs = copyMapReplacingEntry(ud.getArguments(), "value", Secret.class, Secret::getPlainText);
return ud.withArguments(newParamArgs);
}
}
return parameter;
})
.collect(Collectors.toList())
);
return step.withArguments(newStepArgs);
}
/**
* Copy a map, replacing the entry with the specified key if it matches the specified type.
*/
private static <T> Map<String, Object> copyMapReplacingEntry(Map<String, ?> map, String keyToReplace, Class<T> requiredValueType, Function<T, Object> replacer) {
Map<String, Object> newMap = new HashMap<>();
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (entry.getKey().equals(keyToReplace) && requiredValueType.isInstance(entry.getValue())) {
newMap.put(entry.getKey(), replacer.apply(requiredValueType.cast(entry.getValue())));
} else {
newMap.put(entry.getKey(), entry.getValue());
}
}
return newMap;
}
@Override
public Set<? extends Class<?>> getRequiredContext() {
Set<Class<?>> context = new HashSet<>();
Collections.addAll(context, FlowNode.class, Run.class, TaskListener.class);
return Collections.unmodifiableSet(context);
}
@Override
public String getFunctionName() {
return "build";
}
@NonNull
@Override
public String getDisplayName() {
return "Build a job";
}
public AutoCompletionCandidates doAutoCompleteJob(@AncestorInPath ItemGroup<?> container, @QueryParameter final String value) {
// TODO remove code copy&pasted from AutoCompletionCandidates.ofJobNames when it supports testing outside Item bound
final AutoCompletionCandidates candidates = new AutoCompletionCandidates();
class Visitor extends ItemVisitor {
String prefix;
Visitor(String prefix) {
this.prefix = prefix;
}
@Override
public void onItem(Item i) {
String n = contextualNameOf(i);
if ((n.startsWith(value) || value.startsWith(n))
// 'foobar' is a valid candidate if the current value is 'foo'.
// Also, we need to visit 'foo' if the current value is 'foo/bar'
&& (value.length() > n.length() || !n.substring(value.length()).contains("/"))
// but 'foobar/zot' isn't if the current value is 'foo'
// we'll first show 'foobar' and then wait for the user to type '/' to show the rest
&& i.hasPermission(Item.READ)
// and read permission required
) {
if (i instanceof Queue.Task && n.startsWith(value))
candidates.add(n);
// recurse
String oldPrefix = prefix;
prefix = n;
super.onItem(i);
prefix = oldPrefix;
}
}
private String contextualNameOf(Item i) {
if (prefix.endsWith("/") || prefix.length() == 0)
return prefix + i.getName();
else
return prefix + '/' + i.getName();
}
}
if (container == null || container == Jenkins.getInstanceOrNull()) {
new Visitor("").onItemGroup(Jenkins.getInstanceOrNull());
} else {
new Visitor("").onItemGroup(container);
if (value.startsWith("/"))
new Visitor("/").onItemGroup(Jenkins.getInstanceOrNull());
for (StringBuilder p = new StringBuilder("../"); value.startsWith(p.toString()); p .append("../")) {
container = ((Item) container).getParent();
new Visitor(p.toString()).onItemGroup(container);
}
}
return candidates;
// END of copy&paste
}
@Restricted(DoNotUse.class) // for use from config.jelly
public String getContext() {
Job<?,?> job = StaplerReferer.findItemFromRequest(Job.class);
return job != null ? job.getFullName() : null;
}
@Restricted(DoNotUse.class) // for use from config.jelly
public String getContextEncoded() {
final String context = getContext();
//Functions.jsStringEscape() is also an alternative though the one below escapes more stuff
return context != null ? StringEscapeUtils.escapeJavaScript(context) : null;
}
public FormValidation doCheckPropagate(@QueryParameter boolean value, @QueryParameter boolean wait) {
if (!value && !wait) {
return FormValidation.warningWithMarkup(Messages.BuildTriggerStep_explicitly_disabling_both_propagate_and_wait());
}
return FormValidation.ok();
}
public FormValidation doCheckWait(@AncestorInPath ItemGroup<?> context, @QueryParameter boolean value, @QueryParameter String job) {
if (!value) {
return FormValidation.ok();
}
Item item = Jenkins.get().getItem(job, context, Item.class);
if (item == null) {
return FormValidation.ok();
}
if (item instanceof Job) {
return FormValidation.ok();
}
return FormValidation.error(Messages.BuildTriggerStep_no_wait_for_non_jobs());
}
public FormValidation doCheckJob(@AncestorInPath ItemGroup<?> context, @QueryParameter String value) {
if (StringUtils.isBlank(value)) {
return FormValidation.warning(Messages.BuildTriggerStep_no_job_configured());
}
Item item = Jenkins.get().getItem(value, context, Item.class);
if (item == null) {
return FormValidation.error(Messages.BuildTriggerStep_cannot_find(value));
}
if (item instanceof Queue.Task) {
return FormValidation.ok();
}
if (item instanceof Describable) {
return FormValidation.error(Messages.BuildTriggerStep_unsupported(((Describable<?>)item).getDescriptor().getDisplayName()));
}
return FormValidation.error(Messages.BuildTriggerStep_unsupported(item.getClass().getName()));
}
}
}