Search in sources :

Example 11 with NetworkPolicyIngressRule

use of io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule 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 12 with NetworkPolicyIngressRule

use of io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule 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 13 with NetworkPolicyIngressRule

use of io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule in project strimzi by strimzi.

the class CruiseControlTest method testRestApiPortNetworkPolicyInTheSameNamespace.

@ParallelTest
public void testRestApiPortNetworkPolicyInTheSameNamespace() {
    NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().withMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator")).endPodSelector().build();
    NetworkPolicy np = cc.generateNetworkPolicy(namespace, null);
    assertThat(np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).findFirst().orElse(null), is(notNullValue()));
    List<NetworkPolicyPeer> rules = np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).map(NetworkPolicyIngressRule::getFrom).findFirst().orElse(null);
    assertThat(rules.size(), is(1));
    assertThat(rules.contains(clusterOperatorPeer), is(true));
}
Also used : Quantity(io.fabric8.kubernetes.api.model.Quantity) VolumeMount(io.fabric8.kubernetes.api.model.VolumeMount) CoreMatchers.is(org.hamcrest.CoreMatchers.is) DEFAULT_WEBSERVER_SSL_ENABLED(io.strimzi.operator.cluster.model.CruiseControl.DEFAULT_WEBSERVER_SSL_ENABLED) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) Storage(io.strimzi.api.kafka.model.storage.Storage) ParallelSuite(io.strimzi.test.annotations.ParallelSuite) SecurityContextBuilder(io.fabric8.kubernetes.api.model.SecurityContextBuilder) Matchers.hasItems(org.hamcrest.Matchers.hasItems) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) Collections.singletonList(java.util.Collections.singletonList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) PersistentClaimStorage(io.strimzi.api.kafka.model.storage.PersistentClaimStorage) DEFAULT_WEBSERVER_SECURITY_ENABLED(io.strimzi.operator.cluster.model.CruiseControl.DEFAULT_WEBSERVER_SECURITY_ENABLED) Map(java.util.Map) API_HEALTHCHECK_PATH(io.strimzi.operator.cluster.model.CruiseControl.API_HEALTHCHECK_PATH) ContainerEnvVar(io.strimzi.api.kafka.model.ContainerEnvVar) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) CRUISE_CONTROL_DEFAULT_GOALS_CONFIG_KEY(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters.CRUISE_CONTROL_DEFAULT_GOALS_CONFIG_KEY) Affinity(io.fabric8.kubernetes.api.model.Affinity) IpFamilyPolicy(io.strimzi.api.kafka.model.template.IpFamilyPolicy) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Capacity(io.strimzi.operator.cluster.model.cruisecontrol.Capacity) ParallelTest(io.strimzi.test.annotations.ParallelTest) Collections.emptyList(java.util.Collections.emptyList) Matchers.allOf(org.hamcrest.Matchers.allOf) EnvVarBuilder(io.fabric8.kubernetes.api.model.EnvVarBuilder) ENV_VAR_CRUISE_CONTROL_CAPACITY_CONFIGURATION(io.strimzi.operator.cluster.model.CruiseControl.ENV_VAR_CRUISE_CONTROL_CAPACITY_CONFIGURATION) CruiseControlResources(io.strimzi.api.kafka.model.CruiseControlResources) NodeSelectorTermBuilder(io.fabric8.kubernetes.api.model.NodeSelectorTermBuilder) List(java.util.List) EphemeralStorage(io.strimzi.api.kafka.model.storage.EphemeralStorage) Labels(io.strimzi.operator.common.model.Labels) PodSecurityContextBuilder(io.fabric8.kubernetes.api.model.PodSecurityContextBuilder) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) CRUISE_CONTROL_ANOMALY_DETECTION_CONFIG_KEY(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters.CRUISE_CONTROL_ANOMALY_DETECTION_CONFIG_KEY) HostAliasBuilder(io.fabric8.kubernetes.api.model.HostAliasBuilder) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) EnvVar(io.fabric8.kubernetes.api.model.EnvVar) Container(io.fabric8.kubernetes.api.model.Container) CruiseControlSpecBuilder(io.strimzi.api.kafka.model.CruiseControlSpecBuilder) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ResourceRequirementsBuilder(io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder) SingleVolumeStorage(io.strimzi.api.kafka.model.storage.SingleVolumeStorage) IpFamily(io.strimzi.api.kafka.model.template.IpFamily) HashMap(java.util.HashMap) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) ArrayList(java.util.ArrayList) Matchers.hasProperty(org.hamcrest.Matchers.hasProperty) HostAlias(io.fabric8.kubernetes.api.model.HostAlias) JmxPrometheusExporterMetrics(io.strimzi.api.kafka.model.JmxPrometheusExporterMetrics) SecurityContext(io.fabric8.kubernetes.api.model.SecurityContext) JmxPrometheusExporterMetricsBuilder(io.strimzi.api.kafka.model.JmxPrometheusExporterMetricsBuilder) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) InlineLogging(io.strimzi.api.kafka.model.InlineLogging) MetricsConfig(io.strimzi.api.kafka.model.MetricsConfig) TestUtils(io.strimzi.test.TestUtils) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Volume(io.fabric8.kubernetes.api.model.Volume) JbodStorage(io.strimzi.api.kafka.model.storage.JbodStorage) CruiseControlConfigurationParameters(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters) Toleration(io.fabric8.kubernetes.api.model.Toleration) TolerationBuilder(io.fabric8.kubernetes.api.model.TolerationBuilder) AffinityBuilder(io.fabric8.kubernetes.api.model.AffinityBuilder) Reconciliation(io.strimzi.operator.common.Reconciliation) SystemPropertyBuilder(io.strimzi.api.kafka.model.SystemPropertyBuilder) ConfigMapKeySelectorBuilder(io.fabric8.kubernetes.api.model.ConfigMapKeySelectorBuilder) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) API_USER_NAME(io.strimzi.operator.cluster.model.CruiseControl.API_USER_NAME) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) CruiseControlSpec(io.strimzi.api.kafka.model.CruiseControlSpec) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) Kafka(io.strimzi.api.kafka.model.Kafka) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) BrokerCapacity(io.strimzi.api.kafka.model.balancing.BrokerCapacity) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) ParallelTest(io.strimzi.test.annotations.ParallelTest)

