Search in sources :

Example 1 with Container

use of io.fabric8.kubernetes.api.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 2 with Container

use of io.fabric8.kubernetes.api.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 3 with Container

use of io.fabric8.kubernetes.api.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 4 with Container

use of io.fabric8.kubernetes.api.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 5 with Container

use of io.fabric8.kubernetes.api.model.Container in project che by eclipse.

the class KubernetesEnvVar method getEnvFrom.

/**
     * Retrieves list of {@link EnvVar} based on environment variables specified
     * in {@link ContainerConfig}
     *
     * @param envVariables
     * @return list of {@link EnvVar}
     */
public static List<EnvVar> getEnvFrom(String[] envVariables) {
    LOG.info("Container environment variables:");
    List<EnvVar> env = new ArrayList<>();
    for (String envVariable : envVariables) {
        String[] nameAndValue = envVariable.split("=", 2);
        String varName = nameAndValue[0];
        String varValue = nameAndValue[1];
        EnvVar envVar = new EnvVarBuilder().withName(varName).withValue(varValue).build();
        env.add(envVar);
        LOG.info("- {}={}", varName, varValue);
    }
    return env;
}
Also used : ArrayList(java.util.ArrayList) EnvVar(io.fabric8.kubernetes.api.model.EnvVar) EnvVarBuilder(io.fabric8.kubernetes.api.model.EnvVarBuilder)

Aggregations

Container (io.fabric8.kubernetes.api.model.Container)6 ArrayList (java.util.ArrayList)6 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)5 HashMap (java.util.HashMap)5 Pod (io.fabric8.kubernetes.api.model.Pod)4 ImageStreamTag (io.fabric8.openshift.api.model.ImageStreamTag)4 List (java.util.List)4 Map (java.util.Map)4 ContainerPort (io.fabric8.kubernetes.api.model.ContainerPort)3 Service (io.fabric8.kubernetes.api.model.Service)3 Exchange (org.apache.camel.Exchange)3 Processor (org.apache.camel.Processor)3 OpenShiftException (org.eclipse.che.plugin.openshift.client.exception.OpenShiftException)3 KubernetesContainer (org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesContainer)3 KubernetesService (org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesService)3 Test (org.junit.Test)3 ContainerBuilder (io.fabric8.kubernetes.api.model.ContainerBuilder)2 PodList (io.fabric8.kubernetes.api.model.PodList)2 PodSpecBuilder (io.fabric8.kubernetes.api.model.PodSpecBuilder)2 ServiceList (io.fabric8.kubernetes.api.model.ServiceList)2