Search in sources :

Example 16 with BuildContext

use of com.google.cloud.tools.jib.configuration.BuildContext in project jib by google.

the class Containerizer method to.

/**
 * Gets a new {@link Containerizer} that containerizes to a tarball archive.
 *
 * @param tarImage the {@link TarImage} that defines target output file
 * @return a new {@link Containerizer}
 */
public static Containerizer to(TarImage tarImage) {
    Optional<ImageReference> imageReference = tarImage.getImageReference();
    if (!imageReference.isPresent()) {
        throw new IllegalArgumentException("Image name must be set when building a TarImage; use TarImage#named(...) to set the name" + " of the target image");
    }
    ImageConfiguration imageConfiguration = ImageConfiguration.builder(imageReference.get()).build();
    Function<BuildContext, StepsRunner> stepsRunnerFactory = buildContext -> StepsRunner.begin(buildContext).tarBuildSteps(tarImage.getPath());
    return new Containerizer(DESCRIPTION_FOR_TARBALL, imageConfiguration, stepsRunnerFactory, false);
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ImageConfiguration(com.google.cloud.tools.jib.configuration.ImageConfiguration) ListMultimap(com.google.common.collect.ListMultimap) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) Function(java.util.function.Function) HashSet(java.util.HashSet) DockerClient(com.google.cloud.tools.jib.docker.DockerClient) XdgDirectories(com.google.cloud.tools.jib.filesystem.XdgDirectories) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) ImmutableSet(com.google.common.collect.ImmutableSet) Files(java.nio.file.Files) Set(java.util.Set) IOException(java.io.IOException) StepsRunner(com.google.cloud.tools.jib.builder.steps.StepsRunner) BuildResult(com.google.cloud.tools.jib.builder.steps.BuildResult) Executors(java.util.concurrent.Executors) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) List(java.util.List) Paths(java.nio.file.Paths) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) EventHandlers(com.google.cloud.tools.jib.event.EventHandlers) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) ImageConfiguration(com.google.cloud.tools.jib.configuration.ImageConfiguration) StepsRunner(com.google.cloud.tools.jib.builder.steps.StepsRunner)

Example 17 with BuildContext

use of com.google.cloud.tools.jib.configuration.BuildContext in project jib by google.

the class JibContainerBuilder method containerize.

/**
 * Builds the container.
 *
 * @param containerizer the {@link Containerizer} that configures how to containerize
 * @return the built container
 * @throws IOException if an I/O exception occurs
 * @throws CacheDirectoryCreationException if a directory to be used for the cache could not be
 *     created
 * @throws HttpHostConnectException if jib failed to connect to a registry
 * @throws RegistryUnauthorizedException if a registry request is unauthorized and needs
 *     authentication
 * @throws RegistryAuthenticationFailedException if registry authentication failed
 * @throws UnknownHostException if the registry does not exist
 * @throws InsecureRegistryException if a server could not be verified due to an insecure
 *     connection
 * @throws RegistryException if some other error occurred while interacting with a registry
 * @throws ExecutionException if some other exception occurred during execution
 * @throws InterruptedException if the execution was interrupted
 */
public JibContainer containerize(Containerizer containerizer) throws InterruptedException, RegistryException, IOException, CacheDirectoryCreationException, ExecutionException {
    try (BuildContext buildContext = toBuildContext(containerizer);
        TimerEventDispatcher ignored = new TimerEventDispatcher(buildContext.getEventHandlers(), containerizer.getDescription())) {
        logSources(buildContext.getEventHandlers());
        BuildResult buildResult = containerizer.run(buildContext);
        return JibContainer.from(buildContext, buildResult);
    } catch (ExecutionException ex) {
        // If an ExecutionException occurs, re-throw the cause to be more easily handled by the user
        if (ex.getCause() instanceof RegistryException) {
            throw (RegistryException) ex.getCause();
        }
        throw ex;
    }
}
Also used : BuildResult(com.google.cloud.tools.jib.builder.steps.BuildResult) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) TimerEventDispatcher(com.google.cloud.tools.jib.builder.TimerEventDispatcher) ExecutionException(java.util.concurrent.ExecutionException)

Example 18 with BuildContext

use of com.google.cloud.tools.jib.configuration.BuildContext in project jib by google.

the class PullBaseImageStep method getCachedBaseImages.

/**
 * Retrieves the cached base images. If a base image reference is not a manifest list, returns a
 * single image (if cached). If a manifest list, returns all the images matching the configured
 * platforms in the manifest list but only when all of the images are cached.
 *
 * @return the cached images, if found
 * @throws IOException when an I/O exception occurs
 * @throws CacheCorruptedException if the cache is corrupted
 * @throws LayerPropertyNotFoundException if adding image layers fails
 * @throws BadContainerConfigurationFormatException if the container configuration is in a bad
 *     format
 * @throws UnlistedPlatformInManifestListException if a cached manifest list has no manifests
 *     matching the configured platform
 */
