Search in sources :

Example 81 with FileEntriesLayer

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

the class StandardExplodedProcessorTest method testCreateLayers_emptyJar.

@Test
public void testCreateLayers_emptyJar() throws IOException, URISyntaxException {
    Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI());
    Path destDir = temporaryFolder.newFolder().toPath();
    StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION);
    List<FileEntriesLayer> layers = standardExplodedModeProcessor.createLayers();
    assertThat(layers.size()).isEqualTo(1);
    FileEntriesLayer resourcesLayer = layers.get(0);
    assertThat(resourcesLayer.getEntries().size()).isEqualTo(1);
    assertThat(resourcesLayer.getEntries().get(0).getExtractionPath()).isEqualTo(AbsoluteUnixPath.get("/app/explodedJar/META-INF/MANIFEST.MF"));
}
Also used : AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Path(java.nio.file.Path) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) Test(org.junit.Test)

Example 82 with FileEntriesLayer

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

the class StandardWarExplodedProcessorTest method testCreateLayers_webInfClassesDoesNotExist_correctExtractionPaths.

@Test
public void testCreateLayers_webInfClassesDoesNotExist_correctExtractionPaths() throws IOException, URISyntaxException {
    // Prepare war file for test
    Path tempDirectory = temporaryFolder.getRoot().toPath();
    Path warContents = Paths.get(Resources.getResource("war/standard/noWebInfClasses").toURI());
    Path standardWar = zipUpDirectory(warContents, tempDirectory.resolve("noClassesWar.war"));
    Path explodedWarDestination = temporaryFolder.newFolder("exploded-war").toPath();
    StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(standardWar, explodedWarDestination, APP_ROOT);
    List<FileEntriesLayer> layers = processor.createLayers();
    assertThat(layers.size()).isEqualTo(3);
    FileEntriesLayer nonSnapshotLayer = layers.get(0);
    FileEntriesLayer snapshotLayer = layers.get(1);
    FileEntriesLayer resourcesLayer = layers.get(2);
    assertThat(nonSnapshotLayer.getEntries()).comparingElementsUsing(EXTRACTION_PATH_OF).containsExactly("/my/app/WEB-INF/lib/dependency-1.0.0.jar");
    assertThat(snapshotLayer.getEntries()).comparingElementsUsing(EXTRACTION_PATH_OF).containsExactly("/my/app/WEB-INF/lib/dependencyX-1.0.0-SNAPSHOT.jar");
    assertThat(resourcesLayer.getEntries()).comparingElementsUsing(EXTRACTION_PATH_OF).containsExactly("/my/app/META-INF/context.xml");
}
Also used : AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Path(java.nio.file.Path) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) Test(org.junit.Test)

Example 83 with FileEntriesLayer

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

the class WarFilesTest method testToJibContainerBuilder_explodedStandard_basicInfo.

@Test
public void testToJibContainerBuilder_explodedStandard_basicInfo() throws IOException, InvalidImageReferenceException {
    FileEntriesLayer layer = FileEntriesLayer.builder().setName("classes").addEntry(Paths.get("path/to/tempDirectory/WEB-INF/classes/class1.class"), AbsoluteUnixPath.get("/my/app/WEB-INF/classes/class1.class")).build();
    when(mockStandardWarExplodedProcessor.createLayers()).thenReturn(Arrays.asList(layer));
    when(mockCommonContainerConfigCliOptions.isJettyBaseimage()).thenReturn(true);
    JibContainerBuilder containerBuilder = WarFiles.toJibContainerBuilder(mockStandardWarExplodedProcessor, mockCommonCliOptions, mockCommonContainerConfigCliOptions, mockLogger);
    ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();
    assertThat(buildPlan.getBaseImage()).isEqualTo("jetty");
    assertThat(buildPlan.getEntrypoint()).containsExactly("java", "-jar", "/usr/local/jetty/start.jar").inOrder();
    assertThat(buildPlan.getLayers()).hasSize(1);
    assertThat(buildPlan.getLayers().get(0).getName()).isEqualTo("classes");
    assertThat(((FileEntriesLayer) buildPlan.getLayers().get(0)).getEntries()).containsExactlyElementsIn(FileEntriesLayer.builder().addEntry(Paths.get("path/to/tempDirectory/WEB-INF/classes/class1.class"), AbsoluteUnixPath.get("/my/app/WEB-INF/classes/class1.class")).build().getEntries());
}
Also used : FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) ContainerBuildPlan(com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan) Test(org.junit.Test)

