io.fabric8.kubernetes.api.model.ObjectMetaBuilder Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.ObjectMetaBuilder. 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: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNotAddImagePullPolicyTwice() throws Exception {
  // given
  PodSpec podSpec1 =
      new PodSpecBuilder()
          .withImagePullSecrets(new LocalObjectReferenceBuilder().withName("secret").build())
          .build();
  podSpec1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 =
      new PodSpecBuilder()
          .withImagePullSecrets(new LocalObjectReferenceBuilder().withName("secret").build())
          .build();
  podSpec2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  List<LocalObjectReference> imagePullSecrets = podTemplate.getSpec().getImagePullSecrets();
  assertEquals(imagePullSecrets.size(), 1);
  assertEquals(imagePullSecrets.get(0).getName(), "secret");
}
 
Example #2
Source File: PKITest.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private Vault generateVaultResource() {
    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("pki").withNamespace("default").build()
    );

    VaultSpec spec = new VaultSpec();
    spec.setType(VaultType.PKI);
    spec.setPath("testpki/issue/testrole");

    VaultPkiConfiguration vaultPkiConfiguration = new VaultPkiConfiguration();
    vaultPkiConfiguration.setCommonName("test.url.de");
    vaultPkiConfiguration.setTtl("10m");
    spec.setPkiConfiguration(vaultPkiConfiguration);

    vault.setSpec(spec);

    return vault;
}
 
Example #3
Source File: PKIChainTest.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private Vault generateVaultResource() {
    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("pki").withNamespace("default").build()
    );

    VaultSpec spec = new VaultSpec();
    spec.setType(VaultType.PKI);
    spec.setPath("testpki/issue/testrole");

    VaultPkiConfiguration vaultPkiConfiguration = new VaultPkiConfiguration();
    vaultPkiConfiguration.setCommonName("test.url.de");
    vaultPkiConfiguration.setTtl("10m");
    spec.setPkiConfiguration(vaultPkiConfiguration);

    vault.setSpec(spec);

    return vault;
}
 
Example #4
Source File: KubernetesMockTest.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Test
public void findServices() {
  final ObjectMeta build = new ObjectMetaBuilder().addToLabels("test", "test").build();
  final ServiceSpec spec =
      new ServiceSpecBuilder().addNewPort().and().withClusterIP("192.168.1.1").build();
  final Service service = new ServiceBuilder().withMetadata(build).withSpec(spec).build();
  server
      .expect()
      .withPath("/api/v1/namespaces/default/services")
      .andReturn(200, new ServiceListBuilder().addToItems().addToItems(service).build())
      .once();
  KubernetesClient client = this.client;
  final ServiceList list = client.services().inNamespace("default").list();
  assertNotNull(list);
  assertEquals("test", list.getItems().get(0).getMetadata().getLabels().get("test"));
  System.out.println(list.getItems().get(0).getSpec().getClusterIP());
}
 
Example #5
Source File: IntegrationTestSupport.java    From java-operator-sdk with Apache License 2.0 6 votes vote down vote up
public void initialize(boolean updateStatus) {
    k8sClient = new DefaultKubernetesClient();

    log.info("Initializing integration test in namespace {}", TEST_NAMESPACE);

    CustomResourceDefinition crd = loadYaml(CustomResourceDefinition.class, "test-crd.yaml");
    k8sClient.customResourceDefinitions().createOrReplace(crd);

    controller = new TestCustomResourceController(k8sClient, updateStatus);
    Class doneableClass = getCustomResourceDoneableClass(controller);
    crOperations = k8sClient.customResources(crd, TestCustomResource.class, CustomResourceList.class, doneableClass);
    crOperations.inNamespace(TEST_NAMESPACE).delete(crOperations.list().getItems());

    if (k8sClient.namespaces().withName(TEST_NAMESPACE).get() == null) {
        k8sClient.namespaces().create(new NamespaceBuilder()
                .withMetadata(new ObjectMetaBuilder().withName(TEST_NAMESPACE).build()).build());
    }
    operator = new Operator(k8sClient);
    operator.registerController(controller, TEST_NAMESPACE);
    log.info("Operator is running with TestCustomeResourceController");
}
 
