-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
blaze.cc
2190 lines (1924 loc) · 88.1 KB
/
blaze.cc
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.
//
// blaze.cc: bootstrap and client code for Blaze server.
//
// Responsible for:
// - extracting the Python, C++ and Java components.
// - starting the server or finding the existing one.
// - client options parsing.
// - passing the argv array, and printing the out/err streams.
// - signal handling.
// - exiting with the right error/WTERMSIG code.
// - debugger + profiler support.
// - mutual exclusion between batch invocations.
#include "src/main/cpp/blaze.h"
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <chrono> // NOLINT (gRPC requires this)
#include <cinttypes>
#include <map>
#include <memory>
#include <mutex> // NOLINT
#include <set>
#include <sstream>
#include <string>
#include <thread> // NOLINT
#include <unordered_set>
#include <utility>
#include <vector>
#if !defined(_WIN32)
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "src/main/cpp/archive_utils.h"
#include "src/main/cpp/blaze_util.h"
#include "src/main/cpp/blaze_util_platform.h"
#include "src/main/cpp/option_processor.h"
#include "src/main/cpp/server_process_info.h"
#include "src/main/cpp/startup_options.h"
#include "src/main/cpp/util/bazel_log_handler.h"
#include "src/main/cpp/util/errors.h"
#include "src/main/cpp/util/exit_code.h"
#include "src/main/cpp/util/file.h"
#include "src/main/cpp/util/logging.h"
#include "src/main/cpp/util/numbers.h"
#include "src/main/cpp/util/path.h"
#include "src/main/cpp/util/path_platform.h"
#include "src/main/cpp/util/port.h"
#include "src/main/cpp/util/strings.h"
#include "src/main/cpp/workspace_layout.h"
#include "src/main/protobuf/command_server.grpc.pb.h"
using blaze_util::GetLastErrorString;
#if !defined(_WIN32)
extern char **environ;
#endif
namespace blaze {
using command_server::CommandServer;
using std::map;
using std::set;
using std::string;
using std::vector;
// The following is a treatise on how the interaction between the client and the
// server works.
//
// First, the client unconditionally acquires an flock() lock on
// $OUTPUT_BASE/lock then verifies if it has already extracted itself by
// checking if the directory it extracts itself to (install base + a checksum)
// is present. If not, then it does the extraction. Care is taken that this
// process is atomic so that Blazen in multiple output bases do not clash.
//
// Then the client tries to connect to the currently executing server and kills
// it if at least one of the following conditions is true:
//
// - The server is of the wrong version (as determined by the
// $OUTPUT_BASE/install symlink)
// - The server has different startup options than the client wants
// - The client wants to run the command in batch mode
//
// Then, if needed, the client adjusts the install link to indicate which
// version of the server it is running.
//
// In batch mode, the client then simply executes the server while taking care
// that the output base lock is kept until it finishes.
//
// If in server mode, the client starts up a server if needed then sends the
// command to the client and streams back stdout and stderr. The output base
// lock is released after the command is sent to the server (the server
// implements its own locking mechanism).
// Synchronization between the client and the server is a little precarious
// because the client needs to know the PID of the server and it is not
// available using a Java API and we don't have JNI on Windows at the moment,
// so the server can't just communicate this over the communication channel.
// Thus, a PID file is used, but care needs to be taken that the contents of
// this PID file are right.
//
// Upon server startup, the PID file is written before the client spawns the
// server. Thus, when the client can connect, it can be certain that the PID
// file is up to date.
//
// Upon server shutdown, the PID file is deleted using a server shutdown hook.
// However, this happens *after* the server stopped listening, so it's possible
// that a client has already started up a server and written a new PID file.
// In order to avoid this, when the client starts up a new server, it reads the
// contents of the PID file and kills the process indicated in it (it could do
// with a bit more care, since PIDs can be reused, but for now, we just believe
// the PID file)
//
// Some more interesting scenarios:
//
// - The server receives a kill signal and it does not have a chance to delete
// the PID file: the client cannot connect, reads the PID file, kills the
// process indicated in it and starts up a new server.
//
// - The server stopped accepting connections but hasn't quit yet and a new
// client comes around: the new client will kill the server based on the
// PID file before a new server is started up.
//
// Alternative implementations:
//
// - Don't deal with PIDs at all. This would make it impossible for the client
// to deliver a SIGKILL to the server after three SIGINTs. It would only be
// possible with gRPC anyway.
//
// - Have the server check that the PID file contains the correct things
// before deleting them: there is a window of time between checking the file
// and deleting it in which a new server can overwrite the PID file. The
// output base lock cannot be acquired, either, because when starting up a
// new server, the client already holds it.
//
// - Delete the PID file before stopping to accept connections: then a client
// could come about after deleting the PID file but before stopping accepting
// connections. It would also not be resilient against a dead server that
// left a PID file around.
// The reason for a blaze server restart.
// Keep in sync with logging.proto.
enum RestartReason {
NO_RESTART = 0,
NO_DAEMON,
NEW_VERSION,
NEW_OPTIONS,
PID_FILE_BUT_NO_SERVER,
SERVER_VANISHED,
SERVER_UNRESPONSIVE
};
// String string representation of RestartReason.
static const char *ReasonString(RestartReason reason) {
switch (reason) {
case NO_RESTART:
return "no_restart";
case NO_DAEMON:
return "no_daemon";
case NEW_VERSION:
return "new_version";
case NEW_OPTIONS:
return "new_options";
case PID_FILE_BUT_NO_SERVER:
return "pid_file_but_no_server";
case SERVER_VANISHED:
return "server_vanished";
case SERVER_UNRESPONSIVE:
return "server_unresponsive";
}
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "unknown RestartReason (" << reason << ").";
// Cannot actually reach this, but it makes the compiler happy.
return "unknown";
}
struct DurationMillis {
const uint64_t millis;
DurationMillis() : millis(kUnknownDuration) {}
DurationMillis(const uint64_t ms) : millis(ms) {}
bool IsKnown() const { return millis == kUnknownDuration; }
private:
// Value representing that a timing event never occurred or is unknown.
static constexpr uint64_t kUnknownDuration = 0;
};
// Encapsulates miscellaneous information reported to the server for logging and
// profiling purposes.
struct LoggingInfo {
explicit LoggingInfo(const string &binary_path_,
const uint64_t start_time_ms_)
: binary_path(binary_path_),
start_time_ms(start_time_ms_),
restart_reason(NO_RESTART) {}
void SetRestartReasonIfNotSet(const RestartReason restart_reason_) {
if (restart_reason == NO_RESTART) {
restart_reason = restart_reason_;
}
}
// Path of this binary.
const string binary_path;
// The time in ms the binary started up, measured from approximately the time
// that "main" was called.
const uint64_t start_time_ms;
// The reason the server was restarted.
RestartReason restart_reason;
};
class BlazeServer final {
public:
explicit BlazeServer(const StartupOptions &startup_options);
// Acquire a lock for the server running in this output base. Returns the
// number of milliseconds spent waiting for the lock.
uint64_t AcquireLock();
// Whether there is an active connection to a server.
bool Connected() const { return client_.get(); }
// Connect to the server. Returns if the connection was successful. Only
// call this when this object is in disconnected state. If it returns true,
// this object will be in connected state.
bool Connect();
// Send the command line to the server and forward whatever it says to stdout
// and stderr. Returns the desired exit code. Only call this when the server
// is in connected state.
unsigned int Communicate(
const std::string &command, const std::vector<std::string> &command_args,
const std::string &invocation_policy,
const std::vector<RcStartupFlag> &original_startup_options,
const LoggingInfo &logging_info,
const DurationMillis client_startup_duration,
const DurationMillis extract_data_duration,
const DurationMillis command_wait_duration_ms);
// Disconnects and kills an existing server. Only call this when this object
// is in connected state.
void KillRunningServer();
// Cancel the currently running command. If there is no command currently
// running, the result is unspecified. When called, this object must be in
// connected state.
void Cancel();
// Returns information about the actual server process and its configuration.
const ServerProcessInfo &ProcessInfo() const { return process_info_; }
private:
BlazeLock blaze_lock_;
enum CancelThreadAction { NOTHING, JOIN, CANCEL, COMMAND_ID_RECEIVED };
std::unique_ptr<CommandServer::Stub> client_;
std::string request_cookie_;
std::string response_cookie_;
std::string command_id_;
// protects command_id_ . Although we always set it before making the cancel
// thread do something with it, the mutex is still useful because it provides
// a memory fence.
std::mutex cancel_thread_mutex_;
// Pipe that the main thread sends actions to and the cancel thread receives
// actions from.
std::unique_ptr<blaze_util::IPipe> pipe_;
bool TryConnect(CommandServer::Stub *client);
void CancelThread();
void SendAction(CancelThreadAction action);
void SendCancelMessage();
ServerProcessInfo process_info_;
const int connect_timeout_secs_;
const bool batch_;
const bool block_for_lock_;
const bool preemptible_;
const blaze_util::Path output_base_;
};
////////////////////////////////////////////////////////////////////////
// Global Variables
static BlazeServer *blaze_server;
// TODO(laszlocsomor) 2016-11-24: release the `blaze_server` object. Currently
// nothing deletes it. Be careful that some functions may call exit(2) or
// _exit(2) (attributed with ATTRIBUTE_NORETURN) meaning we have to delete the
// objects before those.
uint64_t BlazeServer::AcquireLock() {
return blaze::AcquireLock(output_base_, batch_, block_for_lock_,
&blaze_lock_);
}
////////////////////////////////////////////////////////////////////////
// Logic
static map<string, EnvVarValue> PrepareEnvironmentForJvm();
// Escapes colons by replacing them with '_C' and underscores by replacing them
// with '_U'. E.g. "name:foo_bar" becomes "name_Cfoo_Ubar"
static string EscapeForOptionSource(const string &input) {
string result = input;
blaze_util::Replace("_", "_U", &result);
blaze_util::Replace(":", "_C", &result);
return result;
}
// Returns the JVM command argument array.
static vector<string> GetServerExeArgs(const blaze_util::Path &jvm_path,
const string &server_jar_path,
const vector<string> &archive_contents,
const string &install_md5,
const WorkspaceLayout &workspace_layout,
const string &workspace,
const StartupOptions &startup_options) {
vector<string> result;
// e.g. A Blaze server process running in ~/src/build_root (where there's a
// ~/src/build_root/WORKSPACE file) will appear in ps(1) as "blaze(src)".
result.push_back(startup_options.GetLowercaseProductName() + "(" +
workspace_layout.GetPrettyWorkspaceName(workspace) + ")");
startup_options.AddJVMArgumentPrefix(jvm_path.GetParent().GetParent(),
&result);
// TODO(b/109998449): only assume JDK >= 9 for embedded JDKs
if (!startup_options.GetEmbeddedJavabase().IsEmpty()) {
// quiet warnings from com.google.protobuf.UnsafeUtil,
// see: https://github.com/google/protobuf/issues/3781
result.push_back("--add-opens=java.base/java.nio=ALL-UNNAMED");
result.push_back("--add-opens=java.base/java.lang=ALL-UNNAMED");
}
result.push_back("-Xverify:none");
vector<string> user_options = startup_options.host_jvm_args;
// Add JVM arguments particular to building blaze64 and particular JVM
// versions.
string error;
blaze_exit_code::ExitCode jvm_args_exit_code =
startup_options.AddJVMArguments(startup_options.GetServerJavabase(),
&result, user_options, &error);
if (jvm_args_exit_code != blaze_exit_code::SUCCESS) {
BAZEL_DIE(jvm_args_exit_code) << error;
}
// We put all directories on java.library.path that contain .so/.dll files.
set<string> java_library_paths;
std::stringstream java_library_path;
java_library_path << "-Djava.library.path=";
blaze_util::Path real_install_dir =
blaze_util::Path(startup_options.install_base);
for (const auto &it : archive_contents) {
if (IsSharedLibrary(it)) {
string libpath(real_install_dir.GetRelative(blaze_util::Dirname(it))
.AsJvmArgument());
// Only add the library path if it's not added yet.
if (java_library_paths.insert(libpath).second) {
if (java_library_paths.size() > 1) {
java_library_path << kListSeparator;
}
java_library_path << libpath;
}
}
}
result.push_back(java_library_path.str());
// Force use of latin1 for file names.
result.push_back("-Dfile.encoding=ISO-8859-1");
if (startup_options.host_jvm_debug) {
BAZEL_LOG(USER)
<< "Running host JVM under debugger (listening on TCP port 5005).";
// Start JVM so that it listens for a connection from a
// JDWP-compliant debugger:
result.push_back("-Xdebug");
result.push_back("-Xrunjdwp:transport=dt_socket,server=y,address=5005");
}
result.insert(result.end(), user_options.begin(), user_options.end());
startup_options.AddJVMArgumentSuffix(real_install_dir, server_jar_path,
&result);
// JVM arguments are complete. Now pass in Blaze startup options.
// Note that we always use the --flag=ARG form (instead of the --flag ARG one)
// so that BlazeRuntime#splitStartupOptions has an easy job.
// TODO(b/152047869): Test that whatever the list constructed after this line
// is actually a list of parseable startup options.
if (!startup_options.batch) {
result.push_back("--max_idle_secs=" +
blaze_util::ToString(startup_options.max_idle_secs));
if (startup_options.shutdown_on_low_sys_mem) {
result.push_back("--shutdown_on_low_sys_mem");
} else {
result.push_back("--noshutdown_on_low_sys_mem");
}
} else {
// --batch must come first in the arguments to Java main() because
// the code expects it to be at args[0] if it's been set.
result.push_back("--batch");
}
if (startup_options.command_port != 0) {
result.push_back("--command_port=" +
blaze_util::ToString(startup_options.command_port));
}
result.push_back("--connect_timeout_secs=" +
blaze_util::ToString(startup_options.connect_timeout_secs));
result.push_back("--output_user_root=" +
blaze_util::ConvertPath(startup_options.output_user_root));
result.push_back("--install_base=" +
blaze_util::ConvertPath(startup_options.install_base));
result.push_back("--install_md5=" + install_md5);
result.push_back("--output_base=" +
startup_options.output_base.AsCommandLineArgument());
result.push_back("--workspace_directory=" +
blaze_util::ConvertPath(workspace));
if (startup_options.autodetect_server_javabase) {
result.push_back("--default_system_javabase=" + GetSystemJavabase());
}
if (!startup_options.server_jvm_out.IsEmpty()) {
result.push_back("--server_jvm_out=" +
startup_options.server_jvm_out.AsCommandLineArgument());
}
if (!startup_options.failure_detail_out.IsEmpty()) {
result.push_back(
"--failure_detail_out=" +
startup_options.failure_detail_out.AsCommandLineArgument());
}
if (startup_options.expand_configs_in_place) {
result.push_back("--expand_configs_in_place");
} else {
result.push_back("--noexpand_configs_in_place");
}
if (!startup_options.digest_function.empty()) {
// Only include this if a value is requested - we rely on the empty case
// being "null" to set the programmatic default in the server.
result.push_back("--digest_function=" + startup_options.digest_function);
}
if (!startup_options.unix_digest_hash_attribute_name.empty()) {
result.push_back("--unix_digest_hash_attribute_name=" +
startup_options.unix_digest_hash_attribute_name);
}
if (startup_options.idle_server_tasks) {
result.push_back("--idle_server_tasks");
} else {
result.push_back("--noidle_server_tasks");
}
if (startup_options.write_command_log) {
result.push_back("--write_command_log");
} else {
result.push_back("--nowrite_command_log");
}
if (startup_options.watchfs) {
result.push_back("--watchfs");
} else {
result.push_back("--nowatchfs");
}
if (startup_options.fatal_event_bus_exceptions) {
result.push_back("--fatal_event_bus_exceptions");
} else {
result.push_back("--nofatal_event_bus_exceptions");
}
if (startup_options.windows_enable_symlinks) {
result.push_back("--windows_enable_symlinks");
} else {
result.push_back("--nowindows_enable_symlinks");
}
// We use this syntax so that the logic in AreStartupOptionsDifferent() that
// decides whether the server needs killing is simpler. This is parsed by the
// Java code where --noclient_debug and --client_debug=false are equivalent.
// Note that --client_debug false (separated by space) won't work either,
// because the logic in AreStartupOptionsDifferent() assumes that every
// argument is in the --arg=value form.
if (startup_options.client_debug) {
result.push_back("--client_debug=true");
} else {
result.push_back("--client_debug=false");
}
// These flags are passed to the java process only for Blaze reporting
// purposes; the real interpretation of the jvm flags occurs when we set up
// the java command line.
if (!startup_options.GetExplicitServerJavabase().IsEmpty()) {
result.push_back(
"--server_javabase=" +
startup_options.GetExplicitServerJavabase().AsCommandLineArgument());
}
if (startup_options.host_jvm_debug) {
result.push_back("--host_jvm_debug");
}
if (!startup_options.host_jvm_profile.empty()) {
result.push_back("--host_jvm_profile=" + startup_options.host_jvm_profile);
}
if (!startup_options.host_jvm_args.empty()) {
for (const auto &arg : startup_options.host_jvm_args) {
result.push_back("--host_jvm_args=" + arg);
}
}
// Pass in invocation policy as a startup argument for batch mode only.
if (startup_options.batch && !startup_options.invocation_policy.empty()) {
result.push_back("--invocation_policy=" +
startup_options.invocation_policy);
}
result.push_back("--product_name=" + startup_options.product_name);
startup_options.AddExtraOptions(&result);
// The option sources are transmitted in the following format:
// --option_sources=option1:source1:option2:source2:...
string option_sources = "--option_sources=";
bool first = true;
for (const auto &it : startup_options.option_sources) {
if (!first) {
option_sources += ":";
}
first = false;
option_sources += EscapeForOptionSource(it.first) + ":" +
EscapeForOptionSource(it.second);
}
result.push_back(option_sources);
return result;
}
// Add common command options for logging to the given argument array.
static void AddLoggingArgs(const LoggingInfo &logging_info,
const DurationMillis client_startup_duration,
const DurationMillis extract_data_duration,
const DurationMillis command_wait_duration_ms,
vector<string> *args) {
// The time in ms the launcher spends before sending the request to the blaze
// server.
args->push_back("--startup_time=" +
blaze_util::ToString(client_startup_duration.millis));
// The time in ms a command had to wait on a busy Blaze server process.
// This is part of startup_time.
if (command_wait_duration_ms.IsKnown()) {
args->push_back("--command_wait_time=" +
blaze_util::ToString(command_wait_duration_ms.millis));
}
// The time in ms spent on extracting the new blaze version.
// This is part of startup_time.
if (extract_data_duration.IsKnown()) {
args->push_back("--extract_data_time=" +
blaze_util::ToString(extract_data_duration.millis));
}
if (logging_info.restart_reason != NO_RESTART) {
args->push_back(string("--restart_reason=") +
ReasonString(logging_info.restart_reason));
}
args->push_back(string("--binary_path=") + logging_info.binary_path);
}
// Join the elements of the specified array with NUL's (\0's), akin to the
// format of /proc/$PID/cmdline.
static string GetArgumentString(const vector<string> &argument_array) {
string result;
blaze_util::JoinStrings(argument_array, '\0', &result);
return result;
}
static void EnsureServerDir(const blaze_util::Path &server_dir) {
// The server dir has the connection info - don't allow access by other users.
if (!blaze_util::MakeDirectories(server_dir, 0700)) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "server directory '" << server_dir.AsPrintablePath()
<< "' could not be created: " << GetLastErrorString();
}
}
// Do a chdir into the workspace, and die if it fails.
static const void GoToWorkspace(const WorkspaceLayout &workspace_layout,
const string &workspace) {
if (workspace_layout.InWorkspace(workspace) &&
!blaze_util::ChangeDirectory(workspace)) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "changing directory into " << workspace
<< " failed: " << GetLastErrorString();
}
}
static const bool IsServerMode(const string &command) {
return "exec-server" == command;
}
// Replace this process with the blaze server. Does not exit.
static void RunServerMode(
const blaze_util::Path &server_exe, const vector<string> &server_exe_args,
const blaze_util::Path &server_dir, const WorkspaceLayout &workspace_layout,
const string &workspace, const OptionProcessor &option_processor,
const StartupOptions &startup_options, BlazeServer *server) {
if (startup_options.batch) {
BAZEL_DIE(blaze_exit_code::BAD_ARGV)
<< "exec-server command is not compatible with --batch";
}
BAZEL_LOG(INFO) << "Running in server mode.";
if (server->Connected()) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "exec-server failed, please shut down existing server pid="
<< server->ProcessInfo().server_pid_ << " and retry.";
}
EnsureServerDir(server_dir);
blaze_util::WriteFile(blaze::GetProcessIdAsString(),
server_dir.GetRelative("server.pid.txt"));
blaze_util::WriteFile(GetArgumentString(server_exe_args),
server_dir.GetRelative("cmdline"));
GoToWorkspace(workspace_layout, workspace);
SetScheduling(startup_options.batch_cpu_scheduling,
startup_options.io_nice_level);
{
WithEnvVars env_obj(PrepareEnvironmentForJvm());
ExecuteServerJvm(server_exe, server_exe_args);
}
}
// Replace this process with blaze in standalone/batch mode.
// The batch mode blaze process handles the command and exits.
static void RunBatchMode(
const blaze_util::Path &server_exe, const vector<string> &server_exe_args,
const WorkspaceLayout &workspace_layout, const string &workspace,
const OptionProcessor &option_processor,
const StartupOptions &startup_options, LoggingInfo *logging_info,
const DurationMillis extract_data_duration,
const DurationMillis command_wait_duration_ms, BlazeServer *server) {
if (server->Connected()) {
server->KillRunningServer();
}
const DurationMillis client_startup_duration(GetMillisecondsMonotonic() -
logging_info->start_time_ms);
BAZEL_LOG(INFO) << "Starting " << startup_options.product_name
<< " in batch mode.";
const string command = option_processor.GetCommand();
const vector<string> command_arguments =
option_processor.GetCommandArguments();
if (!command_arguments.empty() && command == "shutdown") {
string product = startup_options.GetLowercaseProductName();
BAZEL_LOG(WARNING)
<< "Running command \"shutdown\" in batch mode. Batch mode is "
"triggered\nwhen not running "
<< startup_options.product_name
<< " within a workspace. If you intend to shutdown an\nexisting "
<< startup_options.product_name << " server, run \"" << product
<< " shutdown\" from the directory where\nit was started.";
}
vector<string> jvm_args_vector = server_exe_args;
if (!command.empty()) {
jvm_args_vector.push_back(command);
AddLoggingArgs(*logging_info, client_startup_duration,
extract_data_duration, command_wait_duration_ms,
&jvm_args_vector);
}
jvm_args_vector.insert(jvm_args_vector.end(), command_arguments.begin(),
command_arguments.end());
GoToWorkspace(workspace_layout, workspace);
SetScheduling(startup_options.batch_cpu_scheduling,
startup_options.io_nice_level);
{
WithEnvVars env_obj(PrepareEnvironmentForJvm());
ExecuteServerJvm(server_exe, jvm_args_vector);
}
}
static void WriteFileToStderrOrDie(const blaze_util::Path &path) {
#if defined(_WIN32) || defined(__CYGWIN__)
FILE *fp = _wfopen(path.AsNativePath().c_str(), L"r");
#else
FILE *fp = fopen(path.AsNativePath().c_str(), "r");
#endif
if (fp == nullptr) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "opening " << path.AsPrintablePath()
<< " failed: " << GetLastErrorString();
}
char buffer[255];
int num_read;
while ((num_read = fread(buffer, 1, sizeof buffer, fp)) > 0) {
if (ferror(fp)) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "failed to read from '" << path.AsPrintablePath()
<< "': " << GetLastErrorString();
}
fwrite(buffer, 1, num_read, stderr);
}
fclose(fp);
}
// After connecting to the Blaze server, return its PID, or -1 if there was an
// error.
static int GetServerPid(const blaze_util::Path &server_dir) {
// Note: there is no race here on startup since the server creates
// the pid file strictly before it binds the socket.
blaze_util::Path pid_file = server_dir.GetRelative(kServerPidFile);
string bufstr;
int result;
if (!blaze_util::ReadFile(pid_file, &bufstr, 32) ||
!blaze_util::safe_strto32(bufstr, &result)) {
return -1;
}
return result;
}
// Connect to the server process or exit if it doesn't work out.
static void ConnectOrDie(const OptionProcessor &option_processor,
const StartupOptions &startup_options,
const int server_pid,
BlazeServerStartup *server_startup,
BlazeServer *server) {
// Give the server two minutes to start up. That's enough to connect with a
// debugger.
const auto start_time = std::chrono::system_clock::now();
const auto try_until_time =
start_time +
std::chrono::seconds(startup_options.local_startup_timeout_secs);
// Print an update at most once every 10 seconds if we are still trying to
// connect.
const auto min_message_interval = std::chrono::seconds(10);
auto last_message_time = start_time;
while (std::chrono::system_clock::now() < try_until_time) {
const auto attempt_time = std::chrono::system_clock::now();
const auto next_attempt_time =
attempt_time + std::chrono::milliseconds(100);
if (server->Connect()) {
return;
}
if (attempt_time >= (last_message_time + min_message_interval)) {
auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(
attempt_time - start_time);
BAZEL_LOG(USER) << "... still trying to connect to local "
<< startup_options.product_name << " server ("
<< server_pid << ") after " << elapsed_time.count()
<< " seconds ...";
last_message_time = attempt_time;
}
std::this_thread::sleep_until(next_attempt_time);
if (!server_startup->IsStillAlive()) {
option_processor.PrintStartupOptionsProvenanceMessage();
if (server->ProcessInfo().jvm_log_file_append_) {
// Don't dump the log if we were appending - the user should know where
// to find it, and who knows how much content they may have accumulated.
BAZEL_LOG(USER)
<< "Server crashed during startup. See "
<< server->ProcessInfo().jvm_log_file_.AsPrintablePath();
} else {
BAZEL_LOG(USER)
<< "Server crashed during startup. Now printing "
<< server->ProcessInfo().jvm_log_file_.AsPrintablePath();
WriteFileToStderrOrDie(server->ProcessInfo().jvm_log_file_);
}
exit(blaze_exit_code::INTERNAL_ERROR);
}
}
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "couldn't connect to server (" << server_pid << ") after "
<< startup_options.local_startup_timeout_secs << " seconds.";
}
// Ensures that any server previously associated with `server_dir` is no longer
// running.
static void EnsurePreviousServerProcessTerminated(
const blaze_util::Path &server_dir, const StartupOptions &startup_options,
LoggingInfo *logging_info) {
int server_pid = GetServerPid(server_dir);
if (server_pid > 0) {
if (VerifyServerProcess(server_pid, startup_options.output_base)) {
if (KillServerProcess(server_pid, startup_options.output_base)) {
BAZEL_LOG(USER) << "Killed non-responsive server process (pid="
<< server_pid << ")";
logging_info->SetRestartReasonIfNotSet(SERVER_UNRESPONSIVE);
} else {
logging_info->SetRestartReasonIfNotSet(SERVER_VANISHED);
}
} else {
logging_info->SetRestartReasonIfNotSet(PID_FILE_BUT_NO_SERVER);
}
}
}
// Starts up a new server and connects to it. Exits if it didn't work out.
static void StartServerAndConnect(
const blaze_util::Path &server_exe, const vector<string> &server_exe_args,
const blaze_util::Path &server_dir, const WorkspaceLayout &workspace_layout,
const string &workspace, const OptionProcessor &option_processor,
const StartupOptions &startup_options, LoggingInfo *logging_info,
BlazeServer *server) {
// Delete the old command_port file if it already exists. Otherwise we might
// run into the race condition that we read the old command_port file before
// the new server has written the new file and we try to connect to the old
// port, run into a timeout and try again.
(void)blaze_util::UnlinkPath(server_dir.GetRelative("command_port"));
EnsureServerDir(server_dir);
// Really make sure there's no other server running in this output base (even
// an unresponsive one), as that could cause major problems.
EnsurePreviousServerProcessTerminated(server_dir, startup_options,
logging_info);
// cmdline file is used to validate the server running in this server_dir.
// There's no server running now so we're safe to unconditionally write this.
blaze_util::WriteFile(GetArgumentString(server_exe_args),
server_dir.GetRelative("cmdline"));
// Do this here instead of in the daemon so the user can see if it fails.
GoToWorkspace(workspace_layout, workspace);
logging_info->SetRestartReasonIfNotSet(NO_DAEMON);
SetScheduling(startup_options.batch_cpu_scheduling,
startup_options.io_nice_level);
BAZEL_LOG(USER) << "Starting local " << startup_options.product_name
<< " server and connecting to it...";
BlazeServerStartup *server_startup;
const int server_pid = ExecuteDaemon(
server_exe, server_exe_args, PrepareEnvironmentForJvm(),
server->ProcessInfo().jvm_log_file_,
server->ProcessInfo().jvm_log_file_append_, startup_options.install_base,
server_dir, startup_options, &server_startup);
ConnectOrDie(option_processor, startup_options, server_pid, server_startup,
server);
delete server_startup;
}
static void BlessFiles(const string &embedded_binaries) {
blaze_util::Path embedded_binaries_(embedded_binaries);
// Set the timestamps of the extracted files to the future and make sure (or
// at least as sure as we can...) that the files we have written are actually
// on the disk.
vector<string> extracted_files;
// Walks the temporary directory recursively and collects full file paths.
blaze_util::GetAllFilesUnder(embedded_binaries, &extracted_files);
std::unique_ptr<blaze_util::IFileMtime> mtime(blaze_util::CreateFileMtime());
set<blaze_util::Path> synced_directories;
for (const auto &f : extracted_files) {
blaze_util::Path it(f);
// Set the time to a distantly futuristic value so we can observe tampering.
// Note that keeping a static, deterministic timestamp, such as the default
// timestamp set by unzip (1970-01-01) and using that to detect tampering is
// not enough, because we also need the timestamp to change between Bazel
// releases so that the metadata cache knows that the files may have
// changed. This is essential for the correctness of actions that use
// embedded binaries as artifacts.
if (!mtime->SetToDistantFuture(it)) {
string err = GetLastErrorString();
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "failed to set timestamp on '" << it.AsPrintablePath()
<< "': " << err;
}
blaze_util::SyncFile(it);
blaze_util::Path directory = it.GetParent();
// Now walk up until embedded_binaries and sync every directory in between.
// synced_directories is used to avoid syncing the same directory twice.
// The !directory.empty() and !blaze_util::IsRootDirectory(directory)
// conditions are not strictly needed, but it makes this loop more robust,
// because otherwise, if due to some glitch, directory was not under
// embedded_binaries, it would get into an infinite loop.
while (directory != embedded_binaries_ && !directory.IsEmpty() &&
!blaze_util::IsRootDirectory(directory) &&
synced_directories.insert(directory).second) {
blaze_util::SyncFile(directory);
directory = directory.GetParent();
}
}
blaze_util::SyncFile(embedded_binaries_);
}
// Installs Blaze by extracting the embedded data files, iff necessary.
// The MD5-named install_base directory on disk is trusted; we assume
// no-one has modified the extracted files beneath this directory once
// it is in place. Concurrency during extraction is handled by
// extracting in a tmp dir and then renaming it into place where it
// becomes visible atomically at the new path.
static DurationMillis ExtractData(const string &self_path,
const vector<string> &archive_contents,
const string &expected_install_md5,
const StartupOptions &startup_options,
LoggingInfo *logging_info) {
const string &install_base = startup_options.install_base;
// If the install dir doesn't exist, create it, if it does, we know it's good.
if (!blaze_util::PathExists(install_base)) {
uint64_t st = GetMillisecondsMonotonic();
// Work in a temp dir to avoid races.
string tmp_install = blaze_util::CreateTempDir(install_base + ".tmp.");
ExtractArchiveOrDie(self_path, startup_options.product_name,
expected_install_md5, tmp_install);
BlessFiles(tmp_install);
uint64_t et = GetMillisecondsMonotonic();
const DurationMillis extract_data_duration(et - st);
// Now rename the completed installation to its final name.
int attempts = 0;
while (attempts < 120) {
int result = blaze_util::RenameDirectory(tmp_install, install_base);
if (result == blaze_util::kRenameDirectorySuccess ||
result == blaze_util::kRenameDirectoryFailureNotEmpty) {
// If renaming fails because the directory already exists and is not
// empty, then we assume another good installation snuck in before us.
blaze_util::RemoveRecursively(tmp_install);
break;
} else {
// Otherwise the install directory may still be scanned by the antivirus
// (in case we're running on Windows) so we need to wait for that to
// finish and try renaming again.
++attempts;
BAZEL_LOG(USER) << "install base directory '" << tmp_install
<< "' could not be renamed into place after "
<< attempts << " second(s), trying again\r";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
// Give up renaming after 120 failed attempts / 2 minutes.
if (attempts == 120) {
blaze_util::RemoveRecursively(tmp_install);