Java Code Examples for io.fabric8.kubernetes.api.model.ObjectMeta#setAnnotations()

The following examples show how to use io.fabric8.kubernetes.api.model.ObjectMeta#setAnnotations() . 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: KubernetesService.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private ObjectMeta metaData(ObjectMeta resource, String compare) {
    ObjectMeta meta = new ObjectMeta();
    meta.setNamespace(resource.getNamespace());
    meta.setName(resource.getName());
    if (resource.getLabels() != null) {
        meta.setLabels(resource.getLabels());
    }

    HashMap<String, String> annotations = new HashMap<>();
    if (resource.getAnnotations() != null) {
        annotations.putAll(resource.getAnnotations());
    }
    annotations.put(crdName + LAST_UPDATE_ANNOTATION, LocalDateTime.now().toString());
    annotations.put(crdName + COMPARE_ANNOTATION, compare);
    meta.setAnnotations(annotations);
    return meta;
}
 
Example 2
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private static Secret fakeServiceAccountKeySecret(String serviceAccount, long epoch, String jsonKeyId,
    String p12KeyId, String creationTimestamp) {
  final String jsonKeyName = keyName(serviceAccount, jsonKeyId);
  final String p12KeyName = keyName(serviceAccount, p12KeyId);

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setCreationTimestamp(creationTimestamp);
  metadata.setName("styx-wf-sa-keys-" + epoch + "-" + Hashing.sha256().hashString(serviceAccount, UTF_8));
  metadata.setAnnotations(Map.of(
      "styx-wf-sa", serviceAccount,
      "styx-wf-sa-json-key-name", jsonKeyName,
      "styx-wf-sa-p12-key-name", p12KeyName));

  return new SecretBuilder()
      .withMetadata(metadata)
      .withData(Map.of(
          "styx-wf-sa.json", "json-private-key-data",
          "styx-wf-sa.p12", "p12-private-key-data"))
      .build();
}
 
Example 3
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceSerializationRoundTrip() {

    String topicName = "tom";
    Topic.Builder builder = new Topic.Builder();
    builder.withTopicName(topicName);
    builder.withNumReplicas((short) 1);
    builder.withNumPartitions(2);
    builder.withConfigEntry("cleanup.policy", "bar");
    ObjectMeta metadata = new ObjectMeta();
    metadata.setAnnotations(new HashMap<>());
    builder.withMetadata(metadata);
    Topic wroteTopic = builder.build();
    KafkaTopic kafkaTopic = TopicSerialization.toTopicResource(wroteTopic, labels);

    assertThat(kafkaTopic.getMetadata().getName(), is(wroteTopic.getTopicName().toString()));
    assertThat(kafkaTopic.getMetadata().getLabels().size(), is(1));
    assertThat(kafkaTopic.getMetadata().getLabels().get("app"), is("strimzi"));
    assertThat(kafkaTopic.getSpec().getTopicName(), is(wroteTopic.getTopicName().toString()));
    assertThat(kafkaTopic.getSpec().getPartitions(), is(Integer.valueOf(2)));
    assertThat(kafkaTopic.getSpec().getReplicas(), is(Integer.valueOf(1)));
    assertThat(kafkaTopic.getSpec().getConfig(), is(singletonMap("cleanup.policy", "bar")));

    Topic readTopic = TopicSerialization.fromTopicResource(kafkaTopic);
    assertThat(readTopic, is(wroteTopic));
}
 
Example 4
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static void mergeMetadata(PodTemplateSpec item1, PodTemplateSpec item2) {
    if (item1 != null && item2 != null) {
        ObjectMeta metadata1 = item1.getMetadata();
        ObjectMeta metadata2 = item2.getMetadata();
        if (metadata1 == null) {
            item1.setMetadata(metadata2);
        } else if (metadata2 != null) {
            metadata1.setAnnotations(mergeMapsAndRemoveEmptyStrings(metadata2.getAnnotations(), metadata1.getAnnotations()));
            metadata1.setLabels(mergeMapsAndRemoveEmptyStrings(metadata2.getLabels(), metadata1.getLabels()));
        }
    }
}
 
Example 5
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
protected static void mergeMetadata(HasMetadata item1, HasMetadata item2) {
    if (item1 != null && item2 != null) {
        ObjectMeta metadata1 = item1.getMetadata();
        ObjectMeta metadata2 = item2.getMetadata();
        if (metadata1 == null) {
            item1.setMetadata(metadata2);
        } else if (metadata2 != null) {
            metadata1.setAnnotations(mergeMapsAndRemoveEmptyStrings(metadata2.getAnnotations(), metadata1.getAnnotations()));
            metadata1.setLabels(mergeMapsAndRemoveEmptyStrings(metadata2.getLabels(), metadata1.getLabels()));
        }
    }
}
 
