Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d34010e495d90c6b35813c264f2cf66734f0bafe (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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*******************************************************************************
 * Copyright (c) 2015 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.ui.launch;

import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.ALLOCATE_PSEUDO_CONSOLE;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.AUTO_REMOVE;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.COMMAND;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.CONNECTION_NAME;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.CONTAINER_NAME;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.CPU_PRIORITY;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.CREATION_DATE;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.DATA_VOLUMES;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.ENABLE_LIMITS;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.ENTRYPOINT;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.ENV_VARIABLES;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.IMAGE_ID;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.IMAGE_NAME;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.INTERACTIVE;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.LINKS;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.MB;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.MEMORY_LIMIT;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.PUBLISHED_PORTS;
import static org.eclipse.linuxtools.internal.docker.ui.launch.IRunDockerImageLaunchConfigurationConstants.PUBLISH_ALL_PORTS;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.layout.PixelConverter;
import org.eclipse.linuxtools.docker.core.IDockerContainer;
import org.eclipse.linuxtools.docker.core.IDockerContainerConfig;
import org.eclipse.linuxtools.docker.core.IDockerHostConfig;
import org.eclipse.linuxtools.docker.core.IDockerImage;
import org.eclipse.linuxtools.docker.core.IDockerImageInfo;
import org.eclipse.linuxtools.docker.core.IDockerPortBinding;
import org.eclipse.linuxtools.docker.ui.Activator;
import org.eclipse.linuxtools.internal.docker.ui.wizards.DataVolumeModel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;

/**
 * Utility class to manage {@link ILaunchConfiguration}
 */
public class LaunchConfigurationUtils {

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"YYYY-MM-dd HH:mm:ss");

	/**
	 * Private constructor for this utility class.
	 */
	private LaunchConfigurationUtils() {
		// empty
	}
	
	/**
	 * @return the ILaunchConfigurationType for the given configuration type.
	 * @param configType
	 *            the id of the configuration type
	 */
	public static ILaunchConfigurationType getLaunchConfigType(
			final String configType) {
		return DebugPlugin.getDefault().getLaunchManager()
				.getLaunchConfigurationType(configType);
	}

	/**
	 * Creates a new {@link ILaunchConfiguration} for the given
	 * {@link IDockerContainer}.
	 * 
	 * @param baseConfigurationName
	 *            the base configuration name to use when creating the
	 *            {@link ILaunchConfiguration}.
	 * @param image
	 *            the {@link IDockerImage} used to create the container
	 * @param containerName
	 *            the actual container name (given by the user or generated by
	 *            the Docker daemon)
	 * @param containerConfig
	 * @param hostConfig
	 *            the user-provided {@link IDockerHostConfig} (created
	 *            container's one)
	 * @param removeWhenExits
	 *            flag to indicate if container should be removed when exited
	 * @return the generated {@link ILaunchConfiguration}
	 * 
	 */
	public static ILaunchConfiguration createLaunchConfiguration(
			final IDockerImage image,
			final IDockerContainerConfig containerConfig,
			final IDockerHostConfig hostConfig, final String containerName,
			final boolean removeWhenExits) {
		try {
			final ILaunchManager manager = DebugPlugin.getDefault()
					.getLaunchManager();
			final ILaunchConfigurationType type = manager
					.getLaunchConfigurationType(
							IRunDockerImageLaunchConfigurationConstants.CONFIG_TYPE_ID);
			final String imageName = image.repoTags().get(0);
			// using the image repo + first tag
			final ILaunchConfigurationWorkingCopy workingCopy = getLaunchConfigurationworkingCopy(
					type, imageName);
			workingCopy.setAttribute(CREATION_DATE,
					DATE_FORMAT.format(new Date()));
			workingCopy.setAttribute(CONNECTION_NAME,
					image.getConnection().getName());
			workingCopy.setAttribute(IMAGE_ID, image.id());
			workingCopy.setAttribute(IMAGE_NAME, image.repoTags().get(0));
			if (containerName != null && !containerName.isEmpty()) {
				workingCopy.setAttribute(CONTAINER_NAME, containerName);
			}
			workingCopy.setAttribute(COMMAND, toString(containerConfig.cmd()));
			workingCopy.setAttribute(ENTRYPOINT,
					toString(containerConfig.entrypoint()));
			// selected ports
			workingCopy.setAttribute(PUBLISH_ALL_PORTS,
					hostConfig.publishAllPorts());
			// format: <containerPort><type>:<hostIP>:<hostPort>
			if (hostConfig.publishAllPorts()) {
				final IDockerImageInfo imageInfo = image.getConnection()
						.getImageInfo(image.id());
				if (imageInfo != null) {
					workingCopy.setAttribute(PUBLISHED_PORTS,
							serializePortBindings(imageInfo.containerConfig()
									.exposedPorts()));
				}
			} else {
				workingCopy.setAttribute(PUBLISHED_PORTS,
						serializePortBindings(hostConfig.portBindings()));
			}
			// links (with format being: "<containerName>:<containerAlias>")
			workingCopy.setAttribute(LINKS, hostConfig.links());
			// env variables
			workingCopy.setAttribute(ENV_VARIABLES, containerConfig.env());
			// volumes
			final List<String> volumes = new ArrayList<>();
			// volumes from other containers
			for (String volumeFrom : hostConfig.volumesFrom()) {
				final DataVolumeModel volume = DataVolumeModel
						.parseVolumeFrom(volumeFrom);
				if (volume != null) {
					volumes.add(volume.toString());
				}
			}
			// bindings to host directory or file
			for (String bind : hostConfig.binds()) {
				final DataVolumeModel volume = DataVolumeModel
						.parseHostBinding(bind);
				if (volume != null) {
					volumes.add(volume.toString());
				}
			}
			// TODO: container path declaration
			
			workingCopy.setAttribute(DATA_VOLUMES, volumes);
			// options
			workingCopy.setAttribute(AUTO_REMOVE, removeWhenExits);
			workingCopy.setAttribute(ALLOCATE_PSEUDO_CONSOLE,
					containerConfig.tty());
			workingCopy.setAttribute(INTERACTIVE, containerConfig.openStdin());
			// resources limitations
			if (containerConfig.memory() != null) {
				workingCopy.setAttribute(ENABLE_LIMITS, true);
				// memory in containerConfig is expressed in bytes
				workingCopy.setAttribute(MEMORY_LIMIT, Long
						.toString(containerConfig.memory().longValue() / MB));
			}
			if (containerConfig.cpuShares() != null) {
				workingCopy.setAttribute(ENABLE_LIMITS, true);
				workingCopy.setAttribute(CPU_PRIORITY,
						containerConfig.cpuShares().toString());
			}
			return workingCopy.doSave();
		} catch (CoreException e) {
			Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
					LaunchMessages.getString(
							"RunDockerImageLaunchConfiguration.creation.failure"), //$NON-NLS-1$
					e));
		}
		return null;
	}

	private static String toString(final List<String> input) {
		final StringBuilder command = new StringBuilder();
		for (Iterator<String> iterator = input.iterator(); iterator
				.hasNext();) {
			String fragment = iterator.next();
			command.append(fragment);
			if (iterator.hasNext()) {
				command.append(" ");
			}
		}
		return command.toString();
	}

	/**
	 * Serializes the given Port Bindings to save them in an
	 * {@link ILaunchConfiguration}
	 * 
	 * @param bindings
	 * @return a {@link List} of port bindings serialized in the following
	 *         format:
	 *         <code>&lt;containerPort&gt;&lt;type&gt;:&lt;hostIP&gt;:&lt;hostPort&gt;</code>
	 *         Note that the <code>&lt;hostIP&gt;</code> part may be empty if
	 *         undefined by the user.
	 */
	public static List<String> serializePortBindings(
			final Map<String, List<IDockerPortBinding>> bindings) {
		final List<String> serializedBindings = new ArrayList<>();
		if (bindings != null) {
			for (Entry<String, List<IDockerPortBinding>> entry : bindings
					.entrySet()) {
				for (IDockerPortBinding portBinding : entry.getValue()) {
					final StringBuilder portBindingBuilder = new StringBuilder();
					portBindingBuilder.append(entry.getKey());
					portBindingBuilder.append(':'); // $NON-NLS-1$
					if (portBinding.hostIp() != null) {
						portBindingBuilder.append(portBinding.hostIp());
					}
					portBindingBuilder.append(':'); // $NON-NLS-1$
					portBindingBuilder.append(portBinding.hostPort());
					serializedBindings.add(portBindingBuilder.toString());
				}
			}
		}
		return serializedBindings;
	}

	/**
	 * Serializes the given Port Bindings to save them in an
	 * {@link ILaunchConfiguration}
	 * 
	 * @param bindings
	 * @return a {@link List} of port bindings serialized in the following
	 *         format:
	 *         <code>&lt;containerPort&gt;:&lt;type&gt;:&lt;hostIP&gt;:&lt;hostPort&gt;</code>
	 *         Note that the <code>&lt;hostIP&gt;</code> part may be empty if
	 *         undefined by the user.
	 */
	public static List<String> serializePortBindings(
			final Set<String> bindings) {
		final List<String> serializedBindings = new ArrayList<>();
		if (bindings != null) {
			for (String portBinding : bindings) {
				final StringBuilder portBindingBuilder = new StringBuilder();
				portBindingBuilder.append(portBinding);
				portBindingBuilder.append(':'); // $NON-NLS-1$
				portBindingBuilder.append(':'); // $NON-NLS-1$
				final String[] containerPort = portBinding.split("/"); // $NON-NLS-1$
				portBindingBuilder.append(containerPort[0]);
				serializedBindings.add(portBindingBuilder.toString());
			}
		}
		return serializedBindings;
	}

	public static int getButtonWidthHint(Button button) {
		/* button.setFont(JFaceResources.getDialogFont()); */
		PixelConverter converter = new PixelConverter(button);
		int widthHint = converter
				.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
		return Math.max(widthHint,
				button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
	}

	/**
	 * Looks-up the {@link ILaunchConfiguration} with the given type and
	 * <strong>IDockerImage's name</strong>.
	 * 
	 * @param type
	 *            the configuration type
	 * @param imageName
	 *            the associated {@link IDockerImage} name
	 * @return the first matching {@link ILaunchConfiguration} or
	 *         <code>null</code> if none was found.
	 * @throws CoreException
	 */
	public static ILaunchConfiguration getLaunchConfigurationByImageName(
			final ILaunchConfigurationType type, final String imageName)
					throws CoreException {
		final ILaunchManager manager = DebugPlugin.getDefault()
				.getLaunchManager();
		ILaunchConfiguration lastLaunchConfiguration = null;
		String lastCreationDate = ""; //$NON-NLS-1$
		for (ILaunchConfiguration launchConfiguration : manager
				.getLaunchConfigurations(type)) {
			final String launchConfigImageName = launchConfiguration
					.getAttribute(IMAGE_NAME, ""); //$NON-NLS-1$
			final String launchConfigCreationDate = launchConfiguration
					.getAttribute(CREATION_DATE, ""); //$NON-NLS-1$
			if (launchConfigImageName.equals(imageName)
					&& launchConfigCreationDate
							.compareTo(lastCreationDate) > 0) {
				lastCreationDate = launchConfigCreationDate;
				lastLaunchConfiguration = launchConfiguration;
			}
		}
		return lastLaunchConfiguration;
	}
	
	/**
	 * Returns the {@link ILaunchConfigurationWorkingCopy} with the given type
	 * and <strong>IDockerImage's name</strong>.
	 * 
	 * @param type
	 *            the configuration type
	 * @param imageName
	 *            the associated {@link IDockerImage} name
	 * @param createIfNotFound
	 *            flag to indicate if a new {@link ILaunchConfiguration} should
	 *            be created if none was found.
	 * @return the ILaunchConfigurationWorkingCopy for the matching
	 *         {@link ILaunchConfiguration} or a new instance if none was found.
	 * @throws CoreException
	 */
	private static ILaunchConfigurationWorkingCopy getLaunchConfigurationworkingCopy(
			final ILaunchConfigurationType type, final String imageName)
					throws CoreException {
		final ILaunchConfiguration existingLaunchConfiguration = getLaunchConfigurationByImageName(
				type, imageName);
		if (existingLaunchConfiguration != null) {
			return existingLaunchConfiguration.getWorkingCopy();
		}
		final ILaunchManager manager = DebugPlugin.getDefault()
				.getLaunchManager();
		final String configurationName = manager
				.generateLaunchConfigurationName(imageName);
		return type.newInstance(null, configurationName);
	}
	
	/**
	 * Looks-up the {@link ILaunchConfiguration} with the given type and
	 * <strong>name</strong>.
	 * 
	 * @param type
	 *            the configuration type
	 * @param name
	 *            the name
	 * @return the first matching {@link ILaunchConfiguration} or
	 *         <code>null</code> if none was found.
	 * @throws CoreException
	 */
	public static ILaunchConfiguration getLaunchConfigurationByName(
			final ILaunchConfigurationType type, final String name)
					throws CoreException {
		final ILaunchManager manager = DebugPlugin.getDefault()
				.getLaunchManager();
		for (ILaunchConfiguration launchConfiguration : manager
				.getLaunchConfigurations(type)) {
			final String launchConfigName = launchConfiguration.getName(); // $NON-NLS-1$
			if (launchConfigName.equals(name)) {
				return launchConfiguration;
			}
		}
		return null;
	}

	/**
	 * Converts the given <code>path</code> to a Unix path if the current OS if
	 * {@link Platform#OS_WIN32}
	 * 
	 * @param path
	 *            the path to convert
	 * @return the converted path or the given path, depending on the current
	 *         OS.
	 * @see <a href=
	 *      http://docs.docker.com/v1.7/userguide/dockervolumes/#mount-a-host-directory-as-a-data-volume">
	 *      http://docs.docker.com/v1.7/userguide/dockervolumes/#mount-a-host-
	 *      directory-as-a-data-volume</a>
	 */
	public static String convertToUnixPath(String path) {
		return convertToUnixPath(Platform.getOS(), path);
	}

	/**
	 * Converts the given path to a portable form, replacing all "\" and ":
	 * " with "/" if the given <code>os</code> is {@link Platform#OS_WIN32}.
	 * 
	 * @param os
	 *            the current OS
	 * @param path
	 *            the path to convert
	 * @return the converted path or the given path
	 * @see LaunchConfigurationUtils#convertToUnixPath(String)
	 * @see {@link Platform#getOS()}
	 */
	public static String convertToUnixPath(final String os, final String path) {
		if (os != null && os.equals(Platform.OS_WIN32)) {
			// replace all "\" with "/" and then drive info (eg "C:/" to "/c/")
			final Matcher m = Pattern.compile("([a-zA-Z]):/")
					.matcher(path.replaceAll("\\\\", "/"));
			if (m.find()) {
				final StringBuffer b = new StringBuffer();
				b.append('/');
				m.appendReplacement(b, m.group(1).toLowerCase());
				b.append('/');
				m.appendTail(b);
				return b.toString();
			}
		}
		return path;
	}

	/**
	 * Converts the given <code>path</code> back to a Windows path if the
	 * current OS if {@link Platform#OS_WIN32}.
	 * 
	 * <p>
	 * Note: This is the revert operation of
	 * {@link LaunchConfigurationUtils#convertToUnixPath(String)}.
	 * </p>
	 * 
	 * @param path
	 *            the path to convert
	 * @return the converted path or the given path, depending on the current
	 *         OS.
	 * @see <a href=
	 *      http://docs.docker.com/v1.7/userguide/dockervolumes/#mount-a-host-directory-as-a-data-volume">
	 *      http://docs.docker.com/v1.7/userguide/dockervolumes/#mount-a-host-
	 *      directory-as-a-data-volume</a>
	 */
	public static String convertToWin32Path(String path) {
		return convertToWin32Path(Platform.getOS(), path);
	}

	/**
	 * Converts the given path to a portable form, replacing all "\" and ":
	 * " with "/" if the given <code>os</code> is {@link Platform#OS_WIN32}.
	 * 
	 * @param os
	 *            the current OS
	 * @param path
	 *            the path to convert
	 * @return the converted path or the given path
	 * @see LaunchConfigurationUtils#convertToWin32Path(String)
	 * @see {@link Platform#getOS()}
	 */
	public static String convertToWin32Path(final String os,
			final String path) {
		if (os != null && os.equals(Platform.OS_WIN32)) {
			// replace all "/" with "\" and then drive info (eg "/c/" to "C:/")
			final Matcher m = Pattern.compile("^/([a-zA-Z])/").matcher(path);
			if (m.find()) {
				final StringBuffer b = new StringBuffer();
				m.appendReplacement(b, m.group(1).toUpperCase());
				b.append(":\\");
				m.appendTail(b);
				return b.toString().replace('/', '\\');
			}
		}
		return path;
	}

}

Back to the top