Example #6
Source File: PropertiesTest.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private Vault generatePropertiesManifest() throws IOException {
    HashMap<String, String> properties = new HashMap<>();
    File file = new ClassPathResource("test.properties").getFile();
    String content = new String(Files.readAllBytes(file.toPath()));
    properties.put("test.properties", content);

    HashMap<String, String> context = new HashMap<>();
    context.put("contextkey", "contextvalue");

    VaultSpec vaultSpec = new VaultSpec();
    vaultSpec.setType(VaultType.PROPERTIES);

    VaultPropertiesConfiguration vaultPropertiesConfiguration = new VaultPropertiesConfiguration();
    vaultPropertiesConfiguration.setFiles(properties);
    vaultPropertiesConfiguration.setContext(context);
    vaultSpec.setPropertiesConfiguration(vaultPropertiesConfiguration);

    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("properties").withNamespace("default").build()
    );
    vault.setSpec(vaultSpec);

    return vault;
}
 
Example #7
Source File: KafkaConnectAssemblyOperatorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testReconcileCreateAndUpdate(VertxTestContext context) {
    setConnectResource(new KafkaConnectBuilder()
            .withMetadata(new ObjectMetaBuilder()
                    .withName(CLUSTER_NAME)
                    .withNamespace(NAMESPACE)
                    .withLabels(TestUtils.map("foo", "bar"))
                    .build())
            .withNewSpec()
            .withReplicas(replicas)
            .endSpec()
        .build());
    KafkaConnectApi mock = mock(KafkaConnectApi.class);
    when(mock.list(anyString(), anyInt())).thenReturn(Future.succeededFuture(emptyList()));
    when(mock.listConnectorPlugins(anyString(), anyInt())).thenReturn(Future.succeededFuture(emptyList()));

    Checkpoint async = context.checkpoint();
    createConnectCluster(context, mock)
        .onComplete(context.succeeding())
        .compose(v -> {
            LOGGER.info("Reconciling again -> update");
            return kco.reconcile(new Reconciliation("test-trigger", KafkaConnect.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME));
        })
        .onComplete(context.succeeding(v -> async.flag()));

}
 
Example #8
Source File: ConfigMapLockTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void updateWithValidLeaderElectionRecordShouldSendPutRequest() throws Exception {
  // Given
  final Resource<ConfigMap, ?> configMapResource = configMaps.withName("name");
  final Replaceable<ConfigMap, ConfigMap> replaceable = mock(Replaceable.class, Answers.RETURNS_DEEP_STUBS);
  when(configMapResource.lockResourceVersion(any())).thenReturn(replaceable);
  final ConfigMap configMapInTheCluster = new ConfigMap();
  configMapInTheCluster.setMetadata(new ObjectMetaBuilder().withAnnotations(new HashMap<>()).build());
  when(configMapResource.get()).thenReturn(configMapInTheCluster);
  final LeaderElectionRecord record = new LeaderElectionRecord(
    "1337", Duration.ofSeconds(1), ZonedDateTime.now(), ZonedDateTime.now(), 0);
  record.setVersion("313373");
  final ConfigMapLock lock = new ConfigMapLock("namespace", "name", "1337");
  // When
  lock.update(kc, record);
  // Then
  verify(replaceable, times(1)).replace(eq(configMapInTheCluster));
}
 
Example #9
Source File: KafkaUpdateTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private Kafka initialKafka(String version, Map<String, Object> config) {
    return new KafkaBuilder()
            .withMetadata(new ObjectMetaBuilder().withName(NAME)
                    .withNamespace(NAMESPACE)
                    .build())
            .withNewSpec()
            .withNewKafka()
            .withReplicas(2)
            .withVersion(version)
            .withConfig(config)
            .withNewEphemeralStorage().endEphemeralStorage()
            .endKafka()
            .withNewZookeeper()
            .withReplicas(1)
            .withNewEphemeralStorage().endEphemeralStorage()
            .endZookeeper()
            .withNewTopicOperator()
            .endTopicOperator()
            .endSpec()
            .build();
}
 
