|
| 1 | +package io.github.intisy.docker; |
| 2 | + |
| 3 | +import com.github.dockerjava.api.DockerClient; |
| 4 | +import com.github.dockerjava.core.DefaultDockerClientConfig; |
| 5 | +import com.github.dockerjava.core.DockerClientImpl; |
| 6 | +import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; |
| 7 | +import com.github.dockerjava.transport.DockerHttpClient; |
| 8 | +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; |
| 9 | +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; |
| 10 | +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; |
| 11 | + |
| 12 | +import java.io.File; |
| 13 | +import java.io.IOException; |
| 14 | +import java.io.InputStream; |
| 15 | +import java.net.URI; |
| 16 | +import java.net.http.HttpClient; |
| 17 | +import java.net.http.HttpRequest; |
| 18 | +import java.net.http.HttpResponse; |
| 19 | +import java.nio.file.Files; |
| 20 | +import java.nio.file.Path; |
| 21 | +import java.nio.file.StandardCopyOption; |
| 22 | +import java.util.concurrent.TimeUnit; |
| 23 | + |
| 24 | +/** |
| 25 | + * @author Finn Birich |
| 26 | + */ |
| 27 | +@SuppressWarnings({"ResultOfMethodCallIgnored", "BusyWait"}) |
| 28 | +public class MacDockerProvider implements DockerProvider { |
| 29 | + private static final String DOCKER_DOWNLOAD_URL = "https://download.docker.com/mac/static/stable/%s/docker-%s.tgz"; |
| 30 | + private static final Path DOCKER_DIR = Path.of(System.getProperty("user.home"), ".docker-java"); |
| 31 | + private static final Path DOCKER_PATH = DOCKER_DIR.resolve("docker/dockerd"); |
| 32 | + private static final Path DOCKER_SOCKET_PATH = DOCKER_DIR.resolve("run/docker.sock"); |
| 33 | + private static final Path DOCKER_VERSION_FILE = DOCKER_DIR.resolve(".docker-version"); |
| 34 | + |
| 35 | + private DockerClient dockerClient; |
| 36 | + private Process dockerProcess; |
| 37 | + |
| 38 | + @Override |
| 39 | + public void ensureInstalled() throws IOException, InterruptedException { |
| 40 | + boolean autoUpdate = Boolean.parseBoolean(System.getProperty("docker.auto.update", "true")); |
| 41 | + String latestVersion = DockerVersionFetcher.getLatestVersion(); |
| 42 | + boolean needsUpdate = true; |
| 43 | + |
| 44 | + if (Files.exists(DOCKER_PATH)) { |
| 45 | + if (autoUpdate && Files.exists(DOCKER_VERSION_FILE)) { |
| 46 | + String installedVersion = Files.readString(DOCKER_VERSION_FILE).trim(); |
| 47 | + if (!installedVersion.equals(latestVersion)) { |
| 48 | + System.out.println("Newer Docker version available. Updating from " + installedVersion + " to " + latestVersion); |
| 49 | + } else { |
| 50 | + System.out.println("Docker is up to date. (" + latestVersion + ")"); |
| 51 | + needsUpdate = false; |
| 52 | + } |
| 53 | + } else if (!autoUpdate) { |
| 54 | + needsUpdate = false; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + if (needsUpdate) { |
| 59 | + System.out.println("Docker installation is incomplete or outdated. Re-installing..."); |
| 60 | + |
| 61 | + Path dockerInstallDir = DOCKER_DIR.resolve("docker"); |
| 62 | + if (Files.exists(dockerInstallDir)) { |
| 63 | + try (java.util.stream.Stream<Path> walk = Files.walk(dockerInstallDir)) { |
| 64 | + walk.sorted(java.util.Comparator.reverseOrder()) |
| 65 | + .map(Path::toFile) |
| 66 | + .forEach(File::delete); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + String arch = getArch(); |
| 71 | + String dockerUrl = String.format(DOCKER_DOWNLOAD_URL, arch, latestVersion); |
| 72 | + downloadAndExtract(dockerUrl); |
| 73 | + Files.writeString(DOCKER_VERSION_FILE, latestVersion); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + private String getArch() { |
| 78 | + String osArch = System.getProperty("os.arch"); |
| 79 | + return switch (osArch) { |
| 80 | + case "amd64" -> "x86_64"; |
| 81 | + case "aarch64" -> "aarch64"; |
| 82 | + default -> throw new UnsupportedOperationException("Unsupported architecture: " + osArch); |
| 83 | + }; |
| 84 | + } |
| 85 | + |
| 86 | + @Override |
| 87 | + public void start() throws IOException, InterruptedException { |
| 88 | + Path runDir = DOCKER_DIR.resolve("run"); |
| 89 | + Path dataDir = DOCKER_DIR.resolve("data"); |
| 90 | + runDir.toFile().mkdirs(); |
| 91 | + dataDir.toFile().mkdirs(); |
| 92 | + |
| 93 | + ProcessBuilder pb = new ProcessBuilder(DOCKER_PATH.toString(), "--config-file", DOCKER_DIR.resolve("config.json").toString()); |
| 94 | + pb.environment().put("XDG_RUNTIME_DIR", runDir.toString()); |
| 95 | + pb.environment().put("XDG_DATA_HOME", dataDir.toString()); |
| 96 | + pb.redirectErrorStream(true); |
| 97 | + pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); |
| 98 | + dockerProcess = pb.start(); |
| 99 | + |
| 100 | + if (!waitForSocket()) { |
| 101 | + throw new RuntimeException("Docker daemon failed to create socket in time."); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public DockerClient getClient() { |
| 107 | + if (this.dockerClient == null) { |
| 108 | + DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() |
| 109 | + .withDockerHost("unix://" + DOCKER_SOCKET_PATH).build(); |
| 110 | + |
| 111 | + DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder() |
| 112 | + .dockerHost(config.getDockerHost()) |
| 113 | + .sslConfig(config.getSSLConfig()) |
| 114 | + .build(); |
| 115 | + |
| 116 | + this.dockerClient = DockerClientImpl.getInstance(config, httpClient); |
| 117 | + } |
| 118 | + return this.dockerClient; |
| 119 | + } |
| 120 | + |
| 121 | + @Override |
| 122 | + public void stop() { |
| 123 | + if (dockerProcess != null) { |
| 124 | + dockerProcess.destroy(); |
| 125 | + try { |
| 126 | + dockerProcess.waitFor(10, TimeUnit.SECONDS); |
| 127 | + } catch (InterruptedException e) { |
| 128 | + dockerProcess.destroyForcibly(); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + @SuppressWarnings("deprecation") |
| 134 | + private void downloadAndExtract(String urlString) throws IOException, InterruptedException { |
| 135 | + System.out.println("Downloading and extracting " + urlString + "..."); |
| 136 | + HttpClient client = HttpClient.newBuilder() |
| 137 | + .followRedirects(HttpClient.Redirect.NORMAL) |
| 138 | + .build(); |
| 139 | + HttpRequest request = HttpRequest.newBuilder().uri(URI.create(urlString)).build(); |
| 140 | + HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); |
| 141 | + |
| 142 | + if (response.statusCode() != 200) { |
| 143 | + throw new IOException("Failed to download file from " + urlString + ". Status code: " + response.statusCode()); |
| 144 | + } |
| 145 | + |
| 146 | + try (InputStream is = response.body(); |
| 147 | + GzipCompressorInputStream gzis = new GzipCompressorInputStream(is); |
| 148 | + TarArchiveInputStream tis = new TarArchiveInputStream(gzis)) { |
| 149 | + TarArchiveEntry entry; |
| 150 | + while ((entry = tis.getNextTarEntry()) != null) { |
| 151 | + if (!tis.canReadEntryData(entry)) continue; |
| 152 | + Path outputPath = MacDockerProvider.DOCKER_DIR.resolve(entry.getName()); |
| 153 | + if (entry.isDirectory()) { |
| 154 | + Files.createDirectories(outputPath); |
| 155 | + } else { |
| 156 | + Files.createDirectories(outputPath.getParent()); |
| 157 | + Files.copy(tis, outputPath, StandardCopyOption.REPLACE_EXISTING); |
| 158 | + if (entry.getName().endsWith("dockerd")) { |
| 159 | + outputPath.toFile().setExecutable(true); |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + private boolean waitForSocket() throws InterruptedException { |
| 167 | + System.out.println("Waiting for Docker socket to be available at " + DOCKER_SOCKET_PATH + "..."); |
| 168 | + long timeoutMillis = TimeUnit.SECONDS.toMillis(30); |
| 169 | + long startTime = System.currentTimeMillis(); |
| 170 | + while (System.currentTimeMillis() - startTime < timeoutMillis) { |
| 171 | + if (Files.exists(DOCKER_SOCKET_PATH)) { |
| 172 | + System.out.println("Docker socket found."); |
| 173 | + return true; |
| 174 | + } |
| 175 | + Thread.sleep(500); |
| 176 | + } |
| 177 | + System.err.println("Timed out waiting for Docker socket."); |
| 178 | + return false; |
| 179 | + } |
| 180 | +} |
0 commit comments