forked from docker-java/docker-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildImageCmdImpl.java
More file actions
274 lines (217 loc) · 6.93 KB
/
Copy pathBuildImageCmdImpl.java
File metadata and controls
274 lines (217 loc) · 6.93 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
266
267
268
269
270
271
272
273
274
package com.github.dockerjava.core.command;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import com.github.dockerjava.api.DockerClientException;
import com.github.dockerjava.api.command.BuildImageCmd;
import com.github.dockerjava.core.CompressArchiveUtil;
import com.google.common.base.Preconditions;
/**
*
* Build an image from Dockerfile.
*
* TODO: http://docs.docker.com/reference/builder/#dockerignore
*
*/
public class BuildImageCmdImpl extends AbstrDockerCmd<BuildImageCmd, InputStream> implements BuildImageCmd {
private static final Pattern ADD_OR_COPY_PATTERN = Pattern
.compile("^(ADD|COPY)\\s+(.*)\\s+(.*)$");
private static final Pattern ENV_PATTERN = Pattern
.compile("^ENV\\s+(.*)\\s+(.*)$");
private InputStream tarInputStream = null;
private String tag;
private boolean noCache;
private boolean remove = true;
private boolean quiet;
public BuildImageCmdImpl(BuildImageCmd.Exec exec, File dockerFolder) {
super(exec);
Preconditions.checkNotNull(dockerFolder, "dockerFolder is null");
withTarInputStream(buildDockerFolderTar(dockerFolder));
}
public BuildImageCmdImpl(BuildImageCmd.Exec exec, InputStream tarInputStream) {
super(exec);
Preconditions.checkNotNull(tarInputStream, "tarInputStream is null");
withTarInputStream(tarInputStream);
}
@Override
public InputStream getTarInputStream() {
return tarInputStream;
}
@Override
public BuildImageCmdImpl withTarInputStream(InputStream tarInputStream) {
Preconditions.checkNotNull(tarInputStream, "tarInputStream is null");
this.tarInputStream = tarInputStream;
return this;
}
@Override
public BuildImageCmdImpl withTag(String tag) {
Preconditions.checkNotNull(tag, "Tag is null");
this.tag = tag;
return this;
}
@Override
public String getTag() {
return tag;
}
@Override
public boolean hasNoCacheEnabled() {
return noCache;
}
@Override
public boolean hasRemoveEnabled() {
return remove;
}
@Override
public boolean isQuiet() {
return quiet;
}
@Override
public BuildImageCmdImpl withNoCache() {
return withNoCache(true);
}
@Override
public BuildImageCmdImpl withNoCache(boolean noCache) {
this.noCache = noCache;
return this;
}
@Override
public BuildImageCmdImpl withRemove() {
return withRemove(true);
}
@Override
public BuildImageCmdImpl withRemove(boolean rm) {
this.remove = rm;
return this;
}
@Override
public BuildImageCmdImpl withQuiet() {
return withQuiet(true);
}
@Override
public BuildImageCmdImpl withQuiet(boolean quiet) {
this.quiet = quiet;
return this;
}
@Override
public String toString() {
return new StringBuilder("build ")
.append(tag != null ? "-t " + tag + " " : "")
.append(noCache ? "--nocache=true " : "")
.append(quiet ? "--quiet=true " : "")
.append(!remove ? "--rm=false " : "")
.toString();
}
protected InputStream buildDockerFolderTar(File dockerFolder) {
Preconditions.checkArgument(dockerFolder.exists(),
"Path %s doesn't exist", dockerFolder);
Preconditions.checkArgument(dockerFolder.isDirectory(),
"Folder %s doesn't exist", dockerFolder);
Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(),
"Dockerfile doesn't exist in " + dockerFolder);
// ARCHIVE TAR
String archiveNameWithOutExtension = UUID.randomUUID().toString();
File dockerFolderTar = null;
try {
File dockerFile = new File(dockerFolder, "Dockerfile");
List<String> dockerFileContent = FileUtils.readLines(dockerFile);
if (dockerFileContent.size() <= 0) {
throw new DockerClientException(String.format(
"Dockerfile %s is empty", dockerFile));
}
List<File> filesToAdd = new ArrayList<File>();
filesToAdd.add(dockerFile);
Map<String, String> environmentMap = new HashMap<String, String>();
int lineNumber = 0;
for (String cmd : dockerFileContent) {
lineNumber++;
if (cmd.trim().isEmpty() || cmd.startsWith("#"))
continue; // skip emtpy and commend lines
final Matcher envMatcher = ENV_PATTERN.matcher(cmd.trim());
if (envMatcher.find()) {
if (envMatcher.groupCount() != 2)
throw new DockerClientException(String.format(
"Wrong ENV format on line [%d]", lineNumber));
String variable = envMatcher.group(1).trim();
String value = envMatcher.group(2).trim();
environmentMap.put(variable, value);
}
final Matcher matcher = ADD_OR_COPY_PATTERN.matcher(cmd.trim());
if (matcher.find()) {
if (matcher.groupCount() != 3) {
throw new DockerClientException(String.format(
"Wrong ADD or COPY format on line [%d]",
lineNumber));
}
String extractedResource = matcher.group(2);
String resource = filterForEnvironmentVars(
extractedResource, environmentMap).trim();
if (isFileResource(resource)) {
File src = new File(resource);
if (!src.isAbsolute()) {
src = new File(dockerFolder, resource)
.getCanonicalFile();
} else {
throw new DockerClientException(String.format(
"Source file %s must be relative to %s",
src, dockerFolder));
}
if (!src.exists()) {
throw new DockerClientException(String.format(
"Source file %s doesn't exist", src));
}
if (src.isDirectory()) {
filesToAdd.addAll(FileUtils.listFiles(src, null,
true));
} else {
filesToAdd.add(src);
}
}
}
}
dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder,
filesToAdd, archiveNameWithOutExtension);
return FileUtils.openInputStream(dockerFolderTar);
} catch (IOException ex) {
FileUtils.deleteQuietly(dockerFolderTar);
throw new DockerClientException(
"Error occurred while preparing Docker context folder.", ex);
}
}
private String filterForEnvironmentVars(String extractedResource,
Map<String, String> environmentMap) {
if (environmentMap.size() > 0) {
String currentResourceContent = extractedResource;
for (Map.Entry<String, String> entry : environmentMap.entrySet()) {
String variable = entry.getKey();
String replacementValue = entry.getValue();
// handle: $VARIABLE case
currentResourceContent = currentResourceContent.replaceAll(
"\\$" + variable, replacementValue);
// handle ${VARIABLE} case
currentResourceContent = currentResourceContent.replaceAll(
"\\$\\{" + variable + "\\}", replacementValue);
}
return currentResourceContent;
} else
return extractedResource;
}
private static boolean isFileResource(String resource) {
URI uri;
try {
uri = new URI(resource);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return uri.getScheme() == null || "file".equals(uri.getScheme());
}
}