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

The following examples show how to use io.fabric8.kubernetes.api.model.ObjectMeta#setLabels() . 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: MockKubernetesServerSupport.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected void createMockService(final String serviceName, final String ip, final Map<String, String> labels, final String namespace) {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP(ip);
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName(serviceName);
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(labels);

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    if (namespace != null) {
        this.server.getClient().inNamespace(namespace).services().create(service);
    } else {
        this.server.getClient().services().create(service);
    }

}
 
Example 2
Source File: KubernetesDiscoveredServiceWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGivenServiceExists() {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP("172.30.158.31");
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName("test-kieserver");
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(Collections.singletonMap("test-kieserver", "service"));

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    getClient().services().create(service);

    final DiscoveredServiceWorkItemHandler handler = new TestDiscoveredServiceWorkItemHandler(this);
    final ServiceInfo serviceInfo = handler.findEndpoint(MOCK_NAMESPACE, "test-kieserver");
    assertThat(serviceInfo, notNullValue());
    assertThat(serviceInfo.getUrl(), is("http://172.30.158.31:8080/test-kieserver"));
}
 
Example 3
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 4
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 6 votes vote down vote up
protected Service createService(final String namespace,
                                final String serviceName,
                                Map<String, String> labels) {
  labels = normalizeLabels(labels);

  final Service service = new Service();
  
  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(normalizeNamespace(namespace));
  metadata.setName(normalizeServiceName(serviceName));
  metadata.setLabels(labels);
  
  service.setMetadata(metadata);
  service.setSpec(this.createServiceSpec(labels));

  return service;
}
 
Example 5
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
protected Secret createSecret(final String namespace,
                              final URI tlsKeyUri,
                              final URI tlsCertUri,
                              final URI tlsCaCertUri,
                              final Map<String, String> labels)
  throws IOException {
  
  final Secret secret = new Secret();
  secret.setType("Opaque");

  final Map<String, String> secretData = new HashMap<>();
  
  try (final InputStream tlsKeyStream = read(tlsKeyUri)) {
    if (tlsKeyStream != null) {
      secretData.put("tls.key", Base64.getEncoder().encodeToString(toByteArray(tlsKeyStream)));
    }
  }

  try (final InputStream tlsCertStream = read(tlsCertUri)) {
    if (tlsCertStream != null) {
      secretData.put("tls.crt", Base64.getEncoder().encodeToString(toByteArray(tlsCertStream)));
    }
  }
  
  try (final InputStream tlsCaCertStream = read(tlsCaCertUri)) {
    if (tlsCaCertStream != null) {
      secretData.put("ca.crt", Base64.getEncoder().encodeToString(toByteArray(tlsCaCertStream)));
    }
  }

  secret.setData(secretData);

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(normalizeNamespace(namespace));
  metadata.setName(SECRET_NAME);
  metadata.setLabels(normalizeLabels(labels));
  secret.setMetadata(metadata);
  
  return secret;
}
 
Example 6
Source File: KubernetesResourceUtil.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Null safe get method for getting Labels of a Kubernetes Resource
 *
 * @param entity Kubernetes Resource
 * @return returns a hashmap containing labels
 */
public static Map<String, String> getOrCreateLabels(HasMetadata entity) {
  ObjectMeta metadata = getOrCreateMetadata(entity);
  Map<String, String> answer = metadata.getLabels();
  if (answer == null) {
    // use linked so the annotations can be in the FIFO order
    answer = new LinkedHashMap<>();
    metadata.setLabels(answer);
  }
  return answer;
}
 
Example 7
Source File: KubernetesObjectUtil.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Adds label to target Kubernetes object. */
public static void putLabel(ObjectMeta metadata, String key, String value) {
  Map<String, String> labels = metadata.getLabels();
  if (labels == null) {
    metadata.setLabels(labels = new HashMap<>());
  }

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

  Map<String, String> metaLabels = metadata.getLabels();
  if (metaLabels == null) {
    metadata.setLabels(new HashMap<>(labels));
  } else {
    metaLabels.putAll(labels);
  }
}
 