@VisibleForTesting
List<Image> getCachedBaseImages() throws IOException, CacheCorruptedException, BadContainerConfigurationFormatException, LayerCountMismatchException, UnlistedPlatformInManifestListException {
    ImageReference baseImage = buildContext.getBaseImageConfiguration().getImage();
    Optional<ImageMetadataTemplate> metadata = buildContext.getBaseImageLayersCache().retrieveMetadata(baseImage);
    if (!metadata.isPresent()) {
        return Collections.emptyList();
    }
    ManifestTemplate manifestList = metadata.get().getManifestList();
    List<ManifestAndConfigTemplate> manifestsAndConfigs = metadata.get().getManifestsAndConfigs();
    if (manifestList == null) {
        Verify.verify(manifestsAndConfigs.size() == 1);
        ManifestTemplate manifest = manifestsAndConfigs.get(0).getManifest();
        if (manifest instanceof V21ManifestTemplate) {
            return Collections.singletonList(JsonToImageTranslator.toImage((V21ManifestTemplate) manifest));
        }
        ContainerConfigurationTemplate containerConfig = Verify.verifyNotNull(manifestsAndConfigs.get(0).getConfig());
        PlatformChecker.checkManifestPlatform(buildContext, containerConfig);
        return Collections.singletonList(JsonToImageTranslator.toImage((BuildableManifestTemplate) Verify.verifyNotNull(manifest), containerConfig));
    }
    // Manifest list cached. Identify matching platforms and check if all of them are cached.
    ImmutableList.Builder<Image> images = ImmutableList.builder();
    for (Platform platform : buildContext.getContainerConfiguration().getPlatforms()) {
        String manifestDigest = lookUpPlatformSpecificImageManifest((V22ManifestListTemplate) manifestList, platform);
        Optional<ManifestAndConfigTemplate> manifestAndConfigFound = manifestsAndConfigs.stream().filter(entry -> manifestDigest.equals(entry.getManifestDigest())).findFirst();
        if (!manifestAndConfigFound.isPresent()) {
            return Collections.emptyList();
        }
        ManifestTemplate manifest = Verify.verifyNotNull(manifestAndConfigFound.get().getManifest());
        ContainerConfigurationTemplate containerConfig = Verify.verifyNotNull(manifestAndConfigFound.get().getConfig());
        images.add(JsonToImageTranslator.toImage((BuildableManifestTemplate) manifest, containerConfig));
    }
    return images.build();
}
Also used : TimerEventDispatcher(com.google.cloud.tools.jib.builder.TimerEventDispatcher) ImageReference(com.google.cloud.tools.jib.api.ImageReference) ImageConfiguration(com.google.cloud.tools.jib.configuration.ImageConfiguration) ManifestAndConfigTemplate(com.google.cloud.tools.jib.image.json.ManifestAndConfigTemplate) ProgressEvent(com.google.cloud.tools.jib.event.events.ProgressEvent) Callable(java.util.concurrent.Callable) LayerPropertyNotFoundException(com.google.cloud.tools.jib.image.LayerPropertyNotFoundException) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) UnknownManifestFormatException(com.google.cloud.tools.jib.image.json.UnknownManifestFormatException) V22ManifestListTemplate(com.google.cloud.tools.jib.image.json.V22ManifestListTemplate) Credential(com.google.cloud.tools.jib.api.Credential) ImagesAndRegistryClient(com.google.cloud.tools.jib.builder.steps.PullBaseImageStep.ImagesAndRegistryClient) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Nullable(javax.annotation.Nullable) Verify(com.google.common.base.Verify) V21ManifestTemplate(com.google.cloud.tools.jib.image.json.V21ManifestTemplate) BuildableManifestTemplate(com.google.cloud.tools.jib.image.json.BuildableManifestTemplate) UnlistedPlatformInManifestListException(com.google.cloud.tools.jib.image.json.UnlistedPlatformInManifestListException) Collection(java.util.Collection) JsonTemplateMapper(com.google.cloud.tools.jib.json.JsonTemplateMapper) Set(java.util.Set) IOException(java.io.IOException) RegistryUnauthorizedException(com.google.cloud.tools.jib.api.RegistryUnauthorizedException) RegistryException(com.google.cloud.tools.jib.api.RegistryException) CredentialRetrievalException(com.google.cloud.tools.jib.registry.credentials.CredentialRetrievalException) Cache(com.google.cloud.tools.jib.cache.Cache) CacheCorruptedException(com.google.cloud.tools.jib.cache.CacheCorruptedException) ContainerConfigurationTemplate(com.google.cloud.tools.jib.image.json.ContainerConfigurationTemplate) RegistryClient(com.google.cloud.tools.jib.registry.RegistryClient) LogEvent(com.google.cloud.tools.jib.api.LogEvent) ManifestAndDigest(com.google.cloud.tools.jib.registry.ManifestAndDigest) List(java.util.List) JsonToImageTranslator(com.google.cloud.tools.jib.image.json.JsonToImageTranslator) ImageMetadataTemplate(com.google.cloud.tools.jib.image.json.ImageMetadataTemplate) ManifestTemplate(com.google.cloud.tools.jib.image.json.ManifestTemplate) ProgressEventDispatcher(com.google.cloud.tools.jib.builder.ProgressEventDispatcher) EventHandlers(com.google.cloud.tools.jib.event.EventHandlers) Optional(java.util.Optional) Blobs(com.google.cloud.tools.jib.blob.Blobs) BadContainerConfigurationFormatException(com.google.cloud.tools.jib.image.json.BadContainerConfigurationFormatException) Preconditions(com.google.common.base.Preconditions) Platform(com.google.cloud.tools.jib.api.buildplan.Platform) VisibleForTesting(com.google.common.annotations.VisibleForTesting) LayerCountMismatchException(com.google.cloud.tools.jib.image.LayerCountMismatchException) Collections(java.util.Collections) Image(com.google.cloud.tools.jib.image.Image) ContainerConfigurationTemplate(com.google.cloud.tools.jib.image.json.ContainerConfigurationTemplate) Platform(com.google.cloud.tools.jib.api.buildplan.Platform) ImmutableList(com.google.common.collect.ImmutableList) V21ManifestTemplate(com.google.cloud.tools.jib.image.json.V21ManifestTemplate) BuildableManifestTemplate(com.google.cloud.tools.jib.image.json.BuildableManifestTemplate) ManifestTemplate(com.google.cloud.tools.jib.image.json.ManifestTemplate) ManifestAndConfigTemplate(com.google.cloud.tools.jib.image.json.ManifestAndConfigTemplate) Image(com.google.cloud.tools.jib.image.Image) ImageReference(com.google.cloud.tools.jib.api.ImageReference) ImageMetadataTemplate(com.google.cloud.tools.jib.image.json.ImageMetadataTemplate) BuildableManifestTemplate(com.google.cloud.tools.jib.image.json.BuildableManifestTemplate) V21ManifestTemplate(com.google.cloud.tools.jib.image.json.V21ManifestTemplate) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 19 with BuildContext