Example 14 with NetworkPolicyIngressRule

use of io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule in project strimzi by strimzi.

the class CruiseControlTest method testRestApiPortNetworkPolicy.

@ParallelTest
public void testRestApiPortNetworkPolicy() {
    NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder().withNewPodSelector().withMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator")).endPodSelector().withNewNamespaceSelector().endNamespaceSelector().build();
    NetworkPolicy np = cc.generateNetworkPolicy("operator-namespace", null);
    assertThat(np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).findFirst().orElse(null), is(notNullValue()));
    List<NetworkPolicyPeer> rules = np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).map(NetworkPolicyIngressRule::getFrom).findFirst().orElse(null);
    assertThat(rules.size(), is(1));
    assertThat(rules.contains(clusterOperatorPeer), is(true));
}
Also used : Quantity(io.fabric8.kubernetes.api.model.Quantity) VolumeMount(io.fabric8.kubernetes.api.model.VolumeMount) CoreMatchers.is(org.hamcrest.CoreMatchers.is) DEFAULT_WEBSERVER_SSL_ENABLED(io.strimzi.operator.cluster.model.CruiseControl.DEFAULT_WEBSERVER_SSL_ENABLED) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) Storage(io.strimzi.api.kafka.model.storage.Storage) ParallelSuite(io.strimzi.test.annotations.ParallelSuite) SecurityContextBuilder(io.fabric8.kubernetes.api.model.SecurityContextBuilder) Matchers.hasItems(org.hamcrest.Matchers.hasItems) PodDisruptionBudget(io.fabric8.kubernetes.api.model.policy.v1.PodDisruptionBudget) Collections.singletonList(java.util.Collections.singletonList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) AfterAll(org.junit.jupiter.api.AfterAll) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) PersistentClaimStorage(io.strimzi.api.kafka.model.storage.PersistentClaimStorage) DEFAULT_WEBSERVER_SECURITY_ENABLED(io.strimzi.operator.cluster.model.CruiseControl.DEFAULT_WEBSERVER_SECURITY_ENABLED) Map(java.util.Map) API_HEALTHCHECK_PATH(io.strimzi.operator.cluster.model.CruiseControl.API_HEALTHCHECK_PATH) ContainerEnvVar(io.strimzi.api.kafka.model.ContainerEnvVar) ResourceUtils(io.strimzi.operator.cluster.ResourceUtils) CRUISE_CONTROL_DEFAULT_GOALS_CONFIG_KEY(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters.CRUISE_CONTROL_DEFAULT_GOALS_CONFIG_KEY) Affinity(io.fabric8.kubernetes.api.model.Affinity) IpFamilyPolicy(io.strimzi.api.kafka.model.template.IpFamilyPolicy) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Capacity(io.strimzi.operator.cluster.model.cruisecontrol.Capacity) ParallelTest(io.strimzi.test.annotations.ParallelTest) Collections.emptyList(java.util.Collections.emptyList) Matchers.allOf(org.hamcrest.Matchers.allOf) EnvVarBuilder(io.fabric8.kubernetes.api.model.EnvVarBuilder) ENV_VAR_CRUISE_CONTROL_CAPACITY_CONFIGURATION(io.strimzi.operator.cluster.model.CruiseControl.ENV_VAR_CRUISE_CONTROL_CAPACITY_CONFIGURATION) CruiseControlResources(io.strimzi.api.kafka.model.CruiseControlResources) NodeSelectorTermBuilder(io.fabric8.kubernetes.api.model.NodeSelectorTermBuilder) List(java.util.List) EphemeralStorage(io.strimzi.api.kafka.model.storage.EphemeralStorage) Labels(io.strimzi.operator.common.model.Labels) PodSecurityContextBuilder(io.fabric8.kubernetes.api.model.PodSecurityContextBuilder) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) CRUISE_CONTROL_ANOMALY_DETECTION_CONFIG_KEY(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters.CRUISE_CONTROL_ANOMALY_DETECTION_CONFIG_KEY) HostAliasBuilder(io.fabric8.kubernetes.api.model.HostAliasBuilder) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) EnvVar(io.fabric8.kubernetes.api.model.EnvVar) Container(io.fabric8.kubernetes.api.model.Container) CruiseControlSpecBuilder(io.strimzi.api.kafka.model.CruiseControlSpecBuilder) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ResourceRequirementsBuilder(io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder) SingleVolumeStorage(io.strimzi.api.kafka.model.storage.SingleVolumeStorage) IpFamily(io.strimzi.api.kafka.model.template.IpFamily) HashMap(java.util.HashMap) KafkaBuilder(io.strimzi.api.kafka.model.KafkaBuilder) ArrayList(java.util.ArrayList) Matchers.hasProperty(org.hamcrest.Matchers.hasProperty) HostAlias(io.fabric8.kubernetes.api.model.HostAlias) JmxPrometheusExporterMetrics(io.strimzi.api.kafka.model.JmxPrometheusExporterMetrics) SecurityContext(io.fabric8.kubernetes.api.model.SecurityContext) JmxPrometheusExporterMetricsBuilder(io.strimzi.api.kafka.model.JmxPrometheusExporterMetricsBuilder) KafkaVersionTestUtils(io.strimzi.operator.cluster.KafkaVersionTestUtils) InlineLogging(io.strimzi.api.kafka.model.InlineLogging) MetricsConfig(io.strimzi.api.kafka.model.MetricsConfig) TestUtils(io.strimzi.test.TestUtils) Collections.singletonMap(java.util.Collections.singletonMap) Service(io.fabric8.kubernetes.api.model.Service) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Volume(io.fabric8.kubernetes.api.model.Volume) JbodStorage(io.strimzi.api.kafka.model.storage.JbodStorage) CruiseControlConfigurationParameters(io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters) Toleration(io.fabric8.kubernetes.api.model.Toleration) TolerationBuilder(io.fabric8.kubernetes.api.model.TolerationBuilder) AffinityBuilder(io.fabric8.kubernetes.api.model.AffinityBuilder) Reconciliation(io.strimzi.operator.common.Reconciliation) SystemPropertyBuilder(io.strimzi.api.kafka.model.SystemPropertyBuilder) ConfigMapKeySelectorBuilder(io.fabric8.kubernetes.api.model.ConfigMapKeySelectorBuilder) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) API_USER_NAME(io.strimzi.operator.cluster.model.CruiseControl.API_USER_NAME) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) CruiseControlSpec(io.strimzi.api.kafka.model.CruiseControlSpec) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) Kafka(io.strimzi.api.kafka.model.Kafka) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Collections(java.util.Collections) BrokerCapacity(io.strimzi.api.kafka.model.balancing.BrokerCapacity) NetworkPolicyPeer(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer) NetworkPolicyIngressRule(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) NetworkPolicyPeerBuilder(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder) ParallelTest(io.strimzi.test.annotations.ParallelTest)

