Search in sources :

Example 1 with DockerContainerConfig

use of org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig in project linuxtools by eclipse.

the class LaunchConfigurationUtils method createRunImageLaunchConfiguration.

/**
 * Creates a new {@link ILaunchConfiguration} for the given
 * {@link IDockerContainer}.
 *
 * @param baseConfigurationName
 *            the base configuration name to use when creating the
 *            {@link ILaunchConfiguration}.
 * @param image
 *            the {@link IDockerImage} used to create the container
 * @param containerName
 *            the actual container name (given by the user or generated by
 *            the Docker daemon)
 * @param containerConfig
 * @param hostConfig
 *            the user-provided {@link IDockerHostConfig} (created
 *            container's one)
 * @param removeWhenExits
 *            flag to indicate if container should be removed when exited
 * @return the generated {@link ILaunchConfiguration}
 */
public static ILaunchConfiguration createRunImageLaunchConfiguration(final IDockerImage image, final IDockerContainerConfig containerConfig, final IDockerHostConfig hostConfig, final String containerName, final boolean removeWhenExits) {
    try {
        final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
        final ILaunchConfigurationType type = manager.getLaunchConfigurationType(IRunDockerImageLaunchConfigurationConstants.CONFIG_TYPE_ID);
        final String imageName = createRunImageLaunchConfigurationName(image);
        // using the image repo + first tag
        final ILaunchConfigurationWorkingCopy workingCopy = getLaunchConfigurationWorkingCopy(type, imageName);
        workingCopy.setAttribute(CREATION_DATE, DATE_FORMAT.format(new Date()));
        workingCopy.setAttribute(CONNECTION_NAME, image.getConnection().getName());
        workingCopy.setAttribute(IMAGE_ID, image.id());
        workingCopy.setAttribute(IMAGE_NAME, createRunImageLaunchConfigurationName(image));
        if (containerName != null && !containerName.isEmpty()) {
            workingCopy.setAttribute(CONTAINER_NAME, containerName);
        }
        // if we know the raw command string, use it since the container
        // config will remove quotes to split up command properly
        DockerContainerConfig config = (DockerContainerConfig) containerConfig;
        if (config.rawcmd() != null) {
            workingCopy.setAttribute(COMMAND, config.rawcmd());
        } else {
            workingCopy.setAttribute(COMMAND, toString(containerConfig.cmd()));
        }
        workingCopy.setAttribute(ENTRYPOINT, toString(containerConfig.entrypoint()));
        // selected ports
        workingCopy.setAttribute(PUBLISH_ALL_PORTS, hostConfig.publishAllPorts());
        // format: <containerPort><type>:<hostIP>:<hostPort>
        if (hostConfig.publishAllPorts()) {
            final IDockerImageInfo imageInfo = image.getConnection().getImageInfo(image.id());
            if (imageInfo != null) {
                workingCopy.setAttribute(PUBLISHED_PORTS, serializePortBindings(imageInfo.containerConfig().exposedPorts()));
            }
        } else {
            workingCopy.setAttribute(PUBLISHED_PORTS, serializePortBindings(hostConfig.portBindings()));
        }
        // links (with format being: "<containerName>:<containerAlias>")
        workingCopy.setAttribute(LINKS, hostConfig.links());
        // env variables
        workingCopy.setAttribute(ENV_VARIABLES, containerConfig.env());
        // labels
        workingCopy.setAttribute(LABELS, containerConfig.labels());
        // volumes
        final List<String> volumes = new ArrayList<>();
        // volumes from other containers
        for (String volumeFrom : hostConfig.volumesFrom()) {
            final DataVolumeModel volume = DataVolumeModel.parseVolumeFrom(volumeFrom);
            if (volume != null) {
                volumes.add(volume.toString());
            }
        }
        // bindings to host directory or file
        for (String bind : hostConfig.binds()) {
            final DataVolumeModel volume = DataVolumeModel.parseHostBinding(bind);
            if (volume != null) {
                volumes.add(volume.toString());
            }
        }
        // TODO: container path declaration
        workingCopy.setAttribute(DATA_VOLUMES, volumes);
        // options
        workingCopy.setAttribute(AUTO_REMOVE, removeWhenExits);
        workingCopy.setAttribute(ALLOCATE_PSEUDO_CONSOLE, containerConfig.tty());
        workingCopy.setAttribute(INTERACTIVE, containerConfig.openStdin());
        workingCopy.setAttribute(PRIVILEGED, hostConfig.privileged());
        workingCopy.setAttribute(READONLY, ((DockerHostConfig) hostConfig).readonlyRootfs());
        if (hostConfig.networkMode() != null)
            workingCopy.setAttribute(NETWORK_MODE, hostConfig.networkMode());
        // resources limitations
        if (containerConfig.memory() != null) {
            workingCopy.setAttribute(ENABLE_LIMITS, true);
            // memory in containerConfig is expressed in bytes
            workingCopy.setAttribute(MEMORY_LIMIT, Long.toString(containerConfig.memory().longValue() / MB));
        }
        if (containerConfig.cpuShares() != null) {
            workingCopy.setAttribute(ENABLE_LIMITS, true);
            workingCopy.setAttribute(CPU_PRIORITY, containerConfig.cpuShares().toString());
        }
        return workingCopy.doSave();
    } catch (CoreException e) {
        Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, LaunchMessages.getString(// $NON-NLS-1$
        "RunDockerImageLaunchConfiguration.creation.failure"), e));
    }
    return null;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) DataVolumeModel(org.eclipse.linuxtools.internal.docker.ui.wizards.DataVolumeModel) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) IDockerContainerConfig(org.eclipse.linuxtools.docker.core.IDockerContainerConfig) CoreException(org.eclipse.core.runtime.CoreException) ILaunchConfigurationType(org.eclipse.debug.core.ILaunchConfigurationType) ArrayList(java.util.ArrayList) ILaunchManager(org.eclipse.debug.core.ILaunchManager) IDockerImageInfo(org.eclipse.linuxtools.docker.core.IDockerImageInfo) ILaunchConfigurationWorkingCopy(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) Date(java.util.Date)

