forked from docker-java/docker-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerfile.java
More file actions
265 lines (210 loc) · 9.34 KB
/
Copy pathDockerfile.java
File metadata and controls
265 lines (210 loc) · 9.34 KB
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
package com.github.dockerjava.core.dockerfile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.core.GoLangFileMatch;
import com.github.dockerjava.core.exception.GoLangFileMatchException;
import com.github.dockerjava.core.util.CompressArchiveUtil;
import com.github.dockerjava.core.util.FilePathUtil;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
/**
* Parse a Dockerfile.
*/
public class Dockerfile {
public final File dockerFile;
private final File baseDirectory;
public Dockerfile(File dockerFile, File baseDirectory) {
if (!dockerFile.exists()) {
throw new IllegalStateException(String.format("Dockerfile %s does not exist", dockerFile.getAbsolutePath()));
}
if (!dockerFile.isFile()) {
throw new IllegalStateException(String.format("Dockerfile %s is not a file", dockerFile.getAbsolutePath()));
}
this.dockerFile = dockerFile;
if (!baseDirectory.exists()) {
throw new IllegalStateException(String.format("Base directory %s does not exist", baseDirectory.getAbsolutePath()));
}
if (!baseDirectory.isDirectory()) {
throw new IllegalStateException(String.format("Base directory %s is not a directory", baseDirectory.getAbsolutePath()));
}
this.baseDirectory = baseDirectory;
}
private static class LineTransformer implements Function<String, Optional<? extends DockerfileStatement>> {
private int line = 0;
@Override
public Optional<? extends DockerfileStatement> apply(String input) {
try {
line++;
return DockerfileStatement.createFromLine(input);
} catch (Exception ex) {
throw new DockerClientException("Error on dockerfile line " + line);
}
}
}
public Iterable<DockerfileStatement> getStatements() throws IOException {
Collection<String> dockerFileContent = FileUtils.readLines(dockerFile);
if (dockerFileContent.size() <= 0) {
throw new DockerClientException(String.format("Dockerfile %s is empty", dockerFile));
}
Collection<Optional<? extends DockerfileStatement>> optionals = Collections2.transform(dockerFileContent,
new LineTransformer());
return Optional.presentInstances(optionals);
}
public List<String> getIgnores() throws IOException {
List<String> ignores = new ArrayList<>();
File dockerIgnoreFile = new File(baseDirectory, ".dockerignore");
if (dockerIgnoreFile.exists()) {
int lineNumber = 0;
List<String> dockerIgnoreFileContent = FileUtils.readLines(dockerIgnoreFile);
for (String pattern : dockerIgnoreFileContent) {
lineNumber++;
pattern = pattern.trim();
if (pattern.isEmpty()) {
continue; // skip empty lines
}
pattern = FilenameUtils.normalize(pattern);
try {
ignores.add(pattern);
} catch (GoLangFileMatchException e) {
throw new DockerClientException(String.format(
"Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber));
}
}
}
return ignores;
}
public ScannedResult parse() throws IOException {
return new ScannedResult();
}
/**
* Result of scanning / parsing a docker file.
*/
public class ScannedResult {
final List<String> ignores;
final List<File> filesToAdd = new ArrayList<>();
public InputStream buildDockerFolderTar() {
return buildDockerFolderTar(baseDirectory);
}
public InputStream buildDockerFolderTar(File directory) {
File dockerFolderTar = null;
try {
final String archiveNameWithOutExtension = UUID.randomUUID().toString();
dockerFolderTar = CompressArchiveUtil.archiveTARFiles(directory, filesToAdd,
archiveNameWithOutExtension);
final FileInputStream tarInputStream = FileUtils.openInputStream(dockerFolderTar);
final File tarFile = dockerFolderTar;
return new InputStream() {
@Override
public int available() throws IOException {
return tarInputStream.available();
}
@Override
public int read() throws IOException {
return tarInputStream.read();
}
@Override
public int read(byte[] buff, int offset, int len) throws IOException {
return tarInputStream.read(buff, offset, len);
}
@Override
public void close() throws IOException {
IOUtils.closeQuietly(tarInputStream);
FileUtils.deleteQuietly(tarFile);
}
};
} catch (IOException ex) {
FileUtils.deleteQuietly(dockerFolderTar);
throw new DockerClientException("Error occurred while preparing Docker context folder.", ex);
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("ignores", ignores).add("filesToAdd", filesToAdd).toString();
}
public ScannedResult() throws IOException {
ignores = getIgnores();
String matchingIgnorePattern = effectiveMatchingIgnorePattern(dockerFile);
if (matchingIgnorePattern != null) {
throw new DockerClientException(String.format(
"Dockerfile is excluded by pattern '%s' in .dockerignore file", matchingIgnorePattern));
}
addFilesInDirectory(baseDirectory);
}
/**
* Adds all files found in <code>directory</code> and subdirectories to
* <code>filesToAdd</code> collection. It also adds any empty directories
* if found.
*
* @param directory directory
* @throws DockerClientException when IO error occurs
*/
private void addFilesInDirectory(File directory) {
File[] files = directory.listFiles();
if (files == null) {
throw new DockerClientException("Failed to read build context directory: " + baseDirectory.getAbsolutePath());
}
if (files.length != 0) {
for (File f : files) {
if (f.isDirectory()) {
addFilesInDirectory(f);
} else if (effectiveMatchingIgnorePattern(f) == null) {
filesToAdd.add(f);
}
}
// base directory should at least contains Dockerfile, but better check
} else if (!isBaseDirectory(directory)) {
// add empty directory
filesToAdd.add(directory);
}
}
private boolean isBaseDirectory(File directory) {
return directory.compareTo(baseDirectory) == 0;
}
/**
* Returns all matching ignore patterns for the given file name.
*/
private List<String> matchingIgnorePatterns(String fileName) {
List<String> matches = new ArrayList<>();
int lineNumber = 0;
for (String pattern : ignores) {
String goLangPattern = pattern.startsWith("!") ? pattern.substring(1) : pattern;
lineNumber++;
try {
if (GoLangFileMatch.match(goLangPattern, fileName)) {
matches.add(pattern);
}
} catch (GoLangFileMatchException e) {
throw new DockerClientException(String.format(
"Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber));
}
}
return matches;
}
/**
* Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like "!Dockerfile"
* will be respected.
*/
private String effectiveMatchingIgnorePattern(File file) {
// normalize path to replace '/' to '\' on Windows
String relativeFilename = FilenameUtils.normalize(FilePathUtil.relativize(baseDirectory, file));
List<String> matchingPattern = matchingIgnorePatterns(relativeFilename);
if (matchingPattern.isEmpty()) {
return null;
}
String lastMatchingPattern = matchingPattern.get(matchingPattern.size() - 1);
return !lastMatchingPattern.startsWith("!") ? lastMatchingPattern : null;
}
}
}