Search in sources :

Example 21 with NetworkPolicy

use of com.google.container.v1.NetworkPolicy in project strimzi by strimzi.

the class KafkaConnectBuildAssemblyOperatorOpenShiftTest method testUpdateWithoutRebuildOnOpenShift.

@Test
public void testUpdateWithoutRebuildOnOpenShift(VertxTestContext context) {
    Plugin plugin1 = new PluginBuilder().withName("plugin1").withArtifacts(new JarArtifactBuilder().withUrl("https://my-domain.tld/my.jar").build()).build();
    KafkaConnect kc = new KafkaConnectBuilder().withNewMetadata().withName(NAME).withNamespace(NAMESPACE).endMetadata().withNewSpec().withReplicas(1).withBootstrapServers("my-cluster-kafka-bootstrap:9092").withNewBuild().withNewDockerOutput().withImage(OUTPUT_IMAGE).withPushSecret("my-docker-credentials").endDockerOutput().withPlugins(plugin1).endBuild().endSpec().build();
    KafkaConnectCluster connect = KafkaConnectCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kc, VERSIONS);
    KafkaConnectBuild build = KafkaConnectBuild.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kc, VERSIONS);
    // Prepare and get mocks
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
    CrdOperator mockConnectOps = supplier.connectOperator;
    DeploymentOperator mockDepOps = supplier.deploymentOperations;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    PodDisruptionBudgetV1Beta1Operator mockPdbOpsV1Beta1 = supplier.podDisruptionBudgetV1Beta1Operator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    NetworkPolicyOperator mockNetPolOps = supplier.networkPolicyOperator;
    PodOperator mockPodOps = supplier.podOperations;
    BuildConfigOperator mockBcOps = supplier.buildConfigOperations;
    BuildOperator mockBuildOps = supplier.buildOperations;
    SecretOperator mockSecretOps = supplier.secretOperations;
    CrdOperator<KubernetesClient, KafkaConnector, KafkaConnectorList> mockConnectorOps = supplier.kafkaConnectorOperator;
    // Mock KafkaConnector ops
    when(mockConnectorOps.listAsync(anyString(), any(Optional.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Mock KafkaConnect ops
    when(mockConnectOps.get(NAMESPACE, NAME)).thenReturn(kc);
    when(mockConnectOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kc));
    // Mock and capture service ops
    ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class);
    when(mockServiceOps.reconcile(any(), anyString(), anyString(), serviceCaptor.capture())).thenReturn(Future.succeededFuture());
    // Mock and capture deployment ops
    ArgumentCaptor<Deployment> depCaptor = ArgumentCaptor.forClass(Deployment.class);
    when(mockDepOps.reconcile(any(), anyString(), anyString(), depCaptor.capture())).thenReturn(Future.succeededFuture());
    when(mockDepOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.deploymentName(NAME)))).thenAnswer(inv -> {
        Deployment dep = connect.generateDeployment(emptyMap(), false, null, null);
        dep.getSpec().getTemplate().getMetadata().getAnnotations().put(Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, build.generateDockerfile().hashStub() + OUTPUT_IMAGE_HASH_STUB);
        dep.getSpec().getTemplate().getSpec().getContainers().get(0).setImage("my-connect-build@sha256:blablabla");
        return Future.succeededFuture(dep);
    });
    when(mockDepOps.scaleUp(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDepOps.scaleDown(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockSecretOps.reconcile(any(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    // Mock and capture CM ops
    when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    // Mock and capture Pod ops
    when(mockPodOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildPodName(NAME)), eq(null))).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    // Mock and capture BuildConfig ops
    ArgumentCaptor<BuildConfig> buildConfigCaptor = ArgumentCaptor.forClass(BuildConfig.class);
    when(mockBcOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildConfigName(NAME)), buildConfigCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    // Mock and capture NP ops
    when(mockNetPolOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.deploymentName(NAME)), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new NetworkPolicy())));
    // Mock and capture PDB ops
    when(mockPdbOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture());
    when(mockPdbOpsV1Beta1.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture());
    // Mock and capture KafkaConnect ops for status update
    ArgumentCaptor<KafkaConnect> connectCaptor = ArgumentCaptor.forClass(KafkaConnect.class);
    when(mockConnectOps.updateStatusAsync(any(), connectCaptor.capture())).thenReturn(Future.succeededFuture());
    // Mock KafkaConnect API client
    KafkaConnectApi mockConnectClient = mock(KafkaConnectApi.class);
    // Prepare and run reconciliation
    KafkaConnectAssemblyOperator ops = new KafkaConnectAssemblyOperator(vertx, new PlatformFeaturesAvailability(true, kubernetesVersion), supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS), x -> mockConnectClient);
    Checkpoint async = context.checkpoint();
    ops.reconcile(new Reconciliation("test-trigger", KafkaConnect.RESOURCE_KIND, NAMESPACE, NAME)).onComplete(context.succeeding(v -> context.verify(() -> {
        // Verify Deployment
        List<Deployment> capturedDeps = depCaptor.getAllValues();
        assertThat(capturedDeps, hasSize(1));
        Deployment dep = capturedDeps.get(0);
        assertThat(dep.getMetadata().getName(), is(connect.getName()));
        assertThat(dep.getSpec().getTemplate().getSpec().getContainers().get(0).getImage(), is("my-connect-build@sha256:blablabla"));
        assertThat(Annotations.stringAnnotation(dep.getSpec().getTemplate(), Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, null), is(build.generateDockerfile().hashStub() + OUTPUT_IMAGE_HASH_STUB));
        // Verify BuildConfig
        List<BuildConfig> capturedBcs = buildConfigCaptor.getAllValues();
        assertThat(capturedBcs, hasSize(0));
        // Verify status
        List<KafkaConnect> capturedConnects = connectCaptor.getAllValues();
        assertThat(capturedConnects, hasSize(1));
        KafkaConnectStatus connectStatus = capturedConnects.get(0).getStatus();
        assertThat(connectStatus.getConditions().get(0).getStatus(), is("True"));
        assertThat(connectStatus.getConditions().get(0).getType(), is("Ready"));
        async.flag();
    })));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Annotations(io.strimzi.operator.common.Annotations) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) BeforeAll(org.junit.jupiter.api.BeforeAll) BuildOperator(io.strimzi.operator.common.operator.resource.BuildOperator) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Build(io.fabric8.openshift.api.model.Build) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) Collections.emptyList(java.util.Collections.emptyList) KafkaConnectBuild(io.strimzi.operator.cluster.model.KafkaConnectBuild) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) KafkaConnectBuilder(io.strimzi.api.kafka.model.KafkaConnectBuilder) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) List(java.util.List) Plugin(io.strimzi.api.kafka.model.connect.build.Plugin) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) BuildRequest(io.fabric8.openshift.api.model.BuildRequest) PluginBuilder(io.strimzi.api.kafka.model.connect.build.PluginBuilder) BuildBuilder(io.fabric8.openshift.api.model.BuildBuilder) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) BiPredicate(java.util.function.BiPredicate) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Collections.emptyMap(java.util.Collections.emptyMap) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) Mockito.when(org.mockito.Mockito.when) JarArtifactBuilder(io.strimzi.api.kafka.model.connect.build.JarArtifactBuilder) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) Reconciliation(io.strimzi.operator.common.Reconciliation) Util(io.strimzi.operator.common.Util) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) KafkaConnectResources(io.strimzi.api.kafka.model.KafkaConnectResources) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) PluginBuilder(io.strimzi.api.kafka.model.connect.build.PluginBuilder) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) JarArtifactBuilder(io.strimzi.api.kafka.model.connect.build.JarArtifactBuilder) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) KafkaConnectBuilder(io.strimzi.api.kafka.model.KafkaConnectBuilder) BuildOperator(io.strimzi.operator.common.operator.resource.BuildOperator) Reconciliation(io.strimzi.operator.common.Reconciliation) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaConnectBuild(io.strimzi.operator.cluster.model.KafkaConnectBuild) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Optional(java.util.Optional) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) Service(io.fabric8.kubernetes.api.model.Service) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) Checkpoint(io.vertx.junit5.Checkpoint) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) Plugin(io.strimzi.api.kafka.model.connect.build.Plugin) Test(org.junit.jupiter.api.Test)

