Search in sources :

Example 41 with NetworkPolicy

use of com.google.container.v1beta1.NetworkPolicy in project onos by opennetworkinglab.

the class K8sNetworkPolicyListCommand method json.

private String json(List<NetworkPolicy> policies) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode result = mapper.createArrayNode();
    try {
        for (NetworkPolicy policy : policies) {
            ObjectNode json = (ObjectNode) new ObjectMapper().readTree(Serialization.asJson(policy));
            result.add(json);
        }
        return prettyJson(mapper, result.toString());
    } catch (IOException e) {
        log.warn("Failed to parse Network Policy's JSON string.");
        return "";
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 42 with NetworkPolicy

use of com.google.container.v1beta1.NetworkPolicy in project onos by opennetworkinglab.

the class K8sNetworkPolicyHandler method setAllowRulesByPolicy.

private void setAllowRulesByPolicy(NetworkPolicy policy, boolean install) {
    Map<String, Map<String, List<NetworkPolicyPort>>> white = Maps.newConcurrentMap();
    int nsHash = namespaceHashByNamespace(k8sNamespaceService, policy.getMetadata().getNamespace());
    List<NetworkPolicyIngressRule> ingress = policy.getSpec().getIngress();
    if (ingress != null && ingress.size() == 1) {
        NetworkPolicyIngressRule rule = ingress.get(0);
        if (rule.getFrom().size() == 0 && rule.getPorts().size() == 0) {
            setAllowAllRule(nsHash, DIRECTION_INGRESS, install);
        }
    }
    policy.getSpec().getIngress().forEach(i -> {
        Map<String, List<NetworkPolicyPort>> direction = Maps.newConcurrentMap();
        direction.put(DIRECTION_INGRESS, i.getPorts());
        i.getFrom().forEach(peer -> {
            // IP block
            if (peer.getIpBlock() != null) {
                if (peer.getIpBlock().getExcept() != null && peer.getIpBlock().getExcept().size() > 0) {
                    Map<String, List<NetworkPolicyPort>> blkDirection = Maps.newConcurrentMap();
                    blkDirection.put(DIRECTION_INGRESS, i.getPorts());
                    white.compute(peer.getIpBlock().getCidr(), (k, v) -> blkDirection);
                    setBlackRules(peer.getIpBlock().getCidr(), DIRECTION_INGRESS, peer.getIpBlock().getExcept(), install);
                } else {
                    white.compute(peer.getIpBlock().getCidr(), (k, v) -> direction);
                }
            }
            // POD selector
            Set<Pod> pods = podsFromPolicyPeer(peer, policy.getMetadata().getNamespace());
            pods.stream().filter(pod -> pod.getStatus().getPodIP() != null).forEach(pod -> {
                white.compute(shiftIpDomain(pod.getStatus().getPodIP(), SHIFTED_IP_PREFIX) + "/" + HOST_PREFIX, (m, n) -> direction);
                white.compute(pod.getStatus().getPodIP() + "/" + HOST_PREFIX, (m, n) -> direction);
            });
            // Namespace selector
            setAllowNamespaceRules(nsHash, namespacesByPolicyPeer(peer), DIRECTION_INGRESS, install);
        });
    });
    List<NetworkPolicyEgressRule> egress = policy.getSpec().getEgress();
    if (egress != null && egress.size() == 1) {
        NetworkPolicyEgressRule rule = egress.get(0);
        if (rule.getTo().size() == 0 && rule.getPorts().size() == 0) {
            setAllowAllRule(nsHash, DIRECTION_EGRESS, install);
        }
    }
    policy.getSpec().getEgress().forEach(e -> {
        Map<String, List<NetworkPolicyPort>> direction = Maps.newConcurrentMap();
        direction.put(DIRECTION_EGRESS, e.getPorts());
        e.getTo().forEach(peer -> {
            // IP block
            if (peer.getIpBlock() != null) {
                if (peer.getIpBlock().getExcept() != null && peer.getIpBlock().getExcept().size() > 0) {
                    Map<String, List<NetworkPolicyPort>> blkDirection = Maps.newConcurrentMap();
                    blkDirection.put(DIRECTION_EGRESS, e.getPorts());
                    white.compute(peer.getIpBlock().getCidr(), (k, v) -> {
                        if (v != null) {
                            v.put(DIRECTION_EGRESS, e.getPorts());
                            return v;
                        } else {
                            return blkDirection;
                        }
                    });
                    setBlackRules(peer.getIpBlock().getCidr(), DIRECTION_EGRESS, peer.getIpBlock().getExcept(), install);
                } else {
                    white.compute(peer.getIpBlock().getCidr(), (k, v) -> {
                        if (v != null) {
                            v.put(DIRECTION_EGRESS, e.getPorts());
                            return v;
                        } else {
                            return direction;
                        }
                    });
                }
            }
            // POD selector
            Set<Pod> pods = podsFromPolicyPeer(peer, policy.getMetadata().getNamespace());
            pods.stream().filter(pod -> pod.getStatus().getPodIP() != null).forEach(pod -> {
                white.compute(shiftIpDomain(pod.getStatus().getPodIP(), SHIFTED_IP_PREFIX) + "/" + HOST_PREFIX, (m, n) -> {
                    if (n != null) {
                        n.put(DIRECTION_EGRESS, e.getPorts());
                        return n;
                    } else {
                        return direction;
                    }
                });
                white.compute(pod.getStatus().getPodIP() + "/" + HOST_PREFIX, (m, n) -> {
                    if (n != null) {
                        n.put(DIRECTION_EGRESS, e.getPorts());
                        return n;
                    } else {
                        return direction;
                    }
                });
            });
            // Namespace selector
            setAllowNamespaceRules(nsHash, namespacesByPolicyPeer(peer), DIRECTION_EGRESS, install);
        });
    });
    setAllowRules(namespaceHashByNamespace(k8sNamespaceService, policy.getMetadata().getNamespace()), white, install);
    setBlackToRouteRules(true);
}
Also used : ACL_INGRESS_WHITE_TABLE(org.onosproject.k8snetworking.api.Constants.ACL_INGRESS_WHITE_TABLE) K8sNetworkingUtil.shiftIpDomain(org.onosproject.k8snetworking.util.K8sNetworkingUtil.shiftIpDomain) CoreService(org.onosproject.core.CoreService) DeviceService(org.onosproject.net.device.DeviceService) Tools.groupedThreads(org.onlab.util.Tools.groupedThreads) PRIORITY_NAMESPACE_RULE(org.onosproject.k8snetworking.api.Constants.PRIORITY_NAMESPACE_RULE) NAMESPACE_TABLE(org.onosproject.k8snetworking.api.Constants.NAMESPACE_TABLE) PRIORITY_CIDR_RULE(org.onosproject.k8snetworking.api.Constants.PRIORITY_CIDR_RULE) DriverService(org.onosproject.net.driver.DriverService) DefaultTrafficTreatment(org.onosproject.net.flow.DefaultTrafficTreatment) K8sNetworkPolicyEvent(org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent) DEFAULT_METADATA_MASK(org.onosproject.k8snetworking.api.Constants.DEFAULT_METADATA_MASK) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) StorageService(org.onosproject.store.service.StorageService) ROUTING_TABLE(org.onosproject.k8snetworking.api.Constants.ROUTING_TABLE) DEFAULT_SEGMENT_ID(org.onosproject.k8snetworking.api.Constants.DEFAULT_SEGMENT_ID) DEFAULT_NAMESPACE_HASH(org.onosproject.k8snetworking.api.Constants.DEFAULT_NAMESPACE_HASH) Map(java.util.Map) SERVICE_IP_CIDR_DEFAULT(org.onosproject.k8snetworking.impl.OsgiPropertyConstants.SERVICE_IP_CIDR_DEFAULT) ApplicationId(org.onosproject.core.ApplicationId) K8sPodService(org.onosproject.k8snetworking.api.K8sPodService) K8sServiceEvent(org.onosproject.k8snetworking.api.K8sServiceEvent) TYPE_IPV4(org.onlab.packet.Ethernet.TYPE_IPV4) K8sPodListener(org.onosproject.k8snetworking.api.K8sPodListener) ACL_EGRESS_BLACK_TABLE(org.onosproject.k8snetworking.api.Constants.ACL_EGRESS_BLACK_TABLE) NodeId(org.onosproject.cluster.NodeId) ImmutableSet(com.google.common.collect.ImmutableSet) K8sNetworkingUtil.namespaceHashByPodIp(org.onosproject.k8snetworking.util.K8sNetworkingUtil.namespaceHashByPodIp) Deactivate(org.osgi.service.component.annotations.Deactivate) K8sNetworkingUtil.namespaceHashByServiceIp(org.onosproject.k8snetworking.util.K8sNetworkingUtil.namespaceHashByServiceIp) ACL_INGRESS_BLACK_TABLE(org.onosproject.k8snetworking.api.Constants.ACL_INGRESS_BLACK_TABLE) Set(java.util.Set) K8sFlowRuleService(org.onosproject.k8snetworking.api.K8sFlowRuleService) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) List(java.util.List) Namespace(io.fabric8.kubernetes.api.model.Namespace) K8sNetworkPolicyService(org.onosproject.k8snetworking.api.K8sNetworkPolicyService) ClusterService(org.onosproject.cluster.ClusterService) LabelSelectorRequirement(io.fabric8.kubernetes.api.model.LabelSelectorRequirement) IpPrefix(org.onlab.packet.IpPrefix) ACL_EGRESS_WHITE_TABLE(org.onosproject.k8snetworking.api.Constants.ACL_EGRESS_WHITE_TABLE) K8sServiceService(org.onosproject.k8snetworking.api.K8sServiceService) ACL_TABLE(org.onosproject.k8snetworking.api.Constants.ACL_TABLE) GROUPING_TABLE(org.onosproject.k8snetworking.api.Constants.GROUPING_TABLE) K8sNetworkService(org.onosproject.k8snetworking.api.K8sNetworkService) AtomicReference(java.util.concurrent.atomic.AtomicReference) NetworkPolicyEgressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyEgressRule) K8sNamespaceListener(org.onosproject.k8snetworking.api.K8sNamespaceListener) Component(org.osgi.service.component.annotations.Component) TrafficSelector(org.onosproject.net.flow.TrafficSelector) K8sNamespaceEvent(org.onosproject.k8snetworking.api.K8sNamespaceEvent) NetworkPolicyPort(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPort) K8sServiceListener(org.onosproject.k8snetworking.api.K8sServiceListener) Activate(org.osgi.service.component.annotations.Activate) Service(io.fabric8.kubernetes.api.model.Service) DefaultTrafficSelector(org.onosproject.net.flow.DefaultTrafficSelector) ExecutorService(java.util.concurrent.ExecutorService) K8S_NETWORKING_APP_ID(org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID) IpAddress(org.onlab.packet.IpAddress) TpPort(org.onlab.packet.TpPort) ComponentConfigService(org.onosproject.cfg.ComponentConfigService) TrafficTreatment(org.onosproject.net.flow.TrafficTreatment) Logger(org.slf4j.Logger) SHIFTED_IP_PREFIX(org.onosproject.k8snetworking.api.Constants.SHIFTED_IP_PREFIX) Pod(io.fabric8.kubernetes.api.model.Pod) Maps(com.google.common.collect.Maps) K8sNamespaceService(org.onosproject.k8snetworking.api.K8sNamespaceService) K8sNetworkPolicyListener(org.onosproject.k8snetworking.api.K8sNetworkPolicyListener) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) IPv4(org.onlab.packet.IPv4) DEFAULT_SERVICE_IP_NONE(org.onosproject.k8snetworking.api.Constants.DEFAULT_SERVICE_IP_NONE) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) K8sNetworkingUtil.namespaceHashByNamespace(org.onosproject.k8snetworking.util.K8sNetworkingUtil.namespaceHashByNamespace) K8sPodEvent(org.onosproject.k8snetworking.api.K8sPodEvent) K8sNodeService(org.onosproject.k8snode.api.K8sNodeService) Reference(org.osgi.service.component.annotations.Reference) LeadershipService(org.onosproject.cluster.LeadershipService) NetworkPolicyPort(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPort) Pod(io.fabric8.kubernetes.api.model.Pod) NetworkPolicyEgressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyEgressRule) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) List(java.util.List) Map(java.util.Map)