Example #10
Source File: ProjectLabelEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void enrich(PlatformMode platformMode, KubernetesListBuilder builder) {
    // Add to all objects in the builder
    builder.accept(new TypedVisitor<ObjectMetaBuilder>() {
        @Override
        public void visit(ObjectMetaBuilder element) {
            if (element.getLabels() != null) {
                Map<String, String> labels = element.getLabels();
                MapUtil.mergeIfAbsent(labels, createLabels());
            } else {
                Map<String, String> newLabels = new HashMap<>();
                MapUtil.mergeIfAbsent(newLabels, createLabels());
                element.withLabels(newLabels);
            }
        }
    });
}
 
Example #11
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldAssignServiceAccountSharedByPods() throws Exception {
  // given
  PodSpec podSpec1 = new PodSpecBuilder().withServiceAccount("sa").build();
  podSpec1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 = new PodSpecBuilder().withServiceAccount("sa").build();
  podSpec2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  String sa = podTemplate.getSpec().getServiceAccount();
  assertEquals(sa, "sa");
}
 
Example #12
Source File: KubernetesEnvironment.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public PodData(Deployment deployment) {
  PodTemplateSpec podTemplate = deployment.getSpec().getTemplate();

  // it is not required for PodTemplate to have name specified
  // but many of Che Server components rely that PodData has name
  // so, provision name from deployment if it is missing
  ObjectMeta podTemplateMeta = podTemplate.getMetadata();
  if (podTemplateMeta == null) {
    podTemplate.setMetadata(
        new ObjectMetaBuilder().withName(deployment.getMetadata().getName()).build());
  } else {
    if (podTemplateMeta.getName() == null) {
      podTemplateMeta.setName(deployment.getMetadata().getName());
    }
  }

  this.podSpec = podTemplate.getSpec();
  this.podMeta = podTemplate.getMetadata();
  this.role = PodRole.DEPLOYMENT;
}
 
Example #13
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(dataProvider = "terminationGracePeriodProvider")
public void shouldBeAbleToMergeTerminationGracePeriodS(
    List<Long> terminationGracePeriods, Long expectedResultLong) throws ValidationException {
  List<PodData> podData =
      terminationGracePeriods
          .stream()
          .map(
              p ->
                  new PodData(
                      new PodSpecBuilder().withTerminationGracePeriodSeconds(p).build(),
                      new ObjectMetaBuilder().build()))
          .collect(Collectors.toList());

  // when
  Deployment merged = podMerger.merge(podData);
  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  assertEquals(podTemplate.getSpec().getTerminationGracePeriodSeconds(), expectedResultLong);
}
 
Example #14
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldMatchMergedPodTemplateLabelsWithDeploymentSelector() throws Exception {
  // given
  ObjectMeta podMeta1 =
      new ObjectMetaBuilder()
          .withName("ignored-1")
          .withAnnotations(ImmutableMap.of("ann1", "v1"))
          .withLabels(ImmutableMap.of("label1", "v1"))
          .build();
  podMeta1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(new PodSpecBuilder().build(), podMeta1);

  // when
  Deployment merged = podMerger.merge(Collections.singletonList(podData1));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  ObjectMeta podMeta = podTemplate.getMetadata();
  Map<String, String> deploymentSelector = merged.getSpec().getSelector().getMatchLabels();
  assertTrue(podMeta.getLabels().entrySet().containsAll(deploymentSelector.entrySet()));
}
 
