Search in sources :

Example 31 with PasswordGenerator

use of io.strimzi.operator.common.PasswordGenerator in project strimzi by strimzi.

the class KafkaAssemblyOperatorTest method updateCluster.

@SuppressWarnings({ "checkstyle:NPathComplexity", "checkstyle:JavaNCSS", "checkstyle:MethodLength" })
private void updateCluster(VertxTestContext context, Kafka originalAssembly, Kafka updatedAssembly) {
    KafkaCluster originalKafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, originalAssembly, VERSIONS);
    KafkaCluster updatedKafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, updatedAssembly, VERSIONS);
    ZookeeperCluster originalZookeeperCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, originalAssembly, VERSIONS);
    ZookeeperCluster updatedZookeeperCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, updatedAssembly, VERSIONS);
    EntityOperator originalEntityOperator = EntityOperator.fromCrd(new Reconciliation("test", originalAssembly.getKind(), originalAssembly.getMetadata().getNamespace(), originalAssembly.getMetadata().getName()), originalAssembly, VERSIONS, true);
    KafkaExporter originalKafkaExporter = KafkaExporter.fromCrd(new Reconciliation("test", originalAssembly.getKind(), originalAssembly.getMetadata().getNamespace(), originalAssembly.getMetadata().getName()), originalAssembly, VERSIONS);
    CruiseControl originalCruiseControl = CruiseControl.fromCrd(Reconciliation.DUMMY_RECONCILIATION, originalAssembly, VERSIONS, updatedKafkaCluster.getStorage());
    // create CM, Service, headless service, statefulset and so on
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(openShift);
    ClusterOperatorConfig config = ResourceUtils.dummyClusterOperatorConfig(VERSIONS);
    var mockKafkaOps = supplier.kafkaOperator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    StatefulSetOperator mockStsOps = supplier.stsOperations;
    PvcOperator mockPvcOps = supplier.pvcOperations;
    PodOperator mockPodOps = supplier.podOperations;
    DeploymentOperator mockDepOps = supplier.deploymentOperations;
    SecretOperator mockSecretOps = supplier.secretOperations;
    NetworkPolicyOperator mockPolicyOps = supplier.networkPolicyOperator;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    NodeOperator mockNodeOps = supplier.nodeOperator;
    IngressOperator mockIngressOps = supplier.ingressOperations;
    RouteOperator mockRouteOps = supplier.routeOperations;
    var mockPodSetOps = supplier.strimziPodSetOperator;
    String clusterName = updatedAssembly.getMetadata().getName();
    String clusterNamespace = updatedAssembly.getMetadata().getNamespace();
    Map<String, PersistentVolumeClaim> zkPvcs = createPvcs(clusterNamespace, originalZookeeperCluster.getStorage(), originalZookeeperCluster.getReplicas(), (replica, storageId) -> AbstractModel.VOLUME_NAME + "-" + KafkaResources.zookeeperPodName(clusterName, replica));
    zkPvcs.putAll(createPvcs(clusterNamespace, updatedZookeeperCluster.getStorage(), updatedZookeeperCluster.getReplicas(), (replica, storageId) -> AbstractModel.VOLUME_NAME + "-" + KafkaResources.zookeeperPodName(clusterName, replica)));
    Map<String, PersistentVolumeClaim> kafkaPvcs = createPvcs(clusterNamespace, originalKafkaCluster.getStorage(), originalKafkaCluster.getReplicas(), (replica, storageId) -> {
        String name = VolumeUtils.createVolumePrefix(storageId, false);
        return name + "-" + KafkaResources.kafkaPodName(clusterName, replica);
    });
    kafkaPvcs.putAll(createPvcs(clusterNamespace, updatedKafkaCluster.getStorage(), updatedKafkaCluster.getReplicas(), (replica, storageId) -> {
        String name = VolumeUtils.createVolumePrefix(storageId, false);
        return name + "-" + KafkaResources.kafkaPodName(clusterName, replica);
    }));
    when(mockPvcOps.get(eq(clusterNamespace), ArgumentMatchers.startsWith("data-"))).thenAnswer(invocation -> {
        String pvcName = invocation.getArgument(1);
        if (pvcName.contains(originalZookeeperCluster.getName())) {
            return zkPvcs.get(pvcName);
        } else if (pvcName.contains(originalKafkaCluster.getName())) {
            return kafkaPvcs.get(pvcName);
        }
        return null;
    });
    when(mockPvcOps.getAsync(eq(clusterNamespace), ArgumentMatchers.startsWith("data-"))).thenAnswer(invocation -> {
        String pvcName = invocation.getArgument(1);
        if (pvcName.contains(originalZookeeperCluster.getName())) {
            return Future.succeededFuture(zkPvcs.get(pvcName));
        } else if (pvcName.contains(originalKafkaCluster.getName())) {
            return Future.succeededFuture(kafkaPvcs.get(pvcName));
        }
        return Future.succeededFuture(null);
    });
    when(mockPvcOps.listAsync(eq(clusterNamespace), ArgumentMatchers.any(Labels.class))).thenAnswer(invocation -> {
        Labels labels = invocation.getArgument(1);
        if (labels.toMap().get(Labels.STRIMZI_NAME_LABEL).contains("kafka")) {
            return Future.succeededFuture(new ArrayList<>(kafkaPvcs.values()));
        } else if (labels.toMap().get(Labels.STRIMZI_NAME_LABEL).contains("zookeeper")) {
            return Future.succeededFuture(new ArrayList<>(zkPvcs.values()));
        }
        return Future.succeededFuture(Collections.EMPTY_LIST);
    });
    when(mockPvcOps.reconcile(any(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    // Mock CM get
    when(mockKafkaOps.get(clusterNamespace, clusterName)).thenReturn(updatedAssembly);
    when(mockKafkaOps.getAsync(eq(clusterNamespace), eq(clusterName))).thenReturn(Future.succeededFuture(updatedAssembly));
    when(mockKafkaOps.updateStatusAsync(any(), any(Kafka.class))).thenReturn(Future.succeededFuture());
    when(mockPodSetOps.reconcile(any(), any(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new StrimziPodSet())));
    when(mockPodSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(null));
    ConfigMap metricsCm = new ConfigMapBuilder().withNewMetadata().withName("metrics-cm").endMetadata().withData(singletonMap("metrics-config.yml", "")).build();
    ConfigMap metricsAndLoggingCm = originalKafkaCluster.generateSharedConfigurationConfigMap(new MetricsAndLogging(metricsCm, null), Map.of(), Map.of(), false);
    when(mockCmOps.get(clusterNamespace, KafkaResources.kafkaMetricsAndLogConfigMapName(clusterName))).thenReturn(metricsAndLoggingCm);
    when(mockCmOps.getAsync(clusterNamespace, KafkaResources.kafkaMetricsAndLogConfigMapName(clusterName))).thenReturn(Future.succeededFuture(metricsAndLoggingCm));
    ConfigMap zkMetricsCm = new ConfigMapBuilder().withNewMetadata().withName(KafkaResources.zookeeperMetricsAndLogConfigMapName(clusterName)).withNamespace(clusterNamespace).endMetadata().withData(singletonMap(AbstractModel.ANCILLARY_CM_KEY_METRICS, TestUtils.toYamlString(METRICS_CONFIG))).build();
    when(mockCmOps.get(clusterNamespace, KafkaResources.zookeeperMetricsAndLogConfigMapName(clusterName))).thenReturn(zkMetricsCm);
    ConfigMap logCm = new ConfigMapBuilder().withNewMetadata().withName(KafkaResources.kafkaMetricsAndLogConfigMapName(clusterName)).withNamespace(clusterNamespace).endMetadata().withData(singletonMap(AbstractModel.ANCILLARY_CM_KEY_LOG_CONFIG, updatedKafkaCluster.loggingConfiguration(LOG_KAFKA_CONFIG, null))).build();
    when(mockCmOps.get(clusterNamespace, KafkaResources.kafkaMetricsAndLogConfigMapName(clusterName))).thenReturn(logCm);
    ConfigMap zklogsCm = new ConfigMapBuilder().withNewMetadata().withName(KafkaResources.zookeeperMetricsAndLogConfigMapName(clusterName)).withNamespace(clusterNamespace).endMetadata().withData(singletonMap(AbstractModel.ANCILLARY_CM_KEY_LOG_CONFIG, updatedZookeeperCluster.loggingConfiguration(LOG_ZOOKEEPER_CONFIG, null))).build();
    when(mockCmOps.get(clusterNamespace, KafkaResources.zookeeperMetricsAndLogConfigMapName(clusterName))).thenReturn(zklogsCm);
    when(mockCmOps.getAsync(clusterNamespace, metricsCMName)).thenReturn(Future.succeededFuture(metricsCM));
    when(mockCmOps.getAsync(clusterNamespace, differentMetricsCMName)).thenReturn(Future.succeededFuture(metricsCM));
    when(mockCmOps.listAsync(clusterNamespace, updatedKafkaCluster.getSelectorLabels())).thenReturn(Future.succeededFuture(List.of()));
    // Mock pod ops
    when(mockPodOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockPodOps.listAsync(anyString(), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Mock node ops
    when(mockNodeOps.listAsync(any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Mock Service gets
    Set<Service> expectedServices = new HashSet<>();
    expectedServices.add(updatedKafkaCluster.generateService());
    expectedServices.add(updatedKafkaCluster.generateHeadlessService());
    expectedServices.addAll(updatedKafkaCluster.generateExternalBootstrapServices());
    int replicas = updatedKafkaCluster.getReplicas();
    for (int i = 0; i < replicas; i++) {
        expectedServices.addAll(updatedKafkaCluster.generateExternalServices(i));
    }
    Map<String, Service> expectedServicesMap = expectedServices.stream().collect(Collectors.toMap(s -> s.getMetadata().getName(), s -> s));
    when(mockServiceOps.endpointReadiness(any(), eq(clusterNamespace), any(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockServiceOps.get(eq(clusterNamespace), anyString())).thenAnswer(i -> Future.succeededFuture(expectedServicesMap.get(i.<String>getArgument(1))));
    when(mockServiceOps.getAsync(eq(clusterNamespace), anyString())).thenAnswer(i -> {
        Service svc = expectedServicesMap.get(i.<String>getArgument(1));
        if (svc != null && "NodePort".equals(svc.getSpec().getType())) {
            svc.getSpec().getPorts().get(0).setNodePort(32000);
        }
        return Future.succeededFuture(svc);
    });
    when(mockServiceOps.listAsync(eq(clusterNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(asList(originalKafkaCluster.generateService(), originalKafkaCluster.generateHeadlessService())));
    when(mockServiceOps.hasNodePort(any(), eq(clusterNamespace), any(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    // Ingress mocks
    when(mockIngressOps.listAsync(eq(clusterNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Route Mocks
    if (openShift) {
        Set<Route> expectedRoutes = new HashSet<>(originalKafkaCluster.generateExternalBootstrapRoutes());
        for (int i = 0; i < replicas; i++) {
            expectedRoutes.addAll(originalKafkaCluster.generateExternalRoutes(i));
        }
        Map<String, Route> expectedRoutesMap = expectedRoutes.stream().collect(Collectors.toMap(s -> s.getMetadata().getName(), s -> s));
        when(mockRouteOps.get(eq(clusterNamespace), anyString())).thenAnswer(i -> Future.succeededFuture(expectedRoutesMap.get(i.<String>getArgument(1))));
        when(mockRouteOps.getAsync(eq(clusterNamespace), anyString())).thenAnswer(i -> {
            Route rt = expectedRoutesMap.get(i.<String>getArgument(1));
            if (rt != null) {
                RouteStatus st = new RouteStatusBuilder().withIngress(new RouteIngressBuilder().withHost("host").build()).build();
                rt.setStatus(st);
            }
            return Future.succeededFuture(rt);
        });
        when(mockRouteOps.listAsync(eq(clusterNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
        when(mockRouteOps.hasAddress(any(), eq(clusterNamespace), any(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    }
    // Mock Secret gets
    when(mockSecretOps.list(anyString(), any())).thenReturn(emptyList());
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.kafkaJmxSecretName(clusterName))).thenReturn(Future.succeededFuture(originalKafkaCluster.generateJmxSecret(null)));
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.zookeeperJmxSecretName(clusterName))).thenReturn(Future.succeededFuture(originalZookeeperCluster.generateJmxSecret(null)));
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.zookeeperSecretName(clusterName))).thenReturn(Future.succeededFuture());
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.kafkaSecretName(clusterName))).thenReturn(Future.succeededFuture());
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.entityTopicOperatorSecretName(clusterName))).thenReturn(Future.succeededFuture());
    when(mockSecretOps.getAsync(clusterNamespace, KafkaExporterResources.secretName(clusterName))).thenReturn(Future.succeededFuture());
    when(mockSecretOps.getAsync(clusterNamespace, KafkaResources.clusterCaCertificateSecretName(clusterName))).thenReturn(Future.succeededFuture(new Secret()));
    when(mockSecretOps.getAsync(clusterNamespace, ClusterOperator.secretName(clusterName))).thenReturn(Future.succeededFuture(new Secret()));
    when(mockSecretOps.getAsync(clusterNamespace, CruiseControlResources.secretName(clusterName))).thenReturn(Future.succeededFuture());
    // Mock NetworkPolicy get
    when(mockPolicyOps.get(clusterNamespace, KafkaResources.kafkaNetworkPolicyName(clusterName))).thenReturn(originalKafkaCluster.generateNetworkPolicy(null, null));
    when(mockPolicyOps.get(clusterNamespace, KafkaResources.zookeeperNetworkPolicyName(clusterName))).thenReturn(originalZookeeperCluster.generateNetworkPolicy(null, null));
    // Mock PodDisruptionBudget get
    when(mockPdbOps.get(clusterNamespace, KafkaResources.kafkaStatefulSetName(clusterName))).thenReturn(originalKafkaCluster.generatePodDisruptionBudget());
    when(mockPdbOps.get(clusterNamespace, KafkaResources.zookeeperStatefulSetName(clusterName))).thenReturn(originalZookeeperCluster.generatePodDisruptionBudget());
    // Mock StatefulSet get
    when(mockStsOps.get(eq(clusterNamespace), eq(KafkaResources.kafkaStatefulSetName(clusterName)))).thenReturn(originalKafkaCluster.generateStatefulSet(openShift, null, null, null));
    when(mockStsOps.get(eq(clusterNamespace), eq(KafkaResources.zookeeperStatefulSetName(clusterName)))).thenReturn(originalZookeeperCluster.generateStatefulSet(openShift, null, null));
    // Mock Deployment get
    if (originalEntityOperator != null) {
        when(mockDepOps.get(clusterNamespace, KafkaResources.entityOperatorDeploymentName(clusterName))).thenReturn(originalEntityOperator.generateDeployment(true, null, null));
        when(mockDepOps.getAsync(clusterNamespace, KafkaResources.entityOperatorDeploymentName(clusterName))).thenReturn(Future.succeededFuture(originalEntityOperator.generateDeployment(true, null, null)));
        when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
        when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    }
    if (originalCruiseControl != null) {
        when(mockDepOps.get(clusterNamespace, CruiseControlResources.deploymentName(clusterName))).thenReturn(originalCruiseControl.generateDeployment(true, null, null));
        when(mockDepOps.getAsync(clusterNamespace, KafkaResources.entityOperatorDeploymentName(clusterName))).thenReturn(Future.succeededFuture(originalCruiseControl.generateDeployment(true, null, null)));
        when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
        when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    }
    if (metrics) {
        when(mockDepOps.get(clusterNamespace, KafkaExporterResources.deploymentName(clusterName))).thenReturn(originalKafkaExporter.generateDeployment(true, null, null));
        when(mockDepOps.getAsync(clusterNamespace, KafkaExporterResources.deploymentName(clusterName))).thenReturn(Future.succeededFuture(originalKafkaExporter.generateDeployment(true, null, null)));
        when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
        when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    }
    // Mock CM patch
    Set<String> metricsCms = set();
    doAnswer(invocation -> {
        metricsCms.add(invocation.getArgument(1));
        return Future.succeededFuture();
    }).when(mockCmOps).reconcile(any(), eq(clusterNamespace), any(), any());
    Set<String> logCms = set();
    doAnswer(invocation -> {
        logCms.add(invocation.getArgument(1));
        return Future.succeededFuture();
    }).when(mockCmOps).reconcile(any(), eq(clusterNamespace), any(), any());
    // Mock Service patch (both service and headless service
    ArgumentCaptor<String> patchedServicesCaptor = ArgumentCaptor.forClass(String.class);
    when(mockServiceOps.reconcile(any(), eq(clusterNamespace), patchedServicesCaptor.capture(), any())).thenReturn(Future.succeededFuture());
    // Mock Secrets patch
    when(mockSecretOps.reconcile(any(), eq(clusterNamespace), any(), any())).thenReturn(Future.succeededFuture());
    // Mock NetworkPolicy patch
    when(mockPolicyOps.reconcile(any(), eq(clusterNamespace), any(), any())).thenReturn(Future.succeededFuture());
    // Mock PodDisruptionBudget patch
    when(mockPdbOps.reconcile(any(), eq(clusterNamespace), any(), any())).thenReturn(Future.succeededFuture());
    // Mock StatefulSet patch
    when(mockStsOps.reconcile(any(), eq(clusterNamespace), eq(KafkaResources.zookeeperStatefulSetName(clusterName)), any())).thenAnswer(invocation -> {
        StatefulSet sts = invocation.getArgument(3);
        return Future.succeededFuture(ReconcileResult.patched(sts));
    });
    when(mockStsOps.reconcile(any(), eq(clusterNamespace), eq(KafkaResources.kafkaStatefulSetName(clusterName)), any())).thenAnswer(invocation -> {
        StatefulSet sts = invocation.getArgument(3);
        return Future.succeededFuture(ReconcileResult.patched(sts));
    });
    when(mockStsOps.getAsync(eq(clusterNamespace), eq(KafkaResources.zookeeperStatefulSetName(clusterName)))).thenReturn(Future.succeededFuture(originalZookeeperCluster.generateStatefulSet(openShift, null, null)));
    when(mockStsOps.getAsync(eq(clusterNamespace), eq(KafkaResources.kafkaStatefulSetName(clusterName)))).thenReturn(Future.succeededFuture());
    // Mock StatefulSet scaleUp
    // ArgumentCaptor<String> scaledUpCaptor = ArgumentCaptor.forClass(String.class);
    when(mockStsOps.scaleUp(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    // Mock StatefulSet scaleDown
    // ArgumentCaptor<String> scaledDownCaptor = ArgumentCaptor.forClass(String.class);
    when(mockStsOps.scaleDown(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    // Mock Deployment patch
    ArgumentCaptor<String> depCaptor = ArgumentCaptor.forClass(String.class);
    when(mockDepOps.reconcile(any(), anyString(), depCaptor.capture(), any())).thenReturn(Future.succeededFuture());
    KafkaAssemblyOperator ops = new KafkaAssemblyOperator(vertx, new PlatformFeaturesAvailability(openShift, kubernetesVersion), certManager, passwordGenerator, supplier, config);
    // Now try to update a KafkaCluster based on this CM
    Checkpoint async = context.checkpoint();
    ops.createOrUpdate(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, clusterNamespace, clusterName), updatedAssembly).onComplete(context.succeeding(v -> context.verify(() -> {
        // rolling restart
        Set<String> expectedRollingRestarts = set();
        if (StatefulSetOperator.needsRollingUpdate(Reconciliation.DUMMY_RECONCILIATION, new StatefulSetDiff(Reconciliation.DUMMY_RECONCILIATION, originalKafkaCluster.generateStatefulSet(openShift, null, null, null), updatedKafkaCluster.generateStatefulSet(openShift, null, null, null)))) {
            expectedRollingRestarts.add(originalKafkaCluster.getName());
        }
        if (StatefulSetOperator.needsRollingUpdate(Reconciliation.DUMMY_RECONCILIATION, new StatefulSetDiff(Reconciliation.DUMMY_RECONCILIATION, originalZookeeperCluster.generateStatefulSet(openShift, null, null), updatedZookeeperCluster.generateStatefulSet(openShift, null, null)))) {
            expectedRollingRestarts.add(originalZookeeperCluster.getName());
        }
        // Check that ZK scale-up happens when it should
        boolean zkScaledUp = updatedAssembly.getSpec().getZookeeper().getReplicas() > originalAssembly.getSpec().getZookeeper().getReplicas();
        verify(mockStsOps, times(zkScaledUp ? 1 : 0)).scaleUp(any(), eq(clusterNamespace), eq(KafkaResources.zookeeperStatefulSetName(clusterName)), anyInt());
        // No metrics config  => no CMs created
        verify(mockCmOps, never()).createOrUpdate(any(), any());
        async.flag();
    })));
}
Also used : RouteIngressBuilder(io.fabric8.openshift.api.model.RouteIngressBuilder) JmxTransQueryTemplateBuilder(io.strimzi.api.kafka.model.template.JmxTransQueryTemplateBuilder) ArgumentMatchers(org.mockito.ArgumentMatchers) KafkaExporterResources(io.strimzi.api.kafka.model.KafkaExporterResources) KafkaJmxOptions(io.strimzi.api.kafka.model.KafkaJmxOptions) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) AfterAll(org.junit.jupiter.api.AfterAll) PersistentClaimStorage(io.strimzi.api.kafka.model.storage.PersistentClaimStorage) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) RouteStatusBuilder(io.fabric8.openshift.api.model.RouteStatusBuilder) KafkaResources(io.strimzi.api.kafka.model.KafkaResources) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) AbstractModel(io.strimzi.operator.cluster.model.AbstractModel) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) KafkaJmxOptionsBuilder(io.strimzi.api.kafka.model.KafkaJmxOptionsBuilder) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) Set(java.util.Set) GenericKafkaListenerBuilder(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder) EphemeralStorage(io.strimzi.api.kafka.model.storage.EphemeralStorage) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) RouteOperator(io.strimzi.operator.common.operator.resource.RouteOperator) EntityOperator(io.strimzi.operator.cluster.model.EntityOperator) ClusterCa(io.strimzi.operator.cluster.model.ClusterCa) PersistentVolumeClaimBuilder(io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder) EntityUserOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityUserOperatorSpecBuilder) ClusterOperatorConfig(io.strimzi.operator.cluster.ClusterOperatorConfig) StatefulSetBuilder(io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder) VertxTestContext(io.vertx.junit5.VertxTestContext) GenericKafkaListener(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListener) IngressOperator(io.strimzi.operator.common.operator.resource.IngressOperator) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) PersistentClaimStorageBuilder(io.strimzi.api.kafka.model.storage.PersistentClaimStorageBuilder) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) KafkaJmxAuthenticationPasswordBuilder(io.strimzi.api.kafka.model.KafkaJmxAuthenticationPasswordBuilder) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) JmxTransSpecBuilder(io.strimzi.api.kafka.model.JmxTransSpecBuilder) Mockito.times(org.mockito.Mockito.times) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) PvcOperator(io.strimzi.operator.common.operator.resource.PvcOperator) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) Reconciliation(io.strimzi.operator.common.Reconciliation) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Mockito.never(org.mockito.Mockito.never) KafkaListenerType(io.strimzi.api.kafka.model.listener.arraylistener.KafkaListenerType) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Storage(io.strimzi.api.kafka.model.storage.Storage) StrimziPodSetOperator(io.strimzi.operator.common.operator.resource.StrimziPodSetOperator) BiFunction(java.util.function.BiFunction) Timeout(io.vertx.junit5.Timeout) Matchers.hasKey(org.hamcrest.Matchers.hasKey) KafkaExporter(io.strimzi.operator.cluster.model.KafkaExporter) Route(io.fabric8.openshift.api.model.Route) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaExporterSpec(io.strimzi.api.kafka.model.KafkaExporterSpec) MethodSource(org.junit.jupiter.params.provider.MethodSource) ListenersUtils(io.strimzi.operator.cluster.model.ListenersUtils) Collections.emptyList(java.util.Collections.emptyList) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) ClientsCa(io.strimzi.operator.cluster.model.ClientsCa) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) CruiseControlResources(io.strimzi.api.kafka.model.CruiseControlResources) Objects(java.util.Objects) List(java.util.List) Labels(io.strimzi.operator.common.model.Labels) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) Secret(io.fabric8.kubernetes.api.model.Secret) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) MockCertManager(io.strimzi.operator.common.operator.MockCertManager) EntityOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityOperatorSpecBuilder) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) EntityTopicOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityTopicOperatorSpecBuilder) KafkaStatus(io.strimzi.api.kafka.model.status.KafkaStatus) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) SingleVolumeStorage(io.strimzi.api.kafka.model.storage.SingleVolumeStorage) HashMap(java.util.HashMap) ZookeeperCluster(io.strimzi.operator.cluster.model.ZookeeperCluster) VolumeUtils(io.strimzi.operator.cluster.model.VolumeUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) MetricsAndLogging(io.strimzi.operator.common.MetricsAndLogging) HashSet(java.util.HashSet) JmxPrometheusExporterMetrics(io.strimzi.api.kafka.model.JmxPrometheusExporterMetrics) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaCluster(io.strimzi.operator.cluster.model.KafkaCluster) ClusterOperator(io.strimzi.operator.cluster.ClusterOperator) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) InlineLogging(io.strimzi.api.kafka.model.InlineLogging) TestUtils(io.strimzi.test.TestUtils) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) RouteStatus(io.fabric8.openshift.api.model.RouteStatus) JmxTransResources(io.strimzi.api.kafka.model.JmxTransResources) StatefulSetDiff(io.strimzi.operator.cluster.operator.resource.StatefulSetDiff) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) EntityOperatorSpec(io.strimzi.api.kafka.model.EntityOperatorSpec) CruiseControl(io.strimzi.operator.cluster.model.CruiseControl) Collections.emptyMap(java.util.Collections.emptyMap) NodeOperator(io.strimzi.operator.common.operator.resource.NodeOperator) JmxTransOutputDefinitionTemplateBuilder(io.strimzi.api.kafka.model.template.JmxTransOutputDefinitionTemplateBuilder) TestUtils.set(io.strimzi.test.TestUtils.set) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) Kafka(io.strimzi.api.kafka.model.Kafka) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) KafkaCluster(io.strimzi.operator.cluster.model.KafkaCluster) ArrayList(java.util.ArrayList) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RouteStatus(io.fabric8.openshift.api.model.RouteStatus) PvcOperator(io.strimzi.operator.common.operator.resource.PvcOperator) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) NodeOperator(io.strimzi.operator.common.operator.resource.NodeOperator) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) Route(io.fabric8.openshift.api.model.Route) HashSet(java.util.HashSet) CruiseControl(io.strimzi.operator.cluster.model.CruiseControl) MetricsAndLogging(io.strimzi.operator.common.MetricsAndLogging) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) Labels(io.strimzi.operator.common.model.Labels) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Secret(io.fabric8.kubernetes.api.model.Secret) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) RouteOperator(io.strimzi.operator.common.operator.resource.RouteOperator) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) EntityOperator(io.strimzi.operator.cluster.model.EntityOperator) ClusterOperatorConfig(io.strimzi.operator.cluster.ClusterOperatorConfig) Kafka(io.strimzi.api.kafka.model.Kafka) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) Reconciliation(io.strimzi.operator.common.Reconciliation) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Service(io.fabric8.kubernetes.api.model.Service) ZookeeperCluster(io.strimzi.operator.cluster.model.ZookeeperCluster) RouteStatusBuilder(io.fabric8.openshift.api.model.RouteStatusBuilder) Checkpoint(io.vertx.junit5.Checkpoint) IngressOperator(io.strimzi.operator.common.operator.resource.IngressOperator) Checkpoint(io.vertx.junit5.Checkpoint) StatefulSetDiff(io.strimzi.operator.cluster.operator.resource.StatefulSetDiff) KafkaExporter(io.strimzi.operator.cluster.model.KafkaExporter) RouteIngressBuilder(io.fabric8.openshift.api.model.RouteIngressBuilder) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator)