Example 6
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, String> getOrCreateAnnotations(HasMetadata entity) {
    ObjectMeta metadata = getOrCreateMetadata(entity);
    Map<String, String> answer = metadata.getAnnotations();
    if (answer == null) {
        // use linked so the annotations can be in the FIFO order
        answer = new LinkedHashMap<>();
        metadata.setAnnotations(answer);
    }
    return answer;
}
 
Example 7
Source File: TopicSerialization.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Create a resource to reflect the given Topic.
 */
public static KafkaTopic toTopicResource(Topic topic, Labels labels) {
    ResourceName resourceName = topic.getOrAsKubeName();
    ObjectMeta om = topic.getMetadata();
    Map<String, String> lbls = new HashMap<>();
    lbls.putAll(labels.labels());
    if (om != null) {
        om.setName(resourceName.toString());
        if (topic.getMetadata().getLabels() != null)
            lbls.putAll(topic.getMetadata().getLabels());
        om.setLabels(lbls);
        om.setOwnerReferences(topic.getMetadata().getOwnerReferences());
        om.setAnnotations(topic.getMetadata().getAnnotations());
    } else {
        om = new ObjectMetaBuilder()
                .withName(resourceName.toString())
                .withLabels(lbls)
                .build();
    }

    KafkaTopic kt = new KafkaTopicBuilder().withApiVersion(KafkaTopic.RESOURCE_GROUP + "/" + KafkaTopic.V1BETA1)
            .withMetadata(om)
            // TODO .withUid()
            .withNewSpec()
                .withTopicName(topic.getTopicName().toString())
                .withPartitions(topic.getNumPartitions())
                .withReplicas((int) topic.getNumReplicas())
                .withConfig(new LinkedHashMap<>(topic.getConfig()))
            .endSpec()
            .build();
    // for some reason when the `topic.getMetadata().getAnnotations()` is null
    // topic is created with annotations={} (empty map but should be null as well)
    if (topic.getMetadata() != null)
        kt.getMetadata().setAnnotations(topic.getMetadata().getAnnotations());
    return kt;
}
 
Example 8
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testResourceSerializationRoundTripWithKubernetesLabels() {
    String topicName = "tom";
    Topic.Builder builder = new Topic.Builder();
    builder.withTopicName(topicName);
    builder.withNumReplicas((short) 1);
    builder.withNumPartitions(2);
    builder.withConfigEntry("cleanup.policy", "bar");
    ObjectMeta metadata = new ObjectMeta();
    metadata.setAnnotations(new HashMap<>());

    Map<String, String> kubeLabels = new HashMap<>(3);
    kubeLabels.put("app.kubernetes.io/name", "kstreams");
    kubeLabels.put("app.kubernetes.io/instance", "fraud-detection");
    kubeLabels.put("app.kubernetes.io/managed-by", "helm");

    metadata.setLabels(kubeLabels);
    builder.withMetadata(metadata);
    Topic wroteTopic = builder.build();
    KafkaTopic kafkaTopic = TopicSerialization.toTopicResource(wroteTopic, labels);

    assertThat(kafkaTopic.getMetadata().getName(), is(wroteTopic.getTopicName().toString()));
    assertThat(kafkaTopic.getMetadata().getLabels().size(), is(4));
    assertThat(kafkaTopic.getMetadata().getLabels().get("app"), is("strimzi"));
    assertThat(kafkaTopic.getMetadata().getLabels().get("app.kubernetes.io/name"), is("kstreams"));
    assertThat(kafkaTopic.getMetadata().getLabels().get("app.kubernetes.io/instance"), is("fraud-detection"));
    assertThat(kafkaTopic.getMetadata().getLabels().get("app.kubernetes.io/managed-by"), is("helm"));
    assertThat(kafkaTopic.getSpec().getTopicName(), is(wroteTopic.getTopicName().toString()));
    assertThat(kafkaTopic.getSpec().getPartitions(), is(Integer.valueOf(2)));
    assertThat(kafkaTopic.getSpec().getReplicas(), is(Integer.valueOf(1)));
    assertThat(kafkaTopic.getSpec().getConfig(), is(singletonMap("cleanup.policy", "bar")));

    Topic readTopic = TopicSerialization.fromTopicResource(kafkaTopic);
    assertThat(readTopic, is(wroteTopic));
}
 