Example 84 with FileEntriesLayer

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

the class JavaContainerBuilder method toContainerBuilder.

/**
 * Returns a new {@link JibContainerBuilder} using the parameters specified on the {@link
 * JavaContainerBuilder}.
 *
 * @return a new {@link JibContainerBuilder} using the parameters specified on the {@link
 *     JavaContainerBuilder}
 * @throws IOException if building the {@link JibContainerBuilder} fails.
 */
public JibContainerBuilder toContainerBuilder() throws IOException {
    if (mainClass == null && !jvmFlags.isEmpty()) {
        throw new IllegalStateException("Failed to construct entrypoint on JavaContainerBuilder; " + "jvmFlags were set, but mainClass is null. Specify the main class using " + "JavaContainerBuilder#setMainClass(String), or consider using MainClassFinder to " + "infer the main class.");
    }
    if (classpathOrder.isEmpty()) {
        throw new IllegalStateException("Failed to construct entrypoint because no files were added to the JavaContainerBuilder");
    }
    Map<LayerType, FileEntriesLayer.Builder> layerBuilders = new EnumMap<>(LayerType.class);
    // Add classes to layer configuration
    for (PathPredicatePair directory : addedClasses) {
        addDirectoryContentsToLayer(layerBuilders, LayerType.CLASSES, directory.path, directory.predicate, appRoot.resolve(classesDestination));
    }
    // Add resources to layer configuration
    for (PathPredicatePair directory : addedResources) {
        addDirectoryContentsToLayer(layerBuilders, LayerType.RESOURCES, directory.path, directory.predicate, appRoot.resolve(resourcesDestination));
    }
    // Detect duplicate filenames across all dependency layer types
    Map<String, Long> occurrences = Streams.concat(addedDependencies.stream(), addedSnapshotDependencies.stream(), addedProjectDependencies.stream()).map(path -> path.getFileName().toString()).collect(Collectors.groupingBy(filename -> filename, Collectors.counting()));
    List<String> duplicates = occurrences.entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
    ImmutableMap<LayerType, List<Path>> layerMap = ImmutableMap.of(LayerType.DEPENDENCIES, addedDependencies, LayerType.SNAPSHOT_DEPENDENCIES, addedSnapshotDependencies, LayerType.PROJECT_DEPENDENCIES, addedProjectDependencies);
    for (Map.Entry<LayerType, List<Path>> entry : layerMap.entrySet()) {
        for (Path file : Preconditions.checkNotNull(entry.getValue())) {
            // Handle duplicates by appending filesize to the end of the file. This renaming logic
            // must be in sync with the code that does the same in the other place. See
            // https://github.com/GoogleContainerTools/jib/issues/3331
            String jarName = file.getFileName().toString();
            if (duplicates.contains(jarName)) {
                jarName = jarName.replaceFirst("\\.jar$", "-" + Files.size(file)) + ".jar";
            }
            // Add dependencies to layer configuration
            addFileToLayer(layerBuilders, entry.getKey(), file, appRoot.resolve(dependenciesDestination).resolve(jarName));
        }
    }
    // Add others to layer configuration
    for (Path path : addedOthers) {
        if (Files.isDirectory(path)) {
            addDirectoryContentsToLayer(layerBuilders, LayerType.EXTRA_FILES, path, ignored -> true, appRoot.resolve(othersDestination));
        } else {
            addFileToLayer(layerBuilders, LayerType.EXTRA_FILES, path, appRoot.resolve(othersDestination).resolve(path.getFileName()));
        }
    }
    // Add layer configurations to container builder
    List<FileEntriesLayer> layers = new ArrayList<>();
    layerBuilders.forEach((type, builder) -> layers.add(builder.setName(type.getName()).build()));
    jibContainerBuilder.setFileEntriesLayers(layers);
    if (mainClass != null) {
        // Construct entrypoint. Ensure classpath elements are in the same order as the files were
        // added to the JavaContainerBuilder.
        List<String> classpathElements = new ArrayList<>();
        for (LayerType path : classpathOrder) {
            switch(path) {
                case CLASSES:
                    classpathElements.add(appRoot.resolve(classesDestination).toString());
                    break;
                case RESOURCES:
                    classpathElements.add(appRoot.resolve(resourcesDestination).toString());
                    break;
                case DEPENDENCIES:
                    classpathElements.add(appRoot.resolve(dependenciesDestination).resolve("*").toString());
                    break;
                case EXTRA_FILES:
                    classpathElements.add(appRoot.resolve(othersDestination).toString());
                    break;
                default:
                    throw new RuntimeException("Bug in jib-core; please report the bug at " + ProjectInfo.GITHUB_NEW_ISSUE_URL);
            }
        }
        String classpathString = String.join(":", classpathElements);
        List<String> entrypoint = new ArrayList<>(4 + jvmFlags.size());
        entrypoint.add("java");
        entrypoint.addAll(jvmFlags);
        entrypoint.add("-cp");
        entrypoint.add(classpathString);
        entrypoint.add(mainClass);
        jibContainerBuilder.setEntrypoint(entrypoint);
    }
    return jibContainerBuilder;
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) EnumMap(java.util.EnumMap) Predicate(java.util.function.Predicate) NotDirectoryException(java.nio.file.NotDirectoryException) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) IOException(java.io.IOException) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) ModificationTimeProvider(com.google.cloud.tools.jib.api.buildplan.ModificationTimeProvider) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) ProjectInfo(com.google.cloud.tools.jib.ProjectInfo) RelativeUnixPath(com.google.cloud.tools.jib.api.buildplan.RelativeUnixPath) Preconditions(com.google.common.base.Preconditions) Path(java.nio.file.Path) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) RelativeUnixPath(com.google.cloud.tools.jib.api.buildplan.RelativeUnixPath) Path(java.nio.file.Path) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) EnumMap(java.util.EnumMap) ImmutableMap(com.google.common.collect.ImmutableMap) EnumMap(java.util.EnumMap) Map(java.util.Map)