Example 32 with PasswordGenerator

use of io.strimzi.operator.common.PasswordGenerator in project strimzi by strimzi.

the class KafkaAssemblyOperatorTest method createCluster.

@SuppressWarnings({ "checkstyle:CyclomaticComplexity", "checkstyle:NPathComplexity", "checkstyle:JavaNCSS", "checkstyle:MethodLength" })
private void createCluster(VertxTestContext context, Kafka kafka, List<Secret> secrets) {
    KafkaCluster kafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS);
    ZookeeperCluster zookeeperCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS);
    EntityOperator entityOperator = EntityOperator.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS, true);
    // create CM, Service, headless service, statefulset and so on
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(openShift);
    ClusterOperatorConfig config = ResourceUtils.dummyClusterOperatorConfig(VERSIONS);
    var mockKafkaOps = supplier.kafkaOperator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    StatefulSetOperator mockStsOps = supplier.stsOperations;
    PvcOperator mockPvcOps = supplier.pvcOperations;
    PodOperator mockPodOps = supplier.podOperations;
    DeploymentOperator mockDepOps = supplier.deploymentOperations;
    SecretOperator mockSecretOps = supplier.secretOperations;
    NetworkPolicyOperator mockPolicyOps = supplier.networkPolicyOperator;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    RouteOperator mockRouteOps = supplier.routeOperations;
    IngressOperator mockIngressOps = supplier.ingressOperations;
    NodeOperator mockNodeOps = supplier.nodeOperator;
    StrimziPodSetOperator mockPodSetOps = supplier.strimziPodSetOperator;
    // Create a CM
    String kafkaName = kafka.getMetadata().getName();
    String kafkaNamespace = kafka.getMetadata().getNamespace();
    when(mockKafkaOps.get(kafkaNamespace, kafkaName)).thenReturn(null);
    when(mockKafkaOps.getAsync(eq(kafkaNamespace), eq(kafkaName))).thenReturn(Future.succeededFuture(kafka));
    when(mockKafkaOps.updateStatusAsync(any(), any(Kafka.class))).thenReturn(Future.succeededFuture());
    when(mockPodSetOps.reconcile(any(), any(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new StrimziPodSet())));
    when(mockPodSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(null));
    ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class);
    ArgumentCaptor<NetworkPolicy> policyCaptor = ArgumentCaptor.forClass(NetworkPolicy.class);
    ArgumentCaptor<PodDisruptionBudget> pdbCaptor = ArgumentCaptor.forClass(PodDisruptionBudget.class);
    ArgumentCaptor<io.fabric8.kubernetes.api.model.policy.v1beta1.PodDisruptionBudget> pdbV1Beta1Captor = ArgumentCaptor.forClass(io.fabric8.kubernetes.api.model.policy.v1beta1.PodDisruptionBudget.class);
    ArgumentCaptor<StatefulSet> ssCaptor = ArgumentCaptor.forClass(StatefulSet.class);
    when(mockStsOps.reconcile(any(), eq(kafkaNamespace), eq(KafkaResources.zookeeperStatefulSetName(kafkaName)), ssCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new StatefulSet())));
    when(mockStsOps.scaleDown(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(null));
    when(mockStsOps.scaleUp(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    AtomicReference<StatefulSet> ref = new AtomicReference<>();
    when(mockStsOps.reconcile(any(), eq(kafkaNamespace), eq(KafkaResources.kafkaStatefulSetName(kafkaName)), ssCaptor.capture())).thenAnswer(i -> {
        StatefulSet sts = new StatefulSetBuilder().withNewMetadata().withName(kafkaName + "kafka").withNamespace(kafkaNamespace).addToLabels(Labels.STRIMZI_CLUSTER_LABEL, kafkaName).endMetadata().withNewSpec().withReplicas(3).endSpec().build();
        ref.set(sts);
        return Future.succeededFuture(ReconcileResult.created(sts));
    });
    when(mockPolicyOps.reconcile(any(), anyString(), anyString(), policyCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new NetworkPolicy())));
    when(mockStsOps.getAsync(eq(kafkaNamespace), eq(KafkaResources.zookeeperStatefulSetName(kafkaName)))).thenReturn(Future.succeededFuture());
    when(mockStsOps.getAsync(eq(kafkaNamespace), eq(KafkaResources.kafkaStatefulSetName(kafkaName)))).thenAnswer(i -> Future.succeededFuture(ref.get()));
    when(mockPdbOps.reconcile(any(), anyString(), anyString(), pdbCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new PodDisruptionBudget())));
    // Service mocks
    Set<Service> createdServices = new HashSet<>();
    createdServices.add(kafkaCluster.generateService());
    createdServices.add(kafkaCluster.generateHeadlessService());
    createdServices.addAll(kafkaCluster.generateExternalBootstrapServices());
    int replicas = kafkaCluster.getReplicas();
    for (int i = 0; i < replicas; i++) {
        createdServices.addAll(kafkaCluster.generateExternalServices(i));
    }
    Map<String, Service> expectedServicesMap = createdServices.stream().collect(Collectors.toMap(s -> s.getMetadata().getName(), s -> s));
    when(mockServiceOps.get(eq(kafkaNamespace), anyString())).thenAnswer(i -> Future.succeededFuture(expectedServicesMap.get(i.<String>getArgument(1))));
    when(mockServiceOps.getAsync(eq(kafkaNamespace), anyString())).thenAnswer(i -> {
        Service svc = expectedServicesMap.get(i.<String>getArgument(1));
        if (svc != null && "NodePort".equals(svc.getSpec().getType())) {
            svc.getSpec().getPorts().get(0).setNodePort(32000);
        }
        return Future.succeededFuture(svc);
    });
    when(mockServiceOps.reconcile(any(), anyString(), anyString(), serviceCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new Service())));
    when(mockServiceOps.endpointReadiness(any(), anyString(), any(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockServiceOps.listAsync(eq(kafkaNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Ingress mocks
    when(mockIngressOps.listAsync(eq(kafkaNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Route Mocks
    if (openShift) {
        Set<Route> expectedRoutes = new HashSet<>(kafkaCluster.generateExternalBootstrapRoutes());
        for (int i = 0; i < replicas; i++) {
            expectedRoutes.addAll(kafkaCluster.generateExternalRoutes(i));
        }
        Map<String, Route> expectedRoutesMap = expectedRoutes.stream().collect(Collectors.toMap(s -> s.getMetadata().getName(), s -> s));
        when(mockRouteOps.get(eq(kafkaNamespace), anyString())).thenAnswer(i -> Future.succeededFuture(expectedRoutesMap.get(i.<String>getArgument(1))));
        when(mockRouteOps.getAsync(eq(kafkaNamespace), anyString())).thenAnswer(i -> {
            Route rt = expectedRoutesMap.get(i.<String>getArgument(1));
            if (rt != null) {
                RouteStatus st = new RouteStatusBuilder().withIngress(new RouteIngressBuilder().withHost("host").build()).build();
                rt.setStatus(st);
            }
            return Future.succeededFuture(rt);
        });
        when(mockRouteOps.listAsync(eq(kafkaNamespace), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    }
    // Mock pod readiness
    when(mockPodOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockPodOps.listAsync(anyString(), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Mock node ops
    when(mockNodeOps.listAsync(any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
    Map<String, PersistentVolumeClaim> zkPvcs = createPvcs(kafkaNamespace, zookeeperCluster.getStorage(), zookeeperCluster.getReplicas(), (replica, storageId) -> AbstractModel.VOLUME_NAME + "-" + KafkaResources.zookeeperPodName(kafkaName, replica));
    Map<String, PersistentVolumeClaim> kafkaPvcs = createPvcs(kafkaNamespace, kafkaCluster.getStorage(), kafkaCluster.getReplicas(), (replica, storageId) -> {
        String name = VolumeUtils.createVolumePrefix(storageId, false);
        return name + "-" + KafkaResources.kafkaPodName(kafkaName, replica);
    });
    when(mockPvcOps.get(eq(kafkaNamespace), ArgumentMatchers.startsWith("data-"))).thenAnswer(invocation -> {
        String pvcName = invocation.getArgument(1);
        if (pvcName.contains(zookeeperCluster.getName())) {
            return zkPvcs.get(pvcName);
        } else if (pvcName.contains(kafkaCluster.getName())) {
            return kafkaPvcs.get(pvcName);
        }
        return null;
    });
    when(mockPvcOps.getAsync(eq(kafkaNamespace), ArgumentMatchers.startsWith("data-"))).thenAnswer(invocation -> {
        String pvcName = invocation.getArgument(1);
        if (pvcName.contains(zookeeperCluster.getName())) {
            return Future.succeededFuture(zkPvcs.get(pvcName));
        } else if (pvcName.contains(kafkaCluster.getName())) {
            return Future.succeededFuture(kafkaPvcs.get(pvcName));
        }
        return Future.succeededFuture(null);
    });
    when(mockPvcOps.listAsync(eq(kafkaNamespace), ArgumentMatchers.any(Labels.class))).thenAnswer(invocation -> Future.succeededFuture(Collections.EMPTY_LIST));
    Set<String> expectedPvcs = new HashSet<>(zkPvcs.keySet());
    expectedPvcs.addAll(kafkaPvcs.keySet());
    ArgumentCaptor<PersistentVolumeClaim> pvcCaptor = ArgumentCaptor.forClass(PersistentVolumeClaim.class);
    when(mockPvcOps.reconcile(any(), anyString(), anyString(), pvcCaptor.capture())).thenReturn(Future.succeededFuture());
    Set<String> expectedSecrets = set(KafkaResources.clientsCaKeySecretName(kafkaName), KafkaResources.clientsCaCertificateSecretName(kafkaName), KafkaResources.clusterCaCertificateSecretName(kafkaName), KafkaResources.clusterCaKeySecretName(kafkaName), KafkaResources.kafkaSecretName(kafkaName), KafkaResources.zookeeperSecretName(kafkaName), ClusterOperator.secretName(kafkaName));
    if (metrics) {
        expectedSecrets.add(KafkaExporterResources.secretName(kafkaName));
    }
    expectedSecrets.addAll(secrets.stream().map(s -> s.getMetadata().getName()).collect(Collectors.toSet()));
    if (eoConfig != null) {
        // it's expected only when the Entity Operator is deployed by the Cluster Operator
        expectedSecrets.add(KafkaResources.entityTopicOperatorSecretName(kafkaName));
        expectedSecrets.add(KafkaResources.entityUserOperatorSecretName(kafkaName));
    }
    when(mockDepOps.reconcile(any(), anyString(), anyString(), any())).thenAnswer(invocation -> {
        String name = invocation.getArgument(2);
        Deployment desired = invocation.getArgument(3);
        if (desired != null) {
            if (name.contains("operator")) {
                if (entityOperator != null) {
                    context.verify(() -> assertThat(desired.getMetadata().getName(), is(KafkaResources.entityOperatorDeploymentName(kafkaName))));
                }
            } else if (name.contains("exporter")) {
                context.verify(() -> assertThat(metrics, is(true)));
            }
        }
        return Future.succeededFuture(desired != null ? ReconcileResult.created(desired) : ReconcileResult.deleted());
    });
    when(mockDepOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture());
    when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    Map<String, Secret> secretsMap = secrets.stream().collect(Collectors.toMap(s -> s.getMetadata().getName(), s -> s));
    when(mockSecretOps.list(anyString(), any())).thenAnswer(i -> new ArrayList<>(secretsMap.values()));
    when(mockSecretOps.getAsync(anyString(), any())).thenAnswer(i -> Future.succeededFuture(secretsMap.get(i.<String>getArgument(1))));
    when(mockSecretOps.getAsync(kafkaNamespace, KafkaResources.clusterCaCertificateSecretName(kafkaName))).thenAnswer(i -> Future.succeededFuture(secretsMap.get(i.<String>getArgument(1))));
    when(mockSecretOps.getAsync(kafkaNamespace, ClusterOperator.secretName(kafkaName))).thenAnswer(i -> Future.succeededFuture(secretsMap.get(i.<String>getArgument(1))));
    when(mockSecretOps.reconcile(any(), anyString(), anyString(), any())).thenAnswer(invocation -> {
        Secret desired = invocation.getArgument(3);
        if (desired != null) {
            secretsMap.put(desired.getMetadata().getName(), desired);
        }
        return Future.succeededFuture(ReconcileResult.created(new Secret()));
    });
    ArgumentCaptor<ConfigMap> metricsCaptor = ArgumentCaptor.forClass(ConfigMap.class);
    ArgumentCaptor<String> metricsNameCaptor = ArgumentCaptor.forClass(String.class);
    when(mockCmOps.reconcile(any(), anyString(), metricsNameCaptor.capture(), metricsCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    ArgumentCaptor<ConfigMap> logCaptor = ArgumentCaptor.forClass(ConfigMap.class);
    ArgumentCaptor<String> logNameCaptor = ArgumentCaptor.forClass(String.class);
    when(mockCmOps.reconcile(any(), anyString(), logNameCaptor.capture(), logCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    ConfigMap metricsCm = kafkaCluster.generateSharedConfigurationConfigMap(new MetricsAndLogging(metricsCM, null), Map.of(), Map.of(), false);
    when(mockCmOps.getAsync(kafkaNamespace, KafkaResources.kafkaMetricsAndLogConfigMapName(kafkaName))).thenReturn(Future.succeededFuture(metricsCm));
    when(mockCmOps.getAsync(kafkaNamespace, metricsCMName)).thenReturn(Future.succeededFuture(metricsCM));
    when(mockCmOps.getAsync(kafkaNamespace, differentMetricsCMName)).thenReturn(Future.succeededFuture(metricsCM));
    when(mockCmOps.getAsync(anyString(), eq(JmxTransResources.configMapName(kafkaName)))).thenReturn(Future.succeededFuture(new ConfigMapBuilder().withNewMetadata().withResourceVersion("123").endMetadata().build()));
    when(mockCmOps.listAsync(kafkaNamespace, kafkaCluster.getSelectorLabels())).thenReturn(Future.succeededFuture(List.of()));
    ArgumentCaptor<Route> routeCaptor = ArgumentCaptor.forClass(Route.class);
    ArgumentCaptor<String> routeNameCaptor = ArgumentCaptor.forClass(String.class);
    if (openShift) {
        when(mockRouteOps.reconcile(any(), eq(kafkaNamespace), routeNameCaptor.capture(), routeCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new Route())));
    }
    KafkaAssemblyOperator ops = new KafkaAssemblyOperator(vertx, new PlatformFeaturesAvailability(openShift, kubernetesVersion), certManager, passwordGenerator, supplier, config);
    // Now try to create a KafkaCluster based on this CM
    Checkpoint async = context.checkpoint();
    ops.createOrUpdate(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, kafkaNamespace, kafkaName), kafka).onComplete(context.succeeding(v -> context.verify(() -> {
        // We expect a headless and headful service
        Set<String> expectedServices = set(KafkaResources.zookeeperHeadlessServiceName(kafkaName), KafkaResources.zookeeperServiceName(kafkaName), KafkaResources.bootstrapServiceName(kafkaName), KafkaResources.brokersServiceName(kafkaName));
        if (kafkaListeners != null) {
            List<GenericKafkaListener> externalListeners = ListenersUtils.externalListeners(kafkaListeners);
            for (GenericKafkaListener listener : externalListeners) {
                expectedServices.add(ListenersUtils.backwardsCompatibleBootstrapServiceName(kafkaName, listener));
                for (int i = 0; i < kafkaCluster.getReplicas(); i++) {
                    expectedServices.add(ListenersUtils.backwardsCompatibleBrokerServiceName(kafkaName, i, listener));
                }
            }
        }
        List<Service> capturedServices = serviceCaptor.getAllValues();
        assertThat(capturedServices.stream().filter(Objects::nonNull).map(svc -> svc.getMetadata().getName()).collect(Collectors.toSet()).size(), is(expectedServices.size()));
        assertThat(capturedServices.stream().filter(Objects::nonNull).map(svc -> svc.getMetadata().getName()).collect(Collectors.toSet()), is(expectedServices));
        // Assertions on the statefulset
        List<StatefulSet> capturedSs = ssCaptor.getAllValues();
        // We expect a statefulSet for kafka and zookeeper...
        assertThat(capturedSs.stream().map(sts -> sts.getMetadata().getName()).collect(Collectors.toSet()), is(set(KafkaResources.kafkaStatefulSetName(kafkaName), KafkaResources.zookeeperStatefulSetName(kafkaName))));
        // expected Secrets with certificates
        assertThat(new TreeSet<>(secretsMap.keySet()), is(new TreeSet<>(expectedSecrets)));
        // Check PDBs
        assertThat(pdbCaptor.getAllValues(), hasSize(2));
        assertThat(pdbCaptor.getAllValues().stream().map(sts -> sts.getMetadata().getName()).collect(Collectors.toSet()), is(set(KafkaResources.kafkaStatefulSetName(kafkaName), KafkaResources.zookeeperStatefulSetName(kafkaName))));
        // Check PVCs
        assertThat(pvcCaptor.getAllValues(), hasSize(expectedPvcs.size()));
        assertThat(pvcCaptor.getAllValues().stream().map(pvc -> pvc.getMetadata().getName()).collect(Collectors.toSet()), is(expectedPvcs));
        for (PersistentVolumeClaim pvc : pvcCaptor.getAllValues()) {
            assertThat(pvc.getMetadata().getAnnotations(), hasKey(AbstractModel.ANNO_STRIMZI_IO_DELETE_CLAIM));
        }
        // Verify deleted routes
        if (openShift) {
            Set<String> expectedRoutes = set(KafkaResources.bootstrapServiceName(kafkaName));
            for (int i = 0; i < kafkaCluster.getReplicas(); i++) {
                expectedRoutes.add(KafkaResources.kafkaStatefulSetName(kafkaName) + "-" + i);
            }
            assertThat(captured(routeNameCaptor), is(expectedRoutes));
        } else {
            assertThat(routeNameCaptor.getAllValues(), hasSize(0));
        }
        async.flag();
    })));
}
Also used : RouteIngressBuilder(io.fabric8.openshift.api.model.RouteIngressBuilder) JmxTransQueryTemplateBuilder(io.strimzi.api.kafka.model.template.JmxTransQueryTemplateBuilder) ArgumentMatchers(org.mockito.ArgumentMatchers) KafkaExporterResources(io.strimzi.api.kafka.model.KafkaExporterResources) KafkaJmxOptions(io.strimzi.api.kafka.model.KafkaJmxOptions) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) AfterAll(org.junit.jupiter.api.AfterAll) PersistentClaimStorage(io.strimzi.api.kafka.model.storage.PersistentClaimStorage) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) RouteStatusBuilder(io.fabric8.openshift.api.model.RouteStatusBuilder) KafkaResources(io.strimzi.api.kafka.model.KafkaResources) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) AbstractModel(io.strimzi.operator.cluster.model.AbstractModel) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) KafkaJmxOptionsBuilder(io.strimzi.api.kafka.model.KafkaJmxOptionsBuilder) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) Set(java.util.Set) GenericKafkaListenerBuilder(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder) EphemeralStorage(io.strimzi.api.kafka.model.storage.EphemeralStorage) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) RouteOperator(io.strimzi.operator.common.operator.resource.RouteOperator) EntityOperator(io.strimzi.operator.cluster.model.EntityOperator) ClusterCa(io.strimzi.operator.cluster.model.ClusterCa) PersistentVolumeClaimBuilder(io.fabric8.kubernetes.api.model.PersistentVolumeClaimBuilder) EntityUserOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityUserOperatorSpecBuilder) ClusterOperatorConfig(io.strimzi.operator.cluster.ClusterOperatorConfig) StatefulSetBuilder(io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder) VertxTestContext(io.vertx.junit5.VertxTestContext) GenericKafkaListener(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListener) IngressOperator(io.strimzi.operator.common.operator.resource.IngressOperator) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) PersistentClaimStorageBuilder(io.strimzi.api.kafka.model.storage.PersistentClaimStorageBuilder) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) KafkaJmxAuthenticationPasswordBuilder(io.strimzi.api.kafka.model.KafkaJmxAuthenticationPasswordBuilder) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) JmxTransSpecBuilder(io.strimzi.api.kafka.model.JmxTransSpecBuilder) Mockito.times(org.mockito.Mockito.times) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) PvcOperator(io.strimzi.operator.common.operator.resource.PvcOperator) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) Reconciliation(io.strimzi.operator.common.Reconciliation) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Mockito.never(org.mockito.Mockito.never) KafkaListenerType(io.strimzi.api.kafka.model.listener.arraylistener.KafkaListenerType) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Storage(io.strimzi.api.kafka.model.storage.Storage) StrimziPodSetOperator(io.strimzi.operator.common.operator.resource.StrimziPodSetOperator) BiFunction(java.util.function.BiFunction) Timeout(io.vertx.junit5.Timeout) Matchers.hasKey(org.hamcrest.Matchers.hasKey) KafkaExporter(io.strimzi.operator.cluster.model.KafkaExporter) Route(io.fabric8.openshift.api.model.Route) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaExporterSpec(io.strimzi.api.kafka.model.KafkaExporterSpec) MethodSource(org.junit.jupiter.params.provider.MethodSource) ListenersUtils(io.strimzi.operator.cluster.model.ListenersUtils) Collections.emptyList(java.util.Collections.emptyList) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) ClientsCa(io.strimzi.operator.cluster.model.ClientsCa) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) CruiseControlResources(io.strimzi.api.kafka.model.CruiseControlResources) Objects(java.util.Objects) List(java.util.List) Labels(io.strimzi.operator.common.model.Labels) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) Secret(io.fabric8.kubernetes.api.model.Secret) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) MockCertManager(io.strimzi.operator.common.operator.MockCertManager) EntityOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityOperatorSpecBuilder) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) EntityTopicOperatorSpecBuilder(io.strimzi.api.kafka.model.EntityTopicOperatorSpecBuilder) KafkaStatus(io.strimzi.api.kafka.model.status.KafkaStatus) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) SingleVolumeStorage(io.strimzi.api.kafka.model.storage.SingleVolumeStorage) HashMap(java.util.HashMap) ZookeeperCluster(io.strimzi.operator.cluster.model.ZookeeperCluster) VolumeUtils(io.strimzi.operator.cluster.model.VolumeUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) MetricsAndLogging(io.strimzi.operator.common.MetricsAndLogging) HashSet(java.util.HashSet) JmxPrometheusExporterMetrics(io.strimzi.api.kafka.model.JmxPrometheusExporterMetrics) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaCluster(io.strimzi.operator.cluster.model.KafkaCluster) ClusterOperator(io.strimzi.operator.cluster.ClusterOperator) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) InlineLogging(io.strimzi.api.kafka.model.InlineLogging) TestUtils(io.strimzi.test.TestUtils) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) RouteStatus(io.fabric8.openshift.api.model.RouteStatus) JmxTransResources(io.strimzi.api.kafka.model.JmxTransResources) StatefulSetDiff(io.strimzi.operator.cluster.operator.resource.StatefulSetDiff) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) EntityOperatorSpec(io.strimzi.api.kafka.model.EntityOperatorSpec) CruiseControl(io.strimzi.operator.cluster.model.CruiseControl) Collections.emptyMap(java.util.Collections.emptyMap) NodeOperator(io.strimzi.operator.common.operator.resource.NodeOperator) JmxTransOutputDefinitionTemplateBuilder(io.strimzi.api.kafka.model.template.JmxTransOutputDefinitionTemplateBuilder) TestUtils.set(io.strimzi.test.TestUtils.set) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) Kafka(io.strimzi.api.kafka.model.Kafka) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) KafkaCluster(io.strimzi.operator.cluster.model.KafkaCluster) StrimziPodSetOperator(io.strimzi.operator.common.operator.resource.StrimziPodSetOperator) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RouteStatus(io.fabric8.openshift.api.model.RouteStatus) PvcOperator(io.strimzi.operator.common.operator.resource.PvcOperator) GenericKafkaListener(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListener) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) TreeSet(java.util.TreeSet) NodeOperator(io.strimzi.operator.common.operator.resource.NodeOperator) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) Route(io.fabric8.openshift.api.model.Route) HashSet(java.util.HashSet) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) MetricsAndLogging(io.strimzi.operator.common.MetricsAndLogging) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) Labels(io.strimzi.operator.common.model.Labels) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Secret(io.fabric8.kubernetes.api.model.Secret) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Objects(java.util.Objects) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) RouteOperator(io.strimzi.operator.common.operator.resource.RouteOperator) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) EntityOperator(io.strimzi.operator.cluster.model.EntityOperator) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) ClusterOperatorConfig(io.strimzi.operator.cluster.ClusterOperatorConfig) Kafka(io.strimzi.api.kafka.model.Kafka) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) StatefulSetBuilder(io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) Reconciliation(io.strimzi.operator.common.Reconciliation) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Service(io.fabric8.kubernetes.api.model.Service) ZookeeperCluster(io.strimzi.operator.cluster.model.ZookeeperCluster) AtomicReference(java.util.concurrent.atomic.AtomicReference) RouteStatusBuilder(io.fabric8.openshift.api.model.RouteStatusBuilder) Checkpoint(io.vertx.junit5.Checkpoint) IngressOperator(io.strimzi.operator.common.operator.resource.IngressOperator) Checkpoint(io.vertx.junit5.Checkpoint) RouteIngressBuilder(io.fabric8.openshift.api.model.RouteIngressBuilder) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator)

