io.fabric8.openshift.api.model.ImageStream Java Examples

The following examples show how to use io.fabric8.openshift.api.model.ImageStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HandlersTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void checkHandlers() {
  checkHandler(new BuildConfig(), new BuildConfigHandler());
  checkHandler(new Build(), new BuildHandler());
  checkHandler(new DeploymentConfig(), new DeploymentConfigHandler());
  checkHandler(new Group(), new GroupHandler());
  checkHandler(new Identity(), new IdentityHandler());
  checkHandler(new Image(), new ImageHandler());
  checkHandler(new ImageStream(), new ImageStreamHandler());
  checkHandler(new ImageStreamTag(), new ImageStreamTagHandler());
  checkHandler(new NetNamespace(), new NetNamespaceHandler());
  checkHandler(new OAuthAccessToken(), new OAuthAccessTokenHandler());
  checkHandler(new OAuthAuthorizeToken(), new OAuthAuthorizeTokenHandler());
  checkHandler(new OAuthClient(), new OAuthClientHandler());
  checkHandler(new Project(), new ProjectHandler());
  checkHandler(new Route(), new RouteHandler());
  checkHandler(new SecurityContextConstraints(), new SecurityContextConstraintsHandler());
  checkHandler(new User(), new UserHandler());
}
 
Example #2
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void createOrUpdateImageStreamTag(OpenShiftClient client, ImageName image, ImageStream is) {
    String namespace = client.getNamespace();
    String tagSha = findTagSha(client, image.getSimpleName(), client.getNamespace());
    String name = image.getSimpleName() + "@" + tagSha;

    TagReference tag = extractTag(is);
    ObjectReference from = extractFrom(tag);

    if (!Objects.equals(image.getTag(), tag.getName())) {
        tag.setName(image.getTag());
    }
    if (!Objects.equals("ImageStreamImage", from.getKind())) {
        from.setKind("ImageStreamImage");
    }
    if (!Objects.equals(namespace, from.getNamespace())) {
        from.setNamespace(namespace);
    }
    if (!Objects.equals(name, from.getName())) {
        from.setName(name);
    }
}
 
Example #3
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private TagReference extractTag(ImageStream is) {
    ImageStreamSpec spec = is.getSpec();
    if (spec == null) {
        spec = new ImageStreamSpec();
        is.setSpec(spec);
    }
    List<TagReference> tags = spec.getTags();
    if (tags == null) {
        tags = new ArrayList<>();
        spec.setTags(tags);
    }
    TagReference tag = null;
    if (tags.isEmpty()) {
        tag = new TagReference();
        tags.add(tag);
    } else {
        tag = tags.get(tags.size() - 1);
    }
    return tag;
}
 
Example #4
Source File: ListImageStreams.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  try {
    OpenShiftClient client = new DefaultOpenShiftClient();
    if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE)) {
      System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.IMAGE);
      return;
    }
    ImageStreamList list = client.imageStreams().list();
    if (list == null) {
      System.out.println("ERROR no list returned!");
      return;
    }
    List<ImageStream> items = list.getItems();
    for (ImageStream item : items) {
      System.out.println("ImageStream " + item.getMetadata().getName() + " has version: " + item.getApiVersion());
    }
    System.out.println("Found " + items.size() + " ImageStream(s)");
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #5
Source File: PatchService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static EntityPatcher<ImageStream> isPatcher() {
    return (KubernetesClient client, String namespace, ImageStream newObj, ImageStream oldObj) -> {
        if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
            return oldObj;
        }
        OpenShiftClient openShiftClient = OpenshiftHelper.asOpenShiftClient(client);
        if (openShiftClient == null) {
            throw new IllegalArgumentException("ImageStream can only be patched when connected to an OpenShift cluster");
        }
        DoneableImageStream entity =
            openShiftClient.imageStreams()
                  .inNamespace(namespace)
                  .withName(oldObj.getMetadata().getName())
                  .edit();

        if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
            entity.withMetadata(newObj.getMetadata());
        }

        if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
                entity.withSpec(newObj.getSpec());
        }
        return entity.done();
    };
}
 
