blob: 4c7b40131dfc42ba97ee8e1cf67440b994d17c1a [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>
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010038#include <time.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000039
40#include <grpc/grpc.h>
Googler197547b2016-09-26 22:25:14 +000041#include <grpc/support/log.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000042#include <grpc++/channel.h>
43#include <grpc++/client_context.h>
44#include <grpc++/create_channel.h>
45#include <grpc++/security/credentials.h>
46
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010047#include <algorithm>
Lukacs Berki1b25ce22016-04-15 13:11:21 +000048#include <chrono> // NOLINT (gRPC requires this)
Lukacs Berkif1df38a2016-04-19 07:42:22 +000049#include <mutex> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010050#include <set>
51#include <string>
Lukacs Berkif1df38a2016-04-19 07:42:22 +000052#include <thread> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010053#include <utility>
54#include <vector>
55
Lukacs Berkie21e5922016-04-12 12:22:20 +000056
Nathan Harmatabf98f392016-01-07 22:58:29 +000057#include "src/main/cpp/blaze_abrupt_exit.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000058#include "src/main/cpp/blaze_util.h"
59#include "src/main/cpp/blaze_util_platform.h"
Thiago Farina676cb9f2016-10-06 11:00:43 +000060#include "src/main/cpp/global_variables.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000061#include "src/main/cpp/option_processor.h"
Julio Merino28774852016-09-14 16:59:46 +000062#include "src/main/cpp/startup_options.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000063#include "src/main/cpp/util/errors.h"
Thiago Farina7f9357f2015-04-23 13:57:43 +000064#include "src/main/cpp/util/exit_code.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000065#include "src/main/cpp/util/file.h"
Laszlo Csomor9c951962016-11-10 13:31:27 +000066#include "src/main/cpp/util/file_platform.h"
Chloe Calvarin78f1c852016-11-22 21:58:50 +000067#include "src/main/cpp/util/logging.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000068#include "src/main/cpp/util/numbers.h"
69#include "src/main/cpp/util/port.h"
70#include "src/main/cpp/util/strings.h"
Julio Merino211a95c2016-08-29 11:01:35 +000071#include "src/main/cpp/workspace_layout.h"
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +000072#include "third_party/ijar/zip.h"
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010073
Lukacs Berkie21e5922016-04-12 12:22:20 +000074#include "src/main/protobuf/command_server.grpc.pb.h"
75
Thiago Farina241f46c2015-04-13 14:33:30 +000076using blaze_util::die;
77using blaze_util::pdie;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010078
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010079namespace blaze {
80
Thiago Farina80bb0f22016-10-17 15:57:13 +000081using std::set;
82using std::string;
83using std::vector;
84
Lukacs Berki1977d922016-05-02 09:31:37 +000085static int GetServerPid(const string &server_dir);
Eric Fellheimer3a695f32016-05-11 17:26:30 +000086static void VerifyJavaVersionAndSetJvm();
Lukacs Berki907dbbf2016-04-15 11:30:12 +000087
Lukacs Berki1977d922016-05-02 09:31:37 +000088// The following is a treatise on how the interaction between the client and the
89// server works.
90//
91// First, the client unconditionally acquires an flock() lock on
92// $OUTPUT_BASE/lock then verifies if it has already extracted itself by
93// checking if the directory it extracts itself to (install base + a checksum)
94// is present. If not, then it does the extraction. Care is taken that this
95// process is atomic so that Blazen in multiple output bases do not clash.
96//
97// Then the client tries to connect to the currently executing server and kills
98// it if at least one of the following conditions is true:
99//
100// - The server is of the wrong version (as determined by the
101// $OUTPUT_BASE/install symlink)
102// - The server has different startup options than the client wants
103// - The client wants to run the command in batch mode
104//
105// Then, if needed, the client adjusts the install link to indicate which
106// version of the server it is running.
107//
108// In batch mode, the client then simply executes the server while taking care
109// that the output base lock is kept until it finishes.
110//
111// If in server mode, the client starts up a server if needed then sends the
Thiago Farina69dac862016-11-02 09:48:27 +0000112// command to the client and streams back stdout and stderr. The output base
113// lock is released after the command is sent to the server (the server
114// implements its own locking mechanism).
Lukacs Berki1977d922016-05-02 09:31:37 +0000115
116// Synchronization between the client and the server is a little precarious
117// because the client needs to know the PID of the server and it is not
118// available using a Java API and we don't have JNI on Windows at the moment,
119// so the server can't just communicate this over the communication channel.
120// Thus, a PID file is used, but care needs to be taken that the contents of
121// this PID file are right.
122//
123// Upon server startup, the PID file is written before the client spawns the
124// server. Thus, when the client can connect, it can be certain that the PID
125// file is up to date.
126//
127// Upon server shutdown, the PID file is deleted using a server shutdown hook.
128// However, this happens *after* the server stopped listening, so it's possible
129// that a client has already started up a server and written a new PID file.
130// In order to avoid this, when the client starts up a new server, it reads the
131// contents of the PID file and kills the process indicated in it (it could do
132// with a bit more care, since PIDs can be reused, but for now, we just believe
133// the PID file)
134//
135// Some more interesting scenarios:
136//
137// - The server receives a kill signal and it does not have a chance to delete
138// the PID file: the client cannot connect, reads the PID file, kills the
139// process indicated in it and starts up a new server.
140//
141// - The server stopped accepting connections but hasn't quit yet and a new
142// client comes around: the new client will kill the server based on the
143// PID file before a new server is started up.
144//
145// Alternative implementations:
146//
147// - Don't deal with PIDs at all. This would make it impossible for the client
148// to deliver a SIGKILL to the server after three SIGINTs. It would only be
149// possible with gRPC anyway.
150//
151// - Have the server check that the PID file containts the correct things
152// before deleting them: there is a window of time between checking the file
153// and deleting it in which a new server can overwrite the PID file. The
154// output base lock cannot be acquired, either, because when starting up a
155// new server, the client already holds it.
156//
157// - Delete the PID file before stopping to accept connections: then a client
158// could come about after deleting the PID file but before stopping accepting
159// connections. It would also not be resilient against a dead server that
160// left a PID file around.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000161class BlazeServer {
162 public:
163 virtual ~BlazeServer() {}
164
Lukacs Berki1977d922016-05-02 09:31:37 +0000165 // Acquire a lock for the server running in this output base. Returns the
166 // number of milliseconds spent waiting for the lock.
Lukacs Berki415d39a2016-04-28 13:18:54 +0000167 uint64_t AcquireLock();
168
Lukacs Berki1977d922016-05-02 09:31:37 +0000169 // Whether there is an active connection to a server.
170 bool Connected() const { return connected_; }
171
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000172 // Connect to the server. Returns if the connection was successful. Only
173 // call this when this object is in disconnected state. If it returns true,
174 // this object will be in connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000175 virtual bool Connect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000176
177 // Disconnects from an existing server. Only call this when this object is in
178 // connected state. After this call returns, the object will be in connected
179 // state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000180 virtual void Disconnect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000181
182 // Send the command line to the server and forward whatever it says to stdout
183 // and stderr. Returns the desired exit code. Only call this when the server
184 // is in connected state.
185 virtual unsigned int Communicate() = 0;
186
187 // Disconnects and kills an existing server. Only call this when this object
188 // is in connected state.
Lukacs Berki1977d922016-05-02 09:31:37 +0000189 virtual void KillRunningServer() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000190
191 // Cancel the currently running command. If there is no command currently
Lukacs Berki1977d922016-05-02 09:31:37 +0000192 // running, the result is unspecified. When called, this object must be in
193 // connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000194 virtual void Cancel() = 0;
Thiago Farina69dac862016-11-02 09:48:27 +0000195
196 protected:
197 BlazeLock blaze_lock_;
198 bool connected_;
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000199};
200
Lukacs Berki415d39a2016-04-28 13:18:54 +0000201////////////////////////////////////////////////////////////////////////
202// Global Variables
203static GlobalVariables *globals;
204static BlazeServer *blaze_server;
205
Laszlo Csomor32086b22016-11-24 15:23:55 +0000206// TODO(laszlocsomor) 2016-11-24: release the `globals` and `blaze_server`
207// objects. Currently nothing deletes them. Be careful that some functions may
208// call exit(2) or _exit(2) (attributed with ATTRIBUTE_NORETURN) meaning we have
209// to delete the objects before those.
210
Lukacs Berki415d39a2016-04-28 13:18:54 +0000211uint64_t BlazeServer::AcquireLock() {
212 return blaze::AcquireLock(
Julio Merino28774852016-09-14 16:59:46 +0000213 globals->options->output_base, globals->options->batch,
214 globals->options->block_for_lock, &blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +0000215}
216
Lukacs Berki1977d922016-05-02 09:31:37 +0000217// Communication method that uses gRPC on a socket bound to localhost. More
218// documentation is in command_server.proto .
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000219class GrpcBlazeServer : public BlazeServer {
220 public:
Lukacs Berki71675a52016-11-08 09:48:27 +0000221 GrpcBlazeServer(int connect_timeout_secs);
Lukacs Berki6dd29092016-05-30 14:05:33 +0000222 virtual ~GrpcBlazeServer();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000223
Lukacs Berki9d52bc52016-06-07 11:11:04 +0000224 virtual bool Connect();
225 virtual void Disconnect();
226 virtual unsigned int Communicate();
227 virtual void KillRunningServer();
228 virtual void Cancel();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000229
230 private:
Lukacs Berki6dd29092016-05-30 14:05:33 +0000231 enum CancelThreadAction { NOTHING, JOIN, CANCEL, COMMAND_ID_RECEIVED };
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000232
233 std::unique_ptr<command_server::CommandServer::Stub> client_;
234 std::string request_cookie_;
235 std::string response_cookie_;
236 std::string command_id_;
237
Lukacs Berki6dd29092016-05-30 14:05:33 +0000238 // protects command_id_ . Although we always set it before making the cancel
239 // thread do something with it, the mutex is still useful because it provides
240 // a memory fence.
241 std::mutex cancel_thread_mutex_;
Lukacs Berki8b999982016-04-26 15:40:38 +0000242
Lukacs Berki71675a52016-11-08 09:48:27 +0000243 int connect_timeout_secs_;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +0000244
245 // Pipe that the main thread sends actions to and the cancel thread receieves
246 // actions from.
247 blaze_util::IPipe* _pipe;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000248
249 void CancelThread();
Lukacs Berki6dd29092016-05-30 14:05:33 +0000250 void SendAction(CancelThreadAction action);
251 void SendCancelMessage();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000252};
253
254
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100255////////////////////////////////////////////////////////////////////////
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100256// Logic
257
Lukacs Berki71675a52016-11-08 09:48:27 +0000258void debug_log(const char* format, ...) {
259 if (!globals->options->client_debug) {
260 return;
261 }
262
263 fprintf(stderr, "CLIENT: ");
264 va_list arglist;
265 va_start(arglist, format);
266 vfprintf(stderr, format, arglist);
267 va_end(arglist);
268 fprintf(stderr, "%s", "\n");
269 fflush(stderr);
270}
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100271
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000272// A devtools_ijar::ZipExtractorProcessor to extract the InstallKeyFile
273class GetInstallKeyFileProcessor : public devtools_ijar::ZipExtractorProcessor {
274 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000275 explicit GetInstallKeyFileProcessor(string *install_base_key)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000276 : install_base_key_(install_base_key) {}
277
278 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
279 globals->extracted_binaries.push_back(filename);
280 return strcmp(filename, "install_base_key") == 0;
281 }
282
283 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
284 const devtools_ijar::u1 *data, const size_t size) {
285 string str(reinterpret_cast<const char *>(data), size);
286 blaze_util::StripWhitespace(&str);
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000287 if (str.size() != 32) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000288 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000289 "\nFailed to extract install_base_key: file size mismatch "
290 "(should be 32, is %zd)", str.size());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000291 }
292 *install_base_key_ = str;
293 }
294
295 private:
296 string *install_base_key_;
297};
298
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100299// Returns the install base (the root concatenated with the contents of the file
300// 'install_base_key' contained as a ZIP entry in the Blaze binary); as a side
301// effect, it also populates the extracted_binaries global variable.
302static string GetInstallBase(const string &root, const string &self_path) {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000303 GetInstallKeyFileProcessor processor(&globals->install_md5);
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000304 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
305 devtools_ijar::ZipExtractor::Create(self_path.c_str(), &processor));
306 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100307 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000308 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000309 globals->options->product_name.c_str(), errno, strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100310 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000311 if (extractor->ProcessAll() < 0) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100312 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000313 "\nFailed to extract install_base_key: %s", extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100314 }
315
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000316 if (globals->install_md5.empty()) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000317 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
318 "\nFailed to find install_base_key's in zip file");
319 }
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000320 return root + "/" + globals->install_md5;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100321}
322
323// Escapes colons by replacing them with '_C' and underscores by replacing them
324// with '_U'. E.g. "name:foo_bar" becomes "name_Cfoo_Ubar"
325static string EscapeForOptionSource(const string& input) {
326 string result = input;
327 blaze_util::Replace("_", "_U", &result);
328 blaze_util::Replace(":", "_C", &result);
329 return result;
330}
331
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000332// Returns the installed embedded binaries directory, under the shared
333// install_base location.
334string GetEmbeddedBinariesRoot(const string &install_base) {
335 return blaze_util::JoinPath(install_base, "_embedded_binaries");
336}
337
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100338// Returns the JVM command argument array.
339static vector<string> GetArgumentArray() {
340 vector<string> result;
341
342 // e.g. A Blaze server process running in ~/src/build_root (where there's a
343 // ~/src/build_root/WORKSPACE file) will appear in ps(1) as "blaze(src)".
344 string workspace =
345 blaze_util::Basename(blaze_util::Dirname(globals->workspace));
Julio Merino28774852016-09-14 16:59:46 +0000346 string product = globals->options->product_name;
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000347 blaze_util::ToLower(&product);
348 result.push_back(product + "(" + workspace + ")");
Julio Merino28774852016-09-14 16:59:46 +0000349 globals->options->AddJVMArgumentPrefix(
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000350 blaze_util::Dirname(blaze_util::Dirname(globals->jvm_path)),
351 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100352
353 result.push_back("-XX:+HeapDumpOnOutOfMemoryError");
Julio Merino28774852016-09-14 16:59:46 +0000354 string heap_crash_path = globals->options->output_base;
Dmitry Lomov7608db52016-07-14 11:27:10 +0000355 result.push_back("-XX:HeapDumpPath=" + ConvertPath(heap_crash_path));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100356
357 result.push_back("-Xverify:none");
358
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000359 vector<string> user_options;
360
Janak Ramakrishnan0acd1542016-01-06 18:42:30 +0000361 user_options.insert(user_options.begin(),
Julio Merino28774852016-09-14 16:59:46 +0000362 globals->options->host_jvm_args.begin(),
363 globals->options->host_jvm_args.end());
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000364
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100365 // Add JVM arguments particular to building blaze64 and particular JVM
366 // versions.
367 string error;
368 blaze_exit_code::ExitCode jvm_args_exit_code =
Julio Merino28774852016-09-14 16:59:46 +0000369 globals->options->AddJVMArguments(globals->options->GetHostJavabase(),
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000370 &result, user_options, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100371 if (jvm_args_exit_code != blaze_exit_code::SUCCESS) {
372 die(jvm_args_exit_code, "%s", error.c_str());
373 }
374
Julio Merino28774852016-09-14 16:59:46 +0000375 if (globals->options->batch && globals->options->oom_more_eagerly) {
Janak Ramakrishnan70c57902016-03-10 00:58:59 +0000376 // Put this OOM trigger with kill after --host_jvm_args, in case
377 // --host_jvm_args contains user-specified OOM triggers since we want those
378 // to execute first.
379 result.push_back("-XX:OnOutOfMemoryError=kill -USR2 %p");
380 }
381
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100382 // We put all directories on the java.library.path that contain .so files.
383 string java_library_path = "-Djava.library.path=";
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000384 string real_install_dir =
385 GetEmbeddedBinariesRoot(globals->options->install_base);
386
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100387 bool first = true;
388 for (const auto& it : globals->extracted_binaries) {
Thiago Farina01f36002015-04-08 15:59:08 +0000389 if (IsSharedLibrary(it)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100390 if (!first) {
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000391 java_library_path += blaze::ListSeparator();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100392 }
393 first = false;
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000394 java_library_path += blaze::ConvertPath(
395 blaze_util::JoinPath(real_install_dir, blaze_util::Dirname(it)));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100396 }
397 }
398 result.push_back(java_library_path);
399
400 // Force use of latin1 for file names.
401 result.push_back("-Dfile.encoding=ISO-8859-1");
402
Julio Merino28774852016-09-14 16:59:46 +0000403 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100404 fprintf(stderr,
405 "Running host JVM under debugger (listening on TCP port 5005).\n");
406 // Start JVM so that it listens for a connection from a
407 // JDWP-compliant debugger:
408 result.push_back("-Xdebug");
409 result.push_back("-Xrunjdwp:transport=dt_socket,server=y,address=5005");
410 }
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000411 result.insert(result.end(), user_options.begin(), user_options.end());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100412
Julio Merino28774852016-09-14 16:59:46 +0000413 globals->options->AddJVMArgumentSuffix(real_install_dir,
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000414 globals->extracted_binaries[0],
415 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100416
Lukacs Berki3d486832016-10-26 12:51:38 +0000417 // JVM arguments are complete. Now pass in Blaze startup options.
418 // Note that we always use the --flag=ARG form (instead of the --flag ARG one)
419 // so that BlazeRuntime#splitStartupOptions has an easy job.
Lukacs Berki71675a52016-11-08 09:48:27 +0000420
421 // TODO(lberki): Test that whatever the list constructed after this line is
422 // actually a list of parseable startup options.
Julio Merino28774852016-09-14 16:59:46 +0000423 if (!globals->options->batch) {
Lukacs Berki3d486832016-10-26 12:51:38 +0000424 result.push_back("--max_idle_secs=" +
425 ToString(globals->options->max_idle_secs));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100426 } else {
Googlerc8c64e72015-03-23 23:22:18 +0000427 // --batch must come first in the arguments to Java main() because
428 // the code expects it to be at args[0] if it's been set.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100429 result.push_back("--batch");
430 }
Lukacs Berkice1445f2016-04-19 15:52:55 +0000431
Julio Merino28774852016-09-14 16:59:46 +0000432 if (globals->options->command_port != 0) {
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000433 result.push_back(
Julio Merino28774852016-09-14 16:59:46 +0000434 "--command_port=" + ToString(globals->options->command_port));
Lukacs Berkice1445f2016-04-19 15:52:55 +0000435 }
436
Lukacs Berki71675a52016-11-08 09:48:27 +0000437 result.push_back(
438 "--connect_timeout_secs=" +
439 ToString(globals->options->connect_timeout_secs));
440
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000441 result.push_back("--install_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000442 blaze::ConvertPath(globals->options->install_base));
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000443 result.push_back("--install_md5=" + globals->install_md5);
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000444 result.push_back("--output_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000445 blaze::ConvertPath(globals->options->output_base));
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000446 result.push_back("--workspace_directory=" +
447 blaze::ConvertPath(globals->workspace));
Marian Lobur6dcdd602015-04-09 09:28:40 +0000448
Julio Merino28774852016-09-14 16:59:46 +0000449 if (globals->options->allow_configurable_attributes) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100450 result.push_back("--allow_configurable_attributes");
451 }
Julio Merino28774852016-09-14 16:59:46 +0000452 if (globals->options->deep_execroot) {
Lukacs Berki5fb98d12015-12-09 15:29:46 +0000453 result.push_back("--deep_execroot");
454 } else {
455 result.push_back("--nodeep_execroot");
456 }
Julio Merino28774852016-09-14 16:59:46 +0000457 if (globals->options->oom_more_eagerly) {
Janak Ramakrishnanadc706f2016-03-07 19:12:48 +0000458 result.push_back("--experimental_oom_more_eagerly");
459 }
Janak Ramakrishnan19fde1f2016-05-23 21:20:16 +0000460 result.push_back("--experimental_oom_more_eagerly_threshold=" +
Julio Merino28774852016-09-14 16:59:46 +0000461 ToString(globals->options->oom_more_eagerly_threshold));
Janak Ramakrishnan8cc772e2016-03-23 17:26:12 +0000462
Michajlo Matijkiwaf79a322016-09-16 15:44:35 +0000463 if (!globals->options->write_command_log) {
464 result.push_back("--nowrite_command_log");
465 }
466
Julio Merino28774852016-09-14 16:59:46 +0000467 if (globals->options->watchfs) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100468 result.push_back("--watchfs");
469 }
Julio Merino28774852016-09-14 16:59:46 +0000470 if (globals->options->fatal_event_bus_exceptions) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100471 result.push_back("--fatal_event_bus_exceptions");
472 } else {
473 result.push_back("--nofatal_event_bus_exceptions");
474 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100475
Lukacs Berki71675a52016-11-08 09:48:27 +0000476 // We use this syntax so that the logic in ServerNeedsToBeKilled() that
477 // decides whether the server needs killing is simpler. This is parsed by the
478 // Java code where --noclient_debug and --client_debug=false are equivalent.
479 // Note that --client_debug false (separated by space) won't work either,
480 // because the logic in ServerNeedsToBeKilled() assumes that every argument
481 // is in the --arg=value form.
482 if (globals->options->client_debug) {
483 result.push_back("--client_debug=true");
484 } else {
485 result.push_back("--client_debug=false");
486 }
487
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100488 // This is only for Blaze reporting purposes; the real interpretation of the
489 // jvm flags occurs when we set up the java command line.
Julio Merino28774852016-09-14 16:59:46 +0000490 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100491 result.push_back("--host_jvm_debug");
492 }
Julio Merino28774852016-09-14 16:59:46 +0000493 if (!globals->options->host_jvm_profile.empty()) {
494 result.push_back("--host_jvm_profile=" +
495 globals->options->host_jvm_profile);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100496 }
Julio Merino28774852016-09-14 16:59:46 +0000497 if (!globals->options->host_jvm_args.empty()) {
498 for (const auto &arg : globals->options->host_jvm_args) {
Janak Ramakrishnan533657e2015-11-13 23:34:14 +0000499 result.push_back("--host_jvm_args=" + arg);
500 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100501 }
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000502
Julio Merino28774852016-09-14 16:59:46 +0000503 if (globals->options->invocation_policy != NULL &&
504 strlen(globals->options->invocation_policy) > 0) {
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000505 result.push_back(string("--invocation_policy=") +
Julio Merino28774852016-09-14 16:59:46 +0000506 globals->options->invocation_policy);
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000507 }
508
Julio Merino28774852016-09-14 16:59:46 +0000509 result.push_back("--product_name=" + globals->options->product_name);
Luis Fernando Pino Duque623cdf82016-05-31 16:21:46 +0000510
Julio Merino28774852016-09-14 16:59:46 +0000511 globals->options->AddExtraOptions(&result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100512
513 // The option sources are transmitted in the following format:
514 // --option_sources=option1:source1:option2:source2:...
515 string option_sources = "--option_sources=";
516 first = true;
Julio Merino28774852016-09-14 16:59:46 +0000517 for (const auto& it : globals->options->option_sources) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100518 if (!first) {
519 option_sources += ":";
520 }
521
522 first = false;
523 option_sources += EscapeForOptionSource(it.first) + ":" +
524 EscapeForOptionSource(it.second);
525 }
526
527 result.push_back(option_sources);
528 return result;
529}
530
Thiago Farina5735c252016-04-27 16:16:27 +0000531// Add common command options for logging to the given argument array.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100532static void AddLoggingArgs(vector<string>* args) {
Googler9588b812015-07-23 11:49:37 +0000533 args->push_back("--startup_time=" + ToString(globals->startup_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100534 if (globals->command_wait_time != 0) {
535 args->push_back("--command_wait_time=" +
Googler9588b812015-07-23 11:49:37 +0000536 ToString(globals->command_wait_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100537 }
538 if (globals->extract_data_time != 0) {
539 args->push_back("--extract_data_time=" +
Googler9588b812015-07-23 11:49:37 +0000540 ToString(globals->extract_data_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100541 }
542 if (globals->restart_reason != NO_RESTART) {
543 const char *reasons[] = {
544 "no_restart", "no_daemon", "new_version", "new_options"
545 };
546 args->push_back(
547 string("--restart_reason=") + reasons[globals->restart_reason]);
548 }
549 args->push_back(
550 string("--binary_path=") + globals->binary_path);
551}
552
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100553// Join the elements of the specified array with NUL's (\0's), akin to the
554// format of /proc/$PID/cmdline.
Thiago Farina0b6963e2015-04-28 20:26:45 +0000555static string GetArgumentString(const vector<string>& argument_array) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100556 string result;
557 blaze_util::JoinStrings(argument_array, '\0', &result);
558 return result;
559}
560
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100561// Do a chdir into the workspace, and die if it fails.
562static void GoToWorkspace() {
Julio Merino211a95c2016-08-29 11:01:35 +0000563 if (WorkspaceLayout::InWorkspace(globals->workspace) &&
Laszlo Csomor9c951962016-11-10 13:31:27 +0000564 !blaze_util::ChangeDirectory(globals->workspace)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100565 pdie(blaze_exit_code::INTERNAL_ERROR,
Laszlo Csomor9c951962016-11-10 13:31:27 +0000566 "changing directory into %s failed", globals->workspace.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100567 }
568}
569
570// Check the java version if a java version specification is bundled. On
Thiago Farina5735c252016-04-27 16:16:27 +0000571// success, returns the executable path of the java command.
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000572static void VerifyJavaVersionAndSetJvm() {
Julio Merino28774852016-09-14 16:59:46 +0000573 string exe = globals->options->GetJvm();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100574
575 string version_spec_file = blaze_util::JoinPath(
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000576 GetEmbeddedBinariesRoot(globals->options->install_base), "java.version");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100577 string version_spec = "";
Laszlo Csomor49970e02016-11-28 08:55:47 +0000578 if (blaze_util::ReadFile(version_spec_file, &version_spec)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100579 blaze_util::StripWhitespace(&version_spec);
580 // A version specification is given, get version of java.
581 string jvm_version = GetJvmVersion(exe);
582
583 // Compare that jvm_version is found and at least the one specified.
584 if (jvm_version.size() == 0) {
585 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
586 "Java version not detected while at least %s is needed.\n"
587 "Please set JAVA_HOME.", version_spec.c_str());
588 } else if (!CheckJavaVersionIsAtLeast(jvm_version, version_spec)) {
589 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
590 "Java version is %s while at least %s is needed.\n"
591 "Please set JAVA_HOME.",
592 jvm_version.c_str(), version_spec.c_str());
593 }
594 }
595
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000596 globals->jvm_path = exe;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100597}
598
599// Starts the Blaze server. Returns a readable fd connected to the server.
600// This is currently used only to detect liveness.
Lukacs Berki1977d922016-05-02 09:31:37 +0000601static void StartServer(BlazeServerStartup** server_startup) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100602 vector<string> jvm_args_vector = GetArgumentArray();
603 string argument_string = GetArgumentString(jvm_args_vector);
Julio Merino28774852016-09-14 16:59:46 +0000604 string server_dir = globals->options->output_base + "/server";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100605 // Write the cmdline argument string to the server dir. If we get to this
606 // point, there is no server running, so we don't overwrite the cmdline file
607 // for the existing server. If might be that the server dies and the cmdline
608 // file stays there, but that is not a problem, since we always check the
609 // server, too.
Laszlo Csomor49970e02016-11-28 08:55:47 +0000610 blaze_util::WriteFile(argument_string, 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.
621 GoToWorkspace();
622
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.).
Lukacs Berki907dbbf2016-04-15 11:30:12 +0000632static void StartStandalone(BlazeServer* server) {
Lukacs Berki1977d922016-05-02 09:31:37 +0000633 if (server->Connected()) {
634 server->KillRunningServer();
635 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100636
637 // Wall clock time since process startup.
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000638 globals->startup_time = GetMillisecondsSinceProcessStart();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100639
640 if (VerboseLogging()) {
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000641 fprintf(stderr, "Starting %s in batch mode.\n",
Julio Merino28774852016-09-14 16:59:46 +0000642 globals->options->product_name.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100643 }
Julio Merino28774852016-09-14 16:59:46 +0000644 string command = globals->option_processor->GetCommand();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100645 vector<string> command_arguments;
Julio Merino28774852016-09-14 16:59:46 +0000646 globals->option_processor->GetCommandArguments(&command_arguments);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100647
648 if (!command_arguments.empty() && command == "shutdown") {
Julio Merino28774852016-09-14 16:59:46 +0000649 string product = globals->options->product_name;
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000650 blaze_util::ToLower(&product);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100651 fprintf(stderr,
652 "WARNING: Running command \"shutdown\" in batch mode. Batch mode "
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000653 "is triggered\nwhen not running %s within a workspace. If you "
654 "intend to shutdown an\nexisting %s server, run \"%s "
655 "shutdown\" from the directory where\nit was started.\n",
Julio Merino28774852016-09-14 16:59:46 +0000656 globals->options->product_name.c_str(),
657 globals->options->product_name.c_str(), product.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100658 }
659 vector<string> jvm_args_vector = GetArgumentArray();
660 if (command != "") {
661 jvm_args_vector.push_back(command);
662 AddLoggingArgs(&jvm_args_vector);
663 }
664
665 jvm_args_vector.insert(jvm_args_vector.end(),
666 command_arguments.begin(),
667 command_arguments.end());
668
669 GoToWorkspace();
670
Julio Merino28774852016-09-14 16:59:46 +0000671 string exe = globals->options->GetExe(globals->jvm_path,
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000672 globals->extracted_binaries[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100673 ExecuteProgram(exe, jvm_args_vector);
674 pdie(blaze_exit_code::INTERNAL_ERROR, "execv of '%s' failed", exe.c_str());
675}
676
Laszlo Csomorae16e762016-11-18 10:16:08 +0000677static void WriteFileToStderrOrDie(const char *file_name) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100678 FILE *fp = fopen(file_name, "r");
679 if (fp == NULL) {
680 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
681 "opening %s failed", file_name);
682 }
683 char buffer[255];
684 int num_read;
685 while ((num_read = fread(buffer, 1, sizeof buffer, fp)) > 0) {
686 if (ferror(fp)) {
687 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
688 "failed to read from '%s'", file_name);
689 }
Laszlo Csomorae16e762016-11-18 10:16:08 +0000690 fwrite(buffer, 1, num_read, stderr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100691 }
692 fclose(fp);
693}
694
Lukacs Berki4912f7f2016-06-17 16:12:22 +0000695// After connecting to the Blaze server, return its PID, or -1 if there was an
696// error.
Lukacs Berkid9da60f2016-04-26 11:40:24 +0000697static int GetServerPid(const string &server_dir) {
Lukacs Berki907dbbf2016-04-15 11:30:12 +0000698 // Note: there is no race here on startup since the server creates
699 // the pid file strictly before it binds the socket.
Thiago Farina048bbfc2016-09-21 08:20:41 +0000700 string pid_file = blaze_util::JoinPath(server_dir, kServerPidFile);
Laszlo Csomorae16e762016-11-18 10:16:08 +0000701 string bufstr;
Lukacs Berkiea4c42e2016-04-25 07:22:11 +0000702 int result;
Laszlo Csomor49970e02016-11-28 08:55:47 +0000703 if (!blaze_util::ReadFile(pid_file, &bufstr, 32) ||
Laszlo Csomor6450c182016-11-24 10:28:20 +0000704 !blaze_util::safe_strto32(bufstr, &result)) {
Lukacs Berkiea4c42e2016-04-25 07:22:11 +0000705 return -1;
706 }
707
708 return result;
Doug Rabsond655f2a2015-08-13 14:41:50 +0000709}
710
Lukacs Berki1977d922016-05-02 09:31:37 +0000711// Starts up a new server and connects to it. Exits if it didn't work not.
712static void StartServerAndConnect(BlazeServer *server) {
Julio Merino28774852016-09-14 16:59:46 +0000713 string server_dir = globals->options->output_base + "/server";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100714
715 // The server dir has the socket, so we don't allow access by other
716 // users.
Thiago Farina227369a2016-12-07 12:40:40 +0000717 if (!blaze_util::MakeDirectories(server_dir, 0700)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100718 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
719 "server directory '%s' could not be created", server_dir.c_str());
720 }
721
Laszlo Csomor6450c182016-11-24 10:28:20 +0000722 // TODO(laszlocsomor) 2016-11-21: remove `pid_symlink` and the `remove` call
723 // after 2017-05-01 (~half a year from writing this comment). By that time old
724 // Bazel clients that used to write PID symlinks will probably no longer be in
725 // use.
726 // Until then, defensively delete old PID symlinks that older clients may have
727 // left behind.
728 string pid_symlink = blaze_util::JoinPath(server_dir, kServerPidSymlink);
729 remove(pid_symlink.c_str());
730
Lukacs Berki1977d922016-05-02 09:31:37 +0000731 // If we couldn't connect to the server check if there is still a PID file
732 // and if so, kill the server that wrote it. This can happen e.g. if the
733 // server is in a GC pause and therefore cannot respond to ping requests and
734 // having two server instances running in the same output base is a
735 // disaster.
736 int server_pid = GetServerPid(server_dir);
737 if (server_pid > 0) {
Julio Merino28774852016-09-14 16:59:46 +0000738 if (VerifyServerProcess(server_pid, globals->options->output_base,
739 globals->options->install_base) &&
Lukacs Berkiee44c382016-09-14 10:53:37 +0000740 KillServerProcess(server_pid)) {
Lukacs Berki119dd4b2016-07-13 15:28:42 +0000741 fprintf(stderr, "Killed non-responsive server process (pid=%d)\n",
742 server_pid);
743 }
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000744 }
745
Julio Merino28774852016-09-14 16:59:46 +0000746 SetScheduling(globals->options->batch_cpu_scheduling,
747 globals->options->io_nice_level);
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000748
Lukacs Berki1977d922016-05-02 09:31:37 +0000749 BlazeServerStartup* server_startup;
750 StartServer(&server_startup);
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000751
752 // Give the server two minutes to start up. That's enough to connect with a
753 // debugger.
754 auto try_until_time(
755 std::chrono::system_clock::now() + std::chrono::seconds(120));
756 bool had_to_wait = false;
757 while (std::chrono::system_clock::now() < try_until_time) {
758 auto next_attempt_time(
759 std::chrono::system_clock::now() + std::chrono::milliseconds(100));
Lukacs Berki1977d922016-05-02 09:31:37 +0000760 if (server->Connect()) {
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000761 if (had_to_wait && !globals->options->client_debug) {
Lukacs Berki1977d922016-05-02 09:31:37 +0000762 fputc('\n', stderr);
763 fflush(stderr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100764 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000765 delete server_startup;
766 return;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100767 }
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000768
769 had_to_wait = true;
Lukacs Berki71675a52016-11-08 09:48:27 +0000770 if (!globals->options->client_debug) {
771 fputc('.', stderr);
772 fflush(stderr);
773 }
774
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000775 std::this_thread::sleep_until(next_attempt_time);
Lukacs Berki1977d922016-05-02 09:31:37 +0000776 if (!server_startup->IsStillAlive()) {
777 fprintf(stderr, "\nunexpected pipe read status: %s\n"
778 "Server presumed dead. Now printing '%s':\n",
779 strerror(errno), globals->jvm_log_file.c_str());
Laszlo Csomorae16e762016-11-18 10:16:08 +0000780 WriteFileToStderrOrDie(globals->jvm_log_file.c_str());
Lukacs Berki1977d922016-05-02 09:31:37 +0000781 exit(blaze_exit_code::INTERNAL_ERROR);
782 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100783 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000784 die(blaze_exit_code::INTERNAL_ERROR,
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000785 "\nError: couldn't connect to server after 120 seconds.");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100786}
787
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000788// A devtools_ijar::ZipExtractorProcessor to extract the files from the blaze
789// zip.
790class ExtractBlazeZipProcessor : public devtools_ijar::ZipExtractorProcessor {
791 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000792 explicit ExtractBlazeZipProcessor(const string &embedded_binaries)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000793 : embedded_binaries_(embedded_binaries) {}
794
795 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
796 return !devtools_ijar::zipattr_is_dir(attr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100797 }
798
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000799 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
800 const devtools_ijar::u1 *data, const size_t size) {
801 string path = blaze_util::JoinPath(embedded_binaries_, filename);
Thiago Farina227369a2016-12-07 12:40:40 +0000802 if (!blaze_util::MakeDirectories(blaze_util::Dirname(path), 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100803 pdie(blaze_exit_code::INTERNAL_ERROR,
804 "couldn't create '%s'", path.c_str());
805 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100806
Laszlo Csomor49970e02016-11-28 08:55:47 +0000807 if (!blaze_util::WriteFile(data, size, path)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000808 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Laszlo Csomorae16e762016-11-18 10:16:08 +0000809 "\nFailed to write zipped file \"%s\": %s", path.c_str(),
810 strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100811 }
812 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000813
814 private:
815 const string embedded_binaries_;
816};
817
818// Actually extracts the embedded data files into the tree whose root
819// is 'embedded_binaries'.
820static void ActuallyExtractData(const string &argv0,
821 const string &embedded_binaries) {
822 ExtractBlazeZipProcessor processor(embedded_binaries);
Thiago Farina227369a2016-12-07 12:40:40 +0000823 if (!blaze_util::MakeDirectories(embedded_binaries, 0777)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000824 pdie(blaze_exit_code::INTERNAL_ERROR, "couldn't create '%s'",
825 embedded_binaries.c_str());
826 }
827
828 fprintf(stderr, "Extracting %s installation...\n",
Julio Merino28774852016-09-14 16:59:46 +0000829 globals->options->product_name.c_str());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000830 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
831 devtools_ijar::ZipExtractor::Create(argv0.c_str(), &processor));
832 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100833 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000834 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000835 globals->options->product_name.c_str(), errno, strerror(errno));
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000836 }
837 if (extractor->ProcessAll() < 0) {
838 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
839 "\nFailed to extract %s as a zip file: %s",
Julio Merino28774852016-09-14 16:59:46 +0000840 globals->options->product_name.c_str(), extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100841 }
842
843 const time_t TEN_YEARS_IN_SEC = 3600 * 24 * 365 * 10;
844 time_t future_time = time(NULL) + TEN_YEARS_IN_SEC;
845
846 // 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
855 set<string> synced_directories;
Laszlo Csomor251bf032016-11-16 11:01:32 +0000856 for (const auto &it : extracted_files) {
857 const char *extracted_path = it.c_str();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100858
859 // Set the time to a distantly futuristic value so we can observe tampering.
Laszlo Csomor251bf032016-11-16 11:01:32 +0000860 // Note that keeping the default timestamp set by unzip (1970-01-01) and
861 // using that to detect tampering is not enough, because we also need the
862 // timestamp to change between Blaze releases so that the metadata cache
863 // knows that the files may have changed. This is important for actions that
864 // use embedded binaries as artifacts.
Laszlo Csomor6c167652016-11-17 11:00:49 +0000865 if (!blaze_util::SetMtimeMillisec(it, future_time)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100866 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
867 "failed to set timestamp on '%s'", extracted_path);
868 }
869
Laszlo Csomorae16e762016-11-18 10:16:08 +0000870 blaze_util::SyncFile(it);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100871
872 string directory = blaze_util::Dirname(extracted_path);
873
874 // Now walk up until embedded_binaries and sync every directory in between.
875 // synced_directories is used to avoid syncing the same directory twice.
876 // The !directory.empty() and directory != "/" conditions are not strictly
877 // needed, but it makes this loop more robust, because otherwise, if due to
878 // some glitch, directory was not under embedded_binaries, it would get
879 // into an infinite loop.
880 while (directory != embedded_binaries &&
881 synced_directories.count(directory) == 0 &&
882 !directory.empty() &&
883 directory != "/") {
Laszlo Csomorae16e762016-11-18 10:16:08 +0000884 blaze_util::SyncFile(directory);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100885 synced_directories.insert(directory);
886 directory = blaze_util::Dirname(directory);
887 }
888 }
889
Laszlo Csomorae16e762016-11-18 10:16:08 +0000890 blaze_util::SyncFile(embedded_binaries);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100891}
892
893// Installs Blaze by extracting the embedded data files, iff necessary.
894// The MD5-named install_base directory on disk is trusted; we assume
895// no-one has modified the extracted files beneath this directory once
896// it is in place. Concurrency during extraction is handled by
897// extracting in a tmp dir and then renaming it into place where it
898// becomes visible automically at the new path.
899// Populates globals->extracted_binaries with their extracted locations.
900static void ExtractData(const string &self_path) {
901 // If the install dir doesn't exist, create it, if it does, we know it's good.
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000902 if (!blaze_util::PathExists(globals->options->install_base)) {
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000903 uint64_t st = GetMillisecondsMonotonic();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100904 // Work in a temp dir to avoid races.
Julio Merino28774852016-09-14 16:59:46 +0000905 string tmp_install = globals->options->install_base + ".tmp." +
Laszlo Csomorae16e762016-11-18 10:16:08 +0000906 blaze::GetProcessIdAsString();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100907 string tmp_binaries = tmp_install + "/_embedded_binaries";
908 ActuallyExtractData(self_path, tmp_binaries);
909
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000910 uint64_t et = GetMillisecondsMonotonic();
911 globals->extract_data_time = et - st;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100912
913 // Now rename the completed installation to its final name. If this
914 // fails due to an ENOTEMPTY then we assume another good
915 // installation snuck in before us.
Laszlo Csomor49970e02016-11-28 08:55:47 +0000916 if (rename(tmp_install.c_str(), globals->options->install_base.c_str()) ==
917 -1 &&
918 errno != ENOTEMPTY) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100919 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
920 "install base directory '%s' could not be renamed into place",
921 tmp_install.c_str());
922 }
923 } else {
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000924 if (!blaze_util::IsDirectory(globals->options->install_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100925 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
926 "Error: Install base directory '%s' could not be created. "
927 "It exists but is not a directory.",
Julio Merino28774852016-09-14 16:59:46 +0000928 globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100929 }
930
931 const time_t time_now = time(NULL);
932 string real_install_dir = blaze_util::JoinPath(
Julio Merino28774852016-09-14 16:59:46 +0000933 globals->options->install_base,
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100934 "_embedded_binaries");
935 for (const auto& it : globals->extracted_binaries) {
936 string path = blaze_util::JoinPath(real_install_dir, it);
937 // Check that the file exists and is readable.
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000938 if (!blaze_util::CanAccess(path, true, false, false)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100939 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
940 "Error: corrupt installation: file '%s' missing."
941 " Please remove '%s' and try again.",
Julio Merino28774852016-09-14 16:59:46 +0000942 path.c_str(), globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100943 }
Laszlo Csomor8a48f612016-11-17 10:18:34 +0000944 // Check that the timestamp is in the future. A past timestamp would
945 // indicate that the file has been tampered with.
946 // See ActuallyExtractData().
947 if (!blaze_util::IsDirectory(path)) {
948 time_t mtime = blaze_util::GetMtimeMillisec(path);
949 if (mtime == -1) {
950 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
951 "Error: could not retrieve mtime of file '%s'. "
952 "Please remove '%s' and try again.",
953 path.c_str(), globals->options->install_base.c_str());
954 } else if (mtime <= time_now) {
955 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
956 "Error: corrupt installation: file '%s' "
957 "modified. Please remove '%s' and try again.",
958 path.c_str(), globals->options->install_base.c_str());
959 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100960 }
961 }
962 }
963}
964
Lukacs Berki71675a52016-11-08 09:48:27 +0000965const char *volatile_startup_options[] = {
966 "--option_sources=",
967 "--max_idle_secs=",
968 "--connect_timeout_secs=",
969 "--client_debug=",
970 NULL,
971};
972
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100973// Returns true if the server needs to be restarted to accommodate changes
974// between the two argument lists.
975static bool ServerNeedsToBeKilled(const vector<string>& args1,
976 const vector<string>& args2) {
977 // We need not worry about one side missing an argument and the other side
978 // having the default value, since this command line is already the
979 // canonicalized one that always contains every switch (with default values
980 // if it was not present on the real command line). Same applies for argument
981 // ordering.
982 if (args1.size() != args2.size()) {
983 return true;
984 }
985
986 for (int i = 0; i < args1.size(); i++) {
Lukacs Berki71675a52016-11-08 09:48:27 +0000987 bool option_volatile = false;
988 for (const char** candidate = volatile_startup_options;
989 *candidate != NULL;
990 candidate++) {
991 string candidate_string(*candidate);
992 if (args1[i].substr(0, candidate_string.size()) == candidate_string &&
993 args2[i].substr(0, candidate_string.size()) == candidate_string) {
994 option_volatile = true;
995 break;
996 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100997 }
998
Lukacs Berki71675a52016-11-08 09:48:27 +0000999 if (!option_volatile && args1[i] != args2[i]) {
Lukacs Berki3d486832016-10-26 12:51:38 +00001000 return true;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001001 }
1002 }
1003
1004 return false;
1005}
1006
1007// Kills the running Blaze server, if any, if the startup options do not match.
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001008static void KillRunningServerIfDifferentStartupOptions(BlazeServer* server) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001009 if (!server->Connected()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001010 return;
1011 }
1012
Julio Merino28774852016-09-14 16:59:46 +00001013 string cmdline_path = globals->options->output_base + "/server/cmdline";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001014 string joined_arguments;
1015
1016 // No, /proc/$PID/cmdline does not work, because it is limited to 4K. Even
1017 // worse, its behavior differs slightly between kernels (in some, when longer
1018 // command lines are truncated, the last 4 bytes are replaced with
1019 // "..." + NUL.
Laszlo Csomor49970e02016-11-28 08:55:47 +00001020 blaze_util::ReadFile(cmdline_path, &joined_arguments);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001021 vector<string> arguments = blaze_util::Split(joined_arguments, '\0');
1022
1023 // These strings contain null-separated command line arguments. If they are
1024 // the same, the server can stay alive, otherwise, it needs shuffle off this
1025 // mortal coil.
1026 if (ServerNeedsToBeKilled(arguments, GetArgumentArray())) {
1027 globals->restart_reason = NEW_OPTIONS;
1028 fprintf(stderr,
Kristina Chodorow11d40d22015-03-17 18:26:59 +00001029 "WARNING: Running %s server needs to be killed, because the "
1030 "startup options are different.\n",
Julio Merino28774852016-09-14 16:59:46 +00001031 globals->options->product_name.c_str());
Lukacs Berki1977d922016-05-02 09:31:37 +00001032 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001033 }
1034}
1035
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001036// Kills the old running server if it is not the same version as us,
1037// dealing with various combinations of installation scheme
1038// (installation symlink and older MD5_MANIFEST contents).
1039// This function requires that the installation be complete, and the
1040// server lock acquired.
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001041static void EnsureCorrectRunningVersion(BlazeServer* server) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001042 // Read the previous installation's semaphore symlink in output_base. If the
1043 // target dirs don't match, or if the symlink was not present, then kill any
1044 // running servers. Lastly, symlink to our installation so others know which
1045 // installation is running.
Julio Merino28774852016-09-14 16:59:46 +00001046 string installation_path = globals->options->output_base + "/install";
Lukacs Berki497d8242016-04-28 07:21:26 +00001047 string prev_installation;
Laszlo Csomor49970e02016-11-28 08:55:47 +00001048 bool ok = ReadDirectorySymlink(installation_path, &prev_installation);
Lukacs Berki497d8242016-04-28 07:21:26 +00001049 if (!ok || !CompareAbsolutePaths(
Julio Merino28774852016-09-14 16:59:46 +00001050 prev_installation, globals->options->install_base)) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001051 if (server->Connected()) {
1052 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001053 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001054
1055 globals->restart_reason = NEW_VERSION;
Laszlo Csomor49970e02016-11-28 08:55:47 +00001056 blaze_util::UnlinkPath(installation_path);
1057 if (!SymlinkDirectories(globals->options->install_base,
1058 installation_path)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001059 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1060 "failed to create installation symlink '%s'",
1061 installation_path.c_str());
1062 }
1063 const time_t time_now = time(NULL);
Laszlo Csomor6c167652016-11-17 11:00:49 +00001064 if (!blaze_util::SetMtimeMillisec(globals->options->install_base,
1065 time_now)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001066 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1067 "failed to set timestamp on '%s'",
Julio Merino28774852016-09-14 16:59:46 +00001068 globals->options->install_base.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001069 }
1070 }
1071}
1072
Laszlo Csomor32086b22016-11-24 15:23:55 +00001073static void CancelServer() {
1074 blaze_server->Cancel();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001075}
1076
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001077// Performs all I/O for a single client request to the server, and
1078// shuts down the client (by exit or signal).
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001079static ATTRIBUTE_NORETURN void SendServerRequest(BlazeServer* server) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001080 while (true) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001081 if (!server->Connected()) {
1082 StartServerAndConnect(server);
1083 }
1084
Lukacs Berki4de98942016-09-09 09:23:36 +00001085 // Check for the case when the workspace directory deleted and then gets
1086 // recreated while the server is running
1087
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001088 string server_cwd = GetProcessCWD(globals->server_pid);
Lukacs Berki4be230a2015-10-15 13:43:03 +00001089 // If server_cwd is empty, GetProcessCWD failed. This notably occurs when
1090 // running under Docker because then readlink(/proc/[pid]/cwd) returns
1091 // EPERM.
1092 // Docker issue #6687 (https://github.com/docker/docker/issues/6687) fixed
1093 // this, but one still needs the --cap-add SYS_PTRACE command line flag, at
1094 // least according to the discussion on Docker issue #6800
1095 // (https://github.com/docker/docker/issues/6687), and even then, it's a
1096 // non-default Docker flag. Given that this occurs only in very weird
1097 // cases, it's better to assume that everything is alright if we can't get
1098 // the cwd.
1099
1100 if (!server_cwd.empty() &&
1101 (server_cwd != globals->workspace || // changed
1102 server_cwd.find(" (deleted)") != string::npos)) { // deleted.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001103 // There's a distant possibility that the two paths look the same yet are
1104 // actually different because the two processes have different mount
1105 // tables.
1106 if (VerboseLogging()) {
1107 fprintf(stderr, "Server's cwd moved or deleted (%s).\n",
1108 server_cwd.c_str());
1109 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001110 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001111 } else {
1112 break;
1113 }
1114 }
1115
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001116 if (VerboseLogging()) {
1117 fprintf(stderr, "Connected (server pid=%d).\n", globals->server_pid);
1118 }
1119
1120 // Wall clock time since process startup.
Laszlo Csomor943d3cf2016-11-07 14:27:21 +00001121 globals->startup_time = GetMillisecondsSinceProcessStart();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001122
Laszlo Csomor32086b22016-11-24 15:23:55 +00001123 SignalHandler::Get().Install(globals, CancelServer);
1124 SignalHandler::Get().PropagateSignalOrExit(server->Communicate());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001125}
1126
1127// Parse the options, storing parsed values in globals.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001128static void ParseOptions(int argc, const char *argv[]) {
1129 string error;
1130 blaze_exit_code::ExitCode parse_exit_code =
Julio Merino28774852016-09-14 16:59:46 +00001131 globals->option_processor->ParseOptions(argc, argv, globals->workspace,
1132 globals->cwd, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001133 if (parse_exit_code != blaze_exit_code::SUCCESS) {
1134 die(parse_exit_code, "%s", error.c_str());
1135 }
Julio Merino28774852016-09-14 16:59:46 +00001136 globals->options = globals->option_processor->GetParsedStartupOptions();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001137}
1138
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001139// Compute the globals globals->cwd and globals->workspace.
1140static void ComputeWorkspace() {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001141 globals->cwd = blaze_util::MakeCanonical(blaze_util::GetCwd().c_str());
1142 if (globals->cwd.empty()) {
1143 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1144 "blaze_util::MakeCanonical('%s') failed",
1145 blaze_util::GetCwd().c_str());
1146 }
Julio Merino211a95c2016-08-29 11:01:35 +00001147 globals->workspace = WorkspaceLayout::GetWorkspace(globals->cwd);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001148}
1149
1150// Figure out the base directories based on embedded data, username, cwd, etc.
Julio Merino28774852016-09-14 16:59:46 +00001151// Sets globals->options->install_base, globals->options->output_base,
Thiago Farina6fd9bf12016-04-26 09:02:18 +00001152// globals->lockfile, globals->jvm_log_file.
Thiago Farina2fd78902015-05-18 11:37:59 +00001153static void ComputeBaseDirectories(const string &self_path) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001154 // Only start a server when in a workspace because otherwise we won't do more
1155 // than emit a help message.
Julio Merino211a95c2016-08-29 11:01:35 +00001156 if (!WorkspaceLayout::InWorkspace(globals->workspace)) {
Julio Merino28774852016-09-14 16:59:46 +00001157 globals->options->batch = true;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001158 }
1159
1160 // The default install_base is <output_user_root>/install/<md5(blaze)>
1161 // but if an install_base is specified on the command line, we use that as
1162 // the base instead.
Julio Merino28774852016-09-14 16:59:46 +00001163 if (globals->options->install_base.empty()) {
1164 string install_user_root = globals->options->output_user_root + "/install";
1165 globals->options->install_base =
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001166 GetInstallBase(install_user_root, self_path);
1167 } else {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +00001168 // We call GetInstallBase anyway to populate extracted_binaries and
1169 // install_md5.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001170 GetInstallBase("", self_path);
1171 }
1172
Julio Merino28774852016-09-14 16:59:46 +00001173 if (globals->options->output_base.empty()) {
Laszlo Csomor6bf95762016-11-16 13:29:22 +00001174 globals->options->output_base = blaze::GetHashedBaseDir(
Julio Merino28774852016-09-14 16:59:46 +00001175 globals->options->output_user_root, globals->workspace);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001176 }
1177
Julio Merino28774852016-09-14 16:59:46 +00001178 const char *output_base = globals->options->output_base.c_str();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001179 if (!blaze_util::PathExists(globals->options->output_base)) {
Thiago Farina227369a2016-12-07 12:40:40 +00001180 if (!blaze_util::MakeDirectories(globals->options->output_base, 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001181 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1182 "Output base directory '%s' could not be created",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001183 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001184 }
1185 } else {
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001186 if (!blaze_util::IsDirectory(globals->options->output_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001187 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1188 "Error: Output base directory '%s' could not be created. "
1189 "It exists but is not a directory.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001190 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001191 }
1192 }
Laszlo Csomor9c951962016-11-10 13:31:27 +00001193 if (!blaze_util::CanAccess(globals->options->output_base, true, true, true)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001194 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1195 "Error: Output base directory '%s' must be readable and writable.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001196 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001197 }
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001198 ExcludePathFromBackup(output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001199
Laszlo Csomorc3545392016-11-24 13:33:28 +00001200 globals->options->output_base = blaze_util::MakeCanonical(output_base);
1201 if (globals->options->output_base.empty()) {
1202 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1203 "blaze_util::MakeCanonical('%s') failed", output_base);
1204 }
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001205
Julio Merino28774852016-09-14 16:59:46 +00001206 globals->lockfile = globals->options->output_base + "/lock";
1207 globals->jvm_log_file = globals->options->output_base + "/server/jvm.out";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001208}
1209
1210static void CheckEnvironment() {
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001211 if (!blaze::GetEnv("http_proxy").empty()) {
Lukacs Berki86a28b02016-10-25 10:34:45 +00001212 fprintf(stderr, "Warning: ignoring http_proxy in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001213 blaze::UnsetEnv("http_proxy");
Lukacs Berki86a28b02016-10-25 10:34:45 +00001214 }
1215
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001216 if (!blaze::GetEnv("LD_ASSUME_KERNEL").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001217 // Fix for bug: if ulimit -s and LD_ASSUME_KERNEL are both
1218 // specified, the JVM fails to create threads. See thread_stack_regtest.
1219 // This is also provoked by LD_LIBRARY_PATH=/usr/lib/debug,
1220 // or anything else that causes the JVM to use LinuxThreads.
1221 fprintf(stderr, "Warning: ignoring LD_ASSUME_KERNEL in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001222 blaze::UnsetEnv("LD_ASSUME_KERNEL");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001223 }
1224
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001225 if (!blaze::GetEnv("LD_PRELOAD").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001226 fprintf(stderr, "Warning: ignoring LD_PRELOAD in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001227 blaze::UnsetEnv("LD_PRELOAD");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001228 }
1229
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001230 if (!blaze::GetEnv("_JAVA_OPTIONS").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001231 // This would override --host_jvm_args
1232 fprintf(stderr, "Warning: ignoring _JAVA_OPTIONS in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001233 blaze::UnsetEnv("_JAVA_OPTIONS");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001234 }
1235
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001236 if (!blaze::GetEnv("TEST_TMPDIR").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001237 fprintf(stderr, "INFO: $TEST_TMPDIR defined: output root default is "
Julio Merino28774852016-09-14 16:59:46 +00001238 "'%s'.\n", globals->options->output_root.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001239 }
1240
1241 // TODO(bazel-team): We've also seen a failure during loading (creating
1242 // threads?) when ulimit -Hs 8192. Characterize that and check for it here.
1243
1244 // Make the JVM use ISO-8859-1 for parsing its command line because "blaze
1245 // run" doesn't handle non-ASCII command line arguments. This is apparently
1246 // the most reliable way to select the platform default encoding.
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001247 blaze::SetEnv("LANG", "en_US.ISO-8859-1");
1248 blaze::SetEnv("LANGUAGE", "en_US.ISO-8859-1");
1249 blaze::SetEnv("LC_ALL", "en_US.ISO-8859-1");
1250 blaze::SetEnv("LC_CTYPE", "en_US.ISO-8859-1");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001251}
1252
Laszlo Csomorc3545392016-11-24 13:33:28 +00001253static string CheckAndGetBinaryPath(const string& argv0) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001254 if (argv0[0] == '/') {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001255 return argv0;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001256 } else {
1257 string abs_path = globals->cwd + '/' + argv0;
Laszlo Csomorc3545392016-11-24 13:33:28 +00001258 string resolved_path = blaze_util::MakeCanonical(abs_path.c_str());
1259 if (!resolved_path.empty()) {
1260 return resolved_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001261 } else {
1262 // This happens during our integration tests, but thats okay, as we won't
1263 // log the invocation anyway.
Laszlo Csomorc3545392016-11-24 13:33:28 +00001264 return abs_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001265 }
1266 }
1267}
1268
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001269// TODO(bazel-team): Execute the server as a child process and write its exit
1270// code to a file. In case the server becomes unresonsive or terminates
1271// unexpectedly (in a way that isn't already handled), we can observe the file,
1272// if it exists. (If it doesn't, then we know something went horribly wrong.)
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001273int Main(int argc, const char *argv[], OptionProcessor *option_processor,
1274 std::unique_ptr<blaze_util::LogHandler> log_handler) {
1275 // Logging must be set first to assure no log statements are missed.
1276 blaze_util::SetLogHandler(std::move(log_handler));
Thiago Farina676cb9f2016-10-06 11:00:43 +00001277 globals = new GlobalVariables(option_processor);
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001278 blaze::SetupStdStreams();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001279
1280 // Must be done before command line parsing.
1281 ComputeWorkspace();
Laszlo Csomorc3545392016-11-24 13:33:28 +00001282 globals->binary_path = CheckAndGetBinaryPath(argv[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001283 ParseOptions(argc, argv);
Lukacs Berkibb2230f2016-04-27 14:19:25 +00001284
Lukacs Berki71675a52016-11-08 09:48:27 +00001285 debug_log("Debug logging active");
1286
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001287 CheckEnvironment();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001288 blaze::CreateSecureOutputRoot(globals->options->output_user_root);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001289
1290 const string self_path = GetSelfPath();
1291 ComputeBaseDirectories(self_path);
1292
Lukacs Berki71675a52016-11-08 09:48:27 +00001293 blaze_server = static_cast<BlazeServer *>(new GrpcBlazeServer(
1294 globals->options->connect_timeout_secs));
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001295
Lukacs Berki415d39a2016-04-28 13:18:54 +00001296 globals->command_wait_time = blaze_server->AcquireLock();
Lukacs Berkice1445f2016-04-19 15:52:55 +00001297
Julio Merino28774852016-09-14 16:59:46 +00001298 WarnFilesystemType(globals->options->output_base);
Lukacs Berkice1445f2016-04-19 15:52:55 +00001299
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001300 ExtractData(self_path);
Lukacs Berki949c8762016-07-08 12:17:28 +00001301 VerifyJavaVersionAndSetJvm();
1302
Lukacs Berki1977d922016-05-02 09:31:37 +00001303 blaze_server->Connect();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001304 EnsureCorrectRunningVersion(blaze_server);
1305 KillRunningServerIfDifferentStartupOptions(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001306
Julio Merino28774852016-09-14 16:59:46 +00001307 if (globals->options->batch) {
1308 SetScheduling(globals->options->batch_cpu_scheduling,
1309 globals->options->io_nice_level);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001310 StartStandalone(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001311 } else {
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001312 SendServerRequest(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001313 }
1314 return 0;
1315}
Thiago Farina0b6963e2015-04-28 20:26:45 +00001316
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001317static void null_grpc_log_function(gpr_log_func_args *args) {
1318}
1319
Lukacs Berki71675a52016-11-08 09:48:27 +00001320GrpcBlazeServer::GrpcBlazeServer(int connect_timeout_secs) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001321 connected_ = false;
Lukacs Berki71675a52016-11-08 09:48:27 +00001322 connect_timeout_secs_ = connect_timeout_secs;
1323
1324 gpr_set_log_function(null_grpc_log_function);
1325
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001326 _pipe = blaze_util::CreatePipe();
1327 if (_pipe == NULL) {
1328 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "Couldn't create pipe");
Lukacs Berki6dd29092016-05-30 14:05:33 +00001329 }
1330}
1331
1332GrpcBlazeServer::~GrpcBlazeServer() {
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001333 delete _pipe;
1334 _pipe = NULL;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001335}
1336
1337bool GrpcBlazeServer::Connect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001338 assert(!connected_);
1339
Julio Merino28774852016-09-14 16:59:46 +00001340 std::string server_dir = globals->options->output_base + "/server";
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001341 std::string port;
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001342 std::string ipv4_prefix = "127.0.0.1:";
Lukacs Berkic8e74242016-04-28 08:32:04 +00001343 std::string ipv6_prefix_1 = "[0:0:0:0:0:0:0:1]:";
1344 std::string ipv6_prefix_2 = "[::1]:";
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001345
Laszlo Csomor49970e02016-11-28 08:55:47 +00001346 if (!blaze_util::ReadFile(server_dir + "/command_port", &port)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001347 return false;
1348 }
1349
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001350 // Make sure that we are being directed to localhost
1351 if (port.compare(0, ipv4_prefix.size(), ipv4_prefix)
Lukacs Berkic8e74242016-04-28 08:32:04 +00001352 && port.compare(0, ipv6_prefix_1.size(), ipv6_prefix_1)
1353 && port.compare(0, ipv6_prefix_2.size(), ipv6_prefix_2)) {
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001354 return false;
1355 }
1356
Laszlo Csomor49970e02016-11-28 08:55:47 +00001357 if (!blaze_util::ReadFile(server_dir + "/request_cookie", &request_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001358 return false;
1359 }
1360
Laszlo Csomor49970e02016-11-28 08:55:47 +00001361 if (!blaze_util::ReadFile(server_dir + "/response_cookie",
1362 &response_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001363 return false;
1364 }
1365
1366 std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel(
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001367 port, grpc::InsecureChannelCredentials()));
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001368 std::unique_ptr<command_server::CommandServer::Stub> client(
1369 command_server::CommandServer::NewStub(channel));
1370
1371 grpc::ClientContext context;
1372 context.set_deadline(
Lukacs Berki71675a52016-11-08 09:48:27 +00001373 std::chrono::system_clock::now() +
1374 std::chrono::seconds(connect_timeout_secs_));
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001375
1376 command_server::PingRequest request;
1377 command_server::PingResponse response;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001378 request.set_cookie(request_cookie_);
Lukacs Berki7494c922016-04-27 11:17:51 +00001379
Lukacs Berki71675a52016-11-08 09:48:27 +00001380 debug_log("Trying to connect to server (timeout: %d secs)...",
1381 connect_timeout_secs_);
Lukacs Berki7e0249e2016-04-21 08:14:08 +00001382 grpc::Status status = client->Ping(&context, request, &response);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001383
Lukacs Berkic55e9c72016-04-25 13:43:40 +00001384 if (!status.ok() || response.cookie() != response_cookie_) {
Lukacs Berki71675a52016-11-08 09:48:27 +00001385 debug_log("Connection to server failed: %s",
1386 status.error_message().c_str());
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001387 return false;
1388 }
1389
Lukacs Berki1977d922016-05-02 09:31:37 +00001390 globals->server_pid = GetServerPid(server_dir);
1391 if (globals->server_pid <= 0) {
1392 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1393 "can't get PID of existing server (server dir=%s)",
1394 server_dir.c_str());
1395 }
1396
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001397 this->client_ = std::move(client);
Lukacs Berki1977d922016-05-02 09:31:37 +00001398 connected_ = true;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001399 return true;
1400}
1401
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001402// Cancellation works as follows:
1403//
1404// When the user presses Ctrl-C, a SIGINT is delivered to the client, which is
1405// translated into a BlazeServer::Cancel() call. Since it's not a good idea to
Lukacs Berki6dd29092016-05-30 14:05:33 +00001406// do significant work in signal handlers, all it does is write a byte to an
1407// unnamed pipe.
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001408//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001409// This unnamed pipe is used to communicate with the cancel thread. Whenever
1410// something interesting happens, a byte is written into it, which is read by
1411// the cancel thread. These commands are available:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001412//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001413// - NOP
1414// - JOIN. The cancel thread needs to be terminated.
1415// - CANCEL. If the command ID is already available, a cancel request is sent.
1416// - COMMAND_ID_RECEIVED. The client learned the command ID from the server.
1417// If there is a pending cancellation request, it is acted upon.
1418//
1419// The only data the cancellation thread shares with the main thread is the
1420// file descriptor for receiving commands and command_id_, the latter of which
1421// is protected by a mutex, which mainly serves as a memory fence.
1422//
1423// The cancellation thread is joined at the end of the execution of the command.
1424// The main thread wakes it up just so that it can finish (using the JOIN
1425// action)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001426//
1427// It's conceivable that the server is busy and thus it cannot service the
1428// cancellation request. In that case, we simply ignore the failure and the both
1429// the server and the client go on as if nothing had happened (except that this
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001430// Ctrl-C still counts as a SIGINT, three of which result in a SIGKILL being
1431// delivered to the server)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001432void GrpcBlazeServer::CancelThread() {
1433 bool running = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001434 bool cancel = false;
1435 bool command_id_received = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001436 while (running) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001437 char buf;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001438
1439 int bytes_read = _pipe->Receive(&buf, 1);
1440 if (bytes_read < 0 && errno == EINTR) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001441 continue;
1442 } else if (bytes_read != 1) {
1443 pdie(blaze_exit_code::INTERNAL_ERROR,
1444 "Cannot communicate with cancel thread");
1445 }
1446
1447 switch (buf) {
1448 case CancelThreadAction::NOTHING:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001449 break;
1450
Lukacs Berki6dd29092016-05-30 14:05:33 +00001451 case CancelThreadAction::JOIN:
1452 running = false;
1453 break;
1454
1455 case CancelThreadAction::COMMAND_ID_RECEIVED:
1456 command_id_received = true;
1457 if (cancel) {
1458 SendCancelMessage();
1459 cancel = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001460 }
1461 break;
1462
Lukacs Berki6dd29092016-05-30 14:05:33 +00001463 case CancelThreadAction::CANCEL:
1464 if (command_id_received) {
1465 SendCancelMessage();
1466 } else {
1467 cancel = true;
1468 }
1469 break;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001470 }
1471 }
1472}
1473
Lukacs Berki6dd29092016-05-30 14:05:33 +00001474void GrpcBlazeServer::SendCancelMessage() {
1475 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
1476
1477 command_server::CancelRequest request;
1478 request.set_cookie(request_cookie_);
1479 request.set_command_id(command_id_);
1480 grpc::ClientContext context;
1481 context.set_deadline(std::chrono::system_clock::now() +
Lukacs Berki3ace3002016-08-31 08:55:34 +00001482 std::chrono::seconds(10));
Lukacs Berki6dd29092016-05-30 14:05:33 +00001483 command_server::CancelResponse response;
1484 // There isn't a lot we can do if this request fails
Lukacs Berki3ace3002016-08-31 08:55:34 +00001485 grpc::Status status = client_->Cancel(&context, request, &response);
1486 if (!status.ok()) {
1487 fprintf(stderr, "\nCould not interrupt server (%s)\n\n",
1488 status.error_message().c_str());
1489 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001490}
1491
Lukacs Berki1977d922016-05-02 09:31:37 +00001492// This will wait indefinitely until the server shuts down
1493void GrpcBlazeServer::KillRunningServer() {
1494 assert(connected_);
1495 assert(globals->server_pid > 0);
1496
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001497 grpc::ClientContext context;
1498 command_server::RunRequest request;
1499 command_server::RunResponse response;
1500 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001501 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001502 request.set_client_description("pid=" + blaze::GetProcessIdAsString() +
1503 " (for shutdown)");
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001504 request.add_arg("shutdown");
1505 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
1506 client_->Run(&context, request));
1507
1508 while (reader->Read(&response)) {}
1509
Lukacs Berki1977d922016-05-02 09:31:37 +00001510 // Kill the server process for good measure.
Julio Merino28774852016-09-14 16:59:46 +00001511 if (VerifyServerProcess(globals->server_pid, globals->options->output_base,
1512 globals->options->install_base)) {
Lukacs Berkiee44c382016-09-14 10:53:37 +00001513 KillServerProcess(globals->server_pid);
1514 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001515
1516 connected_ = false;
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001517}
1518
1519unsigned int GrpcBlazeServer::Communicate() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001520 assert(connected_);
1521
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001522 vector<string> arg_vector;
Julio Merino28774852016-09-14 16:59:46 +00001523 string command = globals->option_processor->GetCommand();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001524 if (command != "") {
1525 arg_vector.push_back(command);
1526 AddLoggingArgs(&arg_vector);
1527 }
1528
Julio Merino28774852016-09-14 16:59:46 +00001529 globals->option_processor->GetCommandArguments(&arg_vector);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001530
1531 command_server::RunRequest request;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001532 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001533 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001534 request.set_client_description("pid=" + blaze::GetProcessIdAsString());
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001535 for (const string& arg : arg_vector) {
1536 request.add_arg(arg);
1537 }
1538
1539 grpc::ClientContext context;
1540 command_server::RunResponse response;
1541 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001542 client_->Run(&context, request));
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001543
Lukacs Berki415d39a2016-04-28 13:18:54 +00001544 // Release the server lock because the gRPC handles concurrent clients just
1545 // fine. Note that this may result in two "waiting for other client" messages
1546 // (one during server startup and one emitted by the server)
Lukacs Berki1977d922016-05-02 09:31:37 +00001547 blaze::ReleaseLock(&blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +00001548
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001549 std::thread cancel_thread(&GrpcBlazeServer::CancelThread, this);
1550 bool command_id_set = false;
Laurent Le Brun08849b22016-09-20 12:21:32 +00001551 bool pipe_broken = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001552 while (reader->Read(&response)) {
Lukacs Berkic55e9c72016-04-25 13:43:40 +00001553 if (response.cookie() != response_cookie_) {
1554 fprintf(stderr, "\nServer response cookie invalid, exiting\n");
1555 return blaze_exit_code::INTERNAL_ERROR;
1556 }
1557
Laurent Le Brun08849b22016-09-20 12:21:32 +00001558 bool pipe_broken_now = false;
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001559
1560 if (!response.standard_output().empty()) {
1561 size_t size = response.standard_output().size();
1562 size_t r = fwrite(response.standard_output().c_str(), 1, size, stdout);
1563 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001564 pipe_broken_now = true;
1565 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001566 }
1567
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001568 if (!response.standard_error().empty()) {
1569 size_t size = response.standard_error().size();
1570 size_t r = fwrite(response.standard_error().c_str(), 1, size, stderr);
1571 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001572 pipe_broken_now = true;
1573 }
1574 }
1575
1576 if (pipe_broken_now && !pipe_broken) {
1577 pipe_broken = true;
1578 Cancel();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001579 }
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001580
1581 if (!command_id_set && response.command_id().size() > 0) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001582 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001583 command_id_ = response.command_id();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001584 command_id_set = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001585 SendAction(CancelThreadAction::COMMAND_ID_RECEIVED);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001586 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001587 }
1588
Lukacs Berki6dd29092016-05-30 14:05:33 +00001589 SendAction(CancelThreadAction::JOIN);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001590 cancel_thread.join();
1591
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001592 if (!response.finished()) {
Lukacs Berki3ace3002016-08-31 08:55:34 +00001593 fprintf(stderr, "\nServer finished RPC without an explicit exit code\n\n");
Lukacs Berki2896dc02016-07-07 07:55:04 +00001594 return GetExitCodeForAbruptExit(*globals);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001595 }
1596
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001597 return response.exit_code();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001598}
1599
1600void GrpcBlazeServer::Disconnect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001601 assert(connected_);
1602
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001603 client_.reset();
1604 request_cookie_ = "";
1605 response_cookie_ = "";
Lukacs Berki1977d922016-05-02 09:31:37 +00001606 connected_ = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001607}
1608
Lukacs Berki6dd29092016-05-30 14:05:33 +00001609void GrpcBlazeServer::SendAction(CancelThreadAction action) {
1610 char msg = action;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001611 if (!_pipe->Send(&msg, 1)) {
Laszlo Csomor3b89d2d2016-11-28 14:04:27 +00001612 blaze::SigPrintf(
1613 "\nCould not interrupt server (cannot write to client pipe)\n\n");
Sasha Smundak1fdd31d2016-07-25 17:54:00 +00001614 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001615}
1616
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001617void GrpcBlazeServer::Cancel() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001618 assert(connected_);
Lukacs Berki6dd29092016-05-30 14:05:33 +00001619 SendAction(CancelThreadAction::CANCEL);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001620}
1621
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001622} // namespace blaze