Skip to content

Commit f600c13

Browse files
authored
Move map<->list translation out of ContainerConfigurationTemplate (GoogleContainerTools#537)
1 parent ec36489 commit f600c13

10 files changed

Lines changed: 189 additions & 69 deletions

File tree

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import com.google.cloud.tools.jib.image.Layer;
2828
import com.google.cloud.tools.jib.image.LayerCountMismatchException;
2929
import com.google.cloud.tools.jib.image.LayerPropertyNotFoundException;
30+
import com.google.cloud.tools.jib.image.json.BadContainerConfigurationFormatException;
3031
import com.google.cloud.tools.jib.image.json.ContainerConfigurationTemplate;
3132
import com.google.cloud.tools.jib.image.json.JsonToImageTranslator;
3233
import com.google.cloud.tools.jib.image.json.ManifestTemplate;
@@ -97,7 +98,8 @@ public ListenableFuture<BaseImageWithAuthorization> getFuture() {
9798
@Override
9899
public BaseImageWithAuthorization call()
99100
throws IOException, RegistryException, LayerPropertyNotFoundException,
100-
LayerCountMismatchException, ExecutionException, RegistryAuthenticationFailedException {
101+
LayerCountMismatchException, ExecutionException, BadContainerConfigurationFormatException,
102+
RegistryAuthenticationFailedException {
101103
buildConfiguration
102104
.getBuildLogger()
103105
.lifecycle("Getting base image " + buildConfiguration.getBaseImageReference() + "...");
@@ -156,10 +158,12 @@ public BaseImageWithAuthorization call()
156158
* @throws LayerCountMismatchException if the manifest and configuration contain conflicting layer
157159
* information
158160
* @throws LayerPropertyNotFoundException if adding image layers fails
161+
* @throws BadContainerConfigurationFormatException if the container configuration is in a bad
162+
* format
159163
*/
160164
private Image<Layer> pullBaseImage(@Nullable Authorization registryCredentials)
161165
throws IOException, RegistryException, LayerPropertyNotFoundException,
162-
LayerCountMismatchException {
166+
LayerCountMismatchException, BadContainerConfigurationFormatException {
163167
RegistryClient registryClient =
164168
RegistryClient.factory(
165169
buildConfiguration.getBaseImageRegistry(),

‎jib-core/src/main/java/com/google/cloud/tools/jib/configuration/Port.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.google.cloud.tools.jib.configuration;
1818

1919
import java.util.Objects;
20+
import javax.annotation.Nullable;
2021

2122
/** Holds port number and protocol for an exposed port. */
2223
public class Port {
@@ -36,6 +37,20 @@ public enum Protocol {
3637
public String toString() {
3738
return stringRepresentation;
3839
}
40+
41+
/**
42+
* Returns the {@link Protocol} given its string representation.
43+
*
44+
* @param protocolString the case insensitive string (e.g. "tcp", "udp")
45+
* @return the {@link Protocol} with the corresponding name, or {@code Protocol#TCP} by default
46+
* if invalid
47+
*/
48+
public static Protocol getFromString(@Nullable String protocolString) {
49+
if (protocolString == null) {
50+
return TCP;
51+
}
52+
return UDP.toString().equalsIgnoreCase(protocolString) ? UDP : TCP;
53+
}
3954
}
4055

4156
private final int port;

‎jib-core/src/main/java/com/google/cloud/tools/jib/frontend/ExposedPortsParser.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@ public static ImmutableList<Port> parse(List<String> ports) throws NumberFormatE
6666
if (!Strings.isNullOrEmpty(matcher.group(2))) {
6767
max = Integer.parseInt(matcher.group(2));
6868
}
69-
Protocol protocol =
70-
Protocol.UDP.toString().equals(matcher.group(3)) ? Protocol.UDP : Protocol.TCP;
69+
Protocol protocol = Protocol.getFromString(matcher.group(3));
7170

7271
// Error if configured as 'max-min' instead of 'min-max'
7372
if (min > max) {
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Copyright 2018 Google LLC. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package com.google.cloud.tools.jib.image.json;
18+
19+
/** Exception thrown when trying to parse a bad image configuration format. */
20+
public class BadContainerConfigurationFormatException extends Exception {
21+
22+
// TODO: Potentially provide Path or source object to problem configuration file
23+
BadContainerConfigurationFormatException(String message) {
24+
super(message);
25+
}
26+
}

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

Lines changed: 5 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,12 @@
1717
package com.google.cloud.tools.jib.image.json;
1818

1919
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
20-
import com.google.cloud.tools.jib.configuration.Port;
21-
import com.google.cloud.tools.jib.configuration.Port.Protocol;
2220
import com.google.cloud.tools.jib.image.DescriptorDigest;
2321
import com.google.cloud.tools.jib.json.JsonTemplate;
2422
import com.google.common.annotations.VisibleForTesting;
25-
import com.google.common.collect.ImmutableList;
26-
import com.google.common.collect.ImmutableSortedMap;
2723
import java.util.ArrayList;
28-
import java.util.Collections;
2924
import java.util.List;
3025
import java.util.Map;
31-
import java.util.SortedMap;
32-
import java.util.regex.Matcher;
33-
import java.util.regex.Pattern;
3426
import javax.annotation.Nullable;
3527

3628
/**
@@ -65,14 +57,6 @@
6557
@JsonIgnoreProperties(ignoreUnknown = true)
6658
public class ContainerConfigurationTemplate implements JsonTemplate {
6759

68-
/**
69-
* Pattern used for parsing information out of exposed port configurations. Only accepts single
70-
* ports with protocol.
71-
*
72-
* <p>Example matches: 100, 1000/tcp, 2000/udp
73-
*/
74-
private static final Pattern portPattern = Pattern.compile("(\\d+)(?:/(tcp|udp))?");
75-
7660
/**
7761
* A combined date and time at which the image was created. Constant to maintain reproducibility
7862
* and avoid Docker's weird "292 years old" bug.
@@ -108,7 +92,7 @@ private static class ConfigurationObjectTemplate implements JsonTemplate {
10892
@Nullable private List<String> Cmd;
10993

11094
/** Network ports the container exposes. */
111-
@Nullable private SortedMap<String, Map<?, ?>> ExposedPorts;
95+
@Nullable private Map<String, Map<?, ?>> ExposedPorts;
11296
}
11397

11498
/**
@@ -139,14 +123,8 @@ public void setContainerCmd(List<String> cmd) {
139123
config.Cmd = cmd;
140124
}
141125

142-
public void setContainerExposedPorts(List<Port> exposedPorts) {
143-
// TODO: Do this conversion somewhere else
144-
ImmutableSortedMap.Builder<String, Map<?, ?>> result =
145-
new ImmutableSortedMap.Builder<>(String::compareTo);
146-
for (Port port : exposedPorts) {
147-
result.put(port.getPort() + "/" + port.getProtocol(), Collections.emptyMap());
148-
}
149-
config.ExposedPorts = result.build();
126+
public void setContainerExposedPorts(Map<String, Map<?, ?>> exposedPorts) {
127+
config.ExposedPorts = exposedPorts;
150128
}
151129

152130
public void addLayerDiffId(DescriptorDigest diffId) {
@@ -173,24 +151,8 @@ List<String> getContainerCmd() {
173151
}
174152

175153
@Nullable
176-
ImmutableList<Port> getContainerExposedPorts() {
177-
// TODO: Do this conversion somewhere else
178-
if (config.ExposedPorts == null) {
179-
return null;
180-
}
181-
ImmutableList.Builder<Port> ports = new ImmutableList.Builder<>();
182-
for (Map.Entry<String, Map<?, ?>> entry : config.ExposedPorts.entrySet()) {
183-
String port = entry.getKey();
184-
Matcher matcher = portPattern.matcher(port);
185-
if (!matcher.matches()) {
186-
throw new NumberFormatException("Invalid port configuration: '" + port + "'.");
187-
}
188-
189-
int portNumber = Integer.parseInt(matcher.group(1));
190-
String protocol = matcher.group(2);
191-
ports.add(new Port(portNumber, "udp".equals(protocol) ? Protocol.UDP : Protocol.TCP));
192-
}
193-
return ports.build();
154+
Map<String, Map<?, ?>> getContainerExposedPorts() {
155+
return config.ExposedPorts;
194156
}
195157

196158
@VisibleForTesting

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,16 @@
1919
import com.google.cloud.tools.jib.blob.Blob;
2020
import com.google.cloud.tools.jib.blob.BlobDescriptor;
2121
import com.google.cloud.tools.jib.cache.CachedLayer;
22+
import com.google.cloud.tools.jib.configuration.Port;
2223
import com.google.cloud.tools.jib.image.DescriptorDigest;
2324
import com.google.cloud.tools.jib.image.Image;
2425
import com.google.cloud.tools.jib.json.JsonTemplateMapper;
26+
import com.google.common.annotations.VisibleForTesting;
27+
import com.google.common.collect.ImmutableSortedMap;
2528
import java.lang.reflect.InvocationTargetException;
29+
import java.util.Collections;
30+
import java.util.List;
31+
import java.util.Map;
2632

2733
/**
2834
* Translates an {@link Image} into a manifest or container configuration JSON BLOB.
@@ -38,6 +44,24 @@
3844
*/
3945
public class ImageToJsonTranslator {
4046

47+
/**
48+
* Converts a list of {@link Port}s to the corresponding container config format for exposed ports
49+
* (e.g. {@code Port(1000, Protocol.TCP)} -> {@code {"1000/tcp":{}}}).
50+
*
51+
* @param exposedPorts the list of {@link Port}s to translate
52+
* @return a sorted map with the string representation of the ports as keys and empty maps as
53+
* values
54+
*/
55+
@VisibleForTesting
56+
static Map<String, Map<?, ?>> portListToMap(List<Port> exposedPorts) {
57+
ImmutableSortedMap.Builder<String, Map<?, ?>> result =
58+
new ImmutableSortedMap.Builder<>(String::compareTo);
59+
for (Port port : exposedPorts) {
60+
result.put(port.getPort() + "/" + port.getProtocol(), Collections.emptyMap());
61+
}
62+
return result.build();
63+
}
64+
4165
private final Image<CachedLayer> image;
4266

4367
/**
@@ -73,7 +97,7 @@ public Blob getContainerConfigurationBlob() {
7397
template.setContainerCmd(image.getJavaArguments());
7498

7599
// Sets the exposed ports.
76-
template.setContainerExposedPorts(image.getExposedPorts());
100+
template.setContainerExposedPorts(portListToMap(image.getExposedPorts()));
77101

78102
// Serializes into JSON.
79103
return JsonTemplateMapper.toBlob(template);

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

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
package com.google.cloud.tools.jib.image.json;
1818

1919
import com.google.cloud.tools.jib.blob.BlobDescriptor;
20+
import com.google.cloud.tools.jib.configuration.Port;
21+
import com.google.cloud.tools.jib.configuration.Port.Protocol;
2022
import com.google.cloud.tools.jib.image.DescriptorDigest;
2123
import com.google.cloud.tools.jib.image.DigestOnlyLayer;
2224
import com.google.cloud.tools.jib.image.Image;
@@ -25,12 +27,26 @@
2527
import com.google.cloud.tools.jib.image.LayerPropertyNotFoundException;
2628
import com.google.cloud.tools.jib.image.ReferenceLayer;
2729
import com.google.cloud.tools.jib.image.ReferenceNoDiffIdLayer;
30+
import com.google.common.annotations.VisibleForTesting;
31+
import com.google.common.collect.ImmutableList;
2832
import java.util.ArrayList;
2933
import java.util.List;
34+
import java.util.Map;
35+
import java.util.regex.Matcher;
36+
import java.util.regex.Pattern;
37+
import javax.annotation.Nullable;
3038

3139
/** Translates {@link V21ManifestTemplate} and {@link V22ManifestTemplate} into {@link Image}. */
3240
public class JsonToImageTranslator {
3341

42+
/**
43+
* Pattern used for parsing information out of exposed port configurations. Only accepts single
44+
* ports with protocol.
45+
*
46+
* <p>Example matches: 100, 1000/tcp, 2000/udp
47+
*/
48+
private static final Pattern portPattern = Pattern.compile("(\\d+)(?:/(tcp|udp))?");
49+
3450
/**
3551
* Translates {@link V21ManifestTemplate} to {@link Image}.
3652
*
@@ -60,11 +76,14 @@ public static Image<Layer> toImage(V21ManifestTemplate manifestTemplate)
6076
* @throws LayerCountMismatchException if the manifest and configuration contain conflicting layer
6177
* information.
6278
* @throws LayerPropertyNotFoundException if adding image layers fails.
79+
* @throws BadContainerConfigurationFormatException if the container configuration is in a bad
80+
* format
6381
*/
6482
public static Image<Layer> toImage(
6583
BuildableManifestTemplate manifestTemplate,
6684
ContainerConfigurationTemplate containerConfigurationTemplate)
67-
throws LayerCountMismatchException, LayerPropertyNotFoundException {
85+
throws LayerCountMismatchException, LayerPropertyNotFoundException,
86+
BadContainerConfigurationFormatException {
6887
List<ReferenceNoDiffIdLayer> layers = new ArrayList<>();
6988
for (BuildableManifestTemplate.ContentDescriptorTemplate layerObjectTemplate :
7089
manifestTemplate.getLayers()) {
@@ -103,7 +122,8 @@ public static Image<Layer> toImage(
103122
}
104123

105124
if (containerConfigurationTemplate.getContainerExposedPorts() != null) {
106-
imageBuilder.setExposedPorts(containerConfigurationTemplate.getContainerExposedPorts());
125+
imageBuilder.setExposedPorts(
126+
portMapToList(containerConfigurationTemplate.getContainerExposedPorts()));
107127
}
108128

109129
if (containerConfigurationTemplate.getContainerEnvironment() != null) {
@@ -115,5 +135,34 @@ public static Image<Layer> toImage(
115135
return imageBuilder.build();
116136
}
117137

138+
/**
139+
* Converts a map of exposed ports as strings to a list of {@link Port}s (e.g. {@code
140+
* {"1000/tcp":{}}} -> {@code Port(1000, Protocol.TCP)}).
141+
*
142+
* @param portMap the map to convert
143+
* @return a list of {@link Port}s
144+
*/
145+
@VisibleForTesting
146+
static ImmutableList<Port> portMapToList(@Nullable Map<String, Map<?, ?>> portMap)
147+
throws BadContainerConfigurationFormatException {
148+
if (portMap == null) {
149+
return ImmutableList.of();
150+
}
151+
ImmutableList.Builder<Port> ports = new ImmutableList.Builder<>();
152+
for (Map.Entry<String, Map<?, ?>> entry : portMap.entrySet()) {
153+
String port = entry.getKey();
154+
Matcher matcher = portPattern.matcher(port);
155+
if (!matcher.matches()) {
156+
throw new BadContainerConfigurationFormatException(
157+
"Invalid port configuration: '" + port + "'.");
158+
}
159+
160+
int portNumber = Integer.parseInt(matcher.group(1));
161+
String protocol = matcher.group(2);
162+
ports.add(new Port(portNumber, Protocol.getFromString(protocol)));
163+
}
164+
return ports.build();
165+
}
166+
118167
private JsonToImageTranslator() {}
119168
}

‎jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplateTest.java‎

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616

1717
package com.google.cloud.tools.jib.image.json;
1818

19-
import com.google.cloud.tools.jib.configuration.Port;
20-
import com.google.cloud.tools.jib.configuration.Port.Protocol;
2119
import com.google.cloud.tools.jib.image.DescriptorDigest;
2220
import com.google.cloud.tools.jib.json.JsonTemplateMapper;
21+
import com.google.common.collect.ImmutableMap;
22+
import com.google.common.collect.ImmutableSortedMap;
2323
import com.google.common.io.Resources;
2424
import java.io.ByteArrayOutputStream;
2525
import java.io.IOException;
@@ -29,26 +29,13 @@
2929
import java.nio.file.Path;
3030
import java.nio.file.Paths;
3131
import java.security.DigestException;
32-
import java.util.ArrayList;
3332
import java.util.Arrays;
34-
import java.util.List;
3533
import org.junit.Assert;
36-
import org.junit.Before;
3734
import org.junit.Test;
3835

3936
/** Tests for {@link ContainerConfigurationTemplate}. */
4037
public class ContainerConfigurationTemplateTest {
4138

42-
private List<Port> exposedPorts;
43-
44-
@Before
45-
public void setup() {
46-
exposedPorts = new ArrayList<>();
47-
exposedPorts.add(new Port(1000, Protocol.TCP));
48-
exposedPorts.add(new Port(2000, Protocol.TCP));
49-
exposedPorts.add(new Port(3000, Protocol.UDP));
50-
}
51-
5239
@Test
5340
public void testToJson() throws IOException, URISyntaxException, DigestException {
5441
// Loads the expected JSON string.
@@ -61,7 +48,14 @@ public void testToJson() throws IOException, URISyntaxException, DigestException
6148
containerConfigJson.setContainerEnvironment(Arrays.asList("VAR1=VAL1", "VAR2=VAL2"));
6249
containerConfigJson.setContainerEntrypoint(Arrays.asList("some", "entrypoint", "command"));
6350
containerConfigJson.setContainerCmd(Arrays.asList("arg1", "arg2"));
64-
containerConfigJson.setContainerExposedPorts(exposedPorts);
51+
containerConfigJson.setContainerExposedPorts(
52+
ImmutableSortedMap.of(
53+
"1000/tcp",
54+
ImmutableMap.of(),
55+
"2000/tcp",
56+
ImmutableMap.of(),
57+
"3000/udp",
58+
ImmutableMap.of()));
6559

6660
containerConfigJson.addLayerDiffId(
6761
DescriptorDigest.fromDigest(

0 commit comments

Comments
 (0)