-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
MountableFile.java
432 lines (371 loc) · 16.3 KB
/
MountableFile.java
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
package org.testcontainers.utility;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;
import org.jetbrains.annotations.NotNull;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.UnstableAPI;
import org.testcontainers.images.builder.Transferable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.zip.Checksum;
import static lombok.AccessLevel.PACKAGE;
import static org.testcontainers.utility.PathUtils.recursiveDeleteDir;
/**
* An abstraction over files and classpath resources aimed at encapsulating all the complexity of generating
* a path that the Docker daemon is about to create a volume mount for.
*/
@RequiredArgsConstructor(access = PACKAGE)
@Slf4j
public class MountableFile implements Transferable {
private static final String TESTCONTAINERS_TMP_DIR_PREFIX = ".testcontainers-tmp-";
private static final String OS_MAC_TMP_DIR = "/tmp";
private static final int BASE_FILE_MODE = 0100000;
private static final int BASE_DIR_MODE = 0040000;
private final String path;
private final Integer forcedFileMode;
@Getter(lazy = true)
private final String resolvedPath = resolvePath();
@Getter(lazy = true)
private final String filesystemPath = resolveFilesystemPath();
private String resourcePath;
/**
* Obtains a {@link MountableFile} corresponding to a resource on the classpath (including resources in JAR files)
*
* @param resourceName the classpath path to the resource
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forClasspathResource(@NotNull final String resourceName) {
return forClasspathResource(resourceName, null);
}
/**
* Obtains a {@link MountableFile} corresponding to a file on the docker host filesystem.
*
* @param path the path to the resource
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forHostPath(@NotNull final String path) {
return forHostPath(path, null);
}
/**
* Obtains a {@link MountableFile} corresponding to a file on the docker host filesystem.
*
* @param path the path to the resource
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forHostPath(final Path path) {
return forHostPath(path, null);
}
/**
* Obtains a {@link MountableFile} corresponding to a resource on the classpath (including resources in JAR files)
*
* @param resourceName the classpath path to the resource
* @param mode octal value of posix file mode (000..777)
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forClasspathResource(@NotNull final String resourceName, Integer mode) {
return new MountableFile(getClasspathResource(resourceName, new HashSet<>()).toString(), mode);
}
/**
* Obtains a {@link MountableFile} corresponding to a file on the docker host filesystem.
*
* @param path the path to the resource
* @param mode octal value of posix file mode (000..777)
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forHostPath(@NotNull final String path, Integer mode) {
return forHostPath(Paths.get(path), mode);
}
/**
* Obtains a {@link MountableFile} corresponding to a file on the docker host filesystem.
*
* @param path the path to the resource
* @param mode octal value of posix file mode (000..777)
* @return a {@link MountableFile} that may be used to obtain a mountable path
*/
public static MountableFile forHostPath(final Path path, Integer mode) {
return new MountableFile(path.toAbsolutePath().toString(), mode);
}
@NotNull
private static URL getClasspathResource(@NotNull final String resourcePath, @NotNull final Set<ClassLoader> classLoaders) {
final Set<ClassLoader> classLoadersToSearch = new HashSet<>(classLoaders);
// try context and system classloaders as well
classLoadersToSearch.add(Thread.currentThread().getContextClassLoader());
classLoadersToSearch.add(ClassLoader.getSystemClassLoader());
classLoadersToSearch.add(MountableFile.class.getClassLoader());
for (final ClassLoader classLoader : classLoadersToSearch) {
if (classLoader == null) {
continue;
}
URL resource = classLoader.getResource(resourcePath);
if (resource != null) {
return resource;
}
// Be lenient if an absolute path was given
if (resourcePath.startsWith("/")) {
resource = classLoader.getResource(resourcePath.replaceFirst("/", ""));
if (resource != null) {
return resource;
}
}
}
throw new IllegalArgumentException("Resource with path " + resourcePath + " could not be found on any of these classloaders: " + classLoadersToSearch);
}
private static String unencodeResourceURIToFilePath(@NotNull final String resource) {
try {
// Convert any url-encoded characters (e.g. spaces) back into unencoded form
return URLDecoder.decode(resource.replaceAll("\\+", "%2B"), Charsets.UTF_8.name())
.replaceFirst("jar:", "")
.replaceFirst("file:", "")
.replaceAll("!.*", "");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
/**
* Obtain a path that the Docker daemon should be able to use to volume mount a file/resource
* into a container. If this is a classpath resource residing in a JAR, it will be extracted to
* a temporary location so that the Docker daemon is able to access it.
*
* @return a volume-mountable path.
*/
private String resolvePath() {
String result = getResourcePath();
// Special case for Windows
if (SystemUtils.IS_OS_WINDOWS && result.startsWith("/")) {
// Remove leading /
result = result.substring(1);
}
return result;
}
/**
* Obtain a path in local filesystem that the Docker daemon should be able to use to volume mount a file/resource
* into a container. If this is a classpath resource residing in a JAR, it will be extracted to
* a temporary location so that the Docker daemon is able to access it.
*
* TODO: rename method accordingly and check if really needed like this
*
* @return
*/
private String resolveFilesystemPath() {
String result = getResourcePath();
if (SystemUtils.IS_OS_WINDOWS && result.startsWith("/")) {
result = PathUtils.createMinGWPath(result).substring(1);
}
return result;
}
private String getResourcePath() {
if (path.contains(".jar!")) {
resourcePath = extractClassPathResourceToTempLocation(this.path);
} else {
resourcePath = unencodeResourceURIToFilePath(path);
}
return resourcePath;
}
/**
* Extract a file or directory tree from a JAR file to a temporary location.
* This allows Docker to mount classpath resources as files.
*
* @param hostPath the path on the host, expected to be of the format 'file:/path/to/some.jar!/classpath/path/to/resource'
* @return the path of the temporary file/directory
*/
private String extractClassPathResourceToTempLocation(final String hostPath) {
File tmpLocation = createTempDirectory();
//noinspection ResultOfMethodCallIgnored
tmpLocation.delete();
String urldecodedJarPath = unencodeResourceURIToFilePath(hostPath);
String internalPath = hostPath.replaceAll("[^!]*!/", "");
try (JarFile jarFile = new JarFile(urldecodedJarPath)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
final String name = entry.getName();
if (name.startsWith(internalPath)) {
log.debug("Copying classpath resource(s) from {} to {} to permit Docker to bind",
hostPath,
tmpLocation);
copyFromJarToLocation(jarFile, entry, internalPath, tmpLocation);
}
}
} catch (IOException e) {
throw new IllegalStateException("Failed to process JAR file when extracting classpath resource: " + hostPath, e);
}
// Mark temporary files/dirs for deletion at JVM shutdown
deleteOnExit(tmpLocation.toPath());
try {
return tmpLocation.getCanonicalPath();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private File createTempDirectory() {
try {
if (SystemUtils.IS_OS_MAC) {
return Files.createTempDirectory(Paths.get(OS_MAC_TMP_DIR), TESTCONTAINERS_TMP_DIR_PREFIX).toFile();
}
return Files.createTempDirectory(TESTCONTAINERS_TMP_DIR_PREFIX).toFile();
} catch (IOException e) {
return new File(TESTCONTAINERS_TMP_DIR_PREFIX + Base58.randomString(5));
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void copyFromJarToLocation(final JarFile jarFile,
final JarEntry entry,
final String fromRoot,
final File toRoot) throws IOException {
String destinationName = entry.getName().replaceFirst(fromRoot, "");
File newFile = new File(toRoot, destinationName);
log.debug("Copying resource {} from JAR file {}",
fromRoot,
jarFile.getName());
if (!entry.isDirectory()) {
// Create parent directories
Path parent = newFile.getAbsoluteFile().toPath().getParent();
parent.toFile().mkdirs();
newFile.deleteOnExit();
try (InputStream is = jarFile.getInputStream(entry)) {
Files.copy(is, newFile.toPath());
} catch (IOException e) {
log.error("Failed to extract classpath resource " + entry.getName() + " from JAR file " + jarFile.getName(), e);
throw e;
}
}
}
private void deleteOnExit(final Path path) {
Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> recursiveDeleteDir(path)));
}
/**
* {@inheritDoc}
*/
@Override
public void transferTo(final TarArchiveOutputStream outputStream, String destinationPathInTar) {
recursiveTar(destinationPathInTar, this.getResolvedPath(), this.getResolvedPath(), outputStream);
}
/*
* Recursively copies a file/directory into a TarArchiveOutputStream
*/
private void recursiveTar(String entryFilename, String rootPath, String itemPath, TarArchiveOutputStream tarArchive) {
try {
final File sourceFile = new File(itemPath).getCanonicalFile(); // e.g. /foo/bar/baz
final File sourceRootFile = new File(rootPath).getCanonicalFile(); // e.g. /foo
final String relativePathToSourceFile = sourceRootFile.toPath().relativize(sourceFile.toPath()).toFile().toString(); // e.g. /bar/baz
final String tarEntryFilename;
if (relativePathToSourceFile.isEmpty()) {
tarEntryFilename = entryFilename; // entry filename e.g. xyz => xyz
} else {
tarEntryFilename = entryFilename + "/" + relativePathToSourceFile; // entry filename e.g. /xyz/bar/baz => /foo/bar/baz
}
final TarArchiveEntry tarEntry = new TarArchiveEntry(sourceFile, tarEntryFilename.replaceAll("^/", ""));
// TarArchiveEntry automatically sets the mode for file/directory, but we can update to ensure that the mode is set exactly (inc executable bits)
tarEntry.setMode(getUnixFileMode(itemPath));
tarArchive.putArchiveEntry(tarEntry);
if (sourceFile.isFile()) {
Files.copy(sourceFile.toPath(), tarArchive);
}
// a directory entry merely needs to exist in the TAR file - there is no data stored yet
tarArchive.closeArchiveEntry();
final File[] children = sourceFile.listFiles();
if (children != null) {
// recurse into child files/directories
for (final File child : children) {
recursiveTar(entryFilename, sourceRootFile.getCanonicalPath(), child.getCanonicalPath(), tarArchive);
}
}
} catch (IOException e) {
log.error("Error when copying TAR file entry: {}", itemPath, e);
throw new UncheckedIOException(e); // fail fast
}
}
@Override
public long getSize() {
final File file = new File(this.getResolvedPath());
if (file.isFile()) {
return file.length();
} else {
return 0;
}
}
@Override
public String getDescription() {
return this.getResolvedPath();
}
@Override
public void updateChecksum(Checksum checksum) {
File file = new File(getResolvedPath());
checksumFile(file, checksum);
}
@SneakyThrows(IOException.class)
private void checksumFile(File file, Checksum checksum) {
Path path = file.toPath();
checksum.update(MountableFile.getUnixFileMode(path));
if (file.isDirectory()) {
try (Stream<Path> stream = Files.walk(path)) {
stream.filter(it -> it != path).forEach(it -> {
checksumFile(it.toFile(), checksum);
});
}
} else {
FileUtils.checksum(file, checksum);
}
}
@Override
public int getFileMode() {
return getUnixFileMode(this.getResolvedPath());
}
private int getUnixFileMode(final String pathAsString) {
final Path path = Paths.get(pathAsString);
if (this.forcedFileMode != null) {
return this.getModeValue(path);
}
return getUnixFileMode(path);
}
@UnstableAPI
public static int getUnixFileMode(final Path path) {
try {
int unixMode = (int) Files.readAttributes(path, "unix:mode").get("mode");
// Truncate mode bits for z/OS
if ("OS/390".equals(SystemUtils.OS_NAME) ||
"z/OS".equals(SystemUtils.OS_NAME) ||
"zOS".equals(SystemUtils.OS_NAME) ) {
unixMode &= TarConstants.MAXID;
unixMode |= Files.isDirectory(path) ? 040000 : 0100000;
}
return unixMode;
} catch (IOException | UnsupportedOperationException e) {
// fallback for non-posix environments
int mode = DEFAULT_FILE_MODE;
if (Files.isDirectory(path)) {
mode = DEFAULT_DIR_MODE;
} else if (Files.isExecutable(path)) {
mode |= 0111; // equiv to +x for user/group/others
}
return mode;
}
}
private int getModeValue(final Path path) {
int result = Files.isDirectory(path) ? BASE_DIR_MODE : BASE_FILE_MODE;
return result | this.forcedFileMode;
}
}