Search in sources :

Example 31 with IDockerImage

use of org.eclipse.linuxtools.docker.core.IDockerImage in project linuxtools by eclipse.

the class JavaImageTab method initializeFrom.

@Override
public void initializeFrom(ILaunchConfiguration configuration) {
    try {
        DockerConnection conn;
        String connUri = configuration.getAttribute(JavaLaunchConfigurationConstants.CONNECTION_URI, (String) null);
        if (connUri != null) {
            connCmb.getCombo().setText(connUri);
            conn = (DockerConnection) DockerConnectionManager.getInstance().getConnectionByUri(connUri);
            String imageId = configuration.getAttribute(JavaLaunchConfigurationConstants.IMAGE_ID, (String) null);
            if (imageId != null && conn != null) {
                selectedConnection = conn;
                // generate known images for given connection
                imageCmb.setInput(conn);
                IDockerImage img = conn.getImage(imageId);
                if (img != null) {
                    String repoTag = img.repoTags().get(0);
                    imageCmb.getCombo().setText(repoTag);
                    selectedImage = img;
                }
            }
        }
        java.util.List<String> dirs = configuration.getAttribute(JavaLaunchConfigurationConstants.DIRS, Arrays.asList(new String[0]));
        directoryList.setItems(dirs.toArray(new String[0]));
    } catch (CoreException e) {
    }
}
Also used : IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) DockerConnection(org.eclipse.linuxtools.internal.docker.core.DockerConnection) CoreException(org.eclipse.core.runtime.CoreException) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage)

Example 32 with IDockerImage

use of org.eclipse.linuxtools.docker.core.IDockerImage in project linuxtools by eclipse.

the class ImageRunResourceVolumesVariablesPage method setDefaultValues.

private void setDefaultValues() {
    try {
        // skip if a previous launch configuration was provided
        final IDockerImage selectedImage = model.getSelectedImage();
        if (selectedImage == null) {
            return;
        }
        final IDockerImageInfo selectedImageInfo = findImageInfo(selectedImage);
        // using a map filled with entries (key==value) from default volumes
        // that can be overridden by values from last launch config
        final Map<String, DataVolumeModel> volumes = new HashMap<>();
        final Set<DataVolumeModel> selectedVolumes = new HashSet<>();
        if (selectedImageInfo != null && selectedImageInfo.config() != null) {
            for (String volume : selectedImageInfo.config().volumes().keySet()) {
                volumes.put(volume, new DataVolumeModel(volume));
            }
        }
        if (lastLaunchConfiguration != null) {
            // volumes:
            final List<String> launchConfigVolumes = lastLaunchConfiguration.getAttribute(DATA_VOLUMES, Collections.<String>emptyList());
            for (String containerVolume : launchConfigVolumes) {
                final DataVolumeModel volume = DataVolumeModel.parseString(containerVolume);
                if (volume != null) {
                    volumes.put(volume.getContainerPath(), volume);
                    selectedVolumes.add(volume);
                }
            }
            // environment variables
            model.setEnvironmentVariables(lastLaunchConfiguration.getAttribute(ENV_VARIABLES, Collections.<String>emptyList()));
            // labels
            Map<String, String> labels = lastLaunchConfiguration.getAttribute(LABELS, (Map<String, String>) null);
            if (labels != null) {
                model.setLabelVariables(labels);
            }
            // resource limitations
            model.setEnableResourceLimitations(lastLaunchConfiguration.getAttribute(ENABLE_LIMITS, false));
            // CPU shares
            model.setCpuShareWeight(Long.parseLong(lastLaunchConfiguration.getAttribute(CPU_PRIORITY, Long.toString(ImageRunResourceVolumesVariablesModel.CPU_MEDIUM))));
            // retrieve memory limit stored in MB
            final long memoryLimit = Long.parseLong(lastLaunchConfiguration.getAttribute(MEMORY_LIMIT, Long.toString(ImageRunResourceVolumesVariablesModel.DEFAULT_MEMORY)));
            // make sure memory limit is not higher than maxMemory
            model.setMemoryLimit(Math.min(model.getTotalMemory(), memoryLimit));
        }
        model.setDataVolumes(volumes.values());
        model.setSelectedDataVolumes(selectedVolumes);
    } catch (CoreException | InvocationTargetException | InterruptedException e) {
        Activator.log(e);
    }
}
Also used : HashMap(java.util.HashMap) InvocationTargetException(java.lang.reflect.InvocationTargetException) CoreException(org.eclipse.core.runtime.CoreException) IDockerImageInfo(org.eclipse.linuxtools.docker.core.IDockerImageInfo) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) HashSet(java.util.HashSet)

