Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 359f4f8fbacbcaa23e67468317024441bc36ca82 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2015, 2016 Red Hat.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat - Initial Contribution
 *******************************************************************************/
package org.eclipse.linuxtools.internal.docker.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.linuxtools.docker.core.Activator;
import org.eclipse.linuxtools.docker.core.Messages;
import org.eclipse.osgi.util.NLS;

/**
 * Utility class to discover Docker machines using the 'docker-machine' command
 * line in a process.
 */
public class DockerMachine {

	private static Object lock = new Object();

	/**
	 * @param pathToDockerMachine
	 *            the path to 'docker-machine' stored in the preferences
	 * @return the names of the existing Docker Machines
	 */
	public static String[] getNames(final String pathToDockerMachine) {
		return execute(pathToDockerMachine, new String[] { "ls", "-q" }); //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * @param name
	 *            the name of the Docker Machine to inspect
	 * @param dockerMachineInstallDir
	 *            the installation directory for Docker Machine
	 * @param vmDriverInstallDir
	 *            the installation directory for the underlying VM driver used
	 *            by Docker Machine
	 * @return the host URI to use to connect to it
	 */
	public static String getHost(final String name,
			final String dockerMachineInstallDir,
			final String vmDriverInstallDir) {
		final String[] res = execute(dockerMachineInstallDir,
				new String[] { "url", name }, //$NON-NLS-1$
				vmDriverInstallDir);
		return res.length == 1 ? res[0] : null;
	}

	/**
	 * @param name
	 *            the name of the Docker Machine to inspect
	 * @param pathToDockerMachine
	 *            the path to 'docker-machine' stored in the preferences
	 * @param vmDriverInstallDir
	 *            the installation directory for the underlying VM driver used
	 *            by Docker Machine
	 * @return the path to the directory containing the certificates
	 */
	public static String getCertPath(final String name,
			final String pathToDockerMachine, final String vmDriverInstallDir) {
		final String[] envVariables = execute(pathToDockerMachine,
				new String[] { "env", name }, //$NON-NLS-1$
				vmDriverInstallDir);
		for (String envVariable : envVariables) {
			if (envVariable.contains("DOCKER_CERT_PATH")) { //$NON-NLS-1$
				// DOCKER_CERT_PATH="/path/to/cert-folder"
				return envVariable.split("=")[1].replace("\"", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			}
		}
		return null;
	}

	/**
	 * Executes the command given in parameter
	 * 
	 * @param args
	 *            command arguments
	 * @return the lines read in the {@link Process}' {@link InputStream} or an
	 *         empty array if the {@code docker-machine} command could not be
	 *         found in the {@code PATH}.
	 */
	private static String[] execute(final String dockerMachineInstallDir,
			final String[] args, final String... extraPaths) {
		synchronized (lock) {
			// check that the 'docker-machine' can be found in the given
			// 'dockerMachineInstallDir'
			final boolean dockerMachineCommandExists = checkPathToDockerMachine(
					dockerMachineInstallDir);
			if (!dockerMachineCommandExists) {
				// log a warning and exit
				Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID,
						NLS.bind(Messages.Docker_Machine_Command_Not_Found,
								dockerMachineInstallDir)));
				return new String[0];
			}
			final String[] command = new String[args.length + 1];
			command[0] = Paths.get(dockerMachineInstallDir,
					getDockerMachineExecutableName()).toString();
			System.arraycopy(args, 0, command, 1, args.length);
			try {
				final ProcessBuilder processBuilder = new ProcessBuilder(
						command);
				final Map<String, String> environment = processBuilder
						.environment();
				final StringBuilder path = new StringBuilder();
				for (String extraPath : extraPaths) {
					path.append(File.pathSeparator).append(extraPath);
				}
				final String newEnvPath = environment.get("PATH") //$NON-NLS-1$
						+ path.toString();
				environment.put("PATH", newEnvPath); //$NON-NLS-1$

				final Process p = processBuilder.start();
				p.waitFor();
				if (p.exitValue() == 0) {
					final List<String> result = new ArrayList<>();
					try (final InputStream inputStream = p.getInputStream();
							final BufferedReader buff = new BufferedReader(
									new InputStreamReader(inputStream))) {
						String line;
						while ((line = buff.readLine()) != null) {
							result.add(line);
						}
					}
					return result.toArray(new String[0]);
				} else {
					final StringBuffer errorMessage = new StringBuffer();
					try (final InputStream errorStream = p.getErrorStream();
							final BufferedReader buff = new BufferedReader(
									new InputStreamReader(errorStream))) {
						String line;
						while ((line = buff.readLine()) != null) {
							errorMessage.append(line).append('\n'); // $NON-NLS-1$
						}
					}
					Activator.log(new Status(IStatus.WARNING,
							Activator.PLUGIN_ID,
							NLS.bind(Messages.Docker_Machine_Process_Error,
									new Object[] {
											Stream.of(command).collect(
													Collectors.joining(" ")),
											p.exitValue(),
											errorMessage.toString() })));
				}
			} catch (IOException | InterruptedException e) {
				Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
						NLS.bind(Messages.Docker_Machine_Process_Exception,
								Stream.of(command)
										.collect(Collectors.joining(" ")),
								e)));
			}
			return new String[0];
		}
	}

	/**
	 * Checks that the 'docker-machine' command exists in the given {@code path}
	 * 
	 * @param path
	 *            to path to use to look for the 'docker-machine' command
	 * @return <code>true</code> if the command was found, <code>false</code>
	 *         otherwise.
	 */
	public static boolean checkPathToDockerMachine(final String path) {
		for (String pathFragment : path.split(File.pathSeparator)) {
			final File pathToDockerMachine = new File(pathFragment,
					getDockerMachineExecutableName());
			if (pathToDockerMachine.exists()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @return the name of the Docker Machine executable, depending on the
	 *         current operating system.
	 */
	private static String getDockerMachineExecutableName() {
		if (SystemUtils.isWindows()) {
			return "docker-machine.exe"; //$NON-NLS-1$
		}
		return "docker-machine"; //$NON-NLS-1$
	}
}

Back to the top