Search in sources :

Example 91 with NetworkPolicy

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

the class ZookeeperClusterTest method testNetworkPolicyNewKubernetesVersions.

@ParallelTest
public void testNetworkPolicyNewKubernetesVersions() {
    Kafka kafkaAssembly = ResourceUtils.createKafka(namespace, cluster, replicas, image, healthDelay, healthTimeout, jmxMetricsConfig, configurationJson, emptyMap());
    kafkaAssembly.getSpec().getKafka().setRack(new RackBuilder().withTopologyKey("topology-key").build());
    ZookeeperCluster zc = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafkaAssembly, VERSIONS);
    // Check Network Policies => Other namespace
    NetworkPolicy np = zc.generateNetworkPolicy("operator-namespace", null);
    LabelSelector podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.zookeeperStatefulSetName(zc.getCluster())));
    assertThat(np.getSpec().getPodSelector(), is(podSelector));
    List<NetworkPolicyIngressRule> rules = np.getSpec().getIngress();
    assertThat(rules.size(), is(3));
    // Ports 2888 and 3888
    NetworkPolicyIngressRule zooRule = rules.get(0);
    assertThat(zooRule.getPorts().size(), is(2));
    assertThat(zooRule.getPorts().get(0).getPort(), is(new IntOrString(2888)));
    assertThat(zooRule.getPorts().get(1).getPort(), is(new IntOrString(3888)));
    assertThat(zooRule.getFrom().size(), is(1));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.zookeeperStatefulSetName(zc.getCluster())));
    assertThat(zooRule.getFrom().get(0), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    // Port 2181
    NetworkPolicyIngressRule clientsRule = rules.get(1);
    assertThat(clientsRule.getPorts().size(), is(1));
    assertThat(clientsRule.getPorts().get(0).getPort(), is(new IntOrString(ZookeeperCluster.CLIENT_TLS_PORT)));
    assertThat(clientsRule.getFrom().size(), is(4));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.kafkaStatefulSetName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(0), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.zookeeperStatefulSetName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(1), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaResources.entityOperatorDeploymentName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(2), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator"));
    assertThat(clientsRule.getFrom().get(3), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).withNamespaceSelector(new LabelSelector()).build()));
    // Port 9404
    NetworkPolicyIngressRule metricsRule = rules.get(2);
    assertThat(metricsRule.getPorts().size(), is(1));
    assertThat(metricsRule.getPorts().get(0).getPort(), is(new IntOrString(9404)));
    assertThat(metricsRule.getFrom().size(), is(0));
    // Check Network Policies => The same namespace
    np = zc.generateNetworkPolicy(namespace, null);
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator"));
    assertThat(np.getSpec().getIngress().get(1).getFrom().get(3), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    // Check Network Policies => The same namespace with namespace labels
    np = zc.generateNetworkPolicy(namespace, Labels.fromMap(Collections.singletonMap("nsLabelKey", "nsLabelValue")));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator"));
    assertThat(np.getSpec().getIngress().get(1).getFrom().get(3), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    // Check Network Policies => Other namespace with namespace labels
    np = zc.generateNetworkPolicy("operator-namespace", Labels.fromMap(Collections.singletonMap("nsLabelKey", "nsLabelValue")));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator"));
    LabelSelector namespaceSelector = new LabelSelector();
    namespaceSelector.setMatchLabels(Collections.singletonMap("nsLabelKey", "nsLabelValue"));
    assertThat(np.getSpec().getIngress().get(1).getFrom().get(3), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).withNamespaceSelector(namespaceSelector).build()));
}
Also used : RackBuilder(io.strimzi.api.kafka.model.RackBuilder) 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) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) ParallelTest(io.strimzi.test.annotations.ParallelTest)

Example 92 with NetworkPolicy

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

the class NetworkPolicyTemplates method applyDefaultNetworkPolicy.

