Skip to content

Commit f6028ca

Browse files
authored
Add core changes for configuring exposed ports (GoogleContainerTools#432)
1 parent 2205d43 commit f6028ca

16 files changed

Lines changed: 268 additions & 9 deletions

File tree

‎jib-core/src/integration-test/java/com/google/cloud/tools/jib/builder/BuildStepsIntegrationTest.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
import com.google.cloud.tools.jib.image.ImageReference;
2222
import com.google.cloud.tools.jib.registry.LocalRegistry;
2323
import java.nio.file.Path;
24+
import java.util.Arrays;
2425
import java.util.Collections;
26+
import org.hamcrest.CoreMatchers;
2527
import org.junit.Assert;
2628
import org.junit.ClassRule;
2729
import org.junit.Rule;
@@ -46,6 +48,7 @@ public void testSteps_forBuildToDockerRegistry() throws Exception {
4648
.setTargetImage(ImageReference.of("localhost:5000", "testimage", "testtag"))
4749
.setMainClass("HelloWorld")
4850
.setJavaArguments(Collections.singletonList("An argument."))
51+
.setExposedPorts(Arrays.asList("1000", "2000-2002/tcp", "3000/udp"))
4952
.build();
5053

5154
Path cacheDirectory = temporaryCacheDirectory.newFolder().toPath();
@@ -64,6 +67,15 @@ public void testSteps_forBuildToDockerRegistry() throws Exception {
6467

6568
String imageReference = "localhost:5000/testimage:testtag";
6669
new Command("docker", "pull", imageReference).run();
70+
Assert.assertThat(
71+
new Command("docker", "inspect", imageReference).run(),
72+
CoreMatchers.containsString(
73+
" \"ExposedPorts\": {\n"
74+
+ " \"1000\": {},\n"
75+
+ " \"2000/tcp\": {},\n"
76+
+ " \"2001/tcp\": {},\n"
77+
+ " \"2002/tcp\": {},\n"
78+
+ " \"3000/udp\": {}"));
6779
Assert.assertEquals(
6880
"Hello, world. An argument.\n", new Command("docker", "run", imageReference).run());
6981
}
@@ -77,6 +89,7 @@ public void testSteps_forBuildToDockerDaemon() throws Exception {
7789
.setTargetImage(ImageReference.of(null, "testdocker", null))
7890
.setMainClass("HelloWorld")
7991
.setJavaArguments(Collections.singletonList("An argument."))
92+
.setExposedPorts(Arrays.asList("1000", "2000-2002/tcp", "3000/udp"))
8093
.build();
8194

8295
Path cacheDirectory = temporaryCacheDirectory.newFolder().toPath();
@@ -87,6 +100,15 @@ public void testSteps_forBuildToDockerDaemon() throws Exception {
87100
Caches.newInitializer(cacheDirectory).setBaseCacheDirectory(cacheDirectory));
88101

89102
buildDockerSteps.run();
103+
Assert.assertThat(
104+
new Command("docker", "inspect", "testdocker").run(),
105+
CoreMatchers.containsString(
106+
" \"ExposedPorts\": {\n"
107+
+ " \"1000\": {},\n"
108+
+ " \"2000/tcp\": {},\n"
109+
+ " \"2001/tcp\": {},\n"
110+
+ " \"2002/tcp\": {},\n"
111+
+ " \"3000/udp\": {}"));
90112
Assert.assertEquals(
91113
"Hello, world. An argument.\n", new Command("docker", "run", "testdocker").run());
92114
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/builder/BuildConfiguration.java‎

Lines changed: 88 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,17 @@
2020
import com.google.cloud.tools.jib.image.json.BuildableManifestTemplate;
2121
import com.google.cloud.tools.jib.image.json.V22ManifestTemplate;
2222
import com.google.cloud.tools.jib.registry.credentials.RegistryCredentials;
23+
import com.google.common.annotations.VisibleForTesting;
2324
import com.google.common.base.Splitter;
25+
import com.google.common.base.Strings;
2426
import com.google.common.collect.ImmutableList;
2527
import com.google.common.collect.ImmutableMap;
2628
import java.util.ArrayList;
2729
import java.util.HashMap;
2830
import java.util.List;
2931
import java.util.Map;
32+
import java.util.regex.Matcher;
33+
import java.util.regex.Pattern;
3034
import javax.annotation.Nullable;
3135
import javax.lang.model.SourceVersion;
3236

@@ -35,6 +39,13 @@ public class BuildConfiguration {
3539

3640
public static class Builder {
3741

42+
/**
43+
* Pattern used for parsing information out of exposed port configurations.
44+
*
45+
* <p>Examples: 100, 200-210, 1000/tcp, 2000/udp, 500-600/tcp
46+
*/
47+
private static final Pattern portPattern = Pattern.compile("(\\d+)(?:-(\\d+))?(/tcp|/udp)?");
48+
3849
// All the parameters below are set to their default values.
3950
@Nullable private ImageReference baseImageReference;
4051
@Nullable private String baseImageCredentialHelperName;
@@ -46,6 +57,7 @@ public static class Builder {
4657
private List<String> javaArguments = new ArrayList<>();
4758
private List<String> jvmFlags = new ArrayList<>();
4859
private Map<String, String> environmentMap = new HashMap<>();
60+
private List<String> exposedPorts = new ArrayList<>();
4961
private Class<? extends BuildableManifestTemplate> targetFormat = V22ManifestTemplate.class;
5062

5163
private BuildLogger buildLogger;
@@ -112,6 +124,13 @@ public Builder setEnvironment(@Nullable Map<String, String> environmentMap) {
112124
return this;
113125
}
114126

127+
public Builder setExposedPorts(@Nullable List<String> exposedPorts) {
128+
if (exposedPorts != null) {
129+
this.exposedPorts = exposedPorts;
130+
}
131+
return this;
132+
}
133+
115134
public Builder setTargetFormat(Class<? extends BuildableManifestTemplate> targetFormat) {
116135
this.targetFormat = targetFormat;
117136
return this;
@@ -154,6 +173,7 @@ public BuildConfiguration build() {
154173
ImmutableList.copyOf(javaArguments),
155174
ImmutableList.copyOf(jvmFlags),
156175
ImmutableMap.copyOf(environmentMap),
176+
expandPortRanges(exposedPorts),
157177
targetFormat);
158178

159179
case 1:
@@ -178,6 +198,63 @@ public BuildConfiguration build() {
178198
throw new IllegalStateException(errorMessage.toString());
179199
}
180200
}
201+
202+
/**
203+
* TODO: Move this to a class in frontend
204+
*
205+
* <p>Converts/validates a list of ports with ranges to an expanded form without ranges.
206+
*
207+
* <p>Example: ["1000/tcp", "2000-2002/tcp"] -> ["1000/tcp", "2000/tcp", "2001/tcp", "2002/tcp"]
208+
*
209+
* @param ports the list of port numbers/ranges
210+
* @return the ports as a list of integers
211+
* @throws NumberFormatException if any of the ports are in an invalid format or out of range
212+
*/
213+
@VisibleForTesting
214+
ImmutableList<String> expandPortRanges(List<String> ports) throws NumberFormatException {
215+
ImmutableList.Builder<String> result = new ImmutableList.Builder<>();
216+
217+
for (String port : ports) {
218+
Matcher matcher = portPattern.matcher(port);
219+
220+
if (!matcher.matches()) {
221+
throw new NumberFormatException(
222+
"Invalid port configuration: '"
223+
+ port
224+
+ "'. Make sure the port is a single number or a range of two numbers separated "
225+
+ "with a '-', with or without protocol specified (e.g. '<portNum>/tcp' or "
226+
+ "'<portNum>/udp').");
227+
}
228+
229+
// Parse protocol
230+
int min = Integer.parseInt(matcher.group(1));
231+
int max = min;
232+
if (!Strings.isNullOrEmpty(matcher.group(2))) {
233+
max = Integer.parseInt(matcher.group(2));
234+
}
235+
String protocol = matcher.group(3);
236+
237+
// Error if configured as 'max-min' instead of 'min-max'
238+
if (min > max) {
239+
throw new NumberFormatException(
240+
"Invalid port range '" + port + "'; smaller number must come first.");
241+
}
242+
243+
// Warn for possibly invalid port numbers
244+
if (min < 1 || max > 65535) {
245+
// TODO: Add details/use HelpfulSuggestions for these warnings
246+
buildLogger.warn("Port number '" + port + "' is out of usual range (1-65535).");
247+
}
248+
249+
// Add all numbers in range to list
250+
for (int portNum = min; portNum <= max; portNum++) {
251+
// TODO: Use a class w/ port number and protocol instead of a string
252+
result.add(portNum + (protocol == null ? "" : protocol));
253+
}
254+
}
255+
256+
return result.build();
257+
}
181258
}
182259

183260
/**
@@ -193,6 +270,10 @@ public static boolean isValidJavaClass(String className) {
193270
return true;
194271
}
195272

273+
public static Builder builder(BuildLogger buildLogger) {
274+
return new Builder(buildLogger);
275+
}
276+
196277
private final BuildLogger buildLogger;
197278
private final ImageReference baseImageReference;
198279
@Nullable private final String baseImageCredentialHelperName;
@@ -204,12 +285,9 @@ public static boolean isValidJavaClass(String className) {
204285
private final ImmutableList<String> javaArguments;
205286
private final ImmutableList<String> jvmFlags;
206287
private final ImmutableMap<String, String> environmentMap;
288+
private final ImmutableList<String> exposedPorts;
207289
private final Class<? extends BuildableManifestTemplate> targetFormat;
208290

209-
public static Builder builder(BuildLogger buildLogger) {
210-
return new Builder(buildLogger);
211-
}
212-
213291
/** Instantiate with {@link Builder#build}. */
214292
private BuildConfiguration(
215293
BuildLogger buildLogger,
@@ -223,6 +301,7 @@ private BuildConfiguration(
223301
ImmutableList<String> javaArguments,
224302
ImmutableList<String> jvmFlags,
225303
ImmutableMap<String, String> environmentMap,
304+
ImmutableList<String> exposedPorts,
226305
Class<? extends BuildableManifestTemplate> targetFormat) {
227306
this.buildLogger = buildLogger;
228307
this.baseImageReference = baseImageReference;
@@ -235,6 +314,7 @@ private BuildConfiguration(
235314
this.javaArguments = javaArguments;
236315
this.jvmFlags = jvmFlags;
237316
this.environmentMap = environmentMap;
317+
this.exposedPorts = exposedPorts;
238318
this.targetFormat = targetFormat;
239319
}
240320

@@ -310,6 +390,10 @@ public ImmutableMap<String, String> getEnvironment() {
310390
return environmentMap;
311391
}
312392

393+
public ImmutableList<String> getExposedPorts() {
394+
return exposedPorts;
395+
}
396+
313397
public Class<? extends BuildableManifestTemplate> getTargetFormat() {
314398
return targetFormat;
315399
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/builder/steps/BuildImageStep.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ private Image<CachedLayer> afterCachedLayersSteps()
102102
imageBuilder.setEnvironment(buildConfiguration.getEnvironment());
103103
imageBuilder.setEntrypoint(entrypoint);
104104
imageBuilder.setJavaArguments(buildConfiguration.getJavaArguments());
105+
imageBuilder.setExposedPorts(buildConfiguration.getExposedPorts());
105106

106107
// Gets the container configuration content descriptor.
107108
return imageBuilder.build();

‎jib-core/src/main/java/com/google/cloud/tools/jib/image/Image.java‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public static class Builder<T extends Layer> {
3131

3232
private ImmutableList<String> entrypoint = ImmutableList.of();
3333
private ImmutableList<String> javaArguments = ImmutableList.of();
34+
private ImmutableList<String> exposedPorts = ImmutableList.of();
3435

3536
/**
3637
* Sets the environment with a map from environment variable names to values.
@@ -90,6 +91,18 @@ public Builder<T> setJavaArguments(List<String> javaArguments) {
9091
return this;
9192
}
9293

94+
/**
95+
* Sets the items in the "ExposedPorts" field in the container configuration.
96+
*
97+
* @param exposedPorts the map of exposed ports to add, with the key in the format it would
98+
* appear in the configuration json (e.g. "portNum/tcp")
99+
* @return this
100+
*/
101+
public Builder<T> setExposedPorts(ImmutableList<String> exposedPorts) {
102+
this.exposedPorts = exposedPorts;
103+
return this;
104+
}
105+
93106
/**
94107
* Adds a layer to the image.
95108
*
@@ -107,7 +120,8 @@ public Image<T> build() {
107120
imageLayersBuilder.build(),
108121
environmentBuilder.build(),
109122
ImmutableList.copyOf(entrypoint),
110-
ImmutableList.copyOf(javaArguments));
123+
ImmutableList.copyOf(javaArguments),
124+
exposedPorts);
111125
}
112126
}
113127

@@ -127,15 +141,20 @@ public static <T extends Layer> Builder<T> builder() {
127141
/** Arguments to pass into main when running the image. */
128142
private final ImmutableList<String> javaArguments;
129143

144+
/** Ports that the container listens on. */
145+
private final ImmutableList<String> exposedPorts;
146+
130147
private Image(
131148
ImageLayers<T> layers,
132149
ImmutableList<String> environment,
133150
ImmutableList<String> entrypoint,
134-
ImmutableList<String> javaArguments) {
151+
ImmutableList<String> javaArguments,
152+
ImmutableList<String> exposedPorts) {
135153
this.layers = layers;
136154
this.environmentBuilder = environment;
137155
this.entrypoint = entrypoint;
138156
this.javaArguments = javaArguments;
157+
this.exposedPorts = exposedPorts;
139158
}
140159

141160
public ImmutableList<String> getEnvironment() {
@@ -150,6 +169,10 @@ public ImmutableList<String> getJavaArguments() {
150169
return javaArguments;
151170
}
152171

172+
public ImmutableList<String> getExposedPorts() {
173+
return exposedPorts;
174+
}
175+
153176
public ImmutableList<T> getLayers() {
154177
return layers.getLayers();
155178
}

‎jib-core/src/main/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplate.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,13 @@
2020
import com.google.cloud.tools.jib.image.DescriptorDigest;
2121
import com.google.cloud.tools.jib.json.JsonTemplate;
2222
import com.google.common.annotations.VisibleForTesting;
23+
import com.google.common.collect.ImmutableList;
24+
import com.google.common.collect.ImmutableSortedMap;
2325
import java.util.ArrayList;
26+
import java.util.Collections;
2427
import java.util.List;
28+
import java.util.Map;
29+
import java.util.SortedMap;
2530
import javax.annotation.Nullable;
2631

2732
/**
@@ -38,6 +43,7 @@
3843
* "Env": ["/usr/bin/java"],
3944
* "Entrypoint": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],
4045
* "Cmd": ["arg1", "arg2"]
46+
* "ExposedPorts": { "6000/tcp":{}, "8000/tcp":{}, "9000/tcp":{} }
4147
* },
4248
* "rootfs": {
4349
* "diff_ids": [
@@ -88,6 +94,9 @@ private static class ConfigurationObjectTemplate implements JsonTemplate {
8894

8995
/** Arguments to pass into main. */
9096
@Nullable private List<String> Cmd;
97+
98+
/** Network ports the container exposes. */
99+
@Nullable private SortedMap<String, Map<?, ?>> ExposedPorts;
91100
}
92101

93102
/**
@@ -118,6 +127,16 @@ public void setContainerCmd(List<String> cmd) {
118127
config.Cmd = cmd;
119128
}
120129

130+
public void setContainerExposedPorts(List<String> exposedPorts) {
131+
// TODO: Do this conversion somewhere else
132+
ImmutableSortedMap.Builder<String, Map<?, ?>> result =
133+
new ImmutableSortedMap.Builder<>(String::compareTo);
134+
for (String port : exposedPorts) {
135+
result.put(port, Collections.emptyMap());
136+
}
137+
config.ExposedPorts = result.build();
138+
}
139+
121140
public void addLayerDiffId(DescriptorDigest diffId) {
122141
rootfs.diff_ids.add(diffId);
123142
}
@@ -141,6 +160,19 @@ List<String> getContainerCmd() {
141160
return config.Cmd;
142161
}
143162

163+
@Nullable
164+
ImmutableList<String> getContainerExposedPorts() {
165+
// TODO: Do this conversion somewhere else
166+
if (config.ExposedPorts == null) {
167+
return null;
168+
}
169+
ImmutableList.Builder<String> ports = new ImmutableList.Builder<>();
170+
for (Map.Entry<String, Map<?, ?>> entry : config.ExposedPorts.entrySet()) {
171+
ports.add(entry.getKey());
172+
}
173+
return ports.build();
174+
}
175+
144176
@VisibleForTesting
145177
DescriptorDigest getLayerDiffId(int index) {
146178
return rootfs.diff_ids.get(index);

‎jib-core/src/main/java/com/google/cloud/tools/jib/image/json/ImageToJsonTranslator.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ public Blob getContainerConfigurationBlob() {
7272
// Sets the main method arguments.
7373
template.setContainerCmd(image.getJavaArguments());
7474

75+
// Sets the exposed ports.
76+
template.setContainerExposedPorts(image.getExposedPorts());
77+
7578
// Serializes into JSON.
7679
return JsonTemplateMapper.toBlob(template);
7780
}

0 commit comments

Comments
 (0)