Skip to content

Commit 18cfdca

Browse files
committed
feat: add shared windows elevation and optional feature helpers
- WindowsElevation: administrator detection and UAC-elevated PowerShell runs via -EncodedCommand with the inner exit code propagated - WindowsFeatures: check and enable Windows optional features with -NoRestart, RestartNeeded mapped to exit 3010, and the exact manual command printed when elevation is declined or unavailable - WindowsDockerProvider now uses the shared helpers; the Containers state parse is locale-safe, the WSL Ubuntu install opens the elevation dialog directly instead of a console prompt, and the no-distro error no longer claims WSL is installed Claude-Session: https://claude.ai/code/session_01DwGcP3fq6b37WK6zfAJkMu
1 parent 6619c54 commit 18cfdca

5 files changed

Lines changed: 429 additions & 96 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package io.github.intisy.docker;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.concurrent.TimeUnit;
7+
8+
/**
9+
* Minimal internal helper to run a native command with a timeout,
10+
* capturing combined stdout and stderr without deadlocking on full pipes.
11+
*
12+
* @author Finn Birich
13+
*/
14+
final class ProcessRunner {
15+
16+
static final class Result {
17+
final int exitCode;
18+
final String output;
19+
final boolean timedOut;
20+
21+
Result(int exitCode, String output, boolean timedOut) {
22+
this.exitCode = exitCode;
23+
this.output = output;
24+
this.timedOut = timedOut;
25+
}
26+
}
27+
28+
private ProcessRunner() {
29+
}
30+
31+
static Result run(long timeoutMillis, String... command) throws IOException {
32+
ProcessBuilder processBuilder = new ProcessBuilder(command);
33+
processBuilder.redirectErrorStream(true);
34+
Process process = processBuilder.start();
35+
36+
final StringBuilder output = new StringBuilder();
37+
Thread drainer = new Thread(new Runnable() {
38+
@Override
39+
public void run() {
40+
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
41+
String line;
42+
while ((line = reader.readLine()) != null) {
43+
synchronized (output) {
44+
output.append(line).append('\n');
45+
}
46+
}
47+
} catch (IOException ignored) {
48+
}
49+
}
50+
});
51+
drainer.setDaemon(true);
52+
drainer.start();
53+
54+
try {
55+
if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS)) {
56+
process.destroyForcibly();
57+
synchronized (output) {
58+
return new Result(Integer.MIN_VALUE, output.toString(), true);
59+
}
60+
}
61+
drainer.join(5000);
62+
synchronized (output) {
63+
return new Result(process.exitValue(), output.toString(), false);
64+
}
65+
} catch (InterruptedException e) {
66+
Thread.currentThread().interrupt();
67+
process.destroyForcibly();
68+
throw new IOException("Interrupted while waiting for command: " + command[0], e);
69+
}
70+
}
71+
}

‎src/main/java/io/github/intisy/docker/WindowsDockerProvider.java‎

Lines changed: 21 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -156,39 +156,6 @@ private String runWslCommandAsRoot(String command, int timeoutSeconds) {
156156
}
157157
}
158158