Example 33 with IDockerImage

use of org.eclipse.linuxtools.docker.core.IDockerImage in project linuxtools by eclipse.

the class ContainerLauncher method runCommand.

/**
 * Create a Process to run an arbitrary command in a Container with uid of
 * caller so any files created are accessible to user.
 *
 * @param connectionName
 *            - uri of connection to use
 * @param imageName
 *            - name of image to use
 * @param project
 *            - Eclipse project
 * @param errMsgHolder
 *            - holder for any error messages
 * @param cmdList
 *            - command to run as list of String
 * @param workingDir
 *            - where to run command
 * @param additionalDirs
 *            - additional directories to mount
 * @param origEnv
 *            - original environment if we are appending to existing
 * @param envMap
 *            - new environment
 * @param supportStdin
 *            - support using stdin
 * @param privilegedMode
 *            - run in privileged mode
 * @param labels
 *            - labels to apply to Container
 * @param keepContainer
 *            - boolean whether to keep Container when done
 * @return Process that can be used to check for completion and for routing
 *         stdout/stderr
 *
 * @since 4.0
 */
public Process runCommand(String connectionName, String imageName, IProject project, IErrorMessageHolder errMsgHolder, List<String> cmdList, String workingDir, List<String> additionalDirs, Map<String, String> origEnv, Properties envMap, boolean supportStdin, boolean privilegedMode, HashMap<String, String> labels, boolean keepContainer) {
    Integer uid = null;
    Integer gid = null;
    // For Unix, make sure that the user id is passed with the run
    // so any output files are accessible by this end-user
    // $NON-NLS-1$
    String os = System.getProperty("os.name");
    if (os.indexOf("nux") > 0) {
        // $NON-NLS-1$
        // first try and see if we have already run a command on this
        // project
        ID ugid = fidMap.get(project);
        if (ugid == null) {
            try {
                uid = (Integer) Files.getAttribute(project.getLocation().toFile().toPath(), // $NON-NLS-1$
                "unix:uid");
                gid = (Integer) Files.getAttribute(project.getLocation().toFile().toPath(), // $NON-NLS-1$
                "unix:gid");
                ugid = new ID(uid, gid);
                // store the uid for possible later usage
                fidMap.put(project, ugid);
            } catch (IOException e) {
            // do nothing...leave as null
            }
        // $NON-NLS-1$
        } else {
            uid = ugid.getuid();
            gid = ugid.getgid();
        }
    }
    final List<String> env = new ArrayList<>();
    env.addAll(toList(origEnv));
    env.addAll(toList(envMap));
    final Map<String, List<IDockerPortBinding>> portBindingsMap = new HashMap<>();
    IDockerConnection[] connections = DockerConnectionManager.getInstance().getConnections();
    if (connections == null || connections.length == 0) {
        errMsgHolder.setErrorMessage(// $NON-NLS-1$
        Messages.getString("ContainerLaunch.noConnections.error"));
        return null;
    }
    IDockerConnection connection = null;
    for (IDockerConnection c : connections) {
        if (c.getUri().equals(connectionName)) {
            connection = c;
            break;
        }
    }
    if (connection == null) {
        errMsgHolder.setErrorMessage(Messages.getFormattedString(// $NON-NLS-1$
        "ContainerLaunch.connectionNotFound.error", connectionName));
        return null;
    }
    List<IDockerImage> images = connection.getImages();
    if (images.isEmpty()) {
        errMsgHolder.setErrorMessage(// $NON-NLS-1$
        Messages.getString("ContainerLaunch.noImages.error"));
        return null;
    }
    IDockerImageInfo info = connection.getImageInfo(imageName);
    if (info == null) {
        errMsgHolder.setErrorMessage(Messages.getFormattedString("ContainerLaunch.imageNotFound.error", // $NON-NLS-1$
        imageName));
        return null;
    }
    DockerContainerConfig.Builder builder = new DockerContainerConfig.Builder().openStdin(supportStdin).cmd(cmdList).image(imageName).workingDir(workingDir);
    // switch to user id for Linux so output is accessible
    if (uid != null) {
        builder = builder.user(uid.toString());
    }
    // add any labels if specified
    if (labels != null)
        builder = builder.labels(labels);
    DockerHostConfig.Builder hostBuilder = new DockerHostConfig.Builder().privileged(privilegedMode);
    // Note we only pass volumes to the config if we have a
    // remote daemon. Local mounted volumes are passed
    // via the HostConfig binds setting
    @SuppressWarnings("rawtypes") final Map<String, Map> remoteVolumes = new HashMap<>();
    final Map<String, String> remoteDataVolumes = new HashMap<>();
    final Set<String> readOnlyVolumes = new TreeSet<>();
    if (!((DockerConnection) connection).isLocal()) {
        // the host data over before starting.
        if (additionalDirs != null) {
            for (String dir : additionalDirs) {
                IPath p = new Path(dir).removeTrailingSeparator();
                remoteVolumes.put(p.toPortableString(), new HashMap<>());
                remoteDataVolumes.put(p.toPortableString(), p.toPortableString());
                if (dir.contains(":")) {
                    // $NON-NLS-1$
                    DataVolumeModel dvm = DataVolumeModel.parseString(dir);
                    switch(dvm.getMountType()) {
                        case HOST_FILE_SYSTEM:
                            dir = dvm.getHostPathMount();
                            remoteDataVolumes.put(dir, dvm.getContainerMount());
                            // back after command completion
                            if (dvm.isReadOnly()) {
                                readOnlyVolumes.add(dir);
                            }
                            break;
                        default:
                            continue;
                    }
                }
            }
        }
        if (workingDir != null) {
            IPath p = new Path(workingDir).removeTrailingSeparator();
            remoteVolumes.put(p.toPortableString(), new HashMap<>());
            remoteDataVolumes.put(p.toPortableString(), p.toPortableString());
        }
        builder = builder.volumes(remoteVolumes);
    } 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 Set<String> volumes = new TreeSet<>();
        final List<String> volumesFrom = new ArrayList<>();
        if (additionalDirs != null) {
            for (String dir : additionalDirs) {
                IPath p = new Path(dir).removeTrailingSeparator();
                if (dir.contains(":")) {
                    // $NON-NLS-1$
                    DataVolumeModel dvm = DataVolumeModel.parseString(dir);
                    switch(dvm.getMountType()) {
                        case HOST_FILE_SYSTEM:
                            String bind = LaunchConfigurationUtils.convertToUnixPath(dvm.getHostPathMount()) + ':' + dvm.getContainerPath() + // $NON-NLS-1$ //$NON-NLS-2$
                            ":Z";
                            if (dvm.isReadOnly()) {
                                // $NON-NLS-1$
                                bind += ",ro";
                            }
                            volumes.add(bind);
                            break;
                        case CONTAINER:
                            volumesFrom.add(dvm.getContainerMount());
                            break;
                        default:
                            break;
                    }
                } else {
                    volumes.add(// $NON-NLS-1$
                    p.toPortableString() + ":" + p.toPortableString() + // $NON-NLS-1$
                    ":Z");
                }
            }
        }
        if (workingDir != null) {
            IPath p = new Path(workingDir).removeTrailingSeparator();
            volumes.add(// $NON-NLS-1$
            p.toPortableString() + ":" + p.toPortableString() + // $NON-NLS-1$
            ":Z");
        }
        List<String> volumeList = new ArrayList<>(volumes);
        hostBuilder = hostBuilder.binds(volumeList);
        if (!volumesFrom.isEmpty()) {
            hostBuilder = hostBuilder.volumesFrom(volumesFrom);
        }
    }
    final DockerContainerConfig config = builder.build();
    // add any port bindings if specified
    if (portBindingsMap.size() > 0)
        hostBuilder = hostBuilder.portBindings(portBindingsMap);
    final IDockerHostConfig hostConfig = hostBuilder.build();
    // create the container
    String containerId = null;
    try {
        containerId = ((DockerConnection) connection).createContainer(config, hostConfig, null);
    } catch (DockerException | InterruptedException e) {
        errMsgHolder.setErrorMessage(e.getMessage());
        return null;
    }
    final String id = containerId;
    final IDockerConnection conn = connection;
    if (!((DockerConnection) conn).isLocal()) {
        // data over from the host.
        if (!remoteVolumes.isEmpty()) {
            CopyVolumesJob job = new CopyVolumesJob(remoteDataVolumes, conn, id);
            job.schedule();
            try {
                job.join();
            } catch (InterruptedException e) {
            // ignore
            }
        }
    }
    // volumes so they won't be copied back on command completion
    for (String readonly : readOnlyVolumes) {
        remoteDataVolumes.remove(readonly);
    }
    return new ContainerCommandProcess(connection, imageName, containerId, remoteDataVolumes, keepContainer);
}
Also used : DataVolumeModel(org.eclipse.linuxtools.internal.docker.ui.wizards.DataVolumeModel) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) TreeSet(java.util.TreeSet) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) List(java.util.List) ArrayList(java.util.ArrayList) IDockerImageInfo(org.eclipse.linuxtools.docker.core.IDockerImageInfo) ContainerCommandProcess(org.eclipse.linuxtools.internal.docker.ui.launch.ContainerCommandProcess) IDockerHostConfig(org.eclipse.linuxtools.docker.core.IDockerHostConfig) DockerHostConfig(org.eclipse.linuxtools.internal.docker.core.DockerHostConfig) IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) DockerException(org.eclipse.linuxtools.docker.core.DockerException) IPath(org.eclipse.core.runtime.IPath) IOException(java.io.IOException) DockerContainerConfig(org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig) IDockerContainerConfig(org.eclipse.linuxtools.docker.core.IDockerContainerConfig) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) Map(java.util.Map) HashMap(java.util.HashMap)

