/
BlazeRuntime.java
1717 lines (1558 loc) · 69.1 KB
/
BlazeRuntime.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 2014 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.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.devtools.build.lib.util.DetailedExitCode.DetailedExitCodeComparator.chooseMoreImportantWithFirstIfTie;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionHandler;
import com.google.common.flogger.GoogleLogger;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.BlazeVersionInfo;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ServerDirectories;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.test.CoverageReportActionFactory;
import com.google.devtools.build.lib.bazel.repository.downloader.Downloader;
import com.google.devtools.build.lib.bugreport.BugReport;
import com.google.devtools.build.lib.bugreport.BugReporter;
import com.google.devtools.build.lib.bugreport.Crash;
import com.google.devtools.build.lib.bugreport.CrashContext;
import com.google.devtools.build.lib.buildeventstream.BuildEvent.LocalFile.LocalFileType;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader.UploadContext;
import com.google.devtools.build.lib.buildeventstream.BuildEventProtocolOptions;
import com.google.devtools.build.lib.buildtool.buildevent.ProfilerStartedEvent;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.events.OutputFilter;
import com.google.devtools.build.lib.exec.BinTools;
import com.google.devtools.build.lib.jni.JniLoader;
import com.google.devtools.build.lib.packages.Package.Builder.DefaultPackageSettings;
import com.google.devtools.build.lib.packages.Package.Builder.PackageSettings;
import com.google.devtools.build.lib.packages.PackageFactory;
import com.google.devtools.build.lib.packages.PackageLoadingListener;
import com.google.devtools.build.lib.packages.PackageOverheadEstimator;
import com.google.devtools.build.lib.packages.PackageValidator;
import com.google.devtools.build.lib.profiler.AutoProfiler;
import com.google.devtools.build.lib.profiler.MemoryProfiler;
import com.google.devtools.build.lib.profiler.ProfilePhase;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.Profiler.Format;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.profiler.SilentCloseable;
import com.google.devtools.build.lib.query2.QueryEnvironmentFactory;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.QueryFunction;
import com.google.devtools.build.lib.query2.query.output.OutputFormatter;
import com.google.devtools.build.lib.query2.query.output.OutputFormatters;
import com.google.devtools.build.lib.runtime.CommandDispatcher.LockingMode;
import com.google.devtools.build.lib.runtime.proto.InvocationPolicyOuterClass.InvocationPolicy;
import com.google.devtools.build.lib.server.CommandProtos.EnvironmentVariable;
import com.google.devtools.build.lib.server.CommandProtos.ExecRequest;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Filesystem;
import com.google.devtools.build.lib.server.GrpcServerImpl;
import com.google.devtools.build.lib.server.PidFileWatcher;
import com.google.devtools.build.lib.server.RPCServer;
import com.google.devtools.build.lib.server.ShutdownHooks;
import com.google.devtools.build.lib.server.signal.InterruptSignalHandler;
import com.google.devtools.build.lib.shell.JavaSubprocessFactory;
import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.shell.SubprocessFactory;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.CustomExitCodePublisher;
import com.google.devtools.build.lib.util.CustomFailureDetailPublisher;
import com.google.devtools.build.lib.util.DebugLoggerConfigurator;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.InterruptedFailureDetails;
import com.google.devtools.build.lib.util.LoggingUtil;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.util.ProcessUtils;
import com.google.devtools.build.lib.util.TestType;
import com.google.devtools.build.lib.util.ThreadUtils;
import com.google.devtools.build.lib.util.io.OutErr;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.windows.WindowsSubprocessFactory;
import com.google.devtools.build.lib.worker.WorkerMetricsCollector;
import com.google.devtools.common.options.CommandNameCache;
import com.google.devtools.common.options.InvocationPolicyParser;
import com.google.devtools.common.options.OptionDefinition;
import com.google.devtools.common.options.OptionPriority.PriorityCategory;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.OptionsParsingResult;
import com.google.devtools.common.options.OptionsProvider;
import com.google.devtools.common.options.TriState;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import net.starlark.java.eval.EvalException;
/**
* The BlazeRuntime class encapsulates the immutable configuration of the current instance. These
* runtime settings and services are available to most parts of any Blaze application for the
* duration of the batch run or server lifetime.
*
* <p>The parts specific to the current command are stored in {@link CommandEnvironment}.
*/
public final class BlazeRuntime implements BugReport.BlazeRuntimeInterface {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private final FileSystem fileSystem;
private final ImmutableList<BlazeModule> blazeModules;
private final Map<String, BlazeCommand> commandMap = new LinkedHashMap<>();
private final Clock clock;
private final Runnable abruptShutdownHandler;
private final PackageFactory packageFactory;
private final ConfiguredRuleClassProvider ruleClassProvider;
// For bazel info.
private final ImmutableMap<String, InfoItem> infoItems;
// For bazel query.
private final QueryEnvironmentFactory queryEnvironmentFactory;
private final ImmutableList<QueryFunction> queryFunctions;
private final ImmutableList<OutputFormatter> queryOutputFormatters;
private final AtomicReference<DetailedExitCode> storedExitCode = new AtomicReference<>();
// TODO(b/1030062): If multiple commands can ever run simultaneously, this should be a set of
// command environments, with environments removed in some after-command hook.
// Null if a command is not in progress.
@Nullable private volatile CommandEnvironment env = null;
// We pass this through here to make it available to the MasterLogWriter.
private final OptionsParsingResult startupOptionsProvider;
private final ProjectFile.Provider projectFileProvider;
private final QueryRuntimeHelper.Factory queryRuntimeHelperFactory;
private final InvocationPolicy moduleInvocationPolicy;
private final SubscriberExceptionHandler eventBusExceptionHandler;
private final BugReporter bugReporter;
private final String productName;
private final BuildEventArtifactUploaderFactoryMap buildEventArtifactUploaderFactoryMap;
private final ActionKeyContext actionKeyContext;
private final ImmutableMap<String, AuthHeadersProvider> authHeadersProviderMap;
@Nullable private final RepositoryRemoteExecutorFactory repositoryRemoteExecutorFactory;
private final Supplier<Downloader> downloaderSupplier;
// Workspace state (currently exactly one workspace per server)
private BlazeWorkspace workspace;
private BlazeRuntime(
FileSystem fileSystem,
QueryEnvironmentFactory queryEnvironmentFactory,
ImmutableList<QueryFunction> queryFunctions,
ImmutableList<OutputFormatter> queryOutputFormatters,
PackageFactory pkgFactory,
ConfiguredRuleClassProvider ruleClassProvider,
ImmutableMap<String, InfoItem> infoItems,
ActionKeyContext actionKeyContext,
Clock clock,
Runnable abruptShutdownHandler,
OptionsParsingResult startupOptionsProvider,
ImmutableList<BlazeModule> blazeModules,
SubscriberExceptionHandler eventBusExceptionHandler,
BugReporter bugReporter,
ProjectFile.Provider projectFileProvider,
QueryRuntimeHelper.Factory queryRuntimeHelperFactory,
InvocationPolicy moduleInvocationPolicy,
Iterable<BlazeCommand> commands,
String productName,
BuildEventArtifactUploaderFactoryMap buildEventArtifactUploaderFactoryMap,
ImmutableMap<String, AuthHeadersProvider> authHeadersProviderMap,
RepositoryRemoteExecutorFactory repositoryRemoteExecutorFactory,
Supplier<Downloader> downloaderSupplier) {
// Server state
this.fileSystem = fileSystem;
this.blazeModules = blazeModules;
overrideCommands(commands);
this.packageFactory = pkgFactory;
this.projectFileProvider = projectFileProvider;
this.queryRuntimeHelperFactory = queryRuntimeHelperFactory;
this.moduleInvocationPolicy = moduleInvocationPolicy;
this.ruleClassProvider = ruleClassProvider;
this.infoItems = infoItems;
this.actionKeyContext = actionKeyContext;
this.clock = clock;
this.abruptShutdownHandler = abruptShutdownHandler;
this.startupOptionsProvider = startupOptionsProvider;
this.queryEnvironmentFactory = queryEnvironmentFactory;
this.queryFunctions = queryFunctions;
this.queryOutputFormatters = queryOutputFormatters;
this.eventBusExceptionHandler = eventBusExceptionHandler;
this.bugReporter = bugReporter;
CommandNameCache.CommandNameCacheInstance.INSTANCE.setCommandNameCache(
new CommandNameCacheImpl(commandMap));
this.productName = productName;
this.buildEventArtifactUploaderFactoryMap = buildEventArtifactUploaderFactoryMap;
this.authHeadersProviderMap =
Preconditions.checkNotNull(authHeadersProviderMap, "authHeadersProviderMap");
this.repositoryRemoteExecutorFactory = repositoryRemoteExecutorFactory;
this.downloaderSupplier = downloaderSupplier;
}
public BlazeWorkspace initWorkspace(BlazeDirectories directories, BinTools binTools)
throws AbruptExitException {
Preconditions.checkState(this.workspace == null);
WorkspaceBuilder builder = new WorkspaceBuilder(directories, binTools);
for (BlazeModule module : blazeModules) {
module.workspaceInit(this, directories, builder);
}
this.workspace = builder.build(this, packageFactory, eventBusExceptionHandler);
return workspace;
}
@Nullable
public CoverageReportActionFactory getCoverageReportActionFactory(
OptionsProvider commandOptions) {
CoverageReportActionFactory firstFactory = null;
for (BlazeModule module : blazeModules) {
CoverageReportActionFactory factory = module.getCoverageReportFactory(commandOptions);
if (factory != null) {
Preconditions.checkState(
firstFactory == null, "only one Bazel Module can have a Coverage Report Factory");
firstFactory = factory;
}
}
return firstFactory;
}
/**
* Adds the given command under the given name to the map of commands.
*
* @throws AssertionError if the name is already used by another command.
*/
private void addCommand(BlazeCommand command) {
String name = command.getClass().getAnnotation(Command.class).name();
if (commandMap.containsKey(name)) {
throw new IllegalStateException("Command name or alias " + name + " is already used.");
}
commandMap.put(name, command);
}
@VisibleForTesting
public void overrideCommands(Iterable<BlazeCommand> commands) {
commandMap.clear();
for (BlazeCommand command : commands) {
addCommand(command);
}
}
public InvocationPolicy getModuleInvocationPolicy() {
return moduleInvocationPolicy;
}
private BuildEventArtifactUploader newUploader(
CommandEnvironment env, String buildEventUploadStrategy) throws IOException {
return buildEventArtifactUploaderFactoryMap.select(buildEventUploadStrategy).create(env);
}
/** Configure profiling based on the provided options. */
ProfilerStartedEvent initProfiler(
boolean tracerEnabled,
ExtendedEventHandler eventHandler,
BlazeWorkspace workspace,
CommonCommandOptions options,
BuildEventProtocolOptions bepOptions,
CommandEnvironment env,
long execStartTimeNanos,
long waitTimeInMs) {
OutputStream out = null;
boolean recordFullProfilerData = options.recordFullProfilerData;
ImmutableSet.Builder<ProfilerTask> profiledTasksBuilder = ImmutableSet.builder();
Profiler.Format format = Format.JSON_TRACE_FILE_FORMAT;
Path profilePath = null;
String profileName = null;
UploadContext streamingContext = null;
try {
if (tracerEnabled) {
if (options.profilePath == null) {
profileName = "command.profile.gz";
format = Format.JSON_TRACE_FILE_COMPRESSED_FORMAT;
if (bepOptions != null && bepOptions.streamingLogFileUploads) {
BuildEventArtifactUploader buildEventArtifactUploader =
newUploader(env, bepOptions.buildEventUploadStrategy);
streamingContext = buildEventArtifactUploader.startUpload(LocalFileType.LOG, null);
out = streamingContext.getOutputStream();
} else {
profilePath = workspace.getOutputBase().getRelative(profileName);
out = profilePath.getOutputStream();
}
} else {
format =
options.profilePath.toString().endsWith(".gz")
? Format.JSON_TRACE_FILE_COMPRESSED_FORMAT
: Format.JSON_TRACE_FILE_FORMAT;
profilePath = workspace.getWorkspace().getRelative(options.profilePath);
out = profilePath.getOutputStream(/* append= */ false, /* internal= */ true);
}
if (profilePath != null && options.announceProfilePath) {
eventHandler.handle(Event.info("Writing tracer profile to '" + profilePath + "'"));
}
for (ProfilerTask profilerTask : ProfilerTask.values()) {
if (!profilerTask.isVfs()
// CRITICAL_PATH corresponds to writing the file.
&& profilerTask != ProfilerTask.CRITICAL_PATH
&& profilerTask != ProfilerTask.SKYFUNCTION) {
profiledTasksBuilder.add(profilerTask);
}
}
profiledTasksBuilder.addAll(options.additionalProfileTasks);
if (options.recordFullProfilerData) {
profiledTasksBuilder.addAll(EnumSet.allOf(ProfilerTask.class));
}
} else if (options.alwaysProfileSlowOperations) {
recordFullProfilerData = false;
out = null;
for (ProfilerTask profilerTask : ProfilerTask.values()) {
if (profilerTask.collectsSlowestInstances()) {
profiledTasksBuilder.add(profilerTask);
}
}
}
ImmutableSet<ProfilerTask> profiledTasks = profiledTasksBuilder.build();
if (!profiledTasks.isEmpty()) {
if (options.slimProfile && options.includePrimaryOutput) {
eventHandler.handle(
Event.warn(
"Enabling both --slim_profile and"
+ " --experimental_profile_include_primary_output: the \"out\" field"
+ " will be omitted in merged actions."));
}
Profiler profiler = Profiler.instance();
profiler.start(
profiledTasks,
out,
format,
workspace.getOutputBase().toString(),
env.getCommandId(),
recordFullProfilerData,
clock,
execStartTimeNanos,
options.slimProfile,
options.includePrimaryOutput,
options.profileIncludeTargetLabel,
options.alwaysProfileSlowOperations,
options.collectWorkerDataInProfiler,
options.collectLoadAverageInProfiler,
WorkerMetricsCollector.instance(),
bugReporter);
// Instead of logEvent() we're calling the low level function to pass the timings we took in
// the launcher. We're setting the INIT phase marker so that it follows immediately the
// LAUNCH phase.
long startupTimeNanos = options.startupTime * 1000000L;
long waitTimeNanos = waitTimeInMs * 1000000L;
long clientStartTimeNanos = execStartTimeNanos - startupTimeNanos - waitTimeNanos;
profiler.logSimpleTaskDuration(
clientStartTimeNanos,
Duration.ofNanos(startupTimeNanos),
ProfilerTask.PHASE,
ProfilePhase.LAUNCH.description);
if (options.extractDataTime > 0) {
profiler.logSimpleTaskDuration(
clientStartTimeNanos,
Duration.ofMillis(options.extractDataTime),
ProfilerTask.PHASE,
"Extracting Bazel binary");
}
if (options.waitTime > 0) {
profiler.logSimpleTaskDuration(
clientStartTimeNanos,
Duration.ofMillis(options.waitTime),
ProfilerTask.PHASE,
"Blocking on busy Bazel server (in client)");
}
if (waitTimeInMs > 0) {
profiler.logSimpleTaskDuration(
clientStartTimeNanos + startupTimeNanos,
Duration.ofMillis(waitTimeInMs),
ProfilerTask.PHASE,
"Blocking on busy Bazel server (in server)");
}
profiler.logSimpleTaskDuration(
execStartTimeNanos, Duration.ZERO, ProfilerTask.PHASE, ProfilePhase.INIT.description);
}
} catch (IOException e) {
eventHandler.handle(Event.error("Error while creating profile file: " + e.getMessage()));
}
return new ProfilerStartedEvent(profileName, profilePath, streamingContext);
}
public FileSystem getFileSystem() {
return fileSystem;
}
public BlazeWorkspace getWorkspace() {
return workspace;
}
public ActionKeyContext getActionKeyContext() {
return actionKeyContext;
}
/** The directory in which blaze stores the server state - that is, the socket file and a log. */
private Path getServerDirectory() {
return workspace.getDirectories().getOutputBase().getChild("server");
}
/**
* Returns the {@link QueryEnvironmentFactory} that should be used to create a {@link
* com.google.devtools.build.lib.query2.common.AbstractBlazeQueryEnvironment}, whenever one is
* needed.
*/
public QueryEnvironmentFactory getQueryEnvironmentFactory() {
return queryEnvironmentFactory;
}
public ImmutableList<QueryFunction> getQueryFunctions() {
return queryFunctions;
}
public ImmutableList<OutputFormatter> getQueryOutputFormatters() {
return queryOutputFormatters;
}
/** Returns the package factory. */
public PackageFactory getPackageFactory() {
return packageFactory;
}
/** Returns the rule class provider. */
public ConfiguredRuleClassProvider getRuleClassProvider() {
return ruleClassProvider;
}
public ImmutableMap<String, InfoItem> getInfoItems() {
return infoItems;
}
public Iterable<BlazeModule> getBlazeModules() {
return blazeModules;
}
/**
* Returns the first module that is an instance of a given class or interface.
*
* @param moduleClass a class or interface that we want to match to a module
* @param <T> the type of the module's class
* @return a module that is an instance of this class or interface
*/
@SuppressWarnings("unchecked")
public <T> T getBlazeModule(Class<T> moduleClass) {
for (BlazeModule module : blazeModules) {
if (moduleClass.isInstance(module)) {
return (T) module;
}
}
return null;
}
/**
* Returns a provider for project file objects. Can be null if no such provider was set by any of
* the modules.
*/
@Nullable
public ProjectFile.Provider getProjectFileProvider() {
return projectFileProvider;
}
public QueryRuntimeHelper.Factory getQueryRuntimeHelperFactory() {
return queryRuntimeHelperFactory;
}
/**
* Hook method called by the BlazeCommandDispatcher prior to the dispatch of each command.
*
* @param options The CommonCommandOptions used by every command.
*/
void beforeCommand(CommandEnvironment env, CommonCommandOptions options) {
this.env = env;
if (options.memoryProfilePath != null) {
Path memoryProfilePath = env.getWorkingDirectory().getRelative(options.memoryProfilePath);
MemoryProfiler.instance()
.setStableMemoryParameters(options.memoryProfileStableHeapParameters);
try {
MemoryProfiler.instance().start(memoryProfilePath.getOutputStream());
} catch (IOException e) {
env.getReporter()
.handle(Event.error("Error while creating memory profile file: " + e.getMessage()));
}
}
}
@Override
public void cleanUpForCrash(DetailedExitCode exitCode) {
logger.atInfo().log("Cleaning up in crash: %s", exitCode);
if (declareExitCode(exitCode)) {
CommandEnvironment localEnv = env;
if (localEnv != null) {
localEnv.notifyOnCrash(
productName + " is crashing: " + exitCode.getFailureDetail().getMessage());
}
// Only try to publish events if we won the exit code race. Otherwise someone else is already
// exiting for us.
if (workspace == null) {
return; // A crash during server startup.
}
EventBus eventBus = workspace.getSkyframeExecutor().getEventBus();
if (eventBus != null) {
workspace
.getSkyframeExecutor()
.postLoggingStatsWhenCrashing(
new ExtendedEventHandler() {
@Override
public void post(Postable obj) {
eventBus.post(obj);
}
@Override
public void handle(Event event) {}
});
eventBus.post(new CrashEvent());
eventBus.post(new CommandCompleteEvent(exitCode));
}
}
// We don't call #shutDown() here because all it does is shut down the modules, and who knows if
// they can be trusted. Instead, we call runtime#shutdownOnCrash() which attempts to cleanly
// shut down those modules that might have something pending to do as a best-effort operation.
shutDownModulesOnCrash(exitCode);
}
@Nullable
public DetailedExitCode getCrashExitCode() {
return storedExitCode.get();
}
private boolean declareExitCode(DetailedExitCode detailedExitCode) {
return storedExitCode.compareAndSet(null, detailedExitCode);
}
/**
* Posts the {@link CommandCompleteEvent}, so that listeners can tidy up. Called by {@link
* #afterCommand}, and by BugReport when crashing from an exception in an async thread.
*
* <p>Returns null if {@code exitCode} was registered as the exit code, and the {@link
* DetailedExitCode} to use if another thread already registered an exit code.
*/
@Nullable
private DetailedExitCode notifyCommandComplete(DetailedExitCode exitCode) {
if (!declareExitCode(exitCode)) {
// This command has already been called, presumably because there is a race between the main
// thread and a worker thread that crashed. Don't try to arbitrate the dispute. If the main
// thread won the race (unlikely, but possible), this may be incorrectly logged as a success.
return storedExitCode.get();
}
workspace.getSkyframeExecutor().getEventBus().post(new CommandCompleteEvent(exitCode));
return null;
}
/**
* Hook method called by the BlazeCommandDispatcher after the dispatch of each command. Returns a
* new exit code in case exceptions were encountered during cleanup.
*/
@VisibleForTesting
public BlazeCommandResult afterCommand(CommandEnvironment env, BlazeCommandResult commandResult) {
this.env = null;
// Remove any filters that the command might have added to the reporter.
env.getReporter().setOutputFilter(OutputFilter.OUTPUT_EVERYTHING);
DetailedExitCode moduleExitCode = null;
for (BlazeModule module : blazeModules) {
try (SilentCloseable c = Profiler.instance().profile(module + ".afterCommand")) {
module.afterCommand();
} catch (AbruptExitException e) {
env.getReporter().handle(Event.error(e.getMessage()));
logger.atWarning().withCause(e).log("While running afterCommand() on %s", module);
moduleExitCode = chooseMoreImportantWithFirstIfTie(moduleExitCode, e.getDetailedExitCode());
}
}
env.getEventBus().post(new AfterCommandEvent());
// Wipe the dependency graph if requested. Note that this method always runs at the end of
// a commands unless the server crashes, in which case no inmemory state will linger for the
// next build anyway.
CommonCommandOptions commonOptions = env.getOptions().getOptions(CommonCommandOptions.class);
if (!commonOptions.keepStateAfterBuild) {
workspace.getSkyframeExecutor().resetEvaluator();
}
// Build-related commands already call this hook in BuildTool#stopRequest, but non-build
// commands might also need to notify the SkyframeExecutor. It's called in #stopRequest so that
// timing metrics for builds can be more accurate (since this call can be slow).
try {
workspace.getSkyframeExecutor().notifyCommandComplete(env.getReporter());
} catch (InterruptedException e) {
logger.atInfo().withCause(e).log("Interrupted in afterCommand");
moduleExitCode =
chooseMoreImportantWithFirstIfTie(
moduleExitCode,
InterruptedFailureDetails.detailedExitCode("executor completion interrupted"));
Thread.currentThread().interrupt();
}
BlazeCommandResult finalCommandResult;
if (!commandResult.getExitCode().isInfrastructureFailure() && moduleExitCode != null) {
finalCommandResult = BlazeCommandResult.detailedExitCode(moduleExitCode);
} else {
finalCommandResult = commandResult;
}
DetailedExitCode otherThreadWonExitCode =
notifyCommandComplete(finalCommandResult.getDetailedExitCode());
if (otherThreadWonExitCode != null) {
finalCommandResult = BlazeCommandResult.detailedExitCode(otherThreadWonExitCode);
}
env.getBlazeWorkspace().clearEventBus();
for (BlazeModule module : blazeModules) {
try (SilentCloseable closeable = Profiler.instance().profile(module + ".commandComplete")) {
module.commandComplete();
}
}
env.getReporter().clearEventBus();
actionKeyContext.clear();
DebugLoggerConfigurator.flushServerLog();
storedExitCode.set(null);
return BlazeCommandResult.withResponseExtensions(
finalCommandResult, env.getResponseExtensions());
}
/**
* Returns the Clock-instance used for the entire build. Before, individual classes (such as
* Profiler) used to specify the type of clock (e.g. EpochClock) they wanted to use. This made it
* difficult to get Blaze working on Windows as some of the clocks available for Linux aren't
* (directly) available on Windows. Setting the Blaze-wide clock upon construction of BlazeRuntime
* allows injecting whatever Clock instance should be used from BlazeMain.
*
* @return The Blaze-wide clock
*/
public Clock getClock() {
return clock;
}
/**
* Returns the {@link BugReporter} that should be used when filing bug reports, if possible. Use
* this in preference to {@link BugReport#sendBugReport} for ease of testing codepaths that file
* bug reports.
*/
public BugReporter getBugReporter() {
return bugReporter;
}
public OptionsParsingResult getStartupOptionsProvider() {
return startupOptionsProvider;
}
public Map<String, BlazeCommand> getCommandMap() {
return commandMap;
}
/** Invokes {@link BlazeModule#blazeShutdown()} on all registered modules. */
public void shutdown() {
try {
for (BlazeModule module : blazeModules) {
module.blazeShutdown();
}
} finally {
DebugLoggerConfigurator.flushServerLog();
}
}
public void prepareForAbruptShutdown() {
if (abruptShutdownHandler != null) {
abruptShutdownHandler.run();
}
}
/** Invokes {@link BlazeModule#blazeShutdownOnCrash} on all registered modules. */
private void shutDownModulesOnCrash(DetailedExitCode exitCode) {
// TODO(b/167592709): remove verbose logging when bug resolved.
logger.atInfo().log("Shutting down modules on crash: %s", blazeModules);
try {
for (BlazeModule module : blazeModules) {
logger.atInfo().log("Shutting down %s on crash", module);
module.blazeShutdownOnCrash(exitCode);
}
} finally {
DebugLoggerConfigurator.flushServerLog();
}
}
/** Creates a BuildOptions class for the given options taken from an {@link OptionsProvider}. */
public BuildOptions createBuildOptions(OptionsProvider optionsProvider) {
return BuildOptions.of(
ruleClassProvider.getFragmentRegistry().getOptionsClasses(), optionsProvider);
}
/**
* Main method for the Blaze server startup. Note: This method logs exceptions to remote servers.
* Do not add this to a unittest.
*/
public static void main(Iterable<Class<? extends BlazeModule>> moduleClasses, String[] args) {
setupUncaughtHandlerAtStartup(args);
List<BlazeModule> modules = createModules(moduleClasses);
// blaze.cc will put --batch first if the user set it.
if (args.length >= 1 && args[0].equals("--batch")) {
// Run Blaze in batch mode.
System.exit(batchMain(modules, args));
}
logger.atInfo().log(
"Starting Bazel server with %s, args %s", maybeGetPidString(), Arrays.toString(args));
try {
// Run Blaze in server mode.
System.exit(serverMain(modules, OutErr.SYSTEM_OUT_ERR, args));
} catch (RuntimeException | Error e) { // A definite bug...
Crash crash = Crash.from(e);
BugReport.handleCrash(crash, CrashContext.keepAlive().withArgs(args));
System.exit(crash.getDetailedExitCode().getExitCode().getNumericExitCode());
}
}
@VisibleForTesting
public static List<BlazeModule> createModules(
Iterable<Class<? extends BlazeModule>> moduleClasses) {
ImmutableList.Builder<BlazeModule> result = ImmutableList.builder();
for (Class<? extends BlazeModule> moduleClass : moduleClasses) {
try {
BlazeModule module = moduleClass.getConstructor().newInstance();
result.add(module);
} catch (Throwable e) {
throw new IllegalStateException("Cannot instantiate module " + moduleClass.getName(), e);
}
}
return result.build();
}
/** Command line options split in to two parts: startup options and everything else. */
@VisibleForTesting
static class CommandLineOptions {
private final ImmutableList<String> startupArgs;
private final ImmutableList<String> otherArgs;
CommandLineOptions(ImmutableList<String> startupArgs, ImmutableList<String> otherArgs) {
this.startupArgs = Preconditions.checkNotNull(startupArgs);
this.otherArgs = Preconditions.checkNotNull(otherArgs);
}
public ImmutableList<String> getStartupArgs() {
return startupArgs;
}
public ImmutableList<String> getOtherArgs() {
return otherArgs;
}
}
/**
* Splits given options into two lists - arguments matching options defined in this class and
* everything else, while preserving order in each list.
*
* <p>Note that this method relies on the startup options always being in the <code>--flag=ARG
* </code> form (instead of <code>--flag ARG</code>). This is enforced by <code>GetArgumentArray()
* </code> in <code>blaze.cc</code> by reconstructing the startup options from their parsed
* versions instead of using <code>argv</code> verbatim.
*/
static CommandLineOptions splitStartupOptions(Iterable<BlazeModule> modules, String... args) {
List<String> prefixes = new ArrayList<>();
List<OptionDefinition> startupOptions = Lists.newArrayList();
for (Class<? extends OptionsBase> defaultOptions :
BlazeCommandUtils.getStartupOptions(modules)) {
startupOptions.addAll(OptionsParser.getOptionDefinitions(defaultOptions));
}
for (OptionDefinition optionDefinition : startupOptions) {
Type optionType = optionDefinition.getField().getType();
prefixes.add("--" + optionDefinition.getOptionName());
if (optionType == boolean.class || optionType == TriState.class) {
prefixes.add("--no" + optionDefinition.getOptionName());
}
}
List<String> startupArgs = new ArrayList<>();
List<String> otherArgs = Lists.newArrayList(args);
for (Iterator<String> argi = otherArgs.iterator(); argi.hasNext(); ) {
String arg = argi.next();
if (!arg.startsWith("--")) {
break; // stop at command - all startup options would be specified before it.
}
for (String prefix : prefixes) {
if (arg.startsWith(prefix)) {
startupArgs.add(arg);
argi.remove();
break;
}
}
}
return new CommandLineOptions(
ImmutableList.copyOf(startupArgs), ImmutableList.copyOf(otherArgs));
}
@Nullable
private static String getSlowInterruptMessageSuffix(Iterable<BlazeModule> modules) {
String slowInterruptMessageSuffix = null;
for (BlazeModule module : modules) {
String message = module.getSlowThreadInterruptMessageSuffix();
if (message != null) {
checkState(
slowInterruptMessageSuffix == null,
"Two messages: %s %s (%s)",
slowInterruptMessageSuffix,
message,
module);
slowInterruptMessageSuffix = message;
}
}
return slowInterruptMessageSuffix;
}
private static InterruptSignalHandler captureSigint(@Nullable String slowInterruptMessage) {
Thread mainThread = Thread.currentThread();
AtomicInteger numInterrupts = new AtomicInteger();
Runnable interruptWatcher =
() -> {
int count = 0;
// Not an actual infinite loop because it's run in a daemon thread.
while (true) {
count++;
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
logger.atWarning().log("Slow interrupt number %d in batch mode", count);
ThreadUtils.warnAboutSlowInterrupt(slowInterruptMessage);
}
};
return new InterruptSignalHandler() {
@Override
public void run() {
logger.atInfo().log("User interrupt");
OutErr.SYSTEM_OUT_ERR.printErrLn("Bazel received an interrupt");
mainThread.interrupt();
int curNumInterrupts = numInterrupts.incrementAndGet();
if (curNumInterrupts == 1) {
Thread interruptWatcherThread = new Thread(interruptWatcher, "interrupt-watcher");
interruptWatcherThread.setDaemon(true);
interruptWatcherThread.start();
} else if (curNumInterrupts == 2) {
logger.atWarning().log("Second --batch interrupt: Reverting to JVM SIGINT handler");
uninstall();
}
}
};
}
/**
* A main method that runs blaze commands in batch mode. The return value indicates the desired
* exit status of the program.
*/
private static int batchMain(Iterable<BlazeModule> modules, String[] args) {
InterruptSignalHandler signalHandler = captureSigint(getSlowInterruptMessageSuffix(modules));
CommandLineOptions commandLineOptions = splitStartupOptions(modules, args);
logger.atInfo().log(
"Running Bazel in batch mode with %s, startup args %s",
maybeGetPidString(), commandLineOptions.getStartupArgs());
BlazeRuntime runtime;
InvocationPolicy policy;
try {
runtime = newRuntime(modules, commandLineOptions.getStartupArgs(), null);
policy =
InvocationPolicyParser.parsePolicy(
runtime.startupOptionsProvider.getOptions(BlazeServerStartupOptions.class)
.invocationPolicy);
} catch (OptionsParsingException e) {
OutErr.SYSTEM_OUT_ERR.printErrLn(e.getMessage());
return ExitCode.COMMAND_LINE_ERROR.getNumericExitCode();
} catch (AbruptExitException e) {
OutErr.SYSTEM_OUT_ERR.printErrLn(e.getMessage());
return e.getExitCode().getNumericExitCode();
}
ImmutableList.Builder<Pair<String, String>> startupOptionsFromCommandLine =
ImmutableList.builder();
for (String option : commandLineOptions.getStartupArgs()) {
startupOptionsFromCommandLine.add(new Pair<>("", option));
}
BlazeCommandDispatcher dispatcher =
new BlazeCommandDispatcher(runtime, BlazeCommandDispatcher.UNKNOWN_SERVER_PID);
boolean shutdownDone = false;
try {
logger.atInfo().log(
"%s", SafeRequestLogging.getRequestLogString(commandLineOptions.getOtherArgs()));
BlazeCommandResult result =
dispatcher.exec(
policy,
commandLineOptions.getOtherArgs(),
OutErr.SYSTEM_OUT_ERR,
LockingMode.ERROR_OUT,
"batch client",
runtime.clock.currentTimeMillis(),
Optional.of(startupOptionsFromCommandLine.build()),
/*commandExtensions=*/ ImmutableList.of());
if (result.getExecRequest() == null) {
// Simple case: we are given an exit code
return result.getExitCode().getNumericExitCode();
}
// Not so simple case: we need to execute a binary on shutdown. exec() is not accessible from
// Java and is impossible on Windows in any case, so we just execute the binary after getting
// out of the way as completely as possible and forward its exit code.
// When this code is executed, no locks are held: the client lock is released by the client
// before it executes any command and the server lock is handled by BlazeCommandDispatcher,
// whose job is done by the time we get here.
runtime.shutdown();
dispatcher.shutdown();
shutdownDone = true;
signalHandler.uninstall();
ExecRequest request = result.getExecRequest();
String[] argv = new String[request.getArgvCount()];
for (int i = 0; i < argv.length; i++) {
argv[i] = request.getArgv(i).toString(StandardCharsets.ISO_8859_1);
}
String workingDirectory = request.getWorkingDirectory().toString(StandardCharsets.ISO_8859_1);
try {
ProcessBuilder process =
new ProcessBuilder().command(argv).directory(new File(workingDirectory)).inheritIO();
for (int i = 0; i < request.getEnvironmentVariableCount(); i++) {
EnvironmentVariable variable = request.getEnvironmentVariable(i);
process
.environment()
.put(
variable.getName().toString(StandardCharsets.ISO_8859_1),
variable.getValue().toString(StandardCharsets.ISO_8859_1));
}
return process.start().waitFor();
} catch (IOException e) {
// We are in batch mode, thus, stdout/stderr are the same as that of the client.
System.err.println("Cannot execute process for 'run' command: " + e.getMessage());