Search in sources :

Example 66 with IDockerConnection

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

the class DockerExplorerView method createConnectionsPane.

private Control createConnectionsPane(final PageBook pageBook, final FormToolkit toolkit) {
    final Form form = toolkit.createForm(pageBook);
    final Composite container = form.getBody();
    GridLayoutFactory.fillDefaults().numColumns(1).margins(5, 5).applyTo(container);
    this.search = new Text(container, SWT.SEARCH | SWT.ICON_SEARCH);
    GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(search);
    search.addModifyListener(onSearch());
    super.createPartControl(container);
    GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(getCommonViewer().getControl());
    if (DockerConnectionManager.getInstance().hasConnections()) {
        final IDockerConnection connection = DockerConnectionManager.getInstance().getFirstConnection();
        getCommonViewer().setSelection(new StructuredSelection(connection));
    }
    return form;
}
Also used : Composite(org.eclipse.swt.widgets.Composite) Form(org.eclipse.ui.forms.widgets.Form) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) Text(org.eclipse.swt.widgets.Text)

Example 67 with IDockerConnection

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

the class JavaImageTab method createControl.

@Override
public void createControl(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout(2, false);
    composite.setLayout(layout);
    composite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
    Label connLbl = new Label(composite, SWT.NONE);
    connLbl.setText(Messages.ImageSelectionDialog_connection_label);
    connCmb = new ComboViewer(composite, SWT.READ_ONLY);
    connCmb.getCombo().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
    connCmb.setContentProvider(new IStructuredContentProvider() {

        @Override
        public Object[] getElements(Object inputElement) {
            for (IDockerConnection conn : DockerConnectionManager.getInstance().getAllConnections()) {
                try {
                    ((DockerConnection) conn).open(false);
                } catch (DockerException e) {
                }
            }
            return DockerConnectionManager.getInstance().getAllConnections().stream().filter(c -> c.isOpen()).toArray(size -> new IDockerConnection[size]);
        }
    });
    // $NON-NLS-1$
    connCmb.setInput("place_holder");
    Label imageLbl = new Label(composite, SWT.NONE);
    imageLbl.setText(Messages.ImageSelectionDialog_image_label);
    imageCmb = new ComboViewer(composite, SWT.READ_ONLY);
    imageCmb.getCombo().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
    imageCmb.setContentProvider(new IStructuredContentProvider() {

        @Override
        public Object[] getElements(Object inputElement) {
            IDockerConnection conn = (IDockerConnection) inputElement;
            if (conn == null || conn.getImages() == null) {
                return new Object[0];
            } else {
                return conn.getImages().stream().filter(// $NON-NLS-1$
                i -> !i.repoTags().get(0).equals("<none>:<none>")).toArray(size -> new IDockerImage[size]);
            }
        }
    });
    imageCmb.setLabelProvider(new ColumnLabelProvider() {

        @Override
        public String getText(Object element) {
            IDockerImage img = (IDockerImage) element;
            return img.repoTags().get(0);
        }
    });
    imageCmb.setInput(null);
    connCmb.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = event.getStructuredSelection();
            IDockerConnection conn = (IDockerConnection) sel.getFirstElement();
            selectedConnection = conn;
            imageCmb.setInput(conn);
            updateLaunchConfigurationDialog();
        }
    });
    imageCmb.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = event.getStructuredSelection();
            IDockerImage img = (IDockerImage) sel.getFirstElement();
            selectedImage = img;
            updateLaunchConfigurationDialog();
        }
    });
    Group dirGroup = new Group(composite, SWT.NONE);
    dirGroup.setText(Messages.JavaImageTab_additional_dirs);
    dirGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
    dirGroup.setLayout(new GridLayout(2, false));
    directoryList = new List(dirGroup, SWT.SINGLE | SWT.V_SCROLL);
    directoryList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2));
    directoryList.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            removeButton.setEnabled(true);
        }
    });
    addButton = createPushButton(dirGroup, Messages.JavaImageTab_button_add, null);
    addButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
    addButton.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            DirectoryDialog dialog = new DirectoryDialog(getShell());
            String directory = dialog.open();
            if (directory != null && !listContains(directoryList, directory)) {
                directoryList.add(directory);
                updateLaunchConfigurationDialog();
            }
        }
    });
    removeButton = createPushButton(dirGroup, Messages.JavaImageTab_button_remove, null);
    removeButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true));
    removeButton.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            int i = directoryList.getSelectionIndex();
            if (i >= 0) {
                directoryList.remove(i);
                updateLaunchConfigurationDialog();
            }
            if (directoryList.getItemCount() == 0) {
                removeButton.setEnabled(false);
            }
        }
    });
    removeButton.setEnabled(false);
    setControl(composite);
}
Also used : DockerException(org.eclipse.linuxtools.docker.core.DockerException) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) Arrays(java.util.Arrays) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) CoreException(org.eclipse.core.runtime.CoreException) ComboViewer(org.eclipse.jface.viewers.ComboViewer) ILaunchConfiguration(org.eclipse.debug.core.ILaunchConfiguration) AbstractLaunchConfigurationTab(org.eclipse.debug.ui.AbstractLaunchConfigurationTab) Composite(org.eclipse.swt.widgets.Composite) IStructuredContentProvider(org.eclipse.jface.viewers.IStructuredContentProvider) DockerException(org.eclipse.linuxtools.docker.core.DockerException) GridData(org.eclipse.swt.layout.GridData) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Button(org.eclipse.swt.widgets.Button) DockerConnectionManager(org.eclipse.linuxtools.docker.core.DockerConnectionManager) ILaunchConfigurationWorkingCopy(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) ColumnLabelProvider(org.eclipse.jface.viewers.ColumnLabelProvider) Group(org.eclipse.swt.widgets.Group) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) DockerConnection(org.eclipse.linuxtools.internal.docker.core.DockerConnection) SWT(org.eclipse.swt.SWT) DirectoryDialog(org.eclipse.swt.widgets.DirectoryDialog) List(org.eclipse.swt.widgets.List) SelectionEvent(org.eclipse.swt.events.SelectionEvent) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) Label(org.eclipse.swt.widgets.Label) GridLayout(org.eclipse.swt.layout.GridLayout) Group(org.eclipse.swt.widgets.Group) Composite(org.eclipse.swt.widgets.Composite) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Label(org.eclipse.swt.widgets.Label) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) ColumnLabelProvider(org.eclipse.jface.viewers.ColumnLabelProvider) GridLayout(org.eclipse.swt.layout.GridLayout) ComboViewer(org.eclipse.jface.viewers.ComboViewer) GridData(org.eclipse.swt.layout.GridData) IStructuredContentProvider(org.eclipse.jface.viewers.IStructuredContentProvider) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) SelectionEvent(org.eclipse.swt.events.SelectionEvent) List(org.eclipse.swt.widgets.List) IDockerImage(org.eclipse.linuxtools.docker.core.IDockerImage) DirectoryDialog(org.eclipse.swt.widgets.DirectoryDialog)