Example #15
Source File: KeyValueTest.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
@Test
public void preventNullPointerExceptionWhenSecretDoesNotExist() {
    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("simple").withNamespace("default").build());
    VaultSpec vaultSpec = new VaultSpec();
    vaultSpec.setType(VaultType.KEYVALUE);
    vaultSpec.setPath("secret/simple");
    vault.setSpec(vaultSpec);

    stubFor(get(urlPathMatching("/v1/secret/simple"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody("{\"request_id\":\"6cc090a8-3821-8244-73e4-5ab62b605587\",\"lease_id\":\"\",\"renewable\":false,\"lease_duration\":2764800,\"data\":{\"key\":\"value\"},\"wrap_info\":null,\"warnings\":null,\"auth\":null}")));

    handler.modifyHandler(vault);

    Secret secret = client.secrets().inNamespace("default").withName("simple").get();
    assertEquals("simple", secret.getMetadata().getName());
    assertEquals("default", secret.getMetadata().getNamespace());
    assertEquals("Opaque", secret.getType());
    assertEquals("dmFsdWU=", secret.getData().get("key"));
    assertNotNull(secret.getMetadata().getAnnotations().get("vault.koudingspawn.de" + LAST_UPDATE_ANNOTATION));
    assertEquals("dYxf3NXqZ1l2d1YL1htbVBs6EUot33VjoBUUrBJg1eY=", secret.getMetadata().getAnnotations().get("vault.koudingspawn.de" + COMPARE_ANNOTATION));
}
 
Example #16
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorInTopicName() {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder().withMetadata(new ObjectMetaBuilder().withName("foo")
            .build()).withNewSpec()
                .withReplicas(1)
                .withPartitions(1)
                .withConfig(emptyMap())
                .withTopicName("An invalid topic name!")
            .endSpec()
        .build();
    try {
        TopicSerialization.fromTopicResource(kafkaTopic);
        fail("Should throw");
    } catch (InvalidTopicException e) {
        assertThat(e.getMessage(), is("KafkaTopics's spec.topicName property is invalid as a topic name: Topic name \"An invalid topic name!\" is illegal, it contains a character other than ASCII alphanumerics, '.', '_' and '-'"));
    }
}
 
Example #17
Source File: KeyValueTest.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGenerateSimpleSecretFromVaultCustomResource() {
    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("simple").withNamespace("default").build());
    VaultSpec vaultSpec = new VaultSpec();
    vaultSpec.setType(VaultType.KEYVALUE);
    vaultSpec.setPath("secret/simple");
    vault.setSpec(vaultSpec);

    stubFor(get(urlPathMatching("/v1/secret/simple"))
        .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"request_id\":\"6cc090a8-3821-8244-73e4-5ab62b605587\",\"lease_id\":\"\",\"renewable\":false,\"lease_duration\":2764800,\"data\":{\"key\":\"value\"},\"wrap_info\":null,\"warnings\":null,\"auth\":null}")));

    handler.addHandler(vault);

    Secret secret = client.secrets().inNamespace("default").withName("simple").get();
    assertEquals("simple", secret.getMetadata().getName());
    assertEquals("default", secret.getMetadata().getNamespace());
    assertEquals("Opaque", secret.getType());
    assertEquals("dmFsdWU=", secret.getData().get("key"));
    assertNotNull(secret.getMetadata().getAnnotations().get("vault.koudingspawn.de" + LAST_UPDATE_ANNOTATION));
    assertEquals("dYxf3NXqZ1l2d1YL1htbVBs6EUot33VjoBUUrBJg1eY=", secret.getMetadata().getAnnotations().get("vault.koudingspawn.de" + COMPARE_ANNOTATION));
}
 
Example #18
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorInReplicas() {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder()
            .withMetadata(new ObjectMetaBuilder().withName("my-topic").build())
            .withNewSpec()
                .withReplicas(-1)
                .withPartitions(1)
                .withConfig(emptyMap())
            .endSpec()
        .build();

    try {
        TopicSerialization.fromTopicResource(kafkaTopic);
        fail("Should throw");
    } catch (InvalidTopicException e) {
        assertThat(e.getMessage(), is("KafkaTopic's spec.replicas should be between 1 and 32767 inclusive"));
    }
}
 
Example #19
Source File: EnvironmentVariableSecretApplierTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp =
        "Unable to mount key 'foo'  of secret 'test_secret': It is configured to be mount as a environment variable, but its name was not specified. Please define the 'che.eclipse.org/foo_env-name' annotation on the secret to specify it.")
