Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 1 | // 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. |
| 14 | package com.google.devtools.build.lib.util; |
| 15 | |
Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 16 | import java.io.IOException; |
janakr | 5bfe343 | 2018-04-20 14:45:13 -0700 | [diff] [blame] | 17 | import java.nio.charset.StandardCharsets; |
| 18 | import java.nio.file.Files; |
| 19 | import java.nio.file.Path; |
| 20 | import java.nio.file.Paths; |
Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 21 | import 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. |
janakr | 5bfe343 | 2018-04-20 14:45:13 -0700 | [diff] [blame] | 27 | * |
| 28 | * <p>Uses Java 8 {@link Path} objects rather than Bazel ones to avoid depending on the rest of |
| 29 | * Bazel. |
Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 30 | */ |
| 31 | public 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 | |
janakr | 5bfe343 | 2018-04-20 14:45:13 -0700 | [diff] [blame] | 35 | public static void setAbruptExitStatusFileDir(String path) { |
| 36 | abruptExitCodeFilePath = Paths.get(path).resolve(EXIT_CODE_FILENAME); |
Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 37 | } |
| 38 | |
| 39 | public static void maybeWriteExitStatusFile(int exitCode) { |
| 40 | if (abruptExitCodeFilePath != null) { |
| 41 | try { |
janakr | 5bfe343 | 2018-04-20 14:45:13 -0700 | [diff] [blame] | 42 | Files.write( |
| 43 | abruptExitCodeFilePath, String.valueOf(exitCode).getBytes(StandardCharsets.UTF_8)); |
Chloe Calvarin | eaa3be7 | 2016-12-13 19:48:34 +0000 | [diff] [blame] | 44 | } 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 | } |