Search in sources :

Example 1 with Port

use of com.google.cloud.tools.jib.api.buildplan.Port in project jib by GoogleContainerTools.

the class BuildContextTest method testBuilder.

@Test
public void testBuilder() throws Exception {
    String expectedBaseImageServerUrl = "someserver";
    String expectedBaseImageName = "baseimage";
    String expectedBaseImageTag = "baseimagetag";
    String expectedTargetServerUrl = "someotherserver";
    String expectedTargetImageName = "targetimage";
    String expectedTargetTag = "targettag";
    Set<String> additionalTargetImageTags = ImmutableSet.of("tag1", "tag2", "tag3");
    Set<String> expectedTargetImageTags = ImmutableSet.of("targettag", "tag1", "tag2", "tag3");
    List<CredentialRetriever> credentialRetrievers = Collections.singletonList(() -> Optional.of(Credential.from("username", "password")));
    Instant expectedCreationTime = Instant.ofEpochSecond(10000);
    List<String> expectedEntrypoint = Arrays.asList("some", "entrypoint");
    List<String> expectedProgramArguments = Arrays.asList("arg1", "arg2");
    Map<String, String> expectedEnvironment = ImmutableMap.of("key", "value");
    Set<Port> expectedExposedPorts = ImmutableSet.of(Port.tcp(1000), Port.tcp(2000));
    Map<String, String> expectedLabels = ImmutableMap.of("key1", "value1", "key2", "value2");
    Class<? extends BuildableManifestTemplate> expectedTargetFormat = OciManifestTemplate.class;
    Path expectedApplicationLayersCacheDirectory = Paths.get("application/layers");
    Path expectedBaseImageLayersCacheDirectory = Paths.get("base/image/layers");
    List<FileEntriesLayer> expectedLayerConfigurations = Collections.singletonList(FileEntriesLayer.builder().addEntry(Paths.get("sourceFile"), AbsoluteUnixPath.get("/path/in/container")).build());
    String expectedCreatedBy = "createdBy";
    ListMultimap<String, String> expectedRegistryMirrors = ImmutableListMultimap.of("some.registry", "mirror1", "some.registry", "mirror2");
    ImageConfiguration baseImageConfiguration = ImageConfiguration.builder(ImageReference.of(expectedBaseImageServerUrl, expectedBaseImageName, expectedBaseImageTag)).build();
    ImageConfiguration targetImageConfiguration = ImageConfiguration.builder(ImageReference.of(expectedTargetServerUrl, expectedTargetImageName, expectedTargetTag)).setCredentialRetrievers(credentialRetrievers).build();
    ContainerConfiguration containerConfiguration = ContainerConfiguration.builder().setCreationTime(expectedCreationTime).setEntrypoint(expectedEntrypoint).setProgramArguments(expectedProgramArguments).setEnvironment(expectedEnvironment).setExposedPorts(expectedExposedPorts).setLabels(expectedLabels).build();
    BuildContext.Builder buildContextBuilder = BuildContext.builder().setBaseImageConfiguration(baseImageConfiguration).setTargetImageConfiguration(targetImageConfiguration).setAdditionalTargetImageTags(additionalTargetImageTags).setContainerConfiguration(containerConfiguration).setApplicationLayersCacheDirectory(expectedApplicationLayersCacheDirectory).setBaseImageLayersCacheDirectory(expectedBaseImageLayersCacheDirectory).setTargetFormat(ImageFormat.OCI).setEnablePlatformTags(true).setAllowInsecureRegistries(true).setLayerConfigurations(expectedLayerConfigurations).setToolName(expectedCreatedBy).setRegistryMirrors(expectedRegistryMirrors);
    BuildContext buildContext = buildContextBuilder.build();
    Assert.assertEquals(expectedCreationTime, buildContext.getContainerConfiguration().getCreationTime());
    Assert.assertEquals(expectedBaseImageServerUrl, buildContext.getBaseImageConfiguration().getImageRegistry());
    Assert.assertEquals(expectedBaseImageName, buildContext.getBaseImageConfiguration().getImageRepository());
    Assert.assertEquals(expectedBaseImageTag, buildContext.getBaseImageConfiguration().getImageQualifier());
    Assert.assertEquals(expectedTargetServerUrl, buildContext.getTargetImageConfiguration().getImageRegistry());
    Assert.assertEquals(expectedTargetImageName, buildContext.getTargetImageConfiguration().getImageRepository());
    Assert.assertEquals(expectedTargetTag, buildContext.getTargetImageConfiguration().getImageQualifier());
    Assert.assertEquals(expectedTargetImageTags, buildContext.getAllTargetImageTags());
    Assert.assertEquals(Credential.from("username", "password"), buildContext.getTargetImageConfiguration().getCredentialRetrievers().get(0).retrieve().orElseThrow(AssertionError::new));
    Assert.assertEquals(expectedProgramArguments, buildContext.getContainerConfiguration().getProgramArguments());
    Assert.assertEquals(expectedEnvironment, buildContext.getContainerConfiguration().getEnvironmentMap());
    Assert.assertEquals(expectedExposedPorts, buildContext.getContainerConfiguration().getExposedPorts());
    Assert.assertEquals(expectedLabels, buildContext.getContainerConfiguration().getLabels());
    Assert.assertEquals(expectedTargetFormat, buildContext.getTargetFormat());
    Assert.assertEquals(expectedApplicationLayersCacheDirectory, buildContextBuilder.getApplicationLayersCacheDirectory());
    Assert.assertEquals(expectedBaseImageLayersCacheDirectory, buildContextBuilder.getBaseImageLayersCacheDirectory());
    Assert.assertEquals(expectedLayerConfigurations, buildContext.getLayerConfigurations());
    Assert.assertEquals(expectedEntrypoint, buildContext.getContainerConfiguration().getEntrypoint());
    Assert.assertEquals(expectedCreatedBy, buildContext.getToolName());
    Assert.assertEquals(expectedRegistryMirrors, buildContext.getRegistryMirrors());
    Assert.assertNotNull(buildContext.getExecutorService());
    Assert.assertTrue(buildContext.getEnablePlatformTags());
}
Also used : CredentialRetriever(com.google.cloud.tools.jib.api.CredentialRetriever) Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Instant(java.time.Instant) Port(com.google.cloud.tools.jib.api.buildplan.Port) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) OciManifestTemplate(com.google.cloud.tools.jib.image.json.OciManifestTemplate) Test(org.junit.Test)

