Search in sources :

Example 1 with Container

use of io.fabric8.maven.docker.model.Container in project che by eclipse.

the class OpenShiftConnector method createContainer.

/**
     * @param createContainerParams
     * @return
     * @throws IOException
     */
@Override
public ContainerCreated createContainer(CreateContainerParams createContainerParams) throws IOException {
    String containerName = KubernetesStringUtils.convertToContainerName(createContainerParams.getContainerName());
    String workspaceID = getCheWorkspaceId(createContainerParams);
    // Generate workspaceID if CHE_WORKSPACE_ID env var does not exist
    workspaceID = workspaceID.isEmpty() ? KubernetesStringUtils.generateWorkspaceID() : workspaceID;
    // imageForDocker is the docker version of the image repository. It's needed for other
    // OpenShiftConnector API methods, but is not acceptable as an OpenShift name
    String imageForDocker = createContainerParams.getContainerConfig().getImage();
    // imageStreamTagName is imageForDocker converted into a form that can be used
    // in OpenShift
    String imageStreamTagName = KubernetesStringUtils.convertPullSpecToTagName(imageForDocker);
    // imageStreamTagName is not enough to fill out a pull spec; it is only the tag, so we
    // have to get the ImageStreamTag from the tag, and then get the full ImageStreamTag name
    // from that tag. This works because the tags used in Che are unique.
    ImageStreamTag imageStreamTag = getImageStreamTagFromRepo(imageStreamTagName);
    String imageStreamTagPullSpec = imageStreamTag.getMetadata().getName();
    // Next we need to get the address of the registry where the ImageStreamTag is stored
    String imageStreamName = KubernetesStringUtils.getImageStreamNameFromPullSpec(imageStreamTagPullSpec);
    ImageStream imageStream = openShiftClient.imageStreams().inNamespace(openShiftCheProjectName).withName(imageStreamName).get();
    if (imageStream == null) {
        throw new OpenShiftException("ImageStream not found");
    }
    String registryAddress = imageStream.getStatus().getDockerImageRepository().split("/")[0];
    // The above needs to be combined to form a pull spec that will work when defining a container.
    String dockerPullSpec = String.format("%s/%s/%s", registryAddress, openShiftCheProjectName, imageStreamTagPullSpec);
    Set<String> containerExposedPorts = createContainerParams.getContainerConfig().getExposedPorts().keySet();
    Set<String> imageExposedPorts = inspectImage(InspectImageParams.create(imageForDocker)).getConfig().getExposedPorts().keySet();
    Set<String> exposedPorts = getExposedPorts(containerExposedPorts, imageExposedPorts);
    boolean runContainerAsRoot = runContainerAsRoot(imageForDocker);
    String[] envVariables = createContainerParams.getContainerConfig().getEnv();
    String[] volumes = createContainerParams.getContainerConfig().getHostConfig().getBinds();
    Map<String, String> additionalLabels = createContainerParams.getContainerConfig().getLabels();
    String containerID;
    try {
        createOpenShiftService(workspaceID, exposedPorts, additionalLabels);
        String deploymentName = createOpenShiftDeployment(workspaceID, dockerPullSpec, containerName, exposedPorts, envVariables, volumes, runContainerAsRoot);
        containerID = waitAndRetrieveContainerID(deploymentName);
        if (containerID == null) {
            throw new OpenShiftException("Failed to get the ID of the container running in the OpenShift pod");
        }
    } catch (IOException e) {
        // Make sure we clean up deployment and service in case of an error -- otherwise Che can end up
        // in an inconsistent state.
        LOG.info("Error while creating Pod, removing deployment");
        String deploymentName = CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID;
        cleanUpWorkspaceResources(deploymentName);
        openShiftClient.resource(imageStreamTag).delete();
        throw e;
    }
    return new ContainerCreated(containerID, null);
}
Also used : ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) OpenShiftException(org.eclipse.che.plugin.openshift.client.exception.OpenShiftException) ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag) ImageStream(io.fabric8.openshift.api.model.ImageStream) IOException(java.io.IOException)

Example 2 with Container

use of io.fabric8.maven.docker.model.Container in project che by eclipse.

the class OpenShiftConnector method createOpenShiftDeployment.

