/
DockerSupportService.java
390 lines (332 loc) · 14.8 KB
/
DockerSupportService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.docker;
import org.elasticsearch.gradle.Version;
import org.elasticsearch.gradle.info.BuildParams;
import org.gradle.api.GradleException;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.services.BuildService;
import org.gradle.api.services.BuildServiceParameters;
import org.gradle.process.ExecOperations;
import org.gradle.process.ExecResult;
import javax.inject.Inject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Build service for detecting available Docker installation and checking for compatibility with Elasticsearch Docker image build
* requirements. This includes a minimum version requirement, as well as the ability to run privileged commands.
*/
public abstract class DockerSupportService implements BuildService<DockerSupportService.Parameters> {
private static Logger LOGGER = Logging.getLogger(DockerSupportService.class);
// Defines the possible locations of the Docker CLI. These will be searched in order.
private static String[] DOCKER_BINARIES = { "/usr/bin/docker", "/usr/local/bin/docker" };
private static String[] DOCKER_COMPOSE_BINARIES = { "/usr/local/bin/docker-compose", "/usr/bin/docker-compose" };
private static final Version MINIMUM_DOCKER_VERSION = Version.fromString("17.05.0");
private final ExecOperations execOperations;
private DockerAvailability dockerAvailability;
@Inject
public DockerSupportService(ExecOperations execOperations) {
this.execOperations = execOperations;
}
/**
* Searches for a functional Docker installation, and returns information about the search.
*
* @return the results of the search.
*/
public DockerAvailability getDockerAvailability() {
if (this.dockerAvailability == null) {
String dockerPath = null;
Result lastResult = null;
Version version = null;
boolean isVersionHighEnough = false;
boolean isComposeAvailable = false;
// Check if the Docker binary exists
final Optional<String> dockerBinary = getDockerPath();
if (isExcludedOs() == false && dockerBinary.isPresent()) {
dockerPath = dockerBinary.get();
// Since we use a multi-stage Docker build, check the Docker version meets minimum requirement
lastResult = runCommand(dockerPath, "version", "--format", "{{.Server.Version}}");
var lastResultOutput = lastResult.stdout.trim();
// docker returns 0/success if the daemon is not running, so we need to check the
// output before continuing
if (lastResult.isSuccess() && dockerDaemonIsRunning(lastResultOutput)) {
version = Version.fromString(lastResultOutput, Version.Mode.RELAXED);
isVersionHighEnough = version.onOrAfter(MINIMUM_DOCKER_VERSION);
if (isVersionHighEnough) {
// Check that we can execute a privileged command
lastResult = runCommand(dockerPath, "images");
// If docker all checks out, see if docker-compose is available and working
Optional<String> composePath = getDockerComposePath();
if (lastResult.isSuccess() && composePath.isPresent()) {
isComposeAvailable = runCommand(composePath.get(), "version").isSuccess();
}
}
}
}
boolean isAvailable = isVersionHighEnough && lastResult != null && lastResult.isSuccess();
this.dockerAvailability = new DockerAvailability(
isAvailable,
isComposeAvailable,
isVersionHighEnough,
dockerPath,
version,
lastResult
);
}
return this.dockerAvailability;
}
private boolean dockerDaemonIsRunning(String lastResultOutput) {
return lastResultOutput.contains("Cannot connect to the Docker daemon") == false;
}
/**
* Given a list of tasks that requires Docker, check whether Docker is available, otherwise throw an exception.
*
* @throws GradleException if Docker is not available. The exception message gives the reason.
*/
void failIfDockerUnavailable(List<String> tasks) {
DockerAvailability availability = getDockerAvailability();
// Docker installation is available and compatible
if (availability.isAvailable) {
return;
}
// No Docker binary was located
if (availability.path == null) {
final String message = String.format(
Locale.ROOT,
"Docker (checked [%s]) is required to run the following task%s: \n%s",
String.join(", ", DOCKER_BINARIES),
tasks.size() > 1 ? "s" : "",
String.join("\n", tasks)
);
throwDockerRequiredException(message);
}
// Docker binaries were located, but did not meet the minimum version requirement
if (availability.lastCommand.isSuccess() && availability.isVersionHighEnough == false) {
final String message = String.format(
Locale.ROOT,
"building Docker images requires minimum Docker version of %s due to use of multi-stage builds yet was [%s]",
MINIMUM_DOCKER_VERSION,
availability.version
);
throwDockerRequiredException(message);
}
// Some other problem, print the error
final String message = String.format(
Locale.ROOT,
"a problem occurred while using Docker from [%s]%s yet it is required to run the following task%s: \n%s\n"
+ "the problem is that Docker exited with exit code [%d] with standard error output:\n%s",
availability.path,
availability.version == null ? "" : " v" + availability.version,
tasks.size() > 1 ? "s" : "",
String.join("\n", tasks),
availability.lastCommand.exitCode,
availability.lastCommand.stderr.trim()
);
throwDockerRequiredException(message);
}
private boolean isExcludedOs() {
// We don't attempt to check the current flavor and version of Linux unless we're
// running in CI, because we don't want to stop people running the Docker tests in
// their own environments if they really want to.
if (BuildParams.isCi() == false) {
return false;
}
// Only some hosts in CI are configured with Docker. We attempt to work out the OS
// and version, so that we know whether to expect to find Docker. We don't attempt
// to probe for whether Docker is available, because that doesn't tell us whether
// Docker is unavailable when it should be.
final Path osRelease = Paths.get("/etc/os-release");
if (Files.exists(osRelease)) {
Map<String, String> values;
try {
final List<String> osReleaseLines = Files.readAllLines(osRelease);
values = parseOsRelease(osReleaseLines);
} catch (IOException e) {
throw new GradleException("Failed to read /etc/os-release", e);
}
final String id = deriveId(values);
final boolean excluded = getLinuxExclusionList().contains(id);
if (excluded) {
LOGGER.warn("Linux OS id [{}] is present in the Docker exclude list. Tasks requiring Docker will be disabled.", id);
}
return excluded;
}
return false;
}
private List<String> getLinuxExclusionList() {
File exclusionsFile = getParameters().getExclusionsFile();
if (exclusionsFile.exists()) {
try {
return Files.readAllLines(exclusionsFile.toPath())
.stream()
.map(String::trim)
.filter(line -> (line.isEmpty() || line.startsWith("#")) == false)
.collect(Collectors.toList());
} catch (IOException e) {
throw new GradleException("Failed to read " + exclusionsFile.getAbsolutePath(), e);
}
} else {
return Collections.emptyList();
}
}
// visible for testing
static String deriveId(Map<String, String> values) {
return values.get("ID") + "-" + values.get("VERSION_ID");
}
// visible for testing
static Map<String, String> parseOsRelease(final List<String> osReleaseLines) {
final Map<String, String> values = new HashMap<>();
osReleaseLines.stream().map(String::trim).filter(line -> (line.isEmpty() || line.startsWith("#")) == false).forEach(line -> {
final String[] parts = line.split("=", 2);
final String key = parts[0];
// remove optional leading and trailing quotes and whitespace
final String value = parts[1].replaceAll("^['\"]?\\s*", "").replaceAll("\\s*['\"]?$", "");
values.put(key, value.toLowerCase());
});
return values;
}
/**
* Searches the entries in {@link #DOCKER_BINARIES} for the Docker CLI. This method does
* not check whether the Docker installation appears usable, see {@link #getDockerAvailability()}
* instead.
*
* @return the path to a CLI, if available.
*/
private Optional<String> getDockerPath() {
// Check if the Docker binary exists
return List.of(DOCKER_BINARIES).stream().filter(path -> new File(path).exists()).findFirst();
}
/**
* Searches the entries in {@link #DOCKER_COMPOSE_BINARIES} for the Docker Compose CLI. This method does
* not check whether the installation appears usable, see {@link #getDockerAvailability()} instead.
*
* @return the path to a CLI, if available.
*/
private Optional<String> getDockerComposePath() {
// Check if the Docker binary exists
return List.of(DOCKER_COMPOSE_BINARIES).stream().filter(path -> new File(path).exists()).findFirst();
}
private void throwDockerRequiredException(final String message) {
throwDockerRequiredException(message, null);
}
private void throwDockerRequiredException(final String message, Exception e) {
throw new GradleException(
message + "\nyou can address this by attending to the reported issue, or removing the offending tasks from being executed.",
e
);
}
/**
* Runs a command and captures the exit code, standard output and standard error.
*
* @param args the command and any arguments to execute
* @return a object that captures the result of running the command. If an exception occurring
* while running the command, or the process was killed after reaching the 10s timeout,
* then the exit code will be -1.
*/
private Result runCommand(String... args) {
if (args.length == 0) {
throw new IllegalArgumentException("Cannot execute with no command");
}
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
final ExecResult execResult = execOperations.exec(spec -> {
// The redundant cast is to silence a compiler warning.
spec.setCommandLine((Object[]) args);
spec.setStandardOutput(stdout);
spec.setErrorOutput(stderr);
spec.setIgnoreExitValue(true);
});
return new Result(execResult.getExitValue(), stdout.toString(), stderr.toString());
}
/**
* An immutable class that represents the results of a Docker search from {@link #getDockerAvailability()}}.
*/
public static class DockerAvailability {
/**
* Indicates whether Docker is available and meets the required criteria.
* True if, and only if, Docker is:
* <ul>
* <li>Installed</li>
* <li>Executable</li>
* <li>Is at least version compatible with minimum version</li>
* <li>Can execute a command that requires privileges</li>
* </ul>
*/
public final boolean isAvailable;
/**
* True if docker-compose is available.
*/
public final boolean isComposeAvailable;
/**
* True if the installed Docker version is >= 17.05
*/
public final boolean isVersionHighEnough;
/**
* The path to the Docker CLI, or null
*/
public final String path;
/**
* The installed Docker version, or null
*/
public final Version version;
/**
* Information about the last command executes while probing Docker, or null.
*/
final Result lastCommand;
DockerAvailability(
boolean isAvailable,
boolean isComposeAvailable,
boolean isVersionHighEnough,
String path,
Version version,
Result lastCommand
) {
this.isAvailable = isAvailable;
this.isComposeAvailable = isComposeAvailable;
this.isVersionHighEnough = isVersionHighEnough;
this.path = path;
this.version = version;
this.lastCommand = lastCommand;
}
}
/**
* This class models the result of running a command. It captures the exit code, standard output and standard error.
*/
private static class Result {
final int exitCode;
final String stdout;
final String stderr;
Result(int exitCode, String stdout, String stderr) {
this.exitCode = exitCode;
this.stdout = stdout;
this.stderr = stderr;
}
boolean isSuccess() {
return exitCode == 0;
}
public String toString() {
return "exitCode = [" + exitCode + "] " + "stdout = [" + stdout.trim() + "] " + "stderr = [" + stderr.trim() + "]";
}
}
interface Parameters extends BuildServiceParameters {
File getExclusionsFile();
void setExclusionsFile(File exclusionsFile);
}
}