Example 68 with IDockerConnection

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

the class EditDockerConnection method performFinish.

@Override
public boolean performFinish() {
    final IDockerConnection updatedConnection = wizardPage.getDockerConnection();
    DockerConnectionManager.getInstance().updateConnection(this.currentConnection, updatedConnection.getName(), updatedConnection.getSettings());
    return true;
}
Also used : IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection)

Example 69 with IDockerConnection

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

the class ImageRunSelectionPage method pullSelectedImage.

private void pullSelectedImage() {
    try {
        getContainer().run(true, true, monitor -> {
            final IDockerConnection connection = model.getSelectedConnection();
            final String imageName = model.getSelectedImageName();
            monitor.beginTask(WizardMessages.getFormattedString("ImageRunSelectionPage.pullingTask", // $NON-NLS-1$
            imageName), 1);
            try {
                connection.pullImage(imageName, new DefaultImagePullProgressHandler(connection, imageName));
            } catch (final DockerException e) {
                Display.getDefault().syncExec(() -> MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), DVMessages.getFormattedString(ERROR_PULLING_IMAGE, imageName), e.getMessage()));
            } finally {
                monitor.done();
                // refresh the widgets
                model.refreshImageNames();
                if (model.getImageNames().contains(imageName)) {
                    model.setSelectedImageName(imageName);
                    model.setSelectedImageNeedsPulling(false);
                    // Force revalidation by changing writeValue which
                    // is made to be a dependency of the ImageCombo
                    // MultiValidator.
                    Display.getDefault().syncExec(() -> {
                        writeValue.setValue(Long.toString(System.currentTimeMillis()));
                    });
                }
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        Activator.log(e);
    }
}
Also used : DockerException(org.eclipse.linuxtools.docker.core.DockerException) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) DefaultImagePullProgressHandler(org.eclipse.linuxtools.internal.docker.core.DefaultImagePullProgressHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 70 with IDockerConnection

use of org.eclipse.linuxtools.docker.core.IDockerConnection 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)

Aggregations

IDockerConnection (org.eclipse.linuxtools.docker.core.IDockerConnection)90 DockerException (org.eclipse.linuxtools.docker.core.DockerException)24 DockerConnection (org.eclipse.linuxtools.internal.docker.core.DockerConnection)20 Job (org.eclipse.core.runtime.jobs.Job)17 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)16 IDockerImage (org.eclipse.linuxtools.docker.core.IDockerImage)15 Test (org.junit.Test)15 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)12 SWTBotTreeItem (org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem)9 File (java.io.File)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 IDockerContainer (org.eclipse.linuxtools.docker.core.IDockerContainer)8 IPath (org.eclipse.core.runtime.IPath)7 ITreeSelection (org.eclipse.jface.viewers.ITreeSelection)7 List (java.util.List)5 IDockerConnectionStorageManager (org.eclipse.linuxtools.docker.core.IDockerConnectionStorageManager)5 RunConsole (org.eclipse.linuxtools.internal.docker.ui.consoles.RunConsole)5 DockerClient (com.spotify.docker.client.DockerClient)4 HashMap (java.util.HashMap)4