public static NetworkPolicy applyDefaultNetworkPolicy(ExtensionContext extensionContext, String namespace, DefaultNetworkPolicy policy) {
    NetworkPolicy networkPolicy = new NetworkPolicyBuilder().withApiVersion("networking.k8s.io/v1").withKind(Constants.NETWORK_POLICY).withNewMetadata().withName("global-network-policy").withNamespace(namespace).endMetadata().withNewSpec().withNewPodSelector().endPodSelector().withPolicyTypes("Ingress").endSpec().build();
    if (policy.equals(DefaultNetworkPolicy.DEFAULT_TO_ALLOW)) {
        networkPolicy = new NetworkPolicyBuilder(networkPolicy).editSpec().addNewIngress().endIngress().endSpec().build();
    }
    LOGGER.debug("Creating NetworkPolicy: {}", networkPolicy.toString());
    return networkPolicy;
}
Also used : NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) DefaultNetworkPolicy(io.strimzi.systemtest.enums.DefaultNetworkPolicy) NetworkPolicyBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyBuilder)

Example 93 with NetworkPolicy

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

the class CruiseControl method generateNetworkPolicy.

/**
 * Generates the NetworkPolicies relevant for Cruise Control
 *
 * @param operatorNamespace                             Namespace where the Strimzi Cluster Operator runs. Null if not configured.
 * @param operatorNamespaceLabels                       Labels of the namespace where the Strimzi Cluster Operator runs. Null if not configured.
 *
 * @return The network policy.
 */
public NetworkPolicy generateNetworkPolicy(String operatorNamespace, Labels operatorNamespaceLabels) {
    List<NetworkPolicyIngressRule> rules = new ArrayList<>(1);
    // CO can access the REST API
    NetworkPolicyIngressRule restApiRule = new NetworkPolicyIngressRuleBuilder().addNewPort().withNewPort(REST_API_PORT).withProtocol("TCP").endPort().build();
    NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().addToMatchLabels(Labels.STRIMZI_KIND_LABEL, "cluster-operator").endPodSelector().build();
    ModelUtils.setClusterOperatorNetworkPolicyNamespaceSelector(clusterOperatorPeer, namespace, operatorNamespace, operatorNamespaceLabels);
    restApiRule.setFrom(Collections.singletonList(clusterOperatorPeer));
    rules.add(restApiRule);
    if (isMetricsEnabled) {
        NetworkPolicyIngressRule metricsRule = new NetworkPolicyIngressRuleBuilder().addNewPort().withNewPort(METRICS_PORT).withProtocol("TCP").endPort().withFrom().build();
        rules.add(metricsRule);
    }
    NetworkPolicy networkPolicy = new NetworkPolicyBuilder().withNewMetadata().withName(CruiseControlResources.networkPolicyName(cluster)).withNamespace(namespace).withLabels(labels.toMap()).withOwnerReferences(createOwnerReference()).endMetadata().withNewSpec().withNewPodSelector().addToMatchLabels(Labels.STRIMZI_NAME_LABEL, CruiseControlResources.deploymentName(cluster)).endPodSelector().withIngress(rules).endSpec().build();
    LOGGER.traceCr(reconciliation, "Created network policy {}", networkPolicy);
    return networkPolicy;
}
Also used : 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) ArrayList(java.util.ArrayList) NetworkPolicyIngressRuleBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRuleBuilder) NetworkPolicyBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyBuilder) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder)

Example 94 with NetworkPolicy

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

the class KafkaConnectAssemblyOperatorTest method createKafkaConnectCluster.