Example #6
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public void applyImageStream(ImageStream entity, String sourceName) {
    OpenShiftClient openShiftClient = getOpenShiftClient();
    if (openShiftClient != null) {
        String kind = getKind(entity);
        String name = getName(entity);
        String namespace = getNamespace();
        try {
            Resource<ImageStream, DoneableImageStream> resource = openShiftClient.imageStreams().inNamespace(namespace).withName(name);
            ImageStream old = resource.get();
            if (old == null) {
                log.info("Creating " + kind + " " + name + " from " + sourceName);
                resource.create(entity);
            } else {
                log.info("Updating " + kind + " " + name + " from " + sourceName);
                copyAllImageStreamTags(entity, old);
                entity = patchService.compareAndPatchEntity(namespace, entity, old);
                openShiftClient.resource(entity).inNamespace(namespace).createOrReplace();
            }
        } catch (Exception e) {
            onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e, e);
        }
    }
}
 
Example #7
Source File: NewIntegrationTestBuildCommand.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    String buildConfigName = buildName.getValue();
    Objects.assertNotNull(buildConfigName, "buildName");
    Map<String, String> labels = BuildConfigs.createBuildLabels(buildConfigName);
    String gitUrlText = getOrFindGitUrl(context, gitUri.getValue());
    String imageText = image.getValue();
    List<EnvVar> envVars = createEnvVars(buildConfigName, gitUrlText, mavenCommand.getValue());
    BuildConfig buildConfig = BuildConfigs.createIntegrationTestBuildConfig(buildConfigName, labels, gitUrlText, imageText, envVars);

    LOG.info("Generated BuildConfig: " + toJson(buildConfig));

    ImageStream imageRepository = BuildConfigs.imageRepository(buildConfigName, labels);

    Controller controller = createController();
    controller.applyImageStream(imageRepository, "generated ImageStream: " + toJson(imageRepository));
    controller.applyBuildConfig(buildConfig, "generated BuildConfig: " + toJson(buildConfig));
    return Results.success("Added BuildConfig: " + Builds.getName(buildConfig) + " to OpenShift at master: " + getKubernetes().getMasterUrl());
}
 
Example #8
Source File: BuilderTest.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateBuild() throws Exception {
    String buildName = "my-build";
    String imageTag = "test";
    String image = "fabric8/quickstart-camel-cdi";
    String webhookSecret = "secret101";

    Map<String, String> labels = BuildConfigs.createBuildLabels(buildName);
    ImageStream imageRepository = BuildConfigs.imageRepository(buildName, labels);
    System.out.println("Generated ImageStream: " + JsonHelper.toJson(imageRepository));

    String gitUrl = "https://github.com/jstrachan/example-cd-workflow.git";
    BuildConfig buildConfig = BuildConfigs.createBuildConfig(buildName, labels, gitUrl, imageTag, image, webhookSecret);

    System.out.println("Generated BuildConfig: " + JsonHelper.toJson(buildConfig));
}
 
Example #9
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateSourceImageStream() {
    ImageStream is = kc.generateSourceImageStream();

    assertThat(is.getMetadata().getName(), is(KafkaConnectS2IResources.sourceImageStreamName(cluster)));
    assertThat(is.getMetadata().getNamespace(), is(namespace));
    assertThat(is.getMetadata().getLabels(), is(expectedLabels(KafkaConnectS2IResources.sourceImageStreamName(cluster))));
    assertThat(is.getSpec().getLookupPolicy().getLocal(), is(false));
    assertThat(is.getSpec().getTags().size(), is(1));
    assertThat(is.getSpec().getTags().get(0).getName(), is(image.substring(image.lastIndexOf(":") + 1)));
    assertThat(is.getSpec().getTags().get(0).getFrom().getKind(), is("DockerImage"));
    assertThat(is.getSpec().getTags().get(0).getFrom().getName(), is(image));
    assertThat(is.getSpec().getTags().get(0).getImportPolicy(), is(nullValue()));
    assertThat(is.getSpec().getTags().get(0).getReferencePolicy().getType(), is("Local"));
    checkOwnerReference(kc.createOwnerReference(), is);
}
 