public void shouldThrowExceptionWhenNoEnvNameSpecifiedMultiValue() throws Exception {
  Container container_match = new ContainerBuilder().withName("maven").build();

  when(podSpec.getContainers()).thenReturn(ImmutableList.of(container_match));

  Secret secret =
      new SecretBuilder()
          .withData(ImmutableMap.of("foo", "random", "bar", "test"))
          .withMetadata(
              new ObjectMetaBuilder()
                  .withName("test_secret")
                  .withAnnotations(
                      ImmutableMap.of(ANNOTATION_MOUNT_AS, "env", ANNOTATION_AUTOMOUNT, "true"))
                  .withLabels(emptyMap())
                  .build())
          .build();

  when(secrets.get(any(LabelSelector.class))).thenReturn(singletonList(secret));
  secretApplier.applySecret(environment, runtimeIdentity, secret);
}
 
Example #20
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorInConfigInvalidValueWrongType() {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder()
            .withMetadata(new ObjectMetaBuilder().withName("my-topic").build())
            .withNewSpec()
                .withReplicas(1)
                .withPartitions(1)
                .withConfig(singletonMap("foo", new Object()))
            .endSpec()
        .build();

    try {
        TopicSerialization.fromTopicResource(kafkaTopic);
        fail("Should throw");
    } catch (InvalidTopicException e) {
        assertThat(e.getMessage(), is("KafkaTopic's spec.config has invalid entry: The key 'foo' of the topic config is invalid: The value corresponding to the key must have a string, number or boolean value but was of type java.lang.Object"));
    }
}
 
Example #21
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expectedExceptions = ValidationException.class)
public void shouldFailServiceAccountDiffersInPods() throws Exception {
  // given
  PodSpec podSpec1 = new PodSpecBuilder().withServiceAccount("sa").build();
  podSpec1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 = new PodSpecBuilder().withServiceAccount("sb").build();
  podSpec2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  // exception is thrown
}
 
Example #22
Source File: TopicSerializationTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorInConfigInvalidValueNull() {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder()
            .withMetadata(new ObjectMetaBuilder().withName("my-topic").build())
            .withNewSpec()
                .withReplicas(1)
                .withPartitions(1)
                .withConfig(singletonMap("foo", null))
            .endSpec()
        .build();

    try {
        TopicSerialization.fromTopicResource(kafkaTopic);
        fail("Should throw");
    } catch (InvalidTopicException e) {
        assertThat(e.getMessage(), is("KafkaTopic's spec.config has invalid entry: The key 'foo' of the topic config is invalid: The value corresponding to the key must have a string, number or boolean value but the value was null"));
    }
}
 
Example #23
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/** Test what happens when a non-topic KafkaTopic gets created in kubernetes */
@Test
public void testOnKafkaTopicAdded_invalidResource(VertxTestContext context) {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder()
            .withMetadata(new ObjectMetaBuilder().withName("invalid").withLabels(labels.labels()).build())
            .withNewSpec()
                .withReplicas(1)
                .withPartitions(1)
                .withConfig(singletonMap(null, null))
            .endSpec()
        .build();
    mockK8s.setGetFromNameResponse(new ResourceName(kafkaTopic), Future.succeededFuture(kafkaTopic));
    LogContext logContext = LogContext.kubeWatch(Watcher.Action.ADDED, kafkaTopic);
    Checkpoint async = context.checkpoint();
    topicOperator.onResourceEvent(logContext, kafkaTopic, ADDED).onComplete(ar -> {
        assertFailed(context, ar);
        context.verify(() -> assertThat(ar.cause(), instanceOf(InvalidTopicException.class)));
        context.verify(() -> assertThat(ar.cause().getMessage(), is("KafkaTopic's spec.config has invalid entry: The key 'null' of the topic config is invalid: The value corresponding to the key must have a string, number or boolean value but the value was null")));
        mockKafka.assertEmpty(context);
        mockTopicStore.assertEmpty(context);
        assertNotReadyStatus(context, new InvalidTopicException(null, ar.cause().getMessage()));
        context.verify(() -> {
            MeterRegistry registry = metrics.meterRegistry();

            assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations").tag("kind", "KafkaTopic").counter().count(), is(1.0));
            assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.successful").tag("kind", "KafkaTopic").counter().count(), is(0.0));
            assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.failed").tag("kind", "KafkaTopic").counter().count(), is(0.0));

            assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.duration").tag("kind", "KafkaTopic").timer().count(), is(0L));
            assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.duration").tag("kind", "KafkaTopic").timer().totalTime(TimeUnit.MILLISECONDS), is(0.0));
        });
        async.flag();

    });
}
 