Example 15 with NetworkPolicyIngressRule

use of io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule 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, ZookeeperCluster.zookeeperClusterName(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, ZookeeperCluster.zookeeperClusterName(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(5));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, KafkaCluster.kafkaClusterName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(0), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, ZookeeperCluster.zookeeperClusterName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(1), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).build()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, EntityOperator.entityOperatorName(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()));
    podSelector = new LabelSelector();
    podSelector.setMatchLabels(Collections.singletonMap(Labels.STRIMZI_NAME_LABEL, CruiseControl.cruiseControlName(zc.getCluster())));
    assertThat(clientsRule.getFrom().get(4), is(new NetworkPolicyPeerBuilder().withPodSelector(podSelector).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)

Aggregations

NetworkPolicy (io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy)25 NetworkPolicyIngressRule (io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyIngressRule)25 NetworkPolicyPeer (io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer)23 NetworkPolicyPeerBuilder (io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeerBuilder)22 ArrayList (java.util.ArrayList)22 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)18 Kafka (io.strimzi.api.kafka.model.Kafka)16 ParallelTest (io.strimzi.test.annotations.ParallelTest)16 Service (io.fabric8.kubernetes.api.model.Service)15 ConfigMapKeySelectorBuilder (io.fabric8.kubernetes.api.model.ConfigMapKeySelectorBuilder)14 Container (io.fabric8.kubernetes.api.model.Container)14 EnvVar (io.fabric8.kubernetes.api.model.EnvVar)14 HostAlias (io.fabric8.kubernetes.api.model.HostAlias)14 HostAliasBuilder (io.fabric8.kubernetes.api.model.HostAliasBuilder)14 PodSecurityContextBuilder (io.fabric8.kubernetes.api.model.PodSecurityContextBuilder)14 Quantity (io.fabric8.kubernetes.api.model.Quantity)14 ResourceRequirementsBuilder (io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder)14 SecurityContext (io.fabric8.kubernetes.api.model.SecurityContext)14 SecurityContextBuilder (io.fabric8.kubernetes.api.model.SecurityContextBuilder)14 ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)14