Example 33 with PasswordGenerator

use of io.strimzi.operator.common.PasswordGenerator in project strimzi by strimzi.

the class KafkaBridgeAssemblyOperatorTest method testCreateOrUpdateWithNoDiffCausesNoChanges.

@Test
public void testCreateOrUpdateWithNoDiffCausesNoChanges(VertxTestContext context) {
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
    var mockBridgeOps = supplier.kafkaBridgeOperator;
    DeploymentOperator mockDcOps = supplier.deploymentOperations;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    String kbName = "foo";
    String kbNamespace = "test";
    KafkaBridge kb = ResourceUtils.createKafkaBridge(kbNamespace, kbName, image, 1, BOOTSTRAP_SERVERS, KAFKA_BRIDGE_PRODUCER_SPEC, KAFKA_BRIDGE_CONSUMER_SPEC, KAFKA_BRIDGE_HTTP_SPEC, true);
    KafkaBridgeCluster bridge = KafkaBridgeCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kb, VERSIONS);
    when(mockBridgeOps.get(kbNamespace, kbName)).thenReturn(kb);
    when(mockBridgeOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kb));
    when(mockBridgeOps.updateStatusAsync(any(), any(KafkaBridge.class))).thenReturn(Future.succeededFuture());
    when(mockServiceOps.get(kbNamespace, bridge.getName())).thenReturn(bridge.generateService());
    when(mockDcOps.get(kbNamespace, bridge.getName())).thenReturn(bridge.generateDeployment(Map.of(), true, null, null));
    when(mockDcOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDcOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<String> serviceNameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class);
    when(mockServiceOps.reconcile(any(), eq(kbNamespace), serviceNameCaptor.capture(), serviceCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<String> dcNameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Deployment> dcCaptor = ArgumentCaptor.forClass(Deployment.class);
    when(mockDcOps.reconcile(any(), eq(kbNamespace), dcNameCaptor.capture(), dcCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<String> dcScaleUpNameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Integer> dcScaleUpReplicasCaptor = ArgumentCaptor.forClass(Integer.class);
    when(mockDcOps.scaleUp(any(), eq(kbNamespace), dcScaleUpNameCaptor.capture(), dcScaleUpReplicasCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<String> dcScaleDownNameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Integer> dcScaleDownReplicasCaptor = ArgumentCaptor.forClass(Integer.class);
    when(mockDcOps.scaleDown(any(), eq(kbNamespace), dcScaleDownNameCaptor.capture(), dcScaleDownReplicasCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<PodDisruptionBudget> pdbCaptor = ArgumentCaptor.forClass(PodDisruptionBudget.class);
    when(mockPdbOps.reconcile(any(), anyString(), any(), pdbCaptor.capture())).thenReturn(Future.succeededFuture());
    when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    KafkaBridgeAssemblyOperator ops = new KafkaBridgeAssemblyOperator(vertx, new PlatformFeaturesAvailability(true, kubernetesVersion), new MockCertManager(), new PasswordGenerator(10, "a", "a"), supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS));
    Checkpoint async = context.checkpoint();
    ops.createOrUpdate(new Reconciliation("test-trigger", KafkaBridge.RESOURCE_KIND, kbNamespace, kbName), kb).onComplete(context.succeeding(v -> context.verify(() -> {
        // Verify service
        List<Service> capturedServices = serviceCaptor.getAllValues();
        assertThat(capturedServices, hasSize(1));
        // Verify Deployment Config
        List<Deployment> capturedDc = dcCaptor.getAllValues();
        assertThat(capturedDc, hasSize(1));
        // Verify PodDisruptionBudget
        List<PodDisruptionBudget> capturedPdb = pdbCaptor.getAllValues();
        assertThat(capturedPdb, hasSize(1));
        PodDisruptionBudget pdb = capturedPdb.get(0);
        assertThat(pdb.getMetadata().getName(), is(bridge.getName()));
        assertThat(pdb, is(bridge.generatePodDisruptionBudget()));
        // Verify scaleDown / scaleUp were not called
        assertThat(dcScaleDownNameCaptor.getAllValues(), hasSize(1));
        assertThat(dcScaleUpNameCaptor.getAllValues(), hasSize(1));
        async.flag();
    })));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Annotations(io.strimzi.operator.common.Annotations) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) AfterAll(org.junit.jupiter.api.AfterAll) KafkaBridge(io.strimzi.api.kafka.model.KafkaBridge) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaBridgeConsumerSpec(io.strimzi.api.kafka.model.KafkaBridgeConsumerSpec) AbstractModel(io.strimzi.operator.cluster.model.AbstractModel) KafkaBridgeProducerSpec(io.strimzi.api.kafka.model.KafkaBridgeProducerSpec) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Set(java.util.Set) VertxExtension(io.vertx.junit5.VertxExtension) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Future(io.vertx.core.Future) KafkaBridgeHttpConfig(io.strimzi.api.kafka.model.KafkaBridgeHttpConfig) Test(org.junit.jupiter.api.Test) List(java.util.List) Labels(io.strimzi.operator.common.model.Labels) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) MockCertManager(io.strimzi.operator.common.operator.MockCertManager) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) HashMap(java.util.HashMap) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) TestUtils(io.strimzi.test.TestUtils) KafkaBridgeBuilder(io.strimzi.api.kafka.model.KafkaBridgeBuilder) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) KafkaBridgeResources(io.strimzi.api.kafka.model.KafkaBridgeResources) Promise(io.vertx.core.Promise) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) Mockito.when(org.mockito.Mockito.when) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) KafkaBridgeCluster(io.strimzi.operator.cluster.model.KafkaBridgeCluster) Mockito.verify(org.mockito.Mockito.verify) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) KafkaBridgeStatus(io.strimzi.api.kafka.model.status.KafkaBridgeStatus) Reconciliation(io.strimzi.operator.common.Reconciliation) Mockito.never(org.mockito.Mockito.never) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) Reconciliation(io.strimzi.operator.common.Reconciliation) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaBridgeCluster(io.strimzi.operator.cluster.model.KafkaBridgeCluster) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) KafkaBridge(io.strimzi.api.kafka.model.KafkaBridge) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) Service(io.fabric8.kubernetes.api.model.Service) Checkpoint(io.vertx.junit5.Checkpoint) MockCertManager(io.strimzi.operator.common.operator.MockCertManager) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) Test(org.junit.jupiter.api.Test)