Example 9
Source File: Names.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Records the machine name used for given container in the annotations of the object metadata.
 *
 * @param objectMeta the object metadata
 * @param containerName the name of the container
 * @param machineName the name of the machine of the container
 */
public static void putMachineName(
    ObjectMeta objectMeta, String containerName, String machineName) {

  Map<String, String> annotations = objectMeta.getAnnotations();
  if (annotations == null) {
    objectMeta.setAnnotations(annotations = new HashMap<>());
  }

  putMachineName(annotations, containerName, machineName);
}
 
Example 10
Source File: KubernetesObjectUtil.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Adds annotation to target ObjectMeta object. */
public static void putAnnotation(ObjectMeta metadata, String key, String value) {
  Map<String, String> annotations = metadata.getAnnotations();
  if (annotations == null) {
    metadata.setAnnotations(annotations = new HashMap<>());
  }

  annotations.put(key, value);
}
 
Example 11
Source File: KubernetesObjectUtil.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Adds annotations to target ObjectMeta object. */
public static void putAnnotations(ObjectMeta metadata, Map<String, String> annotations) {
  if (annotations == null || annotations.isEmpty()) {
    return;
  }

  Map<String, String> metaAnnotations = metadata.getAnnotations();
  if (metaAnnotations == null) {
    metadata.setAnnotations(new HashMap<>(annotations));
  } else {
    metaAnnotations.putAll(annotations);
  }
}
 
Example 12
Source File: KubernetesResourceUtil.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Null safe get for fetching annotations from MetaData of Kubernetes Resource
 *
 * @param entity Kubernetes resource
 * @return returns a hashmap containing annotations
 */
public static Map<String, String> getOrCreateAnnotations(HasMetadata entity) {
  ObjectMeta metadata = getOrCreateMetadata(entity);
  Map<String, String> answer = metadata.getAnnotations();
  if (answer == null) {
    // use linked so the annotations can be in the FIFO order
    answer = new LinkedHashMap<>();
    metadata.setAnnotations(answer);
  }
  return answer;
}
 
Example 13
Source File: KubernetesLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Namespace createNamespace() {
    Namespace namespace = new Namespace();
    ObjectMeta meta = new ObjectMeta();
    Map<String, String> annotations = new HashMap<>();
    annotations.put("test", "name");
    meta.setAnnotations(annotations);
    Map<String, String> labels = new HashMap<>();
    labels.put("ns", "my-namespace");
    meta.setLabels(labels);
    meta.setUid(UUID.randomUUID().toString());
    namespace.setMetadata(meta);
    return namespace;
}
 
Example 14
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldCreateNewServiceAccountKeysIfKeysAreDeleted() throws IOException {

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setAnnotations(Map.of("styx-wf-sa", SERVICE_ACCOUNT));

  final String jsonKeyId = "json-key";
  final String p12KeyId = "p12-key";
  final String newJsonKeyId = "new-json-key";
  final String newP12KeyId = "new-p12-key";

  final String creationTimestamp = CLOCK.instant().minus(Duration.ofDays(1)).toString();
  final Secret secret = fakeServiceAccountKeySecret(
      SERVICE_ACCOUNT, SECRET_EPOCH, jsonKeyId, p12KeyId, creationTimestamp);

  final ServiceAccountKey newJsonKey = new ServiceAccountKey()
      .setName(newJsonKeyId)
      .setPrivateKeyData("new-json-private-key-data");

  final ServiceAccountKey newP12Key = new ServiceAccountKey()
      .setName(newP12KeyId)
      .setPrivateKeyData("new-p12-private-key-data");

  when(serviceAccountKeyManager.serviceAccountExists(SERVICE_ACCOUNT)).thenReturn(true);
  when(serviceAccountKeyManager.keyExists(keyName(SERVICE_ACCOUNT, jsonKeyId))).thenReturn(false);
  when(serviceAccountKeyManager.keyExists(keyName(SERVICE_ACCOUNT, p12KeyId))).thenReturn(false);

  when(serviceAccountKeyManager.createJsonKey(any(String.class))).thenReturn(newJsonKey);
  when(serviceAccountKeyManager.createP12Key(any(String.class))).thenReturn(newP12Key);

  when(k8sClient.getSecret(secret.getMetadata().getName())).thenReturn(Optional.of(secret));

  sut.ensureServiceAccountKeySecret(WORKFLOW_INSTANCE.workflowId().toString(), SERVICE_ACCOUNT);

  verify(serviceAccountKeyManager).deleteKey(keyName(SERVICE_ACCOUNT, jsonKeyId));
  verify(serviceAccountKeyManager).deleteKey(keyName(SERVICE_ACCOUNT, p12KeyId));
  verify(serviceAccountKeyManager).createJsonKey(SERVICE_ACCOUNT);
  verify(serviceAccountKeyManager).createP12Key(SERVICE_ACCOUNT);
  verify(k8sClient).deleteSecret(secret.getMetadata().getName());
  verify(k8sClient).createSecret(secretCaptor.capture());

  final Secret createdSecret = secretCaptor.getValue();
  assertThat(createdSecret.getMetadata().getAnnotations(), hasEntry("styx-wf-sa", SERVICE_ACCOUNT));
  assertThat(createdSecret.getData(), hasEntry("styx-wf-sa.json", newJsonKey.getPrivateKeyData()));
  assertThat(createdSecret.getData(), hasEntry("styx-wf-sa.p12", newP12Key.getPrivateKeyData()));
}
 
