From d9205cc55f810f37083819acc0ca14bd7367d0c7 Mon Sep 17 00:00:00 2001 From: gunjan5 Date: Fri, 4 Aug 2017 16:59:20 -0700 Subject: [PATCH] bugfix: fix handling of empty namespaceSelector when using Kubernetes datastore driver --- lib/backend/k8s/conversion.go | 5 ++++ lib/backend/k8s/conversion_test.go | 42 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/lib/backend/k8s/conversion.go b/lib/backend/k8s/conversion.go index 0590f8c91..bf12a903f 100644 --- a/lib/backend/k8s/conversion.go +++ b/lib/backend/k8s/conversion.go @@ -269,6 +269,11 @@ func (c converter) k8sSelectorToCalico(s *metav1.LabelSelector, ns *string) stri } } + // If namespace selector is empty then we select all namespaces. + if len(selectors) == 0 && ns == nil { + selectors = []string{"has(calico/k8s_ns)"} + } + return strings.Join(selectors, " && ") } diff --git a/lib/backend/k8s/conversion_test.go b/lib/backend/k8s/conversion_test.go index 3e3a3c8e8..52ca88347 100644 --- a/lib/backend/k8s/conversion_test.go +++ b/lib/backend/k8s/conversion_test.go @@ -471,6 +471,48 @@ var _ = Describe("Test NetworkPolicy conversion", func() { Expect(pol.Value.(*model.Policy).OutboundRules[0]).To(Equal(model.Rule{Action: "allow"})) }) + It("should parse a NetworkPolicy with an empty namespaceSelector", func() { + np := extensions.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "testPolicy", + Namespace: "default", + }, + Spec: extensions.NetworkPolicySpec{ + PodSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{"label": "value"}, + }, + Ingress: []extensions.NetworkPolicyIngressRule{ + extensions.NetworkPolicyIngressRule{ + From: []extensions.NetworkPolicyPeer{ + extensions.NetworkPolicyPeer{ + NamespaceSelector: &metav1.LabelSelector{ + MatchLabels: map[string]string{}, + }, + }, + }, + }, + }, + }, + } + + // Parse the policy. + pol, err := c.networkPolicyToPolicy(&np) + Expect(err).NotTo(HaveOccurred()) + + // Assert key fields are correct. + Expect(pol.Key.(model.PolicyKey).Name).To(Equal("np.projectcalico.org/default.testPolicy")) + + // Assert value fields are correct. + Expect(int(*pol.Value.(*model.Policy).Order)).To(Equal(1000)) + Expect(pol.Value.(*model.Policy).Selector).To(Equal("calico/k8s_ns == 'default' && label == 'value'")) + Expect(len(pol.Value.(*model.Policy).InboundRules)).To(Equal(1)) + Expect(pol.Value.(*model.Policy).InboundRules[0].SrcSelector).To(Equal("has(calico/k8s_ns)")) + + // OutboundRules should only have one rule and it should be allow. + Expect(len(pol.Value.(*model.Policy).OutboundRules)).To(Equal(1)) + Expect(pol.Value.(*model.Policy).OutboundRules[0]).To(Equal(model.Rule{Action: "allow"})) + }) + It("should parse a NetworkPolicy with podSelector.MatchExpressions", func() { np := extensions.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{