Example 9
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 10
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 11
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
protected DeploymentSpec createDeploymentSpec(final int replicas,
                                              final Map<String, String> labels,
                                              final Map<String, String> nodeSelector,
                                              String serviceAccountName,
                                              final String imageName,
                                              final ImagePullPolicy imagePullPolicy,
                                              final int maxHistory,
                                              final String namespace,
                                              final boolean hostNetwork,
                                              final boolean tls,
                                              final boolean verifyTls) {    
  final DeploymentSpec deploymentSpec = new DeploymentSpec();
  deploymentSpec.setReplicas(Math.max(1, replicas));
  final PodTemplateSpec podTemplateSpec = new PodTemplateSpec();
  final ObjectMeta metadata = new ObjectMeta();
  metadata.setLabels(normalizeLabels(labels));
  podTemplateSpec.setMetadata(metadata);
  final PodSpec podSpec = new PodSpec();
  serviceAccountName = normalizeServiceAccountName(serviceAccountName);    
  podSpec.setServiceAccountName(serviceAccountName);
  podSpec.setContainers(Arrays.asList(this.createContainer(imageName, imagePullPolicy, maxHistory, namespace, tls, verifyTls)));
  podSpec.setHostNetwork(Boolean.valueOf(hostNetwork));
  if (nodeSelector != null && !nodeSelector.isEmpty()) {
    podSpec.setNodeSelector(nodeSelector);
  }
  if (tls) {
    final Volume volume = new Volume();
    volume.setName(DEFAULT_NAME + "-certs");
    final SecretVolumeSource secretVolumeSource = new SecretVolumeSource();
    secretVolumeSource.setSecretName(SECRET_NAME);
    volume.setSecret(secretVolumeSource);
    podSpec.setVolumes(Arrays.asList(volume));
  }
  podTemplateSpec.setSpec(podSpec);
  deploymentSpec.setTemplate(podTemplateSpec);
  final LabelSelector selector = new LabelSelector();
  selector.setMatchLabels(labels);
  deploymentSpec.setSelector(selector);
  return deploymentSpec;
}
 
Example 12
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 13
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
protected Deployment createDeployment(String namespace,
                                      final String deploymentName,
                                      final int replicas,
                                      Map<String, String> labels,
                                      final Map<String, String> nodeSelector,
                                      final String serviceAccountName,
                                      final String imageName,
                                      final ImagePullPolicy imagePullPolicy,
                                      final int maxHistory,
                                      final boolean hostNetwork,
                                      final boolean tls,
                                      final boolean verifyTls) {
  namespace = normalizeNamespace(namespace);
  labels = normalizeLabels(labels);

  final Deployment deployment = new Deployment();

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(namespace);
  metadata.setName(normalizeDeploymentName(deploymentName));
  metadata.setLabels(labels);
  deployment.setMetadata(metadata);

  deployment.setSpec(this.createDeploymentSpec(Math.max(1, replicas),
                                               labels,
                                               nodeSelector,
                                               serviceAccountName,
                                               imageName,
                                               imagePullPolicy,
                                               maxHistory,
                                               namespace,
                                               hostNetwork,
                                               tls,
                                               verifyTls));
  return deployment;
}
 
Example 14
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 15
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 16
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 4 votes vote down vote up
@Test
public void listScheduleWithExternalCronJobs() {
	CronJobList cronJobList = new CronJobList();
	CronJobSpec cronJobSpec = new CronJobSpec();
	JobTemplateSpec jobTemplateSpec = new JobTemplateSpec();
	JobSpec jobSpec = new JobSpec();
	PodTemplateSpec podTemplateSpec = new PodTemplateSpec();
	PodSpec podSpec = new PodSpec();
	Container container = new Container();
	container.setName("test");
	container.setImage("busybox");
	podSpec.setContainers(Arrays.asList(container));
	podSpec.setRestartPolicy("OnFailure");
	podTemplateSpec.setSpec(podSpec);
	jobSpec.setTemplate(podTemplateSpec);
	jobTemplateSpec.setSpec(jobSpec);
	cronJobSpec.setJobTemplate(jobTemplateSpec);
	cronJobSpec.setSchedule("0/10 * * * *");

	CronJob cronJob1 = new CronJob();
	ObjectMeta objectMeta1 = new ObjectMeta();
	Map<String, String> labels = new HashMap<>();
	labels.put("spring-cronjob-id", "test");
	objectMeta1.setLabels(labels);
	objectMeta1.setName("job1");
	cronJob1.setMetadata(objectMeta1);
	cronJob1.setSpec(cronJobSpec);
	ObjectMeta objectMeta2 = new ObjectMeta();
	objectMeta2.setName("job2");
	CronJob cronJob2 = new CronJob();
	cronJob2.setSpec(cronJobSpec);
	cronJob2.setMetadata(objectMeta2);
	ObjectMeta objectMeta3 = new ObjectMeta();
	objectMeta3.setName("job3");
	CronJob cronJob3 = new CronJob();
	cronJob3.setSpec(cronJobSpec);
	cronJob3.setMetadata(objectMeta3);
	cronJobList.setItems(Arrays.asList(cronJob1, cronJob2, cronJob3));
	this.kubernetesClient.batch().cronjobs().create(cronJob1);
	this.kubernetesClient.batch().cronjobs().create(cronJob2);
	this.kubernetesClient.batch().cronjobs().create(cronJob3);
	List<ScheduleInfo> scheduleInfos = this.scheduler.list();
	assertThat(scheduleInfos.size() == 1);
	assertThat(scheduleInfos.get(0).getScheduleName().equals("job1"));
}
 
