blob: 96d6b4e7e74a9a2e70e76f21fb9adcfe9631b38b [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>
39#include <unistd.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000040
41#include <grpc/grpc.h>
Googler197547b2016-09-26 22:25:14 +000042#include <grpc/support/log.h>
Lukacs Berkie21e5922016-04-12 12:22:20 +000043#include <grpc++/channel.h>
44#include <grpc++/client_context.h>
45#include <grpc++/create_channel.h>
46#include <grpc++/security/credentials.h>
47
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010048#include <algorithm>
Lukacs Berki1b25ce22016-04-15 13:11:21 +000049#include <chrono> // NOLINT (gRPC requires this)
Lukacs Berkif1df38a2016-04-19 07:42:22 +000050#include <mutex> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010051#include <set>
52#include <string>
Lukacs Berkif1df38a2016-04-19 07:42:22 +000053#include <thread> // NOLINT
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010054#include <utility>
55#include <vector>
56
Lukacs Berkie21e5922016-04-12 12:22:20 +000057
Nathan Harmatabf98f392016-01-07 22:58:29 +000058#include "src/main/cpp/blaze_abrupt_exit.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000059#include "src/main/cpp/blaze_util.h"
60#include "src/main/cpp/blaze_util_platform.h"
Thiago Farina676cb9f2016-10-06 11:00:43 +000061#include "src/main/cpp/global_variables.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000062#include "src/main/cpp/option_processor.h"
Julio Merino28774852016-09-14 16:59:46 +000063#include "src/main/cpp/startup_options.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000064#include "src/main/cpp/util/errors.h"
Thiago Farina7f9357f2015-04-23 13:57:43 +000065#include "src/main/cpp/util/exit_code.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000066#include "src/main/cpp/util/file.h"
Laszlo Csomor9c951962016-11-10 13:31:27 +000067#include "src/main/cpp/util/file_platform.h"
Chloe Calvarin78f1c852016-11-22 21:58:50 +000068#include "src/main/cpp/util/logging.h"
Han-Wen Nienhuys36fbe632015-04-21 13:58:08 +000069#include "src/main/cpp/util/numbers.h"
70#include "src/main/cpp/util/port.h"
71#include "src/main/cpp/util/strings.h"
Julio Merino211a95c2016-08-29 11:01:35 +000072#include "src/main/cpp/workspace_layout.h"
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +000073#include "third_party/ijar/zip.h"
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010074
Lukacs Berkie21e5922016-04-12 12:22:20 +000075#include "src/main/protobuf/command_server.grpc.pb.h"
76
Thiago Farina241f46c2015-04-13 14:33:30 +000077using blaze_util::die;
78using blaze_util::pdie;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010079
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010080namespace blaze {
81
Thiago Farina80bb0f22016-10-17 15:57:13 +000082using std::set;
83using std::string;
84using std::vector;
85
Lukacs Berki1977d922016-05-02 09:31:37 +000086static int GetServerPid(const string &server_dir);
Eric Fellheimer3a695f32016-05-11 17:26:30 +000087static void VerifyJavaVersionAndSetJvm();
Lukacs Berki907dbbf2016-04-15 11:30:12 +000088
Lukacs Berki1977d922016-05-02 09:31:37 +000089// The following is a treatise on how the interaction between the client and the
90// server works.
91//
92// First, the client unconditionally acquires an flock() lock on
93// $OUTPUT_BASE/lock then verifies if it has already extracted itself by
94// checking if the directory it extracts itself to (install base + a checksum)
95// is present. If not, then it does the extraction. Care is taken that this
96// process is atomic so that Blazen in multiple output bases do not clash.
97//
98// Then the client tries to connect to the currently executing server and kills
99// it if at least one of the following conditions is true:
100//
101// - The server is of the wrong version (as determined by the
102// $OUTPUT_BASE/install symlink)
103// - The server has different startup options than the client wants
104// - The client wants to run the command in batch mode
105//
106// Then, if needed, the client adjusts the install link to indicate which
107// version of the server it is running.
108//
109// In batch mode, the client then simply executes the server while taking care
110// that the output base lock is kept until it finishes.
111//
112// If in server mode, the client starts up a server if needed then sends the
Thiago Farina69dac862016-11-02 09:48:27 +0000113// command to the client and streams back stdout and stderr. The output base
114// lock is released after the command is sent to the server (the server
115// implements its own locking mechanism).
Lukacs Berki1977d922016-05-02 09:31:37 +0000116
117// Synchronization between the client and the server is a little precarious
118// because the client needs to know the PID of the server and it is not
119// available using a Java API and we don't have JNI on Windows at the moment,
120// so the server can't just communicate this over the communication channel.
121// Thus, a PID file is used, but care needs to be taken that the contents of
122// this PID file are right.
123//
124// Upon server startup, the PID file is written before the client spawns the
125// server. Thus, when the client can connect, it can be certain that the PID
126// file is up to date.
127//
128// Upon server shutdown, the PID file is deleted using a server shutdown hook.
129// However, this happens *after* the server stopped listening, so it's possible
130// that a client has already started up a server and written a new PID file.
131// In order to avoid this, when the client starts up a new server, it reads the
132// contents of the PID file and kills the process indicated in it (it could do
133// with a bit more care, since PIDs can be reused, but for now, we just believe
134// the PID file)
135//
136// Some more interesting scenarios:
137//
138// - The server receives a kill signal and it does not have a chance to delete
139// the PID file: the client cannot connect, reads the PID file, kills the
140// process indicated in it and starts up a new server.
141//
142// - The server stopped accepting connections but hasn't quit yet and a new
143// client comes around: the new client will kill the server based on the
144// PID file before a new server is started up.
145//
146// Alternative implementations:
147//
148// - Don't deal with PIDs at all. This would make it impossible for the client
149// to deliver a SIGKILL to the server after three SIGINTs. It would only be
150// possible with gRPC anyway.
151//
152// - Have the server check that the PID file containts the correct things
153// before deleting them: there is a window of time between checking the file
154// and deleting it in which a new server can overwrite the PID file. The
155// output base lock cannot be acquired, either, because when starting up a
156// new server, the client already holds it.
157//
158// - Delete the PID file before stopping to accept connections: then a client
159// could come about after deleting the PID file but before stopping accepting
160// connections. It would also not be resilient against a dead server that
161// left a PID file around.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000162class BlazeServer {
163 public:
164 virtual ~BlazeServer() {}
165
Lukacs Berki1977d922016-05-02 09:31:37 +0000166 // Acquire a lock for the server running in this output base. Returns the
167 // number of milliseconds spent waiting for the lock.
Lukacs Berki415d39a2016-04-28 13:18:54 +0000168 uint64_t AcquireLock();
169
Lukacs Berki1977d922016-05-02 09:31:37 +0000170 // Whether there is an active connection to a server.
171 bool Connected() const { return connected_; }
172
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000173 // Connect to the server. Returns if the connection was successful. Only
174 // call this when this object is in disconnected state. If it returns true,
175 // this object will be in connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000176 virtual bool Connect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000177
178 // Disconnects from an existing server. Only call this when this object is in
179 // connected state. After this call returns, the object will be in connected
180 // state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000181 virtual void Disconnect() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000182
183 // Send the command line to the server and forward whatever it says to stdout
184 // and stderr. Returns the desired exit code. Only call this when the server
185 // is in connected state.
186 virtual unsigned int Communicate() = 0;
187
188 // Disconnects and kills an existing server. Only call this when this object
189 // is in connected state.
Lukacs Berki1977d922016-05-02 09:31:37 +0000190 virtual void KillRunningServer() = 0;
Lukacs Berkie6a34f62016-04-25 12:16:04 +0000191
192 // Cancel the currently running command. If there is no command currently
Lukacs Berki1977d922016-05-02 09:31:37 +0000193 // running, the result is unspecified. When called, this object must be in
194 // connected state.
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000195 virtual void Cancel() = 0;
Thiago Farina69dac862016-11-02 09:48:27 +0000196
197 protected:
198 BlazeLock blaze_lock_;
199 bool connected_;
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000200};
201
Lukacs Berki415d39a2016-04-28 13:18:54 +0000202////////////////////////////////////////////////////////////////////////
203// Global Variables
204static GlobalVariables *globals;
205static BlazeServer *blaze_server;
206
Laszlo Csomor32086b22016-11-24 15:23:55 +0000207// TODO(laszlocsomor) 2016-11-24: release the `globals` and `blaze_server`
208// objects. Currently nothing deletes them. Be careful that some functions may
209// call exit(2) or _exit(2) (attributed with ATTRIBUTE_NORETURN) meaning we have
210// to delete the objects before those.
211
Lukacs Berki415d39a2016-04-28 13:18:54 +0000212uint64_t BlazeServer::AcquireLock() {
213 return blaze::AcquireLock(
Julio Merino28774852016-09-14 16:59:46 +0000214 globals->options->output_base, globals->options->batch,
215 globals->options->block_for_lock, &blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +0000216}
217
Lukacs Berki1977d922016-05-02 09:31:37 +0000218// Communication method that uses gRPC on a socket bound to localhost. More
219// documentation is in command_server.proto .
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000220class GrpcBlazeServer : public BlazeServer {
221 public:
Lukacs Berki71675a52016-11-08 09:48:27 +0000222 GrpcBlazeServer(int connect_timeout_secs);
Lukacs Berki6dd29092016-05-30 14:05:33 +0000223 virtual ~GrpcBlazeServer();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000224
Lukacs Berki9d52bc52016-06-07 11:11:04 +0000225 virtual bool Connect();
226 virtual void Disconnect();
227 virtual unsigned int Communicate();
228 virtual void KillRunningServer();
229 virtual void Cancel();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000230
231 private:
Lukacs Berki6dd29092016-05-30 14:05:33 +0000232 enum CancelThreadAction { NOTHING, JOIN, CANCEL, COMMAND_ID_RECEIVED };
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000233
234 std::unique_ptr<command_server::CommandServer::Stub> client_;
235 std::string request_cookie_;
236 std::string response_cookie_;
237 std::string command_id_;
238
Lukacs Berki6dd29092016-05-30 14:05:33 +0000239 // protects command_id_ . Although we always set it before making the cancel
240 // thread do something with it, the mutex is still useful because it provides
241 // a memory fence.
242 std::mutex cancel_thread_mutex_;
Lukacs Berki8b999982016-04-26 15:40:38 +0000243
Lukacs Berki71675a52016-11-08 09:48:27 +0000244 int connect_timeout_secs_;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +0000245
246 // Pipe that the main thread sends actions to and the cancel thread receieves
247 // actions from.
248 blaze_util::IPipe* _pipe;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000249
250 void CancelThread();
Lukacs Berki6dd29092016-05-30 14:05:33 +0000251 void SendAction(CancelThreadAction action);
252 void SendCancelMessage();
Lukacs Berki00cfb7d2016-04-20 09:01:52 +0000253};
254
255
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100256////////////////////////////////////////////////////////////////////////
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100257// Logic
258
Lukacs Berki71675a52016-11-08 09:48:27 +0000259void debug_log(const char* format, ...) {
260 if (!globals->options->client_debug) {
261 return;
262 }
263
264 fprintf(stderr, "CLIENT: ");
265 va_list arglist;
266 va_start(arglist, format);
267 vfprintf(stderr, format, arglist);
268 va_end(arglist);
269 fprintf(stderr, "%s", "\n");
270 fflush(stderr);
271}
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100272
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000273// A devtools_ijar::ZipExtractorProcessor to extract the InstallKeyFile
274class GetInstallKeyFileProcessor : public devtools_ijar::ZipExtractorProcessor {
275 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000276 explicit GetInstallKeyFileProcessor(string *install_base_key)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000277 : install_base_key_(install_base_key) {}
278
279 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
280 globals->extracted_binaries.push_back(filename);
281 return strcmp(filename, "install_base_key") == 0;
282 }
283
284 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
285 const devtools_ijar::u1 *data, const size_t size) {
286 string str(reinterpret_cast<const char *>(data), size);
287 blaze_util::StripWhitespace(&str);
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000288 if (str.size() != 32) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000289 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Lukacs Berki58c29ae2015-10-16 14:48:33 +0000290 "\nFailed to extract install_base_key: file size mismatch "
291 "(should be 32, is %zd)", str.size());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000292 }
293 *install_base_key_ = str;
294 }
295
296 private:
297 string *install_base_key_;
298};
299
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100300// Returns the install base (the root concatenated with the contents of the file
301// 'install_base_key' contained as a ZIP entry in the Blaze binary); as a side
302// effect, it also populates the extracted_binaries global variable.
303static string GetInstallBase(const string &root, const string &self_path) {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000304 GetInstallKeyFileProcessor processor(&globals->install_md5);
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000305 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
306 devtools_ijar::ZipExtractor::Create(self_path.c_str(), &processor));
307 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100308 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000309 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000310 globals->options->product_name.c_str(), errno, strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100311 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000312 if (extractor->ProcessAll() < 0) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100313 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000314 "\nFailed to extract install_base_key: %s", extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100315 }
316
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000317 if (globals->install_md5.empty()) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000318 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
319 "\nFailed to find install_base_key's in zip file");
320 }
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000321 return root + "/" + globals->install_md5;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100322}
323
324// Escapes colons by replacing them with '_C' and underscores by replacing them
325// with '_U'. E.g. "name:foo_bar" becomes "name_Cfoo_Ubar"
326static string EscapeForOptionSource(const string& input) {
327 string result = input;
328 blaze_util::Replace("_", "_U", &result);
329 blaze_util::Replace(":", "_C", &result);
330 return result;
331}
332
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000333// Returns the installed embedded binaries directory, under the shared
334// install_base location.
335string GetEmbeddedBinariesRoot(const string &install_base) {
336 return blaze_util::JoinPath(install_base, "_embedded_binaries");
337}
338
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100339// Returns the JVM command argument array.
340static vector<string> GetArgumentArray() {
341 vector<string> result;
342
343 // e.g. A Blaze server process running in ~/src/build_root (where there's a
344 // ~/src/build_root/WORKSPACE file) will appear in ps(1) as "blaze(src)".
345 string workspace =
346 blaze_util::Basename(blaze_util::Dirname(globals->workspace));
Julio Merino28774852016-09-14 16:59:46 +0000347 string product = globals->options->product_name;
Kristina Chodorow11d40d22015-03-17 18:26:59 +0000348 blaze_util::ToLower(&product);
349 result.push_back(product + "(" + workspace + ")");
Julio Merino28774852016-09-14 16:59:46 +0000350 globals->options->AddJVMArgumentPrefix(
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000351 blaze_util::Dirname(blaze_util::Dirname(globals->jvm_path)),
352 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100353
354 result.push_back("-XX:+HeapDumpOnOutOfMemoryError");
Julio Merino28774852016-09-14 16:59:46 +0000355 string heap_crash_path = globals->options->output_base;
Dmitry Lomov7608db52016-07-14 11:27:10 +0000356 result.push_back("-XX:HeapDumpPath=" + ConvertPath(heap_crash_path));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100357
358 result.push_back("-Xverify:none");
359
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000360 vector<string> user_options;
361
Janak Ramakrishnan0acd1542016-01-06 18:42:30 +0000362 user_options.insert(user_options.begin(),
Julio Merino28774852016-09-14 16:59:46 +0000363 globals->options->host_jvm_args.begin(),
364 globals->options->host_jvm_args.end());
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000365
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100366 // Add JVM arguments particular to building blaze64 and particular JVM
367 // versions.
368 string error;
369 blaze_exit_code::ExitCode jvm_args_exit_code =
Julio Merino28774852016-09-14 16:59:46 +0000370 globals->options->AddJVMArguments(globals->options->GetHostJavabase(),
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000371 &result, user_options, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100372 if (jvm_args_exit_code != blaze_exit_code::SUCCESS) {
373 die(jvm_args_exit_code, "%s", error.c_str());
374 }
375
Julio Merino28774852016-09-14 16:59:46 +0000376 if (globals->options->batch && globals->options->oom_more_eagerly) {
Janak Ramakrishnan70c57902016-03-10 00:58:59 +0000377 // Put this OOM trigger with kill after --host_jvm_args, in case
378 // --host_jvm_args contains user-specified OOM triggers since we want those
379 // to execute first.
380 result.push_back("-XX:OnOutOfMemoryError=kill -USR2 %p");
381 }
382
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100383 // We put all directories on the java.library.path that contain .so files.
384 string java_library_path = "-Djava.library.path=";
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000385 string real_install_dir =
386 GetEmbeddedBinariesRoot(globals->options->install_base);
387
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100388 bool first = true;
389 for (const auto& it : globals->extracted_binaries) {
Thiago Farina01f36002015-04-08 15:59:08 +0000390 if (IsSharedLibrary(it)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100391 if (!first) {
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000392 java_library_path += blaze::ListSeparator();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100393 }
394 first = false;
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000395 java_library_path += blaze::ConvertPath(
396 blaze_util::JoinPath(real_install_dir, blaze_util::Dirname(it)));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100397 }
398 }
399 result.push_back(java_library_path);
400
401 // Force use of latin1 for file names.
402 result.push_back("-Dfile.encoding=ISO-8859-1");
403
Julio Merino28774852016-09-14 16:59:46 +0000404 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100405 fprintf(stderr,
406 "Running host JVM under debugger (listening on TCP port 5005).\n");
407 // Start JVM so that it listens for a connection from a
408 // JDWP-compliant debugger:
409 result.push_back("-Xdebug");
410 result.push_back("-Xrunjdwp:transport=dt_socket,server=y,address=5005");
411 }
Janak Ramakrishnande735c02015-06-02 16:38:57 +0000412 result.insert(result.end(), user_options.begin(), user_options.end());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100413
Julio Merino28774852016-09-14 16:59:46 +0000414 globals->options->AddJVMArgumentSuffix(real_install_dir,
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000415 globals->extracted_binaries[0],
416 &result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100417
Lukacs Berki3d486832016-10-26 12:51:38 +0000418 // JVM arguments are complete. Now pass in Blaze startup options.
419 // Note that we always use the --flag=ARG form (instead of the --flag ARG one)
420 // so that BlazeRuntime#splitStartupOptions has an easy job.
Lukacs Berki71675a52016-11-08 09:48:27 +0000421
422 // TODO(lberki): Test that whatever the list constructed after this line is
423 // actually a list of parseable startup options.
Julio Merino28774852016-09-14 16:59:46 +0000424 if (!globals->options->batch) {
Lukacs Berki3d486832016-10-26 12:51:38 +0000425 result.push_back("--max_idle_secs=" +
426 ToString(globals->options->max_idle_secs));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100427 } else {
Googlerc8c64e72015-03-23 23:22:18 +0000428 // --batch must come first in the arguments to Java main() because
429 // the code expects it to be at args[0] if it's been set.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100430 result.push_back("--batch");
431 }
Lukacs Berkice1445f2016-04-19 15:52:55 +0000432
Julio Merino28774852016-09-14 16:59:46 +0000433 if (globals->options->command_port != 0) {
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000434 result.push_back(
Julio Merino28774852016-09-14 16:59:46 +0000435 "--command_port=" + ToString(globals->options->command_port));
Lukacs Berkice1445f2016-04-19 15:52:55 +0000436 }
437
Lukacs Berki71675a52016-11-08 09:48:27 +0000438 result.push_back(
439 "--connect_timeout_secs=" +
440 ToString(globals->options->connect_timeout_secs));
441
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000442 result.push_back("--install_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000443 blaze::ConvertPath(globals->options->install_base));
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +0000444 result.push_back("--install_md5=" + globals->install_md5);
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000445 result.push_back("--output_base=" +
Julio Merino28774852016-09-14 16:59:46 +0000446 blaze::ConvertPath(globals->options->output_base));
Dmitry Lomov78c0cc72015-08-11 16:44:21 +0000447 result.push_back("--workspace_directory=" +
448 blaze::ConvertPath(globals->workspace));
Marian Lobur6dcdd602015-04-09 09:28:40 +0000449
Julio Merino28774852016-09-14 16:59:46 +0000450 if (globals->options->allow_configurable_attributes) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100451 result.push_back("--allow_configurable_attributes");
452 }
Julio Merino28774852016-09-14 16:59:46 +0000453 if (globals->options->deep_execroot) {
Lukacs Berki5fb98d12015-12-09 15:29:46 +0000454 result.push_back("--deep_execroot");
455 } else {
456 result.push_back("--nodeep_execroot");
457 }
Julio Merino28774852016-09-14 16:59:46 +0000458 if (globals->options->oom_more_eagerly) {
Janak Ramakrishnanadc706f2016-03-07 19:12:48 +0000459 result.push_back("--experimental_oom_more_eagerly");
460 }
Janak Ramakrishnan19fde1f2016-05-23 21:20:16 +0000461 result.push_back("--experimental_oom_more_eagerly_threshold=" +
Julio Merino28774852016-09-14 16:59:46 +0000462 ToString(globals->options->oom_more_eagerly_threshold));
Janak Ramakrishnan8cc772e2016-03-23 17:26:12 +0000463
Michajlo Matijkiwaf79a322016-09-16 15:44:35 +0000464 if (!globals->options->write_command_log) {
465 result.push_back("--nowrite_command_log");
466 }
467
Julio Merino28774852016-09-14 16:59:46 +0000468 if (globals->options->watchfs) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100469 result.push_back("--watchfs");
470 }
Julio Merino28774852016-09-14 16:59:46 +0000471 if (globals->options->fatal_event_bus_exceptions) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100472 result.push_back("--fatal_event_bus_exceptions");
473 } else {
474 result.push_back("--nofatal_event_bus_exceptions");
475 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100476
Lukacs Berki71675a52016-11-08 09:48:27 +0000477 // We use this syntax so that the logic in ServerNeedsToBeKilled() that
478 // decides whether the server needs killing is simpler. This is parsed by the
479 // Java code where --noclient_debug and --client_debug=false are equivalent.
480 // Note that --client_debug false (separated by space) won't work either,
481 // because the logic in ServerNeedsToBeKilled() assumes that every argument
482 // is in the --arg=value form.
483 if (globals->options->client_debug) {
484 result.push_back("--client_debug=true");
485 } else {
486 result.push_back("--client_debug=false");
487 }
488
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100489 // This is only for Blaze reporting purposes; the real interpretation of the
490 // jvm flags occurs when we set up the java command line.
Julio Merino28774852016-09-14 16:59:46 +0000491 if (globals->options->host_jvm_debug) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100492 result.push_back("--host_jvm_debug");
493 }
Julio Merino28774852016-09-14 16:59:46 +0000494 if (!globals->options->host_jvm_profile.empty()) {
495 result.push_back("--host_jvm_profile=" +
496 globals->options->host_jvm_profile);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100497 }
Julio Merino28774852016-09-14 16:59:46 +0000498 if (!globals->options->host_jvm_args.empty()) {
499 for (const auto &arg : globals->options->host_jvm_args) {
Janak Ramakrishnan533657e2015-11-13 23:34:14 +0000500 result.push_back("--host_jvm_args=" + arg);
501 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100502 }
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000503
Julio Merino28774852016-09-14 16:59:46 +0000504 if (globals->options->invocation_policy != NULL &&
505 strlen(globals->options->invocation_policy) > 0) {
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000506 result.push_back(string("--invocation_policy=") +
Julio Merino28774852016-09-14 16:59:46 +0000507 globals->options->invocation_policy);
Alex Humesky2f3f4cf2015-09-29 01:42:00 +0000508 }
509
Julio Merino28774852016-09-14 16:59:46 +0000510 result.push_back("--product_name=" + globals->options->product_name);
Luis Fernando Pino Duque623cdf82016-05-31 16:21:46 +0000511
Julio Merino28774852016-09-14 16:59:46 +0000512 globals->options->AddExtraOptions(&result);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100513
514 // The option sources are transmitted in the following format:
515 // --option_sources=option1:source1:option2:source2:...
516 string option_sources = "--option_sources=";
517 first = true;
Julio Merino28774852016-09-14 16:59:46 +0000518 for (const auto& it : globals->options->option_sources) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100519 if (!first) {
520 option_sources += ":";
521 }
522
523 first = false;
524 option_sources += EscapeForOptionSource(it.first) + ":" +
525 EscapeForOptionSource(it.second);
526 }
527
528 result.push_back(option_sources);
529 return result;
530}
531
Thiago Farina5735c252016-04-27 16:16:27 +0000532// Add common command options for logging to the given argument array.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100533static void AddLoggingArgs(vector<string>* args) {
Googler9588b812015-07-23 11:49:37 +0000534 args->push_back("--startup_time=" + ToString(globals->startup_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100535 if (globals->command_wait_time != 0) {
536 args->push_back("--command_wait_time=" +
Googler9588b812015-07-23 11:49:37 +0000537 ToString(globals->command_wait_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100538 }
539 if (globals->extract_data_time != 0) {
540 args->push_back("--extract_data_time=" +
Googler9588b812015-07-23 11:49:37 +0000541 ToString(globals->extract_data_time));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100542 }
543 if (globals->restart_reason != NO_RESTART) {
544 const char *reasons[] = {
545 "no_restart", "no_daemon", "new_version", "new_options"
546 };
547 args->push_back(
548 string("--restart_reason=") + reasons[globals->restart_reason]);
549 }
550 args->push_back(
551 string("--binary_path=") + globals->binary_path);
552}
553
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100554// Join the elements of the specified array with NUL's (\0's), akin to the
555// format of /proc/$PID/cmdline.
Thiago Farina0b6963e2015-04-28 20:26:45 +0000556static string GetArgumentString(const vector<string>& argument_array) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100557 string result;
558 blaze_util::JoinStrings(argument_array, '\0', &result);
559 return result;
560}
561
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100562// Do a chdir into the workspace, and die if it fails.
563static void GoToWorkspace() {
Julio Merino211a95c2016-08-29 11:01:35 +0000564 if (WorkspaceLayout::InWorkspace(globals->workspace) &&
Laszlo Csomor9c951962016-11-10 13:31:27 +0000565 !blaze_util::ChangeDirectory(globals->workspace)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100566 pdie(blaze_exit_code::INTERNAL_ERROR,
Laszlo Csomor9c951962016-11-10 13:31:27 +0000567 "changing directory into %s failed", globals->workspace.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100568 }
569}
570
571// Check the java version if a java version specification is bundled. On
Thiago Farina5735c252016-04-27 16:16:27 +0000572// success, returns the executable path of the java command.
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000573static void VerifyJavaVersionAndSetJvm() {
Julio Merino28774852016-09-14 16:59:46 +0000574 string exe = globals->options->GetJvm();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100575
576 string version_spec_file = blaze_util::JoinPath(
Thiago Farina6a2dc2b2016-10-28 13:05:22 +0000577 GetEmbeddedBinariesRoot(globals->options->install_base), "java.version");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100578 string version_spec = "";
579 if (ReadFile(version_spec_file, &version_spec)) {
580 blaze_util::StripWhitespace(&version_spec);
581 // A version specification is given, get version of java.
582 string jvm_version = GetJvmVersion(exe);
583
584 // Compare that jvm_version is found and at least the one specified.
585 if (jvm_version.size() == 0) {
586 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
587 "Java version not detected while at least %s is needed.\n"
588 "Please set JAVA_HOME.", version_spec.c_str());
589 } else if (!CheckJavaVersionIsAtLeast(jvm_version, version_spec)) {
590 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
591 "Java version is %s while at least %s is needed.\n"
592 "Please set JAVA_HOME.",
593 jvm_version.c_str(), version_spec.c_str());
594 }
595 }
596
Eric Fellheimer3a695f32016-05-11 17:26:30 +0000597 globals->jvm_path = exe;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100598}
599
600// Starts the Blaze server. Returns a readable fd connected to the server.
601// This is currently used only to detect liveness.
Lukacs Berki1977d922016-05-02 09:31:37 +0000602static void StartServer(BlazeServerStartup** server_startup) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100603 vector<string> jvm_args_vector = GetArgumentArray();
604 string argument_string = GetArgumentString(jvm_args_vector);
Julio Merino28774852016-09-14 16:59:46 +0000605 string server_dir = globals->options->output_base + "/server";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100606 // Write the cmdline argument string to the server dir. If we get to this
607 // point, there is no server running, so we don't overwrite the cmdline file
608 // for the existing server. If might be that the server dies and the cmdline
609 // file stays there, but that is not a problem, since we always check the
610 // server, too.
Lukacs Berki5a781662016-04-25 11:17:31 +0000611 WriteFile(argument_string, server_dir + "/cmdline");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100612
613 // unless we restarted for a new-version, mark this as initial start
614 if (globals->restart_reason == NO_RESTART) {
615 globals->restart_reason = NO_DAEMON;
616 }
617
Julio Merino28774852016-09-14 16:59:46 +0000618 string exe = globals->options->GetExe(globals->jvm_path,
619 globals->extracted_binaries[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100620 // Go to the workspace before we daemonize, so
621 // we can still print errors to the terminal.
622 GoToWorkspace();
623
Lukacs Berki1977d922016-05-02 09:31:37 +0000624 ExecuteDaemon(exe, jvm_args_vector, globals->jvm_log_file.c_str(),
625 server_dir, server_startup);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100626}
627
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100628// Replace this process with blaze in standalone/batch mode.
629// The batch mode blaze process handles the command and exits.
630//
631// This function passes the commands array to the blaze process.
632// This array should start with a command ("build", "info", etc.).
Lukacs Berki907dbbf2016-04-15 11:30:12 +0000633static void StartStandalone(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
670 GoToWorkspace();
671
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 Csomor6450c182016-11-24 10:28:20 +0000704 if (!blaze::ReadFile(pid_file, &bufstr, 32) ||
705 !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.
713static void StartServerAndConnect(BlazeServer *server) {
Julio Merino28774852016-09-14 16:59:46 +0000714 string server_dir = globals->options->output_base + "/server";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100715
716 // The server dir has the socket, so we don't allow access by other
717 // users.
Laszlo Csomorcefa9a22016-11-22 10:50:07 +0000718 if (!MakeDirectories(server_dir, 0700)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100719 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
720 "server directory '%s' could not be created", server_dir.c_str());
721 }
722
Laszlo Csomor6450c182016-11-24 10:28:20 +0000723 // TODO(laszlocsomor) 2016-11-21: remove `pid_symlink` and the `remove` call
724 // after 2017-05-01 (~half a year from writing this comment). By that time old
725 // Bazel clients that used to write PID symlinks will probably no longer be in
726 // use.
727 // Until then, defensively delete old PID symlinks that older clients may have
728 // left behind.
729 string pid_symlink = blaze_util::JoinPath(server_dir, kServerPidSymlink);
730 remove(pid_symlink.c_str());
731
Lukacs Berki1977d922016-05-02 09:31:37 +0000732 // If we couldn't connect to the server check if there is still a PID file
733 // and if so, kill the server that wrote it. This can happen e.g. if the
734 // server is in a GC pause and therefore cannot respond to ping requests and
735 // having two server instances running in the same output base is a
736 // disaster.
737 int server_pid = GetServerPid(server_dir);
738 if (server_pid > 0) {
Julio Merino28774852016-09-14 16:59:46 +0000739 if (VerifyServerProcess(server_pid, globals->options->output_base,
740 globals->options->install_base) &&
Lukacs Berkiee44c382016-09-14 10:53:37 +0000741 KillServerProcess(server_pid)) {
Lukacs Berki119dd4b2016-07-13 15:28:42 +0000742 fprintf(stderr, "Killed non-responsive server process (pid=%d)\n",
743 server_pid);
744 }
Lukacs Berki7e0249e2016-04-21 08:14:08 +0000745 }
746
Julio Merino28774852016-09-14 16:59:46 +0000747 SetScheduling(globals->options->batch_cpu_scheduling,
748 globals->options->io_nice_level);
Lukacs Berkif1df38a2016-04-19 07:42:22 +0000749
Lukacs Berki1977d922016-05-02 09:31:37 +0000750 BlazeServerStartup* server_startup;
751 StartServer(&server_startup);
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000752
753 // Give the server two minutes to start up. That's enough to connect with a
754 // debugger.
755 auto try_until_time(
756 std::chrono::system_clock::now() + std::chrono::seconds(120));
757 bool had_to_wait = false;
758 while (std::chrono::system_clock::now() < try_until_time) {
759 auto next_attempt_time(
760 std::chrono::system_clock::now() + std::chrono::milliseconds(100));
Lukacs Berki1977d922016-05-02 09:31:37 +0000761 if (server->Connect()) {
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000762 if (had_to_wait && !globals->options->client_debug) {
Lukacs Berki1977d922016-05-02 09:31:37 +0000763 fputc('\n', stderr);
764 fflush(stderr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100765 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000766 delete server_startup;
767 return;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100768 }
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000769
770 had_to_wait = true;
Lukacs Berki71675a52016-11-08 09:48:27 +0000771 if (!globals->options->client_debug) {
772 fputc('.', stderr);
773 fflush(stderr);
774 }
775
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000776 std::this_thread::sleep_until(next_attempt_time);
Lukacs Berki1977d922016-05-02 09:31:37 +0000777 if (!server_startup->IsStillAlive()) {
778 fprintf(stderr, "\nunexpected pipe read status: %s\n"
779 "Server presumed dead. Now printing '%s':\n",
780 strerror(errno), globals->jvm_log_file.c_str());
Laszlo Csomorae16e762016-11-18 10:16:08 +0000781 WriteFileToStderrOrDie(globals->jvm_log_file.c_str());
Lukacs Berki1977d922016-05-02 09:31:37 +0000782 exit(blaze_exit_code::INTERNAL_ERROR);
783 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100784 }
Lukacs Berki1977d922016-05-02 09:31:37 +0000785 die(blaze_exit_code::INTERNAL_ERROR,
Lukacs Berki5570bcc2016-11-15 15:45:58 +0000786 "\nError: couldn't connect to server after 120 seconds.");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100787}
788
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000789// A devtools_ijar::ZipExtractorProcessor to extract the files from the blaze
790// zip.
791class ExtractBlazeZipProcessor : public devtools_ijar::ZipExtractorProcessor {
792 public:
Thiago Farina9cb32752015-06-03 15:34:19 +0000793 explicit ExtractBlazeZipProcessor(const string &embedded_binaries)
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000794 : embedded_binaries_(embedded_binaries) {}
795
796 virtual bool Accept(const char *filename, const devtools_ijar::u4 attr) {
797 return !devtools_ijar::zipattr_is_dir(attr);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100798 }
799
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000800 virtual void Process(const char *filename, const devtools_ijar::u4 attr,
801 const devtools_ijar::u1 *data, const size_t size) {
802 string path = blaze_util::JoinPath(embedded_binaries_, filename);
Laszlo Csomorcefa9a22016-11-22 10:50:07 +0000803 if (!MakeDirectories(blaze_util::Dirname(path), 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100804 pdie(blaze_exit_code::INTERNAL_ERROR,
805 "couldn't create '%s'", path.c_str());
806 }
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100807
Laszlo Csomorae16e762016-11-18 10:16:08 +0000808 if (!blaze::WriteFile(data, size, path)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000809 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Laszlo Csomorae16e762016-11-18 10:16:08 +0000810 "\nFailed to write zipped file \"%s\": %s", path.c_str(),
811 strerror(errno));
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100812 }
813 }
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000814
815 private:
816 const string embedded_binaries_;
817};
818
819// Actually extracts the embedded data files into the tree whose root
820// is 'embedded_binaries'.
821static void ActuallyExtractData(const string &argv0,
822 const string &embedded_binaries) {
823 ExtractBlazeZipProcessor processor(embedded_binaries);
Laszlo Csomorcefa9a22016-11-22 10:50:07 +0000824 if (!MakeDirectories(embedded_binaries, 0777)) {
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000825 pdie(blaze_exit_code::INTERNAL_ERROR, "couldn't create '%s'",
826 embedded_binaries.c_str());
827 }
828
829 fprintf(stderr, "Extracting %s installation...\n",
Julio Merino28774852016-09-14 16:59:46 +0000830 globals->options->product_name.c_str());
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000831 std::unique_ptr<devtools_ijar::ZipExtractor> extractor(
832 devtools_ijar::ZipExtractor::Create(argv0.c_str(), &processor));
833 if (extractor.get() == NULL) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100834 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000835 "\nFailed to open %s as a zip file: (%d) %s",
Julio Merino28774852016-09-14 16:59:46 +0000836 globals->options->product_name.c_str(), errno, strerror(errno));
Damien Martin-Guillerezeb6e9032015-06-01 14:45:21 +0000837 }
838 if (extractor->ProcessAll() < 0) {
839 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
840 "\nFailed to extract %s as a zip file: %s",
Julio Merino28774852016-09-14 16:59:46 +0000841 globals->options->product_name.c_str(), extractor->GetError());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100842 }
843
844 const time_t TEN_YEARS_IN_SEC = 3600 * 24 * 365 * 10;
845 time_t future_time = time(NULL) + TEN_YEARS_IN_SEC;
846
847 // Set the timestamps of the extracted files to the future and make sure (or
848 // at least as sure as we can...) that the files we have written are actually
849 // on the disk.
850
851 vector<string> extracted_files;
Laszlo Csomor251bf032016-11-16 11:01:32 +0000852
853 // Walks the temporary directory recursively and collects full file paths.
854 blaze_util::GetAllFilesUnder(embedded_binaries, &extracted_files);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100855
856 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 Csomor251bf032016-11-16 11:01:32 +0000861 // Note that keeping the default timestamp set by unzip (1970-01-01) and
862 // using that to detect tampering is not enough, because we also need the
863 // timestamp to change between Blaze releases so that the metadata cache
864 // knows that the files may have changed. This is important for actions that
865 // use embedded binaries as artifacts.
Laszlo Csomor6c167652016-11-17 11:00:49 +0000866 if (!blaze_util::SetMtimeMillisec(it, future_time)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100867 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
868 "failed to set timestamp on '%s'", extracted_path);
869 }
870
Laszlo Csomorae16e762016-11-18 10:16:08 +0000871 blaze_util::SyncFile(it);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100872
873 string directory = blaze_util::Dirname(extracted_path);
874
875 // Now walk up until embedded_binaries and sync every directory in between.
876 // synced_directories is used to avoid syncing the same directory twice.
877 // The !directory.empty() and directory != "/" conditions are not strictly
878 // needed, but it makes this loop more robust, because otherwise, if due to
879 // some glitch, directory was not under embedded_binaries, it would get
880 // into an infinite loop.
881 while (directory != embedded_binaries &&
882 synced_directories.count(directory) == 0 &&
883 !directory.empty() &&
884 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();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100908 string tmp_binaries = tmp_install + "/_embedded_binaries";
909 ActuallyExtractData(self_path, tmp_binaries);
910
Laszlo Csomor943d3cf2016-11-07 14:27:21 +0000911 uint64_t et = GetMillisecondsMonotonic();
912 globals->extract_data_time = et - st;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100913
914 // Now rename the completed installation to its final name. If this
915 // fails due to an ENOTEMPTY then we assume another good
916 // installation snuck in before us.
Julio Merino28774852016-09-14 16:59:46 +0000917 if (rename(tmp_install.c_str(), globals->options->install_base.c_str()) == -1
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +0100918 && errno != ENOTEMPTY) {
919 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.
1020 ReadFile(cmdline_path, &joined_arguments);
1021 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;
1048 bool ok = ReadDirectorySymlink(installation_path.c_str(), &prev_installation);
1049 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;
Thiago Farina4e4ffd22016-03-09 17:02:28 +00001056 UnlinkPath(installation_path.c_str());
Julio Merino28774852016-09-14 16:59:46 +00001057 if (!SymlinkDirectories(globals->options->install_base.c_str(),
Dmitry Lomov47afaab2016-02-19 08:21:13 +00001058 installation_path.c_str())) {
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
Lukacs Berkiee44c382016-09-14 10:53:37 +00001073// A signal-safe version of fprintf(stderr, ...).
1074//
1075// WARNING: any output from the blaze client may be interleaved
1076// with output from the blaze server. In --curses mode,
1077// the Blaze server often erases the previous line of output.
1078// So, be sure to end each such message with TWO newlines,
1079// otherwise it may be erased by the next message from the
1080// Blaze server.
1081// Also, it's a good idea to start each message with a newline,
1082// in case the Blaze server has written a partial line.
1083static void sigprintf(const char *format, ...) {
1084 char buf[1024];
1085 va_list ap;
1086 va_start(ap, format);
1087 int r = vsnprintf(buf, sizeof buf, format, ap);
1088 va_end(ap);
1089 if (write(STDERR_FILENO, buf, r) <= 0) {
1090 // We don't care, just placate the compiler.
1091 }
1092}
1093
Laszlo Csomor32086b22016-11-24 15:23:55 +00001094static void CancelServer() {
1095 blaze_server->Cancel();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001096}
1097
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001098// Performs all I/O for a single client request to the server, and
1099// shuts down the client (by exit or signal).
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001100static ATTRIBUTE_NORETURN void SendServerRequest(BlazeServer* server) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001101 while (true) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001102 if (!server->Connected()) {
1103 StartServerAndConnect(server);
1104 }
1105
Lukacs Berki4de98942016-09-09 09:23:36 +00001106 // Check for the case when the workspace directory deleted and then gets
1107 // recreated while the server is running
1108
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001109 string server_cwd = GetProcessCWD(globals->server_pid);
Lukacs Berki4be230a2015-10-15 13:43:03 +00001110 // If server_cwd is empty, GetProcessCWD failed. This notably occurs when
1111 // running under Docker because then readlink(/proc/[pid]/cwd) returns
1112 // EPERM.
1113 // Docker issue #6687 (https://github.com/docker/docker/issues/6687) fixed
1114 // this, but one still needs the --cap-add SYS_PTRACE command line flag, at
1115 // least according to the discussion on Docker issue #6800
1116 // (https://github.com/docker/docker/issues/6687), and even then, it's a
1117 // non-default Docker flag. Given that this occurs only in very weird
1118 // cases, it's better to assume that everything is alright if we can't get
1119 // the cwd.
1120
1121 if (!server_cwd.empty() &&
1122 (server_cwd != globals->workspace || // changed
1123 server_cwd.find(" (deleted)") != string::npos)) { // deleted.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001124 // There's a distant possibility that the two paths look the same yet are
1125 // actually different because the two processes have different mount
1126 // tables.
1127 if (VerboseLogging()) {
1128 fprintf(stderr, "Server's cwd moved or deleted (%s).\n",
1129 server_cwd.c_str());
1130 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001131 server->KillRunningServer();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001132 } else {
1133 break;
1134 }
1135 }
1136
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001137 if (VerboseLogging()) {
1138 fprintf(stderr, "Connected (server pid=%d).\n", globals->server_pid);
1139 }
1140
1141 // Wall clock time since process startup.
Laszlo Csomor943d3cf2016-11-07 14:27:21 +00001142 globals->startup_time = GetMillisecondsSinceProcessStart();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001143
Laszlo Csomor32086b22016-11-24 15:23:55 +00001144 SignalHandler::Get().Install(globals, CancelServer);
1145 SignalHandler::Get().PropagateSignalOrExit(server->Communicate());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001146}
1147
1148// Parse the options, storing parsed values in globals.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001149static void ParseOptions(int argc, const char *argv[]) {
1150 string error;
1151 blaze_exit_code::ExitCode parse_exit_code =
Julio Merino28774852016-09-14 16:59:46 +00001152 globals->option_processor->ParseOptions(argc, argv, globals->workspace,
1153 globals->cwd, &error);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001154 if (parse_exit_code != blaze_exit_code::SUCCESS) {
1155 die(parse_exit_code, "%s", error.c_str());
1156 }
Julio Merino28774852016-09-14 16:59:46 +00001157 globals->options = globals->option_processor->GetParsedStartupOptions();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001158}
1159
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001160// Compute the globals globals->cwd and globals->workspace.
1161static void ComputeWorkspace() {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001162 globals->cwd = blaze_util::MakeCanonical(blaze_util::GetCwd().c_str());
1163 if (globals->cwd.empty()) {
1164 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1165 "blaze_util::MakeCanonical('%s') failed",
1166 blaze_util::GetCwd().c_str());
1167 }
Julio Merino211a95c2016-08-29 11:01:35 +00001168 globals->workspace = WorkspaceLayout::GetWorkspace(globals->cwd);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001169}
1170
1171// Figure out the base directories based on embedded data, username, cwd, etc.
Julio Merino28774852016-09-14 16:59:46 +00001172// Sets globals->options->install_base, globals->options->output_base,
Thiago Farina6fd9bf12016-04-26 09:02:18 +00001173// globals->lockfile, globals->jvm_log_file.
Thiago Farina2fd78902015-05-18 11:37:59 +00001174static void ComputeBaseDirectories(const string &self_path) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001175 // Only start a server when in a workspace because otherwise we won't do more
1176 // than emit a help message.
Julio Merino211a95c2016-08-29 11:01:35 +00001177 if (!WorkspaceLayout::InWorkspace(globals->workspace)) {
Julio Merino28774852016-09-14 16:59:46 +00001178 globals->options->batch = true;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001179 }
1180
1181 // The default install_base is <output_user_root>/install/<md5(blaze)>
1182 // but if an install_base is specified on the command line, we use that as
1183 // the base instead.
Julio Merino28774852016-09-14 16:59:46 +00001184 if (globals->options->install_base.empty()) {
1185 string install_user_root = globals->options->output_user_root + "/install";
1186 globals->options->install_base =
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001187 GetInstallBase(install_user_root, self_path);
1188 } else {
Eric Fellheimer4c5eb0f2015-08-12 15:02:24 +00001189 // We call GetInstallBase anyway to populate extracted_binaries and
1190 // install_md5.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001191 GetInstallBase("", self_path);
1192 }
1193
Julio Merino28774852016-09-14 16:59:46 +00001194 if (globals->options->output_base.empty()) {
Laszlo Csomor6bf95762016-11-16 13:29:22 +00001195 globals->options->output_base = blaze::GetHashedBaseDir(
Julio Merino28774852016-09-14 16:59:46 +00001196 globals->options->output_user_root, globals->workspace);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001197 }
1198
Julio Merino28774852016-09-14 16:59:46 +00001199 const char *output_base = globals->options->output_base.c_str();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001200 if (!blaze_util::PathExists(globals->options->output_base)) {
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001201 if (!MakeDirectories(globals->options->output_base, 0777)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001202 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1203 "Output base directory '%s' could not be created",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001204 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001205 }
1206 } else {
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001207 if (!blaze_util::IsDirectory(globals->options->output_base)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001208 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1209 "Error: Output base directory '%s' could not be created. "
1210 "It exists but is not a directory.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001211 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001212 }
1213 }
Laszlo Csomor9c951962016-11-10 13:31:27 +00001214 if (!blaze_util::CanAccess(globals->options->output_base, true, true, true)) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001215 die(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1216 "Error: Output base directory '%s' must be readable and writable.",
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001217 output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001218 }
Dave MacLachlan6b747ee2016-07-20 10:00:44 +00001219 ExcludePathFromBackup(output_base);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001220
Laszlo Csomorc3545392016-11-24 13:33:28 +00001221 globals->options->output_base = blaze_util::MakeCanonical(output_base);
1222 if (globals->options->output_base.empty()) {
1223 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1224 "blaze_util::MakeCanonical('%s') failed", output_base);
1225 }
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001226
Julio Merino28774852016-09-14 16:59:46 +00001227 globals->lockfile = globals->options->output_base + "/lock";
1228 globals->jvm_log_file = globals->options->output_base + "/server/jvm.out";
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001229}
1230
1231static void CheckEnvironment() {
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001232 if (!blaze::GetEnv("http_proxy").empty()) {
Lukacs Berki86a28b02016-10-25 10:34:45 +00001233 fprintf(stderr, "Warning: ignoring http_proxy in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001234 blaze::UnsetEnv("http_proxy");
Lukacs Berki86a28b02016-10-25 10:34:45 +00001235 }
1236
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001237 if (!blaze::GetEnv("LD_ASSUME_KERNEL").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001238 // Fix for bug: if ulimit -s and LD_ASSUME_KERNEL are both
1239 // specified, the JVM fails to create threads. See thread_stack_regtest.
1240 // This is also provoked by LD_LIBRARY_PATH=/usr/lib/debug,
1241 // or anything else that causes the JVM to use LinuxThreads.
1242 fprintf(stderr, "Warning: ignoring LD_ASSUME_KERNEL in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001243 blaze::UnsetEnv("LD_ASSUME_KERNEL");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001244 }
1245
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001246 if (!blaze::GetEnv("LD_PRELOAD").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001247 fprintf(stderr, "Warning: ignoring LD_PRELOAD in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001248 blaze::UnsetEnv("LD_PRELOAD");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001249 }
1250
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001251 if (!blaze::GetEnv("_JAVA_OPTIONS").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001252 // This would override --host_jvm_args
1253 fprintf(stderr, "Warning: ignoring _JAVA_OPTIONS in environment.\n");
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001254 blaze::UnsetEnv("_JAVA_OPTIONS");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001255 }
1256
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001257 if (!blaze::GetEnv("TEST_TMPDIR").empty()) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001258 fprintf(stderr, "INFO: $TEST_TMPDIR defined: output root default is "
Julio Merino28774852016-09-14 16:59:46 +00001259 "'%s'.\n", globals->options->output_root.c_str());
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001260 }
1261
1262 // TODO(bazel-team): We've also seen a failure during loading (creating
1263 // threads?) when ulimit -Hs 8192. Characterize that and check for it here.
1264
1265 // Make the JVM use ISO-8859-1 for parsing its command line because "blaze
1266 // run" doesn't handle non-ASCII command line arguments. This is apparently
1267 // the most reliable way to select the platform default encoding.
Laszlo Csomorcefa9a22016-11-22 10:50:07 +00001268 blaze::SetEnv("LANG", "en_US.ISO-8859-1");
1269 blaze::SetEnv("LANGUAGE", "en_US.ISO-8859-1");
1270 blaze::SetEnv("LC_ALL", "en_US.ISO-8859-1");
1271 blaze::SetEnv("LC_CTYPE", "en_US.ISO-8859-1");
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001272}
1273
Laszlo Csomorc3545392016-11-24 13:33:28 +00001274static string CheckAndGetBinaryPath(const string& argv0) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001275 if (argv0[0] == '/') {
Laszlo Csomorc3545392016-11-24 13:33:28 +00001276 return argv0;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001277 } else {
1278 string abs_path = globals->cwd + '/' + argv0;
Laszlo Csomorc3545392016-11-24 13:33:28 +00001279 string resolved_path = blaze_util::MakeCanonical(abs_path.c_str());
1280 if (!resolved_path.empty()) {
1281 return resolved_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001282 } else {
1283 // This happens during our integration tests, but thats okay, as we won't
1284 // log the invocation anyway.
Laszlo Csomorc3545392016-11-24 13:33:28 +00001285 return abs_path;
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001286 }
1287 }
1288}
1289
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001290// TODO(bazel-team): Execute the server as a child process and write its exit
1291// code to a file. In case the server becomes unresonsive or terminates
1292// unexpectedly (in a way that isn't already handled), we can observe the file,
1293// if it exists. (If it doesn't, then we know something went horribly wrong.)
Chloe Calvarin78f1c852016-11-22 21:58:50 +00001294int Main(int argc, const char *argv[], OptionProcessor *option_processor,
1295 std::unique_ptr<blaze_util::LogHandler> log_handler) {
1296 // Logging must be set first to assure no log statements are missed.
1297 blaze_util::SetLogHandler(std::move(log_handler));
Thiago Farina676cb9f2016-10-06 11:00:43 +00001298 globals = new GlobalVariables(option_processor);
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001299 blaze::SetupStdStreams();
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001300
1301 // Must be done before command line parsing.
1302 ComputeWorkspace();
Laszlo Csomorc3545392016-11-24 13:33:28 +00001303 globals->binary_path = CheckAndGetBinaryPath(argv[0]);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001304 ParseOptions(argc, argv);
Lukacs Berkibb2230f2016-04-27 14:19:25 +00001305
Lukacs Berki71675a52016-11-08 09:48:27 +00001306 debug_log("Debug logging active");
1307
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001308 CheckEnvironment();
Laszlo Csomor8a48f612016-11-17 10:18:34 +00001309 blaze::CreateSecureOutputRoot(globals->options->output_user_root);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001310
1311 const string self_path = GetSelfPath();
1312 ComputeBaseDirectories(self_path);
1313
Lukacs Berki71675a52016-11-08 09:48:27 +00001314 blaze_server = static_cast<BlazeServer *>(new GrpcBlazeServer(
1315 globals->options->connect_timeout_secs));
Lukacs Berki907dbbf2016-04-15 11:30:12 +00001316
Lukacs Berki415d39a2016-04-28 13:18:54 +00001317 globals->command_wait_time = blaze_server->AcquireLock();
Lukacs Berkice1445f2016-04-19 15:52:55 +00001318
Julio Merino28774852016-09-14 16:59:46 +00001319 WarnFilesystemType(globals->options->output_base);
Lukacs Berkice1445f2016-04-19 15:52:55 +00001320
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001321 ExtractData(self_path);
Lukacs Berki949c8762016-07-08 12:17:28 +00001322 VerifyJavaVersionAndSetJvm();
1323
Lukacs Berki1977d922016-05-02 09:31:37 +00001324 blaze_server->Connect();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001325 EnsureCorrectRunningVersion(blaze_server);
1326 KillRunningServerIfDifferentStartupOptions(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001327
Julio Merino28774852016-09-14 16:59:46 +00001328 if (globals->options->batch) {
1329 SetScheduling(globals->options->batch_cpu_scheduling,
1330 globals->options->io_nice_level);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001331 StartStandalone(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001332 } else {
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001333 SendServerRequest(blaze_server);
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001334 }
1335 return 0;
1336}
Thiago Farina0b6963e2015-04-28 20:26:45 +00001337
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001338static void null_grpc_log_function(gpr_log_func_args *args) {
1339}
1340
Lukacs Berki71675a52016-11-08 09:48:27 +00001341GrpcBlazeServer::GrpcBlazeServer(int connect_timeout_secs) {
Lukacs Berki1977d922016-05-02 09:31:37 +00001342 connected_ = false;
Lukacs Berki71675a52016-11-08 09:48:27 +00001343 connect_timeout_secs_ = connect_timeout_secs;
1344
1345 gpr_set_log_function(null_grpc_log_function);
1346
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001347 _pipe = blaze_util::CreatePipe();
1348 if (_pipe == NULL) {
1349 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "Couldn't create pipe");
Lukacs Berki6dd29092016-05-30 14:05:33 +00001350 }
1351}
1352
1353GrpcBlazeServer::~GrpcBlazeServer() {
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001354 delete _pipe;
1355 _pipe = NULL;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001356}
1357
1358bool GrpcBlazeServer::Connect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001359 assert(!connected_);
1360
Julio Merino28774852016-09-14 16:59:46 +00001361 std::string server_dir = globals->options->output_base + "/server";
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001362 std::string port;
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001363 std::string ipv4_prefix = "127.0.0.1:";
Lukacs Berkic8e74242016-04-28 08:32:04 +00001364 std::string ipv6_prefix_1 = "[0:0:0:0:0:0:0:1]:";
1365 std::string ipv6_prefix_2 = "[::1]:";
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001366
Lukacs Berki7e0249e2016-04-21 08:14:08 +00001367 if (!ReadFile(server_dir + "/command_port", &port)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001368 return false;
1369 }
1370
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001371 // Make sure that we are being directed to localhost
1372 if (port.compare(0, ipv4_prefix.size(), ipv4_prefix)
Lukacs Berkic8e74242016-04-28 08:32:04 +00001373 && port.compare(0, ipv6_prefix_1.size(), ipv6_prefix_1)
1374 && port.compare(0, ipv6_prefix_2.size(), ipv6_prefix_2)) {
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001375 return false;
1376 }
1377
Lukacs Berki7e0249e2016-04-21 08:14:08 +00001378 if (!ReadFile(server_dir + "/request_cookie", &request_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001379 return false;
1380 }
1381
Lukacs Berki7e0249e2016-04-21 08:14:08 +00001382 if (!ReadFile(server_dir + "/response_cookie", &response_cookie_)) {
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001383 return false;
1384 }
1385
1386 std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel(
Lukacs Berkib7caf9d2016-04-25 09:44:14 +00001387 port, grpc::InsecureChannelCredentials()));
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001388 std::unique_ptr<command_server::CommandServer::Stub> client(
1389 command_server::CommandServer::NewStub(channel));
1390
1391 grpc::ClientContext context;
1392 context.set_deadline(
Lukacs Berki71675a52016-11-08 09:48:27 +00001393 std::chrono::system_clock::now() +
1394 std::chrono::seconds(connect_timeout_secs_));
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001395
1396 command_server::PingRequest request;
1397 command_server::PingResponse response;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001398 request.set_cookie(request_cookie_);
Lukacs Berki7494c922016-04-27 11:17:51 +00001399
Lukacs Berki71675a52016-11-08 09:48:27 +00001400 debug_log("Trying to connect to server (timeout: %d secs)...",
1401 connect_timeout_secs_);
Lukacs Berki7e0249e2016-04-21 08:14:08 +00001402 grpc::Status status = client->Ping(&context, request, &response);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001403
Lukacs Berkic55e9c72016-04-25 13:43:40 +00001404 if (!status.ok() || response.cookie() != response_cookie_) {
Lukacs Berki71675a52016-11-08 09:48:27 +00001405 debug_log("Connection to server failed: %s",
1406 status.error_message().c_str());
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001407 return false;
1408 }
1409
Lukacs Berki1977d922016-05-02 09:31:37 +00001410 globals->server_pid = GetServerPid(server_dir);
1411 if (globals->server_pid <= 0) {
1412 pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR,
1413 "can't get PID of existing server (server dir=%s)",
1414 server_dir.c_str());
1415 }
1416
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001417 this->client_ = std::move(client);
Lukacs Berki1977d922016-05-02 09:31:37 +00001418 connected_ = true;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001419 return true;
1420}
1421
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001422// Cancellation works as follows:
1423//
1424// When the user presses Ctrl-C, a SIGINT is delivered to the client, which is
1425// translated into a BlazeServer::Cancel() call. Since it's not a good idea to
Lukacs Berki6dd29092016-05-30 14:05:33 +00001426// do significant work in signal handlers, all it does is write a byte to an
1427// unnamed pipe.
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001428//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001429// This unnamed pipe is used to communicate with the cancel thread. Whenever
1430// something interesting happens, a byte is written into it, which is read by
1431// the cancel thread. These commands are available:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001432//
Lukacs Berki6dd29092016-05-30 14:05:33 +00001433// - NOP
1434// - JOIN. The cancel thread needs to be terminated.
1435// - CANCEL. If the command ID is already available, a cancel request is sent.
1436// - COMMAND_ID_RECEIVED. The client learned the command ID from the server.
1437// If there is a pending cancellation request, it is acted upon.
1438//
1439// The only data the cancellation thread shares with the main thread is the
1440// file descriptor for receiving commands and command_id_, the latter of which
1441// is protected by a mutex, which mainly serves as a memory fence.
1442//
1443// The cancellation thread is joined at the end of the execution of the command.
1444// The main thread wakes it up just so that it can finish (using the JOIN
1445// action)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001446//
1447// It's conceivable that the server is busy and thus it cannot service the
1448// cancellation request. In that case, we simply ignore the failure and the both
1449// the server and the client go on as if nothing had happened (except that this
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001450// Ctrl-C still counts as a SIGINT, three of which result in a SIGKILL being
1451// delivered to the server)
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001452void GrpcBlazeServer::CancelThread() {
1453 bool running = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001454 bool cancel = false;
1455 bool command_id_received = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001456 while (running) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001457 char buf;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001458
1459 int bytes_read = _pipe->Receive(&buf, 1);
1460 if (bytes_read < 0 && errno == EINTR) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001461 continue;
1462 } else if (bytes_read != 1) {
1463 pdie(blaze_exit_code::INTERNAL_ERROR,
1464 "Cannot communicate with cancel thread");
1465 }
1466
1467 switch (buf) {
1468 case CancelThreadAction::NOTHING:
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001469 break;
1470
Lukacs Berki6dd29092016-05-30 14:05:33 +00001471 case CancelThreadAction::JOIN:
1472 running = false;
1473 break;
1474
1475 case CancelThreadAction::COMMAND_ID_RECEIVED:
1476 command_id_received = true;
1477 if (cancel) {
1478 SendCancelMessage();
1479 cancel = false;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001480 }
1481 break;
1482
Lukacs Berki6dd29092016-05-30 14:05:33 +00001483 case CancelThreadAction::CANCEL:
1484 if (command_id_received) {
1485 SendCancelMessage();
1486 } else {
1487 cancel = true;
1488 }
1489 break;
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001490 }
1491 }
1492}
1493
Lukacs Berki6dd29092016-05-30 14:05:33 +00001494void GrpcBlazeServer::SendCancelMessage() {
1495 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
1496
1497 command_server::CancelRequest request;
1498 request.set_cookie(request_cookie_);
1499 request.set_command_id(command_id_);
1500 grpc::ClientContext context;
1501 context.set_deadline(std::chrono::system_clock::now() +
Lukacs Berki3ace3002016-08-31 08:55:34 +00001502 std::chrono::seconds(10));
Lukacs Berki6dd29092016-05-30 14:05:33 +00001503 command_server::CancelResponse response;
1504 // There isn't a lot we can do if this request fails
Lukacs Berki3ace3002016-08-31 08:55:34 +00001505 grpc::Status status = client_->Cancel(&context, request, &response);
1506 if (!status.ok()) {
1507 fprintf(stderr, "\nCould not interrupt server (%s)\n\n",
1508 status.error_message().c_str());
1509 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001510}
1511
Lukacs Berki1977d922016-05-02 09:31:37 +00001512// This will wait indefinitely until the server shuts down
1513void GrpcBlazeServer::KillRunningServer() {
1514 assert(connected_);
1515 assert(globals->server_pid > 0);
1516
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001517 grpc::ClientContext context;
1518 command_server::RunRequest request;
1519 command_server::RunResponse response;
1520 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001521 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001522 request.set_client_description("pid=" + blaze::GetProcessIdAsString() +
1523 " (for shutdown)");
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001524 request.add_arg("shutdown");
1525 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
1526 client_->Run(&context, request));
1527
1528 while (reader->Read(&response)) {}
1529
Lukacs Berki1977d922016-05-02 09:31:37 +00001530 // Kill the server process for good measure.
Julio Merino28774852016-09-14 16:59:46 +00001531 if (VerifyServerProcess(globals->server_pid, globals->options->output_base,
1532 globals->options->install_base)) {
Lukacs Berkiee44c382016-09-14 10:53:37 +00001533 KillServerProcess(globals->server_pid);
1534 }
Lukacs Berki1977d922016-05-02 09:31:37 +00001535
1536 connected_ = false;
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001537}
1538
1539unsigned int GrpcBlazeServer::Communicate() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001540 assert(connected_);
1541
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001542 vector<string> arg_vector;
Julio Merino28774852016-09-14 16:59:46 +00001543 string command = globals->option_processor->GetCommand();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001544 if (command != "") {
1545 arg_vector.push_back(command);
1546 AddLoggingArgs(&arg_vector);
1547 }
1548
Julio Merino28774852016-09-14 16:59:46 +00001549 globals->option_processor->GetCommandArguments(&arg_vector);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001550
1551 command_server::RunRequest request;
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001552 request.set_cookie(request_cookie_);
Julio Merino28774852016-09-14 16:59:46 +00001553 request.set_block_for_lock(globals->options->block_for_lock);
Laszlo Csomorae16e762016-11-18 10:16:08 +00001554 request.set_client_description("pid=" + blaze::GetProcessIdAsString());
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001555 for (const string& arg : arg_vector) {
1556 request.add_arg(arg);
1557 }
1558
1559 grpc::ClientContext context;
1560 command_server::RunResponse response;
1561 std::unique_ptr<grpc::ClientReader<command_server::RunResponse>> reader(
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001562 client_->Run(&context, request));
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001563
Lukacs Berki415d39a2016-04-28 13:18:54 +00001564 // Release the server lock because the gRPC handles concurrent clients just
1565 // fine. Note that this may result in two "waiting for other client" messages
1566 // (one during server startup and one emitted by the server)
Lukacs Berki1977d922016-05-02 09:31:37 +00001567 blaze::ReleaseLock(&blaze_lock_);
Lukacs Berki415d39a2016-04-28 13:18:54 +00001568
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001569 std::thread cancel_thread(&GrpcBlazeServer::CancelThread, this);
1570 bool command_id_set = false;
Laurent Le Brun08849b22016-09-20 12:21:32 +00001571 bool pipe_broken = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001572 while (reader->Read(&response)) {
Lukacs Berkic55e9c72016-04-25 13:43:40 +00001573 if (response.cookie() != response_cookie_) {
1574 fprintf(stderr, "\nServer response cookie invalid, exiting\n");
1575 return blaze_exit_code::INTERNAL_ERROR;
1576 }
1577
Laurent Le Brun08849b22016-09-20 12:21:32 +00001578 bool pipe_broken_now = false;
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001579
1580 if (!response.standard_output().empty()) {
1581 size_t size = response.standard_output().size();
1582 size_t r = fwrite(response.standard_output().c_str(), 1, size, stdout);
1583 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001584 pipe_broken_now = true;
1585 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001586 }
1587
Laszlo Csomor74ffaf72016-11-24 12:17:20 +00001588 if (!response.standard_error().empty()) {
1589 size_t size = response.standard_error().size();
1590 size_t r = fwrite(response.standard_error().c_str(), 1, size, stderr);
1591 if (r < size && errno == EPIPE) {
Laurent Le Brun08849b22016-09-20 12:21:32 +00001592 pipe_broken_now = true;
1593 }
1594 }
1595
1596 if (pipe_broken_now && !pipe_broken) {
1597 pipe_broken = true;
1598 Cancel();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001599 }
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001600
1601 if (!command_id_set && response.command_id().size() > 0) {
Lukacs Berki6dd29092016-05-30 14:05:33 +00001602 std::unique_lock<std::mutex> lock(cancel_thread_mutex_);
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001603 command_id_ = response.command_id();
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001604 command_id_set = true;
Lukacs Berki6dd29092016-05-30 14:05:33 +00001605 SendAction(CancelThreadAction::COMMAND_ID_RECEIVED);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001606 }
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001607 }
1608
Lukacs Berki6dd29092016-05-30 14:05:33 +00001609 SendAction(CancelThreadAction::JOIN);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001610 cancel_thread.join();
1611
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001612 if (!response.finished()) {
Lukacs Berki3ace3002016-08-31 08:55:34 +00001613 fprintf(stderr, "\nServer finished RPC without an explicit exit code\n\n");
Lukacs Berki2896dc02016-07-07 07:55:04 +00001614 return GetExitCodeForAbruptExit(*globals);
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001615 }
1616
Lukacs Berkie6a34f62016-04-25 12:16:04 +00001617 return response.exit_code();
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001618}
1619
1620void GrpcBlazeServer::Disconnect() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001621 assert(connected_);
1622
Lukacs Berki00cfb7d2016-04-20 09:01:52 +00001623 client_.reset();
1624 request_cookie_ = "";
1625 response_cookie_ = "";
Lukacs Berki1977d922016-05-02 09:31:37 +00001626 connected_ = false;
Lukacs Berki1b25ce22016-04-15 13:11:21 +00001627}
1628
Lukacs Berki6dd29092016-05-30 14:05:33 +00001629void GrpcBlazeServer::SendAction(CancelThreadAction action) {
1630 char msg = action;
Laszlo Csomoref5ceef2016-11-18 11:19:02 +00001631 if (!_pipe->Send(&msg, 1)) {
Lukacs Berki3ace3002016-08-31 08:55:34 +00001632 sigprintf("\nCould not interrupt server (cannot write to client pipe)\n\n");
Sasha Smundak1fdd31d2016-07-25 17:54:00 +00001633 }
Lukacs Berki6dd29092016-05-30 14:05:33 +00001634}
1635
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001636void GrpcBlazeServer::Cancel() {
Lukacs Berki1977d922016-05-02 09:31:37 +00001637 assert(connected_);
Lukacs Berki6dd29092016-05-30 14:05:33 +00001638 SendAction(CancelThreadAction::CANCEL);
Lukacs Berkif1df38a2016-04-19 07:42:22 +00001639}
1640
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001641} // namespace blaze