Example 2 with Port

use of com.google.cloud.tools.jib.api.buildplan.Port in project component-runtime by Talend.

the class ImageM2Mojo method doExecute.

@Override
public void doExecute() throws MojoExecutionException {
    try (final JibHelper jibHelper = new JibHelper(getLog(), project.getBuild().getDirectory(), layersCacheDirectory, repository, dockerEnvironment, dockerExecutable, laggyPushWorkaround)) {
        jibHelper.prepare(project.getArtifactId(), project.getVersion(), project.getProperties(), fromImage, toImage, creationTime, workingDirectory, this::createWorkingDirectory, environment, labels);
        addLayers(jibHelper.getBuilder());
        if (ports != null) {
            ports.stream().map(Port::tcp).forEach(jibHelper.getBuilder()::addExposedPort);
        }
        getLog().info("Creating the image (can be long)");
        jibHelper.build("Talend Image Maven Plugin", () -> ofNullable(session.getSettings().getServer(repository)).map(it -> settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(it))).map(SettingsDecryptionResult::getServer).orElse(null));
        if (versionProperty != null) {
            jibHelper.setProperties(project, versionProperty);
        }
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (m2Root.exists()) {
            try {
                Files.walkFileTree(m2Root.toPath(), new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                        file.toFile().delete();
                        return super.visitFile(file, attrs);
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
                        dir.toFile().delete();
                        return super.postVisitDirectory(dir, exc);
                    }
                });
            } catch (final IOException e) {
                getLog().warn(e.getMessage(), e);
            }
        }
    }
}
Also used : TEST(org.apache.maven.plugins.annotations.ResolutionScope.TEST) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) Date(java.util.Date) DefaultSettingsDecryptionRequest(org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest) MAX_VALUE(java.lang.Long.MAX_VALUE) Component(org.apache.maven.plugins.annotations.Component) SettingsDecryptionResult(org.apache.maven.settings.crypto.SettingsDecryptionResult) Parameter(org.apache.maven.plugins.annotations.Parameter) Port(com.google.cloud.tools.jib.api.buildplan.Port) Mojo(org.apache.maven.plugins.annotations.Mojo) LayerConfiguration(com.google.cloud.tools.jib.api.LayerConfiguration) TALEND_INTERNAL(org.talend.sdk.component.maven.api.Audience.Type.TALEND_INTERNAL) Map(java.util.Map) Comparator.comparing(java.util.Comparator.comparing) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) JibHelper(org.talend.sdk.component.maven.docker.JibHelper) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) MavenSession(org.apache.maven.execution.MavenSession) Audience(org.talend.sdk.component.maven.api.Audience) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) SettingsDecrypter(org.apache.maven.settings.crypto.SettingsDecrypter) Set(java.util.Set) Artifact(org.eclipse.aether.artifact.Artifact) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Instant(java.time.Instant) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) File(java.io.File) Objects(java.util.Objects) PACKAGE(org.apache.maven.plugins.annotations.LifecyclePhase.PACKAGE) FileVisitResult(java.nio.file.FileVisitResult) AtomicLong(java.util.concurrent.atomic.AtomicLong) Collectors.toList(java.util.stream.Collectors.toList) AbstractMap(java.util.AbstractMap) List(java.util.List) Stream(java.util.stream.Stream) Data(lombok.Data) Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) JibHelper(org.talend.sdk.component.maven.docker.JibHelper) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DefaultSettingsDecryptionRequest(org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest) FileVisitResult(java.nio.file.FileVisitResult) SettingsDecryptionResult(org.apache.maven.settings.crypto.SettingsDecryptionResult) IOException(java.io.IOException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 3 with Port

use of com.google.cloud.tools.jib.api.buildplan.Port in project jib by google.

the class BuildContextTest method testBuilder.

@Test
public void testBuilder() throws Exception {
    String expectedBaseImageServerUrl = "someserver";
    String expectedBaseImageName = "baseimage";
    String expectedBaseImageTag = "baseimagetag";
    String expectedTargetServerUrl = "someotherserver";
    String expectedTargetImageName = "targetimage";
    String expectedTargetTag = "targettag";
    Set<String> additionalTargetImageTags = ImmutableSet.of("tag1", "tag2", "tag3");
    Set<String> expectedTargetImageTags = ImmutableSet.of("targettag", "tag1", "tag2", "tag3");
    List<CredentialRetriever> credentialRetrievers = Collections.singletonList(() -> Optional.of(Credential.from("username", "password")));
    Instant expectedCreationTime = Instant.ofEpochSecond(10000);
    List<String> expectedEntrypoint = Arrays.asList("some", "entrypoint");
    List<String> expectedProgramArguments = Arrays.asList("arg1", "arg2");
    Map<String, String> expectedEnvironment = ImmutableMap.of("key", "value");
    Set<Port> expectedExposedPorts = ImmutableSet.of(Port.tcp(1000), Port.tcp(2000));
    Map<String, String> expectedLabels = ImmutableMap.of("key1", "value1", "key2", "value2");
    Class<? extends BuildableManifestTemplate> expectedTargetFormat = OciManifestTemplate.class;
    Path expectedApplicationLayersCacheDirectory = Paths.get("application/layers");
    Path expectedBaseImageLayersCacheDirectory = Paths.get("base/image/layers");
    List<FileEntriesLayer> expectedLayerConfigurations = Collections.singletonList(FileEntriesLayer.builder().addEntry(Paths.get("sourceFile"), AbsoluteUnixPath.get("/path/in/container")).build());
    String expectedCreatedBy = "createdBy";
    ListMultimap<String, String> expectedRegistryMirrors = ImmutableListMultimap.of("some.registry", "mirror1", "some.registry", "mirror2");
    ImageConfiguration baseImageConfiguration = ImageConfiguration.builder(ImageReference.of(expectedBaseImageServerUrl, expectedBaseImageName, expectedBaseImageTag)).build();
    ImageConfiguration targetImageConfiguration = ImageConfiguration.builder(ImageReference.of(expectedTargetServerUrl, expectedTargetImageName, expectedTargetTag)).setCredentialRetrievers(credentialRetrievers).build();
    ContainerConfiguration containerConfiguration = ContainerConfiguration.builder().setCreationTime(expectedCreationTime).setEntrypoint(expectedEntrypoint).setProgramArguments(expectedProgramArguments).setEnvironment(expectedEnvironment).setExposedPorts(expectedExposedPorts).setLabels(expectedLabels).build();
    BuildContext.Builder buildContextBuilder = BuildContext.builder().setBaseImageConfiguration(baseImageConfiguration).setTargetImageConfiguration(targetImageConfiguration).setAdditionalTargetImageTags(additionalTargetImageTags).setContainerConfiguration(containerConfiguration).setApplicationLayersCacheDirectory(expectedApplicationLayersCacheDirectory).setBaseImageLayersCacheDirectory(expectedBaseImageLayersCacheDirectory).setTargetFormat(ImageFormat.OCI).setEnablePlatformTags(true).setAllowInsecureRegistries(true).setLayerConfigurations(expectedLayerConfigurations).setToolName(expectedCreatedBy).setRegistryMirrors(expectedRegistryMirrors);
    BuildContext buildContext = buildContextBuilder.build();
    Assert.assertEquals(expectedCreationTime, buildContext.getContainerConfiguration().getCreationTime());
    Assert.assertEquals(expectedBaseImageServerUrl, buildContext.getBaseImageConfiguration().getImageRegistry());
    Assert.assertEquals(expectedBaseImageName, buildContext.getBaseImageConfiguration().getImageRepository());
    Assert.assertEquals(expectedBaseImageTag, buildContext.getBaseImageConfiguration().getImageQualifier());
    Assert.assertEquals(expectedTargetServerUrl, buildContext.getTargetImageConfiguration().getImageRegistry());
    Assert.assertEquals(expectedTargetImageName, buildContext.getTargetImageConfiguration().getImageRepository());
    Assert.assertEquals(expectedTargetTag, buildContext.getTargetImageConfiguration().getImageQualifier());
    Assert.assertEquals(expectedTargetImageTags, buildContext.getAllTargetImageTags());
    Assert.assertEquals(Credential.from("username", "password"), buildContext.getTargetImageConfiguration().getCredentialRetrievers().get(0).retrieve().orElseThrow(AssertionError::new));
    Assert.assertEquals(expectedProgramArguments, buildContext.getContainerConfiguration().getProgramArguments());
    Assert.assertEquals(expectedEnvironment, buildContext.getContainerConfiguration().getEnvironmentMap());
    Assert.assertEquals(expectedExposedPorts, buildContext.getContainerConfiguration().getExposedPorts());
    Assert.assertEquals(expectedLabels, buildContext.getContainerConfiguration().getLabels());
    Assert.assertEquals(expectedTargetFormat, buildContext.getTargetFormat());
    Assert.assertEquals(expectedApplicationLayersCacheDirectory, buildContextBuilder.getApplicationLayersCacheDirectory());
    Assert.assertEquals(expectedBaseImageLayersCacheDirectory, buildContextBuilder.getBaseImageLayersCacheDirectory());
    Assert.assertEquals(expectedLayerConfigurations, buildContext.getLayerConfigurations());
    Assert.assertEquals(expectedEntrypoint, buildContext.getContainerConfiguration().getEntrypoint());
    Assert.assertEquals(expectedCreatedBy, buildContext.getToolName());
    Assert.assertEquals(expectedRegistryMirrors, buildContext.getRegistryMirrors());
    Assert.assertNotNull(buildContext.getExecutorService());
    Assert.assertTrue(buildContext.getEnablePlatformTags());
}
Also used : CredentialRetriever(com.google.cloud.tools.jib.api.CredentialRetriever) Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Instant(java.time.Instant) Port(com.google.cloud.tools.jib.api.buildplan.Port) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) OciManifestTemplate(com.google.cloud.tools.jib.image.json.OciManifestTemplate) Test(org.junit.Test)