use of com.google.cloud.tools.jib.configuration.BuildContext in project jib by google.

the class PushImageStep method makeListForManifestList.

static ImmutableList<PushImageStep> makeListForManifestList(BuildContext buildContext, ProgressEventDispatcher.Factory progressEventDispatcherFactory, RegistryClient registryClient, ManifestTemplate manifestList, boolean manifestListAlreadyExists) throws IOException {
    Set<String> tags = buildContext.getAllTargetImageTags();
    EventHandlers eventHandlers = buildContext.getEventHandlers();
    try (TimerEventDispatcher ignored = new TimerEventDispatcher(eventHandlers, "Preparing manifest list pushers");
        ProgressEventDispatcher progressEventDispatcher = progressEventDispatcherFactory.create("launching manifest list pushers", tags.size())) {
        boolean singlePlatform = buildContext.getContainerConfiguration().getPlatforms().size() == 1;
        if (singlePlatform) {
            // single image; no need to push a manifest list
            return ImmutableList.of();
        }
        if (JibSystemProperties.skipExistingImages() && manifestListAlreadyExists) {
            eventHandlers.dispatch(LogEvent.info("Skipping pushing manifest list; already exists."));
            return ImmutableList.of();
        }
        DescriptorDigest manifestListDigest = Digests.computeJsonDigest(manifestList);
        return tags.stream().map(tag -> new PushImageStep(buildContext, progressEventDispatcher.newChildProducer(), registryClient, manifestList, tag, manifestListDigest, // return value and type.
        manifestListDigest)).collect(ImmutableList.toImmutableList());
    }
}
Also used : TimerEventDispatcher(com.google.cloud.tools.jib.builder.TimerEventDispatcher) BuildableManifestTemplate(com.google.cloud.tools.jib.image.json.BuildableManifestTemplate) ImageToJsonTranslator(com.google.cloud.tools.jib.image.json.ImageToJsonTranslator) Set(java.util.Set) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) RegistryException(com.google.cloud.tools.jib.api.RegistryException) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) Collectors(java.util.stream.Collectors) BlobDescriptor(com.google.cloud.tools.jib.blob.BlobDescriptor) DescriptorDigest(com.google.cloud.tools.jib.api.DescriptorDigest) Digests(com.google.cloud.tools.jib.hash.Digests) RegistryClient(com.google.cloud.tools.jib.registry.RegistryClient) LogEvent(com.google.cloud.tools.jib.api.LogEvent) ImmutableList(com.google.common.collect.ImmutableList) JibSystemProperties(com.google.cloud.tools.jib.global.JibSystemProperties) ManifestTemplate(com.google.cloud.tools.jib.image.json.ManifestTemplate) ProgressEventDispatcher(com.google.cloud.tools.jib.builder.ProgressEventDispatcher) EventHandlers(com.google.cloud.tools.jib.event.EventHandlers) Collections(java.util.Collections) Image(com.google.cloud.tools.jib.image.Image) ProgressEventDispatcher(com.google.cloud.tools.jib.builder.ProgressEventDispatcher) DescriptorDigest(com.google.cloud.tools.jib.api.DescriptorDigest) TimerEventDispatcher(com.google.cloud.tools.jib.builder.TimerEventDispatcher) EventHandlers(com.google.cloud.tools.jib.event.EventHandlers)