public void createKafkaConnectCluster(VertxTestContext context, KafkaConnect kc, boolean connectorOperator) {
    ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
    var mockConnectOps = supplier.connectOperator;
    DeploymentOperator mockDcOps = supplier.deploymentOperations;
    PodDisruptionBudgetOperator mockPdbOps = supplier.podDisruptionBudgetOperator;
    ConfigMapOperator mockCmOps = supplier.configMapOperations;
    ServiceOperator mockServiceOps = supplier.serviceOperations;
    NetworkPolicyOperator mockNetPolOps = supplier.networkPolicyOperator;
    PodOperator mockPodOps = supplier.podOperations;
    BuildConfigOperator mockBcOps = supplier.buildConfigOperations;
    SecretOperator mockSecretOps = supplier.secretOperations;
    CrdOperator<KubernetesClient, KafkaConnector, KafkaConnectorList> mockConnectorOps = supplier.kafkaConnectorOperator;
    when(mockConnectorOps.listAsync(anyString(), any(Optional.class))).thenReturn(Future.succeededFuture(emptyList()));
    when(mockConnectOps.get(kc.getMetadata().getNamespace(), kc.getMetadata().getName())).thenReturn(kc);
    when(mockConnectOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kc));
    ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class);
    when(mockServiceOps.reconcile(any(), anyString(), anyString(), serviceCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<Deployment> dcCaptor = ArgumentCaptor.forClass(Deployment.class);
    when(mockDcOps.reconcile(any(), anyString(), anyString(), dcCaptor.capture())).thenReturn(Future.succeededFuture());
    when(mockDcOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture());
    when(mockDcOps.scaleUp(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDcOps.scaleDown(any(), anyString(), anyString(), anyInt())).thenReturn(Future.succeededFuture(42));
    when(mockDcOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDcOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    when(mockSecretOps.reconcile(any(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    when(mockSecretOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture());
    when(mockPodOps.reconcile(any(), eq(kc.getMetadata().getNamespace()), eq(KafkaConnectResources.buildPodName(kc.getMetadata().getName())), eq(null))).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    when(mockBcOps.reconcile(any(), eq(kc.getMetadata().getNamespace()), eq(KafkaConnectResources.buildConfigName(kc.getMetadata().getName())), eq(null))).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    ArgumentCaptor<NetworkPolicy> npCaptor = ArgumentCaptor.forClass(NetworkPolicy.class);
    when(mockNetPolOps.reconcile(any(), eq(kc.getMetadata().getNamespace()), eq(KafkaConnectResources.deploymentName(kc.getMetadata().getName())), npCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new NetworkPolicy())));
    ArgumentCaptor<PodDisruptionBudget> pdbCaptor = ArgumentCaptor.forClass(PodDisruptionBudget.class);
    when(mockPdbOps.reconcile(any(), anyString(), any(), pdbCaptor.capture())).thenReturn(Future.succeededFuture());
    ArgumentCaptor<KafkaConnect> connectCaptor = ArgumentCaptor.forClass(KafkaConnect.class);
    when(mockConnectOps.updateStatusAsync(any(), connectCaptor.capture())).thenReturn(Future.succeededFuture());
    KafkaConnectApi mockConnectClient = mock(KafkaConnectApi.class);
    when(mockConnectClient.list(anyString(), anyInt())).thenReturn(Future.succeededFuture(emptyList()));
    ConnectorPlugin plugin1 = new ConnectorPluginBuilder().withConnectorClass("io.strimzi.MyClass").withType("sink").withVersion("1.0.0").build();
    when(mockConnectClient.listConnectorPlugins(any(), anyString(), anyInt())).thenReturn(Future.succeededFuture(singletonList(plugin1)));
    when(mockConnectClient.updateConnectLoggers(any(), anyString(), anyInt(), anyString(), any(OrderedProperties.class))).thenReturn(Future.succeededFuture());
    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, kc.getMetadata().getNamespace(), kc.getMetadata().getName())).onComplete(context.succeeding(v -> context.verify(() -> {
        // Verify service
        List<Service> capturedServices = serviceCaptor.getAllValues();
        assertThat(capturedServices, hasSize(1));
        Service service = capturedServices.get(0);
        assertThat(service.getMetadata().getName(), is(connect.getServiceName()));
        assertThat(service, is(connect.generateService()));
        // Verify Deployment
        List<Deployment> capturedDc = dcCaptor.getAllValues();
        assertThat(capturedDc, hasSize(1));
        Deployment dc = capturedDc.get(0);
        assertThat(dc.getMetadata().getName(), is(connect.getName()));
        Map<String, String> annotations = new HashMap<>();
        annotations.put(Annotations.ANNO_STRIMZI_LOGGING_DYNAMICALLY_UNCHANGEABLE_HASH, Util.hashStub(Util.getLoggingDynamicallyUnmodifiableEntries(LOGGING_CONFIG)));
        annotations.put(Annotations.ANNO_STRIMZI_AUTH_HASH, "0");
        assertThat(dc, is(connect.generateDeployment(annotations, true, null, null)));
        // Verify PodDisruptionBudget
        List<PodDisruptionBudget> capturedPdb = pdbCaptor.getAllValues();
        assertThat(capturedPdb.size(), is(1));
        PodDisruptionBudget pdb = capturedPdb.get(0);
        assertThat(pdb.getMetadata().getName(), is(connect.getName()));
        assertThat(pdb, is(connect.generatePodDisruptionBudget()));
        // Verify status
        List<KafkaConnect> capturedConnects = connectCaptor.getAllValues();
        assertThat(capturedConnects, hasSize(1));
        KafkaConnectStatus connectStatus = capturedConnects.get(0).getStatus();
        assertThat(connectStatus.getUrl(), is("http://foo-connect-api.test.svc:8083"));
        assertThat(connectStatus.getReplicas(), is(connect.getReplicas()));
        assertThat(connectStatus.getLabelSelector(), is(connect.getSelectorLabels().toSelectorString()));
        assertThat(connectStatus.getConditions().get(0).getStatus(), is("True"));
        assertThat(connectStatus.getConditions().get(0).getType(), is("Ready"));
        if (connectorOperator) {
            assertThat(npCaptor.getValue(), is(notNullValue()));
            assertThat(connectStatus.getConnectorPlugins(), hasSize(1));
            assertThat(connectStatus.getConnectorPlugins().get(0).getConnectorClass(), is("io.strimzi.MyClass"));
            assertThat(connectStatus.getConnectorPlugins().get(0).getType(), is("sink"));
            assertThat(connectStatus.getConnectorPlugins().get(0).getVersion(), is("1.0.0"));
        } else {
            assertThat(npCaptor.getValue(), is(nullValue()));
            assertThat(connectStatus.getConnectorPlugins(), nullValue());
        }
        async.flag();
    })));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) ConnectorPluginBuilder(io.strimzi.api.kafka.model.connect.ConnectorPluginBuilder) OrderedProperties(io.strimzi.operator.common.model.OrderedProperties) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Annotations(io.strimzi.operator.common.Annotations) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) ClusterRoleBindingOperator(io.strimzi.operator.common.operator.resource.ClusterRoleBindingOperator) Collections.singletonList(java.util.Collections.singletonList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) AbstractModel(io.strimzi.operator.cluster.model.AbstractModel) KafkaJmxOptionsBuilder(io.strimzi.api.kafka.model.KafkaJmxOptionsBuilder) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Collections.emptyList(java.util.Collections.emptyList) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) KafkaVersion(io.strimzi.operator.cluster.model.KafkaVersion) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Set(java.util.Set) VertxExtension(io.vertx.junit5.VertxExtension) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) List(java.util.List) Labels(io.strimzi.operator.common.model.Labels) RackBuilder(io.strimzi.api.kafka.model.RackBuilder) 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) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) HashMap(java.util.HashMap) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) ArgumentCaptor(org.mockito.ArgumentCaptor) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) TestUtils(io.strimzi.test.TestUtils) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) KafkaJmxAuthenticationPasswordBuilder(io.strimzi.api.kafka.model.KafkaJmxAuthenticationPasswordBuilder) Promise(io.vertx.core.Promise) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) ConnectorPlugin(io.strimzi.api.kafka.model.connect.ConnectorPlugin) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Mockito.verify(org.mockito.Mockito.verify) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) Reconciliation(io.strimzi.operator.common.Reconciliation) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) Util(io.strimzi.operator.common.Util) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) KafkaConnectResources(io.strimzi.api.kafka.model.KafkaConnectResources) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) HashMap(java.util.HashMap) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) 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) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) OrderedProperties(io.strimzi.operator.common.model.OrderedProperties) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) 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) ConnectorPluginBuilder(io.strimzi.api.kafka.model.connect.ConnectorPluginBuilder) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) ConnectorPlugin(io.strimzi.api.kafka.model.connect.ConnectorPlugin) KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) Checkpoint(io.vertx.junit5.Checkpoint) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator)