Example 15
Source File: TopicOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Test
public void testKafkaTopicWithOwnerRef() throws InterruptedException, ExecutionException, TimeoutException {
    String topicName = "test-kafka-topic-with-owner-ref-1";

    // this CM is created to be the owner of the KafkaTopic we're about to create.
    String cmName = "hodor";
    HashMap<String, String> cmData = new HashMap<>();
    cmData.put("strimzi", "rulez");
    kubeClient.configMaps().inNamespace(NAMESPACE).create(new ConfigMapBuilder().withNewMetadata().withName(cmName)
            .withNamespace(NAMESPACE).endMetadata().withApiVersion("v1").withData(cmData).build());
    String uid = kubeClient.configMaps().inNamespace(NAMESPACE).withName(cmName).get().getMetadata().getUid();

    ObjectMeta metadata = new ObjectMeta();
    OwnerReference or = new OwnerReferenceBuilder().withName(cmName)
            .withApiVersion("v1")
            .withController(false)
            .withBlockOwnerDeletion(false)
            .withUid(uid)
            .withKind("ConfigMap")
            .build();

    metadata.getOwnerReferences().add(or);
    Map<String, String> annos = new HashMap<>();
    annos.put("iam", "groot");
    Map<String, String> lbls = new HashMap<>();
    lbls.put("iam", "root");
    metadata.setAnnotations(annos);
    metadata.setLabels(lbls);

    // create topic and test OR, labels, annotations
    Topic topic = new Topic.Builder(topicName, 1, (short) 1, emptyMap(), metadata).build();
    KafkaTopic topicResource = TopicSerialization.toTopicResource(topic, labels);
    createKafkaTopicResource(topicResource);
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getOwnerReferences().size(), is(1));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getOwnerReferences().get(0).getUid(), is(uid));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getAnnotations().size(), is(1));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getAnnotations().get("iam"), is("groot"));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getLabels().size(), is(2));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getLabels().get("iam"), is("root"));

    // edit kafka topic
    topicName = "test-kafka-topic-with-owner-ref-2";
    Topic topic2 = new Topic.Builder(topicName, 1, (short) 1, emptyMap(), metadata).build();
    KafkaTopic topicResource2 = TopicSerialization.toTopicResource(topic2, labels);
    topicResource = TopicSerialization.toTopicResource(topic2, labels);
    topicResource.getMetadata().getAnnotations().put("han", "solo");
    createKafkaTopicResource(topicResource2);
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getOwnerReferences().get(0).getUid(), is(uid));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getAnnotations().size(), is(2));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getAnnotations().get("iam"), is("groot"));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getAnnotations().get("han"), is("solo"));

    // edit k8s topic
    topicName = "test-kafka-topic-with-owner-ref-3";
    Topic topic3 = new Topic.Builder(topicName, 1, (short) 1, emptyMap(), metadata).build();
    topic3.getMetadata().getLabels().put("stan", "lee");
    topicResource = TopicSerialization.toTopicResource(topic3, labels);
    createKafkaTopicResource(topicResource);
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getOwnerReferences().get(0).getUid(), is(uid));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getLabels().size(), is(3));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getLabels().get("stan"), is("lee"));
    assertThat(operation().inNamespace(NAMESPACE).withName(topicName).get().getMetadata().getLabels().get("iam"), is("root"));
}