Example #10
Source File: KafkaConnectS2ICluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Generate new target ImageStream
 *
 * @return      Target ImageStream resource definition
 */
public ImageStream generateTargetImageStream() {
    ImageStream imageStream = new ImageStreamBuilder()
            .withNewMetadata()
                .withName(KafkaConnectS2IResources.targetImageStreamName(cluster))
                .withNamespace(namespace)
                .withLabels(getLabelsWithStrimziName(name, null).toMap())
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withLookupPolicy(new ImageLookupPolicyBuilder().withLocal(true).build())
            .endSpec()
            .build();

    return imageStream;
}
 
Example #11
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static BuildConfig createBuildConfig(OpenShiftClient client, String namespace, String openShiftName, ImageStream is,
        PublishConfiguration pc) {
    String imageStreamName = is.getMetadata().getName()+":latest";
    return client.buildConfigs().inNamespace(namespace).createOrReplaceWithNew()
        .withNewMetadata().withName(getBuildConfigName(openShiftName))
            .addToLabels("application", openShiftName)
            .addToLabels(MANAGED_BY, SYSDESIS)
            .addToLabels(DEPLOYMENT_VERSION_LABEL, String.valueOf(pc.getPublishedRevision()))
            .endMetadata()
        .withNewSpec()
            .withRunPolicy("SerialLatestOnly")
            .withNewSource().withType("Binary").endSource()
            .withNewStrategy()
            .withType("Source").withNewSourceStrategy()
            .withNewFrom()
                .withKind("ImageStreamTag")
            .withName(pc.getBuildImageStream())
                .withNamespace(namespace)
            .endFrom()
            .withIncremental(false)
            .withEnv(pc.getUserEnvVars())
            .endSourceStrategy()
            .endStrategy()
            .withNewOutput()
                .withNewTo().withKind("ImageStreamTag").withName(imageStreamName).endTo()
            .endOutput()
            .withNodeSelector(pc.getBuildNodeSelector()).endSpec()
        .done();
}
 
Example #12
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, ImageStream> readAlreadyExtractedImageStreams(File target) throws IOException {
    // If it already exists, read in the file and use it for update
    Map<String, ImageStream> imageStreams = new HashMap<>();
    if (target.length() > 0) {
        for (HasMetadata entity : KubernetesHelper.loadResources(target)) {
            if ("ImageStream".equals(KubernetesHelper.getKind(entity))) {
                imageStreams.put(entity.getMetadata().getName(), (ImageStream) entity);
            }
            // Ignore all other kind of entities. There shouldn't be any included anyway
        }
    }
    return imageStreams;
}
 
Example #13
Source File: NewBuildCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    String buildConfigName = buildName.getValue();
    Objects.assertNotNull(buildConfigName, "buildName");
    Map<String, String> labels = BuildConfigs.createBuildLabels(buildConfigName);
    String ouputImageName = imageName.getValue();
    String gitUrlText = getOrFindGitUrl(context, gitUri.getValue());
    String imageText = outputImage.getValue();
    Model mavenModel = getMavenModel(context);
    if (Strings.isNullOrBlank(imageText) && mavenModel != null) {
        imageText = mavenModel.getProperties().getProperty("docker.image");
    }

    String webhookSecretText = webHookSecret.getValue();
    if (Strings.isNullOrBlank(webhookSecretText)) {
        // TODO generate a really good secret!
        webhookSecretText = "secret101";
    }
    BuildConfig buildConfig = BuildConfigs.createBuildConfig(buildConfigName, labels, gitUrlText, ouputImageName, imageText, webhookSecretText);

    System.out.println("Generated BuildConfig: " + toJson(buildConfig));

    ImageStream imageRepository = BuildConfigs.imageRepository(buildConfigName, labels);

    Controller controller = createController();
    controller.applyImageStream(imageRepository, "generated ImageStream: " + toJson(imageRepository));
    controller.applyBuildConfig(buildConfig, "generated BuildConfig: " + toJson(buildConfig));
    return Results.success("Added BuildConfig: " + Builds.getName(buildConfig) + " to OpenShift at master: " + getKubernetes().getMasterUrl());
}
 