Example 22 with NetworkPolicy

use of com.google.container.v1.NetworkPolicy in project strimzi by strimzi.

the class KafkaConnectBuildAssemblyOperatorOpenShiftTest method testRestartPreviousBuildOnOpenShift.

@SuppressWarnings({ "checkstyle:MethodLength" })
@Test
public void testRestartPreviousBuildOnOpenShift(VertxTestContext context) {
    Plugin plugin1 = new PluginBuilder().withName("plugin1").withArtifacts(new JarArtifactBuilder().withUrl("https://my-domain.tld/my.jar").build()).build();
    Plugin plugin2 = new PluginBuilder().withName("plugin2").withArtifacts(new JarArtifactBuilder().withUrl("https://my-domain.tld/my2.jar").build()).build();
    KafkaConnect oldKc = new KafkaConnectBuilder().withNewMetadata().withName(NAME).withNamespace(NAMESPACE).endMetadata().withNewSpec().withReplicas(1).withBootstrapServers("my-cluster-kafka-bootstrap:9092").withNewBuild().withNewDockerOutput().withImage(OUTPUT_IMAGE).withPushSecret("my-docker-credentials").endDockerOutput().withPlugins(plugin1).endBuild().endSpec().build();
    KafkaConnectCluster oldConnect = KafkaConnectCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, oldKc, VERSIONS);
    KafkaConnectBuild oldBuild = KafkaConnectBuild.fromCrd(Reconciliation.DUMMY_RECONCILIATION, oldKc, VERSIONS);
    KafkaConnect kc = new KafkaConnectBuilder(oldKc).editSpec().editBuild().withPlugins(plugin1, plugin2).endBuild().endSpec().build();
    KafkaConnectBuild build = KafkaConnectBuild.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kc, VERSIONS);
    // Prepare and get mocks
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
    CrdOperator mockConnectOps = supplier.connectOperator;
    DeploymentOperator mockDepOps = supplier.deploymentOperations;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    PodDisruptionBudgetV1Beta1Operator mockPdbOpsV1Beta1 = supplier.podDisruptionBudgetV1Beta1Operator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    NetworkPolicyOperator mockNetPolOps = supplier.networkPolicyOperator;
    PodOperator mockPodOps = supplier.podOperations;
    BuildConfigOperator mockBcOps = supplier.buildConfigOperations;
    BuildOperator mockBuildOps = supplier.buildOperations;
    SecretOperator mockSecretOps = supplier.secretOperations;
    CrdOperator<KubernetesClient, KafkaConnector, KafkaConnectorList> mockConnectorOps = supplier.kafkaConnectorOperator;
    // Mock KafkaConnector ops
    when(mockConnectorOps.listAsync(anyString(), any(Optional.class))).thenReturn(Future.succeededFuture(emptyList()));
    // Mock KafkaConnect ops
    when(mockConnectOps.get(NAMESPACE, NAME)).thenReturn(kc);
    when(mockConnectOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kc));
    // Mock and capture service ops
    ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class);
    when(mockServiceOps.reconcile(any(), anyString(), anyString(), serviceCaptor.capture())).thenReturn(Future.succeededFuture());
    // Mock and capture deployment ops
    ArgumentCaptor<Deployment> depCaptor = ArgumentCaptor.forClass(Deployment.class);
    when(mockDepOps.reconcile(any(), anyString(), anyString(), depCaptor.capture())).thenReturn(Future.succeededFuture());
    when(mockDepOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.deploymentName(NAME)))).thenAnswer(inv -> {
        Deployment dep = oldConnect.generateDeployment(emptyMap(), false, null, null);
        dep.getSpec().getTemplate().getMetadata().getAnnotations().put(Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, oldBuild.generateDockerfile().hashStub());
        dep.getSpec().getTemplate().getSpec().getContainers().get(0).setImage("my-connect-build@sha256:olddigest");
        return Future.succeededFuture(dep);
    });
    when(mockDepOps.scaleUp(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDepOps.scaleDown(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDepOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDepOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockSecretOps.reconcile(any(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    // Mock and capture CM ops
    when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    // Mock and capture Pod ops
    when(mockPodOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildPodName(NAME)), eq(null))).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    // Mock and capture Build ops
    Build oldBuilder = new BuildBuilder().withNewMetadata().withNamespace(NAMESPACE).withName(KafkaConnectResources.buildName(NAME, 1L)).withAnnotations(singletonMap(Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, oldBuild.generateDockerfile().hashStub())).endMetadata().withNewSpec().endSpec().withNewStatus().withPhase("Running").endStatus().build();
    Build newBuilder = new BuildBuilder().withNewMetadata().withNamespace(NAMESPACE).withName(KafkaConnectResources.buildName(NAME, 2L)).withAnnotations(singletonMap(Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, build.generateDockerfile().hashStub())).endMetadata().withNewSpec().endSpec().withNewStatus().withPhase("Complete").withNewOutputDockerImageReference(OUTPUT_IMAGE).withNewOutput().withNewTo().withImageDigest("sha256:blablabla").endTo().endOutput().endStatus().build();
    when(mockBuildOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.buildName(NAME, 1L)))).thenReturn(Future.succeededFuture(oldBuilder));
    when(mockBuildOps.waitFor(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildName(NAME, 2L)), anyString(), anyLong(), anyLong(), any(BiPredicate.class))).thenReturn(Future.succeededFuture());
    when(mockBuildOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.buildName(NAME, 2L)))).thenReturn(Future.succeededFuture(newBuilder));
    // Mock and capture BuildConfig ops
    ArgumentCaptor<BuildConfig> buildConfigCaptor = ArgumentCaptor.forClass(BuildConfig.class);
    when(mockBcOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildConfigName(NAME)), buildConfigCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    BuildConfig oldBuildConfig = new BuildConfigBuilder(oldBuild.generateBuildConfig(oldBuild.generateDockerfile())).withNewStatus().withLastVersion(1L).endStatus().build();
    when(mockBcOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.buildConfigName(NAME)))).thenReturn(Future.succeededFuture(oldBuildConfig));
    ArgumentCaptor<BuildRequest> buildRequestCaptor = ArgumentCaptor.forClass(BuildRequest.class);
    when(mockBcOps.startBuild(eq(NAMESPACE), eq(KafkaConnectResources.buildConfigName(NAME)), buildRequestCaptor.capture())).thenReturn(Future.succeededFuture(newBuilder));
    // Mock and capture NP ops
    when(mockNetPolOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.deploymentName(NAME)), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new NetworkPolicy())));
    // Mock and capture PDB ops
    when(mockPdbOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture());
    when(mockPdbOpsV1Beta1.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture());
    // Mock and capture KafkaConnect ops for status update
    ArgumentCaptor<KafkaConnect> connectCaptor = ArgumentCaptor.forClass(KafkaConnect.class);
    when(mockConnectOps.updateStatusAsync(any(), connectCaptor.capture())).thenReturn(Future.succeededFuture());
    // Mock KafkaConnect API client
    KafkaConnectApi mockConnectClient = mock(KafkaConnectApi.class);
    // Prepare and run reconciliation
    KafkaConnectAssemblyOperator ops = new KafkaConnectAssemblyOperator(vertx, new PlatformFeaturesAvailability(true, kubernetesVersion), supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS), x -> mockConnectClient);
    KafkaConnectCluster connect = KafkaConnectCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kc, VERSIONS);
    Checkpoint async = context.checkpoint();
    ops.reconcile(new Reconciliation("test-trigger", KafkaConnect.RESOURCE_KIND, NAMESPACE, NAME)).onComplete(context.succeeding(v -> context.verify(() -> {
        // Verify Deployment
        List<Deployment> capturedDeps = depCaptor.getAllValues();
        assertThat(capturedDeps, hasSize(1));
        Deployment dep = capturedDeps.get(0);
        assertThat(dep.getMetadata().getName(), is(connect.getName()));
        assertThat(dep.getSpec().getTemplate().getSpec().getContainers().get(0).getImage(), is("my-connect-build@sha256:blablabla"));
        assertThat(Annotations.stringAnnotation(dep.getSpec().getTemplate(), Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, null), is(build.generateDockerfile().hashStub() + OUTPUT_IMAGE_HASH_STUB));
        // Verify BuildConfig
        List<BuildConfig> capturedBcs = buildConfigCaptor.getAllValues();
        assertThat(capturedBcs, hasSize(1));
        BuildConfig buildConfig = capturedBcs.get(0);
        assertThat(buildConfig.getSpec().getSource().getDockerfile(), is(build.generateDockerfile().getDockerfile()));
        // Verify status
        List<KafkaConnect> capturedConnects = connectCaptor.getAllValues();
        assertThat(capturedConnects, hasSize(1));
        KafkaConnectStatus connectStatus = capturedConnects.get(0).getStatus();
        assertThat(connectStatus.getConditions().get(0).getStatus(), is("True"));
        assertThat(connectStatus.getConditions().get(0).getType(), is("Ready"));
        async.flag();
    })));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Annotations(io.strimzi.operator.common.Annotations) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) BeforeAll(org.junit.jupiter.api.BeforeAll) BuildOperator(io.strimzi.operator.common.operator.resource.BuildOperator) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Build(io.fabric8.openshift.api.model.Build) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) Collections.emptyList(java.util.Collections.emptyList) KafkaConnectBuild(io.strimzi.operator.cluster.model.KafkaConnectBuild) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) KafkaConnectBuilder(io.strimzi.api.kafka.model.KafkaConnectBuilder) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) List(java.util.List) Plugin(io.strimzi.api.kafka.model.connect.build.Plugin) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) BuildRequest(io.fabric8.openshift.api.model.BuildRequest) PluginBuilder(io.strimzi.api.kafka.model.connect.build.PluginBuilder) BuildBuilder(io.fabric8.openshift.api.model.BuildBuilder) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) BiPredicate(java.util.function.BiPredicate) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Collections.emptyMap(java.util.Collections.emptyMap) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) Mockito.when(org.mockito.Mockito.when) JarArtifactBuilder(io.strimzi.api.kafka.model.connect.build.JarArtifactBuilder) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) Reconciliation(io.strimzi.operator.common.Reconciliation) Util(io.strimzi.operator.common.Util) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) KafkaConnectResources(io.strimzi.api.kafka.model.KafkaConnectResources) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) PluginBuilder(io.strimzi.api.kafka.model.connect.build.PluginBuilder) BuildConfigBuilder(io.fabric8.openshift.api.model.BuildConfigBuilder) KafkaConnectBuilder(io.strimzi.api.kafka.model.KafkaConnectBuilder) BuildOperator(io.strimzi.operator.common.operator.resource.BuildOperator) Build(io.fabric8.openshift.api.model.Build) KafkaConnectBuild(io.strimzi.operator.cluster.model.KafkaConnectBuild) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) Optional(java.util.Optional) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) BuildRequest(io.fabric8.openshift.api.model.BuildRequest) BuildBuilder(io.fabric8.openshift.api.model.BuildBuilder) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) BiPredicate(java.util.function.BiPredicate) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) JarArtifactBuilder(io.strimzi.api.kafka.model.connect.build.JarArtifactBuilder) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) Reconciliation(io.strimzi.operator.common.Reconciliation) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) KafkaConnectBuild(io.strimzi.operator.cluster.model.KafkaConnectBuild) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) Service(io.fabric8.kubernetes.api.model.Service) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) Checkpoint(io.vertx.junit5.Checkpoint) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) Plugin(io.strimzi.api.kafka.model.connect.build.Plugin) Test(org.junit.jupiter.api.Test)