Example 2 with DockerContainerConfig

use of org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig in project linuxtools by eclipse.

the class ImageRun method getDockerContainerConfig.

public DockerContainerConfig getDockerContainerConfig() {
    final ImageRunSelectionModel selectionModel = this.imageRunSelectionPage.getModel();
    final ImageRunResourceVolumesVariablesModel resourcesModel = this.imageRunResourceVolumesPage.getModel();
    final Builder config = new DockerContainerConfig.Builder().cmd(selectionModel.getCommand()).entryPoint(selectionModel.getEntrypoint()).image(selectionModel.getSelectedImageName()).tty(selectionModel.isAllocatePseudoTTY()).openStdin(selectionModel.isInteractiveMode());
    if (resourcesModel.isEnableResourceLimitations()) {
        // memory limit must be converted from MB to bytes
        config.memory(resourcesModel.getMemoryLimit() * MB);
        config.cpuShares(resourcesModel.getCpuShareWeight());
    }
    // environment variables
    final List<String> environmentVariables = new ArrayList<>();
    for (Iterator<EnvironmentVariableModel> iterator = resourcesModel.getEnvironmentVariables().iterator(); iterator.hasNext(); ) {
        final EnvironmentVariableModel var = iterator.next();
        // $NON-NLS-1$
        environmentVariables.add(var.getName() + "=" + var.getValue());
    }
    config.env(environmentVariables);
    // container labels
    final Map<String, String> labelVariables = new HashMap<>();
    for (Iterator<LabelVariableModel> iterator = resourcesModel.getLabelVariables().iterator(); iterator.hasNext(); ) {
        final LabelVariableModel var = iterator.next();
        // $NON-NLS-1$
        labelVariables.put(var.getName(), var.getValue());
    }
    config.labels(labelVariables);
    if (!selectionModel.isPublishAllPorts()) {
        final Set<String> exposedPorts = new HashSet<>();
        for (Iterator<ExposedPortModel> iterator = selectionModel.getExposedPorts().iterator(); iterator.hasNext(); ) {
            final ExposedPortModel exposedPort = iterator.next();
            // only selected Ports in the CheckboxTableViewer are exposed.
            if (!selectionModel.getSelectedPorts().contains(exposedPort)) {
                continue;
            }
            exposedPorts.add(exposedPort.getContainerPort() + exposedPort.getPortType());
        }
        config.exposedPorts(exposedPorts);
    }
    return config.build();
}
Also used : ExposedPortModel(org.eclipse.linuxtools.internal.docker.ui.wizards.ImageRunSelectionModel.ExposedPortModel) HashMap(java.util.HashMap) Builder(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig.Builder) ArrayList(java.util.ArrayList) Builder(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig.Builder) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) HashSet(java.util.HashSet)