Example 17
Source File: ResourceUtils.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static Kafka createKafkaCluster(String clusterCmNamespace, String clusterCmName, int replicas,
                                       String image, int healthDelay, int healthTimeout,
                                       Map<String, Object> metricsCm,
                                       Map<String, Object> kafkaConfiguration,
                                       Map<String, Object> zooConfiguration,
                                       Storage kafkaStorage,
                                       SingleVolumeStorage zkStorage,
                                       Logging kafkaLogging, Logging zkLogging,
                                       KafkaExporterSpec keSpec,
                                       CruiseControlSpec ccSpec) {
    Kafka result = new Kafka();
    ObjectMeta meta = new ObjectMeta();
    meta.setNamespace(clusterCmNamespace);
    meta.setName(clusterCmName);
    meta.setLabels(Labels.fromMap(TestUtils.map(Labels.KUBERNETES_DOMAIN + "part-of", "tests", "my-user-label", "cromulent")).toMap());
    result.setMetadata(meta);

    KafkaSpec spec = new KafkaSpec();

    KafkaClusterSpec kafkaClusterSpec = new KafkaClusterSpec();
    kafkaClusterSpec.setReplicas(replicas);
    kafkaClusterSpec.setImage(image);
    if (kafkaLogging != null) {
        kafkaClusterSpec.setLogging(kafkaLogging);
    }
    Probe livenessProbe = new Probe();
    livenessProbe.setInitialDelaySeconds(healthDelay);
    livenessProbe.setTimeoutSeconds(healthTimeout);
    livenessProbe.setSuccessThreshold(4);
    livenessProbe.setFailureThreshold(10);
    livenessProbe.setPeriodSeconds(33);
    kafkaClusterSpec.setLivenessProbe(livenessProbe);
    kafkaClusterSpec.setReadinessProbe(livenessProbe);
    if (metricsCm != null) {
        kafkaClusterSpec.setMetrics(metricsCm);
    }

    if (kafkaConfiguration != null) {
        kafkaClusterSpec.setConfig(kafkaConfiguration);
    }
    kafkaClusterSpec.setStorage(kafkaStorage);
    spec.setKafka(kafkaClusterSpec);

    ZookeeperClusterSpec zk = new ZookeeperClusterSpec();
    zk.setReplicas(replicas);
    zk.setImage(image + "-zk");
    if (zkLogging != null) {
        zk.setLogging(zkLogging);
    }
    zk.setLivenessProbe(livenessProbe);
    zk.setReadinessProbe(livenessProbe);
    if (zooConfiguration != null) {
        zk.setConfig(zooConfiguration);
    }
    zk.setStorage(zkStorage);
    if (metricsCm != null) {
        zk.setMetrics(metricsCm);
    }

    spec.setKafkaExporter(keSpec);
    spec.setCruiseControl(ccSpec);

    spec.setZookeeper(zk);
    result.setSpec(spec);
    return result;
}
 
Example 18
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"));
}
 