159-
/**
160-
* Run a Windows command with UAC elevation (administrator prompt).
161-
* Uses PowerShell {@code Start-Process -Verb RunAs} to trigger the UAC dialog.
162-
*
163-
* @param command The executable to run elevated
164-
* @param arguments Arguments for the command
165-
* @param waitForExit Whether to wait for the elevated process to complete
166-
* @return true if the elevated process was started (and completed successfully if waitForExit)
167-
*/
168-
private boolean runElevatedWindowsCommand(String command, String arguments, boolean waitForExit) {
169-
try {
170-
String psCommand = String.format(
171-
"Start-Process '%s' -ArgumentList '%s' -Verb RunAs%s",
172-
command, arguments, waitForExit ? " -Wait" : "");
173-
174-
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", psCommand);
175-
pb.redirectErrorStream(true);
176-
Process process = pb.start();
177-
byte[] output = readAllBytes(process.getInputStream());
178-
int exitCode = process.waitFor();
179-
180-
String outputStr = new String(output).trim();
181-
if (!outputStr.isEmpty()) {
182-
log.debug("Elevated command output: {}", outputStr);
183-
}
184-
185-
return exitCode == 0;
186-
} catch (IOException | InterruptedException e) {
187-
log.warn("Failed to run elevated command: {}", e.getMessage());
188-
return false;
189-
}
190-
}
191-
192159
@Override
193160
public String getInstanceId() {
194161
return instanceId;
@@ -585,12 +552,12 @@ private void createInstanceDirectories() throws IOException {
585552
public void start() throws IOException, InterruptedException {
586553
log.info("Starting Docker (instance: {})...", instanceId);
587554

588-
boolean isAdmin = isAdministrator();
555+
boolean isAdmin = WindowsElevation.isAdministrator();
589556
log.debug("Administrator check result: {}", isAdmin);
590-
557+
591558
if (isAdmin) {
592559
log.info("Running with administrator privileges. Using native Windows Docker");
593-
ensureContainersFeatureEnabled();
560+
WindowsFeatures.ensureEnabled(WindowsFeatures.CONTAINERS);
594561
startNativeDocker();
595562
} else {
596563
log.info("Not running as administrator. Checking for WSL2...");
@@ -603,30 +570,29 @@ public void start() throws IOException, InterruptedException {
603570
startWsl2Docker();
604571
} else {
605572
log.error("Docker requires either administrator privileges or a usable WSL2 Linux distribution.");
606-
log.error("You have WSL but only Docker Desktop's internal distros are installed.");
607-
608-
if (promptForAutoSetup("A Linux distribution (Ubuntu) needs to be installed in WSL.\n" +
609-
"This requires a one-time administrator elevation (UAC prompt).")) {
610-
log.info("Installing Ubuntu in WSL2 via elevated command...");
611-
boolean success = runElevatedWindowsCommand("wsl", "--install -d Ubuntu", true);
612-
613-
if (success) {
614-
log.info("Ubuntu WSL installation started successfully.");
615-
log.info("Please complete the Ubuntu setup (create username/password) when prompted,");
616-
log.info("then run your application again.");
617-
throw new RuntimeException("WSL Ubuntu installed. Please complete setup and restart the application.");
618-
} else {
619-
log.error("Elevated installation was cancelled or failed.");
620-
log.error("You can install it manually:");
621-
printWslInstallManualInstructions();
622-
throw new RuntimeException("Cannot start Docker: WSL Ubuntu installation failed. See instructions above.");
623-
}
624-
} else {
573+
log.error("No usable WSL2 Linux distribution was found (WSL is missing, or only Docker Desktop's internal distros exist).");
574+
575+
if ("false".equals(System.getProperty("docker.auto.setup"))) {
625576
log.error("To fix this, install a Linux distribution:");
626577
printWslInstallManualInstructions();
627578
throw new RuntimeException("Cannot start Docker: no admin privileges and no usable WSL2 Linux distro. " +
628579
"Install Ubuntu with 'wsl --install -d Ubuntu' (requires admin once).");
629580
}
581+
582+
log.info("Installing Ubuntu in WSL. Opening the Windows elevation prompt...");
583+
int exitCode = WindowsElevation.runElevated("wsl --install -d Ubuntu");
584+
585+
if (exitCode == 0) {
586+
log.info("Ubuntu WSL installation started successfully.");
587+
log.info("Please complete the Ubuntu setup (create username/password) when prompted,");
588+
log.info("then run your application again.");
589+
throw new RuntimeException("WSL Ubuntu installed. Please complete setup and restart the application.");
590+
} else {
591+
log.error("The elevation prompt was declined or the installation failed.");
592+
log.error("You can install it manually:");
593+
printWslInstallManualInstructions();
594+
throw new RuntimeException("Cannot start Docker: WSL Ubuntu installation failed. See instructions above.");
595+
}
630596
}
631597
}
632598
}
@@ -1025,47 +991,6 @@ private String runWslCommand(String command, boolean useSudo, int timeoutSeconds
1025991
}
1026992
}
1027993

1028-
private void ensureContainersFeatureEnabled() throws IOException, InterruptedException {
1029-
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", "Get-WindowsOptionalFeature -Online -FeatureName Containers");
1030-
pb.redirectErrorStream(true);
1031-
Process process = pb.start();
1032-
1033-
StringBuilder output = new StringBuilder();
1034-
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
1035-
String line;
1036-
while ((line = reader.readLine()) != null) {
1037-
output.append(line).append("\n");
1038-
}
1039-
}
1040-
1041-
process.waitFor();
1042-
String outputStr = output.toString();
1043-
1044-
if (!outputStr.contains("State : Enabled")) {
1045-
log.info("Enabling Windows Containers feature (requires reboot)...");
1046-
ProcessBuilder enablePb = new ProcessBuilder("powershell.exe", "-Command", "Enable-WindowsOptionalFeature -Online -FeatureName Containers -All");
1047-
enablePb.inheritIO();
1048-
Process enableProcess = enablePb.start();
1049-
enableProcess.waitFor();
1050-
throw new RuntimeException("Windows Containers feature enabled. Reboot required.");
1051-
}
1052-
}
1053-
1054-
private boolean isAdministrator() {
1055-
try {
1056-
ProcessBuilder pb = new ProcessBuilder("net", "session");
1057-
pb.redirectErrorStream(true);
1058-
Process process = pb.start();
1059-
byte[] output = readAllBytes(process.getInputStream());
1060-
int exitCode = process.waitFor();
1061-
log.debug("Admin check (net session) exit code: {}", exitCode);
1062-
return exitCode == 0;
1063-
} catch (IOException | InterruptedException e) {
1064-
log.debug("Admin check failed with exception: {}", e.getMessage());
1065-
return false;
1066-
}
1067-
}
1068-
1069994
private String wslDistro = null;
1070995

1071996
private boolean isWsl2Available() {
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package io.github.intisy.docker;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import java.io.IOException;
7+
import java.nio.charset.StandardCharsets;
8+
import java.util.Base64;
9+
import java.util.concurrent.TimeUnit;
10+
11+
/**
12+
* Detects whether the current JVM runs with administrator privileges and
13+
* runs PowerShell scripts through the Windows elevation (UAC) dialog.
14+
* Shared by docker-java itself and by consumers such as kubernetes-java,
15+
* so elevation behavior stays identical across libraries and machines.
16+
*
17+
* @author Finn Birich
18+
*/
19+
public final class WindowsElevation {
20+
21+
private static final Logger log = LoggerFactory.getLogger(WindowsElevation.class);
22+
23+
/** Returned by {@link #runElevated} when the elevated process could not be launched at all. */
24+
public static final int EXIT_LAUNCH_FAILED = Integer.MIN_VALUE;
25+
26+
private static final long ADMIN_CHECK_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(10);
27+
private static final long ELEVATED_RUN_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(15);
28+
29+
private WindowsElevation() {
30+
}
31+
32+
/**
33+
* Whether the current process runs with administrator privileges.
34+
*
35+
* @implNote {@code net session} succeeds only in an elevated context; this is the
36+
* same probe both libraries previously carried as private copies.
37+
*/
38+
public static boolean isAdministrator() {
39+
try {
40+
ProcessRunner.Result result = ProcessRunner.run(ADMIN_CHECK_TIMEOUT_MILLIS, "net", "session");
41+
log.debug("Admin check (net session) exit code: {}", result.exitCode);
42+
return !result.timedOut && result.exitCode == 0;
43+
} catch (IOException e) {
44+
log.debug("Admin check failed with exception: {}", e.getMessage());
45+
return false;
46+
}
47+
}
48+
49+
/**
50+
* Runs a PowerShell script in an elevated process, opening the Windows
51+
* elevation (UAC) dialog when the current process is not elevated.
52+
* Blocks until the elevated process exits and returns its exit code.
53+
*
54+
* @param powershellScript script to execute elevated; its {@code exit} code is propagated
55+
* @return the elevated script's exit code; a declined UAC dialog yields a non-zero
56+
* code from the launcher, {@link #EXIT_LAUNCH_FAILED} if nothing could be started
57+
* @implNote the script travels as {@code -EncodedCommand} (Base64 UTF-16LE), so no
58+
* quoting or escaping of the script content is ever needed
59+
*/
60+
public static int runElevated(String powershellScript) {
61+
String launcher = launcherCommand(toEncodedCommand(powershellScript));
62+
try {
63+
ProcessRunner.Result result = ProcessRunner.run(ELEVATED_RUN_TIMEOUT_MILLIS,
64+
"powershell.exe", "-NoProfile", "-NonInteractive", "-Command", launcher);
65+
if (!result.output.trim().isEmpty()) {
66+
log.debug("Elevated command output: {}", result.output.trim());
67+
}
68+
if (result.timedOut) {
69+
log.warn("Elevated command timed out");
70+
return EXIT_LAUNCH_FAILED;
71+
}
72+
return result.exitCode;
73+
} catch (IOException e) {
74+
log.warn("Failed to run elevated command: {}", e.getMessage());
75+
return EXIT_LAUNCH_FAILED;
76+
}
77+
}
78+
79+
static String toEncodedCommand(String script) {
80+
return Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
81+
}
82+
83+
static String launcherCommand(String encodedCommand) {
84+
return "$p = Start-Process powershell.exe -ArgumentList "
85+
+ "'-NoProfile','-NonInteractive','-EncodedCommand','" + encodedCommand + "'"
86+
+ " -Verb RunAs -Wait -PassThru; exit $p.ExitCode";
87+
}
88+
}

0 commit comments

Comments
 (0)