Search in sources :

Example 11 with Application

use of com.oracle.bedrock.runtime.Application in project oracle-bedrock by coherence-community.

the class AbstractWindowsTest method getPowershellVersion.

/**
 * If powershell.exe exists then return the version
 * of PowerShell installed.
 *
 * @return the version of PowerShell installed
 */
public static double getPowershellVersion(Platform platform) {
    if (!powershellPresent()) {
        return -1.0;
    }
    double version = -1.0;
    CapturingApplicationConsole console = new CapturingApplicationConsole();
    try (Application application = platform.launch(Application.class, Executable.named("powershell"), Argument.of("-Command"), Argument.of("&{$PSVersionTable.PSVersion}"), DisplayName.of("PSVersionCheck"), Console.of(console))) {
        try {
            Eventually.assertThat(invoking(console).getCapturedOutputLines().size(), is(greaterThan(3)));
        } catch (AssertionError assertionError) {
        // ignored
        }
    }
    Queue<String> lines = console.getCapturedOutputLines();
    if (lines.size() >= 4) {
        lines.poll();
        lines.poll();
        lines.poll();
        String[] versions = lines.poll().split("(\\s)+");
        try {
            version = Double.parseDouble(versions[0] + '.' + versions[1]);
        } catch (NumberFormatException e) {
        // ignored
        }
    }
    return version;
}
Also used : CapturingApplicationConsole(com.oracle.bedrock.runtime.console.CapturingApplicationConsole) Application(com.oracle.bedrock.runtime.Application)

Example 12 with Application

use of com.oracle.bedrock.runtime.Application in project oracle-bedrock by coherence-community.

the class Build method onLaunched.

@Override
public void onLaunched(Platform platform, Application application, OptionsByType optionsByType) {
    Arguments arguments = optionsByType.get(Arguments.class);
    String tagPrefix = "--tag=";
    int prefixLen = tagPrefix.length();
    List<String> tags = arguments.stream().map((arg) -> String.valueOf(arg.getValue())).filter((tagArg) -> tagArg.startsWith(tagPrefix)).map((tagArg) -> tagArg.substring(prefixLen)).collect(Collectors.toList());
    DockerImage image = new DockerImage(tags, optionsByType);
    application.add(image);
}
Also used : Timeout(com.oracle.bedrock.options.Timeout) URL(java.net.URL) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Arguments(com.oracle.bedrock.runtime.options.Arguments) File(java.io.File) Argument(com.oracle.bedrock.runtime.options.Argument) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Platform(com.oracle.bedrock.runtime.Platform) DockerImage(com.oracle.bedrock.runtime.docker.DockerImage) OptionsByType(com.oracle.bedrock.OptionsByType) Application(com.oracle.bedrock.runtime.Application) Arguments(com.oracle.bedrock.runtime.options.Arguments) DockerImage(com.oracle.bedrock.runtime.docker.DockerImage)

Example 13 with Application

use of com.oracle.bedrock.runtime.Application in project oracle-bedrock by coherence-community.

the class DockerRemoteTerminal method runContainer.

/**
 * Run a container using the specified image.
 *
 * @param containerName  the name of the container
 * @param launchable     the {@link RemoteTerminal.Launchable} that will give the command to execute
 * @param image          the image to use to run the container
 * @param docker         the {@link Docker} environment to use
 * @param optionsByType  the {@link OptionsByType} to use
 *
 * @return  a {@link DockerContainer} representing the running image
 */