Example 3 with DockerContainerConfig

use of org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig in project linuxtools by eclipse.

the class ContainerInspectContentProvider method getChildren.

@Override
public Object[] getChildren(Object parentElement) {
    final Object propertyValue = ((Object[]) parentElement)[1];
    if (propertyValue instanceof IDockerContainerState) {
        final IDockerContainerState containerState = (IDockerContainerState) propertyValue;
        return new Object[] { // $NON-NLS-1$
        new Object[] { "ExitCode", containerState.exitCode() }, // $NON-NLS-1$
        new Object[] { "Finished at", LabelProviderUtils.toFinishedDate(containerState.finishDate()) }, // $NON-NLS-1$
        new Object[] { "Running", containerState.running() }, // $NON-NLS-1$
        new Object[] { "Paused", containerState.paused() }, // $NON-NLS-1$
        new Object[] { "Pid", containerState.pid() } };
    } else if (propertyValue instanceof IDockerHostConfig) {
        final DockerHostConfig hostConfig = (DockerHostConfig) propertyValue;
        return new Object[] { // $NON-NLS-1$
        new Object[] { "Binds", LabelProviderUtils.reduce(hostConfig.binds()) }, // $NON-NLS-1$
        new Object[] { "CapAdd", hostConfig.capAdd() }, // $NON-NLS-1$
        new Object[] { "CapDrop", hostConfig.capDrop() }, // $NON-NLS-1$
        new Object[] { "ContainerIDFile", hostConfig.containerIDFile() }, // $NON-NLS-1$
        new Object[] { "Dns", LabelProviderUtils.reduce(hostConfig.dns()) }, // $NON-NLS-1$
        new Object[] { "DnsSearch", LabelProviderUtils.reduce(hostConfig.dnsSearch()) }, // $NON-NLS-1$
        new Object[] { "Links", splitLinks(hostConfig.links()) }, // $NON-NLS-1$
        new Object[] { "LxcConf", hostConfig.lxcConf() }, // $NON-NLS-1$
        new Object[] { "NetworkMode", hostConfig.networkMode() }, // $NON-NLS-1$
        new Object[] { "PortBindings", LabelProviderUtils.reduce(hostConfig.portBindings()) }, // $NON-NLS-1$
        new Object[] { "Privileged", hostConfig.privileged() }, // $NON-NLS-1$
        new Object[] { "PublishAllPorts", hostConfig.publishAllPorts() }, new Object[] { // $NON-NLS-1$
        "ReadonlyRootfs", hostConfig.readonlyRootfs() }, // $NON-NLS-1$
        new Object[] { "SecurityOpt", hostConfig.securityOpt() }, // $NON-NLS-1$
        new Object[] { "Tmpfs", hostConfig.tmpfs() }, // $NON-NLS-1$
        new Object[] { "VolumesFrom", LabelProviderUtils.reduce(hostConfig.volumesFrom()) } };
    } else if (propertyValue instanceof IDockerContainerConfig) {
        final IDockerContainerConfig config = (IDockerContainerConfig) propertyValue;
        return new Object[] { // $NON-NLS-1$
        new Object[] { "AttachStderr", config.attachStderr() }, // $NON-NLS-1$
        new Object[] { "AttachStdin", config.attachStdin() }, // $NON-NLS-1$
        new Object[] { "AttachStdout", config.attachStdout() }, // $NON-NLS-1$
        new Object[] { "Cmd", LabelProviderUtils.reduce(config.cmd()) }, // $NON-NLS-1$
        new Object[] { "CpuSet", config.cpuset() }, // $NON-NLS-1$
        new Object[] { "CpuShares", config.cpuShares() }, // $NON-NLS-1$
        new Object[] { "Domainname", config.domainname() }, // $NON-NLS-1$
        new Object[] { "Entrypoint", LabelProviderUtils.reduce(config.entrypoint()) }, // $NON-NLS-1$
        new Object[] { "Env", LabelProviderUtils.reduce(config.env()) }, // $NON-NLS-1$
        new Object[] { "ExposedPorts", LabelProviderUtils.reduce(config.exposedPorts()) }, // $NON-NLS-1$
        new Object[] { "Hostname", config.hostname() }, // $NON-NLS-1$
        new Object[] { "Image", config.image() }, new Object[] { // $NON-NLS-1$
        "Labels", ((DockerContainerConfig) config).labels() }, // $NON-NLS-1$
        new Object[] { "Memory", config.memory() }, // $NON-NLS-1$
        new Object[] { "MemorySwap", config.memorySwap() }, // $NON-NLS-1$
        new Object[] { "NetworkDisabled", config.networkDisabled() }, // $NON-NLS-1$
        new Object[] { "OnBuild", config.onBuild() }, // $NON-NLS-1$
        new Object[] { "OpenStdin", config.openStdin() }, // $NON-NLS-1$
        new Object[] { "PortSpecs", LabelProviderUtils.reduce(config.portSpecs()) }, // $NON-NLS-1$
        new Object[] { "StdinOnce", config.stdinOnce() }, // $NON-NLS-1$
        new Object[] { "Tty", config.tty() }, new Object[] { // $NON-NLS-1$
        "Volumes", LabelProviderUtils.reduce(config.volumes().keySet()) }, // $NON-NLS-1$
        new Object[] { "WorkingDir", config.workingDir() } };
    } else if (propertyValue instanceof IDockerPortBinding) {
        final IDockerPortBinding portBinding = (IDockerPortBinding) propertyValue;
        return new Object[] { // $NON-NLS-1$
        new Object[] { "Host IP/Port", LabelProviderUtils.toString(portBinding) } };
    } else if (propertyValue instanceof IDockerNetworkSettings) {
        final IDockerNetworkSettings networkSettings = (IDockerNetworkSettings) propertyValue;
        return new Object[] { // $NON-NLS-1$
        new Object[] { "Bridge", networkSettings.bridge() }, // $NON-NLS-1$
        new Object[] { "Gateway", networkSettings.gateway() }, // $NON-NLS-1$
        new Object[] { "IPAddress", networkSettings.ipAddress() }, // $NON-NLS-1$
        new Object[] { "IPPrefixLen", networkSettings.ipPrefixLen() }, // $NON-NLS-1$
        new Object[] { "PortMapping", networkSettings.portMapping() }, // $NON-NLS-1$
        new Object[] { "Ports", LabelProviderUtils.reduce(networkSettings.ports()) } };
    } else if (propertyValue instanceof List<?>) {
        @SuppressWarnings("unchecked") final List<Object> propertyValues = (List<Object>) propertyValue;
        final Object[] result = new Object[propertyValues.size()];
        for (int i = 0; i < propertyValues.size(); i++) {
            // $NON-NLS-1$
            result[i] = new Object[] { "", LabelProviderUtils.toString(propertyValues.get(i)) };
        }
        return result;
    } else if (propertyValue instanceof Set<?>) {
        @SuppressWarnings("unchecked") final Set<Object> propertyValues = (Set<Object>) propertyValue;
        final Object[] result = new Object[propertyValues.size()];
        Iterator<Object> iterator = propertyValues.iterator();
        for (int i = 0; i < propertyValues.size(); i++) {
            result[i] = new Object[] { // $NON-NLS-1$
            "", LabelProviderUtils.toString(iterator.next()) };
        }
        return result;
    } else if (propertyValue instanceof Map<?, ?>) {
        final Map<?, ?> propertyValues = (Map<?, ?>) propertyValue;
        final Object[] result = new Object[propertyValues.size()];
        int i = 0;
        for (Entry<?, ?> entry : propertyValues.entrySet()) {
            result[i] = new Object[] { entry.getKey(), entry.getValue() };
            i++;
        }
        return result;
    }
    return EMPTY;
}
Also used : IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) DockerHostConfig(org.eclipse.linuxtools.internal.docker.core.DockerHostConfig) IDockerNetworkSettings(org.eclipse.linuxtools.docker.core.IDockerNetworkSettings) IDockerContainerConfig(org.eclipse.linuxtools.docker.core.IDockerContainerConfig) Set(java.util.Set) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) IDockerPortBinding(org.eclipse.linuxtools.docker.core.IDockerPortBinding) Entry(java.util.Map.Entry) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) IDockerContainerConfig(org.eclipse.linuxtools.docker.core.IDockerContainerConfig) List(java.util.List) IDockerContainerState(org.eclipse.linuxtools.docker.core.IDockerContainerState) Map(java.util.Map)

