def _get_network_policy_spec(self, spec): ''' Return V1NetworkPolicySpec ''' ingress_rules = spec.get('ingress', []) ingress_rules_obj = [] egress_rules = spec.get('egress', []) egress_rules_obj = [] policy_types = spec.get('policy_types', None) pod_selector = self._get_label_selector(**spec['pod_selector']) for rule in ingress_rules: _from = self._get_network_policy_peer_list(rule_list=rule.get('from', [])) ports = self._get_network_policy_port_list(rule.get('ports', [])) ingress_rules_obj.append( client.V1NetworkPolicyIngressRule( _from=_from, ports=ports)) for rule in egress_rules: to = self._get_network_policy_peer_list(rule_list=rule.get('to', [])) ports = self._get_network_policy_port_list(rule.get('egress_ports', [])) egress_rules_obj.append( client.V1NetworkPolicyEgressRule( to=to, ports=ports)) return client.V1NetworkPolicySpec(ingress=ingress_rules_obj, egress=egress_rules_obj, pod_selector=pod_selector, policy_types=policy_types)
def simple_networkpolicy(): """Return the Kubernetes config matching the simple-networkpolicy.yaml manifest.""" return client.V1NetworkPolicy( api_version='networking.k8s.io/v1', kind='NetworkPolicy', metadata=client.V1ObjectMeta(name='default-deny'), spec=client.V1NetworkPolicySpec( pod_selector=client.V1LabelSelector(), policy_types=["Egress", "Ingress"], ))
def create_network_policy(policy_name, **kwargs): networkingv1 = client.NetworkingV1Api() policy_namespace = kwargs[ 'namespace'] if 'namespace' in kwargs else 'default' policy_labels = kwargs['labels'] if 'labels' in kwargs else {} policy_annotations = kwargs[ 'annotations'] if 'annotations' in kwargs else {} match_labels = kwargs['match_labels'] if 'match_labels' in kwargs else {} match_expressions = kwargs[ 'match_expressions'] if 'match_expressions' in kwargs else [] egress = kwargs['egress'] if 'egress' in kwargs else [] ingress = kwargs['ingress'] if 'ingress' in kwargs else [] egress_len = len(egress) ingress_len = len(ingress) policy_types = \ ["Ingress", "Egress"] if ingress_len > 0 and egress_len > 0 else \ ["Ingress"] if ingress_len > 0 and egress_len == 0 else \ ["Egress"] if egress_len > 0 and ingress_len == 0 else \ [] if not policy_types: logger.warning( "Warning: Creating NetworkPolicy with empty policy_types") if not match_labels and not match_expressions: logger.warning( "Warning: Creating NetworkPolicy that would operate on all resources" ) policy = networkingv1.create_namespaced_network_policy( namespace=policy_namespace, body=client.V1NetworkPolicy( api_version='v1', kind='NetworkPolicy', metadata=client.V1ObjectMeta(name=policy_name, namespace=policy_namespace, annotations=policy_annotations, labels=policy_labels), spec=client.V1NetworkPolicySpec( egress=egress, ingress=ingress, policy_types=policy_types, pod_selector=client.V1LabelSelector( match_expressions=match_expressions, match_labels=match_labels)))) return policy
def create_network_policy(cls, name=None, namespace='default', match_labels=None, match_expressions=None, ingress_port=None, ingress_port_protocol='TCP', ingress_ipblock_cidr=None, ingress_ipblock_except=[], egress_port=None, egress_port_protocol='TCP', egress_ipblock_cidr=None, egress_ipblock_except=[]): if not name: name = data_utils.rand_name(prefix='kuryr-network-policy') np = k8s_client.V1NetworkPolicy() np.kind = 'NetworkPolicy' np.api_version = 'networking.k8s.io/v1' np.metadata = k8s_client.V1ObjectMeta(name=name, namespace=namespace) to, _from = None, None if egress_ipblock_cidr: to = [k8s_client.V1NetworkPolicyPeer( ip_block=k8s_client.V1IPBlock(cidr=egress_ipblock_cidr, _except=egress_ipblock_except))] if ingress_ipblock_cidr: _from = [k8s_client.V1NetworkPolicyPeer( ip_block=k8s_client.V1IPBlock(cidr=ingress_ipblock_cidr, _except=ingress_ipblock_except))] if ingress_port: ingress_port = [k8s_client.V1NetworkPolicyPort( port=ingress_port, protocol=ingress_port_protocol)] if egress_port: egress_port = [k8s_client.V1NetworkPolicyPort( port=egress_port, protocol=egress_port_protocol)] np.spec = k8s_client.V1NetworkPolicySpec( egress=[k8s_client.V1NetworkPolicyEgressRule( ports=egress_port, to=to)], ingress=[k8s_client.V1NetworkPolicyIngressRule( ports=ingress_port, _from=_from)], pod_selector=k8s_client.V1LabelSelector( match_expressions=match_expressions, match_labels=match_labels), policy_types=['Ingress', 'Egress']) return k8s_client.NetworkingV1Api( ).create_namespaced_network_policy(namespace=namespace, body=np)
def create_namespace(self, body, message): """ Listen to the `exchange` namespace, | and create the namespace accordly to the messages. | Idempotent. :param body: The message's content. :type body: dict :param message: The namespace to create. :type message: kombu.message.Message :returns: The creation state :rtype: bool """ payload = client.V1Namespace() payload.metadata = client.V1ObjectMeta(name=body['namespace']) core_v1 = client.CoreV1Api() network_v1 = client.NetworkingV1Api() policy = client.V1NetworkPolicy(api_version='networking.k8s.io/v1', kind='NetworkPolicy') policy.metadata = client.V1ObjectMeta(name='deny-namespaces-traffic', namespace=body['namespace']) policy.spec = client.V1NetworkPolicySpec( pod_selector=client.V1LabelSelector(match_labels={}), ingress=[ client.V1NetworkPolicyIngressRule(_from=[ client.V1NetworkPolicyPeer( pod_selector=client.V1LabelSelector()) ]) ]) #Idempotent try: core_v1.create_namespace(payload) core_v1.patch_namespaced_service_account( 'default', body['namespace'], {'automount_service_account_token': False}) network_v1.create_namespaced_network_policy( body['namespace'], policy) except ApiException as e: LOGGER.error(e) if e.status != 409: # 409 == Conclict => Already exist raise message.ack() return True
def test_network_policy_hairpin_traffic(self): namespace_name, namespace = self.create_namespace() self.addCleanup(self.delete_namespace, namespace_name) svc_name, svc_pods = self.create_setup_for_service_test( namespace=namespace_name, cleanup=False, save=False, pod_num=1) self.check_service_internal_connectivity(namespace=namespace_name, pod_num=1, service_name=svc_name, pod_name=svc_pods[0]) policy_name = data_utils.rand_name(prefix='kuryr-policy') np = k8s_client.V1NetworkPolicy( kind='NetworkPolicy', api_version='networking.k8s.io/v1', metadata=k8s_client.V1ObjectMeta(name=policy_name, namespace=namespace_name), spec=k8s_client.V1NetworkPolicySpec( pod_selector=k8s_client.V1LabelSelector(), policy_types=['Egress', 'Ingress'], ingress=[ k8s_client.V1NetworkPolicyIngressRule(_from=[ k8s_client.V1NetworkPolicyPeer( pod_selector=k8s_client.V1LabelSelector(), ), ], ), ], egress=[ k8s_client.V1NetworkPolicyEgressRule(to=[ k8s_client.V1NetworkPolicyPeer( pod_selector=k8s_client.V1LabelSelector(), ), ], ), ], ), ) k8s_client.NetworkingV1Api().create_namespaced_network_policy( namespace=namespace_name, body=np) # Just to wait for SGs. self.get_sg_rules_for_np(namespace_name, policy_name) self.check_service_internal_connectivity(namespace=namespace_name, pod_num=1, service_name=svc_name, pod_name=svc_pods[0])