Search in sources :

Example 1 with ImageStream

use of io.fabric8.openshift.api.model.ImageStream 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 ImageStream

use of io.fabric8.openshift.api.model.ImageStream in project che by eclipse.

the class OpenShiftConnector method tag.

/**
     * Creates an ImageStreamTag that tracks a given image.
     *
     * <p> Docker tags are used extensively in Che: all workspaces run on tagged images
     * tracking built stacks. For new workspaces, or when snapshots are not used, the
     * tracked image is e.g. {@code eclipse/ubuntu_jdk8}, whereas for snapshotted workspaces,
     * the tracked image is the snapshot (e.g. {@code machine_snapshot-<identifier>}.
     *
     * <p> Since OpenShift does not support the same tagging functionality as Docker,
     * tags are implemented as ImageStreamTags, where the {@code From} field is always
     * the original image, and the ImageStreamTag name is derived from both the source
     * image and the target image. This replicates functionality for Che in Docker,
     * while working differently under the hood. The ImageStream name is derived from
     * the image that is being tracked (e.g. {@code eclipse/ubuntu_jdk8}), while the tag
     * name is derived from the target image (e.g. {@code eclipse-che/che_workspace<identifier>}).
     *
     * @see DockerConnector#tag(TagParams)
     */
@Override
public void tag(final TagParams params) throws IOException {
    // E.g. `docker tag sourceImage targetImage`
    // e.g. eclipse/ubuntu_jdk8
    String paramsSourceImage = params.getImage();
    // e.g. eclipse-che/<identifier>
    String targetImage = params.getRepository();
    String paramsTag = params.getTag();
    String sourceImage = KubernetesStringUtils.stripTagFromPullSpec(paramsSourceImage);
    String tag = KubernetesStringUtils.getTagNameFromPullSpec(paramsSourceImage);
    if (isNullOrEmpty(tag)) {
        tag = !isNullOrEmpty(paramsTag) ? paramsTag : "latest";
    }
    String sourceImageWithTag;
    // Check if sourceImage matches existing imageStreamTag (e.g. when tagging a snapshot)
    try {
        String sourceImageTagName = KubernetesStringUtils.convertPullSpecToTagName(sourceImage);
        ImageStreamTag existingTag = getImageStreamTagFromRepo(sourceImageTagName);
        sourceImageWithTag = existingTag.getTag().getFrom().getName();
    } catch (IOException e) {
        // Image not found.
        sourceImageWithTag = String.format("%s:%s", sourceImage, tag);
    }
    String imageStreamTagName = KubernetesStringUtils.createImageStreamTagName(sourceImageWithTag, targetImage);
    createImageStreamTag(sourceImageWithTag, imageStreamTagName);
}
Also used : ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag) IOException(java.io.IOException)

Example 3 with ImageStream

use of io.fabric8.openshift.api.model.ImageStream in project fabric8-maven-plugin by fabric8io.

the class OpenshiftBuildServiceTest method createMockServer.

protected WebServerEventCollector<OpenShiftMockServer> createMockServer(BuildService.BuildServiceConfig config, boolean success, long buildDelay, boolean buildConfigExists, boolean imageStreamExists) {
    OpenShiftMockServer mockServer = new OpenShiftMockServer(false);
    WebServerEventCollector<OpenShiftMockServer> collector = new WebServerEventCollector<>(mockServer);
    BuildConfig bc = new BuildConfigBuilder().withNewMetadata().withName(projectName + config.getS2iBuildNameSuffix()).endMetadata().withNewSpec().endSpec().build();
    ImageStream imageStream = new ImageStreamBuilder().withNewMetadata().withName(projectName).endMetadata().withStatus(new ImageStreamStatusBuilder().addNewTagLike(new NamedTagEventListBuilder().addNewItem().withImage("abcdef0123456789").endItem().build()).endTag().build()).build();
    KubernetesList builds = new KubernetesListBuilder().withItems(new BuildBuilder().withNewMetadata().withName(projectName).endMetadata().build()).withNewMetadata().withResourceVersion("1").endMetadata().build();
    String buildStatus = success ? "Complete" : "Fail";
    Build build = new BuildBuilder().withNewMetadata().withResourceVersion("2").endMetadata().withNewStatus().withPhase(buildStatus).endStatus().build();
    if (!buildConfigExists) {
        mockServer.expect().get().withPath("/oapi/v1/namespaces/test/buildconfigs/" + projectName + config.getS2iBuildNameSuffix()).andReply(collector.record("build-config-check").andReturn(404, "")).once();
        mockServer.expect().post().withPath("/oapi/v1/namespaces/test/buildconfigs").andReply(collector.record("new-build-config").andReturn(201, bc)).once();
    } else {
        mockServer.expect().patch().withPath("/oapi/v1/namespaces/test/buildconfigs/" + projectName + config.getS2iBuildNameSuffix()).andReply(collector.record("patch-build-config").andReturn(200, bc)).once();
    }
    mockServer.expect().get().withPath("/oapi/v1/namespaces/test/buildconfigs/" + projectName + config.getS2iBuildNameSuffix()).andReply(collector.record("build-config-check").andReturn(200, bc)).always();
    if (!imageStreamExists) {
        mockServer.expect().get().withPath("/oapi/v1/namespaces/test/imagestreams/" + projectName).andReturn(404, "").once();
    }
    mockServer.expect().get().withPath("/oapi/v1/namespaces/test/imagestreams/" + projectName).andReturn(200, imageStream).always();
    mockServer.expect().post().withPath("/oapi/v1/namespaces/test/imagestreams").andReturn(201, imageStream).once();
    mockServer.expect().post().withPath("/oapi/v1/namespaces/test/buildconfigs/" + projectName + config.getS2iBuildNameSuffix() + "/instantiatebinary?commit=").andReply(collector.record("pushed").andReturn(201, imageStream)).once();
    mockServer.expect().get().withPath("/oapi/v1/namespaces/test/builds").andReply(collector.record("check-build").andReturn(200, builds)).always();
    mockServer.expect().get().withPath("/oapi/v1/namespaces/test/builds?labelSelector=openshift.io/build-config.name%3D" + projectName + config.getS2iBuildNameSuffix()).andReturn(200, builds).always();
    mockServer.expect().withPath("/oapi/v1/namespaces/test/builds/" + projectName).andReturn(200, build).always();
    mockServer.expect().withPath("/oapi/v1/namespaces/test/builds?fieldSelector=metadata.name%3D" + projectName + "&watch=true").andUpgradeToWebSocket().open().waitFor(buildDelay).andEmit(new WatchEvent(build, "MODIFIED")).done().always();
    return collector;
}
Also used : KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) ImageStreamStatusBuilder(io.fabric8.openshift.api.model.ImageStreamStatusBuilder) ImageStream(io.fabric8.openshift.api.model.ImageStream) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) WebServerEventCollector(io.fabric8.maven.core.util.WebServerEventCollector) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) BuildBuilder(io.fabric8.openshift.api.model.BuildBuilder) ImageStreamBuilder(io.fabric8.openshift.api.model.ImageStreamBuilder) OpenShiftMockServer(io.fabric8.openshift.client.server.mock.OpenShiftMockServer) Build(io.fabric8.openshift.api.model.Build) NamedTagEventListBuilder(io.fabric8.openshift.api.model.NamedTagEventListBuilder) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent)