Example 43 with NetworkPolicy

use of com.google.container.v1beta1.NetworkPolicy in project strimzi-kafka-operator by strimzi.

the class KafkaConnectCluster method generateNetworkPolicy.

/**
 * Generates the NetworkPolicies relevant for Kafka Connect nodes
 *
 * @param connectorOperatorEnabled Whether the ConnectorOperator is enabled or not
 * @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(boolean connectorOperatorEnabled, String operatorNamespace, Labels operatorNamespaceLabels) {
    if (connectorOperatorEnabled) {
        List<NetworkPolicyIngressRule> rules = new ArrayList<>(2);
        // Give CO access to the REST API
        NetworkPolicyIngressRule restApiRule = new NetworkPolicyIngressRuleBuilder().addNewPort().withNewPort(REST_API_PORT).withProtocol("TCP").endPort().build();
        // OCP 3.11 doesn't support network policies with the `from` section containing a namespace.
        // Since the CO can run in a different namespace, we have to leave it wide open on OCP 3.11
        // Therefore these rules are set only when using something else than OCP 3.11 and leaving
        // the `from` section empty on 3.11
        List<NetworkPolicyPeer> peers = new ArrayList<>(2);
        // Other connect pods in the same cluster need to talk with each other over the REST API
        NetworkPolicyPeer connectPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().addToMatchLabels(getSelectorLabels().toMap()).endPodSelector().build();
        peers.add(connectPeer);
        // CO needs to talk with the Connect pods to manage connectors
        NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().addToMatchLabels(Labels.STRIMZI_KIND_LABEL, "cluster-operator").endPodSelector().build();
        ModelUtils.setClusterOperatorNetworkPolicyNamespaceSelector(clusterOperatorPeer, namespace, operatorNamespace, operatorNamespaceLabels);
        peers.add(clusterOperatorPeer);
        restApiRule.setFrom(peers);
        rules.add(restApiRule);
        // If metrics are enabled, we have to open them as well. Otherwise they will be blocked.
        if (isMetricsEnabled) {
            NetworkPolicyIngressRule metricsRule = new NetworkPolicyIngressRuleBuilder().addNewPort().withNewPort(METRICS_PORT).withProtocol("TCP").endPort().withFrom().build();
            rules.add(metricsRule);
        }
        NetworkPolicy networkPolicy = new NetworkPolicyBuilder().withNewMetadata().withName(name).withNamespace(namespace).withLabels(labels.toMap()).withOwnerReferences(createOwnerReference()).endMetadata().withNewSpec().withNewPodSelector().addToMatchLabels(getSelectorLabels().toMap()).endPodSelector().withIngress(rules).endSpec().build();
        LOGGER.traceCr(reconciliation, "Created network policy {}", networkPolicy);
        return networkPolicy;
    } else {
        return null;
    }
}
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 44 with NetworkPolicy

use of com.google.container.v1beta1.NetworkPolicy in project strimzi-kafka-operator 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 45 with NetworkPolicy

use of com.google.container.v1beta1.NetworkPolicy in project strimzi-kafka-operator by strimzi.

the class KafkaConnectAssemblyOperatorTest method testCreateOrUpdatePassesWhenClusterRoleBindingRightsAreMissingAndNotRequired.

@Test
public void testCreateOrUpdatePassesWhenClusterRoleBindingRightsAreMissingAndNotRequired(VertxTestContext context) {
    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;
    ClusterRoleBindingOperator mockCrbOps = supplier.clusterRoleBindingOperator;
    SecretOperator mockSecretOps = supplier.secretOperations;
    String kcName = "foo";
    String kcNamespace = "test";
    KafkaConnect kc = ResourceUtils.createEmptyKafkaConnect(kcNamespace, kcName);
    KafkaConnectCluster connect = KafkaConnectCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kc, VERSIONS);
    when(mockConnectOps.get(kcNamespace, kcName)).thenReturn(kc);
    when(mockConnectOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(kc));
    when(mockConnectOps.updateStatusAsync(any(), any(KafkaConnect.class))).thenReturn(Future.succeededFuture());
    when(mockServiceOps.get(kcNamespace, connect.getName())).thenReturn(connect.generateService());
    when(mockDcOps.getAsync(kcNamespace, connect.getName())).thenReturn(Future.succeededFuture(connect.generateDeployment(Map.of(), true, null, null)));
    when(mockDcOps.readiness(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockDcOps.waitForObserved(any(), anyString(), anyString(), anyLong(), anyLong())).thenReturn(Future.succeededFuture());
    when(mockSecretOps.reconcile(any(), anyString(), anyString(), any())).thenReturn(Future.succeededFuture());
    when(mockCrbOps.reconcile(any(), any(), any())).thenReturn(Future.failedFuture("Message: Forbidden!"));
    when(mockServiceOps.reconcile(any(), any(), any(), any())).thenReturn(Future.succeededFuture());
    when(mockDcOps.reconcile(any(), any(), any(), any())).thenReturn(Future.succeededFuture());
    when(mockDcOps.scaleUp(any(), any(), any(), anyInt())).thenReturn(Future.succeededFuture());
    when(mockDcOps.scaleDown(any(), any(), any(), anyInt())).thenReturn(Future.succeededFuture());
    when(mockNetPolOps.reconcile(any(), eq(kc.getMetadata().getNamespace()), eq(KafkaConnectResources.deploymentName(kc.getMetadata().getName())), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new NetworkPolicy())));
    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)));
    when(mockConnectOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new KafkaConnect())));
    when(mockCmOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new ConfigMap())));
    when(mockPdbOps.reconcile(any(), anyString(), any(), any())).thenReturn(Future.succeededFuture(ReconcileResult.created(new PodDisruptionBudget())));
    KafkaConnectAssemblyOperator ops = new KafkaConnectAssemblyOperator(vertx, new PlatformFeaturesAvailability(true, kubernetesVersion), supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS));
    Checkpoint async = context.checkpoint();
    ops.createOrUpdate(new Reconciliation("test-trigger", KafkaConnect.RESOURCE_KIND, kcNamespace, kcName), kc).onComplete(context.succeeding(v -> 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) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) 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) ClusterRoleBindingOperator(io.strimzi.operator.common.operator.resource.ClusterRoleBindingOperator) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) Checkpoint(io.vertx.junit5.Checkpoint) BuildConfigOperator(io.strimzi.operator.common.operator.resource.BuildConfigOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) Reconciliation(io.strimzi.operator.common.Reconciliation) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) DeploymentOperator(io.strimzi.operator.common.operator.resource.DeploymentOperator) 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