Example 4 with DockerContainerConfig

use of org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig in project linuxtools by eclipse.

the class ContainerLauncher method launch.

/**
 * Perform a launch of a command in a container and output stdout/stderr to
 * console.
 *
 * @param id
 *            - id of caller to use to distinguish console owner
 * @param listener
 *            - optional listener of the run console
 * @param connectionUri
 *            - the specified connection to use
 * @param image
 *            - the image to use
 * @param cmdList
 *            - command to run as list of String
 * @param workingDir
 *            - working directory or null
 * @param additionalDirs
 *            - additional directories to mount or null
 * @param origEnv
 *            - original environment if we are appending to our existing
 *            environment
 * @param envMap
 *            - map of environment variable settings
 * @param ports
 *            - ports to expose
 * @param keep
 *            - keep container after running
 * @param stdinSupport
 *            - true if stdin support is required, false otherwise
 * @param privilegedMode
 *            - true if privileged mode is required, false otherwise
 * @param labels
 *            - Map of labels for the container
 * @param seccomp
 *            - seccomp profile
 * @since 4.0
 */
public void launch(String id, IContainerLaunchListener listener, final String connectionUri, String image, List<String> cmdList, String workingDir, List<String> additionalDirs, Map<String, String> origEnv, Map<String, String> envMap, List<String> ports, boolean keep, boolean stdinSupport, boolean privilegedMode, Map<String, String> labels, String seccomp) {
    // $NON-NLS-1$
    final String LAUNCH_TITLE = "ContainerLaunch.title";
    // $NON-NLS-1$
    final String LAUNCH_EXITED_TITLE = "ContainerLaunchExited.title";
    final List<String> env = new ArrayList<>();
    env.addAll(toList(origEnv));
    env.addAll(toList(envMap));
    final Set<String> exposedPorts = new HashSet<>();
    final Map<String, List<IDockerPortBinding>> portBindingsMap = new HashMap<>();
    if (ports != null) {
        for (String port : ports) {
            port = port.trim();
            if (port.length() > 0) {
                // $NON-NLS-1$
                String[] segments = port.split(":");
                if (segments.length == 1) {
                    // containerPort
                    exposedPorts.add(segments[0]);
                    portBindingsMap.put(segments[0], Arrays.asList((IDockerPortBinding) new DockerPortBinding("", // $NON-NLS-1$ //$NON-NLS-2$
                    "")));
                } else if (segments.length == 2) {
                    // hostPort:containerPort
                    exposedPorts.add(segments[1]);
                    portBindingsMap.put(segments[1], Arrays.asList((IDockerPortBinding) new DockerPortBinding("", // $NON-NLS-1$ //$NON-NLS-2$
                    segments[0])));
                } else if (segments.length == 3) {
                    // either
                    // ip:hostPort:containerPort
                    // or ip::containerPort
                    exposedPorts.add(segments[1]);
                    if (segments[1].isEmpty()) {
                        portBindingsMap.put(segments[2], Arrays.asList((IDockerPortBinding) new DockerPortBinding("", // $NON-NLS-1$ //$NON-NLS-2$
                        segments[0])));
                    } else {
                        portBindingsMap.put(segments[2], Arrays.asList((IDockerPortBinding) new DockerPortBinding(segments[0], // $NON-NLS-1$ //$NON-NLS-2$
                        segments[1])));
                    }
                }
            }
        }
    }
    // Note we only pass volumes to the config if we have a
    // remote daemon. Local mounted volumes are passed
    // via the HostConfig binds setting
    DockerContainerConfig.Builder builder = new DockerContainerConfig.Builder().openStdin(stdinSupport).cmd(cmdList).image(image).workingDir(workingDir);
    // option
    if (listener != null && listener.getClass().getName().equals("org.eclipse.cdt.internal.docker.launcher.ContainerLaunchConfigurationDelegate$StartGdbServerJob")) {
        builder = builder.tty(true);
    }
    // add any exposed ports as needed
    if (exposedPorts.size() > 0)
        builder = builder.exposedPorts(exposedPorts);
    // add any labels if specified
    if (labels != null)
        builder = builder.labels(labels);
    if (!DockerConnectionManager.getInstance().hasConnections()) {
        Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getString(ERROR_LAUNCHING_CONTAINER), DVMessages.getString(ERROR_NO_CONNECTIONS)));
        return;
    }
    // Try and use the specified connection that was used before,
    // otherwise, open an error
    final IDockerConnection connection = DockerConnectionManager.getInstance().getConnectionByUri(connectionUri);
    if (connection == null) {
        Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getString(ERROR_LAUNCHING_CONTAINER), DVMessages.getFormattedString(ERROR_NO_CONNECTION_WITH_URI, connectionUri)));
        return;
    }
    // if connection is not open, force it to be by fetching images
    if (!connection.isOpen()) {
        connection.getImages();
    }
    DockerHostConfig.Builder hostBuilder = new DockerHostConfig.Builder().privileged(privilegedMode);
    // ptrace with gdbserver
    if (seccomp != null) {
        hostBuilder.securityOpt(seccomp);
    }
    final Map<String, String> remoteVolumes = new HashMap<>();
    if (!((DockerConnection) connection).isLocal()) {
        @SuppressWarnings("rawtypes") final Map<String, Map> volumes = new HashMap<>();
        // the host data over before starting.
        if (additionalDirs != null) {
            for (String dir : additionalDirs) {
                remoteVolumes.put(dir, dir);
                volumes.put(dir, new HashMap<>());
            }
        }
        if (workingDir != null) {
            // $NON-NLS-1$
            remoteVolumes.put(workingDir, workingDir);
            volumes.put(workingDir, new HashMap<>());
        }
        builder = builder.volumes(volumes);
    } else {
        // Running daemon on local host.
        // Add mounts for any directories we need to run the executable.
        // When we add mount points, we need entries of the form:
        // hostname:mountname:Z.
        // In our case, we want all directories mounted as-is so the
        // executable will run as the user expects.
        final List<String> volumes = new ArrayList<>();
        if (additionalDirs != null) {
            for (String dir : additionalDirs) {
                // $NON-NLS-1$ //$NON-NLS-2$
                volumes.add(dir + ":" + dir + ":Z");
            }
        }
        if (workingDir != null) {
            // $NON-NLS-1$ //$NON-NLS-2$
            volumes.add(workingDir + ":" + workingDir + ":Z");
        }
        hostBuilder = hostBuilder.binds(volumes);
    }
    final DockerContainerConfig config = builder.build();
    // add any port bindings if specified
    if (portBindingsMap.size() > 0)
        hostBuilder = hostBuilder.portBindings(portBindingsMap);
    final IDockerHostConfig hostConfig = hostBuilder.build();
    final String imageName = image;
    final boolean keepContainer = keep;
    final String consoleId = id;
    final IContainerLaunchListener containerListener = listener;
    Thread t = new Thread(() -> {
        // create the container
        String containerId = null;
        try {
            containerId = ((DockerConnection) connection).createContainer(config, hostConfig, null);
            if (!((DockerConnection) connection).isLocal()) {
                // data over from the host.
                if (!remoteVolumes.isEmpty()) {
                    CopyVolumesJob job = new CopyVolumesJob(remoteVolumes, connection, containerId);
                    job.schedule();
                    job.join();
                    if (job.getResult() != Status.OK_STATUS)
                        return;
                }
            }
            if (config.tty()) {
                // We need tty support to handle issue with Docker daemon
                // not always outputting in time (e.g. we might get an
                // output line after the process has exited which can be
                // too late to show or it might get displayed in a wrong
                // order in relation to other output. We also want the
                // output to ultimately show up in the Console View.
                OutputStream stream = null;
                RunConsole oldConsole = getConsole();
                final RunConsole rc = RunConsole.findConsole(containerId, consoleId);
                setConsole(rc);
                rc.clearConsole();
                if (oldConsole != null)
                    RunConsole.removeConsole(oldConsole);
                Display.getDefault().syncExec(() -> rc.setTitle(Messages.getFormattedString(LAUNCH_TITLE, new String[] { cmdList.get(0), imageName })));
                if (rc != null) {
                    stream = rc.getOutputStream();
                }
                // We want terminal support, but we want to output to the
                // RunConsole.
                // To do this, we create a DockerConsoleOutputStream which
                // we
                // hook into the TM Terminal via stdout and stderr output
                // listeners.
                // These listeners will output to the
                // DockerConsoleOutputStream which
                // will in turn output to the RunConsole. See
                // DockerConnection.openTerminal().
                DockerConsoleOutputStream out = new DockerConsoleOutputStream(stream);
                RunConsole.attachToTerminal(connection, containerId, out);
                if (containerListener != null) {
                    out.addConsoleListener(new RunConsoleListenerBridge(containerListener));
                }
                ((DockerConnection) connection).startContainer(containerId, null, null);
                IDockerContainerInfo info = ((DockerConnection) connection).getContainerInfo(containerId);
                if (containerListener != null) {
                    containerListener.containerInfo(info);
                }
                // Wait for the container to finish
                final IDockerContainerExit status = ((DockerConnection) connection).waitForContainer(containerId);
                Display.getDefault().syncExec(() -> {
                    rc.setTitle(Messages.getFormattedString(LAUNCH_EXITED_TITLE, new String[] { status.statusCode().toString(), cmdList.get(0), imageName }));
                    rc.showConsole();
                    // We used a TM Terminal to receive the output of the
                    // session and
                    // then sent the output to the RunConsole. Remove the
                    // terminal
                    // tab that got created now that we are finished and all
                    // data is shown
                    // in Console View.
                    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                    IViewPart terminalView = page.findView("org.eclipse.tm.terminal.view.ui.TerminalsView");
                    CTabFolder ctabfolder = terminalView.getAdapter(CTabFolder.class);
                    if (ctabfolder != null) {
                        CTabItem[] items = ctabfolder.getItems();
                        for (CTabItem item : items) {
                            if (item.getText().endsWith(info.name())) {
                                item.dispose();
                                break;
                            }
                        }
                    }
                });
                // finished
                if (containerListener != null)
                    containerListener.done();
                if (!keepContainer) {
                    ((DockerConnection) connection).removeContainer(containerId);
                }
            } else {
                OutputStream stream = null;
                RunConsole oldConsole = getConsole();
                final RunConsole rc = RunConsole.findConsole(containerId, consoleId);
                setConsole(rc);
                rc.clearConsole();
                if (oldConsole != null)
                    RunConsole.removeConsole(oldConsole);
                Display.getDefault().syncExec(() -> rc.setTitle(Messages.getFormattedString(LAUNCH_TITLE, new String[] { cmdList.get(0), imageName })));
                // if (!rc.isAttached()) {
                rc.attachToConsole(connection, containerId);
                // }
                if (rc != null) {
                    stream = rc.getOutputStream();
                    if (containerListener != null) {
                        ((ConsoleOutputStream) stream).addConsoleListener(containerListener);
                    }
                }
                // Create a unique logging thread id which has container id
                // and console id
                String loggingId = containerId + "." + consoleId;
                ((DockerConnection) connection).startContainer(containerId, loggingId, stream);
                if (rc != null)
                    rc.showConsole();
                if (containerListener != null) {
                    IDockerContainerInfo info = ((DockerConnection) connection).getContainerInfo(containerId);
                    containerListener.containerInfo(info);
                }
                // Wait for the container to finish
                final IDockerContainerExit status = ((DockerConnection) connection).waitForContainer(containerId);
                Display.getDefault().syncExec(() -> {
                    rc.setTitle(Messages.getFormattedString(LAUNCH_EXITED_TITLE, new String[] { status.statusCode().toString(), cmdList.get(0), imageName }));
                    rc.showConsole();
                });
                // finished
                if (containerListener != null)
                    containerListener.done();
                if (!keepContainer) {
                    // Drain the logging thread before we remove the
                    // container (we need to use the logging id)
                    Thread.sleep(1000);
                    ((DockerConnection) connection).stopLoggingThread(loggingId);
                    // Look for any Display Log console that the user may
                    // have opened which would be
                    // separate and make sure it is removed as well
                    RunConsole rc2 = RunConsole.findConsole(((DockerConnection) connection).getContainer(containerId));
                    if (rc2 != null)
                        RunConsole.removeConsole(rc2);
                    ((DockerConnection) connection).removeContainer(containerId);
                }
            }
        } catch (final DockerException e2) {
            // error in creation, try and remove Container if possible
            if (!keepContainer && containerId != null) {
                try {
                    ((DockerConnection) connection).removeContainer(containerId);
                } catch (DockerException | InterruptedException e1) {
                // ignore exception
                }
            }
            Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getFormattedString(ERROR_CREATING_CONTAINER, imageName), e2.getMessage()));
        } catch (InterruptedException e3) {
        // for now
        // do nothing
        }
        ((DockerConnection) connection).getContainers(true);
    });
    t.start();
}
Also used : IViewPart(org.eclipse.ui.IViewPart) CTabFolder(org.eclipse.swt.custom.CTabFolder) HashMap(java.util.HashMap) DockerConsoleOutputStream(org.eclipse.linuxtools.internal.docker.core.DockerConsoleOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) OutputStream(java.io.OutputStream) ConsoleOutputStream(org.eclipse.linuxtools.internal.docker.ui.consoles.ConsoleOutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) IDockerContainerExit(org.eclipse.linuxtools.docker.core.IDockerContainerExit) CTabItem(org.eclipse.swt.custom.CTabItem) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) DockerConnection(org.eclipse.linuxtools.internal.docker.core.DockerConnection) RunConsole(org.eclipse.linuxtools.internal.docker.ui.consoles.RunConsole) IDockerPortBinding(org.eclipse.linuxtools.docker.core.IDockerPortBinding) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) DockerHostConfig(org.eclipse.linuxtools.internal.docker.core.DockerHostConfig) DockerException(org.eclipse.linuxtools.docker.core.DockerException) IDockerPortBinding(org.eclipse.linuxtools.docker.core.IDockerPortBinding) DockerPortBinding(org.eclipse.linuxtools.internal.docker.core.DockerPortBinding) DockerConsoleOutputStream(org.eclipse.linuxtools.internal.docker.core.DockerConsoleOutputStream) ConsoleOutputStream(org.eclipse.linuxtools.internal.docker.ui.consoles.ConsoleOutputStream) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) IDockerContainerConfig(org.eclipse.linuxtools.docker.core.IDockerContainerConfig) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) IDockerContainerInfo(org.eclipse.linuxtools.docker.core.IDockerContainerInfo) Map(java.util.Map) HashMap(java.util.HashMap) DockerConsoleOutputStream(org.eclipse.linuxtools.internal.docker.core.DockerConsoleOutputStream)

