blob: d94cf864190f45ca7cf2806d072d580bfa4de8f3 [file] [log] [blame]
Chloe Calvarineaa3be72016-12-13 19:48:34 +00001// Copyright 2016 The Bazel Authors. All rights reserved.
2//
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.
14package com.google.devtools.build.lib.util;
15
Chloe Calvarineaa3be72016-12-13 19:48:34 +000016import java.io.IOException;
janakr5bfe3432018-04-20 14:45:13 -070017import java.nio.charset.StandardCharsets;
18import java.nio.file.Files;
19import java.nio.file.Path;
20import java.nio.file.Paths;
Chloe Calvarineaa3be72016-12-13 19:48:34 +000021import javax.annotation.Nullable;
22
23/**
24 * Provides an external way for the Bazel server to communicate its exit code to the client, when
25 * the main gRPC channel is unavailable because the exit is too abrupt or originated in an async
26 * thread.
janakr5bfe3432018-04-20 14:45:13 -070027 *
28 * <p>Uses Java 8 {@link Path} objects rather than Bazel ones to avoid depending on the rest of
29 * Bazel.
Chloe Calvarineaa3be72016-12-13 19:48:34 +000030 */
31public class CustomExitCodePublisher {
32 private static final String EXIT_CODE_FILENAME = "exit_code_to_use_on_abrupt_exit";
33 @Nullable private static Path abruptExitCodeFilePath = null;
34
janakr5bfe3432018-04-20 14:45:13 -070035 public static void setAbruptExitStatusFileDir(String path) {
36 abruptExitCodeFilePath = Paths.get(path).resolve(EXIT_CODE_FILENAME);
Chloe Calvarineaa3be72016-12-13 19:48:34 +000037 }
38
39 public static void maybeWriteExitStatusFile(int exitCode) {
40 if (abruptExitCodeFilePath != null) {
41 try {
janakr5bfe3432018-04-20 14:45:13 -070042 Files.write(
43 abruptExitCodeFilePath, String.valueOf(exitCode).getBytes(StandardCharsets.UTF_8));
Chloe Calvarineaa3be72016-12-13 19:48:34 +000044 } catch (IOException ioe) {
45 System.err.printf(
46 "io error writing %d to abrupt exit status file %s: %s\n",
47 exitCode, abruptExitCodeFilePath, ioe.getMessage());
48 }
49 }
50 }
51}