blob: 199568a4fbf8ddc45b59b9fc7875dcc102d61860 [file] [log] [blame]
jmmv55ccf582018-03-08 10:02:54 -08001// Copyright 2018 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
15package com.google.devtools.build.lib.sandbox;
16
17import static com.google.common.base.Preconditions.checkNotNull;
18import static java.nio.charset.StandardCharsets.UTF_8;
19
20import com.google.common.collect.ImmutableList;
21import com.google.common.collect.ImmutableMap;
jmmvacaca5a2019-03-25 10:46:05 -070022import com.google.common.io.ByteStreams;
jmmv55ccf582018-03-08 10:02:54 -080023import com.google.devtools.build.lib.shell.Subprocess;
24import com.google.devtools.build.lib.shell.SubprocessBuilder;
jmmvacaca5a2019-03-25 10:46:05 -070025import com.google.devtools.build.lib.shell.SubprocessBuilder.StreamAction;
jmmv55ccf582018-03-08 10:02:54 -080026import com.google.devtools.build.lib.util.OS;
27import com.google.devtools.build.lib.vfs.Path;
28import com.google.devtools.build.lib.vfs.PathFragment;
29import java.io.BufferedReader;
30import java.io.BufferedWriter;
jmmvacaca5a2019-03-25 10:46:05 -070031import java.io.ByteArrayOutputStream;
jmmv55ccf582018-03-08 10:02:54 -080032import java.io.IOException;
33import java.io.InputStreamReader;
34import java.io.OutputStreamWriter;
35import java.util.List;
36import java.util.function.Function;
37import java.util.logging.Logger;
38import java.util.stream.Collectors;
39import javax.annotation.Nullable;
40
41/** A sandboxfs implementation that uses an external sandboxfs binary to manage the mount point. */
42final class RealSandboxfsProcess implements SandboxfsProcess {
43 private static final Logger log = Logger.getLogger(RealSandboxfsProcess.class.getName());
44
45 /** Directory on which the sandboxfs is serving. */
46 private final Path mountPoint;
47
48 /**
49 * Process handle to the sandboxfs instance. Null only after {@link #destroy()} has been invoked.
50 */
51 private @Nullable Subprocess process;
52
53 /**
54 * Writer with which to send data to the sandboxfs instance. Null only after {@link #destroy()}
55 * has been invoked.
56 */
57 private @Nullable BufferedWriter processStdIn;
58
59 /**
60 * Reader with which to receive data from the sandboxfs instance. Null only after
61 * {@link #destroy()} has been invoked.
62 */
63 private @Nullable BufferedReader processStdOut;
64
65 /**
66 * Shutdown hook to stop the sandboxfs instance on abrupt termination. Null only after
67 * {@link #destroy()} has been invoked.
68 */
69 private @Nullable Thread shutdownHook;
70
71 /**
72 * Initializes a new sandboxfs process instance.
73 *
74 * @param process process handle for the already-running sandboxfs instance
75 */
76 private RealSandboxfsProcess(Path mountPoint, Subprocess process) {
77 this.mountPoint = mountPoint;
78
79 this.process = process;
80 this.processStdIn = new BufferedWriter(
81 new OutputStreamWriter(process.getOutputStream(), UTF_8));
82 this.processStdOut = new BufferedReader(
83 new InputStreamReader(process.getInputStream(), UTF_8));
84
85 this.shutdownHook =
86 new Thread(
87 () -> {
88 try {
89 this.destroy();
90 } catch (Exception e) {
91 log.warning("Failed to destroy running sandboxfs instance; mount point may have "
92 + "been left behind: " + e);
93 }
94 });
95 Runtime.getRuntime().addShutdownHook(shutdownHook);
96 }
97
98 /**
jmmvacaca5a2019-03-25 10:46:05 -070099 * Checks if the given sandboxfs binary is available and is valid.
100 *
101 * @param binary path to the sandboxfs binary that will later be used in the {@link #mount} call.
102 * @return true if the binary looks good, false otherwise
103 * @throws IOException if there is a problem trying to start the subprocess
104 */
105 static boolean isAvailable(PathFragment binary) {
106 Subprocess process;
107 try {
108 process =
109 new SubprocessBuilder()
110 .setArgv(binary.getPathString(), "--version")
111 .setStdout(StreamAction.STREAM)
112 .redirectErrorStream(true)
113 .start();
114 } catch (IOException e) {
115 log.warning("sandboxfs binary at " + binary + " seems to be missing; got error " + e);
116 return false;
117 }
118
119 ByteArrayOutputStream outErrBytes = new ByteArrayOutputStream();
120 try {
121 ByteStreams.copy(process.getInputStream(), outErrBytes);
122 } catch (IOException e) {
123 try {
124 outErrBytes.write(("Failed to read stdout: " + e).getBytes());
125 } catch (IOException e2) {
126 // Should not really have happened. There is nothing we can do.
127 }
128 }
129 String outErr = outErrBytes.toString().replaceFirst("\n$", "");
130
131 int exitCode = waitForProcess(process);
132 if (exitCode == 0) {
133 // TODO(jmmv): Validate the version number and ensure we support it. Would be nice to reuse
134 // the DottedVersion logic from the Apple rules.
135 if (outErr.matches("sandboxfs .*")) {
136 return true;
137 } else {
138 log.warning(
139 "sandboxfs binary at "
140 + binary
141 + " exists but doesn't seem valid; output was: "
142 + outErr);
143 return false;
144 }
145 } else {
146 log.warning(
147 "sandboxfs binary at "
148 + binary
149 + " returned non-zero exit code "
150 + exitCode
151 + " and output "
152 + outErr);
153 return false;
154 }
155 }
156
157 /**
jmmv55ccf582018-03-08 10:02:54 -0800158 * Mounts a new sandboxfs instance.
159 *
160 * <p>The root of the file system instance is left unmapped which means that it remains as
161 * read-only throughout the lifetime of this instance. Writable subdirectories can later be
162 * mapped via {@link #map(List)}.
163 *
jmmv56d1b1c2018-03-19 19:04:20 -0700164 * @param binary path to the sandboxfs binary. This is a {@link PathFragment} and not a
165 * {@link Path} because we want to support "bare" (non-absolute) names for the location of
166 * the sandboxfs binary; such names are automatically looked for in the {@code PATH}.
jmmv55ccf582018-03-08 10:02:54 -0800167 * @param mountPoint directory on which to mount the sandboxfs instance
168 * @param logFile path to the file that will receive all sandboxfs logging output
169 * @return a new handle that represents the running process
170 * @throws IOException if there is a problem starting the process
171 */
jmmv56d1b1c2018-03-19 19:04:20 -0700172 static SandboxfsProcess mount(PathFragment binary, Path mountPoint, Path logFile)
173 throws IOException {
jmmv55ccf582018-03-08 10:02:54 -0800174 log.info("Mounting sandboxfs (" + binary + ") onto " + mountPoint);
175
176 // TODO(jmmv): Before starting a sandboxfs serving instance, we must query the current version
177 // of sandboxfs and check if we support its communication protocol.
178
179 ImmutableList.Builder<String> argvBuilder = ImmutableList.builder();
180
181 argvBuilder.add(binary.getPathString());
182
183 // On macOS, we need to allow users other than self to access the sandboxfs instance. This is
184 // necessary because macOS's amfid, which runs as root, has to have access to the binaries
185 // within the sandbox in order to validate signatures. See:
186 // http://julio.meroh.net/2017/10/fighting-execs-sandboxfs-macos.html
187 argvBuilder.add(OS.getCurrent() == OS.DARWIN ? "--allow=other" : "--allow=self");
188
189 // TODO(jmmv): Pass flags to enable sandboxfs' debugging support (--listen_address and --debug)
190 // when requested by the user via --sandbox_debug. Tricky because we have to figure out how to
191 // deal with port numbers (which sandboxfs can autoassign, but doesn't currently promise a way
192 // to tell us back what it picked).
193
194 argvBuilder.add(mountPoint.getPathString());
195
196 SubprocessBuilder processBuilder = new SubprocessBuilder();
197 processBuilder.setArgv(argvBuilder.build());
198 processBuilder.setStderr(logFile.getPathFile());
199 processBuilder.setEnv(ImmutableMap.of(
200 // sandboxfs may need to locate fusermount depending on the FUSE implementation so pass the
201 // PATH to the subprocess (which we assume is sufficient).
202 "PATH", System.getenv("PATH")));
203
204 Subprocess process = processBuilder.start();
205 RealSandboxfsProcess sandboxfs = new RealSandboxfsProcess(mountPoint, process);
206 // TODO(jmmv): We should have a better mechanism to wait for sandboxfs to start successfully but
207 // sandboxfs currently provides no interface to do so. Just try to push an empty configuration
208 // and see if it works.
209 try {
210 sandboxfs.reconfigure("[]\n\n");
211 } catch (IOException e) {
212 destroyProcess(process);
213 throw new IOException("sandboxfs failed to start", e);
214 }
215 return sandboxfs;
216 }
217
218 @Override
219 public Path getMountPoint() {
220 return mountPoint;
221 }
222
223 @Override
224 public boolean isAlive() {
225 return process != null && !process.finished();
226 }
227
228 /**
jmmvacaca5a2019-03-25 10:46:05 -0700229 * Waits for a process to terminate.
jmmv55ccf582018-03-08 10:02:54 -0800230 *
jmmvacaca5a2019-03-25 10:46:05 -0700231 * @param process the process to wait for
232 * @return the exit code of the terminated process
jmmv55ccf582018-03-08 10:02:54 -0800233 */
jmmvacaca5a2019-03-25 10:46:05 -0700234 private static int waitForProcess(Subprocess process) {
jmmv55ccf582018-03-08 10:02:54 -0800235 boolean interrupted = false;
236 try {
237 while (true) {
238 try {
239 process.waitFor();
jmmvacaca5a2019-03-25 10:46:05 -0700240 break;
jmmv55ccf582018-03-08 10:02:54 -0800241 } catch (InterruptedException ie) {
242 interrupted = true;
243 }
244 }
245 } finally {
246 if (interrupted) {
247 Thread.currentThread().interrupt();
248 }
249 }
jmmvacaca5a2019-03-25 10:46:05 -0700250 return process.exitValue();
251 }
252
253 /**
254 * Destroys a process and waits for it to exit.
255 *
256 * @param process the process to destroy
257 */
258 // TODO(jmmv): This is adapted from Worker.java. Should probably replace both with a new variant
259 // of Uninterruptibles.callUninterruptibly that takes a lambda instead of a callable.
260 private static void destroyProcess(Subprocess process) {
261 process.destroy();
262 waitForProcess(process);
jmmv55ccf582018-03-08 10:02:54 -0800263 }
264
265 @Override
266 public synchronized void destroy() {
267 if (shutdownHook != null) {
268 Runtime.getRuntime().removeShutdownHook(shutdownHook);
269 shutdownHook = null;
270 }
271
272 if (processStdIn != null) {
273 try {
274 processStdIn.close();
275 } catch (IOException e) {
276 log.warning("Failed to close sandboxfs's stdin pipe: " + e);
277 }
278 processStdIn = null;
279 }
280
281 if (processStdOut != null) {
282 try {
283 processStdOut.close();
284 } catch (IOException e) {
285 log.warning("Failed to close sandboxfs's stdout pipe: " + e);
286 }
287 processStdOut = null;
288 }
289
290 if (process != null) {
291 destroyProcess(process);
292 process = null;
293 }
294 }
295
296 /**
297 * Pushes a new configuration to sandboxfs and waits for acceptance.
298 *
299 * @param config the configuration chunk to push to sandboxfs
300 * @throws IOException if sandboxfs cannot be reconfigured either because of an error in the
301 * configuration or because we failed to communicate with the subprocess
302 */
303 private synchronized void reconfigure(String config) throws IOException {
304 checkNotNull(processStdIn, "sandboxfs already has been destroyed");
305 processStdIn.write(config);
306 processStdIn.flush();
307
308 checkNotNull(processStdOut, "sandboxfs has already been destroyed");
309 String done = processStdOut.readLine();
310 if (done == null) {
311 throw new IOException("premature end of output from sandboxfs");
312 }
313 if (!done.equals("Done")) {
314 throw new IOException("received unknown string from sandboxfs: " + done + "; expected Done");
315 }
316 }
317
318 @Override
319 public void map(List<Mapping> mappings) throws IOException {
320 Function<Mapping, String> formatMapping =
321 (mapping) -> String.format(
322 "{\"Map\": {\"Mapping\": \"%s\", \"Target\": \"%s\", \"Writable\": %s}}",
323 mapping.path(), mapping.target(), mapping.writable() ? "true" : "false");
324
325 StringBuilder sb = new StringBuilder();
326 sb.append("[\n");
327 sb.append(mappings.stream().map(formatMapping).collect(Collectors.joining(",\n")));
328 sb.append("]\n\n");
329 reconfigure(sb.toString());
330 }
331
332 @Override
333 public void unmap(PathFragment mapping) throws IOException {
334 reconfigure(String.format("[{\"Unmap\": \"%s\"}]\n\n", mapping));
335 }
336}