private String createOpenShiftDeployment(String workspaceID, String imageName, String sanitizedContainerName, Set<String> exposedPorts, String[] envVariables, String[] volumes, boolean runContainerAsRoot) {
    String deploymentName = CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID;
    LOG.info("Creating OpenShift deployment {}", deploymentName);
    Map<String, String> selector = Collections.singletonMap(OPENSHIFT_DEPLOYMENT_LABEL, deploymentName);
    LOG.info("Adding container {} to OpenShift deployment {}", sanitizedContainerName, deploymentName);
    Long UID = runContainerAsRoot ? UID_ROOT : UID_USER;
    Container container = new ContainerBuilder().withName(sanitizedContainerName).withImage(imageName).withEnv(KubernetesEnvVar.getEnvFrom(envVariables)).withPorts(KubernetesContainer.getContainerPortsFrom(exposedPorts)).withImagePullPolicy(OPENSHIFT_IMAGE_PULL_POLICY_IFNOTPRESENT).withNewSecurityContext().withRunAsUser(UID).withPrivileged(true).endSecurityContext().withLivenessProbe(getLivenessProbeFrom(exposedPorts)).withVolumeMounts(getVolumeMountsFrom(volumes, workspaceID)).build();
    PodSpec podSpec = new PodSpecBuilder().withContainers(container).withVolumes(getVolumesFrom(volumes, workspaceID)).withServiceAccountName(this.openShiftCheServiceAccount).build();
    Deployment deployment = new DeploymentBuilder().withNewMetadata().withName(deploymentName).withNamespace(this.openShiftCheProjectName).endMetadata().withNewSpec().withReplicas(1).withNewSelector().withMatchLabels(selector).endSelector().withNewTemplate().withNewMetadata().withLabels(selector).endMetadata().withSpec(podSpec).endTemplate().endSpec().build();
    deployment = openShiftClient.extensions().deployments().inNamespace(this.openShiftCheProjectName).create(deployment);
    LOG.info("OpenShift deployment {} created", deploymentName);
    return deployment.getMetadata().getName();
}
Also used : PodSpecBuilder(io.fabric8.kubernetes.api.model.PodSpecBuilder) KubernetesContainer(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesContainer) Container(io.fabric8.kubernetes.api.model.Container) ContainerBuilder(io.fabric8.kubernetes.api.model.ContainerBuilder) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) DeploymentBuilder(io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder)

Example 3 with Container

use of io.fabric8.maven.docker.model.Container in project che by eclipse.

the class OpenShiftConnector method commit.

/**
     * OpenShift does not support taking image snapshots since the underlying assumption
     * is that Pods are largely immutable (and so any snapshot would be identical to the image
     * used to create the pod). Che uses docker commit to create machine snapshots, which are
     * used to restore workspaces. To emulate this functionality in OpenShift, commit
     * actually creates a new ImageStreamTag by calling {@link OpenShiftConnector#tag(TagParams)}
     * named for the snapshot that would be created.
     *
     * @see DockerConnector#commit(CommitParams)
     */
@Override
public String commit(final CommitParams params) throws IOException {
    // e.g. machine_snapshot_mdkfmksdfm
    String repo = params.getRepository();
    // container ID
    String container = params.getContainer();
    Pod pod = getChePodByContainerId(container);
    String image = pod.getSpec().getContainers().get(0).getImage();
    String imageStreamTagName = KubernetesStringUtils.getTagNameFromPullSpec(image);
    ImageStreamTag imageStreamTag = getImageStreamTagFromRepo(imageStreamTagName);
    String sourcePullSpec = imageStreamTag.getTag().getFrom().getName();
    String trackingRepo = KubernetesStringUtils.stripTagFromPullSpec(sourcePullSpec);
    String tag = KubernetesStringUtils.getTagNameFromPullSpec(sourcePullSpec);
    tag(TagParams.create(trackingRepo, repo).withTag(tag));
    // Return value not used.
    return repo;
}
Also used : Pod(io.fabric8.kubernetes.api.model.Pod) ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag)

Example 4 with Container

use of io.fabric8.maven.docker.model.Container in project camel by apache.

the class KubernetesPodsConsumerTest method createAndDeletePod.