Example 34 with IDockerImage

use of org.eclipse.linuxtools.docker.core.IDockerImage in project linuxtools by eclipse.

the class BaseImagesCommandHandler method execute.

@Override
public Object execute(ExecutionEvent event) {
    final IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
    final List<IDockerImage> selectedImages = getSelectedImages(activePart);
    final IDockerConnection connection = getCurrentConnection(activePart);
    if (connection == null || selectedImages.isEmpty()) {
        Activator.log(new DockerException(CommandMessages.getString(// $NON-NLS-1$
        "Command.missing.selection.failure")));
        return null;
    }
    final Job job = new Job(getJobName(selectedImages)) {

        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            if (confirmed(selectedImages)) {
                monitor.beginTask(getJobName(selectedImages), selectedImages.size());
                for (final IDockerImage image : selectedImages) {
                    monitor.setTaskName(getTaskName(image));
                    executeInJob(image, connection);
                    monitor.worked(1);
                }
            }
            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.setPriority(Job.LONG);
    job.setUser(true);
    job.schedule();
    return null;
}
Also used : DockerException(org.eclipse.linuxtools.docker.core.DockerException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) Job(org.eclipse.core.runtime.jobs.Job)

Example 35 with IDockerImage

use of org.eclipse.linuxtools.docker.core.IDockerImage in project linuxtools by eclipse.

the class PushImageCommandHandler method performPushImage.

private void performPushImage(final ImagePush wizard, final IDockerConnection connection) {
    if (connection == null) {
        Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getFormattedString(ERROR_PUSHING_IMAGE, wizard.getSelectedImageTag()), DVMessages.getFormattedString(NO_CONNECTION)));
        return;
    }
    final Job pushImageJob = new Job(DVMessages.getFormattedString(PUSH_IMAGE_JOB_TITLE, wizard.getSelectedImageTag())) {

        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            final IDockerImage image = wizard.getImage();
            final String defaultImageNameTag = wizard.getDefaultImageName();
            final String selectedImageNameTag = wizard.getSelectedImageTag();
            // TODO: remove cast once AbstractRegistry methods are
            // part of the IRegistry interface
            final AbstractRegistry registry = (AbstractRegistry) wizard.getRegistry();
            final boolean forceTagging = wizard.isForceTagging();
            final boolean keepTaggedImage = wizard.isKeepTaggedImage();
            monitor.beginTask(DVMessages.getString(PUSH_IMAGE_JOB_TASK), IProgressMonitor.UNKNOWN);
            // push the image and let the progress
            // handler refresh the images when done
            final String tmpRegistryTag = getNameToTag(selectedImageNameTag, registry);
            boolean tagCreated = false;
            try {
                // selected)
                if (!image.repoTags().contains(tmpRegistryTag) || forceTagging) {
                    // TODO: remove cast to DockerConnection once the
                    // 'tagImage' is added in the public API
                    ((DockerConnection) connection).tagImage(defaultImageNameTag, tmpRegistryTag, forceTagging);
                    tagCreated = true;
                }
                // push image
                if (!registry.isAuthProvided()) {
                    connection.pushImage(tmpRegistryTag, new DefaultImagePushProgressHandler(connection, tmpRegistryTag));
                } else {
                    final IRegistryAccount registryAccount = (IRegistryAccount) registry;
                    connection.pushImage(tmpRegistryTag, registryAccount, new DefaultImagePushProgressHandler(connection, tmpRegistryTag));
                }
            } catch (final DockerException e) {
                Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getFormattedString(ERROR_PUSHING_IMAGE, defaultImageNameTag), e.getMessage()));
                Activator.logErrorMessage(DVMessages.getFormattedString(ERROR_PUSHING_IMAGE, defaultImageNameTag), e);
            // for now
            } catch (InterruptedException e) {
            // do nothing
            } finally {
                if (tagCreated && !keepTaggedImage) {
                    try {
                        connection.removeTag(tmpRegistryTag);
                        connection.getImages(true);
                    } catch (Exception e) {
                    // do nothing
                    }
                }
                monitor.done();
            }
            return Status.OK_STATUS;
        }
    };
    pushImageJob.schedule();
}
Also used : IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) DockerConnection(org.eclipse.linuxtools.internal.docker.core.DockerConnection) DockerException(org.eclipse.linuxtools.docker.core.DockerException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) AbstractRegistry(org.eclipse.linuxtools.docker.core.AbstractRegistry) DefaultImagePushProgressHandler(org.eclipse.linuxtools.internal.docker.core.DefaultImagePushProgressHandler) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) IRegistryAccount(org.eclipse.linuxtools.docker.core.IRegistryAccount) Job(org.eclipse.core.runtime.jobs.Job) DockerException(org.eclipse.linuxtools.docker.core.DockerException)