Example 5 with DockerContainerConfig

use of org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig in project linuxtools by eclipse.

the class EditDockerConnectionSWTBotTest method configureRunImageLaunchConfiguration.

private String configureRunImageLaunchConfiguration(final IDockerConnection connection, final String networkMode) {
    final IDockerImage image = MockDockerImageFactory.name("images").connection(connection).build();
    final DockerContainerConfig containerConfig = MockDockerContainerConfigFactory.cmd("cmd").build();
    final IDockerHostConfig hostConfig = MockDockerHostConfigFactory.publishAllPorts(true).networkMode(networkMode).build();
    final ILaunchConfiguration runImageLaunchConfiguration = LaunchConfigurationUtils.createRunImageLaunchConfiguration(image, containerConfig, hostConfig, "some_container", false);
    return runImageLaunchConfiguration.getName();
}
Also used : ILaunchConfiguration(org.eclipse.debug.core.ILaunchConfiguration) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage)

Aggregations

DockerContainerConfig (org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig)7 IDockerHostConfig (org.eclipse.linuxtools.docker.core.IDockerHostConfig)5 ArrayList (java.util.ArrayList)4 IDockerContainerConfig (org.eclipse.linuxtools.docker.core.IDockerContainerConfig)4 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 IDockerImage (org.eclipse.linuxtools.docker.core.IDockerImage)3 DockerHostConfig (org.eclipse.linuxtools.internal.docker.core.DockerHostConfig)3 HashSet (java.util.HashSet)2 ILaunchConfiguration (org.eclipse.debug.core.ILaunchConfiguration)2 DockerException (org.eclipse.linuxtools.docker.core.DockerException)2 IDockerConnection (org.eclipse.linuxtools.docker.core.IDockerConnection)2 IDockerImageInfo (org.eclipse.linuxtools.docker.core.IDockerImageInfo)2 IDockerPortBinding (org.eclipse.linuxtools.docker.core.IDockerPortBinding)2 DataVolumeModel (org.eclipse.linuxtools.internal.docker.ui.wizards.DataVolumeModel)2 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 ObjectOutputStream (java.io.ObjectOutputStream)1 OutputStream (java.io.OutputStream)1