protected ApplicationProcess runContainer(String containerName, Launchable launchable, DockerImage image, Docker docker, OptionsByType optionsByType) {
    Timeout timeout = optionsByType.get(Timeout.class);
    WorkingDirectory workingDirectory = optionsByType.get(WorkingDirectory.class);
    String workingDirectoryName = workingDirectory.resolve(platform, optionsByType).toString();
    optionsByType.add(PlatformSeparators.forUnix());
    optionsByType.add(new CPModifier(workingDirectoryName));
    // ----- give the container a random UUID as a name -----
    DisplayName displayName = optionsByType.getOrSetDefault(DisplayName.class, DisplayName.of("Container"));
    // ----- create the arguments to pass to the container as the command to execute
    String command = launchable.getCommandToExecute(platform, optionsByType);
    List<?> args = launchable.getCommandLineArguments(platform, optionsByType);
    Arguments containerArgs = Arguments.of(command).with(args);
    // ----- get any captured ports to map -----
    Ports ports = optionsByType.get(Ports.class);
    List<Integer> portList = ports.getPorts().stream().map(Ports.Port::getActualPort).collect(Collectors.toList());
    // ----- create the Run command -----
    Run runCommand = Run.image(image, containerName).interactive().net(docker.getDefaultNetworkName()).hostName(containerName).env(launchable.getEnvironmentVariables(platform, optionsByType)).publish(portList).autoRemove();
    OptionsByType containerOptions = OptionsByType.of(optionsByType).addAll(displayName, docker, WorkingDirectory.at(tmpFolder), ContainerCloseBehaviour.none(), ImageCloseBehaviour.remove(), containerArgs);
    // ----- start the application to capture Docker events so that we know when the container is in the running state -----
    EventsApplicationConsole.CountDownListener latch = new EventsApplicationConsole.CountDownListener(1);
    Predicate<String> predicate = (line) -> line.contains("container start");
    EventsApplicationConsole eventConsole = new EventsApplicationConsole().withStdOutListener(predicate, latch);
    try (Application events = platform.launch(Events.fromContainer(containerName), docker, Console.of(eventConsole))) {
        // ----- launch the container -----
        ContainerApplication application = platform.launch(new ContainerMetaClass(runCommand), containerOptions.asArray());
        // ----- get the container feature from the application -----
        DockerContainer container = application.get(DockerContainer.class);
        FeatureAddingProfile profile = new FeatureAddingProfile(image, container);
        // ----- add the container and default close behaviour to the options
        optionsByType.add(profile);
        optionsByType.add(ImageCloseBehaviour.remove());
        try {
            if (!latch.await(timeout.to(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Failed to detect container start event within " + timeout);
            }
        } catch (InterruptedException e) {
        // ignored
        }
        // ----- obtain the port mappings from the container -----
        JsonObject jsonNet = (JsonObject) container.inspect("{{json .NetworkSettings}}");
        if (!jsonNet.get("Ports").getValueType().equals(JsonValue.ValueType.NULL)) {
            JsonObject jsonPorts = jsonNet.getJsonObject("Ports");
            List<Ports.Port> mappedPorts = ports.getPorts().stream().map((port) -> {
                String key = port.getActualPort() + "/tcp";
                String hostPort = jsonPorts.getJsonArray(key).getJsonObject(0).getString("HostPort");
                return new Ports.Port(port.getName(), port.getActualPort(), Integer.parseInt(hostPort));
            }).collect(Collectors.toList());
            // ----- update the options with the correctly mapped ports -----
            optionsByType.remove(Ports.class);
            optionsByType.add(Ports.of(mappedPorts));
        }
        // ----- return the process from the container application -----
        return application.getProcess();
    }
}
Also used : NullApplicationConsole(com.oracle.bedrock.runtime.console.NullApplicationConsole) Arrays(java.util.Arrays) Timeout(com.oracle.bedrock.options.Timeout) ImageCloseBehaviour(com.oracle.bedrock.runtime.docker.options.ImageCloseBehaviour) RemoteTerminal(com.oracle.bedrock.runtime.remote.RemoteTerminal) Discriminator(com.oracle.bedrock.runtime.options.Discriminator) JsonValue(javax.json.JsonValue) InetAddress(java.net.InetAddress) Console(com.oracle.bedrock.runtime.options.Console) Deployer(com.oracle.bedrock.runtime.remote.options.Deployer) AbstractExtensible(com.oracle.bedrock.extensible.AbstractExtensible) OptionsByType(com.oracle.bedrock.OptionsByType) Build(com.oracle.bedrock.runtime.docker.commands.Build) StringHelper(com.oracle.bedrock.lang.StringHelper) PrintWriter(java.io.PrintWriter) Bedrock(com.oracle.bedrock.Bedrock) Events(com.oracle.bedrock.runtime.docker.commands.Events) JsonObject(javax.json.JsonObject) Predicate(java.util.function.Predicate) ContainerCloseBehaviour(com.oracle.bedrock.runtime.docker.options.ContainerCloseBehaviour) UUID(java.util.UUID) EventsApplicationConsole(com.oracle.bedrock.runtime.console.EventsApplicationConsole) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Option(com.oracle.bedrock.Option) List(java.util.List) Feature(com.oracle.bedrock.extensible.Feature) Platform(com.oracle.bedrock.runtime.Platform) Run(com.oracle.bedrock.runtime.docker.commands.Run) DeployedArtifacts(com.oracle.bedrock.runtime.remote.DeployedArtifacts) Remove(com.oracle.bedrock.runtime.docker.commands.Remove) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ApplicationProcess(com.oracle.bedrock.runtime.ApplicationProcess) MetaClass(com.oracle.bedrock.runtime.MetaClass) PlatformSeparators(com.oracle.bedrock.runtime.options.PlatformSeparators) Variable(com.oracle.bedrock.options.Variable) RemoteApplicationProcess(com.oracle.bedrock.runtime.remote.RemoteApplicationProcess) Kill(com.oracle.bedrock.runtime.docker.commands.Kill) Application(com.oracle.bedrock.runtime.Application) ClassPathModifier(com.oracle.bedrock.runtime.java.ClassPathModifier) OutputStream(java.io.OutputStream) Properties(java.util.Properties) WorkingDirectory(com.oracle.bedrock.runtime.options.WorkingDirectory) Files(java.nio.file.Files) IOException(java.io.IOException) Arguments(com.oracle.bedrock.runtime.options.Arguments) File(java.io.File) Table(com.oracle.bedrock.table.Table) TimeUnit(java.util.concurrent.TimeUnit) Ports(com.oracle.bedrock.runtime.options.Ports) DeploymentArtifact(com.oracle.bedrock.runtime.remote.DeploymentArtifact) DockerfileDeployer(com.oracle.bedrock.runtime.docker.options.DockerfileDeployer) DisplayName(com.oracle.bedrock.runtime.options.DisplayName) FileHelper(com.oracle.bedrock.io.FileHelper) Profile(com.oracle.bedrock.runtime.Profile) InputStream(java.io.InputStream) JsonObject(javax.json.JsonObject) DisplayName(com.oracle.bedrock.runtime.options.DisplayName) WorkingDirectory(com.oracle.bedrock.runtime.options.WorkingDirectory) Timeout(com.oracle.bedrock.options.Timeout) Arguments(com.oracle.bedrock.runtime.options.Arguments) Ports(com.oracle.bedrock.runtime.options.Ports) Run(com.oracle.bedrock.runtime.docker.commands.Run) EventsApplicationConsole(com.oracle.bedrock.runtime.console.EventsApplicationConsole) OptionsByType(com.oracle.bedrock.OptionsByType) Application(com.oracle.bedrock.runtime.Application)

Example 14 with Application

use of com.oracle.bedrock.runtime.Application in project oracle-bedrock by coherence-community.

the class DockerRemoteTerminal method createImage.

/**
 * Create a Docker image.
 * <p>
 * The image will contain all of the required artifacts to run the application.
 * The image will be tagged with a random UUID.
 *
 * @param imageTag       the tag to apply to the image
 * @param dockerFile     the Dockerfile to use to build the image
 * @param docker         the {@link Docker} environment to use
 * @param optionsByType  the {@link OptionsByType} to use
 *
 * @return  a {@link DockerImage} representing the built image
 */
protected DockerImage createImage(String imageTag, File dockerFile, Docker docker, OptionsByType optionsByType) {
    LOGGER.log(Level.INFO, "Building Docker Image...");
    DisplayName displayName = optionsByType.getOrSetDefault(DisplayName.class, DisplayName.of(""));
    String dockerFileName = dockerFile.getName();
    Timeout timeout = optionsByType.getOrSetDefault(Timeout.class, Build.DEFAULT_TIMEOUT);
    try (Application application = platform.launch(Build.fromDockerFile(dockerFileName).withTags(imageTag).labels("oracle.bedrock.image=true").timeoutAfter(timeout), displayName, Discriminator.of("Image"), docker, ImageCloseBehaviour.none(), WorkingDirectory.at(tmpFolder))) {
        if (application.waitFor(timeout) != 0) {
            // If there is a failure attempt to remove the image, just in case it was actually created
            String msg = "An error occurred, build returned " + application.exitValue();
            LOGGER.log(Level.SEVERE, msg + ". Attempting to remove image " + imageTag);
            safelyRemoveImage(imageTag, docker);
            throw new RuntimeException(msg);
        }
        DockerImage image = application.get(DockerImage.class);
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.log(Level.INFO, "Built Docker Image: " + imageTag);
        }
        return image;
    }
}
Also used : Timeout(com.oracle.bedrock.options.Timeout) DisplayName(com.oracle.bedrock.runtime.options.DisplayName) Application(com.oracle.bedrock.runtime.Application)

Example 15 with Application

use of com.oracle.bedrock.runtime.Application in project oracle-bedrock by coherence-community.

the class DockerMachine method environmentFor.

/**
 * Obtain the {@link EnvironmentVariable}s that can be applied to a Docker command
 * to make it execute against the specified Docker Machine.
 *
 * @param machineName  the name of the Docker Machine
 *
 * @return  the {@link EnvironmentVariable}s required to use the Docker Machine
 */
public List<EnvironmentVariable> environmentFor(String machineName) {
    CapturingApplicationConsole console = new CapturingApplicationConsole();
    try (Application application = launch("env", Argument.of(machineName), Console.of(console))) {
        if (application.waitFor() == 0) {
            return console.getCapturedOutputLines().stream().filter((line) -> line.startsWith("export")).map((line) -> line.substring(7)).map((line -> {
                int index = line.indexOf('=');
                if (index >= 0) {
                    String name = line.substring(0, index);
                    String value = StringHelper.unquote(line.substring(index + 1));
                    return EnvironmentVariable.of(name, value);
                }
                return EnvironmentVariable.of(line);
            })).collect(Collectors.toList());
        }
        String msg = "Error obtaining environment for docker-machine " + machineName;
        logError(msg, console);
        throw new RuntimeException(msg);
    }
}
Also used : Arrays(java.util.Arrays) CapturingApplicationConsole(com.oracle.bedrock.runtime.console.CapturingApplicationConsole) Timeout(com.oracle.bedrock.options.Timeout) DockerPlatform(com.oracle.bedrock.runtime.docker.DockerPlatform) Level(java.util.logging.Level) InetAddress(java.net.InetAddress) Console(com.oracle.bedrock.runtime.options.Console) EnvironmentVariable(com.oracle.bedrock.runtime.options.EnvironmentVariable) Json(javax.json.Json) OptionsByType(com.oracle.bedrock.OptionsByType) Application(com.oracle.bedrock.runtime.Application) StringHelper(com.oracle.bedrock.lang.StringHelper) JsonObject(javax.json.JsonObject) JsonReader(javax.json.JsonReader) LocalPlatform(com.oracle.bedrock.runtime.LocalPlatform) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Arguments(com.oracle.bedrock.runtime.options.Arguments) File(java.io.File) Argument(com.oracle.bedrock.runtime.options.Argument) Option(com.oracle.bedrock.Option) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Stream(java.util.stream.Stream) StringReader(java.io.StringReader) Platform(com.oracle.bedrock.runtime.Platform) CapturingApplicationConsole(com.oracle.bedrock.runtime.console.CapturingApplicationConsole) Application(com.oracle.bedrock.runtime.Application)

Aggregations

Application (com.oracle.bedrock.runtime.Application)57 Test (org.junit.Test)23 CapturingApplicationConsole (com.oracle.bedrock.runtime.console.CapturingApplicationConsole)22 Platform (com.oracle.bedrock.runtime.Platform)16 Arguments (com.oracle.bedrock.runtime.options.Arguments)13 OptionsByType (com.oracle.bedrock.OptionsByType)12 File (java.io.File)12 JavaApplication (com.oracle.bedrock.runtime.java.JavaApplication)11 Timeout (com.oracle.bedrock.options.Timeout)9 MetaClass (com.oracle.bedrock.runtime.MetaClass)9 List (java.util.List)7 LocalPlatform (com.oracle.bedrock.runtime.LocalPlatform)6 Remove (com.oracle.bedrock.runtime.docker.commands.Remove)5 RemotePlatform (com.oracle.bedrock.runtime.remote.RemotePlatform)5 InetAddress (java.net.InetAddress)5 SleepingApplication (applications.SleepingApplication)4 ContainerCloseBehaviour (com.oracle.bedrock.runtime.docker.options.ContainerCloseBehaviour)4 TimeUnit (java.util.concurrent.TimeUnit)4 Collectors (java.util.stream.Collectors)4 EventingApplication (classloader.applications.EventingApplication)3