-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathRun.java
2678 lines (2374 loc) · 94.6 KB
/
Run.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-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Daniel Dyer, Red Hat, Inc., Tom Huybrechts, Romain Seguy, Yahoo! Inc.,
* Darek Ostolski, CloudBees, Inc.
* Copyright (c) 2012, Martin Schroeder, Intel Mobile Communications GmbH
* Copyright (c) 2019 Intel Corporation
*
* 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.FINE;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
import com.jcraft.jzlib.GZIPInputStream;
import com.thoughtworks.xstream.XStream;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.AbortException;
import hudson.BulkChange;
import hudson.EnvVars;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FeedAdapter;
import hudson.Functions;
import hudson.Util;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.console.AnnotatedLargeText;
import hudson.console.ConsoleLogFilter;
import hudson.console.ConsoleNote;
import hudson.console.ModelHyperlinkNote;
import hudson.console.PlainTextConsoleOutputStream;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.queue.SubTask;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Fingerprinter.FingerprintAction;
import hudson.util.FormApply;
import hudson.util.LogTaskListener;
import hudson.util.ProcessTree;
import hudson.util.XStream2;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import jenkins.model.ArtifactManager;
import jenkins.model.ArtifactManagerConfiguration;
import jenkins.model.ArtifactManagerFactory;
import jenkins.model.BuildDiscarder;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.RunAction2;
import jenkins.model.StandardArtifactManager;
import jenkins.model.lazy.BuildReference;
import jenkins.model.lazy.LazyBuildMixIn;
import jenkins.security.MasterToSlaveCallable;
import jenkins.util.SystemProperties;
import jenkins.util.VirtualFile;
import jenkins.util.io.OnMaster;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.lang.ArrayUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.verb.POST;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
/**
* A particular execution of {@link Job}.
*
* <p>
* Custom {@link Run} type is always used in conjunction with
* a custom {@link Job} type, so there's no separate registration
* mechanism for custom {@link Run} types.
*
* @author Kohsuke Kawaguchi
* @see RunListener
*/
@ExportedBean
public abstract class Run<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, RunT>>
extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner, OnMaster, StaplerProxy {
/**
* The original {@link Queue.Item#getId()} has not yet been mapped onto the {@link Run} instance.
* @since 1.601
*/
public static final long QUEUE_ID_UNKNOWN = -1;
/**
* Target size limit for truncated {@link #description}s in the Build History Widget.
* This is applied to the raw, unformatted description. Especially complex formatting
* like hyperlinks can result in much less text being shown than this might imply.
* Negative values will disable truncation, {@code 0} will enforce empty strings.
* @since 2.223
*/
private static /* non-final for Groovy */ int TRUNCATED_DESCRIPTION_LIMIT = SystemProperties.getInteger("historyWidget.descriptionLimit", 100);
protected final transient @NonNull JobT project;
/**
* Build number.
*
* <p>
* In earlier versions < 1.24, this number is not unique nor continuous,
* but going forward, it will, and this really replaces the build id.
*/
public transient /*final*/ int number;
/**
* The original Queue task ID from where this Run instance originated.
*/
private long queueId = Run.QUEUE_ID_UNKNOWN;
/**
* Previous build. Can be null.
* TODO JENKINS-22052 this is not actually implemented any more
*
* External code should use {@link #getPreviousBuild()}
*/
@Restricted(NoExternalUse.class)
protected transient volatile RunT previousBuild;
/**
* Next build. Can be null.
*
* External code should use {@link #getNextBuild()}
*/
@Restricted(NoExternalUse.class)
protected transient volatile RunT nextBuild;
/**
* Pointer to the next younger build in progress. This data structure is lazily updated,
* so it may point to the build that's already completed. This pointer is set to 'this'
* if the computation determines that everything earlier than this build is already completed.
*/
/* does not compile on JDK 7: private*/ transient volatile RunT previousBuildInProgress;
/** ID as used for historical build records; otherwise null. */
private @CheckForNull String id;
/**
* When the build is scheduled.
*/
protected /*final*/ long timestamp;
/**
* When the build has started running.
*
* For historical reasons, 0 means no value is recorded.
*
* @see #getStartTimeInMillis()
*/
private long startTime;
/**
* The build result.
* This value may change while the state is in {@link Run.State#BUILDING}.
*/
protected volatile Result result;
/**
* Human-readable description which is used on the main build page.
* It can also be quite long, and it may use markup in a format defined by a {@link hudson.markup.MarkupFormatter}.
* {@link #getTruncatedDescription()} may be used to retrieve a size-limited description,
* but it implies some limitations.
*/
@CheckForNull
protected volatile String description;
/**
* Human-readable name of this build. Can be null.
* If non-null, this text is displayed instead of "#NNN", which is the default.
* @since 1.390
*/
private volatile String displayName;
/**
* The current build state.
*/
private transient volatile State state;
private enum State {
/**
* Build is created/queued but we haven't started building it.
*/
NOT_STARTED,
/**
* Build is in progress.
*/
BUILDING,
/**
* Build is completed now, and the status is determined,
* but log files are still being updated.
*
* The significance of this state is that Jenkins
* will now see this build as completed. Things like
* "triggering other builds" requires this as pre-condition.
* See JENKINS-980.
*/
POST_PRODUCTION,
/**
* Build is completed now, and log file is closed.
*/
COMPLETED
}
/**
* Number of milli-seconds it took to run this build.
*/
protected long duration;
/**
* Charset in which the log file is written.
* For compatibility reason, this field may be null.
* For persistence, this field is string and not {@link Charset}.
*
* @see #getCharset()
* @since 1.257
*/
protected String charset;
/**
* Keeps this build.
*/
private boolean keepLog;
/**
* If the build is in progress, remember {@link RunExecution} that's running it.
* This field is not persisted.
*/
private transient volatile RunExecution runner;
/**
* Artifact manager associated with this build, if any.
* @since 1.532
*/
private @CheckForNull ArtifactManager artifactManager;
/**
* If the build is pending delete.
*/
private transient boolean isPendingDelete;
/**
* Creates a new {@link Run}.
* @param job Owner job
* @see LazyBuildMixIn#newBuild
*/
protected Run(@NonNull JobT job) throws IOException {
this(job, System.currentTimeMillis());
this.number = project.assignBuildNumber();
LOGGER.log(FINER, "new {0} @{1}", new Object[] {this, hashCode()});
}
/**
* Constructor for creating a {@link Run} object in
* an arbitrary state.
* {@link #number} must be set manually.
* <p>May be used in a {@link SubTask#createExecutable} (instead of calling {@link LazyBuildMixIn#newBuild}).
* For example, {@code MatrixConfiguration.newBuild} does this
* so that the {@link #timestamp} as well as {@link #number} are shared with the parent build.
*/
protected Run(@NonNull JobT job, @NonNull Calendar timestamp) {
this(job, timestamp.getTimeInMillis());
}
/** @see #Run(Job, Calendar) */
protected Run(@NonNull JobT job, long timestamp) {
this.project = job;
this.timestamp = timestamp;
this.state = State.NOT_STARTED;
}
/**
* Loads a run from a log file.
* @see LazyBuildMixIn#loadBuild
*/
protected Run(@NonNull JobT project, @NonNull File buildDir) throws IOException {
this.project = project;
this.previousBuildInProgress = _this(); // loaded builds are always completed
number = Integer.parseInt(buildDir.getName());
reload();
}
/**
* Reloads the build record from disk.
*
* @since 1.410
*/
public void reload() throws IOException {
this.state = State.COMPLETED;
// TODO ABORTED would perhaps make more sense than FAILURE:
this.result = Result.FAILURE; // defensive measure. value should be overwritten by unmarshal, but just in case the saved data is inconsistent
getDataFile().unmarshal(this); // load the rest of the data
if (state == State.COMPLETED) {
LOGGER.log(FINER, "reload {0} @{1}", new Object[] {this, hashCode()});
} else {
LOGGER.log(WARNING, "reload {0} @{1} with anomalous state {2}", new Object[] {this, hashCode(), state});
}
// not calling onLoad upon reload. partly because we don't want to call that from Run constructor,
// and partly because some existing use of onLoad isn't assuming that it can be invoked multiple times.
}
/**
* Called after the build is loaded and the object is added to the build list.
*/
@SuppressWarnings("deprecation")
protected void onLoad() {
for (Action a : getAllActions()) {
if (a instanceof RunAction2) {
try {
((RunAction2) a).onLoad(this);
} catch (RuntimeException x) {
LOGGER.log(WARNING, "failed to load " + a + " from " + getDataFile(), x);
removeAction(a); // if possible; might be in an inconsistent state
}
} else if (a instanceof RunAction) {
((RunAction) a).onLoad();
}
}
if (artifactManager != null) {
artifactManager.onLoad(this);
}
}
/**
* Return all transient actions associated with this build.
*
* @return the list can be empty but never null. read only.
* @deprecated Use {@link #getAllActions} instead.
*/
@Deprecated
public List<Action> getTransientActions() {
List<Action> actions = new ArrayList<>();
for (TransientBuildActionFactory factory : TransientBuildActionFactory.all()) {
for (Action created : factory.createFor(this)) {
if (created == null) {
LOGGER.log(WARNING, "null action added by {0}", factory);
continue;
}
actions.add(created);
}
}
return Collections.unmodifiableList(actions);
}
/**
* {@inheritDoc}
* A {@link RunAction2} is handled specially.
*/
@SuppressWarnings("deprecation")
@Override
public void addAction(@NonNull Action a) {
super.addAction(a);
if (a instanceof RunAction2) {
((RunAction2) a).onAttached(this);
} else if (a instanceof RunAction) {
((RunAction) a).onAttached(this);
}
}
/**
* Obtains 'this' in a more type safe signature.
*/
@SuppressWarnings("unchecked")
protected @NonNull RunT _this() {
return (RunT) this;
}
/**
* Ordering based on build numbers.
* If numbers are equal order based on names of parent projects.
*/
@Override
public int compareTo(@NonNull RunT that) {
final int res = this.number - that.number;
if (res == 0)
return this.getParent().getFullName().compareTo(that.getParent().getFullName());
return res;
}
/**
* Get the {@link Queue.Item#getId()} of the original queue item from where this Run instance
* originated.
* @return The queue item ID.
* @since 1.601
*/
@Exported
public long getQueueId() {
return queueId;
}
/**
* Set the queue item ID.
* <p>
* Mapped from the {@link Queue.Item#getId()}.
* @param queueId The queue item ID.
*/
@Restricted(NoExternalUse.class)
public void setQueueId(long queueId) {
this.queueId = queueId;
}
/**
* Returns the build result.
*
* <p>
* When a build is {@link #isBuilding() in progress}, this method
* returns an intermediate result.
* @return The status of the build, if it has completed or some build step has set a status; may be null if the build is ongoing.
*/
@Exported
public @CheckForNull Result getResult() {
return result;
}
/**
* Sets the {@link #getResult} of this build.
* Has no effect when the result is already set and worse than the proposed result.
* May only be called after the build has started and before it has moved into post-production
* (normally meaning both {@link #isInProgress} and {@link #isBuilding} are true).
* @param r the proposed new result
* @throws IllegalStateException if the build has not yet started, is in post-production, or is complete
*/
public void setResult(@NonNull Result r) {
if (state != State.BUILDING) {
throw new IllegalStateException("cannot change build result while in " + state);
}
// result can only get worse
if (result == null || r.isWorseThan(result)) {
result = r;
LOGGER.log(FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null);
}
}
/**
* Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
*/
public @NonNull List<BuildBadgeAction> getBadgeActions() {
List<BuildBadgeAction> r = getActions(BuildBadgeAction.class);
if (isKeepLog()) {
r = new ArrayList<>(r);
r.add(new KeepLogBuildBadge());
}
return r;
}
/**
* Returns true if the build is not completed yet.
* This includes "not started yet" state.
*/
@Exported
public boolean isBuilding() {
return state.compareTo(State.POST_PRODUCTION) < 0;
}
/**
* Determine whether the run is being build right now.
* @return true if after started and before completed.
* @since 1.538
*/
@Exported
public boolean isInProgress() {
return state.equals(State.BUILDING) || state.equals(State.POST_PRODUCTION);
}
/**
* Returns true if the log file is still being updated.
*/
public boolean isLogUpdated() {
return state.compareTo(State.COMPLETED) < 0;
}
/**
* Gets the {@link Executor} building this job, if it's being built.
* Otherwise null.
*
* This method looks for {@link Executor} who's {@linkplain Executor#getCurrentExecutable() assigned to this build},
* and because of that this might not be necessarily in sync with the return value of {@link #isBuilding()} —
* an executor holds on to {@link Run} some more time even after the build is finished (for example to
* perform {@linkplain Run.State#POST_PRODUCTION post-production processing}.)
* @see Executor#of
*/
@Exported
public @CheckForNull Executor getExecutor() {
return this instanceof Queue.Executable ? Executor.of((Queue.Executable) this) : null;
}
/**
* Gets the one off {@link Executor} building this job, if it's being built.
* Otherwise null.
* @since 1.433
*/
public @CheckForNull Executor getOneOffExecutor() {
for (Computer c : Jenkins.get().getComputers()) {
for (Executor e : c.getOneOffExecutors()) {
if (e.getCurrentExecutable() == this)
return e;
}
}
return null;
}
/**
* Gets the charset in which the log file is written.
* @return never null.
* @since 1.257
*/
public final @NonNull Charset getCharset() {
if (charset == null) return Charset.defaultCharset();
return Charset.forName(charset);
}
/**
* Returns the {@link Cause}s that triggered a build.
*
* <p>
* If a build sits in the queue for a long time, multiple build requests made during this period
* are all rolled up into one build, hence this method may return a list.
*
* @return
* can be empty but never null. read-only.
* @since 1.321
*/
public @NonNull List<Cause> getCauses() {
CauseAction a = getAction(CauseAction.class);
if (a == null) return Collections.emptyList();
return Collections.unmodifiableList(a.getCauses());
}
/**
* Returns a {@link Cause} of a particular type.
*
* @since 1.362
*/
public @CheckForNull <T extends Cause> T getCause(Class<T> type) {
for (Cause c : getCauses())
if (type.isInstance(c))
return type.cast(c);
return null;
}
/**
* Returns true if this build should be kept and not deleted.
* (Despite the name, this refers to the entire build, not merely the log file.)
* This is used as a signal to the {@link BuildDiscarder}.
*/
@Exported
public final boolean isKeepLog() {
return getWhyKeepLog() != null;
}
/**
* If {@link #isKeepLog()} returns true, returns a short, human-readable
* sentence that explains why it's being kept.
*/
public @CheckForNull String getWhyKeepLog() {
if (keepLog)
return Messages.Run_MarkedExplicitly();
return null; // not marked at all
}
/**
* The project this build is for.
*/
public @NonNull JobT getParent() {
return project;
}
/**
* When the build is scheduled.
*
* @see #getStartTimeInMillis()
*/
@Exported
public @NonNull Calendar getTimestamp() {
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(timestamp);
return c;
}
/**
* Same as {@link #getTimestamp()} but in a different type.
*/
public final @NonNull Date getTime() {
return new Date(timestamp);
}
/**
* Same as {@link #getTimestamp()} but in a different type, that is since the time of the epoch.
*/
public final long getTimeInMillis() {
return timestamp;
}
/**
* When the build has started running in an executor.
*
* For example, if a build is scheduled 1pm, and stayed in the queue for 1 hour (say, no idle agents),
* then this method returns 2pm, which is the time the job moved from the queue to the building state.
*
* @see #getTimestamp()
*/
public final long getStartTimeInMillis() {
if (startTime == 0) return timestamp; // fallback: approximate by the queuing time
return startTime;
}
@Exported
@CheckForNull
public String getDescription() {
return description;
}
/**
* Returns the length-limited description.
* The method tries to take HTML tags within the description into account, but it is a best-effort attempt.
* Also, the method will likely not work properly if a non-HTML {@link hudson.markup.MarkupFormatter} is used.
* @return The length-limited description.
* @deprecated truncated description based on the {@link #TRUNCATED_DESCRIPTION_LIMIT} setting.
*/
@Deprecated
public @CheckForNull String getTruncatedDescription() {
if (TRUNCATED_DESCRIPTION_LIMIT < 0) { // disabled
return description;
}
if (TRUNCATED_DESCRIPTION_LIMIT == 0) { // Someone wants to suppress descriptions, why not?
return "";
}
final int maxDescrLength = TRUNCATED_DESCRIPTION_LIMIT;
final String localDescription = description;
if (localDescription == null || localDescription.length() < maxDescrLength) {
return localDescription;
}
final String ending = "...";
final int sz = localDescription.length(), maxTruncLength = maxDescrLength - ending.length();
boolean inTag = false;
int displayChars = 0;
int lastTruncatablePoint = -1;
for (int i = 0; i < sz; i++) {
char ch = localDescription.charAt(i);
if (ch == '<') {
inTag = true;
} else if (ch == '>') {
inTag = false;
if (displayChars <= maxTruncLength) {
lastTruncatablePoint = i + 1;
}
}
if (!inTag) {
displayChars++;
if (displayChars <= maxTruncLength && ch == ' ') {
lastTruncatablePoint = i;
}
}
}
String truncDesc = localDescription;
// Could not find a preferred truncatable index, force a trunc at maxTruncLength
if (lastTruncatablePoint == -1)
lastTruncatablePoint = maxTruncLength;
if (displayChars >= maxDescrLength) {
truncDesc = truncDesc.substring(0, lastTruncatablePoint) + ending;
}
return truncDesc;
}
/**
* Gets the string that says how long since this build has started.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public @NonNull String getTimestampString() {
long duration = new GregorianCalendar().getTimeInMillis() - timestamp;
return Util.getTimeSpanString(duration);
}
/**
* Returns the timestamp formatted in xs:dateTime.
*/
public @NonNull String getTimestampString2() {
return Util.XS_DATETIME_FORMATTER.format(new Date(timestamp));
}
/**
* Gets the string that says how long the build took to run.
*/
public @NonNull String getDurationString() {
if (hasntStartedYet()) {
return Messages.Run_NotStartedYet();
} else if (isBuilding()) {
return Messages.Run_InProgressDuration(
Util.getTimeSpanString(System.currentTimeMillis() - startTime));
}
return Util.getTimeSpanString(duration);
}
/**
* Gets the millisecond it took to build.
*/
@Exported
public long getDuration() {
return duration;
}
/**
* Gets the icon color for display.
*/
public @NonNull BallColor getIconColor() {
if (!isBuilding()) {
// already built
return getResult().color;
}
// a new build is in progress
BallColor baseColor;
RunT pb = getPreviousBuild();
if (pb == null)
baseColor = BallColor.NOTBUILT;
else
baseColor = pb.getIconColor();
return baseColor.anime();
}
/**
* Returns true if the build is still queued and hasn't started yet.
*/
public boolean hasntStartedYet() {
return state == State.NOT_STARTED;
}
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "see JENKINS-45892")
@Override
public String toString() {
if (project == null) {
return "<broken data JENKINS-45892>";
}
return project.getFullName() + " #" + number;
}
@Exported
public String getFullDisplayName() {
return project.getFullDisplayName() + ' ' + getDisplayName();
}
@Override
@Exported
public String getDisplayName() {
return displayName != null ? displayName : "#" + number;
}
public boolean hasCustomDisplayName() {
return displayName != null;
}
/**
* @param value
* Set to null to revert back to the default "#NNN".
*/
public void setDisplayName(String value) throws IOException {
checkPermission(UPDATE);
this.displayName = value;
save();
}
@Exported(visibility = 2)
public int getNumber() {
return number;
}
/**
* Called by {@link RunMap} to obtain a reference to this run.
* @return Reference to the build. Never null
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#createReference
* @since 1.556
*/
protected @NonNull BuildReference<RunT> createReference() {
return new BuildReference<>(getId(), _this());
}
/**
* Called by {@link RunMap} to drop bi-directional links in preparation for
* deleting a build.
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#dropLinks
* @since 1.556
*/
protected void dropLinks() {
if (nextBuild != null)
nextBuild.previousBuild = previousBuild;
if (previousBuild != null)
previousBuild.nextBuild = nextBuild;
}
/**
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#getPreviousBuild
*/
public @CheckForNull RunT getPreviousBuild() {
return previousBuild;
}
/**
* Gets the most recent {@linkplain #isBuilding() completed} build excluding 'this' Run itself.
*/
public final @CheckForNull RunT getPreviousCompletedBuild() {
RunT r = getPreviousBuild();
while (r != null && r.isBuilding())
r = r.getPreviousBuild();
return r;
}
/**
* Obtains the next younger build in progress. It uses a skip-pointer so that we can compute this without
* O(n) computation time. This method also fixes up the skip list as we go, in a way that's concurrency safe.
*
* <p>
* We basically follow the existing skip list, and wherever we find a non-optimal pointer, we remember them
* in 'fixUp' and update them later.
*/
public final @CheckForNull RunT getPreviousBuildInProgress() {
if (previousBuildInProgress == this) return null; // the most common case
List<RunT> fixUp = new ArrayList<>();
RunT r = _this(); // 'r' is the source of the pointer (so that we can add it to fix up if we find that the target of the pointer is inefficient.)
RunT answer;
while (true) {
RunT n = r.previousBuildInProgress;
if (n == null) { // no field computed yet.
n = r.getPreviousBuild();
fixUp.add(r);
}
if (r == n || n == null) {
// this indicates that we know there's no build in progress beyond this point
answer = null;
break;
}
if (n.isBuilding()) {
// we now know 'n' is the target we wanted
answer = n;
break;
}
fixUp.add(r); // r contains the stale 'previousBuildInProgress' back pointer
r = n;
}
// fix up so that the next look up will run faster
for (RunT f : fixUp)
f.previousBuildInProgress = answer == null ? f : answer;
return answer;
}
/**
* Returns the last build that was actually built - i.e., skipping any with Result.NOT_BUILT
*/
public @CheckForNull RunT getPreviousBuiltBuild() {
RunT r = getPreviousBuild();
// in certain situations (aborted m2 builds) r.getResult() can still be null, although it should theoretically never happen
while (r != null && (r.getResult() == null || r.getResult() == Result.NOT_BUILT))
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last build that didn't fail before this build.
*/
public @CheckForNull RunT getPreviousNotFailedBuild() {
RunT r = getPreviousBuild();
while (r != null && r.getResult() == Result.FAILURE)
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last failed build before this build.
*/
public @CheckForNull RunT getPreviousFailedBuild() {
RunT r = getPreviousBuild();
while (r != null && r.getResult() != Result.FAILURE)
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last successful build before this build.
* @since 1.383
*/
public @CheckForNull RunT getPreviousSuccessfulBuild() {
RunT r = getPreviousBuild();
while (r != null && r.getResult() != Result.SUCCESS)
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last {@code numberOfBuilds} builds with a build result ≥ {@code threshold}.
*
* @param numberOfBuilds the desired number of builds
* @param threshold the build result threshold
* @return a list with the builds (youngest build first).
* May be smaller than 'numberOfBuilds' or even empty
* if not enough builds satisfying the threshold have been found. Never null.
* @since 1.383
*/
public @NonNull List<RunT> getPreviousBuildsOverThreshold(int numberOfBuilds, @NonNull Result threshold) {
RunT r = getPreviousBuild();
if (r != null) {
return r.getBuildsOverThreshold(numberOfBuilds, threshold);
}
return new ArrayList<>(numberOfBuilds);
}