Example 4 with ImageStream

use of io.fabric8.openshift.api.model.ImageStream in project fabric8-maven-plugin by fabric8io.

the class KubernetesClientUtil method deleteEntities.

public static void deleteEntities(KubernetesClient kubernetes, String namespace, Set<HasMetadata> entities, String s2iBuildNameSuffix, Logger log) {
    List<HasMetadata> list = new ArrayList<>(entities);
    // For OpenShift cluster, also delete s2i buildconfig
    OpenShiftClient openshiftClient = new Controller(kubernetes).getOpenShiftClientOrNull();
    if (openshiftClient != null) {
        for (HasMetadata entity : list) {
            if ("ImageStream".equals(getKind(entity))) {
                ImageName imageName = new ImageName(entity.getMetadata().getName());
                String buildName = getS2IBuildName(imageName, s2iBuildNameSuffix);
                log.info("Deleting resource BuildConfig " + namespace + "/" + buildName);
                openshiftClient.buildConfigs().inNamespace(namespace).withName(buildName).delete();
            }
        }
    }
    // lets delete in reverse order
    Collections.reverse(list);
    for (HasMetadata entity : list) {
        log.info("Deleting resource " + getKind(entity) + " " + namespace + "/" + getName(entity));
        kubernetes.resource(entity).inNamespace(namespace).cascading(true).delete();
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) ArrayList(java.util.ArrayList) Controller(io.fabric8.kubernetes.api.Controller) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController)

Example 5 with ImageStream

use of io.fabric8.openshift.api.model.ImageStream in project fabric8-maven-plugin by fabric8io.

the class ImageStreamService method writeImageStreams.

private File writeImageStreams(File target, KubernetesList entity) throws MojoExecutionException, IOException {
    final File targetWithoutExt;
    final ResourceFileType type;
    String ext = "";
    try {
        ext = FilenameUtils.getExtension(target.getPath());
        type = ResourceFileType.fromExtension(ext);
        String p = target.getAbsolutePath();
        targetWithoutExt = new File(p.substring(0, p.length() - ext.length() - 1));
    } catch (IllegalArgumentException exp) {
        throw new MojoExecutionException(String.format("Invalid extension '%s' for ImageStream target file '%s'. Allowed extensions: yml, json", ext, target.getPath()), exp);
    }
    return KubernetesResourceUtil.writeResource(entity, targetWithoutExt, type);
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ResourceFileType(io.fabric8.maven.core.util.ResourceFileType) File(java.io.File)

Aggregations

ImageStream (io.fabric8.openshift.api.model.ImageStream)19 IOException (java.io.IOException)9 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)8 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)8 Test (org.junit.Test)7 Service (io.fabric8.kubernetes.api.model.Service)6 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)5 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)5 File (java.io.File)5 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)4 Secret (io.fabric8.kubernetes.api.model.Secret)4 ImageStreamTag (io.fabric8.openshift.api.model.ImageStreamTag)4 Reconciliation (io.strimzi.controller.cluster.Reconciliation)4 KafkaConnectS2ICluster (io.strimzi.controller.cluster.model.KafkaConnectS2ICluster)4 BuildConfigOperator (io.strimzi.controller.cluster.operator.resource.BuildConfigOperator)4 ConfigMapOperator (io.strimzi.controller.cluster.operator.resource.ConfigMapOperator)4 DeploymentConfigOperator (io.strimzi.controller.cluster.operator.resource.DeploymentConfigOperator)4 ImageStreamOperator (io.strimzi.controller.cluster.operator.resource.ImageStreamOperator)4 ServiceOperator (io.strimzi.controller.cluster.operator.resource.ServiceOperator)4 Async (io.vertx.ext.unit.Async)4