Example 23 with NetworkPolicy

use of com.google.container.v1.NetworkPolicy 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 24 with NetworkPolicy

use of com.google.container.v1.NetworkPolicy 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 25 with NetworkPolicy

use of com.google.container.v1.NetworkPolicy in project strimzi by strimzi.

the class KafkaClusterTest method testControlPlanePortNetworkPolicy.

@ParallelTest
public void testControlPlanePortNetworkPolicy() {
    NetworkPolicyPeer kafkaBrokersPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().withMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.kafkaStatefulSetName(cluster))).endPodSelector().build();
    Kafka kafkaAssembly = ResourceUtils.createKafka(namespace, cluster, replicas, image, healthDelay, healthTimeout, jmxMetricsConfig, configuration, emptyMap());
    KafkaCluster k = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafkaAssembly, VERSIONS);
    // Check Network Policies => Different namespace
    NetworkPolicy np = k.generateNetworkPolicy("operator-namespace", null);
    assertThat(np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(KafkaCluster.CONTROLPLANE_PORT))).findFirst().orElse(null), is(notNullValue()));
    List<NetworkPolicyPeer> rules = np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(KafkaCluster.CONTROLPLANE_PORT))).map(NetworkPolicyIngressRule::getFrom).findFirst().orElseThrow();
    assertThat(rules.size(), is(1));
    assertThat(rules.contains(kafkaBrokersPeer), is(true));
}
Also used : Quantity(io.fabric8.kubernetes.api.model.Quantity) VolumeMount(io.fabric8.kubernetes.api.model.VolumeMount) ExternalTrafficPolicy(io.strimzi.api.kafka.model.template.ExternalTrafficPolicy) PersistentClaimStorageOverrideBuilder(io.strimzi.api.kafka.model.storage.PersistentClaimStorageOverrideBuilder) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) KafkaExporterResources(io.strimzi.api.kafka.model.KafkaExporterResources) Rack(io.strimzi.api.kafka.model.Rack) GenericKafkaListenerConfigurationBrokerBuilder(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerConfigurationBrokerBuilder) SecurityContextBuilder(io.fabric8.kubernetes.api.model.SecurityContextBuilder) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) Collections.singletonList(java.util.Collections.singletonList) ResourceRequirements(io.fabric8.kubernetes.api.model.ResourceRequirements) KafkaResources(io.strimzi.api.kafka.model.KafkaResources) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) ContainerEnvVar(io.strimzi.api.kafka.model.ContainerEnvVar) KafkaJmxOptionsBuilder(io.strimzi.api.kafka.model.KafkaJmxOptionsBuilder) LabelSelectorBuilder(io.fabric8.kubernetes.api.model.LabelSelectorBuilder) CertSecretSource(io.strimzi.api.kafka.model.CertSecretSource) JbodStorageBuilder(io.strimzi.api.kafka.model.storage.JbodStorageBuilder) Matchers.allOf(org.hamcrest.Matchers.allOf) Set(java.util.Set) GenericKafkaListenerBuilder(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ZoneId(java.time.ZoneId) GenericSecretSourceBuilder(io.strimzi.api.kafka.model.GenericSecretSourceBuilder) PodSecurityContextBuilder(io.fabric8.kubernetes.api.model.PodSecurityContextBuilder) Matchers.contains(org.hamcrest.Matchers.contains) PasswordGenerator(io.strimzi.operator.common.PasswordGenerator) HostAliasBuilder(io.fabric8.kubernetes.api.model.HostAliasBuilder) KafkaListenerAuthenticationOAuthBuilder(io.strimzi.api.kafka.model.listener.KafkaListenerAuthenticationOAuthBuilder) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) Matchers.containsString(org.hamcrest.Matchers.containsString) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) EnvVar(io.fabric8.kubernetes.api.model.EnvVar) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ResourceRequirementsBuilder(io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder) IpFamily(io.strimzi.api.kafka.model.template.IpFamily) LocalObjectReference(io.fabric8.kubernetes.api.model.LocalObjectReference) OwnerReference(io.fabric8.kubernetes.api.model.OwnerReference) GenericKafkaListenerConfigurationBootstrapBuilder(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerConfigurationBootstrapBuilder) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) ArrayList(java.util.ArrayList) Matchers.hasProperty(org.hamcrest.Matchers.hasProperty) PersistentClaimStorageBuilder(io.strimzi.api.kafka.model.storage.PersistentClaimStorageBuilder) GenericKafkaListenerConfigurationBroker(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerConfigurationBroker) SecurityContext(io.fabric8.kubernetes.api.model.SecurityContext) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) KafkaListenerAuthenticationCustomBuilder(io.strimzi.api.kafka.model.listener.KafkaListenerAuthenticationCustomBuilder) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) KafkaJmxAuthenticationPasswordBuilder(io.strimzi.api.kafka.model.KafkaJmxAuthenticationPasswordBuilder) IOException(java.io.IOException) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) Reconciliation(io.strimzi.operator.common.Reconciliation) Util(io.strimzi.operator.common.Util) KafkaListenerType(io.strimzi.api.kafka.model.listener.arraylistener.KafkaListenerType) SystemPropertyBuilder(io.strimzi.api.kafka.model.SystemPropertyBuilder) ConfigMapKeySelectorBuilder(io.fabric8.kubernetes.api.model.ConfigMapKeySelectorBuilder) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) OpenSslCertManager(io.strimzi.certs.OpenSslCertManager) X509Certificate(java.security.cert.X509Certificate) CoreMatchers.is(org.hamcrest.CoreMatchers.is) CoreMatchers(org.hamcrest.CoreMatchers) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Storage(io.strimzi.api.kafka.model.storage.Storage) ParallelSuite(io.strimzi.test.annotations.ParallelSuite) Matchers.hasKey(org.hamcrest.Matchers.hasKey) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) Route(io.fabric8.openshift.api.model.Route) SystemProperty(io.strimzi.api.kafka.model.SystemProperty) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) KafkaAuthorizationKeycloakBuilder(io.strimzi.api.kafka.model.KafkaAuthorizationKeycloakBuilder) IpFamilyPolicy(io.strimzi.api.kafka.model.template.IpFamilyPolicy) ParallelTest(io.strimzi.test.annotations.ParallelTest) Collections.emptyList(java.util.Collections.emptyList) Collectors(java.util.stream.Collectors) CruiseControlResources(io.strimzi.api.kafka.model.CruiseControlResources) List(java.util.List) CertSecretSourceBuilder(io.strimzi.api.kafka.model.CertSecretSourceBuilder) Labels(io.strimzi.operator.common.model.Labels) NodeAddressType(io.strimzi.api.kafka.model.listener.NodeAddressType) RackBuilder(io.strimzi.api.kafka.model.RackBuilder) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Ingress(io.fabric8.kubernetes.api.model.networking.v1.Ingress) Secret(io.fabric8.kubernetes.api.model.Secret) TopologySpreadConstraintBuilder(io.fabric8.kubernetes.api.model.TopologySpreadConstraintBuilder) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) Uuid(org.apache.kafka.common.Uuid) PodManagementPolicy(io.strimzi.api.kafka.model.template.PodManagementPolicy) ContainerTemplate(io.strimzi.api.kafka.model.template.ContainerTemplate) Container(io.fabric8.kubernetes.api.model.Container) WeightedPodAffinityTerm(io.fabric8.kubernetes.api.model.WeightedPodAffinityTerm) EphemeralStorageBuilder(io.strimzi.api.kafka.model.storage.EphemeralStorageBuilder) CertificateParsingException(java.security.cert.CertificateParsingException) HashMap(java.util.HashMap) GenericKafkaListenerConfigurationBootstrap(io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerConfigurationBootstrap) MetricsAndLogging(io.strimzi.operator.common.MetricsAndLogging) HashSet(java.util.HashSet) HostAlias(io.fabric8.kubernetes.api.model.HostAlias) JmxPrometheusExporterMetrics(io.strimzi.api.kafka.model.JmxPrometheusExporterMetrics) JmxPrometheusExporterMetricsBuilder(io.strimzi.api.kafka.model.JmxPrometheusExporterMetricsBuilder) InlineLogging(io.strimzi.api.kafka.model.InlineLogging) MetricsConfig(io.strimzi.api.kafka.model.MetricsConfig) TestUtils(io.strimzi.test.TestUtils) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) CertificateExpirationPolicy(io.strimzi.api.kafka.model.CertificateExpirationPolicy) Volume(io.fabric8.kubernetes.api.model.Volume) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) CruiseControlConfigurationParameters(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters) Collections.emptyMap(java.util.Collections.emptyMap) TopologySpreadConstraint(io.fabric8.kubernetes.api.model.TopologySpreadConstraint) Matchers(org.hamcrest.Matchers) TestUtils.set(io.strimzi.test.TestUtils.set) LabelSelectorRequirementBuilder(io.fabric8.kubernetes.api.model.LabelSelectorRequirementBuilder) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) Kafka(io.strimzi.api.kafka.model.Kafka) Collections(java.util.Collections) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) Kafka(io.strimzi.api.kafka.model.Kafka) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) ParallelTest(io.strimzi.test.annotations.ParallelTest)

Aggregations

NetworkPolicy (io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy)147 Service (io.fabric8.kubernetes.api.model.Service)101 List (java.util.List)99 CoreMatchers.is (org.hamcrest.CoreMatchers.is)98 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)98 KafkaVersionTestUtils (io.strimzi.operator.cluster.KafkaVersionTestUtils)96 ResourceUtils (io.strimzi.operator.cluster.ResourceUtils)96 Reconciliation (io.strimzi.operator.common.Reconciliation)96 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)93 Collections.emptyList (java.util.Collections.emptyList)92 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)91 ConfigMapOperator (io.strimzi.operator.common.operator.resource.ConfigMapOperator)84 DeploymentOperator (io.strimzi.operator.common.operator.resource.DeploymentOperator)84 NetworkPolicyOperator (io.strimzi.operator.common.operator.resource.NetworkPolicyOperator)84 SecretOperator (io.strimzi.operator.common.operator.resource.SecretOperator)84 ServiceOperator (io.strimzi.operator.common.operator.resource.ServiceOperator)84 Optional (java.util.Optional)84 AfterAll (org.junit.jupiter.api.AfterAll)84 KafkaVersion (io.strimzi.operator.cluster.model.KafkaVersion)82 ResourceOperatorSupplier (io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier)82