Example 19
Source File: ServerPingRequestExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 4 votes vote down vote up
@Test
public void testShouldTerminateUnregisteredInstances_forSingleCluster() throws Exception {
    String unregisteredAgentId1 = "unregisteredAgentId1-" + UUID.randomUUID().toString();
    String unregisteredAgentId2 = "unregisteredAgentId2-" + UUID.randomUUID().toString();

    long time = Calendar.getInstance().getTimeInMillis();
    Pod mockedPod = mock(Pod.class);
    when(mockedOperation.withName(anyString())).thenReturn(podResource);
    when(podResource.get()).thenReturn(mockedPod);
    objectMetadata = new ObjectMeta();
    objectMetadata.setLabels(Collections.singletonMap(JOB_ID_LABEL_KEY, "20"));
    objectMetadata.setName(unregisteredAgentId1);
    objectMetadata.setCreationTimestamp(getSimpleDateFormat().format(new Date(time - (20 * 60000))));

    when(mockedPod.getMetadata()).thenReturn(objectMetadata);

    ClusterProfileProperties clusterProfilePropertiesForCluster1 = new ClusterProfileProperties("https://localhost:8154/go", null, null);

    KubernetesInstance k8sUnregisteredCluster1Pod1 = new KubernetesInstance(new DateTime().minusMinutes(100), null, unregisteredAgentId1, Collections.emptyMap(), 3L, PodState.Running);
    KubernetesInstance k8sUnregisteredCluster1Pod2 = new KubernetesInstance(new DateTime(), null, unregisteredAgentId2, Collections.emptyMap(), 3L, PodState.Running);

    final Agents allAgentsInitially = new Agents();

    KubernetesAgentInstances agentInstancesForCluster1 = new KubernetesAgentInstances(factory);
    agentInstancesForCluster1.register(k8sUnregisteredCluster1Pod1);
    agentInstancesForCluster1.register(k8sUnregisteredCluster1Pod2);

    HashMap<String, KubernetesAgentInstances> clusterSpecificInstances = new HashMap<>();
    clusterSpecificInstances.put(clusterProfilePropertiesForCluster1.uuid(), agentInstancesForCluster1);

    ServerPingRequest serverPingRequest = mock(ServerPingRequest.class);
    when(serverPingRequest.allClusterProfileProperties()).thenReturn(Arrays.asList(clusterProfilePropertiesForCluster1));

    PluginRequest pluginRequest = mock(PluginRequest.class);

    when(pluginRequest.listAgents()).thenReturn(allAgentsInitially);

    assertTrue(clusterSpecificInstances.get(clusterProfilePropertiesForCluster1.uuid()).hasInstance(k8sUnregisteredCluster1Pod1.name()));
    assertTrue(clusterSpecificInstances.get(clusterProfilePropertiesForCluster1.uuid()).hasInstance(k8sUnregisteredCluster1Pod2.name()));

    new ServerPingRequestExecutor(serverPingRequest, clusterSpecificInstances, pluginRequest).execute();

    assertFalse(clusterSpecificInstances.get(clusterProfilePropertiesForCluster1.uuid()).hasInstance(k8sUnregisteredCluster1Pod1.name()));
    assertTrue(clusterSpecificInstances.get(clusterProfilePropertiesForCluster1.uuid()).hasInstance(k8sUnregisteredCluster1Pod2.name()));
}
 
Example 20
Source File: ArquillianTest.java    From kubernetes-integration-test with Apache License 2.0 4 votes vote down vote up
@Test
public void shutDownMariadb() throws Exception{
    //Delete mariadb pod
    log.info("mariadb: {}", oc.pods().withName("mariadb").get()); //not null
    log.info("Delete mariadb pod.");
    assertTrue( oc.pods().withName(mariadb.getMetadata().getName()).delete() );
    Awaitility.await().atMost(30,TimeUnit.SECONDS).until(()->oc.pods().withName("mariadb").get()==null);

    //The port-foward url has http schema, but it's actually the amq 61616 port
    String brokerUrl = "tcp://"+ amqsvcUrl.getHost()+":"+ amqsvcUrl.getPort();
    log.info("brokerUrl: {}",brokerUrl);
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("test","secret",brokerUrl);
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);

    //Send test message and receive outcome
    jmsTemplate.convertAndSend("user.in", "{\"email\":\"[email protected]\"}");

    //Wait a sec to make sure message fails
    Thread.sleep(3000);

    //Create mariadb Pod and load sql
    log.info("Create mariadb pod.");
    ObjectMeta emptyObjectMeta = new ObjectMeta();
    emptyObjectMeta.setName(mariadb.getMetadata().getName());
    emptyObjectMeta.setLabels(mariadb.getMetadata().getLabels());
    mariadb.setMetadata(emptyObjectMeta);
    mariadb.setStatus(null);
    Pod newPod = oc.pods().create(mariadb);
    log.info("mariadb: {}", oc.pods().withName("mariadb").get());
    Awaitility.await().atMost(30,TimeUnit.SECONDS).until(()->oc.pods().withName("mariadb").isReady());
    //Recreate table, load data
    loadSql();

    //Receive response message
    TextMessage message = (TextMessage) jmsTemplate.receive("user.out");
    String response = message.getText();

    log.info("Response: {}",response);

    //Asserts
    assertEquals("[email protected]", JsonPath.read(response, "$.email"));
    assertEquals("5551234567", JsonPath.read(response, "$.phone"));
    assertEquals("Test State", JsonPath.read(response, "$.address.state"));
    assertEquals("Test City", JsonPath.read(response, "$.address.city"));
    assertEquals("1 Test St", JsonPath.read(response, "$.address.address"));
    assertEquals("T001", JsonPath.read(response, "$.address.zip"));

}