use of org.eclipse.linuxtools.docker.core.IDockerHostConfig in project linuxtools by eclipse.
the class ImageRunSWTBotTest 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();
}
use of org.eclipse.linuxtools.docker.core.IDockerHostConfig in project linuxtools by eclipse.
the class DockerExplorerContentProvider method getChildren.
@Override
public Object[] getChildren(final Object parentElement) {
if (parentElement instanceof IDockerConnection) {
// check the connection availability before returning the
// 'containers' and 'images' child nodes.
final IDockerConnection connection = (IDockerConnection) parentElement;
if (connection.isOpen()) {
return new Object[] { new DockerImagesCategory(connection), new DockerContainersCategory(connection) };
} else if (connection.getState() == EnumDockerConnectionState.UNKNOWN) {
open(connection);
return new Object[] { new LoadingStub(connection) };
} else if (connection.getState() == EnumDockerConnectionState.CLOSED) {
synchronized (openRetryJobs) {
Job job = openRetryJobs.get(connection);
if (job == null) {
openRetry(connection);
}
}
return new Object[] { new LoadingStub(connection) };
}
return new Object[0];
} else if (parentElement instanceof DockerContainersCategory) {
final DockerContainersCategory containersCategory = (DockerContainersCategory) parentElement;
final IDockerConnection connection = containersCategory.getConnection();
if (connection.isContainersLoaded()) {
return connection.getContainers().toArray();
}
loadContainers(containersCategory);
return new Object[] { new LoadingStub(containersCategory) };
} else if (parentElement instanceof DockerImagesCategory) {
final DockerImagesCategory imagesCategory = (DockerImagesCategory) parentElement;
final IDockerConnection connection = imagesCategory.getConnection();
if (connection.isImagesLoaded()) {
// here we duplicate the images to show one org/repo with all
// its tags per node in the tree
final List<IDockerImage> allImages = connection.getImages();
final List<IDockerImage> explorerImages = splitImageTagsByRepo(allImages);
return explorerImages.toArray();
}
loadImages(imagesCategory);
return new Object[] { new LoadingStub(imagesCategory) };
} else if (parentElement instanceof IDockerContainer) {
final DockerContainer container = (DockerContainer) parentElement;
if (container.isInfoLoaded()) {
final IDockerContainerInfo info = container.info();
final IDockerNetworkSettings networkSettings = (info != null) ? info.networkSettings() : null;
final IDockerHostConfig hostConfig = (info != null) ? info.hostConfig() : null;
return new Object[] { new DockerContainerPortMappingsCategory(container, (networkSettings != null) ? networkSettings.ports() : Collections.<String, List<IDockerPortBinding>>emptyMap()), new DockerContainerVolumesCategory(container, (hostConfig != null) ? hostConfig.binds() : Collections.<String>emptyList()), new DockerContainerLinksCategory(container, (hostConfig != null) ? hostConfig.links() : Collections.<String>emptyList()) };
}
loadContainerInfo(container);
return new Object[] { new LoadingStub(container) };
} else if (parentElement instanceof DockerContainerLinksCategory) {
final DockerContainerLinksCategory linksCategory = (DockerContainerLinksCategory) parentElement;
return linksCategory.getLinks().toArray();
} else if (parentElement instanceof DockerContainerPortMappingsCategory) {
final DockerContainerPortMappingsCategory portMappingsCategory = (DockerContainerPortMappingsCategory) parentElement;
return portMappingsCategory.getPortMappings().toArray();
} else if (parentElement instanceof DockerContainerVolumesCategory) {
final DockerContainerVolumesCategory volumesCategory = (DockerContainerVolumesCategory) parentElement;
return volumesCategory.getVolumes().toArray();
}
return EMPTY;
}
use of org.eclipse.linuxtools.docker.core.IDockerHostConfig in project linuxtools by eclipse.
the class ImageRun method getDockerHostConfig.
public IDockerHostConfig getDockerHostConfig() {
final ImageRunSelectionModel selectionModel = this.imageRunSelectionPage.getModel();
final ImageRunResourceVolumesVariablesModel resourcesModel = this.imageRunResourceVolumesPage.getModel();
final ImageRunNetworkModel networkModel = this.imageRunNetworkPage.getModel();
final DockerHostConfig.Builder hostConfigBuilder = new DockerHostConfig.Builder();
if (selectionModel.isPublishAllPorts()) {
hostConfigBuilder.publishAllPorts(true);
} else {
final Map<String, List<IDockerPortBinding>> portBindings = new HashMap<>();
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;
}
final DockerPortBinding portBinding = new DockerPortBinding(exposedPort.getHostAddress(), exposedPort.getHostPort());
portBindings.put(exposedPort.getContainerPort() + exposedPort.getPortType(), Arrays.<IDockerPortBinding>asList(portBinding));
}
hostConfigBuilder.portBindings(portBindings);
}
// container links
final List<String> links = new ArrayList<>();
for (Iterator<ContainerLinkModel> iterator = selectionModel.getLinks().iterator(); iterator.hasNext(); ) {
final ContainerLinkModel link = iterator.next();
links.add(link.getContainerName() + ':' + link.getContainerAlias());
}
hostConfigBuilder.links(links);
// data volumes
final List<String> volumesFrom = new ArrayList<>();
final List<String> binds = new ArrayList<>();
for (Iterator<DataVolumeModel> iterator = resourcesModel.getDataVolumes().iterator(); iterator.hasNext(); ) {
final DataVolumeModel dataVolume = iterator.next();
// included.
if (!resourcesModel.getSelectedDataVolumes().contains(dataVolume)) {
continue;
}
switch(dataVolume.getMountType()) {
case HOST_FILE_SYSTEM:
String bind = LaunchConfigurationUtils.convertToUnixPath(dataVolume.getHostPathMount()) + ':' + dataVolume.getContainerPath() + // $NON-NLS-1$ //$NON-NLS-2$
":Z";
if (dataVolume.isReadOnly()) {
// $NON-NLS-1$
bind += ",ro";
}
binds.add(bind);
break;
case CONTAINER:
volumesFrom.add(dataVolume.getContainerMount());
break;
default:
break;
}
}
hostConfigBuilder.binds(binds);
hostConfigBuilder.volumesFrom(volumesFrom);
hostConfigBuilder.privileged(selectionModel.isPrivileged());
// make /tmp and /run use tmpfs, and drop all capabilities
if (selectionModel.isBasicSecurity()) {
hostConfigBuilder.readonlyRootfs(true);
Map<String, String> tmpfsValues = new HashMap<>();
// $NON-NLS-1$ //$NON-NLS-2$
tmpfsValues.put("/run", "rw,exec");
// $NON-NLS-1$ //$NON-NLS-2$
tmpfsValues.put("/tmp", "rw,exec");
hostConfigBuilder.tmpfs(tmpfsValues);
List<String> capDropList = new ArrayList<>();
// $NON-NLS-1$
capDropList.add("all");
hostConfigBuilder.capDrop(capDropList);
}
if (selectionModel.isUnconfined()) {
List<String> seccomp = new ArrayList<>();
// $NON-NLS-1$
seccomp.add("seccomp:unconfined");
hostConfigBuilder.securityOpt(seccomp);
}
String networkMode = networkModel.getNetworkModeString();
// if network mode is not default, set it in host config
if (networkMode != null && !networkMode.equals(ImageRunNetworkModel.DEFAULT_MODE))
hostConfigBuilder.networkMode(networkMode);
// memory constraints (in bytes)
if (resourcesModel.isEnableResourceLimitations()) {
hostConfigBuilder.memory(resourcesModel.getMemoryLimit() * MB);
hostConfigBuilder.cpuShares(resourcesModel.getCpuShareWeight());
}
return hostConfigBuilder.build();
}
use of org.eclipse.linuxtools.docker.core.IDockerHostConfig 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);
}
use of org.eclipse.linuxtools.docker.core.IDockerHostConfig in project linuxtools by eclipse.
the class RunImageCommandHandler method execute.
@Override
public Object execute(final ExecutionEvent event) {
final IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
final IDockerImage selectedImage = CommandUtils.getSelectedImage(activePart);
if (selectedImage == null) {
Activator.log(new DockerException(// $NON-NLS-1$
DVMessages.getString("RunImageUnableToRetrieveError.msg")));
} else {
try {
final ImageRun wizard = new ImageRun(selectedImage);
final boolean runImage = CommandUtils.openWizard(wizard, HandlerUtil.getActiveShell(event));
if (runImage) {
final IDockerContainerConfig containerConfig = wizard.getDockerContainerConfig();
final IDockerHostConfig hostConfig = wizard.getDockerHostConfig();
runImage(selectedImage, containerConfig, hostConfig, wizard.getDockerContainerName(), wizard.removeWhenExits());
}
} catch (DockerException | CoreException e) {
Activator.log(e);
}
}
return null;
}
Aggregations