Example 34 with PasswordGenerator

use of io.strimzi.operator.common.PasswordGenerator in project strimzi by strimzi.

the class KafkaClusterTest method generateBrokerSecret.

private Secret generateBrokerSecret(Set<String> externalBootstrapAddress, Map<Integer, Set<String>> externalAddresses) {
    ClusterCa clusterCa = new ClusterCa(Reconciliation.DUMMY_RECONCILIATION, new OpenSslCertManager(), new PasswordGenerator(10, "a", "a"), cluster, null, null);
    clusterCa.createRenewOrReplace(namespace, cluster, emptyMap(), emptyMap(), emptyMap(), null, true);
    ClientsCa clientsCa = new ClientsCa(Reconciliation.DUMMY_RECONCILIATION, new OpenSslCertManager(), new PasswordGenerator(10, "a", "a"), null, null, null, null, 365, 30, true, CertificateExpirationPolicy.RENEW_CERTIFICATE);
    clientsCa.createRenewOrReplace(namespace, cluster, emptyMap(), emptyMap(), emptyMap(), null, true);
    return kc.generateCertificatesSecret(clusterCa, clientsCa, externalBootstrapAddress, externalAddresses, true);
}
Also used : OpenSslCertManager(io.strimzi.certs.OpenSslCertManager) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator)