Aggregations

IDockerImage (org.eclipse.linuxtools.docker.core.IDockerImage)41 IDockerConnection (org.eclipse.linuxtools.docker.core.IDockerConnection)16 DockerException (org.eclipse.linuxtools.docker.core.DockerException)10 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)8 IDockerImageHierarchyNode (org.eclipse.linuxtools.docker.core.IDockerImageHierarchyNode)7 List (java.util.List)6 CoreException (org.eclipse.core.runtime.CoreException)6 IDockerHostConfig (org.eclipse.linuxtools.docker.core.IDockerHostConfig)6 ILaunchConfiguration (org.eclipse.debug.core.ILaunchConfiguration)5 IDockerContainer (org.eclipse.linuxtools.docker.core.IDockerContainer)5 DockerConnection (org.eclipse.linuxtools.internal.docker.core.DockerConnection)5 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)5 HashMap (java.util.HashMap)4 Map (java.util.Map)3 Job (org.eclipse.core.runtime.jobs.Job)3 ColumnLabelProvider (org.eclipse.jface.viewers.ColumnLabelProvider)3 IDockerContainerConfig (org.eclipse.linuxtools.docker.core.IDockerContainerConfig)3 IDockerImageInfo (org.eclipse.linuxtools.docker.core.IDockerImageInfo)3 DockerContainerConfig (org.eclipse.linuxtools.internal.docker.core.DockerContainerConfig)3