Example #14
Source File: KafkaConnectS2ICluster.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Generate new source ImageStream
 *
 * @return      Source ImageStream resource definition
 */
public ImageStream generateSourceImageStream() {
    ObjectReference image = new ObjectReference();
    image.setKind("DockerImage");
    image.setName(sourceImageBaseName + ":" + sourceImageTag);

    TagReference sourceTag = new TagReference();
    sourceTag.setName(sourceImageTag);
    sourceTag.setFrom(image);
    sourceTag.setReferencePolicy(new TagReferencePolicyBuilder().withType("Local").build());

    if (insecureSourceRepository)   {
        sourceTag.setImportPolicy(new TagImportPolicyBuilder().withInsecure(true).build());
    }

    ImageStream imageStream = new ImageStreamBuilder()
            .withNewMetadata()
                .withName(KafkaConnectS2IResources.sourceImageStreamName(cluster))
                .withNamespace(namespace)
                .withLabels(getLabelsWithStrimziName(KafkaConnectS2IResources.sourceImageStreamName(cluster), null).toMap())
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withLookupPolicy(new ImageLookupPolicyBuilder().withLocal(false).build())
                .withTags(sourceTag)
            .endSpec()
            .build();

    return imageStream;
}
 
Example #15
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateTargetImageStream() {
    ImageStream is = kc.generateTargetImageStream();

    assertThat(is.getMetadata().getName(), is(KafkaConnectS2IResources.targetImageStreamName(cluster)));
    assertThat(is.getMetadata().getNamespace(), is(namespace));
    assertThat(is.getMetadata().getLabels(), is(expectedLabels(KafkaConnectS2IResources.targetImageStreamName(cluster))));
    assertThat(is.getSpec().getLookupPolicy().getLocal(), is(true));
    checkOwnerReference(kc.createOwnerReference(), is);
}
 
Example #16
Source File: ImageStreamIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void load() {
  ImageStream aImageStream = client.imageStreams().inNamespace(currentNamespace)
    .load(getClass().getResourceAsStream("/test-imagestream.yml")).get();
  assertThat(aImageStream).isNotNull();
  assertEquals("my-ruby", aImageStream.getMetadata().getName());
}
 
