-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
AbstractBuild.java
1420 lines (1247 loc) · 53.6 KB
/
AbstractBuild.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
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
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., 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 hudson.model;
import static java.util.logging.Level.WARNING;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SCMListener;
import hudson.remoting.ChannelClosedException;
import hudson.remoting.RequestAbortedException;
import hudson.scm.ChangeLogParser;
import hudson.scm.ChangeLogSet;
import hudson.scm.NullChangeLogParser;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.slaves.NodeProperty;
import hudson.slaves.OfflineCause;
import hudson.slaves.WorkspaceList;
import hudson.slaves.WorkspaceList.Lease;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Fingerprinter.FingerprintAction;
import hudson.tasks.Publisher;
import hudson.util.AdaptedIterator;
import hudson.util.HttpResponses;
import hudson.util.Iterators;
import hudson.util.VariableResolver;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.ref.WeakReference;
import java.nio.channels.ClosedByInterruptException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.model.lazy.BuildReference;
import jenkins.model.lazy.LazyBuildMixIn;
import jenkins.scm.RunWithSCM;
import jenkins.util.SystemProperties;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.xml.sax.SAXException;
/**
* Base implementation of {@link Run}s that build software.
*
* For now this is primarily the common part of {@link Build} and MavenBuild.
*
* @author Kohsuke Kawaguchi
* @see AbstractProject
*/
public abstract class AbstractBuild<P extends AbstractProject<P, R>, R extends AbstractBuild<P, R>> extends Run<P, R> implements Queue.Executable, LazyBuildMixIn.LazyLoadingRun<P, R>, RunWithSCM<P, R> {
/**
* Set if we want the blame information to flow from upstream to downstream build.
*/
private static final boolean upstreamCulprits = SystemProperties.getBoolean("hudson.upstreamCulprits");
/**
* Name of the agent this project was built on.
* Null or "" if built by the built-in node. (null happens when we read old record that didn't have this information.)
*/
private String builtOn;
/**
* The file path on the node that performed a build. Kept as a string since {@link FilePath} is not serializable into XML.
* @since 1.319
*/
private String workspace;
/**
* Version of Hudson that built this.
*/
private String hudsonVersion;
/**
* SCM used for this build.
*/
private ChangeLogParser scm;
/**
* Changes in this build.
*/
private transient volatile WeakReference<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSet;
/**
* Cumulative list of people who contributed to the build problem.
*
* <p>
* This is a list of {@link User#getId() user ids} who made a change
* since the last non-broken build. Can be null (which should be
* treated like empty set), because of the compatibility.
*
* <p>
* This field is semi-final --- once set the value will never be modified.
*
* @since 1.137
*/
private volatile Set<String> culprits;
/**
* During the build this field remembers {@link hudson.tasks.BuildWrapper.Environment}s created by
* {@link BuildWrapper}. This design is bit ugly but forced due to compatibility.
*/
protected transient List<Environment> buildEnvironments;
private final transient LazyBuildMixIn.RunMixIn<P, R> runMixIn = new LazyBuildMixIn.RunMixIn<>() {
@Override protected R asRun() {
return _this();
}
};
protected AbstractBuild(P job) throws IOException {
super(job);
}
protected AbstractBuild(P job, Calendar timestamp) {
super(job, timestamp);
}
protected AbstractBuild(P project, File buildDir) throws IOException {
super(project, buildDir);
}
public final P getProject() {
return getParent();
}
@Override public final LazyBuildMixIn.RunMixIn<P, R> getRunMixIn() {
return runMixIn;
}
@NonNull
@Override protected final BuildReference<R> createReference() {
return getRunMixIn().createReference();
}
@Override protected final void dropLinks() {
getRunMixIn().dropLinks();
}
@Override
public R getPreviousBuild() {
return getRunMixIn().getPreviousBuild();
}
@Override
public R getNextBuild() {
return getRunMixIn().getNextBuild();
}
/**
* Returns a {@link Slave} on which this build was done.
*
* @return
* null, for example if the agent that this build run no longer exists.
*/
public @CheckForNull Node getBuiltOn() {
if (builtOn == null || builtOn.isEmpty())
return Jenkins.get();
else
return Jenkins.get().getNode(builtOn);
}
/**
* Returns the name of the agent it was built on; null or "" if built by the built-in node.
* (null happens when we read old record that didn't have this information.)
*/
@Exported(name = "builtOn")
public String getBuiltOnStr() {
return builtOn;
}
/**
* Allows subtypes to set the value of {@link #builtOn}.
* This is used for those implementations where an {@link AbstractBuild} is made 'built' without
* actually running its {@link #run()} method.
*
* @since 1.429
*/
protected void setBuiltOnStr(String builtOn) {
this.builtOn = builtOn;
}
/**
* Gets the nearest ancestor {@link AbstractBuild} that belongs to
* {@linkplain AbstractProject#getRootProject() the root project of getProject()} that
* dominates/governs/encompasses this build.
*
* <p>
* Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs,
* and still in some of them, builds of child projects are related/tied to that of the parent project.
* In such a case, this method returns the governing build.
*
* @return never null. In the worst case the build dominates itself.
* @since 1.421
* @see AbstractProject#getRootProject()
*/
public AbstractBuild<?, ?> getRootBuild() {
return this;
}
@Override
public Queue.Executable getParentExecutable() {
AbstractBuild<?, ?> rootBuild = getRootBuild();
return rootBuild != this ? rootBuild : null;
}
/**
* Used to render the side panel "Back to project" link.
*
* <p>
* In a rare situation where a build can be reached from multiple paths,
* returning different URLs from this method based on situations might
* be desirable.
*
* <p>
* If you override this method, you'll most likely also want to override
* {@link #getDisplayName()}.
* @deprecated navigation through a hierarchy should be done through breadcrumbs, do not add a link using this method
*/
@Deprecated(since = "2.364")
public String getUpUrl() {
return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(), getParent()) + '/';
}
/**
* Gets the directory where this build is being built.
*
* <p>
* Note to implementors: to control where the workspace is created, override
* {@link AbstractBuildExecution#decideWorkspace(Node,WorkspaceList)}.
*
* @return
* null if the workspace is on an agent that's not connected. Note that once the build is completed,
* the workspace may be used to build something else, so the value returned from this method may
* no longer show a workspace as it was used for this build.
* @since 1.319
*/
public final @CheckForNull FilePath getWorkspace() {
if (workspace == null) return null;
Node n = getBuiltOn();
if (n == null) return null;
return n.createPath(workspace);
}
/**
* Normally, a workspace is assigned by {@link hudson.model.Run.RunExecution}, but this lets you set the workspace in case
* {@link AbstractBuild} is created without a build.
*/
protected void setWorkspace(@NonNull FilePath ws) {
this.workspace = ws.getRemote();
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where {@code pom.xml}, {@code build.xml}
* and so on exists.
*/
public final FilePath getModuleRoot() {
FilePath ws = getWorkspace();
if (ws == null) return null;
return getParent().getScm().getModuleRoot(ws, this);
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*/
public FilePath[] getModuleRoots() {
FilePath ws = getWorkspace();
if (ws == null) return null;
return getParent().getScm().getModuleRoots(ws, this);
}
@Override
@CheckForNull public Set<String> getCulpritIds() {
return culprits;
}
@Override
@Exported
@NonNull public Set<User> getCulprits() {
return RunWithSCM.super.getCulprits();
}
@Override
public boolean shouldCalculateCulprits() {
return getCulpritIds() == null;
}
@Override
@NonNull
public Set<User> calculateCulprits() {
Set<User> c = RunWithSCM.super.calculateCulprits();
AbstractBuild<P, R> p = getPreviousCompletedBuild();
if (upstreamCulprits) {
// If we have dependencies since the last successful build, add their authors to our list
if (p != null && p.getPreviousNotFailedBuild() != null) {
Map<AbstractProject, AbstractBuild.DependencyChange> depmap =
p.getDependencyChanges(p.getPreviousSuccessfulBuild());
for (AbstractBuild.DependencyChange dep : depmap.values()) {
for (AbstractBuild<?, ?> b : dep.getBuilds()) {
for (ChangeLogSet.Entry entry : b.getChangeSet()) {
c.add(entry.getAuthor());
}
}
}
}
}
return c;
}
/**
* Gets the version of Hudson that was used to build this job.
*
* @since 1.246
*/
public String getHudsonVersion() {
return hudsonVersion;
}
/**
* @deprecated as of 1.467
* Please use {@link hudson.model.Run.RunExecution}
*/
@Deprecated
public abstract class AbstractRunner extends AbstractBuildExecution {
}
public abstract class AbstractBuildExecution extends Runner {
/*
Some plugins might depend on this instance castable to Runner, so we need to use
deprecated class here.
*/
/**
* Since configuration can be changed while a build is in progress,
* create a launcher once and stick to it for the entire build duration.
*/
protected Launcher launcher;
/**
* Output/progress of this build goes here.
*/
protected BuildListener listener;
/**
* Lease of the workspace.
*/
private Lease lease;
/**
* Returns the current {@link Node} on which we are building.
* @return Returns the current {@link Node}
* @throws IllegalStateException if that cannot be determined
*/
protected final @NonNull Node getCurrentNode() throws IllegalStateException {
Executor exec = Executor.currentExecutor();
if (exec == null) {
throw new IllegalStateException("not being called from an executor thread");
}
Computer c = exec.getOwner();
Node node = c.getNode();
if (node == null) {
throw new IllegalStateException("no longer a configured node for " + c.getName());
}
return node;
}
public Launcher getLauncher() {
return launcher;
}
public BuildListener getListener() {
return listener;
}
/**
* Allocates the workspace from {@link WorkspaceList}.
*
* @param n
* Passed in for the convenience. The node where the build is running.
* @param wsl
* Passed in for the convenience. The returned path must be registered to this object.
*/
protected Lease decideWorkspace(@NonNull Node n, WorkspaceList wsl) throws InterruptedException, IOException {
String customWorkspace = getProject().getCustomWorkspace();
if (customWorkspace != null) {
FilePath rootPath = n.getRootPath();
if (rootPath == null) {
throw new AbortException(n.getDisplayName() + " seems to be offline");
}
// we allow custom workspaces to be concurrently used between jobs.
return Lease.createDummyLease(rootPath.child(getEnvironment(listener).expand(customWorkspace)));
}
// TODO: this cast is indicative of abstraction problem
FilePath ws = n.getWorkspaceFor((TopLevelItem) getProject());
if (ws == null) {
throw new AbortException(n.getDisplayName() + " seems to be offline");
}
return wsl.allocate(ws, getBuild());
}
@NonNull
@Override
public Result run(@NonNull BuildListener listener) throws Exception {
final Node node = getCurrentNode();
assert builtOn == null;
builtOn = node.getNodeName();
hudsonVersion = Jenkins.VERSION;
this.listener = listener;
Result result = null;
buildEnvironments = new ArrayList<>();
// JENKINS-43889: try/finally to make sure Environments are eventually torn down. This used to be done in
// the doRun() implementation, but was not happening in case of early error (for instance in SCM checkout).
// Because some plugin (Maven) implement their own doRun() logic which still includes tearing down in some
// cases, we use a dummy Environment as a marker, to avoid doing it here if redundant.
TearDownCheckEnvironment tearDownMarker = new TearDownCheckEnvironment();
buildEnvironments.add(tearDownMarker);
try {
launcher = createLauncher(listener);
if (!Jenkins.get().getNodes().isEmpty()) {
if (node instanceof Jenkins) {
listener.getLogger().print(Messages.AbstractBuild_BuildingOnMaster());
} else {
listener.getLogger().print(Messages.AbstractBuild_BuildingRemotely(ModelHyperlinkNote.encodeTo("/computer/" + builtOn, node.getDisplayName())));
Set<LabelAtom> assignedLabels = new HashSet<>(node.getAssignedLabels());
assignedLabels.remove(node.getSelfLabel());
if (!assignedLabels.isEmpty()) {
boolean first = true;
for (LabelAtom label : assignedLabels) {
if (first) {
listener.getLogger().print(" (");
first = false;
} else {
listener.getLogger().print(' ');
}
listener.getLogger().print(label.getName());
}
listener.getLogger().print(')');
}
}
} else {
listener.getLogger().print(Messages.AbstractBuild_Building());
}
lease = decideWorkspace(node, Computer.currentComputer().getWorkspaceList());
workspace = lease.path.getRemote();
listener.getLogger().println(Messages.AbstractBuild_BuildingInWorkspace(workspace));
for (WorkspaceListener wl : WorkspaceListener.all()) {
wl.beforeUse(AbstractBuild.this, lease.path, listener);
}
getProject().getScmCheckoutStrategy().preCheckout(AbstractBuild.this, launcher, this.listener);
getProject().getScmCheckoutStrategy().checkout(this);
if (!preBuild(listener, project.getProperties()))
return Result.FAILURE;
result = doRun(listener);
} finally {
if (!tearDownMarker.tornDown) {
// looks like environments are not torn down yet, do it now (might affect the build result)
result = Result.combine(result, tearDownBuildEnvironments(listener));
}
}
if (node.getChannel() != null) {
// kill run-away processes that are left
// use multiple environment variables so that people can escape this massacre by overriding an environment
// variable for some processes
launcher.kill(getCharacteristicEnvVars());
}
// this is ugly, but for historical reason, if non-null value is returned
// it should become the final result.
if (result == null) result = getResult();
if (result == null) result = Result.SUCCESS;
return result;
}
/**
* Tear down all build environments (in reverse order).
* <p>
* Returns a failure {@link Result} in case of failure of at least one {@code tearDown()} method (returning
* false, or throwing some exception), and {@code null} if everything went fine.
*
* @return a build result in case of failure/exception
* @throws InterruptedException
* if thrown while tearing down an environment (would be the first caught one in case caught several)
*/
private Result tearDownBuildEnvironments(@NonNull BuildListener listener) throws InterruptedException {
Result result = null;
InterruptedException firstInterruptedException = null;
// iterate in reverse order on the environments list
for (int i = buildEnvironments.size() - 1; i >= 0; i--) {
final Environment environment = buildEnvironments.get(i);
try {
if (!environment.tearDown(AbstractBuild.this, listener)) {
// by returning false, tearDown() can actually fail the build
result = Result.combine(result, Result.FAILURE);
}
} catch (InterruptedException e) {
// We got interrupted while tearing down an environment. We'll still try to tear down the
// remaining ones, but then we'll re-throw the (first) caught InterruptedException, to let
// the caller (ie., Run#execute(RunExecution)) deal with it properly.
if (firstInterruptedException == null) {
firstInterruptedException = e;
} else {
// log only InterruptedException we won't re-throw
Functions.printStackTrace(e, listener.error("Interrupted during tear down: " + e.getMessage()));
}
} catch (IOException | RuntimeException e) {
// exceptions are only logged, to give a chance to all environments to tear down
if (e instanceof IOException) {
// similar to Run#handleFatalBuildProblem(BuildListener, Throwable)
Util.displayIOException((IOException) e, listener);
}
Functions.printStackTrace(e, listener.error("Unable to tear down: " + e.getMessage()));
// would UNSTABLE be more sensible? (see discussion in PR #4517)
result = Result.combine(result, Result.FAILURE);
}
}
if (firstInterruptedException != null) {
// don't forget we've been interrupted
throw firstInterruptedException;
}
return result;
}
/**
* Creates a {@link Launcher} that this build will use. This can be overridden by derived types
* to decorate the resulting {@link Launcher}.
*
* @param listener
* Always non-null. Connected to the main build output.
*/
@NonNull
protected Launcher createLauncher(@NonNull BuildListener listener) throws IOException, InterruptedException {
final Node currentNode = getCurrentNode();
Launcher l = currentNode.createLauncher(listener);
if (project instanceof BuildableItemWithBuildWrappers) {
BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project;
for (BuildWrapper bw : biwbw.getBuildWrappersList())
l = bw.decorateLauncher(AbstractBuild.this, l, listener);
}
for (RunListener rl : RunListener.all()) {
Environment environment = rl.setUpEnvironment(AbstractBuild.this, l, listener);
if (environment != null) {
buildEnvironments.add(environment);
}
}
for (NodeProperty nodeProperty : Jenkins.get().getGlobalNodeProperties()) {
Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener);
if (environment != null) {
buildEnvironments.add(environment);
}
}
for (NodeProperty nodeProperty : currentNode.getNodeProperties()) {
Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener);
if (environment != null) {
buildEnvironments.add(environment);
}
}
return l;
}
public void defaultCheckout() throws IOException, InterruptedException {
AbstractBuild<?, ?> build = AbstractBuild.this;
AbstractProject<?, ?> project = build.getProject();
for (int retryCount = project.getScmCheckoutRetryCount(); ; retryCount--) {
build.scm = NullChangeLogParser.INSTANCE;
try {
File changeLogFile = new File(build.getRootDir(), "changelog.xml");
if (project.checkout(build, launcher, listener, changeLogFile)) {
// check out succeeded
SCM scm = project.getScm();
for (SCMListener l : SCMListener.all()) {
try {
l.onCheckout(build, scm, build.getWorkspace(), listener, changeLogFile, build.getAction(SCMRevisionState.class));
} catch (Exception e) {
throw new IOException(e);
}
}
build.scm = scm.createChangeLogParser();
build.changeSet = new WeakReference<>(build.calcChangeSet());
for (SCMListener l : SCMListener.all())
try {
l.onChangeLogParsed(build, listener, build.getChangeSet());
} catch (Exception e) {
throw new IOException("Failed to parse changelog", e);
}
// Get a chance to do something after checkout and changelog is done
scm.postCheckout(build, launcher, build.getWorkspace(), listener);
return;
}
} catch (AbortException e) {
listener.error(e.getMessage());
} catch (ClosedByInterruptException | InterruptedIOException e) {
throw (InterruptedException) new InterruptedException().initCause(e);
} catch (IOException e) {
// checkout error not yet reported
Functions.printStackTrace(e, listener.getLogger());
}
if (retryCount == 0) // all attempts failed
throw new RunnerAbortedException();
listener.getLogger().println("Retrying after 10 seconds");
Thread.sleep(10000);
}
}
/**
* The portion of a build that is specific to a subclass of {@link AbstractBuild}
* goes here.
*
* @return
* null to continue the build normally (that means the doRun method
* itself run successfully)
* Return a non-null value to abort the build right there with the specified result code.
*/
protected abstract Result doRun(BuildListener listener) throws Exception;
/**
* @see #post(BuildListener)
*/
protected abstract void post2(BuildListener listener) throws Exception;
@Override
public final void post(@NonNull BuildListener listener) throws Exception {
try {
post2(listener);
} finally {
// update the culprit list
SortedSet<String> r = new TreeSet<>();
for (User u : getCulprits())
r.add(u.getId());
culprits = Collections.unmodifiableSet(r);
CheckPoint.CULPRITS_DETERMINED.report();
}
}
@Override
public void cleanUp(@NonNull BuildListener listener) throws Exception {
if (lease != null) {
lease.release();
lease = null;
}
BuildTrigger.execute(AbstractBuild.this, listener);
buildEnvironments = null;
}
/**
* @deprecated as of 1.356
* Use {@link #performAllBuildSteps(BuildListener, Map, boolean)}
*/
@Deprecated
protected final void performAllBuildStep(BuildListener listener, Map<?, ? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
performAllBuildSteps(listener, buildSteps.values(), phase);
}
protected final boolean performAllBuildSteps(BuildListener listener, Map<?, ? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
return performAllBuildSteps(listener, buildSteps.values(), phase);
}
/**
* @deprecated as of 1.356
* Use {@link #performAllBuildSteps(BuildListener, Iterable, boolean)}
*/
@Deprecated
protected final void performAllBuildStep(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
performAllBuildSteps(listener, buildSteps, phase);
}
/**
* Runs all the given build steps, even if one of them fail.
*
* @param phase
* true for the post build processing, and false for the final "run after finished" execution.
*
* @return false if any build step failed
*/
protected final boolean performAllBuildSteps(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
boolean r = true;
for (BuildStep bs : buildSteps) {
if ((bs instanceof Publisher && ((Publisher) bs).needsToRunAfterFinalized()) ^ phase)
try {
if (!perform(bs, listener)) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, bs});
r = false;
if (phase) {
setResult(Result.FAILURE);
}
}
} catch (Exception | LinkageError e) {
reportError(bs, e, listener, phase);
r = false;
}
}
return r;
}
private void reportError(BuildStep bs, Throwable e, BuildListener listener, boolean phase) {
final String buildStep;
if (bs instanceof Describable) {
buildStep = ((Describable) bs).getDescriptor().getDisplayName();
} else {
buildStep = bs.getClass().getName();
}
if (e instanceof AbortException) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, buildStep});
listener.error("Step ‘" + buildStep + "’ failed: " + e.getMessage());
} else {
String msg = "Step ‘" + buildStep + "’ aborted due to exception: ";
Functions.printStackTrace(e, listener.error(msg));
LOGGER.log(WARNING, msg, e);
}
if (phase) {
setResult(Result.FAILURE);
}
}
/**
* Calls a build step.
*/
protected final boolean perform(BuildStep bs, BuildListener listener) throws InterruptedException, IOException {
BuildStepMonitor mon = bs.getRequiredMonitorService();
Result oldResult = AbstractBuild.this.getResult();
for (BuildStepListener bsl : BuildStepListener.all()) {
bsl.started(AbstractBuild.this, bs, listener);
}
boolean canContinue = false;
try {
canContinue = mon.perform(bs, AbstractBuild.this, launcher, listener);
} catch (RequestAbortedException | ChannelClosedException ex) {
// Channel is closed, do not continue
reportBrokenChannel(listener);
} catch (RuntimeException ex) {
Functions.printStackTrace(ex, listener.error("Build step failed with exception"));
}
for (BuildStepListener bsl : BuildStepListener.all()) {
bsl.finished(AbstractBuild.this, bs, listener, canContinue);
}
Result newResult = AbstractBuild.this.getResult();
if (newResult != oldResult) {
String buildStepName = getBuildStepName(bs);
listener.getLogger().format("Build step '%s' changed build result to %s%n", buildStepName, newResult);
}
if (!canContinue) {
String buildStepName = getBuildStepName(bs);
listener.getLogger().format("Build step '%s' marked build as failure%n", buildStepName);
}
return canContinue;
}
private void reportBrokenChannel(BuildListener listener) throws IOException {
final Node node = getCurrentNode();
listener.hyperlink("/" + node.toComputer().getUrl() + "log", "Agent went offline during the build");
listener.getLogger().println();
final OfflineCause offlineCause = node.toComputer().getOfflineCause();
if (offlineCause != null) {
listener.error(offlineCause.toString());
}
}
private String getBuildStepName(BuildStep bs) {
if (bs instanceof Describable<?>) {
return ((Describable<?>) bs).getDescriptor().getDisplayName();
} else {
return bs.getClass().getSimpleName();
}
}
protected final boolean preBuild(BuildListener listener, Map<?, ? extends BuildStep> steps) {
return preBuild(listener, steps.values());
}
protected final boolean preBuild(BuildListener listener, Collection<? extends BuildStep> steps) {
return preBuild(listener, (Iterable<? extends BuildStep>) steps);
}
protected final boolean preBuild(BuildListener listener, Iterable<? extends BuildStep> steps) {
for (BuildStep bs : steps)
if (!bs.prebuild(AbstractBuild.this, listener)) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, bs});
return false;
}
return true;
}
}
/**
* An {@link Environment} which does nothing, but change state when it gets torn down. Used in
* {@link AbstractBuildExecution#run(BuildListener)} to detect whether environments have yet to be torn down,
* or if it has been done already (in the {@link AbstractBuildExecution#doRun(BuildListener)} implementation).
*/
private static class TearDownCheckEnvironment extends Environment {
private boolean tornDown = false;
@Override
public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException {
this.tornDown = true;
return true;
}
}
/*
* No need to lock the entire AbstractBuild on change set calculation
*/
private transient Object changeSetLock = new Object();
/**
* Gets the changes incorporated into this build.
*
* @return never null.
*/
@Exported
@NonNull public ChangeLogSet<? extends ChangeLogSet.Entry> getChangeSet() {
synchronized (changeSetLock) {
if (scm == null) {
scm = NullChangeLogParser.INSTANCE;
}
}
ChangeLogSet<? extends ChangeLogSet.Entry> cs = null;
if (changeSet != null)
cs = changeSet.get();
if (cs == null)
cs = calcChangeSet();
// defensive check. if the calculation fails (such as through an exception),
// set a dummy value so that it'll work the next time. the exception will
// be still reported, giving the plugin developer an opportunity to fix it.
if (cs == null)
cs = ChangeLogSet.createEmpty(this);
changeSet = new WeakReference<>(cs);
return cs;
}
@Override
@NonNull public List<ChangeLogSet<? extends ChangeLogSet.Entry>> getChangeSets() {
ChangeLogSet<? extends ChangeLogSet.Entry> cs = getChangeSet();
return cs.isEmptySet() ? Collections.emptyList() : List.of(cs);
}
/**
* Returns true if the changelog is already computed.
*/
public boolean hasChangeSetComputed() {
File changelogFile = new File(getRootDir(), "changelog.xml");
return changelogFile.exists();
}
private ChangeLogSet<? extends ChangeLogSet.Entry> calcChangeSet() {
File changelogFile = new File(getRootDir(), "changelog.xml");
if (!changelogFile.exists())
return ChangeLogSet.createEmpty(this);
try {
return scm.parse(this, changelogFile);
} catch (IOException | SAXException e) {
LOGGER.log(WARNING, "Failed to parse " + changelogFile, e);
}
return ChangeLogSet.createEmpty(this);
}
@NonNull
@Override
public EnvVars getEnvironment(@NonNull TaskListener log) throws IOException, InterruptedException {
EnvVars env = super.getEnvironment(log);
FilePath ws = getWorkspace();
if (ws != null) { // if this is done very early on in the build, workspace may not be decided yet. see JENKINS-3997
env.put("WORKSPACE", ws.getRemote());
FilePath tempDir = WorkspaceList.tempDir(ws);
if (tempDir != null) {
env.put("WORKSPACE_TMP", tempDir.getRemote()); // JENKINS-60634
}
}
project.getScm().buildEnvVars(this, env);
if (buildEnvironments != null)
for (Environment e : buildEnvironments)
e.buildEnvVars(env);
for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class))
a.buildEnvVars(this, env);
EnvVars.resolve(env);
return env;
}
/**
* During the build, expose the environments contributed by {@link BuildWrapper}s and others.
*
* <p>
* Since 1.444, executor thread that's doing the build can access mutable underlying list,
* which allows the caller to add/remove environments. The recommended way of adding
* environment is through {@link BuildWrapper}, but this might be handy for build steps
* who wants to expose additional environment variables to the rest of the build.
*
* @return can be empty list, but never null. Immutable.
* @since 1.437
*/
public EnvironmentList getEnvironments() {
Executor e = Executor.currentExecutor();
if (e != null && e.getCurrentExecutable() == this) {
if (buildEnvironments == null) buildEnvironments = new ArrayList<>();
return new EnvironmentList(buildEnvironments);
}
return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : List.copyOf(buildEnvironments));