Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f58778edb7de9f6bc8dcea91be72f970a9686d7e (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
/*******************************************************************************
 * Copyright (c) 2017 Red Hat Inc. and others.
 * 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 java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Map;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.linuxtools.docker.core.DockerException;
import org.eclipse.linuxtools.docker.core.IDockerConnection;
import org.eclipse.linuxtools.docker.core.IDockerContainerConfig;
import org.eclipse.linuxtools.docker.core.IDockerContainerExit;
import org.eclipse.linuxtools.docker.core.IDockerContainerInfo;
import org.eclipse.linuxtools.docker.core.IDockerContainerState;
import org.eclipse.linuxtools.docker.core.IDockerHostConfig;
import org.eclipse.linuxtools.docker.ui.Activator;
import org.eclipse.linuxtools.docker.ui.launch.Messages;
import org.eclipse.linuxtools.internal.docker.core.DockerConnection;
import org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig;
import org.eclipse.linuxtools.internal.docker.core.DockerHostConfig;

public class ContainerCommandProcess extends Process {

	private String containerId;
	private IDockerConnection connection;
	private String imageName;
	private PipedInputStream stdout;
	private PipedInputStream stderr;
	private Map<String, String> remoteVolumes;
	private boolean keepContainer;
	private Thread thread;

	public ContainerCommandProcess(IDockerConnection connection,
			String imageName, String containerId,
			Map<String, String> remoteVolumes,
			boolean keepContainer) {
		this.connection = connection;
		this.imageName = imageName;
		this.containerId = containerId;
		this.remoteVolumes = remoteVolumes;
		this.stdout = new PipedInputStream();
		this.stderr = new PipedInputStream();
		this.keepContainer = keepContainer;
		// Lambda Runnable
		Runnable logContainer = () -> {
			PipedOutputStream pipedOut = null;
			PipedOutputStream pipedErr = null;
			try (PipedOutputStream pipedStdout = new PipedOutputStream(stdout);
					PipedOutputStream pipedStderr = new PipedOutputStream(
							stderr)) {
				pipedOut = pipedStdout;
				pipedErr = pipedStderr;
				connection.attachLog(containerId, pipedStdout, pipedStderr);
				pipedStdout.flush();
				pipedStderr.flush();
			} catch (DockerException | InterruptedException | IOException e) {
				// do nothing but flush/close output streams
				if (pipedOut != null) {
					try {
						pipedOut.flush();
					} catch (IOException e1) {
						// ignore
					}
				}
				if (pipedErr != null) {
					try {
						pipedErr.flush();
					} catch (IOException e1) {
						// ignore
					}
				}
			}
		};

		// start the thread
		this.thread = new Thread(logContainer);
		this.thread.start();
	}

	@Override
	public void destroy() {
		try {
			try {
				// TODO: see if there is a better way of draining the
				// container output before closing the streams. Note
				// that trying to join the attachLog thread does not
				// work.
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				// ignore
			}
			thread.interrupt();
			while (thread.isAlive()) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// ignore
				}
			}
			this.stdout.close();
			this.stderr.close();
		} catch (IOException e) {
			// ignore
		}
	}

	@Override
	public int exitValue() {
		IDockerContainerInfo info = connection
				.getContainerInfo(containerId);
		if (info != null) {
			IDockerContainerState state = info.state();
			if (state != null) {
				if (state.paused() || state.restarting() || state.running()) {
					throw new IllegalThreadStateException(
							LaunchMessages.getFormattedString(
									"ContainerNotFinished.msg", containerId)); //$NON-NLS-1$
				}
				return state.exitCode();
			}
		}
		return -1;
	}

	@Override
	public InputStream getErrorStream() {
		return stderr;
	}

	@Override
	public InputStream getInputStream() {
		return stdout;
	}

	@Override
	public OutputStream getOutputStream() {
		return new ByteArrayOutputStream();
	}

	/**
	 * A blocking input stream that waits until data is available.
	 */
	private class BlockingInputStream extends InputStream {
		private InputStream in;

		public BlockingInputStream(InputStream in) {
			this.in = in;
		}

		@Override
		public int read() throws IOException {
			return in.read();
		}
	}

	private class CopyVolumesFromImageJob extends Job {

		private static final String COPY_VOLUMES_FROM_JOB_TITLE = "ContainerLaunch.copyVolumesFromJob.title"; //$NON-NLS-1$
		private static final String COPY_VOLUMES_FROM_DESC = "ContainerLaunch.copyVolumesFromJob.desc"; //$NON-NLS-1$
		private static final String COPY_VOLUMES_FROM_TASK = "ContainerLaunch.copyVolumesFromJob.task"; //$NON-NLS-1$

		private final Map<String, String> remoteVolumes;
		private final IDockerConnection connection;
		private final String imageName;

		public CopyVolumesFromImageJob(IDockerConnection connection,
				String imageName, Map<String, String> remoteVolumes) {
			super(Messages.getString(COPY_VOLUMES_FROM_JOB_TITLE));
			this.remoteVolumes = remoteVolumes;
			this.connection = connection;
			this.imageName = imageName;
		}

		@Override
		protected IStatus run(final IProgressMonitor monitor) {
			monitor.beginTask(Messages.getFormattedString(
					COPY_VOLUMES_FROM_DESC, imageName), remoteVolumes.size());
			String containerId = null;
			try {
				DockerContainerConfig.Builder builder = new DockerContainerConfig.Builder()
						.cmd("/bin/sh").image(imageName); //$NON-NLS-1$
				IDockerContainerConfig config = builder.build();
				DockerHostConfig.Builder hostBuilder = new DockerHostConfig.Builder();
				IDockerHostConfig hostConfig = hostBuilder.build();
				containerId = ((DockerConnection) connection)
						.createContainer(config, hostConfig, null);
				for (String volume : remoteVolumes.keySet()) {
					try {
						monitor.setTaskName(Messages.getFormattedString(
								COPY_VOLUMES_FROM_TASK, volume));
						monitor.worked(1);

						InputStream in = ((DockerConnection) connection)
								.copyContainer(containerId,
										remoteVolumes.get(volume));

						/*
						 * The input stream from copyContainer might be
						 * incomplete or non-blocking so we should wrap it in a
						 * stream that is guaranteed to block until data is
						 * available.
						 */
						TarArchiveInputStream k = new TarArchiveInputStream(
								new BlockingInputStream(in));
						TarArchiveEntry te = null;
						IPath currDir = new Path(volume).removeLastSegments(1);
						currDir.toFile().mkdirs();
						while ((te = k.getNextTarEntry()) != null) {
							long size = te.getSize();
							IPath path = currDir;
							path = path.append(te.getName());
							File f = new File(path.toOSString());
							if (te.isDirectory()) {
								f.mkdir();
								continue;
							} else {
								f.createNewFile();
							}
							FileOutputStream os = new FileOutputStream(f);
							int bufferSize = ((int) size > 4096 ? 4096
									: (int) size);
							byte[] barray = new byte[bufferSize];
							int result = -1;
							while ((result = k.read(barray, 0,
									bufferSize)) > -1) {
								if (monitor.isCanceled()) {
									monitor.done();
									k.close();
									os.close();
									return Status.CANCEL_STATUS;
								}
								os.write(barray, 0, result);
							}
							os.close();
						}
						k.close();
					} catch (final DockerException e) {
						// ignore
					}
				}
			} catch (InterruptedException e) {
				// do nothing
			} catch (IOException e) {
				Activator.log(e);
			} catch (DockerException e1) {
				Activator.log(e1);
			} finally {
				if (containerId != null) {
					try {
						((DockerConnection) connection)
								.removeContainer(containerId);
					} catch (DockerException | InterruptedException e) {
						// ignore
					}
				}
				monitor.done();
			}
			return Status.OK_STATUS;

		}
	}

	@Override
	public int waitFor() throws InterruptedException {
		try {
			IDockerContainerExit exit = connection
					.waitForContainer(containerId);
			thread.interrupt();
			while (thread.isAlive()) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// ignore
				}
			}
			connection.stopLoggingThread(containerId);
			if (!keepContainer) {
				connection.removeContainer(containerId);
			}
			if (!((DockerConnection) connection).isLocal()) {
				CopyVolumesFromImageJob job = new CopyVolumesFromImageJob(
						connection, imageName, remoteVolumes);
				job.schedule();
				job.join();
			}
			return exit.statusCode();
		} catch (DockerException e) {
			return -1;
		}
	}

	public String getImage() {
		return imageName;
	}

}

Back to the top