Example 95 with NetworkPolicy

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

the class KafkaConnectBuildAssemblyOperatorKubeTest method testUpdateWithBuildImageChangeOnKube.

@SuppressWarnings({ "checkstyle:MethodLength" })
@Test
public void testUpdateWithBuildImageChangeOnKube(VertxTestContext context) {
    Plugin plugin1 = new PluginBuilder().withName("plugin1").withArtifacts(new JarArtifactBuilder().withUrl("https://my-domain.tld/my.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().withNewDockerOutput().withImage("my-connect-build-2:blah").withPushSecret("my-docker-credentials").endDockerOutput().withPlugins(plugin1).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;
    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() + Util.hashStub(oldBuild.getBuild().getOutput().getImage()));
        dep.getSpec().getTemplate().getSpec().getContainers().get(0).setImage("my-connect-build-2@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())));
    ArgumentCaptor<ConfigMap> dockerfileCaptor = ArgumentCaptor.forClass(ConfigMap.class);
    when(mockCmOps.reconcile(any(), anyString(), eq(KafkaConnectResources.dockerFileConfigMapName(NAME)), dockerfileCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    // Mock and capture Pod ops
    ArgumentCaptor<Pod> builderPodCaptor = ArgumentCaptor.forClass(Pod.class);
    when(mockPodOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildPodName(NAME)), builderPodCaptor.capture())).thenReturn(Future.succeededFuture(ReconcileResult.noop(null)));
    Pod terminatedPod = new PodBuilder().withNewMetadata().withName(KafkaConnectResources.buildPodName(NAME)).withNamespace(NAMESPACE).endMetadata().withNewSpec().endSpec().withNewStatus().withContainerStatuses(new ContainerStatusBuilder().withNewState().withNewTerminated().withExitCode(0).withMessage("my-connect-build-2@sha256:blablabla").endTerminated().endState().build()).endStatus().build();
    when(mockPodOps.waitFor(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildPodName(NAME)), anyString(), anyLong(), anyLong(), any(BiPredicate.class))).thenReturn(Future.succeededFuture((Void) null));
    when(mockPodOps.getAsync(eq(NAMESPACE), eq(KafkaConnectResources.buildPodName(NAME)))).thenReturn(Future.succeededFuture(null), Future.succeededFuture(terminatedPod));
    // Mock and capture BuildConfig ops
    when(mockBcOps.reconcile(any(), eq(NAMESPACE), eq(KafkaConnectResources.buildConfigName(NAME)), eq(null))).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(false, 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-2@sha256:blablabla"));
        assertThat(Annotations.stringAnnotation(dep.getSpec().getTemplate(), Annotations.STRIMZI_IO_CONNECT_BUILD_REVISION, null), is(build.generateDockerfile().hashStub() + Util.hashStub(build.getBuild().getOutput().getImage())));
        // Verify ConfigMap
        List<ConfigMap> capturedCms = dockerfileCaptor.getAllValues();
        assertThat(capturedCms, hasSize(1));
        ConfigMap dockerfileCm = capturedCms.get(0);
        assertThat(dockerfileCm.getData().containsKey("Dockerfile"), is(true));
        assertThat(dockerfileCm.getData().get("Dockerfile"), is(build.generateDockerfile().getDockerfile()));
        // Verify builder Pod
        List<Pod> capturedBuilderPods = builderPodCaptor.getAllValues();
        assertThat(capturedBuilderPods, hasSize(2));
        assertThat(capturedBuilderPods.stream().filter(pod -> pod != null).collect(Collectors.toList()), hasSize(1));
        // 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) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) BeforeAll(org.junit.jupiter.api.BeforeAll) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) 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) Collectors(java.util.stream.Collectors) 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) PluginBuilder(io.strimzi.api.kafka.model.connect.build.PluginBuilder) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) BiPredicate(java.util.function.BiPredicate) ArgumentCaptor(org.mockito.ArgumentCaptor) ServiceAccountOperator(io.strimzi.operator.common.operator.resource.ServiceAccountOperator) 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) ContainerStatusBuilder(io.fabric8.kubernetes.api.model.ContainerStatusBuilder) KubernetesVersion(io.strimzi.operator.KubernetesVersion) Vertx(io.vertx.core.Vertx) Pod(io.fabric8.kubernetes.api.model.Pod) Mockito.when(org.mockito.Mockito.when) JarArtifactBuilder(io.strimzi.api.kafka.model.connect.build.JarArtifactBuilder) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) 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) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) 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) Reconciliation(io.strimzi.operator.common.Reconciliation) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) 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) Pod(io.fabric8.kubernetes.api.model.Pod) PodOperator(io.strimzi.operator.common.operator.resource.PodOperator) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) Service(io.fabric8.kubernetes.api.model.Service) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) ContainerStatusBuilder(io.fabric8.kubernetes.api.model.ContainerStatusBuilder) 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) BiPredicate(java.util.function.BiPredicate) Plugin(io.strimzi.api.kafka.model.connect.build.Plugin) Test(org.junit.jupiter.api.Test)

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