Example 4 with Port

use of com.google.cloud.tools.jib.api.buildplan.Port in project jib by google.

the class Ports method parse.

/**
 * Converts/validates a list of strings representing port ranges to an expanded list of {@link
 * Port}s.
 *
 * <p>For example: ["1000", "2000-2002"] will expand to a list of {@link Port}s with the port
 * numbers [1000, 2000, 2001, 2002]
 *
 * @param ports the list of port numbers/ranges, with an optional protocol separated by a '/'
 *     (defaults to TCP if missing).
 * @return the ports as a list of {@link Port}
 * @throws NumberFormatException if any of the ports are in an invalid format or out of range
 */
public static Set<Port> parse(List<String> ports) throws NumberFormatException {
    Set<Port> result = new HashSet<>();
    for (String port : ports) {
        Matcher matcher = portPattern.matcher(port);
        if (!matcher.matches()) {
            throw new NumberFormatException("Invalid port configuration: '" + port + "'. Make sure the port is a single number or a range of two numbers separated " + "with a '-', with or without protocol specified (e.g. '<portNum>/tcp' or " + "'<portNum>/udp').");
        }
        // Parse protocol
        int min = Integer.parseInt(matcher.group(1));
        int max = min;
        if (!Strings.isNullOrEmpty(matcher.group(2))) {
            max = Integer.parseInt(matcher.group(2));
        }
        String protocol = matcher.group(3);
        // Error if configured as 'max-min' instead of 'min-max'
        if (min > max) {
            throw new NumberFormatException("Invalid port range '" + port + "'; smaller number must come first.");
        }
        // Warn for possibly invalid port numbers
        if (min < 1 || max > 65535) {
            throw new NumberFormatException("Port number '" + port + "' is out of usual range (1-65535).");
        }
        for (int portNumber = min; portNumber <= max; portNumber++) {
            result.add(Port.parseProtocol(portNumber, protocol));
        }
    }
    return result;
}
Also used : Matcher(java.util.regex.Matcher) Port(com.google.cloud.tools.jib.api.buildplan.Port) HashSet(java.util.HashSet)