Example 35 with PasswordGenerator

use of io.strimzi.operator.common.PasswordGenerator in project strimzi by strimzi.

the class CertificateRenewalTest method reconcileCa.

private Future<ArgumentCaptor<Secret>> reconcileCa(Vertx vertx, Kafka kafka, Supplier<Date> dateSupplier) {
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
    SecretOperator secretOps = supplier.secretOperations;
    DeploymentOperator deploymentOps = supplier.deploymentOperations;
    StatefulSetOperator stsOps = supplier.stsOperations;
    PodOperator podOps = supplier.podOperations;
    when(secretOps.list(eq(NAMESPACE), any())).thenAnswer(invocation -> {
        Map<String, String> requiredLabels = ((Labels) invocation.getArgument(1)).toMap();
        return secrets.stream().filter(s -> {
            Map<String, String> labels = s.getMetadata().getLabels();
            labels.keySet().retainAll(requiredLabels.keySet());
            return labels.equals(requiredLabels);
        }).collect(Collectors.toList());
    });
    ArgumentCaptor<Secret> c = ArgumentCaptor.forClass(Secret.class);
    when(secretOps.reconcile(any(), eq(NAMESPACE), eq(AbstractModel.clusterCaCertSecretName(NAME)), c.capture())).thenAnswer(i -> Future.succeededFuture(ReconcileResult.noop(i.getArgument(0))));
    when(secretOps.reconcile(any(), eq(NAMESPACE), eq(AbstractModel.clusterCaKeySecretName(NAME)), c.capture())).thenAnswer(i -> Future.succeededFuture(ReconcileResult.noop(i.getArgument(0))));
    when(secretOps.reconcile(any(), eq(NAMESPACE), eq(KafkaResources.clientsCaCertificateSecretName(NAME)), c.capture())).thenAnswer(i -> Future.succeededFuture(ReconcileResult.noop(i.getArgument(0))));
    when(secretOps.reconcile(any(), eq(NAMESPACE), eq(KafkaResources.clientsCaKeySecretName(NAME)), c.capture())).thenAnswer(i -> Future.succeededFuture(ReconcileResult.noop(i.getArgument(0))));
    when(secretOps.reconcile(any(), eq(NAMESPACE), eq(ClusterOperator.secretName(NAME)), any())).thenAnswer(i -> Future.succeededFuture(ReconcileResult.created(i.getArgument(0))));
    when(deploymentOps.getAsync(eq(NAMESPACE), any())).thenReturn(Future.succeededFuture());
    when(stsOps.getAsync(eq(NAMESPACE), any())).thenReturn(Future.succeededFuture());
    when(podOps.listAsync(eq(NAMESPACE), any(Labels.class))).thenReturn(Future.succeededFuture(List.of()));
    KafkaAssemblyOperator op = new KafkaAssemblyOperator(vertx, new PlatformFeaturesAvailability(false, KubernetesVersion.V1_16), certManager, passwordGenerator, supplier, ResourceUtils.dummyClusterOperatorConfig(1L));
    Reconciliation reconciliation = new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, NAME);
    Promise<ArgumentCaptor<Secret>> reconcileCasComplete = Promise.promise();
    op.new ReconciliationState(reconciliation, kafka).reconcileCas(dateSupplier).onComplete(ar -> {
        // If failed then return the throwable of the reconcileCas
        if (ar.succeeded()) {
            reconcileCasComplete.complete(c);
        } else {
            reconcileCasComplete.fail(ar.cause());
        }
    });
    return reconcileCasComplete.future();
}
Also used : X509Certificate(java.security.cert.X509Certificate) CoreMatchers.is(org.hamcrest.CoreMatchers.is) BeforeEach(org.junit.jupiter.api.BeforeEach) CertificateFactory(java.security.cert.CertificateFactory) CA_KEY(io.strimzi.operator.cluster.model.Ca.CA_KEY) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) KeyStoreException(java.security.KeyStoreException) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ByteArrayInputStream(java.io.ByteArrayInputStream) Collections.singleton(java.util.Collections.singleton) KafkaResources(io.strimzi.api.kafka.model.KafkaResources) Ca(io.strimzi.operator.cluster.model.Ca) Map(java.util.Map) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) Path(java.nio.file.Path) AbstractModel(io.strimzi.operator.cluster.model.AbstractModel) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) ModelUtils(io.strimzi.operator.cluster.model.ModelUtils) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) KeyStore(java.security.KeyStore) VertxExtension(io.vertx.junit5.VertxExtension) Instant(java.time.Instant) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Subject(io.strimzi.certs.Subject) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) Labels(io.strimzi.operator.common.model.Labels) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CA_STORE_PASSWORD(io.strimzi.operator.cluster.model.Ca.CA_STORE_PASSWORD) Secret(io.fabric8.kubernetes.api.model.Secret) CA_STORE(io.strimzi.operator.cluster.model.Ca.CA_STORE) Checkpoint(io.vertx.junit5.Checkpoint) ClusterCa(io.strimzi.operator.cluster.model.ClusterCa) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Matchers.aMapWithSize(org.hamcrest.Matchers.aMapWithSize) CoreMatchers.not(org.hamcrest.CoreMatchers.not) OwnerReference(io.fabric8.kubernetes.api.model.OwnerReference) CertAndKey(io.strimzi.certs.CertAndKey) Supplier(java.util.function.Supplier) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) ArrayList(java.util.ArrayList) ArgumentCaptor(org.mockito.ArgumentCaptor) ClusterOperator(io.strimzi.operator.cluster.ClusterOperator) TestUtils(io.strimzi.test.TestUtils) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CertificateExpirationPolicy(io.strimzi.api.kafka.model.CertificateExpirationPolicy) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) CertificateAuthority(io.strimzi.api.kafka.model.CertificateAuthority) Files(java.nio.file.Files) InvalidResourceException(io.strimzi.operator.cluster.model.InvalidResourceException) Promise(io.vertx.core.Promise) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TestUtils.set(io.strimzi.test.TestUtils.set) Mockito.when(org.mockito.Mockito.when) Reconciliation(io.strimzi.operator.common.Reconciliation) CA_CRT(io.strimzi.operator.cluster.model.Ca.CA_CRT) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) Kafka(io.strimzi.api.kafka.model.Kafka) OpenSslCertManager(io.strimzi.certs.OpenSslCertManager) CertificateAuthorityBuilder(io.strimzi.api.kafka.model.CertificateAuthorityBuilder) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ArgumentCaptor(org.mockito.ArgumentCaptor) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Labels(io.strimzi.operator.common.model.Labels) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) StatefulSetOperator(io.strimzi.operator.cluster.operator.resource.StatefulSetOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Secret(io.fabric8.kubernetes.api.model.Secret) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Reconciliation(io.strimzi.operator.common.Reconciliation) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) Map(java.util.Map)

Aggregations

PasswordGenerator (io.strimzi.operator.common.PasswordGenerator)136 ResourceOperatorSupplier (io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier)110 Reconciliation (io.strimzi.operator.common.Reconciliation)104 PlatformFeaturesAvailability (io.strimzi.operator.PlatformFeaturesAvailability)102 Future (io.vertx.core.Future)96 ResourceUtils (io.strimzi.operator.cluster.ResourceUtils)94 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)94 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)94 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)94 Mockito.when (org.mockito.Mockito.when)94 KafkaVersionTestUtils (io.strimzi.operator.cluster.KafkaVersionTestUtils)92 KubernetesVersion (io.strimzi.operator.KubernetesVersion)90 Vertx (io.vertx.core.Vertx)90 CoreMatchers.is (org.hamcrest.CoreMatchers.is)88 AfterAll (org.junit.jupiter.api.AfterAll)88 BeforeAll (org.junit.jupiter.api.BeforeAll)88 Test (org.junit.jupiter.api.Test)86 ArgumentCaptor (org.mockito.ArgumentCaptor)86 MockCertManager (io.strimzi.operator.common.operator.MockCertManager)84 Checkpoint (io.vertx.junit5.Checkpoint)82