Example #24
Source File: ResourceUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static KafkaUser createKafkaUser(KafkaUserQuotas quotas) {
    return new KafkaUserBuilder()
            .withMetadata(
                    new ObjectMetaBuilder()
                            .withNamespace(NAMESPACE)
                            .withName(NAME)
                            .withLabels(LABELS)
                            .build()
            )
            .withNewSpec()
            .withQuotas(quotas)
            .withNewKafkaUserAuthorizationSimple()
                .addNewAcl()
                    .withNewAclRuleTopicResource()
                        .withName("my-topic")
                    .endAclRuleTopicResource()
                .withOperation(AclOperation.READ)
                .endAcl()
                .addNewAcl()
                    .withNewAclRuleTopicResource()
                        .withName("my-topic")
                    .endAclRuleTopicResource()
                    .withOperation(AclOperation.DESCRIBE)
                .endAcl()
                .addNewAcl()
                    .withNewAclRuleGroupResource()
                        .withName("my-group")
                    .endAclRuleGroupResource()
                    .withOperation(AclOperation.READ)
                .endAcl()
            .endKafkaUserAuthorizationSimple()
            .endSpec()
            .build();
}
 
Example #25
Source File: ResolveServicesByNameTest.java    From vxms with Apache License 2.0 5 votes vote down vote up
public void initService() {
  final ObjectMeta buildmyTestService =
      new ObjectMetaBuilder().addToLabels("test", "test").withName("myTestService").build();
  final ServicePort portmyTestService =
      new ServicePortBuilder().withPort(8080).withProtocol("http").build();
  final ServiceSpec specmyTestService =
      new ServiceSpecBuilder()
          .addNewPort()
          .and()
          .withClusterIP("192.168.1.1")
          .withPorts(portmyTestService)
          .build();

  final ObjectMeta buildmyTestService2 =
      new ObjectMetaBuilder().addToLabels("test", "test2").withName("myTestService2").build();
  final ServicePort portmyTestService2 =
      new ServicePortBuilder().withPort(9080).withProtocol("http").build();
  final ServiceSpec specmyTestService2 =
      new ServiceSpecBuilder()
          .addNewPort()
          .and()
          .withClusterIP("192.168.1.2")
          .withPorts(portmyTestService2)
          .build();

  final Service servicemyTestService =
      new ServiceBuilder().withMetadata(buildmyTestService).withSpec(specmyTestService).build();
  final Service servicemyTestService2 =
      new ServiceBuilder().withMetadata(buildmyTestService2).withSpec(specmyTestService2).build();
  server
      .expect()
      .withPath("/api/v1/namespaces/default/services")
      .andReturn(
          200,
          new ServiceListBuilder()
              .addToItems(servicemyTestService, servicemyTestService2)
              .build())
      .times(2);
}
 
Example #26
Source File: ResourceUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Generate empty Kafka MirrorMaker 2.0 ConfigMap
 */
public static KafkaMirrorMaker2 createEmptyKafkaMirrorMaker2Cluster(String clusterCmNamespace, String clusterCmName) {
    return new KafkaMirrorMaker2Builder()
            .withMetadata(new ObjectMetaBuilder()
                    .withName(clusterCmName)
                    .withNamespace(clusterCmNamespace)
                    .withLabels(TestUtils.map(Labels.KUBERNETES_DOMAIN + "part-of", "tests",
                            "my-user-label", "cromulent"))
                    .build())
            .withNewSpec().endSpec()
            .build();
}
 
