-
Notifications
You must be signed in to change notification settings - Fork 168
/
Promotion.java
605 lines (526 loc) · 23.3 KB
/
Promotion.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
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
package hudson.plugins.promoted_builds;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.console.ConsoleLogFilter;
import hudson.console.HyperlinkNote;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.StreamBuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Cause.UserCause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Environment;
import hudson.model.Node;
import hudson.model.ParameterDefinition;
import hudson.model.ParametersAction;
import hudson.model.ParameterValue;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.Run;
import hudson.model.User;
import hudson.plugins.promoted_builds.conditions.ManualCondition;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildTrigger;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import org.kohsuke.accmod.restrictions.DoNotUse;
/**
* Records a promotion process.
*
* @author Kohsuke Kawaguchi
*/
public class Promotion extends AbstractBuild<PromotionProcess,Promotion> {
public Promotion(PromotionProcess job) throws IOException {
super(job);
}
public Promotion(PromotionProcess job, Calendar timestamp) {
super(job, timestamp);
}
public Promotion(PromotionProcess project, File buildDir) throws IOException {
super(project, buildDir);
}
/**
* Gets the build that this promotion promoted.
* @since 3.4
* @return
* {@code null} if there's no such object. For example, if the build has already garbage collected.
*/
@CheckForNull
public AbstractBuild<?,?> getTargetBuild() {
PromotionTargetAction pta = getAction(PromotionTargetAction.class);
return pta == null ? null : pta.resolve(this);
}
/**
* Gets the build that this promotion promoted.
* @since 3.5
* @return Target build
* @throws IllegalStateException There is no target build
*/
@NonNull
public AbstractBuild<?,?> getTargetBuildOrFail() {
final AbstractBuild<?, ?> target = getTargetBuild();
if (target == null) {
throw new IllegalStateException("There is no target build associated with " + this +
". Most probably, the build has been already removed");
}
return target;
}
@Override public AbstractBuild<?,?> getRootBuild() {
return getTargetBuildOrFail().getRootBuild();
}
@Override
public String getUrl() {
return getTargetBuildOrFail().getUrl() + "promotion/" + getParent().getName() + "/promotionBuild/" + getNumber() + "/";
}
/**
* Gets the {@link Status} object that keeps track of what {@link Promotion}s are
* performed for a build, including this {@link Promotion}.
*/
public Status getStatus() {
return getTargetBuildOrFail().getAction(PromotedBuildAction.class).getPromotion(getParent().getName());
}
@Override
public EnvVars getEnvironment(TaskListener listener) throws IOException, InterruptedException {
EnvVars e = super.getEnvironment(listener);
// Augment environment with target build's information
String rootUrl = Jenkins.get().getRootUrl();
AbstractBuild<?, ?> target = getTargetBuildOrFail();
if(rootUrl!=null)
e.put("PROMOTED_URL",rootUrl+target.getUrl());
e.put("PROMOTED_JOB_NAME", target.getParent().getName());
e.put("PROMOTED_JOB_FULL_NAME", target.getParent().getFullName());
e.put("PROMOTED_NUMBER", Integer.toString(target.getNumber()));
e.put("PROMOTED_ID", target.getId());
GlobalBuildPromotedBuilds globalBuildPromotedBuilds = GlobalBuildPromotedBuilds.get();
String dateFormat = globalBuildPromotedBuilds.getDateFormat();
String timeZone = globalBuildPromotedBuilds.getTimeZone();
SimpleDateFormat format = null;
TimeZone tz = null;
if (dateFormat != null && !StringUtils.isBlank(dateFormat)) {
try {
format = new SimpleDateFormat(dateFormat);
} catch (IllegalArgumentException e1) {
LOGGER.log(Level.WARNING, String.format("An illegal date format was introduced: %s. Default ISO 8601 yyyy-MM-dd'T'HH:mmZ will be used", dateFormat), e1);
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
}
} else {
// Per ISO 8601
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
}
if (timeZone !=null && !StringUtils.isBlank(timeZone)) {
try {
tz = TimeZone.getTimeZone(timeZone);
} catch (IllegalArgumentException e2) {
LOGGER.log(Level.WARNING, String.format("An illegal time zone was introduced: %s. Default GMT time zone will be used", timeZone), e2);
tz = TimeZone.getTimeZone("GMT");
}
} else {
tz = TimeZone.getTimeZone("GMT");
}
format.setTimeZone(tz);
e.put("PROMOTED_TIMESTAMP", format.format(new Date()));
e.put("PROMOTED_DISPLAY_NAME", target.getDisplayName());
e.put("PROMOTED_USER_NAME", getUserName());
e.put("PROMOTED_USER_ID", getUserId());
EnvVars envScm = new EnvVars();
target.getProject().getScm().buildEnvVars( target, envScm );
for ( Entry<String, String> entry : envScm.entrySet() )
{
e.put( "PROMOTED_" + entry.getKey(), entry.getValue() );
}
// Allow the promotion status to contribute to build environment
getStatus().buildEnvVars(this, e);
return e;
}
/**
* Get a user name of the person, who triggered the promotion.
* The method tries various sources like {@link UserIdCause} or {@link ManualCondition.Badge}.
* @return user's name who triggered the promotion, or 'anonymous' if the search fails
*/
@NonNull
public String getUserName() {
// Deprecated, but we still want to support it in order to maintain the compatiibility
final UserCause userCause = getCause(UserCause.class);
final String nameFromUserCause = userCause != null ? userCause.getUserName() : null;
if (nameFromUserCause != null) {
return nameFromUserCause;
}
// Modern UserIdCause
final UserIdCause userIdCause = getCause(UserIdCause.class);
final String nameFromUserIdCause = userIdCause != null ? userIdCause.getUserName() : null;
if (nameFromUserIdCause != null) {
return nameFromUserIdCause;
}
//fallback to badge lookup for compatibility
for (PromotionBadge badget : getStatus().getBadges()) {
if (badget instanceof ManualCondition.Badge) {
final String nameFromBadge = ((ManualCondition.Badge) badget).getUserName();
if (!nameFromBadge.equals(ManualCondition.MISSING_USER_ID_DISPLAY_STRING)) {
return nameFromBadge;
}
}
}
return Jenkins.ANONYMOUS.getName();
}
/**
* Gets ID of the {@link User}, who triggered the promotion.
* The method tries various sources like {@link UserIdCause} or {@link ManualCondition.Badge}.
* @return ID of the user who triggered the promotion.
* If the search fails, returns ID of {@link User#getUnknown()}.
* @since 2.22
*/
@NonNull
public String getUserId() {
// Deprecated, but we still want to support it in order to maintain the compatibility
// We try to convert the cause to the user ID by using a search by the full name, not reliable
final UserCause userCause = getCause(UserCause.class);
final String nameFromUserCause = userCause != null ? userCause.getUserName(): null;
final User user = nameFromUserCause != null ? User.get(nameFromUserCause, false, Collections.emptyMap()) : null;
if (user != null) {
return user.getId();
}
// Modern UserIdCause
final UserIdCause userIdCause = getCause(UserIdCause.class);
final String idFromUserIdCause = userIdCause != null ? userIdCause.getUserId(): null;
if (idFromUserIdCause != null) {
return idFromUserIdCause;
}
//fallback to badge lookup for compatibility
for (PromotionBadge badget : getStatus().getBadges()) {
if (badget instanceof ManualCondition.Badge) {
final String idFromBadge = ((ManualCondition.Badge) badget).getUserId();
if (!idFromBadge.equals(ManualCondition.MISSING_USER_ID_DISPLAY_STRING)) {
return idFromBadge;
}
}
}
return User.getUnknown().getId();
}
public List<ParameterValue> getParameterValues(){
List<ParameterValue> values=new ArrayList<ParameterValue>();
ParametersAction parametersAction=getParametersActions(this);
if (parametersAction!=null){
ManualCondition manualCondition=(ManualCondition) getProject().getPromotionCondition(ManualCondition.class.getName());
if (manualCondition!=null){
for (ParameterValue pvalue:parametersAction.getParameters()){
if (manualCondition.getParameterDefinition(pvalue.getName())!=null){
values.add(pvalue);
}
}
}
return values;
}
//fallback to badge lookup for compatibility
for (PromotionBadge badget:getStatus().getBadges()){
if (badget instanceof ManualCondition.Badge){
return ((ManualCondition.Badge) badget).getParameterValues();
}
}
return Collections.emptyList();
}
/**
* Gets parameter definitions from the {@link ManualCondition}.
* @return List of parameter definitions to be presented.
* May be empty if there is no {@link ManualCondition}.
*/
@NonNull
public List<ParameterDefinition> getParameterDefinitionsWithValue(){
List<ParameterDefinition> definitions=new ArrayList<ParameterDefinition>();
ManualCondition manualCondition=(ManualCondition) getProject().getPromotionCondition(ManualCondition.class.getName());
if (manualCondition == null) {
return definitions;
}
for (ParameterValue pvalue:getParameterValues()){
ParameterDefinition pdef=manualCondition.getParameterDefinition(pvalue.getName());
if (pdef == null) {
// We cannot do anything with such missing definitions.
// May happen only in the case of the wrong form submission
continue;
}
definitions.add(pdef.copyWithDefaultValue(pvalue));
}
return definitions;
}
public void doRebuild(StaplerRequest req, StaplerResponse rsp) throws IOException {
throw HttpResponses.error(404, "Promotions may not be rebuilt directly");
}
public void run() {
if (getTargetBuildOrFail() != null) {
getStatus().addPromotionAttempt(this);
}
run(new RunnerImpl(this));
}
protected class RunnerImpl extends AbstractRunner {
final Promotion promotionRun;
RunnerImpl(final Promotion promotionRun) {
this.promotionRun = promotionRun;
}
@Override
protected Lease decideWorkspace(Node n, WorkspaceList wsl) throws InterruptedException, IOException {
if (getTargetBuild() == null) {
throw new IOException("No Promotion target, cannot retrieve workspace");
}
String customWorkspace = Promotion.this.getProject().getCustomWorkspace();
if (customWorkspace != null) {
final FilePath rootPath = n.getRootPath();
if (rootPath == null) {
throw new IOException("Cannot retrieve the root path of the node " + n);
}
// we allow custom workspaces to be concurrently used between jobs.
return Lease.createDummyLease(
rootPath.child(getEnvironment(listener).expand(customWorkspace)));
}
TopLevelItem item = (TopLevelItem) getTargetBuildOrFail().getProject();
FilePath workspace = n.getWorkspaceFor(item);
if (workspace == null) {
throw new IOException("Cannot retrieve workspace for " + item + " on the node " + n);
}
return wsl.allocate(workspace, promotionRun);
}
protected Result doRun(BuildListener listener) throws Exception {
AbstractBuild<?, ?> target = getTargetBuildOrFail();
OutputStream logger = listener.getLogger();
AbstractProject rootProject = project.getRootProject();
// Global log filters
for (ConsoleLogFilter filter : ConsoleLogFilter.all()) {
logger = filter.decorateLogger(target, logger);
}
// Project specific log filters
if (rootProject instanceof BuildableItemWithBuildWrappers) {
BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) rootProject;
for (BuildWrapper bw : biwbw.getBuildWrappersList()) {
logger = bw.decorateLogger(target, logger);
}
}
listener = new StreamBuildListener(logger);
listener.getLogger().println(
Messages.Promotion_RunnerImpl_Promoting(
HyperlinkNote.encodeTo('/' + target.getUrl(), target.getFullDisplayName())
)
);
// start with SUCCESS, unless someone makes it a failure
setResult(Result.SUCCESS);
if(!preBuild(listener,project.getBuildSteps()))
return Result.FAILURE;
try {
List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(project.getBuildWrappers().values());
List<ParameterValue> params=getParameterValues();
if (params!=null){
for(ParameterValue value : params) {
BuildWrapper wrapper=value.createBuildWrapper(Promotion.this);
if (wrapper!=null){
Environment e = wrapper.setUp(Promotion.this, launcher, listener);
if(e==null)
return Result.FAILURE;
buildEnvironments.add(e);
}
}
}
for( BuildWrapper w : wrappers ) {
Environment e = w.setUp(Promotion.this, launcher, listener);
if(e == null)
return Result.FAILURE;
buildEnvironments.add(e);
}
if(!build(listener,project.getBuildSteps(),target))
return Result.FAILURE;
return null;
} finally {
boolean failed = false;
for(int i = buildEnvironments.size()-1; i >= 0; i--) {
if (!buildEnvironments.get(i).tearDown(Promotion.this,listener)) {
failed=true;
}
}
if(failed)
return Result.FAILURE;
}
}
protected void post2(BuildListener listener) throws Exception {
if (getTargetBuild() == null) {
listener.error("No Promotion target, cannot save target or update status");
return;
}
if(getResult()== Result.SUCCESS)
getStatus().onSuccessfulPromotion(Promotion.this);
// persist the updated build record
getTargetBuildOrFail().save();
if (getResult() == Result.SUCCESS) {
// we should evaluate any other pending promotions in case
// they had a condition on this promotion
PromotedBuildAction pba = getTargetBuildOrFail().getAction(PromotedBuildAction.class);
for (PromotionProcess pp : pba.getPendingPromotions()) {
pp.considerPromotion2(getTargetBuildOrFail());
}
// tickle PromotionTriggers
for (AbstractProject<?,?> p : Jenkins.get().getAllItems(AbstractProject.class)) {
PromotionTrigger pt = p.getTrigger(PromotionTrigger.class);
if (pt!=null)
pt.consider(Promotion.this);
}
}
}
private boolean build(final BuildListener listener,
final List<BuildStep> steps,
final Run promotedBuild)
throws IOException, InterruptedException
{
for( BuildStep bs : steps ) {
if ( bs instanceof BuildTrigger) {
BuildTrigger bt = (BuildTrigger)bs;
for(AbstractProject p : bt.getChildProjects()) {
listener.getLogger().println(
Messages.Promotion_RunnerImpl_SchedulingBuild(
HyperlinkNote.encodeTo('/' + p.getUrl(), p.getDisplayName())
)
);
p.scheduleBuild(0, new PromotionCause(promotionRun, promotedBuild));
}
} else if(!bs.perform(Promotion.this, launcher, listener)) {
listener.getLogger().println("failed build " + bs + " " + getResult());
return false;
} else {
listener.getLogger().println("build " + bs + " " + getResult());
}
}
return true;
}
private boolean preBuild(BuildListener listener, List<BuildStep> steps) {
for( BuildStep bs : steps ) {
if(!bs.prebuild(Promotion.this,listener)) {
listener.getLogger().println("failed pre build " + bs + " " + getResult());
return false;
}
}
return true;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Promotion.class, Messages._Promotion_Permissions_Title());
public static final Permission PROMOTE = new Permission(PERMISSIONS, "Promote", Messages._Promotion_PromotePermission_Description(), Jenkins.ADMINISTER, PermissionScope.RUN);
@Initializer(before = InitMilestone.SYSTEM_CONFIG_LOADED)
@Restricted(DoNotUse.class)
public static void registerPermissions() {
// Pending JENKINS-17200, ensure that the above permissions have been registered prior to
// allowing plugins to adapt the system configuration, which may depend on these permissions
// having been registered. Since this method is static and since it follows the above
// construction of static permission objects (and therefore their calls to
// PermissionGroup#register), there is nothing further to do in this method.
}
@Override
public int hashCode() {
return this.getId().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Promotion other = (Promotion) obj;
return this.getId().equals(other.getId());
}
/**
* Factory method for creating {@link ParametersAction}
* @param parameters
* @return
*/
public static ParametersAction createParametersAction(List<ParameterValue> parameters){
return new ParametersAction(parameters);
}
public static ParametersAction getParametersActions(Promotion build){
return build.getAction(ParametersAction.class);
}
/**
* Combine the target build parameters with the promotion build parameters
* @param actions
* @param build
* @param promotionParams
* @deprecated Use {@link PromotionParametersAction} with constructor instead.
*/
@Deprecated
public static void buildParametersAction(@NonNull List<Action> actions,
@NonNull AbstractBuild<?, ?> build,
@CheckForNull List<ParameterValue> promotionParams) {
// Create list of actions to pass to scheduled build
actions.add(PromotionParametersAction.buildFor(build, promotionParams));
}
private static final Logger LOGGER = Logger.getLogger(Promotion.class.getName());
/**
* Action, which stores promotion parameters.
* This class allows defining custom parameters filtering logic, which is
* important for versions after the SECURITY-170 fix.
* @since TODO
*/
@Restricted(NoExternalUse.class)
public static class PromotionParametersAction extends ParametersAction {
private List<ParameterValue> unfilteredParameters;
private PromotionParametersAction(List<ParameterValue> params) {
// Pass the parameters upstairs
super(params);
unfilteredParameters = params;
}
@Override
public List<ParameterValue> getParameters() {
return Collections.unmodifiableList(filter(unfilteredParameters));
}
private List<ParameterValue> filter(List<ParameterValue> params) {
// buildToBePromoted::getParameters() invokes the secured method, hence all
// parameters from the promoted build are safe.
return params;
}
public static PromotionParametersAction buildFor(
@NonNull AbstractBuild<?, ?> buildToBePromoted,
@CheckForNull List<ParameterValue> promotionParams) {
if (promotionParams == null) {
promotionParams = new ArrayList<ParameterValue>();
}
List<ParameterValue> params = new ArrayList<ParameterValue>();
//Add the target build parameters first, if the same parameter is not being provided by the promotion build
List<ParametersAction> parameters = buildToBePromoted.getActions(ParametersAction.class);
for (ParametersAction paramAction : parameters) {
for (ParameterValue pvalue : paramAction.getParameters()) {
if (!promotionParams.contains(pvalue)) {
params.add(pvalue);
}
}
}
//Add all the promotion build parameters
params.addAll(promotionParams);
// Create list of actions to pass to scheduled build
return new PromotionParametersAction(params);
}
}
}