Example 5 with Port

use of com.google.cloud.tools.jib.api.buildplan.Port in project jib by google.

the class JsonToImageTranslator method portMapToSet.

/**
 * Converts a map of exposed ports as strings to a set of {@link Port}s (e.g. {@code
 * {"1000/tcp":{}}} -> {@code Port(1000, Protocol.TCP)}).
 *
 * @param portMap the map to convert
 * @return a set of {@link Port}s
 */
@VisibleForTesting
static ImmutableSet<Port> portMapToSet(@Nullable Map<String, Map<String, String>> portMap) throws BadContainerConfigurationFormatException {
    if (portMap == null) {
        return ImmutableSet.of();
    }
    ImmutableSet.Builder<Port> ports = new ImmutableSet.Builder<>();
    for (Map.Entry<String, Map<String, String>> entry : portMap.entrySet()) {
        String port = entry.getKey();
        Matcher matcher = PORT_PATTERN.matcher(port);
        if (!matcher.matches()) {
            throw new BadContainerConfigurationFormatException("Invalid port configuration: '" + port + "'.");
        }
        int portNumber = Integer.parseInt(matcher.group("portNum"));
        String protocol = matcher.group("protocol");
        ports.add(Port.parseProtocol(portNumber, protocol));
    }
    return ports.build();
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Matcher(java.util.regex.Matcher) Port(com.google.cloud.tools.jib.api.buildplan.Port) Map(java.util.Map) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

Port (com.google.cloud.tools.jib.api.buildplan.Port)7 Matcher (java.util.regex.Matcher)4 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)3 Path (java.nio.file.Path)3 Instant (java.time.Instant)3 Map (java.util.Map)3 CredentialRetriever (com.google.cloud.tools.jib.api.CredentialRetriever)2 FileEntriesLayer (com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer)2 OciManifestTemplate (com.google.cloud.tools.jib.image.json.OciManifestTemplate)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)1 LayerConfiguration (com.google.cloud.tools.jib.api.LayerConfiguration)1 File (java.io.File)1 IOException (java.io.IOException)1 MAX_VALUE (java.lang.Long.MAX_VALUE)1 FileVisitResult (java.nio.file.FileVisitResult)1 Files (java.nio.file.Files)1