Example 20 with BuildContext

use of com.google.cloud.tools.jib.configuration.BuildContext in project jib by google.

the class JavaContainerBuilderTest method testToJibContainerBuilder_setAppRootLate.

@Test
public void testToJibContainerBuilder_setAppRootLate() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException {
    BuildContext buildContext = JavaContainerBuilder.from("scratch").addClasses(getResource("core/application/classes")).addResources(getResource("core/application/resources")).addDependencies(getResource("core/application/dependencies/libraryA.jar")).addToClasspath(getResource("core/fileA")).setAppRoot("/different").setMainClass("HelloWorld").toContainerBuilder().toBuildContext(Containerizer.to(RegistryImage.named("hello")));
    // Check entrypoint
    Assert.assertEquals(ImmutableList.of("java", "-cp", "/different/classes:/different/resources:/different/libs/*:/different/classpath", "HelloWorld"), buildContext.getContainerConfiguration().getEntrypoint());
    // Check classes
    List<AbsoluteUnixPath> expectedClasses = ImmutableList.of(AbsoluteUnixPath.get("/different/classes/HelloWorld.class"), AbsoluteUnixPath.get("/different/classes/some.class"));
    Assert.assertEquals(expectedClasses, getExtractionPaths(buildContext, "classes"));
    // Check resources
    List<AbsoluteUnixPath> expectedResources = ImmutableList.of(AbsoluteUnixPath.get("/different/resources/resourceA"), AbsoluteUnixPath.get("/different/resources/resourceB"), AbsoluteUnixPath.get("/different/resources/world"));
    Assert.assertEquals(expectedResources, getExtractionPaths(buildContext, "resources"));
    // Check dependencies
    List<AbsoluteUnixPath> expectedDependencies = ImmutableList.of(AbsoluteUnixPath.get("/different/libs/libraryA.jar"));
    Assert.assertEquals(expectedDependencies, getExtractionPaths(buildContext, "dependencies"));
    Assert.assertEquals(expectedClasses, getExtractionPaths(buildContext, "classes"));
    // Check additional classpath files
    List<AbsoluteUnixPath> expectedOthers = ImmutableList.of(AbsoluteUnixPath.get("/different/classpath/fileA"));
    Assert.assertEquals(expectedOthers, getExtractionPaths(buildContext, "extra files"));
}
Also used : AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) BuildContext(com.google.cloud.tools.jib.configuration.BuildContext) Test(org.junit.Test)

Aggregations

BuildContext (com.google.cloud.tools.jib.configuration.BuildContext)45 Test (org.junit.Test)31 ImageConfiguration (com.google.cloud.tools.jib.configuration.ImageConfiguration)23 EventHandlers (com.google.cloud.tools.jib.event.EventHandlers)12 IOException (java.io.IOException)12 Set (java.util.Set)12 BuildResult (com.google.cloud.tools.jib.builder.steps.BuildResult)9 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)8 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)8 Platform (com.google.cloud.tools.jib.api.buildplan.Platform)8 TimerEventDispatcher (com.google.cloud.tools.jib.builder.TimerEventDispatcher)8 Preconditions (com.google.common.base.Preconditions)8 List (java.util.List)8 Optional (java.util.Optional)8 ExecutionException (java.util.concurrent.ExecutionException)8 Nullable (javax.annotation.Nullable)8 LogEvent (com.google.cloud.tools.jib.api.LogEvent)6 RegistryException (com.google.cloud.tools.jib.api.RegistryException)6 StepsRunner (com.google.cloud.tools.jib.builder.steps.StepsRunner)6 DockerClient (com.google.cloud.tools.jib.docker.DockerClient)6