-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
UiEventHandler.java
1079 lines (998 loc) · 37.2 KB
/
UiEventHandler.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
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.runtime;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.flogger.GoogleLogger;
import com.google.common.primitives.Bytes;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.devtools.build.lib.actions.ActionCompletionEvent;
import com.google.devtools.build.lib.actions.ActionProgressEvent;
import com.google.devtools.build.lib.actions.ActionScanningCompletedEvent;
import com.google.devtools.build.lib.actions.ActionStartedEvent;
import com.google.devtools.build.lib.actions.ActionUploadFinishedEvent;
import com.google.devtools.build.lib.actions.ActionUploadStartedEvent;
import com.google.devtools.build.lib.actions.CachingActionEvent;
import com.google.devtools.build.lib.actions.RunningActionEvent;
import com.google.devtools.build.lib.actions.ScanningActionEvent;
import com.google.devtools.build.lib.actions.SchedulingActionEvent;
import com.google.devtools.build.lib.actions.StoppedScanningActionEvent;
import com.google.devtools.build.lib.analysis.AnalysisPhaseCompleteEvent;
import com.google.devtools.build.lib.analysis.NoBuildEvent;
import com.google.devtools.build.lib.analysis.NoBuildRequestFinishedEvent;
import com.google.devtools.build.lib.bugreport.BugReport;
import com.google.devtools.build.lib.bugreport.Crash;
import com.google.devtools.build.lib.bugreport.CrashContext;
import com.google.devtools.build.lib.buildeventstream.AnnounceBuildEventTransportsEvent;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransport;
import com.google.devtools.build.lib.buildeventstream.BuildEventTransportClosedEvent;
import com.google.devtools.build.lib.buildtool.buildevent.BuildCompleteEvent;
import com.google.devtools.build.lib.buildtool.buildevent.BuildStartingEvent;
import com.google.devtools.build.lib.buildtool.buildevent.ExecutionProgressReceiverAvailableEvent;
import com.google.devtools.build.lib.buildtool.buildevent.MainRepoMappingComputationStartingEvent;
import com.google.devtools.build.lib.buildtool.buildevent.TestFilteringCompleteEvent;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.Event.ProcessOutput;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.ExtendedEventHandler.FetchProgress;
import com.google.devtools.build.lib.pkgcache.LoadingPhaseCompleteEvent;
import com.google.devtools.build.lib.pkgcache.PathPackageLocator;
import com.google.devtools.build.lib.runtime.CrashDebuggingProtos.InflightActionInfo;
import com.google.devtools.build.lib.skyframe.ConfigurationPhaseStartedEvent;
import com.google.devtools.build.lib.skyframe.LoadingPhaseStartedEvent;
import com.google.devtools.build.lib.skyframe.TopLevelStatusEvents.SomeExecutionStartedEvent;
import com.google.devtools.build.lib.skyframe.TopLevelStatusEvents.TestAnalyzedEvent;
import com.google.devtools.build.lib.util.io.AnsiTerminal;
import com.google.devtools.build.lib.util.io.AnsiTerminal.Color;
import com.google.devtools.build.lib.util.io.AnsiTerminalWriter;
import com.google.devtools.build.lib.util.io.LineCountingAnsiTerminalWriter;
import com.google.devtools.build.lib.util.io.LineWrappingAnsiTerminalWriter;
import com.google.devtools.build.lib.util.io.LoggingTerminalWriter;
import com.google.devtools.build.lib.util.io.OutErr;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.view.test.TestStatus.BlazeTestStatus;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import net.starlark.java.syntax.Location;
/** Presents events to the user in the terminal. */
public final class UiEventHandler implements EventHandler {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
/** Minimal time between scheduled updates */
private static final long MINIMAL_UPDATE_INTERVAL_MILLIS = 200L;
/** Minimal rate limiting (in ms), if the progress bar cannot be updated in place */
private static final long NO_CURSES_MINIMAL_PROGRESS_RATE_LIMIT = 1000L;
/** Periodic update interval of a time-dependent progress bar if it can be updated in place */
private static final long SHORT_REFRESH_MILLIS = 1000L;
private static final DateTimeFormatter TIMESTAMP_FORMAT =
DateTimeFormatter.ofPattern("(HH:mm:ss) ");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final boolean quiet;
private final boolean cursorControl;
private final Clock clock;
private final EventBus eventBus;
private final AnsiTerminal terminal;
private final boolean debugAllEvents;
private final UiStateTracker stateTracker;
private final LocationPrinter locationPrinter;
private final boolean showProgress;
private final boolean progressInTermTitle;
private final boolean showTimestamp;
private final OutErr outErr;
private final ImmutableSet<EventKind> filteredEventKinds;
private long progressRateLimitMillis;
private long minimalUpdateInterval;
private long lastRefreshMillis;
private long mustRefreshAfterMillis;
private boolean dateShown;
private int numLinesProgressBar;
private boolean buildRunning;
// Number of open build even protocol transports.
private boolean progressBarNeedsRefresh;
private volatile boolean shutdown;
private final AtomicReference<Thread> updateThread;
private final Lock updateLock;
private ByteArrayOutputStream stdoutLineBuffer;
private ByteArrayOutputStream stderrLineBuffer;
private final int maxStdoutErrBytes;
private final int terminalWidth;
/**
* An output stream that wraps another output stream and that fully buffers writes until flushed.
*/
private static final class FullyBufferedOutputStream extends ByteArrayOutputStream {
/** The (possibly unbuffered) stream wrapped by this one. */
private final OutputStream wrapped;
/**
* Constructs a new fully-buffered output stream that wraps an unbuffered one.
*
* @param wrapped the (possibly unbuffered) stream wrapped by this one
*/
FullyBufferedOutputStream(OutputStream wrapped) {
this.wrapped = wrapped;
}
@Override
public void flush() throws IOException {
super.flush();
try {
writeTo(wrapped);
wrapped.flush();
} finally {
// If we failed to write our current buffered contents to the output, there is not much
// we can do because reporting an error would require another write, and that write would
// probably fail. So, instead, we silently discard whatever was previously buffered in the
// hopes that the data itself was what caused the problem.
reset();
}
}
}
public UiEventHandler(
OutErr outErr,
UiOptions options,
boolean quiet,
Clock clock,
EventBus eventBus,
@Nullable PathFragment workspacePathFragment,
boolean skymeldMode,
boolean newStatsSummary) {
this.terminalWidth = (options.terminalColumns > 0 ? options.terminalColumns : 80);
this.maxStdoutErrBytes = options.maxStdoutErrBytes;
this.outErr =
OutErr.create(
new FullyBufferedOutputStream(outErr.getOutputStream()),
new FullyBufferedOutputStream(outErr.getErrorStream()));
this.quiet = quiet;
this.cursorControl = options.useCursorControl();
this.terminal = new AnsiTerminal(this.outErr.getErrorStream());
this.showProgress = options.showProgress;
this.progressInTermTitle = options.progressInTermTitle && options.useCursorControl();
this.showTimestamp = options.showTimestamp;
this.clock = clock;
this.eventBus = checkNotNull(eventBus);
this.debugAllEvents = options.experimentalUiDebugAllEvents;
this.locationPrinter =
new LocationPrinter(options.attemptToPrintRelativePaths, workspacePathFragment);
// If we have cursor control, we try to fit in the terminal width to avoid having
// to wrap the progress bar. We will wrap the progress bar to terminalWidth - 2
// characters to avoid depending on knowing whether the underlying terminal does the
// line feed already when reaching the last character of the line, or only once an
// additional character is written. Another column is lost for the continuation character
// in the wrapping process.
if (skymeldMode) {
this.stateTracker =
this.cursorControl
? new SkymeldUiStateTracker(clock, /*targetWidth=*/ this.terminalWidth - 2)
: new SkymeldUiStateTracker(clock);
} else {
this.stateTracker =
this.cursorControl
? new UiStateTracker(clock, /*targetWidth=*/ this.terminalWidth - 2)
: new UiStateTracker(clock);
}
this.stateTracker.setProgressSampleSize(options.uiActionsShown);
this.stateTracker.setNewStatsSummary(newStatsSummary);
this.numLinesProgressBar = 0;
if (this.cursorControl) {
this.progressRateLimitMillis = Math.round(options.showProgressRateLimit * 1000);
} else {
this.progressRateLimitMillis =
Math.max(
Math.round(options.showProgressRateLimit * 1000),
NO_CURSES_MINIMAL_PROGRESS_RATE_LIMIT);
}
this.minimalUpdateInterval =
Math.max(this.progressRateLimitMillis, MINIMAL_UPDATE_INTERVAL_MILLIS);
this.stdoutLineBuffer = new ByteArrayOutputStream();
this.stderrLineBuffer = new ByteArrayOutputStream();
this.dateShown = false;
this.updateThread = new AtomicReference<>();
this.updateLock = new ReentrantLock();
this.filteredEventKinds = options.getFilteredEventKinds();
// The progress bar has not been updated yet.
ignoreRefreshLimitOnce();
}
/**
* Flush buffers for stdout and stderr. Return if either of them flushed a non-zero number of
* symbols.
*/
private synchronized boolean flushStdOutStdErrBuffers() {
boolean didFlush = false;
try {
if (stdoutLineBuffer.size() > 0) {
stdoutLineBuffer.writeTo(outErr.getOutputStream());
outErr.getOutputStream().flush();
// Re-initialize the stream not to retain allocated memory.
stdoutLineBuffer = new ByteArrayOutputStream();
didFlush = true;
}
if (stderrLineBuffer.size() > 0) {
stderrLineBuffer.writeTo(outErr.getErrorStream());
outErr.getErrorStream().flush();
// Re-initialize the stream not to retain allocated memory.
stderrLineBuffer = new ByteArrayOutputStream();
didFlush = true;
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to output stream");
}
return didFlush;
}
private synchronized void maybeAddDate() {
if (!showTimestamp || dateShown || !buildRunning) {
return;
}
dateShown = true;
handle(
Event.info(
"Current date is "
+ DATE_FORMAT.format(
Instant.ofEpochMilli(clock.currentTimeMillis())
.atZone(ZoneId.systemDefault()))));
}
/**
* Helper function for {@link #handleInternal} to process events in debug mode, which causes all
* events to be dumped to the terminal.
*
* @param event the event to process
* @param stdout the event's stdout, already read from disk to avoid blocking within the critical
* section. Null if there is no stdout for this event or if it is empty.
* @param stderr the event's stderr, already read from disk to avoid blocking within the critical
* section. Null if there is no stderr for this event or if it is empty.
*/
private void handleLockedDebug(Event event, @Nullable byte[] stdout, @Nullable byte[] stderr)
throws IOException {
synchronized (this) {
// Debugging only: show all events visible to the new UI.
clearProgressBar();
terminal.flush();
OutputStream stream = outErr.getOutputStream();
stream.write((event + "\n").getBytes(StandardCharsets.ISO_8859_1));
if (stdout != null) {
stream.write("... with STDOUT: ".getBytes(StandardCharsets.ISO_8859_1));
stream.write(stdout);
stream.write("\n".getBytes(StandardCharsets.ISO_8859_1));
}
if (stderr != null) {
stream.write("... with STDERR: ".getBytes(StandardCharsets.ISO_8859_1));
stream.write(stderr);
stream.write("\n".getBytes(StandardCharsets.ISO_8859_1));
}
stream.flush();
addProgressBar();
terminal.flush();
}
}
/**
* Helper function for {@link #handleInternal} to process events in non-debug mode, which filters
* out and pretty-prints some events.
*
* @param event the event to process
* @param stdout the event's stdout, already read from disk to avoid blocking within the critical
* section. Null if there is no stdout for this event or if it is empty.
* @param stderr the event's stderr, already read from disk to avoid blocking within the critical
* section. Null if there is no stderr for this event or if it is empty.
*/
private void handleLocked(Event event, @Nullable byte[] stdout, @Nullable byte[] stderr)
throws IOException {
synchronized (this) {
maybeAddDate();
switch (event.getKind()) {
case STDOUT:
case STDERR:
OutputStream stream =
event.getKind() == EventKind.STDOUT
? outErr.getOutputStream()
: outErr.getErrorStream();
if (!buildRunning) {
stream.write(event.getMessageBytes());
stream.flush();
} else {
boolean clearedProgress =
writeToStream(stream, event.getKind(), event.getMessageBytes());
if (clearedProgress && showProgress && cursorControl) {
addProgressBar();
}
terminal.flush();
}
break;
case FATAL:
case ERROR:
case FAIL:
case WARNING:
case CANCELLED:
case INFO:
case DEBUG:
case SUBCOMMAND:
boolean incompleteLine;
if (showProgress && buildRunning) {
clearProgressBar();
}
incompleteLine = flushStdOutStdErrBuffers();
if (incompleteLine) {
crlf();
}
if (showTimestamp) {
terminal.writeString(
TIMESTAMP_FORMAT.format(
Instant.ofEpochMilli(clock.currentTimeMillis())
.atZone(ZoneId.systemDefault())));
}
setEventKindColor(event.getKind());
terminal.writeString(event.getKind() + ": ");
terminal.resetTerminal();
incompleteLine = true;
Location location = event.getLocation();
if (location != null) {
terminal.writeString(locationPrinter.getLocationString(location) + ": ");
}
if (event.getMessage() != null) {
terminal.writeString(event.getMessage());
incompleteLine = !event.getMessage().endsWith("\n");
}
if (incompleteLine) {
crlf();
}
if (stderr != null) {
writeToStream(outErr.getErrorStream(), EventKind.STDERR, stderr);
outErr.getErrorStream().flush();
}
if (stdout != null) {
writeToStream(outErr.getOutputStream(), EventKind.STDOUT, stdout);
outErr.getOutputStream().flush();
}
if (showProgress && buildRunning && cursorControl) {
addProgressBar();
}
terminal.flush();
break;
case PROGRESS:
if (stateTracker.progressBarTimeDependent()) {
refresh();
}
// Fall through.
case START:
case FINISH:
case PASS:
case TIMEOUT:
case DEPCHECKER:
if (stdout != null || stderr != null) {
BugReport.sendBugReport(
new IllegalStateException(
"stdout/stderr should not be present for this event " + event));
}
break;
}
}
}
@Nullable
private byte[] getContentIfSmallEnough(
String name, long size, Supplier<byte[]> getContent, Supplier<String> getPath) {
if (size == 0) {
// Avoid any possible I/O when we know it'll be empty anyway.
return null;
}
if (size <= maxStdoutErrBytes) {
return getContent.get();
} else {
return String.format(
"%s (%s) %d exceeds maximum size of --experimental_ui_max_stdouterr_bytes=%d bytes;"
+ " skipping\n",
name, getPath.get(), size, maxStdoutErrBytes)
.getBytes(StandardCharsets.ISO_8859_1);
}
}
private void handleInternal(Event event) {
EventKind eventKind = event.getKind();
if (quiet) {
switch (eventKind) {
case ERROR -> {}
case FATAL -> {}
case STDOUT -> {}
case STDERR -> {}
default -> {
return;
}
}
}
if (filteredEventKinds.contains(eventKind)) {
return;
}
try {
// stdout and stderr may be files. Buffer them in memory to avoid doing I/O in the critical
// sections of handleLocked*, at the expense of having to cap their size to avoid using too
// much memory.
byte[] stdout = null;
byte[] stderr = null;
ProcessOutput processOutput = event.getProcessOutput();
if (processOutput != null) {
stdout =
getContentIfSmallEnough(
"stdout",
processOutput.getStdOutSize(),
processOutput::getStdOut,
processOutput::getStdOutPath);
stderr =
getContentIfSmallEnough(
"stderr",
processOutput.getStdErrSize(),
processOutput::getStdErr,
processOutput::getStdErrPath);
}
if (debugAllEvents) {
handleLockedDebug(event, stdout, stderr);
} else {
handleLocked(event, stdout, stderr);
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to output stream");
}
}
@Override
public void handle(Event event) {
if (!debugAllEvents
&& !showTimestamp
&& (event.getKind() == EventKind.START
|| event.getKind() == EventKind.FINISH
|| event.getKind() == EventKind.PASS
|| event.getKind() == EventKind.TIMEOUT
|| event.getKind() == EventKind.DEPCHECKER)) {
// Keep this in sync with the list of no-op event kinds in handleLocked above.
return;
}
// Ensure that default progress messages are not displayed after a FATAL event.
if (event.getKind() == EventKind.FATAL) {
synchronized (this) {
buildRunning = false;
}
stopUpdateThread();
}
handleInternal(event);
}
private boolean writeToStream(OutputStream stream, EventKind eventKind, byte[] message)
throws IOException {
int eolIndex = Bytes.lastIndexOf(message, (byte) '\n');
ByteArrayOutputStream outLineBuffer =
eventKind == EventKind.STDOUT ? stdoutLineBuffer : stderrLineBuffer;
if (eolIndex < 0) {
outLineBuffer.write(message);
return false;
}
clearProgressBar();
terminal.flush();
// Write the buffer so far + the rest of the line (including newline).
outLineBuffer.writeTo(stream);
outLineBuffer.reset();
stream.write(message, 0, eolIndex + 1);
stream.flush();
outLineBuffer.write(message, eolIndex + 1, message.length - eolIndex - 1);
return true;
}
private void setEventKindColor(EventKind kind) throws IOException {
switch (kind) {
case FATAL:
case ERROR:
case FAIL:
terminal.setTextColor(Color.RED);
terminal.textBold();
break;
case WARNING:
case CANCELLED:
terminal.setTextColor(Color.MAGENTA);
break;
case INFO:
terminal.setTextColor(Color.GREEN);
break;
case DEBUG:
terminal.setTextColor(Color.YELLOW);
break;
case SUBCOMMAND:
terminal.setTextColor(Color.BLUE);
break;
default:
terminal.resetTerminal();
}
}
@Subscribe
public void mainRepoMappingComputationStarted(MainRepoMappingComputationStartingEvent event) {
synchronized (this) {
buildRunning = true;
}
maybeAddDate();
stateTracker.mainRepoMappingComputationStarted();
// As a new phase started, inform immediately.
ignoreRefreshLimitOnce();
refresh();
startUpdateThread();
}
@Subscribe
public void buildStarted(BuildStartingEvent event) {
maybeAddDate();
stateTracker.buildStarted();
// As a new phase started, inform immediately.
ignoreRefreshLimitOnce();
refresh();
}
@Subscribe
public void loadingStarted(LoadingPhaseStartedEvent event) {
maybeAddDate();
stateTracker.loadingStarted(event);
// As a new phase started, inform immediately.
ignoreRefreshLimitOnce();
refresh();
startUpdateThread();
}
@Subscribe
public void configurationStarted(ConfigurationPhaseStartedEvent event) {
maybeAddDate();
stateTracker.configurationStarted(event);
// As a new phase started, inform immediately.
ignoreRefreshLimitOnce();
refresh();
startUpdateThread();
}
@Subscribe
public void loadingComplete(LoadingPhaseCompleteEvent event) {
stateTracker.loadingComplete(event);
refresh();
}
@Subscribe
public synchronized void analysisComplete(AnalysisPhaseCompleteEvent event) {
String analysisSummary = stateTracker.analysisComplete();
handle(Event.info(null, analysisSummary));
}
@Subscribe
public void executionPhaseStarted(SomeExecutionStartedEvent event) {
if (event.countedInExecutionTime()) {
stateTracker.executionPhaseStarted();
refresh();
}
}
@Subscribe
public void progressReceiverAvailable(ExecutionProgressReceiverAvailableEvent event) {
stateTracker.progressReceiverAvailable(event);
// As this is the first time we have a progress message, update immediately.
ignoreRefreshLimitOnce();
startUpdateThread();
}
@Subscribe
public void buildComplete(BuildCompleteEvent event) {
// The final progress bar will flow into the scroll-back buffer, to if treat
// it as an event and add a timestamp, if events are supposed to have a timestamp.
boolean done = false;
synchronized (this) {
handleInternal(stateTracker.buildComplete(event));
ignoreRefreshLimitOnce();
// After a build has completed, only stop updating the UI if there is no more activities.
if (!stateTracker.hasActivities()) {
buildRunning = false;
done = true;
}
// Only refresh after we have determined whether we need to keep the progress bar up.
refresh();
}
if (done) {
stopUpdateThread();
flushStdOutStdErrBuffers();
}
}
private void completeBuild() {
synchronized (this) {
if (!buildRunning) {
return;
}
buildRunning = false;
// Have to set this, otherwise there's a lingering "checking cached actions" message for the
// `mod` command, which doesn't even run any actions.
stateTracker.setBuildComplete();
}
stopUpdateThread();
synchronized (this) {
try {
// If a progress bar is currently present, clean it and redraw it.
boolean progressBarPresent = numLinesProgressBar > 0;
if (progressBarPresent) {
clearProgressBar();
}
terminal.flush();
boolean incompleteLine = flushStdOutStdErrBuffers();
if (incompleteLine) {
crlf();
}
if (progressBarPresent) {
addProgressBar();
}
terminal.flush();
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to output stream");
}
}
}
@Subscribe
public void packageLocatorCreated(PathPackageLocator packageLocator) {
locationPrinter.packageLocatorCreated(packageLocator);
}
@Subscribe
public void noBuild(NoBuildEvent event) {
if (event.showProgress()) {
synchronized (this) {
buildRunning = true;
}
return;
}
completeBuild();
}
@Subscribe
public void noBuildFinished(NoBuildRequestFinishedEvent event) {
completeBuild();
}
@Subscribe
public void afterCommand(AfterCommandEvent event) {
synchronized (this) {
buildRunning = false;
}
completeBuild();
try {
flushStdOutStdErrBuffers();
terminal.resetTerminal();
terminal.flush();
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to user terminal");
}
}
@Subscribe
public void downloadProgress(FetchProgress event) {
maybeAddDate();
stateTracker.downloadProgress(event);
if (!event.isFinished()) {
refresh();
} else {
checkActivities();
}
}
@Subscribe
@AllowConcurrentEvents
public void actionStarted(ActionStartedEvent event) {
stateTracker.actionStarted(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void scanningAction(ScanningActionEvent event) {
stateTracker.scanningAction(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void stopScanningAction(StoppedScanningActionEvent event) {
stateTracker.stopScanningAction(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void checkingActionCache(CachingActionEvent event) {
stateTracker.cachingAction(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void schedulingAction(SchedulingActionEvent event) {
stateTracker.schedulingAction(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void runningAction(RunningActionEvent event) {
stateTracker.runningAction(event);
refresh();
}
@Subscribe
@AllowConcurrentEvents
public void actionProgress(ActionProgressEvent event) {
stateTracker.actionProgress(event);
refreshSoon();
}
@Subscribe
@AllowConcurrentEvents
public void actionCompletion(ActionScanningCompletedEvent event) {
stateTracker.actionCompletion(event);
refreshSoon();
}
@Subscribe
@AllowConcurrentEvents
public void actionCompletion(ActionCompletionEvent event) {
stateTracker.actionCompletion(event);
refreshSoon();
}
@Subscribe
public void crash(CrashEvent event) {
InflightActionInfo inflightActions = stateTracker.logAndGetInflightActions();
eventBus.post(inflightActions);
}
private void checkActivities() {
if (stateTracker.hasActivities()) {
refreshSoon();
} else {
stopUpdateThread();
flushStdOutStdErrBuffers();
ignoreRefreshLimitOnce();
refresh();
}
}
@Subscribe
@AllowConcurrentEvents
public void actionUploadStarted(ActionUploadStartedEvent event) {
stateTracker.actionUploadStarted(event);
refreshSoon();
}
@Subscribe
public void actionUploadFinished(ActionUploadFinishedEvent event) {
stateTracker.actionUploadFinished(event);
checkActivities();
}
@Subscribe
public void testFilteringComplete(TestFilteringCompleteEvent event) {
stateTracker.testFilteringComplete(event);
refresh();
}
@Subscribe
public void singleTestAnalyzed(TestAnalyzedEvent event) {
stateTracker.singleTestAnalyzed(event);
refreshSoon();
}
/**
* Return true, if the test summary provides information that is both worth being shown in the
* scroll-back buffer and new with respect to the alreay shown failure messages.
*/
private static boolean testSummaryProvidesNewInformation(TestSummary summary) {
ImmutableSet<BlazeTestStatus> statusToIgnore =
ImmutableSet.of(
BlazeTestStatus.PASSED,
BlazeTestStatus.FAILED_TO_BUILD,
BlazeTestStatus.BLAZE_HALTED_BEFORE_TESTING,
BlazeTestStatus.NO_STATUS);
if (statusToIgnore.contains(summary.getStatus())) {
return false;
}
return summary.getStatus() != BlazeTestStatus.FAILED || summary.getFailedLogs().size() != 1;
}
@Subscribe
public synchronized void testSummary(TestSummary summary) {
stateTracker.testSummary(summary);
if (testSummaryProvidesNewInformation(summary)) {
// For failed test, write the failure to the scroll-back buffer immediately
try {
clearProgressBar();
crlf();
setEventKindColor(
summary.getStatus() == BlazeTestStatus.FLAKY ? EventKind.WARNING : EventKind.ERROR);
terminal.writeString(summary.getStatus() + ": ");
terminal.resetTerminal();
terminal.writeString(summary.getLabel().toString());
terminal.writeString(" (Summary)");
crlf();
for (Path logPath : summary.getFailedLogs()) {
terminal.writeString(" " + logPath.getPathString());
crlf();
}
if (showProgress && cursorControl) {
addProgressBar();
}
terminal.flush();
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to output stream");
}
} else {
refresh();
}
}
@Subscribe
public synchronized void buildEventTransportsAnnounced(AnnounceBuildEventTransportsEvent event) {
stateTracker.buildEventTransportsAnnounced(event);
if (debugAllEvents) {
String message = "Transports announced:";
for (BuildEventTransport transport : event.transports()) {
message += " " + transport.name();
}
this.handle(Event.info(null, message));
}
}
@Subscribe
public void buildEventTransportClosed(BuildEventTransportClosedEvent event) {
stateTracker.buildEventTransportClosed(event);
if (debugAllEvents) {
this.handle(Event.info(null, "Transport " + event.transport().name() + " closed"));
}
checkActivities();
}
private void refresh() {
if (showProgress) {
progressBarNeedsRefresh = true;
doRefresh();
}
}
private void doRefresh(boolean fromUpdateThread) {
if (!buildRunning) {
return;
}
long nowMillis = clock.currentTimeMillis();
if (lastRefreshMillis + progressRateLimitMillis < nowMillis) {
if (updateLock.tryLock()) {
try {
synchronized (this) {
if (showProgress && (progressBarNeedsRefresh || timeBasedRefresh())) {
progressBarNeedsRefresh = false;
clearProgressBar();
addProgressBar();
terminal.flush();
}
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("IO Error writing to output stream");
} finally {
updateLock.unlock();
}
}
} else {
// We skipped an update due to rate limiting. If this however, turned
// out to be the last update for a long while, we need to show it in a
// timely manner, as it best describes the current state.
if (!fromUpdateThread) {
startUpdateThread();
}
}
}
private void doRefresh() {
doRefresh(false);
}
private void refreshSoon() {
// Schedule an update of the progress bar in the near future, unless there is already
// a future update scheduled.
long nowMillis = clock.currentTimeMillis();
if (mustRefreshAfterMillis <= lastRefreshMillis) {
mustRefreshAfterMillis = Math.max(nowMillis + 1, lastRefreshMillis + minimalUpdateInterval);
}
startUpdateThread();
}
/** Decide whether the progress bar should be redrawn only for the reason that time has passed. */
private synchronized boolean timeBasedRefresh() {
if (!stateTracker.progressBarTimeDependent()) {
return false;
}
// Don't do more updates than are requested through events when there is no cursor control.
if (!cursorControl) {
return false;
}
long nowMillis = clock.currentTimeMillis();
if (lastRefreshMillis < mustRefreshAfterMillis
&& mustRefreshAfterMillis < nowMillis + progressRateLimitMillis) {
// Within a small interval from now, an update is scheduled anyway,
// so don't do a time-based update of the progress bar now, to avoid
// updates too close to each other.
return false;
}
return lastRefreshMillis + SHORT_REFRESH_MILLIS < nowMillis;
}
private void ignoreRefreshLimitOnce() {
// Set refresh time variables in a state such that the next progress bar
// update will definitely be written out.
lastRefreshMillis = clock.currentTimeMillis() - progressRateLimitMillis - 1;
}
private void startUpdateThread() {
// Refuse to start an update thread once the build is complete; such a situation might
// arise if the completion of the build is reported (shortly) before the completion of
// the last action is reported.
if (buildRunning && updateThread.get() == null) {
Thread threadToStart =
new Thread(
() -> {
try {
while (!shutdown) {
Thread.sleep(minimalUpdateInterval);
if (lastRefreshMillis < mustRefreshAfterMillis
&& mustRefreshAfterMillis < clock.currentTimeMillis()) {
progressBarNeedsRefresh = true;
}
doRefresh(/* fromUpdateThread= */ true);
}
} catch (InterruptedException e) {
// Ignore
} catch (Throwable t) {