blob: 1aaa11772170d55894e9f53ae9963613b64da1bc [file] [log] [blame]
Damien Martin-Guillerezf88f4d82015-09-25 13:56:55 +00001// Copyright 2014 The Bazel Authors. All rights reserved.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01002//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// blaze.cc: bootstrap and client code for Blaze server.
16//
17// Responsible for:
18// - extracting the Python, C++ and Java components.
19// - starting the server or finding the existing one.
20// - client options parsing.
21// - passing the argv array, and printing the out/err streams.
22// - signal handling.
23// - exiting with the right error/WTERMSIG code.
24// - debugger + profiler support.
25// - mutual exclusion between batch invocations.
Julio Merino28774852016-09-14 16:59:46 +000026#include "src/main/cpp/blaze.h"
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010027
28#include <assert.h>
29#include <ctype.h>
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010030#include <errno.h>
31#include <fcntl.h>
32#include <limits.h>
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010033#include <stdarg.h>
Thiago Farina8a67da42015-05-05 18:04:50 +000034#include <stdint.h>
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010035#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000038
39#include <grpc/grpc.h>
Googler197547b2016-09-26 22:25:14 +000040#include <grpc/support/log.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000041#include <grpc++/channel.h>
42#include <grpc++/client_context.h>
43#include <grpc++/create_channel.h>
44#include <grpc++/security/credentials.h>
45
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010046#include <algorithm>
Lukacs Berki1b25ce22016-04-15 13:11:21 +000047#include <chrono> // NOLINT (gRPC requires this)
Lukacs Berkif1df38a2016-04-19 07:42:22 +000048#include <mutex> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010049#include <set>
50#include <string>
Lukacs Berkif1df38a2016-04-19 07:42:22 +000051#include <thread> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010052#include <utility>
53#include <vector>
54
Lukacs Berkie21e5922016-04-12 12:22:20 +000055
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000056#include "src/main/cpp/blaze_util.h"
57#include "src/main/cpp/blaze_util_platform.h"
Thiago Farina676cb9f2016-10-06 11:00:43 +000058#include "src/main/cpp/global_variables.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000059#include "src/main/cpp/option_processor.h"
Julio Merino28774852016-09-14 16:59:46 +000060#include "src/main/cpp/startup_options.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000061#include "src/main/cpp/util/errors.h"
Thiago Farina7f9357f2015-04-23 13:57:43 +000062#include "src/main/cpp/util/exit_code.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000063#include "src/main/cpp/util/file.h"
Laszlo Csomor9c951962016-11-10 13:31:27 +000064#include "src/main/cpp/util/file_platform.h"
Chloe Calvarin78f1c852016-11-22 21:58:50 +000065#include "src/main/cpp/util/logging.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000066#include "src/main/cpp/util/numbers.h"
67#include "src/main/cpp/util/port.h"
68#include "src/main/cpp/util/strings.h"
Julio Merino211a95c2016-08-29 11:01:35 +000069#include "src/main/cpp/workspace_layout.h"
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +000070#include "third_party/ijar/zip.h"
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010071
Lukacs Berkie21e5922016-04-12 12:22:20 +000072#include "src/main/protobuf/command_server.grpc.pb.h"
73
Thiago Farina241f46c2015-04-13 14:33:30 +000074using blaze_util::die;
75using blaze_util::pdie;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010076
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010077namespace blaze {
78
Thiago Farina80bb0f22016-10-17 15:57:13 +000079using std::set;
80using std::string;
81using std::vector;
82
Lukacs Berki1977d922016-05-02 09:31:37 +000083static int GetServerPid(const string &server_dir);
Eric Fellheimer3a695f32016-05-11 17:26:30 +000084static void VerifyJavaVersionAndSetJvm();
Lukacs Berki907dbbf2016-04-15 11:30:12 +000085
Lukacs Berki1977d922016-05-02 09:31:37 +000086// The following is a treatise on how the interaction between the client and the
87// server works.
88//
89// First, the client unconditionally acquires an flock() lock on
90// $OUTPUT_BASE/lock then verifies if it has already extracted itself by
91// checking if the directory it extracts itself to (install base + a checksum)
92// is present. If not, then it does the extraction. Care is taken that this
93// process is atomic so that Blazen in multiple output bases do not clash.
94//
95// Then the client tries to connect to the currently executing server and kills
96// it if at least one of the following conditions is true:
97//
98// - The server is of the wrong version (as determined by the
99// $OUTPUT_BASE/install symlink)
100// - The server has different startup options than the client wants
101// - The client wants to run the command in batch mode
102//
103// Then, if needed, the client adjusts the install link to indicate which
104// version of the server it is running.
105//
106// In batch mode, the client then simply executes the server while taking care
107// that the output base lock is kept until it finishes.
108//
109// If in server mode, the client starts up a server if needed then sends the
Thiago Farina69dac862016-11-02 09:48:27 +0000110// command to the client and streams back stdout and stderr. The output base
111// lock is released after the command is sent to the server (the server
112// implements its own locking mechanism).
Lukacs Berki1977d922016-05-02 09:31:37 +0000113
114// Synchronization between the client and the server is a little precarious
115// because the client needs to know the PID of the server and it is not
116// available using a Java API and we don't have JNI on Windows at the moment,
117// so the server can't just communicate this over the communication channel.
118// Thus, a PID file is used, but care needs to be taken that the contents of
119// this PID file are right.
120//
121// Upon server startup, the PID file is written before the client spawns the
122// server. Thus, when the client can connect, it can be certain that the PID
123// file is up to date.
124//
125// Upon server shutdown, the PID file is deleted using a server shutdown hook.
126// However, this happens *after* the server stopped listening, so it's possible
127// that a client has already started up a server and written a new PID file.
128// In order to avoid this, when the client starts up a new server, it reads the
129// contents of the PID file and kills the process indicated in it (it could do
130// with a bit more care, since PIDs can be reused, but for now, we just believe
131// the PID file)
132//
133// Some more interesting scenarios:
134//
135// - The server receives a kill signal and it does not have a chance to delete
136// the PID file: the client cannot connect, reads the PID file, kills the
137// process indicated in it and starts up a new server.
138//
139// - The server stopped accepting connections but hasn't quit yet and a new
140// client comes around: the new client will kill the server based on the
141// PID file before a new server is started up.
142//
143// Alternative implementations:
144//
145// - Don't deal with PIDs at all. This would make it impossible for the client
146// to deliver a SIGKILL to the server after three SIGINTs. It would only be
147// possible with gRPC anyway.
148//
149// - Have the server check that the PID file containts the correct things
150// before deleting them: there is a window of time between checking the file
151// and deleting it in which a new server can overwrite the PID file. The
152// output base lock cannot be acquired, either, because when starting up a
153// new server, the client already holds it.
154//
155// - Delete the PID file before stopping to accept connections: then a client
156// could come about after deleting the PID file but before stopping accepting
157// connections. It would also not be resilient against a dead server that
158// left a PID file around.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000159class BlazeServer {
160 public:
161 virtual ~BlazeServer() {}
162
Lukacs Berki1977d922016-05-02 09:31:37 +0000163 // Acquire a lock for the server running in this output base. Returns the
164 // number of milliseconds spent waiting for the lock.
Lukacs Berki415d39a2016-04-28 13:18:54 +0000165 uint64_t AcquireLock();
166
Lukacs Berki1977d922016-05-02 09:31:37 +0000167 // Whether there is an active connection to a server.
168 bool Connected() const { return connected_; }
169
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000170 // Connect to the server. Returns if the connection was successful. Only
171 // call this when this object is in disconnected state. If it returns true,
172 // this object will be in connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000173 virtual bool Connect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000174
175 // Disconnects from an existing server. Only call this when this object is in
176 // connected state. After this call returns, the object will be in connected
177 // state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000178 virtual void Disconnect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000179
180 // Send the command line to the server and forward whatever it says to stdout
181 // and stderr. Returns the desired exit code. Only call this when the server
182 // is in connected state.
183 virtual unsigned int Communicate() = 0;
184
185 // Disconnects and kills an existing server. Only call this when this object
186 // is in connected state.
Lukacs Berki1977d922016-05-02 09:31:37 +0000187 virtual void KillRunningServer() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000188
189 // Cancel the currently running command. If there is no command currently
Lukacs Berki1977d922016-05-02 09:31:37 +0000190 // running, the result is unspecified. When called, this object must be in
191 // connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000192 virtual void Cancel() = 0;
Thiago Farina69dac862016-11-02 09:48:27 +0000193
194 protected:
195 BlazeLock blaze_lock_;
196 bool connected_;
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000197};
198
Lukacs Berki415d39a2016-04-28 13:18:54 +0000199////////////////////////////////////////////////////////////////////////
200// Global Variables
201static GlobalVariables *globals;
202static BlazeServer *blaze_server;
203
Laszlo Csomor32086b22016-11-24 15:23:55 +0000204// TODO(laszlocsomor) 2016-11-24: release the `globals` and `blaze_server`
205// objects. Currently nothing deletes them. Be careful that some functions may
206// call exit(2) or _exit(2) (attributed with ATTRIBUTE_NORETURN) meaning we have
207// to delete the objects before those.
208
Lukacs Berki415d39a2016-04-28 13:18:54 +0000209uint64_t BlazeServer::AcquireLock() {
210 return blaze::AcquireLock(
Julio Merino28774852016-09-14 16:59:46 +0000211 globals->options->output_base, globals->options->batch,
212 globals->options->block_for_lock, &blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +0000213}
214
Lukacs Berki1977d922016-05-02 09:31:37 +0000215// Communication method that uses gRPC on a socket bound to localhost. More
216// documentation is in command_server.proto .
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000217class GrpcBlazeServer : public BlazeServer {
218 public:
Lukacs Berki71675a52016-11-08 09:48:27 +0000219 GrpcBlazeServer(int connect_timeout_secs);
Lukacs Berki6dd29092016-05-30 14:05:33 +0000220 virtual ~GrpcBlazeServer();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000221
Lukacs Berki9d52bc52016-06-07 11:11:04 +0000222 virtual bool Connect();
223 virtual void Disconnect();
224 virtual unsigned int Communicate();
225 virtual void KillRunningServer();
226 virtual void Cancel();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000227
228 private:
Lukacs Berki6dd29092016-05-30 14:05:33 +0000229 enum CancelThreadAction { NOTHING, JOIN, CANCEL, COMMAND_ID_RECEIVED };
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000230
231 std::unique_ptr<command_server::CommandServer::Stub> client_;
232 std::string request_cookie_;
233 std::string response_cookie_;
234 std::string command_id_;
235
Lukacs Berki6dd29092016-05-30 14:05:33 +0000236 // protects command_id_ . Although we always set it before making the cancel
237 // thread do something with it, the mutex is still useful because it provides
238 // a memory fence.
239 std::mutex cancel_thread_mutex_;
Lukacs Berki8b999982016-04-26 15:40:38 +0000240
Lukacs Berki71675a52016-11-08 09:48:27 +0000241 int connect_timeout_secs_;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +0000242
Thiago Farina0bba4c92016-12-14 15:29:11 +0000243 // Pipe that the main thread sends actions to and the cancel thread receives
Laszlo Csomoref5ceef2016-11-18 11:19:02 +0000244 // actions from.
Thiago Farina0bba4c92016-12-14 15:29:11 +0000245 blaze_util::IPipe *pipe_;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000246
Lukacs Berki10dd6382017-01-11 09:08:54 +0000247 bool TryConnect(command_server::CommandServer::Stub* client);
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000248 void CancelThread();
Lukacs Berki6dd29092016-05-30 14:05:33 +0000249 void SendAction(CancelThreadAction action);
250 void SendCancelMessage();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000251};
252
253
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100254////////////////////////////////////////////////////////////////////////
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100255// Logic
256
Lukacs Berki71675a52016-11-08 09:48:27 +0000257void debug_log(const char* format, ...) {
258 if (!globals->options->client_debug) {
259 return;
260 }
261
262 fprintf(stderr, "CLIENT: ");
263 va_list arglist;
264 va_start(arglist, format);
265 vfprintf(stderr, format, arglist);
266 va_end(arglist);
267 fprintf(stderr, "%s", "\n");
268 fflush(stderr);
269}
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100270
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000271// A devtools_ijar::ZipExtractorProcessor to extract the InstallKeyFile
272class GetInstallKeyFileProcessor : public devtools_ijar::ZipExtractorProcessor {
273 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000274 explicit GetInstallKeyFileProcessor(string *install_base_key)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000275 : install_base_key_(install_base_key) {}
276
277 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
278 globals->extracted_binaries.push_back(filename);
279 return strcmp(filename, "install_base_key") == 0;
280 }
281
282 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
283 const devtools_ijar::u1 *data, const size_t size) {
284 string str(reinterpret_cast<const char *>(data), size);
285 blaze_util::StripWhitespace(&str);
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000286 if (str.size() != 32) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000287 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000288 "\nFailed to extract install_base_key: file size mismatch "
289 "(should be 32, is %zd)", str.size());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000290 }
291 *install_base_key_ = str;
292 }
293
294 private:
295 string *install_base_key_;
296};
297
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100298// Returns the install base (the root concatenated with the contents of the file
299// 'install_base_key' contained as a ZIP entry in the Blaze binary); as a side
300// effect, it also populates the extracted_binaries global variable.
301static string GetInstallBase(const string &root, const string &self_path) {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000302 GetInstallKeyFileProcessor processor(&globals->install_md5);
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000303 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
304 devtools_ijar::ZipExtractor::Create(self_path.c_str(), &processor));
305 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100306 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000307 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000308 globals->options->product_name.c_str(), errno, strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100309 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000310 if (extractor->ProcessAll() < 0) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100311 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000312 "\nFailed to extract install_base_key: %s", extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100313 }
314
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000315 if (globals->install_md5.empty()) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000316 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
317 "\nFailed to find install_base_key's in zip file");
318 }
Laszlo Csomor760f7862016-12-19 15:46:47 +0000319 return blaze_util::JoinPath(root, globals->install_md5);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100320}
321
322// Escapes colons by replacing them with '_C' and underscores by replacing them
323// with '_U'. E.g. "name:foo_bar" becomes "name_Cfoo_Ubar"
324static string EscapeForOptionSource(const string& input) {
325 string result = input;
326 blaze_util::Replace("_", "_U", &result);
327 blaze_util::Replace(":", "_C", &result);
328 return result;
329}
330
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000331// Returns the installed embedded binaries directory, under the shared
332// install_base location.
333string GetEmbeddedBinariesRoot(const string &install_base) {
334 return blaze_util::JoinPath(install_base, "_embedded_binaries");
335}
336
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100337// Returns the JVM command argument array.
338static vector<string> GetArgumentArray() {
339 vector<string> result;
340
341 // e.g. A Blaze server process running in ~/src/build_root (where there's a
342 // ~/src/build_root/WORKSPACE file) will appear in ps(1) as "blaze(src)".
343 string workspace =
344 blaze_util::Basename(blaze_util::Dirname(globals->workspace));
Julio Merino28774852016-09-14 16:59:46 +0000345 string product = globals->options->product_name;
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000346 blaze_util::ToLower(&product);
347 result.push_back(product + "(" + workspace + ")");
Julio Merino28774852016-09-14 16:59:46 +0000348 globals->options->AddJVMArgumentPrefix(
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000349 blaze_util::Dirname(blaze_util::Dirname(globals->jvm_path)),
350 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100351
352 result.push_back("-XX:+HeapDumpOnOutOfMemoryError");
Julio Merino28774852016-09-14 16:59:46 +0000353 string heap_crash_path = globals->options->output_base;
Dmitry Lomov7608db52016-07-14 11:27:10 +0000354 result.push_back("-XX:HeapDumpPath=" + ConvertPath(heap_crash_path));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100355
356 result.push_back("-Xverify:none");
357
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000358 vector<string> user_options;
359
Janak Ramakrishnan0acd1542016-01-06 18:42:30 +0000360 user_options.insert(user_options.begin(),
Julio Merino28774852016-09-14 16:59:46 +0000361 globals->options->host_jvm_args.begin(),
362 globals->options->host_jvm_args.end());
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000363
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100364 // Add JVM arguments particular to building blaze64 and particular JVM
365 // versions.
366 string error;
367 blaze_exit_code::ExitCode jvm_args_exit_code =
Julio Merino28774852016-09-14 16:59:46 +0000368 globals->options->AddJVMArguments(globals->options->GetHostJavabase(),
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000369 &result, user_options, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100370 if (jvm_args_exit_code != blaze_exit_code::SUCCESS) {
371 die(jvm_args_exit_code, "%s", error.c_str());
372 }
373
374 // We put all directories on the java.library.path that contain .so files.
375 string java_library_path = "-Djava.library.path=";
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000376 string real_install_dir =
377 GetEmbeddedBinariesRoot(globals->options->install_base);
378
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100379 bool first = true;
380 for (const auto& it : globals->extracted_binaries) {
Thiago Farina01f36002015-04-08 15:59:08 +0000381 if (IsSharedLibrary(it)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100382 if (!first) {
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000383 java_library_path += blaze::ListSeparator();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100384 }
385 first = false;
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000386 java_library_path += blaze::ConvertPath(
387 blaze_util::JoinPath(real_install_dir, blaze_util::Dirname(it)));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100388 }
389 }
390 result.push_back(java_library_path);
391
392 // Force use of latin1 for file names.
393 result.push_back("-Dfile.encoding=ISO-8859-1");
394
Julio Merino28774852016-09-14 16:59:46 +0000395 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100396 fprintf(stderr,
397 "Running host JVM under debugger (listening on TCP port 5005).\n");
398 // Start JVM so that it listens for a connection from a
399 // JDWP-compliant debugger:
400 result.push_back("-Xdebug");
401 result.push_back("-Xrunjdwp:transport=dt_socket,server=y,address=5005");
402 }
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000403 result.insert(result.end(), user_options.begin(), user_options.end());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100404
Julio Merino28774852016-09-14 16:59:46 +0000405 globals->options->AddJVMArgumentSuffix(real_install_dir,
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000406 globals->extracted_binaries[0],
407 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100408
Lukacs Berki3d486832016-10-26 12:51:38 +0000409 // JVM arguments are complete. Now pass in Blaze startup options.
410 // Note that we always use the --flag=ARG form (instead of the --flag ARG one)
411 // so that BlazeRuntime#splitStartupOptions has an easy job.
Lukacs Berki71675a52016-11-08 09:48:27 +0000412
413 // TODO(lberki): Test that whatever the list constructed after this line is
414 // actually a list of parseable startup options.
Julio Merino28774852016-09-14 16:59:46 +0000415 if (!globals->options->batch) {
Lukacs Berki3d486832016-10-26 12:51:38 +0000416 result.push_back("--max_idle_secs=" +
417 ToString(globals->options->max_idle_secs));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100418 } else {
Googlerc8c64e72015-03-23 23:22:18 +0000419 // --batch must come first in the arguments to Java main() because
420 // the code expects it to be at args[0] if it's been set.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100421 result.push_back("--batch");
422 }
Lukacs Berkice1445f2016-04-19 15:52:55 +0000423
Julio Merino28774852016-09-14 16:59:46 +0000424 if (globals->options->command_port != 0) {
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000425 result.push_back(
Julio Merino28774852016-09-14 16:59:46 +0000426 "--command_port=" + ToString(globals->options->command_port));
Lukacs Berkice1445f2016-04-19 15:52:55 +0000427 }
428
Lukacs Berki71675a52016-11-08 09:48:27 +0000429 result.push_back(
430 "--connect_timeout_secs=" +
431 ToString(globals->options->connect_timeout_secs));
432
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000433 result.push_back("--install_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000434 blaze::ConvertPath(globals->options->install_base));
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000435 result.push_back("--install_md5=" + globals->install_md5);
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000436 result.push_back("--output_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000437 blaze::ConvertPath(globals->options->output_base));
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000438 result.push_back("--workspace_directory=" +
439 blaze::ConvertPath(globals->workspace));
Marian Lobur6dcdd602015-04-09 09:28:40 +0000440
Julio Merino28774852016-09-14 16:59:46 +0000441 if (globals->options->allow_configurable_attributes) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100442 result.push_back("--allow_configurable_attributes");
443 }
Julio Merino28774852016-09-14 16:59:46 +0000444 if (globals->options->deep_execroot) {
Lukacs Berki5fb98d12015-12-09 15:29:46 +0000445 result.push_back("--deep_execroot");
446 } else {
447 result.push_back("--nodeep_execroot");
448 }
Julio Merino28774852016-09-14 16:59:46 +0000449 if (globals->options->oom_more_eagerly) {
Janak Ramakrishnanadc706f2016-03-07 19:12:48 +0000450 result.push_back("--experimental_oom_more_eagerly");
451 }
Janak Ramakrishnan19fde1f2016-05-23 21:20:16 +0000452 result.push_back("--experimental_oom_more_eagerly_threshold=" +
Julio Merino28774852016-09-14 16:59:46 +0000453 ToString(globals->options->oom_more_eagerly_threshold));
Janak Ramakrishnan8cc772e2016-03-23 17:26:12 +0000454
Michajlo Matijkiwaf79a322016-09-16 15:44:35 +0000455 if (!globals->options->write_command_log) {
456 result.push_back("--nowrite_command_log");
457 }
458
Julio Merino28774852016-09-14 16:59:46 +0000459 if (globals->options->watchfs) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100460 result.push_back("--watchfs");
461 }
Julio Merino28774852016-09-14 16:59:46 +0000462 if (globals->options->fatal_event_bus_exceptions) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100463 result.push_back("--fatal_event_bus_exceptions");
464 } else {
465 result.push_back("--nofatal_event_bus_exceptions");
466 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100467
Lukacs Berki71675a52016-11-08 09:48:27 +0000468 // We use this syntax so that the logic in ServerNeedsToBeKilled() that
469 // decides whether the server needs killing is simpler. This is parsed by the
470 // Java code where --noclient_debug and --client_debug=false are equivalent.
471 // Note that --client_debug false (separated by space) won't work either,
472 // because the logic in ServerNeedsToBeKilled() assumes that every argument
473 // is in the --arg=value form.
474 if (globals->options->client_debug) {
475 result.push_back("--client_debug=true");
476 } else {
477 result.push_back("--client_debug=false");
478 }
Chloe Calvarineaa3be72016-12-13 19:48:34 +0000479 if (globals->options->use_custom_exit_code_on_abrupt_exit) {
480 result.push_back("--use_custom_exit_code_on_abrupt_exit=true");
481 } else {
482 result.push_back("--use_custom_exit_code_on_abrupt_exit=false");
483 }
Lukacs Berki71675a52016-11-08 09:48:27 +0000484
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100485 // This is only for Blaze reporting purposes; the real interpretation of the
486 // jvm flags occurs when we set up the java command line.
Julio Merino28774852016-09-14 16:59:46 +0000487 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100488 result.push_back("--host_jvm_debug");
489 }
Julio Merino28774852016-09-14 16:59:46 +0000490 if (!globals->options->host_jvm_profile.empty()) {
491 result.push_back("--host_jvm_profile=" +
492 globals->options->host_jvm_profile);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100493 }
Julio Merino28774852016-09-14 16:59:46 +0000494 if (!globals->options->host_jvm_args.empty()) {
495 for (const auto &arg : globals->options->host_jvm_args) {
Janak Ramakrishnan533657e2015-11-13 23:34:14 +0000496 result.push_back("--host_jvm_args=" + arg);
497 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100498 }
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000499
Julio Merino28774852016-09-14 16:59:46 +0000500 if (globals->options->invocation_policy != NULL &&
501 strlen(globals->options->invocation_policy) > 0) {
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000502 result.push_back(string("--invocation_policy=") +
Julio Merino28774852016-09-14 16:59:46 +0000503 globals->options->invocation_policy);
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000504 }
505
Julio Merino28774852016-09-14 16:59:46 +0000506 result.push_back("--product_name=" + globals->options->product_name);
Luis Fernando Pino Duque623cdf82016-05-31 16:21:46 +0000507
Julio Merino28774852016-09-14 16:59:46 +0000508 globals->options->AddExtraOptions(&result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100509
510 // The option sources are transmitted in the following format:
511 // --option_sources=option1:source1:option2:source2:...
512 string option_sources = "--option_sources=";
513 first = true;
Julio Merino28774852016-09-14 16:59:46 +0000514 for (const auto& it : globals->options->option_sources) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100515 if (!first) {
516 option_sources += ":";
517 }
518
519 first = false;
520 option_sources += EscapeForOptionSource(it.first) + ":" +
521 EscapeForOptionSource(it.second);
522 }
523
524 result.push_back(option_sources);
525 return result;
526}
527
Thiago Farina5735c252016-04-27 16:16:27 +0000528// Add common command options for logging to the given argument array.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100529static void AddLoggingArgs(vector<string>* args) {
Googler9588b812015-07-23 11:49:37 +0000530 args->push_back("--startup_time=" + ToString(globals->startup_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100531 if (globals->command_wait_time != 0) {
532 args->push_back("--command_wait_time=" +
Googler9588b812015-07-23 11:49:37 +0000533 ToString(globals->command_wait_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100534 }
535 if (globals->extract_data_time != 0) {
536 args->push_back("--extract_data_time=" +
Googler9588b812015-07-23 11:49:37 +0000537 ToString(globals->extract_data_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100538 }
539 if (globals->restart_reason != NO_RESTART) {
540 const char *reasons[] = {
541 "no_restart", "no_daemon", "new_version", "new_options"
542 };
543 args->push_back(
544 string("--restart_reason=") + reasons[globals->restart_reason]);
545 }
546 args->push_back(
547 string("--binary_path=") + globals->binary_path);
548}
549
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100550// Join the elements of the specified array with NUL's (\0's), akin to the
551// format of /proc/$PID/cmdline.
Thiago Farina0b6963e2015-04-28 20:26:45 +0000552static string GetArgumentString(const vector<string>& argument_array) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100553 string result;
554 blaze_util::JoinStrings(argument_array, '\0', &result);
555 return result;
556}
557
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100558// Do a chdir into the workspace, and die if it fails.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000559static void GoToWorkspace(const WorkspaceLayout* workspace_layout) {
560 if (workspace_layout->InWorkspace(globals->workspace) &&
Laszlo Csomor9c951962016-11-10 13:31:27 +0000561 !blaze_util::ChangeDirectory(globals->workspace)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100562 pdie(blaze_exit_code::INTERNAL_ERROR,
Laszlo Csomor9c951962016-11-10 13:31:27 +0000563 "changing directory into %s failed", globals->workspace.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100564 }
565}
566
567// Check the java version if a java version specification is bundled. On
Thiago Farina5735c252016-04-27 16:16:27 +0000568// success, returns the executable path of the java command.
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000569static void VerifyJavaVersionAndSetJvm() {
Julio Merino28774852016-09-14 16:59:46 +0000570 string exe = globals->options->GetJvm();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100571
572 string version_spec_file = blaze_util::JoinPath(
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000573 GetEmbeddedBinariesRoot(globals->options->install_base), "java.version");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100574 string version_spec = "";
Laszlo Csomor49970e02016-11-28 08:55:47 +0000575 if (blaze_util::ReadFile(version_spec_file, &version_spec)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100576 blaze_util::StripWhitespace(&version_spec);
577 // A version specification is given, get version of java.
578 string jvm_version = GetJvmVersion(exe);
579
580 // Compare that jvm_version is found and at least the one specified.
581 if (jvm_version.size() == 0) {
582 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
583 "Java version not detected while at least %s is needed.\n"
584 "Please set JAVA_HOME.", version_spec.c_str());
585 } else if (!CheckJavaVersionIsAtLeast(jvm_version, version_spec)) {
586 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
587 "Java version is %s while at least %s is needed.\n"
588 "Please set JAVA_HOME.",
589 jvm_version.c_str(), version_spec.c_str());
590 }
591 }
592
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000593 globals->jvm_path = exe;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100594}
595
596// Starts the Blaze server. Returns a readable fd connected to the server.
597// This is currently used only to detect liveness.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000598static void StartServer(const WorkspaceLayout* workspace_layout,
599 BlazeServerStartup** server_startup) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100600 vector<string> jvm_args_vector = GetArgumentArray();
601 string argument_string = GetArgumentString(jvm_args_vector);
Laszlo Csomor760f7862016-12-19 15:46:47 +0000602 string server_dir =
603 blaze_util::JoinPath(globals->options->output_base, "server");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100604 // Write the cmdline argument string to the server dir. If we get to this
605 // point, there is no server running, so we don't overwrite the cmdline file
606 // for the existing server. If might be that the server dies and the cmdline
607 // file stays there, but that is not a problem, since we always check the
608 // server, too.
Laszlo Csomor760f7862016-12-19 15:46:47 +0000609 blaze_util::WriteFile(argument_string,
610 blaze_util::JoinPath(server_dir, "cmdline"));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100611
612 // unless we restarted for a new-version, mark this as initial start
613 if (globals->restart_reason == NO_RESTART) {
614 globals->restart_reason = NO_DAEMON;
615 }
616
Julio Merino28774852016-09-14 16:59:46 +0000617 string exe = globals->options->GetExe(globals->jvm_path,
618 globals->extracted_binaries[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100619 // Go to the workspace before we daemonize, so
620 // we can still print errors to the terminal.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000621 GoToWorkspace(workspace_layout);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100622
Laszlo Csomor49970e02016-11-28 08:55:47 +0000623 ExecuteDaemon(exe, jvm_args_vector, globals->jvm_log_file, server_dir,
624 server_startup);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100625}
626
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100627// Replace this process with blaze in standalone/batch mode.
628// The batch mode blaze process handles the command and exits.
629//
630// This function passes the commands array to the blaze process.
631// This array should start with a command ("build", "info", etc.).
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000632static void StartStandalone(const WorkspaceLayout* workspace_layout,
633 BlazeServer* server) {
Lukacs Berki1977d922016-05-02 09:31:37 +0000634 if (server->Connected()) {
635 server->KillRunningServer();
636 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100637
638 // Wall clock time since process startup.
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000639 globals->startup_time = GetMillisecondsSinceProcessStart();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100640
641 if (VerboseLogging()) {
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000642 fprintf(stderr, "Starting %s in batch mode.\n",
Julio Merino28774852016-09-14 16:59:46 +0000643 globals->options->product_name.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100644 }
Julio Merino28774852016-09-14 16:59:46 +0000645 string command = globals->option_processor->GetCommand();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100646 vector<string> command_arguments;
Julio Merino28774852016-09-14 16:59:46 +0000647 globals->option_processor->GetCommandArguments(&command_arguments);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100648
649 if (!command_arguments.empty() && command == "shutdown") {
Julio Merino28774852016-09-14 16:59:46 +0000650 string product = globals->options->product_name;
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000651 blaze_util::ToLower(&product);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100652 fprintf(stderr,
653 "WARNING: Running command \"shutdown\" in batch mode. Batch mode "
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000654 "is triggered\nwhen not running %s within a workspace. If you "
655 "intend to shutdown an\nexisting %s server, run \"%s "
656 "shutdown\" from the directory where\nit was started.\n",
Julio Merino28774852016-09-14 16:59:46 +0000657 globals->options->product_name.c_str(),
658 globals->options->product_name.c_str(), product.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100659 }
660 vector<string> jvm_args_vector = GetArgumentArray();
661 if (command != "") {
662 jvm_args_vector.push_back(command);
663 AddLoggingArgs(&jvm_args_vector);
664 }
665
666 jvm_args_vector.insert(jvm_args_vector.end(),
667 command_arguments.begin(),
668 command_arguments.end());
669
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000670 GoToWorkspace(workspace_layout);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100671
Julio Merino28774852016-09-14 16:59:46 +0000672 string exe = globals->options->GetExe(globals->jvm_path,
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000673 globals->extracted_binaries[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100674 ExecuteProgram(exe, jvm_args_vector);
675 pdie(blaze_exit_code::INTERNAL_ERROR, "execv of '%s' failed", exe.c_str());
676}
677
Laszlo Csomorae16e762016-11-18 10:16:08 +0000678static void WriteFileToStderrOrDie(const char *file_name) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100679 FILE *fp = fopen(file_name, "r");
680 if (fp == NULL) {
681 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
682 "opening %s failed", file_name);
683 }
684 char buffer[255];
685 int num_read;
686 while ((num_read = fread(buffer, 1, sizeof buffer, fp)) > 0) {
687 if (ferror(fp)) {
688 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
689 "failed to read from '%s'", file_name);
690 }
Laszlo Csomorae16e762016-11-18 10:16:08 +0000691 fwrite(buffer, 1, num_read, stderr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100692 }
693 fclose(fp);
694}
695
Lukacs Berki4912f7f2016-06-17 16:12:22 +0000696// After connecting to the Blaze server, return its PID, or -1 if there was an
697// error.
Lukacs Berkid9da60f2016-04-26 11:40:24 +0000698static int GetServerPid(const string &server_dir) {
Lukacs Berki907dbbf2016-04-15 11:30:12 +0000699 // Note: there is no race here on startup since the server creates
700 // the pid file strictly before it binds the socket.
Thiago Farina048bbfc2016-09-21 08:20:41 +0000701 string pid_file = blaze_util::JoinPath(server_dir, kServerPidFile);
Laszlo Csomorae16e762016-11-18 10:16:08 +0000702 string bufstr;
Lukacs Berkiea4c42e2016-04-25 07:22:11 +0000703 int result;
Laszlo Csomor49970e02016-11-28 08:55:47 +0000704 if (!blaze_util::ReadFile(pid_file, &bufstr, 32) ||
Laszlo Csomor6450c182016-11-24 10:28:20 +0000705 !blaze_util::safe_strto32(bufstr, &result)) {
Lukacs Berkiea4c42e2016-04-25 07:22:11 +0000706 return -1;
707 }
708
709 return result;
Doug Rabsond655f2a2015-08-13 14:41:50 +0000710}
711
Lukacs Berki1977d922016-05-02 09:31:37 +0000712// Starts up a new server and connects to it. Exits if it didn't work not.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000713static void StartServerAndConnect(const WorkspaceLayout* workspace_layout,
714 BlazeServer *server) {
Laszlo Csomor760f7862016-12-19 15:46:47 +0000715 string server_dir =
716 blaze_util::JoinPath(globals->options->output_base, "server");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100717
718 // The server dir has the socket, so we don't allow access by other
719 // users.
Thiago Farina227369a2016-12-07 12:40:40 +0000720 if (!blaze_util::MakeDirectories(server_dir, 0700)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100721 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
722 "server directory '%s' could not be created", server_dir.c_str());
723 }
724
Laszlo Csomor6450c182016-11-24 10:28:20 +0000725 // TODO(laszlocsomor) 2016-11-21: remove `pid_symlink` and the `remove` call
726 // after 2017-05-01 (~half a year from writing this comment). By that time old
727 // Bazel clients that used to write PID symlinks will probably no longer be in
728 // use.
729 // Until then, defensively delete old PID symlinks that older clients may have
730 // left behind.
731 string pid_symlink = blaze_util::JoinPath(server_dir, kServerPidSymlink);
732 remove(pid_symlink.c_str());
733
Lukacs Berki1977d922016-05-02 09:31:37 +0000734 // If we couldn't connect to the server check if there is still a PID file
735 // and if so, kill the server that wrote it. This can happen e.g. if the
736 // server is in a GC pause and therefore cannot respond to ping requests and
737 // having two server instances running in the same output base is a
738 // disaster.
739 int server_pid = GetServerPid(server_dir);
740 if (server_pid > 0) {
Julio Merino28774852016-09-14 16:59:46 +0000741 if (VerifyServerProcess(server_pid, globals->options->output_base,
742 globals->options->install_base) &&
Lukacs Berkiee44c382016-09-14 10:53:37 +0000743 KillServerProcess(server_pid)) {
Lukacs Berki119dd4b2016-07-13 15:28:42 +0000744 fprintf(stderr, "Killed non-responsive server process (pid=%d)\n",
745 server_pid);
746 }
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000747 }
748
Julio Merino28774852016-09-14 16:59:46 +0000749 SetScheduling(globals->options->batch_cpu_scheduling,
750 globals->options->io_nice_level);
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000751
Lukacs Berki1977d922016-05-02 09:31:37 +0000752 BlazeServerStartup* server_startup;
Julio Merinoe3e3bfa2016-12-08 22:22:12 +0000753 StartServer(workspace_layout, &server_startup);
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000754
755 // Give the server two minutes to start up. That's enough to connect with a
756 // debugger.
757 auto try_until_time(
758 std::chrono::system_clock::now() + std::chrono::seconds(120));
759 bool had_to_wait = false;
760 while (std::chrono::system_clock::now() < try_until_time) {
761 auto next_attempt_time(
762 std::chrono::system_clock::now() + std::chrono::milliseconds(100));
Lukacs Berki1977d922016-05-02 09:31:37 +0000763 if (server->Connect()) {
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000764 if (had_to_wait && !globals->options->client_debug) {
Lukacs Berki1977d922016-05-02 09:31:37 +0000765 fputc('\n', stderr);
766 fflush(stderr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100767 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000768 delete server_startup;
769 return;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100770 }
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000771
772 had_to_wait = true;
Lukacs Berki71675a52016-11-08 09:48:27 +0000773 if (!globals->options->client_debug) {
774 fputc('.', stderr);
775 fflush(stderr);
776 }
777
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000778 std::this_thread::sleep_until(next_attempt_time);
Lukacs Berki1977d922016-05-02 09:31:37 +0000779 if (!server_startup->IsStillAlive()) {
780 fprintf(stderr, "\nunexpected pipe read status: %s\n"
781 "Server presumed dead. Now printing '%s':\n",
782 strerror(errno), globals->jvm_log_file.c_str());
Laszlo Csomorae16e762016-11-18 10:16:08 +0000783 WriteFileToStderrOrDie(globals->jvm_log_file.c_str());
Lukacs Berki1977d922016-05-02 09:31:37 +0000784 exit(blaze_exit_code::INTERNAL_ERROR);
785 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100786 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000787 die(blaze_exit_code::INTERNAL_ERROR,
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000788 "\nError: couldn't connect to server after 120 seconds.");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100789}
790
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000791// A devtools_ijar::ZipExtractorProcessor to extract the files from the blaze
792// zip.
793class ExtractBlazeZipProcessor : public devtools_ijar::ZipExtractorProcessor {
794 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000795 explicit ExtractBlazeZipProcessor(const string &embedded_binaries)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000796 : embedded_binaries_(embedded_binaries) {}
797
798 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
799 return !devtools_ijar::zipattr_is_dir(attr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100800 }
801
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000802 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
803 const devtools_ijar::u1 *data, const size_t size) {
804 string path = blaze_util::JoinPath(embedded_binaries_, filename);
Thiago Farina227369a2016-12-07 12:40:40 +0000805 if (!blaze_util::MakeDirectories(blaze_util::Dirname(path), 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100806 pdie(blaze_exit_code::INTERNAL_ERROR,
807 "couldn't create '%s'", path.c_str());
808 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100809
Laszlo Csomor49970e02016-11-28 08:55:47 +0000810 if (!blaze_util::WriteFile(data, size, path)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000811 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Laszlo Csomorae16e762016-11-18 10:16:08 +0000812 "\nFailed to write zipped file \"%s\": %s", path.c_str(),
813 strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100814 }
815 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000816
817 private:
818 const string embedded_binaries_;
819};
820
821// Actually extracts the embedded data files into the tree whose root
822// is 'embedded_binaries'.
823static void ActuallyExtractData(const string &argv0,
824 const string &embedded_binaries) {
825 ExtractBlazeZipProcessor processor(embedded_binaries);
Thiago Farina227369a2016-12-07 12:40:40 +0000826 if (!blaze_util::MakeDirectories(embedded_binaries, 0777)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000827 pdie(blaze_exit_code::INTERNAL_ERROR, "couldn't create '%s'",
828 embedded_binaries.c_str());
829 }
830
831 fprintf(stderr, "Extracting %s installation...\n",
Julio Merino28774852016-09-14 16:59:46 +0000832 globals->options->product_name.c_str());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000833 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
834 devtools_ijar::ZipExtractor::Create(argv0.c_str(), &processor));
835 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100836 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000837 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000838 globals->options->product_name.c_str(), errno, strerror(errno));
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000839 }
840 if (extractor->ProcessAll() < 0) {
841 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
842 "\nFailed to extract %s as a zip file: %s",
Julio Merino28774852016-09-14 16:59:46 +0000843 globals->options->product_name.c_str(), extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100844 }
845
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100846 // Set the timestamps of the extracted files to the future and make sure (or
847 // at least as sure as we can...) that the files we have written are actually
848 // on the disk.
849
850 vector<string> extracted_files;
Laszlo Csomor251bf032016-11-16 11:01:32 +0000851
852 // Walks the temporary directory recursively and collects full file paths.
853 blaze_util::GetAllFilesUnder(embedded_binaries, &extracted_files);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100854
Laszlo Csomorce1b3e12017-01-19 14:56:30 +0000855 std::unique_ptr<blaze_util::IFileMtime> mtime(blaze_util::CreateFileMtime());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100856 set<string> synced_directories;
Laszlo Csomor251bf032016-11-16 11:01:32 +0000857 for (const auto &it : extracted_files) {
858 const char *extracted_path = it.c_str();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100859
860 // Set the time to a distantly futuristic value so we can observe tampering.
Laszlo Csomorce1b3e12017-01-19 14:56:30 +0000861 // Note that keeping a static, deterministic timestamp, such as the default
862 // timestamp set by unzip (1970-01-01) and using that to detect tampering is
863 // not enough, because we also need the timestamp to change between Bazel
864 // releases so that the metadata cache knows that the files may have
865 // changed. This is essential for the correctness of actions that use
866 // embedded binaries as artifacts.
867 if (!mtime.get()->SetToDistantFuture(it)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100868 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
869 "failed to set timestamp on '%s'", extracted_path);
870 }
871
Laszlo Csomorae16e762016-11-18 10:16:08 +0000872 blaze_util::SyncFile(it);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100873
874 string directory = blaze_util::Dirname(extracted_path);
875
876 // Now walk up until embedded_binaries and sync every directory in between.
877 // synced_directories is used to avoid syncing the same directory twice.
Laszlo Csomor760f7862016-12-19 15:46:47 +0000878 // The !directory.empty() and !blaze_util::IsRootDirectory(directory)
879 // conditions are not strictly needed, but it makes this loop more robust,
880 // because otherwise, if due to some glitch, directory was not under
881 // embedded_binaries, it would get into an infinite loop.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100882 while (directory != embedded_binaries &&
Laszlo Csomor760f7862016-12-19 15:46:47 +0000883 synced_directories.count(directory) == 0 && !directory.empty() &&
884 !blaze_util::IsRootDirectory(directory)) {
Laszlo Csomorae16e762016-11-18 10:16:08 +0000885 blaze_util::SyncFile(directory);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100886 synced_directories.insert(directory);
887 directory = blaze_util::Dirname(directory);
888 }
889 }
890
Laszlo Csomorae16e762016-11-18 10:16:08 +0000891 blaze_util::SyncFile(embedded_binaries);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100892}
893
894// Installs Blaze by extracting the embedded data files, iff necessary.
895// The MD5-named install_base directory on disk is trusted; we assume
896// no-one has modified the extracted files beneath this directory once
897// it is in place. Concurrency during extraction is handled by
898// extracting in a tmp dir and then renaming it into place where it
899// becomes visible automically at the new path.
900// Populates globals->extracted_binaries with their extracted locations.
901static void ExtractData(const string &self_path) {
902 // If the install dir doesn't exist, create it, if it does, we know it's good.
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000903 if (!blaze_util::PathExists(globals->options->install_base)) {
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000904 uint64_t st = GetMillisecondsMonotonic();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100905 // Work in a temp dir to avoid races.
Julio Merino28774852016-09-14 16:59:46 +0000906 string tmp_install = globals->options->install_base + ".tmp." +
Laszlo Csomorae16e762016-11-18 10:16:08 +0000907 blaze::GetProcessIdAsString();
Laszlo Csomor760f7862016-12-19 15:46:47 +0000908 string tmp_binaries =
909 blaze_util::JoinPath(tmp_install, "_embedded_binaries");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100910 ActuallyExtractData(self_path, tmp_binaries);
911
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000912 uint64_t et = GetMillisecondsMonotonic();
913 globals->extract_data_time = et - st;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100914
915 // Now rename the completed installation to its final name. If this
916 // fails due to an ENOTEMPTY then we assume another good
917 // installation snuck in before us.
Laszlo Csomor49970e02016-11-28 08:55:47 +0000918 if (rename(tmp_install.c_str(), globals->options->install_base.c_str()) ==
919 -1 &&
920 errno != ENOTEMPTY) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100921 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
922 "install base directory '%s' could not be renamed into place",
923 tmp_install.c_str());
924 }
925 } else {
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000926 if (!blaze_util::IsDirectory(globals->options->install_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100927 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
928 "Error: Install base directory '%s' could not be created. "
929 "It exists but is not a directory.",
Julio Merino28774852016-09-14 16:59:46 +0000930 globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100931 }
932
Laszlo Csomorce1b3e12017-01-19 14:56:30 +0000933 std::unique_ptr<blaze_util::IFileMtime> mtime(
934 blaze_util::CreateFileMtime());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100935 string real_install_dir = blaze_util::JoinPath(
Julio Merino28774852016-09-14 16:59:46 +0000936 globals->options->install_base,
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100937 "_embedded_binaries");
938 for (const auto& it : globals->extracted_binaries) {
939 string path = blaze_util::JoinPath(real_install_dir, it);
940 // Check that the file exists and is readable.
Laszlo Csomor00549b42017-01-11 09:12:10 +0000941 if (blaze_util::IsDirectory(path)) {
942 continue;
943 }
944 if (!blaze_util::CanReadFile(path)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100945 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
946 "Error: corrupt installation: file '%s' missing."
947 " Please remove '%s' and try again.",
Julio Merino28774852016-09-14 16:59:46 +0000948 path.c_str(), globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100949 }
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000950 // Check that the timestamp is in the future. A past timestamp would
951 // indicate that the file has been tampered with.
952 // See ActuallyExtractData().
Laszlo Csomorce1b3e12017-01-19 14:56:30 +0000953 bool is_in_future = false;
954 if (!mtime.get()->GetIfInDistantFuture(path, &is_in_future)) {
Laszlo Csomor00549b42017-01-11 09:12:10 +0000955 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
956 "Error: could not retrieve mtime of file '%s'. "
957 "Please remove '%s' and try again.",
958 path.c_str(), globals->options->install_base.c_str());
Laszlo Csomorce1b3e12017-01-19 14:56:30 +0000959 }
960 if (!is_in_future) {
Laszlo Csomor00549b42017-01-11 09:12:10 +0000961 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
962 "Error: corrupt installation: file '%s' "
963 "modified. Please remove '%s' and try again.",
964 path.c_str(), globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100965 }
966 }
967 }
968}
969
Lukacs Berki71675a52016-11-08 09:48:27 +0000970const char *volatile_startup_options[] = {
971 "--option_sources=",
972 "--max_idle_secs=",
973 "--connect_timeout_secs=",
974 "--client_debug=",
975 NULL,
976};
977
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100978// Returns true if the server needs to be restarted to accommodate changes
979// between the two argument lists.
980static bool ServerNeedsToBeKilled(const vector<string>& args1,
981 const vector<string>& args2) {
982 // We need not worry about one side missing an argument and the other side
983 // having the default value, since this command line is already the
984 // canonicalized one that always contains every switch (with default values
985 // if it was not present on the real command line). Same applies for argument
986 // ordering.
987 if (args1.size() != args2.size()) {
988 return true;
989 }
990
991 for (int i = 0; i < args1.size(); i++) {
Lukacs Berki71675a52016-11-08 09:48:27 +0000992 bool option_volatile = false;
993 for (const char** candidate = volatile_startup_options;
994 *candidate != NULL;
995 candidate++) {
996 string candidate_string(*candidate);
997 if (args1[i].substr(0, candidate_string.size()) == candidate_string &&
998 args2[i].substr(0, candidate_string.size()) == candidate_string) {
999 option_volatile = true;
1000 break;
1001 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001002 }
1003
Lukacs Berki71675a52016-11-08 09:48:27 +00001004 if (!option_volatile && args1[i] != args2[i]) {
Lukacs Berki3d486832016-10-26 12:51:38 +00001005 return true;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001006 }
1007 }
1008
1009 return false;
1010}
1011
1012// Kills the running Blaze server, if any, if the startup options do not match.
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001013static void KillRunningServerIfDifferentStartupOptions(BlazeServer* server) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001014 if (!server->Connected()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001015 return;
1016 }
1017
Laszlo Csomor760f7862016-12-19 15:46:47 +00001018 string cmdline_path =
1019 blaze_util::JoinPath(globals->options->output_base, "server/cmdline");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001020 string joined_arguments;
1021
1022 // No, /proc/$PID/cmdline does not work, because it is limited to 4K. Even
1023 // worse, its behavior differs slightly between kernels (in some, when longer
1024 // command lines are truncated, the last 4 bytes are replaced with
1025 // "..." + NUL.
Laszlo Csomor49970e02016-11-28 08:55:47 +00001026 blaze_util::ReadFile(cmdline_path, &joined_arguments);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001027 vector<string> arguments = blaze_util::Split(joined_arguments, '\0');
1028
1029 // These strings contain null-separated command line arguments. If they are
1030 // the same, the server can stay alive, otherwise, it needs shuffle off this
1031 // mortal coil.
1032 if (ServerNeedsToBeKilled(arguments, GetArgumentArray())) {
1033 globals->restart_reason = NEW_OPTIONS;
1034 fprintf(stderr,
Kristina Chodorow11d40d22015-03-17 18:26:59 +00001035 "WARNING: Running %s server needs to be killed, because the "
1036 "startup options are different.\n",
Julio Merino28774852016-09-14 16:59:46 +00001037 globals->options->product_name.c_str());
Lukacs Berki1977d922016-05-02 09:31:37 +00001038 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001039 }
1040}
1041
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001042// Kills the old running server if it is not the same version as us,
1043// dealing with various combinations of installation scheme
1044// (installation symlink and older MD5_MANIFEST contents).
1045// This function requires that the installation be complete, and the
1046// server lock acquired.
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001047static void EnsureCorrectRunningVersion(BlazeServer* server) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001048 // Read the previous installation's semaphore symlink in output_base. If the
1049 // target dirs don't match, or if the symlink was not present, then kill any
1050 // running servers. Lastly, symlink to our installation so others know which
1051 // installation is running.
Laszlo Csomor760f7862016-12-19 15:46:47 +00001052 string installation_path =
1053 blaze_util::JoinPath(globals->options->output_base, "install");
Lukacs Berki497d8242016-04-28 07:21:26 +00001054 string prev_installation;
Laszlo Csomor49970e02016-11-28 08:55:47 +00001055 bool ok = ReadDirectorySymlink(installation_path, &prev_installation);
Lukacs Berki497d8242016-04-28 07:21:26 +00001056 if (!ok || !CompareAbsolutePaths(
Julio Merino28774852016-09-14 16:59:46 +00001057 prev_installation, globals->options->install_base)) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001058 if (server->Connected()) {
1059 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001060 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001061
1062 globals->restart_reason = NEW_VERSION;
Laszlo Csomor49970e02016-11-28 08:55:47 +00001063 blaze_util::UnlinkPath(installation_path);
1064 if (!SymlinkDirectories(globals->options->install_base,
1065 installation_path)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001066 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1067 "failed to create installation symlink '%s'",
1068 installation_path.c_str());
1069 }
Lukacs Berkib762afd2017-01-17 10:41:52 +00001070
1071 // Update the mtime of the install base so that cleanup tools can
1072 // find install bases that haven't been used for a long time
Laszlo Csomorce1b3e12017-01-19 14:56:30 +00001073 std::unique_ptr<blaze_util::IFileMtime> mtime(
1074 blaze_util::CreateFileMtime());
1075 if (!mtime.get()->SetToNow(globals->options->install_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001076 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1077 "failed to set timestamp on '%s'",
Julio Merino28774852016-09-14 16:59:46 +00001078 globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001079 }
1080 }
1081}
1082
Laszlo Csomor32086b22016-11-24 15:23:55 +00001083static void CancelServer() {
1084 blaze_server->Cancel();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001085}
1086
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001087// Performs all I/O for a single client request to the server, and
1088// shuts down the client (by exit or signal).
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001089static ATTRIBUTE_NORETURN void SendServerRequest(
1090 const WorkspaceLayout* workspace_layout, BlazeServer* server) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001091 while (true) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001092 if (!server->Connected()) {
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001093 StartServerAndConnect(workspace_layout, server);
Lukacs Berki1977d922016-05-02 09:31:37 +00001094 }
1095
Lukacs Berki4de98942016-09-09 09:23:36 +00001096 // Check for the case when the workspace directory deleted and then gets
1097 // recreated while the server is running
1098
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001099 string server_cwd = GetProcessCWD(globals->server_pid);
Lukacs Berki4be230a2015-10-15 13:43:03 +00001100 // If server_cwd is empty, GetProcessCWD failed. This notably occurs when
1101 // running under Docker because then readlink(/proc/[pid]/cwd) returns
1102 // EPERM.
1103 // Docker issue #6687 (https://github.com/docker/docker/issues/6687) fixed
1104 // this, but one still needs the --cap-add SYS_PTRACE command line flag, at
1105 // least according to the discussion on Docker issue #6800
1106 // (https://github.com/docker/docker/issues/6687), and even then, it's a
1107 // non-default Docker flag. Given that this occurs only in very weird
1108 // cases, it's better to assume that everything is alright if we can't get
1109 // the cwd.
1110
1111 if (!server_cwd.empty() &&
1112 (server_cwd != globals->workspace || // changed
1113 server_cwd.find(" (deleted)") != string::npos)) { // deleted.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001114 // There's a distant possibility that the two paths look the same yet are
1115 // actually different because the two processes have different mount
1116 // tables.
1117 if (VerboseLogging()) {
1118 fprintf(stderr, "Server's cwd moved or deleted (%s).\n",
1119 server_cwd.c_str());
1120 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001121 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001122 } else {
1123 break;
1124 }
1125 }
1126
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001127 if (VerboseLogging()) {
1128 fprintf(stderr, "Connected (server pid=%d).\n", globals->server_pid);
1129 }
1130
1131 // Wall clock time since process startup.
Laszlo Csomor943d3cf2016-11-07 14:27:21 +00001132 globals->startup_time = GetMillisecondsSinceProcessStart();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001133
Laszlo Csomor32086b22016-11-24 15:23:55 +00001134 SignalHandler::Get().Install(globals, CancelServer);
1135 SignalHandler::Get().PropagateSignalOrExit(server->Communicate());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001136}
1137
1138// Parse the options, storing parsed values in globals.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001139static void ParseOptions(int argc, const char *argv[]) {
1140 string error;
1141 blaze_exit_code::ExitCode parse_exit_code =
Julio Merino28774852016-09-14 16:59:46 +00001142 globals->option_processor->ParseOptions(argc, argv, globals->workspace,
1143 globals->cwd, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001144 if (parse_exit_code != blaze_exit_code::SUCCESS) {
1145 die(parse_exit_code, "%s", error.c_str());
1146 }
Julio Merino28774852016-09-14 16:59:46 +00001147 globals->options = globals->option_processor->GetParsedStartupOptions();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001148}
1149
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001150// Compute the globals globals->cwd and globals->workspace.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001151static void ComputeWorkspace(const WorkspaceLayout* workspace_layout) {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001152 globals->cwd = blaze_util::MakeCanonical(blaze_util::GetCwd().c_str());
1153 if (globals->cwd.empty()) {
1154 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1155 "blaze_util::MakeCanonical('%s') failed",
1156 blaze_util::GetCwd().c_str());
1157 }
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001158 globals->workspace = workspace_layout->GetWorkspace(globals->cwd);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001159}
1160
1161// Figure out the base directories based on embedded data, username, cwd, etc.
Julio Merino28774852016-09-14 16:59:46 +00001162// Sets globals->options->install_base, globals->options->output_base,
Thiago Farina6fd9bf12016-04-26 09:02:18 +00001163// globals->lockfile, globals->jvm_log_file.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001164static void ComputeBaseDirectories(const WorkspaceLayout* workspace_layout,
1165 const string &self_path) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001166 // Only start a server when in a workspace because otherwise we won't do more
1167 // than emit a help message.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001168 if (!workspace_layout->InWorkspace(globals->workspace)) {
Julio Merino28774852016-09-14 16:59:46 +00001169 globals->options->batch = true;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001170 }
1171
1172 // The default install_base is <output_user_root>/install/<md5(blaze)>
1173 // but if an install_base is specified on the command line, we use that as
1174 // the base instead.
Julio Merino28774852016-09-14 16:59:46 +00001175 if (globals->options->install_base.empty()) {
Laszlo Csomor760f7862016-12-19 15:46:47 +00001176 string install_user_root =
1177 blaze_util::JoinPath(globals->options->output_user_root, "install");
Julio Merino28774852016-09-14 16:59:46 +00001178 globals->options->install_base =
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001179 GetInstallBase(install_user_root, self_path);
1180 } else {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +00001181 // We call GetInstallBase anyway to populate extracted_binaries and
1182 // install_md5.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001183 GetInstallBase("", self_path);
1184 }
1185
Julio Merino28774852016-09-14 16:59:46 +00001186 if (globals->options->output_base.empty()) {
Laszlo Csomor6bf95762016-11-16 13:29:22 +00001187 globals->options->output_base = blaze::GetHashedBaseDir(
Julio Merino28774852016-09-14 16:59:46 +00001188 globals->options->output_user_root, globals->workspace);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001189 }
1190
Julio Merino28774852016-09-14 16:59:46 +00001191 const char *output_base = globals->options->output_base.c_str();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001192 if (!blaze_util::PathExists(globals->options->output_base)) {
Thiago Farina227369a2016-12-07 12:40:40 +00001193 if (!blaze_util::MakeDirectories(globals->options->output_base, 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001194 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1195 "Output base directory '%s' could not be created",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001196 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001197 }
1198 } else {
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001199 if (!blaze_util::IsDirectory(globals->options->output_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001200 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1201 "Error: Output base directory '%s' could not be created. "
1202 "It exists but is not a directory.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001203 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001204 }
1205 }
Laszlo Csomor00549b42017-01-11 09:12:10 +00001206 if (!blaze_util::CanAccessDirectory(globals->options->output_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001207 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1208 "Error: Output base directory '%s' must be readable and writable.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001209 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001210 }
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001211 ExcludePathFromBackup(output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001212
Laszlo Csomorc3545392016-11-24 13:33:28 +00001213 globals->options->output_base = blaze_util::MakeCanonical(output_base);
1214 if (globals->options->output_base.empty()) {
1215 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1216 "blaze_util::MakeCanonical('%s') failed", output_base);
1217 }
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001218
Laszlo Csomor760f7862016-12-19 15:46:47 +00001219 globals->lockfile =
1220 blaze_util::JoinPath(globals->options->output_base, "lock");
1221 globals->jvm_log_file =
1222 blaze_util::JoinPath(globals->options->output_base, "server/jvm.out");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001223}
1224
1225static void CheckEnvironment() {
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001226 if (!blaze::GetEnv("http_proxy").empty()) {
Lukacs Berki86a28b02016-10-25 10:34:45 +00001227 fprintf(stderr, "Warning: ignoring http_proxy in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001228 blaze::UnsetEnv("http_proxy");
Lukacs Berki86a28b02016-10-25 10:34:45 +00001229 }
1230
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001231 if (!blaze::GetEnv("LD_ASSUME_KERNEL").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001232 // Fix for bug: if ulimit -s and LD_ASSUME_KERNEL are both
1233 // specified, the JVM fails to create threads. See thread_stack_regtest.
1234 // This is also provoked by LD_LIBRARY_PATH=/usr/lib/debug,
1235 // or anything else that causes the JVM to use LinuxThreads.
1236 fprintf(stderr, "Warning: ignoring LD_ASSUME_KERNEL in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001237 blaze::UnsetEnv("LD_ASSUME_KERNEL");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001238 }
1239
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001240 if (!blaze::GetEnv("LD_PRELOAD").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001241 fprintf(stderr, "Warning: ignoring LD_PRELOAD in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001242 blaze::UnsetEnv("LD_PRELOAD");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001243 }
1244
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001245 if (!blaze::GetEnv("_JAVA_OPTIONS").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001246 // This would override --host_jvm_args
1247 fprintf(stderr, "Warning: ignoring _JAVA_OPTIONS in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001248 blaze::UnsetEnv("_JAVA_OPTIONS");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001249 }
1250
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001251 if (!blaze::GetEnv("TEST_TMPDIR").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001252 fprintf(stderr, "INFO: $TEST_TMPDIR defined: output root default is "
Julio Merino28774852016-09-14 16:59:46 +00001253 "'%s'.\n", globals->options->output_root.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001254 }
1255
1256 // TODO(bazel-team): We've also seen a failure during loading (creating
1257 // threads?) when ulimit -Hs 8192. Characterize that and check for it here.
1258
1259 // Make the JVM use ISO-8859-1 for parsing its command line because "blaze
1260 // run" doesn't handle non-ASCII command line arguments. This is apparently
1261 // the most reliable way to select the platform default encoding.
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001262 blaze::SetEnv("LANG", "en_US.ISO-8859-1");
1263 blaze::SetEnv("LANGUAGE", "en_US.ISO-8859-1");
1264 blaze::SetEnv("LC_ALL", "en_US.ISO-8859-1");
1265 blaze::SetEnv("LC_CTYPE", "en_US.ISO-8859-1");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001266}
1267
Laszlo Csomorc3545392016-11-24 13:33:28 +00001268static string CheckAndGetBinaryPath(const string& argv0) {
Laszlo Csomor760f7862016-12-19 15:46:47 +00001269 if (blaze_util::IsAbsolute(argv0)) {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001270 return argv0;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001271 } else {
Laszlo Csomor760f7862016-12-19 15:46:47 +00001272 string abs_path = blaze_util::JoinPath(globals->cwd, argv0);
Laszlo Csomorc3545392016-11-24 13:33:28 +00001273 string resolved_path = blaze_util::MakeCanonical(abs_path.c_str());
1274 if (!resolved_path.empty()) {
1275 return resolved_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001276 } else {
1277 // This happens during our integration tests, but thats okay, as we won't
1278 // log the invocation anyway.
Laszlo Csomorc3545392016-11-24 13:33:28 +00001279 return abs_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001280 }
1281 }
1282}
1283
Chloe Calvarineaa3be72016-12-13 19:48:34 +00001284int GetExitCodeForAbruptExit(const GlobalVariables &globals) {
1285 const StartupOptions *startup_options = globals.options;
1286 if (startup_options->use_custom_exit_code_on_abrupt_exit) {
1287 BAZEL_LOG(INFO) << "Looking for a custom exit-code.";
1288 std::string filename = blaze_util::JoinPath(
1289 globals.options->output_base, "exit_code_to_use_on_abrupt_exit");
1290 std::string content;
1291 if (!blaze_util::ReadFile(filename, &content)) {
1292 BAZEL_LOG(INFO) << "Unable to read the custom exit-code file. "
1293 << "Exiting with an INTERNAL_ERROR.";
1294 return blaze_exit_code::INTERNAL_ERROR;
1295 }
1296 if (!blaze_util::UnlinkPath(filename)) {
1297 BAZEL_LOG(INFO) << "Unable to delete the custom exit-code file. "
1298 << "Exiting with an INTERNAL_ERROR.";
1299 return blaze_exit_code::INTERNAL_ERROR;
1300 }
1301 int custom_exit_code;
1302 if (!blaze_util::safe_strto32(content, &custom_exit_code)) {
1303 BAZEL_LOG(INFO) << "Content of custom exit-code file not an int: "
1304 << content << "Exiting with an INTERNAL_ERROR.";
1305 return blaze_exit_code::INTERNAL_ERROR;
1306 }
1307 BAZEL_LOG(INFO) << "Read exit code " << custom_exit_code
1308 << " from custom exit-code file. Exiting accordingly.";
1309 return custom_exit_code;
1310 }
1311 return blaze_exit_code::INTERNAL_ERROR;
1312}
1313
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001314int Main(int argc, const char *argv[], WorkspaceLayout* workspace_layout,
1315 OptionProcessor *option_processor,
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001316 std::unique_ptr<blaze_util::LogHandler> log_handler) {
1317 // Logging must be set first to assure no log statements are missed.
1318 blaze_util::SetLogHandler(std::move(log_handler));
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001319
Thiago Farina676cb9f2016-10-06 11:00:43 +00001320 globals = new GlobalVariables(option_processor);
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001321 blaze::SetupStdStreams();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001322
1323 // Must be done before command line parsing.
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001324 ComputeWorkspace(workspace_layout);
Laszlo Csomorc3545392016-11-24 13:33:28 +00001325 globals->binary_path = CheckAndGetBinaryPath(argv[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001326 ParseOptions(argc, argv);
Lukacs Berkibb2230f2016-04-27 14:19:25 +00001327
Lukacs Berki71675a52016-11-08 09:48:27 +00001328 debug_log("Debug logging active");
1329
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001330 CheckEnvironment();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001331 blaze::CreateSecureOutputRoot(globals->options->output_user_root);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001332
1333 const string self_path = GetSelfPath();
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001334 ComputeBaseDirectories(workspace_layout, self_path);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001335
Lukacs Berki71675a52016-11-08 09:48:27 +00001336 blaze_server = static_cast<BlazeServer *>(new GrpcBlazeServer(
1337 globals->options->connect_timeout_secs));
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001338
Lukacs Berki415d39a2016-04-28 13:18:54 +00001339 globals->command_wait_time = blaze_server->AcquireLock();
Lukacs Berkice1445f2016-04-19 15:52:55 +00001340
Julio Merino28774852016-09-14 16:59:46 +00001341 WarnFilesystemType(globals->options->output_base);
Lukacs Berkice1445f2016-04-19 15:52:55 +00001342
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001343 ExtractData(self_path);
Lukacs Berki949c8762016-07-08 12:17:28 +00001344 VerifyJavaVersionAndSetJvm();
1345
Lukacs Berki1977d922016-05-02 09:31:37 +00001346 blaze_server->Connect();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001347 EnsureCorrectRunningVersion(blaze_server);
1348 KillRunningServerIfDifferentStartupOptions(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001349
Julio Merino28774852016-09-14 16:59:46 +00001350 if (globals->options->batch) {
1351 SetScheduling(globals->options->batch_cpu_scheduling,
1352 globals->options->io_nice_level);
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001353 StartStandalone(workspace_layout, blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001354 } else {
Julio Merinoe3e3bfa2016-12-08 22:22:12 +00001355 SendServerRequest(workspace_layout, blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001356 }
1357 return 0;
1358}
Thiago Farina0b6963e2015-04-28 20:26:45 +00001359
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001360static void null_grpc_log_function(gpr_log_func_args *args) {
1361}
1362
Lukacs Berki71675a52016-11-08 09:48:27 +00001363GrpcBlazeServer::GrpcBlazeServer(int connect_timeout_secs) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001364 connected_ = false;
Lukacs Berki71675a52016-11-08 09:48:27 +00001365 connect_timeout_secs_ = connect_timeout_secs;
1366
1367 gpr_set_log_function(null_grpc_log_function);
1368
Thiago Farina0bba4c92016-12-14 15:29:11 +00001369 pipe_ = blaze_util::CreatePipe();
1370 if (pipe_ == NULL) {
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001371 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "Couldn't create pipe");
Lukacs Berki6dd29092016-05-30 14:05:33 +00001372 }
1373}
1374
1375GrpcBlazeServer::~GrpcBlazeServer() {
Thiago Farina0bba4c92016-12-14 15:29:11 +00001376 delete pipe_;
1377 pipe_ = NULL;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001378}
1379
Lukacs Berki10dd6382017-01-11 09:08:54 +00001380bool GrpcBlazeServer::TryConnect(command_server::CommandServer::Stub* client) {
1381 grpc::ClientContext context;
1382 context.set_deadline(
1383 std::chrono::system_clock::now() +
1384 std::chrono::seconds(connect_timeout_secs_));
1385
1386 command_server::PingRequest request;
1387 command_server::PingResponse response;
1388 request.set_cookie(request_cookie_);
1389
1390 debug_log("Trying to connect to server (timeout: %d secs)...",
1391 connect_timeout_secs_);
1392 grpc::Status status = client->Ping(&context, request, &response);
1393
1394 if (!status.ok() || response.cookie() != response_cookie_) {
1395 debug_log("Connection to server failed: %s",
1396 status.error_message().c_str());
1397 return false;
1398 }
1399
1400 return true;
1401}
1402
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001403bool GrpcBlazeServer::Connect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001404 assert(!connected_);
1405
Laszlo Csomor760f7862016-12-19 15:46:47 +00001406 std::string server_dir =
1407 blaze_util::JoinPath(globals->options->output_base, "server");
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001408 std::string port;
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001409 std::string ipv4_prefix = "127.0.0.1:";
Lukacs Berkic8e74242016-04-28 08:32:04 +00001410 std::string ipv6_prefix_1 = "[0:0:0:0:0:0:0:1]:";
1411 std::string ipv6_prefix_2 = "[::1]:";
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001412
Laszlo Csomor760f7862016-12-19 15:46:47 +00001413 if (!blaze_util::ReadFile(blaze_util::JoinPath(server_dir, "command_port"),
1414 &port)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001415 return false;
1416 }
1417
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001418 // Make sure that we are being directed to localhost
1419 if (port.compare(0, ipv4_prefix.size(), ipv4_prefix)
Lukacs Berkic8e74242016-04-28 08:32:04 +00001420 && port.compare(0, ipv6_prefix_1.size(), ipv6_prefix_1)
1421 && port.compare(0, ipv6_prefix_2.size(), ipv6_prefix_2)) {
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001422 return false;
1423 }
1424
Laszlo Csomor760f7862016-12-19 15:46:47 +00001425 if (!blaze_util::ReadFile(blaze_util::JoinPath(server_dir, "request_cookie"),
1426 &request_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001427 return false;
1428 }
1429
Laszlo Csomor760f7862016-12-19 15:46:47 +00001430 if (!blaze_util::ReadFile(blaze_util::JoinPath(server_dir, "response_cookie"),
Laszlo Csomor49970e02016-11-28 08:55:47 +00001431 &response_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001432 return false;
1433 }
1434
1435 std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel(
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001436 port, grpc::InsecureChannelCredentials()));
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001437 std::unique_ptr<command_server::CommandServer::Stub> client(
1438 command_server::CommandServer::NewStub(channel));
1439
Lukacs Berki10dd6382017-01-11 09:08:54 +00001440 if (!TryConnect(client.get())) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001441 return false;
1442 }
1443
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001444 this->client_ = std::move(client);
Lukacs Berki1977d922016-05-02 09:31:37 +00001445 connected_ = true;
Lukacs Berki10dd6382017-01-11 09:08:54 +00001446
1447 globals->server_pid = GetServerPid(server_dir);
1448 if (globals->server_pid <= 0) {
1449 fprintf(stderr, "Can't get PID of existing server (server dir=%s). "
1450 "Shutting it down and starting a new one...\n",
1451 server_dir.c_str());
1452 // This means that we have a server we could connect to but without a PID
1453 // file, which in turn means that something went wrong before. Kill the
1454 // server so that we can start with as clean a slate as possible. This may
1455 // happen if someone (e.g. a client or server that's very old and uses an
1456 // AF_UNIX socket instead of gRPC) deletes the server.pid.txt file.
1457 KillRunningServer();
1458 // Then wait until it actually dies
1459 do {
1460 auto next_attempt_time(
1461 std::chrono::system_clock::now() + std::chrono::milliseconds(1000));
1462 std::this_thread::sleep_until(next_attempt_time);
1463 } while (TryConnect(client_.get()));
1464
1465 return false;
1466 }
1467
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001468 return true;
1469}
1470
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001471// Cancellation works as follows:
1472//
1473// When the user presses Ctrl-C, a SIGINT is delivered to the client, which is
1474// translated into a BlazeServer::Cancel() call. Since it's not a good idea to
Lukacs Berki6dd29092016-05-30 14:05:33 +00001475// do significant work in signal handlers, all it does is write a byte to an
1476// unnamed pipe.
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001477//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001478// This unnamed pipe is used to communicate with the cancel thread. Whenever
1479// something interesting happens, a byte is written into it, which is read by
1480// the cancel thread. These commands are available:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001481//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001482// - NOP
1483// - JOIN. The cancel thread needs to be terminated.
1484// - CANCEL. If the command ID is already available, a cancel request is sent.
1485// - COMMAND_ID_RECEIVED. The client learned the command ID from the server.
1486// If there is a pending cancellation request, it is acted upon.
1487//
1488// The only data the cancellation thread shares with the main thread is the
1489// file descriptor for receiving commands and command_id_, the latter of which
1490// is protected by a mutex, which mainly serves as a memory fence.
1491//
1492// The cancellation thread is joined at the end of the execution of the command.
1493// The main thread wakes it up just so that it can finish (using the JOIN
1494// action)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001495//
1496// It's conceivable that the server is busy and thus it cannot service the
1497// cancellation request. In that case, we simply ignore the failure and the both
1498// the server and the client go on as if nothing had happened (except that this
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001499// Ctrl-C still counts as a SIGINT, three of which result in a SIGKILL being
1500// delivered to the server)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001501void GrpcBlazeServer::CancelThread() {
1502 bool running = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001503 bool cancel = false;
1504 bool command_id_received = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001505 while (running) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001506 char buf;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001507
Thiago Farina0bba4c92016-12-14 15:29:11 +00001508 int bytes_read = pipe_->Receive(&buf, 1);
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001509 if (bytes_read < 0 && errno == EINTR) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001510 continue;
1511 } else if (bytes_read != 1) {
1512 pdie(blaze_exit_code::INTERNAL_ERROR,
1513 "Cannot communicate with cancel thread");
1514 }
1515
1516 switch (buf) {
1517 case CancelThreadAction::NOTHING:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001518 break;
1519
Lukacs Berki6dd29092016-05-30 14:05:33 +00001520 case CancelThreadAction::JOIN:
1521 running = false;
1522 break;
1523
1524 case CancelThreadAction::COMMAND_ID_RECEIVED:
1525 command_id_received = true;
1526 if (cancel) {
1527 SendCancelMessage();
1528 cancel = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001529 }
1530 break;
1531
Lukacs Berki6dd29092016-05-30 14:05:33 +00001532 case CancelThreadAction::CANCEL:
1533 if (command_id_received) {
1534 SendCancelMessage();
1535 } else {
1536 cancel = true;
1537 }
1538 break;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001539 }
1540 }
1541}
1542
Lukacs Berki6dd29092016-05-30 14:05:33 +00001543void GrpcBlazeServer::SendCancelMessage() {
1544 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
1545
1546 command_server::CancelRequest request;
1547 request.set_cookie(request_cookie_);
1548 request.set_command_id(command_id_);
1549 grpc::ClientContext context;
1550 context.set_deadline(std::chrono::system_clock::now() +
Lukacs Berki3ace3002016-08-31 08:55:34 +00001551 std::chrono::seconds(10));
Lukacs Berki6dd29092016-05-30 14:05:33 +00001552 command_server::CancelResponse response;
1553 // There isn't a lot we can do if this request fails
Lukacs Berki3ace3002016-08-31 08:55:34 +00001554 grpc::Status status = client_->Cancel(&context, request, &response);
1555 if (!status.ok()) {
1556 fprintf(stderr, "\nCould not interrupt server (%s)\n\n",
1557 status.error_message().c_str());
1558 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001559}
1560
Lukacs Berki1977d922016-05-02 09:31:37 +00001561// This will wait indefinitely until the server shuts down
1562void GrpcBlazeServer::KillRunningServer() {
1563 assert(connected_);
Lukacs Berki1977d922016-05-02 09:31:37 +00001564
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001565 grpc::ClientContext context;
1566 command_server::RunRequest request;
1567 command_server::RunResponse response;
1568 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001569 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001570 request.set_client_description("pid=" + blaze::GetProcessIdAsString() +
1571 " (for shutdown)");
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001572 request.add_arg("shutdown");
1573 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
1574 client_->Run(&context, request));
1575
1576 while (reader->Read(&response)) {}
1577
Lukacs Berki10dd6382017-01-11 09:08:54 +00001578 // Kill the server process for good measure (if we know the server PID)
1579 if (globals->server_pid > 0 &&
1580 VerifyServerProcess(globals->server_pid, globals->options->output_base,
Julio Merino28774852016-09-14 16:59:46 +00001581 globals->options->install_base)) {
Lukacs Berkiee44c382016-09-14 10:53:37 +00001582 KillServerProcess(globals->server_pid);
1583 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001584
1585 connected_ = false;
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001586}
1587
1588unsigned int GrpcBlazeServer::Communicate() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001589 assert(connected_);
1590
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001591 vector<string> arg_vector;
Julio Merino28774852016-09-14 16:59:46 +00001592 string command = globals->option_processor->GetCommand();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001593 if (command != "") {
1594 arg_vector.push_back(command);
1595 AddLoggingArgs(&arg_vector);
1596 }
1597
Julio Merino28774852016-09-14 16:59:46 +00001598 globals->option_processor->GetCommandArguments(&arg_vector);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001599
1600 command_server::RunRequest request;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001601 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001602 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001603 request.set_client_description("pid=" + blaze::GetProcessIdAsString());
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001604 for (const string& arg : arg_vector) {
1605 request.add_arg(arg);
1606 }
1607
1608 grpc::ClientContext context;
1609 command_server::RunResponse response;
1610 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001611 client_->Run(&context, request));
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001612
Lukacs Berki415d39a2016-04-28 13:18:54 +00001613 // Release the server lock because the gRPC handles concurrent clients just
1614 // fine. Note that this may result in two "waiting for other client" messages
1615 // (one during server startup and one emitted by the server)
Lukacs Berki1977d922016-05-02 09:31:37 +00001616 blaze::ReleaseLock(&blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +00001617
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001618 std::thread cancel_thread(&GrpcBlazeServer::CancelThread, this);
1619 bool command_id_set = false;
Laurent Le Brun08849b22016-09-20 12:21:32 +00001620 bool pipe_broken = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001621 while (reader->Read(&response)) {
Lukacs Berkic55e9c72016-04-25 13:43:40 +00001622 if (response.cookie() != response_cookie_) {
1623 fprintf(stderr, "\nServer response cookie invalid, exiting\n");
1624 return blaze_exit_code::INTERNAL_ERROR;
1625 }
1626
Laurent Le Brun08849b22016-09-20 12:21:32 +00001627 bool pipe_broken_now = false;
Lukacs Berki3c1e4042017-01-11 13:30:29 +00001628 const char* broken_pipe_name;
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001629
1630 if (!response.standard_output().empty()) {
1631 size_t size = response.standard_output().size();
1632 size_t r = fwrite(response.standard_output().c_str(), 1, size, stdout);
1633 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001634 pipe_broken_now = true;
Lukacs Berki3c1e4042017-01-11 13:30:29 +00001635 broken_pipe_name = "standard output";
Laurent Le Brun08849b22016-09-20 12:21:32 +00001636 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001637 }
1638
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001639 if (!response.standard_error().empty()) {
1640 size_t size = response.standard_error().size();
1641 size_t r = fwrite(response.standard_error().c_str(), 1, size, stderr);
1642 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001643 pipe_broken_now = true;
Lukacs Berki3c1e4042017-01-11 13:30:29 +00001644 broken_pipe_name = "standard error";
Laurent Le Brun08849b22016-09-20 12:21:32 +00001645 }
1646 }
1647
1648 if (pipe_broken_now && !pipe_broken) {
1649 pipe_broken = true;
Lukacs Berki3c1e4042017-01-11 13:30:29 +00001650 fprintf(stderr, "\nCannot write to %s; exiting...\n\n", broken_pipe_name);
Laurent Le Brun08849b22016-09-20 12:21:32 +00001651 Cancel();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001652 }
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001653
1654 if (!command_id_set && response.command_id().size() > 0) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001655 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001656 command_id_ = response.command_id();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001657 command_id_set = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001658 SendAction(CancelThreadAction::COMMAND_ID_RECEIVED);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001659 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001660 }
1661
Lukacs Berki6dd29092016-05-30 14:05:33 +00001662 SendAction(CancelThreadAction::JOIN);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001663 cancel_thread.join();
1664
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001665 if (!response.finished()) {
Lukacs Berki4e250942017-01-13 13:11:10 +00001666 fprintf(stderr, "\nServer finished RPC without an explicit exit code "
1667 "(log file: '%s')\n\n", globals->jvm_log_file.c_str());
Lukacs Berki2896dc02016-07-07 07:55:04 +00001668 return GetExitCodeForAbruptExit(*globals);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001669 }
1670
Lukacs Berki3c1e4042017-01-11 13:30:29 +00001671 // We'll exit with exit code SIGPIPE on Unixes due to PropagateSignalOnExit()
1672 return pipe_broken
1673 ? blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR
1674 : response.exit_code();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001675}
1676
1677void GrpcBlazeServer::Disconnect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001678 assert(connected_);
1679
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001680 client_.reset();
1681 request_cookie_ = "";
1682 response_cookie_ = "";
Lukacs Berki1977d922016-05-02 09:31:37 +00001683 connected_ = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001684}
1685
Lukacs Berki6dd29092016-05-30 14:05:33 +00001686void GrpcBlazeServer::SendAction(CancelThreadAction action) {
1687 char msg = action;
Thiago Farina0bba4c92016-12-14 15:29:11 +00001688 if (!pipe_->Send(&msg, 1)) {
Laszlo Csomor3b89d2d2016-11-28 14:04:27 +00001689 blaze::SigPrintf(
1690 "\nCould not interrupt server (cannot write to client pipe)\n\n");
Sasha Smundak1fdd31d2016-07-25 17:54:00 +00001691 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001692}
1693
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001694void GrpcBlazeServer::Cancel() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001695 assert(connected_);
Lukacs Berki6dd29092016-05-30 14:05:33 +00001696 SendAction(CancelThreadAction::CANCEL);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001697}
1698
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001699} // namespace blaze