Example 85 with FileEntriesLayer

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

the class JavaContainerBuilderHelperTest method testExtraDirectoryLayerConfiguration.

@Test
public void testExtraDirectoryLayerConfiguration() throws URISyntaxException, IOException {
    Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI());
    FileEntriesLayer layerConfiguration = JavaContainerBuilderHelper.extraDirectoryLayerConfiguration(extraFilesDirectory, AbsoluteUnixPath.get("/"), Collections.emptyList(), Collections.emptyList(), Collections.emptyMap(), (ignored1, ignored2) -> Instant.EPOCH);
    assertThat(layerConfiguration.getEntries()).comparingElementsUsing(SOURCE_FILE_OF).containsExactly(extraFilesDirectory.resolve("a"), extraFilesDirectory.resolve("a/b"), extraFilesDirectory.resolve("a/b/bar"), extraFilesDirectory.resolve("c"), extraFilesDirectory.resolve("c/cat"), extraFilesDirectory.resolve("foo"));
}
Also used : Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) Test(org.junit.Test)

Aggregations

FileEntriesLayer (com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer)154 Test (org.junit.Test)111 Path (java.nio.file.Path)92 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)85 ContainerBuildPlan (com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan)55 List (java.util.List)29 IOException (java.io.IOException)26 ArrayList (java.util.ArrayList)26 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)24 FileEntry (com.google.cloud.tools.jib.api.buildplan.FileEntry)23 Map (java.util.Map)23 Files (java.nio.file.Files)21 Predicate (java.util.function.Predicate)20 Platform (com.google.cloud.tools.jib.api.buildplan.Platform)16 Collectors (java.util.stream.Collectors)16 FilePermissions (com.google.cloud.tools.jib.api.buildplan.FilePermissions)13 Paths (java.nio.file.Paths)13 Optional (java.util.Optional)13 JavaContainerBuilder (com.google.cloud.tools.jib.api.JavaContainerBuilder)12 JibPluginExtensionException (com.google.cloud.tools.jib.plugins.extension.JibPluginExtensionException)12