@Test
public void createAndDeletePod() throws Exception {
    if (ObjectHelper.isEmpty(authToken)) {
        return;
    }
    mockResultEndpoint.expectedMessageCount(3);
    mockResultEndpoint.expectedHeaderValuesReceivedInAnyOrder(KubernetesConstants.KUBERNETES_EVENT_ACTION, "ADDED", "MODIFIED", "MODIFIED");
    Exchange ex = template.request("direct:createPod", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "default");
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_POD_NAME, "test");
            Map<String, String> labels = new HashMap<String, String>();
            labels.put("this", "rocks");
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_PODS_LABELS, labels);
            PodSpec podSpec = new PodSpec();
            podSpec.setHostname("localhost");
            Container cont = new Container();
            cont.setImage("docker.io/jboss/wildfly:latest");
            cont.setName("pippo");
            List<ContainerPort> containerPort = new ArrayList<ContainerPort>();
            ContainerPort port = new ContainerPort();
            port.setHostIP("0.0.0.0");
            port.setHostPort(8080);
            port.setContainerPort(8080);
            containerPort.add(port);
            cont.setPorts(containerPort);
            List<Container> list = new ArrayList<Container>();
            list.add(cont);
            podSpec.setContainers(list);
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_POD_SPEC, podSpec);
        }
    });
    ex = template.request("direct:deletePod", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, "default");
            exchange.getIn().setHeader(KubernetesConstants.KUBERNETES_POD_NAME, "test");
        }
    });
    boolean podDeleted = ex.getOut().getBody(Boolean.class);
    assertTrue(podDeleted);
    Thread.sleep(3000);
    mockResultEndpoint.assertIsSatisfied();
}
Also used : Processor(org.apache.camel.Processor) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) Exchange(org.apache.camel.Exchange) Container(io.fabric8.kubernetes.api.model.Container) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 5 with Container

use of io.fabric8.maven.docker.model.Container in project carbon-apimgt by wso2.

the class KubernetesGatewayImpl method createDeploymentResource.

/**
 * Create a deployment in cms
 *
 * @param deploymentTemplate Deployment template as a String
 * @param deploymentName     Name of the deployment
 * @throws ContainerBasedGatewayException if failed to create a deployment
 */
private void createDeploymentResource(String deploymentTemplate, String deploymentName) throws ContainerBasedGatewayException {
    HasMetadata resource = getResourcesFromTemplate(deploymentTemplate);
    try {
        if (resource instanceof Deployment) {
            // check whether there are existing service already
            if (client.extensions().deployments().inNamespace(namespace).withName(deploymentName).get() == null) {
                log.debug("Deploying in CMS type: {} and the Deployment resource definition: {} ", cmsType, deploymentTemplate);
                Deployment deployment = (Deployment) resource;
                Deployment result = client.extensions().deployments().inNamespace(namespace).create(deployment);
                log.info("Created Deployment : " + result.getMetadata().getName() + " in Namespace : " + result.getMetadata().getNamespace() + " in " + cmsType);
            } else {
                log.info("There exist a deployment with the same name in " + cmsType + ". Deployment name : " + deploymentName);
            }
        } else {
            throw new ContainerBasedGatewayException("Loaded Resource is not a Deployment in " + cmsType + "! " + resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
        }
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while creating container based gateway deployment in " + cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

Container (io.fabric8.api.Container)139 Test (org.junit.Test)105 IOException (java.io.IOException)57 FabricService (io.fabric8.api.FabricService)56 Container (io.fabric8.kubernetes.api.model.Container)56 ArrayList (java.util.ArrayList)49 File (java.io.File)39 Profile (io.fabric8.api.Profile)37 HashMap (java.util.HashMap)37 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)35 Map (java.util.Map)34 FabricException (io.fabric8.api.FabricException)27 Pod (io.fabric8.kubernetes.api.model.Pod)25 HashSet (java.util.HashSet)24 BundleContext (org.osgi.framework.BundleContext)24 Version (io.fabric8.api.Version)23 DockerAccessException (io.fabric8.maven.docker.access.DockerAccessException)23 List (java.util.List)21 ContainerBuilder (io.fabric8.kubernetes.api.model.ContainerBuilder)19 Container (io.fabric8.maven.docker.model.Container)19