Example #27
Source File: AddVcsUrlAnnotationDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Override
public void andThenVisit(ObjectMetaBuilder builder, ObjectMeta resourceMeta) {
  Project p = getProject();
  boolean hasVcsUrl = p.getScmInfo() != null && p.getScmInfo().getUrl() != null;
  if (hasVcsUrl) {
    builder.addToAnnotations(annotationKey, getProject().getScmInfo().getUrl());
  }
}
 
Example #28
Source File: KeyValueV2Test.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCheckIfSimpleSecretHasChangedAndReturnFalse() throws SecretNotAccessibleException {
    Vault vault = new Vault();
    vault.setMetadata(
            new ObjectMetaBuilder().withName("simple").withNamespace("default").build());
    VaultSpec vaultSpec = new VaultSpec();
    vaultSpec.setType(VaultType.KEYVALUEV2);
    vaultSpec.setPath("secret/simple");
    vault.setSpec(vaultSpec);

    stubFor(get(urlPathMatching("/v1/secret/data/simple"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody("{\n" +
                            "  \"request_id\": \"1cfee2a6-318a-ea12-f5b5-6fd52d74d2c6\",\n" +
                            "  \"lease_id\": \"\",\n" +
                            "  \"renewable\": false,\n" +
                            "  \"lease_duration\": 0,\n" +
                            "  \"data\": {\n" +
                            "    \"data\": {\n" +
                            "      \"key\": \"value\"\n" +
                            "    },\n" +
                            "    \"metadata\": {\n" +
                            "      \"created_time\": \"2018-12-10T18:59:53.337997525Z\",\n" +
                            "      \"deletion_time\": \"\",\n" +
                            "      \"destroyed\": false,\n" +
                            "      \"version\": 1\n" +
                            "    }\n" +
                            "  },\n" +
                            "  \"wrap_info\": null,\n" +
                            "  \"warnings\": null,\n" +
                            "  \"auth\": null\n" +
                            "}")));

    handler.addHandler(vault);

    assertFalse(keyValueV2Refresh.refreshIsNeeded(vault));
}
 
Example #29
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldMergeMetasOfPodsData() throws Exception {
  // given
  ObjectMeta podMeta1 =
      new ObjectMetaBuilder()
          .withName("ignored-1")
          .withAnnotations(ImmutableMap.of("ann1", "v1"))
          .withLabels(ImmutableMap.of("label1", "v1"))
          .build();
  podMeta1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(new PodSpecBuilder().build(), podMeta1);

  ObjectMeta podMeta2 =
      new ObjectMetaBuilder()
          .withName("ignored-2")
          .withAnnotations(ImmutableMap.of("ann2", "v2"))
          .withLabels(ImmutableMap.of("label2", "v2"))
          .build();
  podMeta2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(new PodSpecBuilder().build(), podMeta2);

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  ObjectMeta podMeta = podTemplate.getMetadata();
  verifyContainsAllFrom(podMeta, podData1.getMetadata());
  verifyContainsAllFrom(podMeta, podData2.getMetadata());
}
 
Example #30
Source File: PodMergerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldGenerateInitContainerNamesIfCollisionHappened() throws Exception {
  // given
  PodSpec podSpec1 =
      new PodSpecBuilder()
          .withInitContainers(new ContainerBuilder().withName("initC").build())
          .build();
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 =
      new PodSpecBuilder()
          .withInitContainers(new ContainerBuilder().withName("initC").build())
          .build();
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());
  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  List<Container> initContainers = podTemplate.getSpec().getInitContainers();
  assertEquals(initContainers.size(), 2);
  Container container1 = initContainers.get(0);
  assertEquals(container1.getName(), "initC");
  Container container2 = initContainers.get(1);
  assertNotEquals(container2.getName(), "initC");
  assertTrue(container2.getName().startsWith("initC"));
}