Example #17
Source File: ImageStreamIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void update() {
  ReadyEntity<ImageStream> imageStreamReady = new ReadyEntity<>(ImageStream.class, client, "java-sti", this.currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(imageStreamReady);
  imageStream1 = client.imageStreams().inNamespace(currentNamespace).withName("java-sti").edit()
    .editSpec().withDockerImageRepository("fabric8/s2i-java").endSpec()
    .done();
  assertThat(imageStream1).isNotNull();
  assertEquals("fabric8/s2i-java", imageStream1.getSpec().getDockerImageRepository());
}
 
Example #18
Source File: ImageStreamIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void delete() {
  ReadyEntity<ImageStream> imageStreamReady = new ReadyEntity<>(ImageStream.class, client, "example-camel-cdi", this.currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(imageStreamReady);
  boolean bDeleted = client.imageStreams().inNamespace(currentNamespace).withName("example-camel-cdi").delete();
  assertTrue(bDeleted);
}
 
Example #19
Source File: ImageStreamIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() throws InterruptedException {
  if (client.imageStreams().inNamespace(currentNamespace).list().getItems().size()!= 0) {
    client.imageStreams().inNamespace(currentNamespace).delete();
  }

  DeleteEntity<ImageStream> imageStream1Delete = new DeleteEntity<>(ImageStream.class, client, "java-sti", this.currentNamespace);
  DeleteEntity<ImageStream> imageStream2Delete = new DeleteEntity<>(ImageStream.class, client, "example-camel-cdi", this.currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(imageStream1Delete);
  await().atMost(30, TimeUnit.SECONDS).until(imageStream2Delete);
}
 
Example #20
Source File: Sample17Test.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Path sourcePath = SOURCE_DIR_PATH.resolve("hello_world_oc.bal");
    
    // save original source
    Stream<String> lines = Files.lines(sourcePath);
    this.originalSourceContent = lines.collect(Collectors.toList());
    
    // replace placeholders with mocks
    lines = Files.lines(sourcePath);
    List<String> replacedContent = lines.map(line -> line
            .replaceAll("<MINISHIFT_IP>", "192.168.99.131")
            .replaceAll("<MINISHIFT_DOCKER_REGISTRY_IP>", "172.30.1.1:5000"))
            .collect(Collectors.toList());
    Files.write(sourcePath, replacedContent);
    
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_oc.bal"), 0);
    File yamlFile = KUBERNETES_TARGET_PATH.resolve(OPENSHIFT).resolve("hello_world_oc.yaml").toFile();
    Assert.assertTrue(yamlFile.exists());
    List<HasMetadata> k8sItems = KubernetesTestUtils.loadYaml(yamlFile);
    for (HasMetadata data : k8sItems) {
        if ("BuildConfig".equals(data.getKind())) {
            buildConfig = (BuildConfig) data;
        } else if ("ImageStream".equals(data.getKind())) {
            imageStream = (ImageStream) data;
        } else if ("Route".equals(data.getKind())) {
            route = (Route) data;
        }
    }
}
 
Example #21
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private void appendImageStreamToFile(ImageStream is, File target) throws IOException {

        Map<String, ImageStream> imageStreams = readAlreadyExtractedImageStreams(target);
        // Override with given image stream
        imageStreams.put(is.getMetadata().getName(),is);
        KubernetesList isList =
            new KubernetesListBuilder().withItems(new ArrayList<HasMetadata>(imageStreams.values())).build();
        ResourceUtil.save(target, isList);
    }
 
Example #22
Source File: ImageStreamServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private void setupClientMock(final ImageStream lookedUpIs, final String name) {
    new Expectations() {{
        client.imageStreams(); result = imageStreamsOp;
        imageStreamsOp.withName(name); result = resource;
        resource.get(); result = lookedUpIs;

        client.getNamespace(); result = "default";
    }};
}
 
Example #23
Source File: ImageStreamServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private ImageStream lookupImageStream(String sha) {
    NamedTagEventList list = new NamedTagEventList();
    TagEvent tag = new TagEvent();
    tag.setImage(sha);
    list.setItems(new ArrayList<TagEvent>(Arrays.asList(tag)));

    return new ImageStreamBuilder()
        .withNewStatus()
        .addToTags(list)
        .endStatus()
        .build();
}
 
Example #24
Source File: OpenShiftImageStreamHandler.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
private void generate(OpenShiftBuildExtensionModel buildConfigModel) throws KubernetesPluginException {
    try {
        buildConfigModel.setLabels(new LinkedHashMap<>());
        if (null != buildConfigModel.getLabels() && !buildConfigModel.getLabels().containsKey("build")) {
            buildConfigModel.getLabels().put("build", buildConfigModel.getName());
        }
        
        String dockerImageName = new DockerImageName(dataHolder.getDockerModel().getName()).getRepository();
        
        ImageStream is = new ImageStreamBuilder()
                .withNewMetadata()
                .withName(dockerImageName)
                .withLabels(buildConfigModel.getLabels())
                .withAnnotations(buildConfigModel.getAnnotations())
                .withNamespace(dataHolder.getNamespace())
                .endMetadata()
                .build();
        
        String resourceQuotaContent = SerializationUtils.dumpWithoutRuntimeStateAsYaml(is);
        KubernetesUtils.writeToFile(dataHolder.getK8sArtifactOutputPath().resolve(OPENSHIFT), resourceQuotaContent,
                OPENSHIFT_IMAGE_STREAM_TAG_FILE_POSTFIX + YAML);
    } catch (IOException e) {
        String errorMessage = "error while generating OpenShift Image Stream yaml file: " +
                              buildConfigModel.getName();
        throw new KubernetesPluginException(errorMessage, e);
    }
}
 
Example #25
Source File: ImageStreamOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractResourceOperator<OpenShiftClient, ImageStream, ImageStreamList, DoneableImageStream, Resource<ImageStream, DoneableImageStream>> createResourceOperations(Vertx vertx, OpenShiftClient mockClient) {
    return new ImageStreamOperator(vertx, mockClient);
}
 
Example #26
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static ImageStream createImageStream(OpenShiftClient client, String namespace, String openShiftName) {
    return client.imageStreams().inNamespace(namespace).createOrReplaceWithNew()
        .withNewMetadata().withName(openShiftName).addToLabels("application", openShiftName).endMetadata()
        .done();
}
 
Example #27
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<ImageStream, ImageStreamList, DoneableImageStream, Resource<ImageStream, DoneableImageStream>> imageStreams() {
  return new ImageStreamOperationsImpl(httpClient, OpenShiftConfig.wrap(getConfiguration()));
}
 
Example #28
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private String findTagSha(OpenShiftClient client, String imageStreamName, String namespace) {
    ImageStream currentImageStream = null;

    for (int i = 0; i < IMAGE_STREAM_TAG_RETRIES; i++) {
        if (i > 0) {
            log.info("Retrying to find tag on ImageStream %s", imageStreamName);
            try {
                Thread.sleep(IMAGE_STREAM_TAG_RETRY_TIMEOUT_IN_MILLIS);
            } catch (InterruptedException e) {
                log.debug("interrupted", e);
                Thread.currentThread().interrupt();
            }
        }
        currentImageStream = client.imageStreams().withName(imageStreamName).get();
        if (currentImageStream == null) {
            continue;
        }
        ImageStreamStatus status = currentImageStream.getStatus();
        if (status == null) {
            continue;
        }
        List<NamedTagEventList> tags = status.getTags();
        if (tags == null || tags.isEmpty()) {
            continue;
        }

        // Iterate all imagestream tags and get the latest one by 'created' attribute
        TagEvent latestTag = null;

        TAG_EVENT_LIST:
        for (NamedTagEventList list : tags) {
            List<TagEvent> items = list.getItems();
            if (items == null || items.isEmpty()) {
                continue TAG_EVENT_LIST;
            }

            for (TagEvent tag : items) {
                latestTag = latestTag == null ? tag : newerTag(tag, latestTag);
            }
        }

        if (latestTag != null && StringUtils.isNotBlank(latestTag.getImage())) {
            String image = latestTag.getImage();
            log.info("Found tag on ImageStream " + imageStreamName + " tag: " + image);
            return image;
        }
    }

    // No image found, even after several retries:
    if (currentImageStream == null) {
        throw new IllegalStateException("Could not find a current ImageStream with name " + imageStreamName + " in namespace " + namespace);
    } else {
        throw new IllegalStateException("Could not find a tag in the ImageStream " + imageStreamName);
    }
}
 
Example #29
Source File: ImageStreamExample.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

    String namespace = "myproject";
    String master = "CLUSTER_URL";
    Config config = new ConfigBuilder().withMasterUrl(master).build();
    OpenShiftClient client = new DefaultOpenShiftClient(config);

    HashMap annotations = new HashMap();
    annotations.put("role", "jenkins-slave");
    annotations.put("slave-label", "jenkins-slave");

    try {

      ImageStream imageStream = new ImageStreamBuilder()
        .withNewMetadata()
          .withName("slave-jenkins")
        .endMetadata()
        .withNewSpec()
          .addToTags(0, new TagReferenceBuilder()
            .withName("base")
            .withFrom(new ObjectReferenceBuilder()
              .withKind("DockerImage")
              .withName("docker.io/openshift/jenkins-slave-maven-centos7:latest")
              .build()
            )
            .build()
          )
          .addToTags(1, new TagReferenceBuilder()
            .withAnnotations(annotations)
            .withName("latest")
            .withFrom(new ObjectReferenceBuilder()
              .withKind("ImageStreamTag")
              .withName("base")
              .build()
            )
            .build()
          )
        .endSpec()
        .build();

      log("Created ImageStream", client.imageStreams().inNamespace(namespace).create(imageStream));

    }finally {

      log("Tags in ImageStream are");
      log("First Tag is " + client.imageStreams().inNamespace(namespace).withName("slave-jenkins").get().getSpec().getTags().get(0).getName());
      log("Second Tag is " + client.imageStreams().inNamespace(namespace).withName("slave-jenkins").get().getSpec().getTags().get(1).getName());

      client.imageStreams().inNamespace(namespace).withName("slave-jenkins").delete();
      client.close();
    }
  }
 
Example #30
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Applies the given DTOs onto the Kubernetes master
 */
private void applyEntity(Object dto, String sourceName) throws Exception {
    if (dto instanceof Pod) {
        applyPod((Pod) dto, sourceName);
    } else if (dto instanceof ReplicationController) {
        applyReplicationController((ReplicationController) dto, sourceName);
    } else if (dto instanceof Service) {
        applyService((Service) dto, sourceName);
    } else if (dto instanceof Route) {
        applyRoute((Route) dto, sourceName);
    } else if (dto instanceof BuildConfig) {
        applyBuildConfig((BuildConfig) dto, sourceName);
    } else if (dto instanceof DeploymentConfig) {
        DeploymentConfig resource = (DeploymentConfig) dto;
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient != null) {
            applyResource(resource, sourceName, openShiftClient.deploymentConfigs());
        } else {
            log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof RoleBinding) {
        applyRoleBinding((RoleBinding) dto, sourceName);
    } else if (dto instanceof Role) {
        applyResource((Role)dto, sourceName, kubernetesClient.rbac().roles());
    } else if (dto instanceof ImageStream) {
        applyImageStream((ImageStream) dto, sourceName);
    } else if (dto instanceof OAuthClient) {
        applyOAuthClient((OAuthClient) dto, sourceName);
    } else if (dto instanceof Template) {
        applyTemplate((Template) dto, sourceName);
    } else if (dto instanceof ServiceAccount) {
        applyServiceAccount((ServiceAccount) dto, sourceName);
    } else if (dto instanceof Secret) {
        applySecret((Secret) dto, sourceName);
    } else if (dto instanceof ConfigMap) {
        applyResource((ConfigMap) dto, sourceName, kubernetesClient.configMaps());
    } else if (dto instanceof DaemonSet) {
        applyResource((DaemonSet) dto, sourceName, kubernetesClient.apps().daemonSets());
    } else if (dto instanceof Deployment) {
        applyResource((Deployment) dto, sourceName, kubernetesClient.apps().deployments());
    } else if (dto instanceof ReplicaSet) {
        applyResource((ReplicaSet) dto, sourceName, kubernetesClient.apps().replicaSets());
    } else if (dto instanceof StatefulSet) {
        applyResource((StatefulSet) dto, sourceName, kubernetesClient.apps().statefulSets());
    } else if (dto instanceof Ingress) {
        applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
    } else if (dto instanceof PersistentVolumeClaim) {
        applyPersistentVolumeClaim((PersistentVolumeClaim) dto, sourceName);
    }else if (dto instanceof CustomResourceDefinition) {
        applyCustomResourceDefinition((CustomResourceDefinition) dto, sourceName);
    } else if (dto instanceof Job) {
        applyJob((Job) dto, sourceName);
    } else if (dto instanceof HasMetadata) {
        HasMetadata entity = (HasMetadata) dto;
        try {
            log.info("Applying " + getKind(entity) + " " + getName(entity) + " from " + sourceName);
            kubernetesClient.resource(entity).inNamespace(getNamespace()).createOrReplace();
        } catch (Exception e) {
            onApplyError("Failed to create " + getKind(entity) + " from " + sourceName + ". " + e, e);
        }
    } else {
        throw new IllegalArgumentException("Unknown entity type " + dto);
    }
}