From c1b690a25181955a16cb7098266b13f6e27fb5dd Mon Sep 17 00:00:00 2001 From: Su Wang Date: Tue, 2 Jun 2020 14:29:36 -0700 Subject: [PATCH 1/6] Agent supports ExternalEntity. This commit moves ToAddresses/FromAddresses in CompletedRule and AddressSetByGroup in ruleCache to use GroupMemberSet instead of GroupMmeberPodSet. Thus both Pods and ExternalEntities are expressed as GroupMember when in these fields. Pods in appliedTo field continue be expressed by existing GroupMemberPod, and migration to GroupMember shall be done in a subsequent PR. --- pkg/agent/controller/networkpolicy/cache.go | 66 ++++++--- .../controller/networkpolicy/cache_test.go | 68 ++++----- .../networkpolicy_controller_test.go | 28 ++-- .../controller/networkpolicy/reconciler.go | 105 +++++++++----- .../networkpolicy/reconciler_test.go | 4 +- pkg/apis/controlplane/v1beta1/sets.go | 129 +++++++++++++++++- 6 files changed, 298 insertions(+), 102 deletions(-) diff --git a/pkg/agent/controller/networkpolicy/cache.go b/pkg/agent/controller/networkpolicy/cache.go index ebb36591077..9e89b1cde02 100644 --- a/pkg/agent/controller/networkpolicy/cache.go +++ b/pkg/agent/controller/networkpolicy/cache.go @@ -93,10 +93,10 @@ func hashRule(r *rule) string { // It's the struct used by reconciler. type CompletedRule struct { *rule - // Source Pods of this rule, can't coexist with ToAddresses. - FromAddresses v1beta1.GroupMemberPodSet - // Destination Pods of this rule, can't coexist with FromAddresses. - ToAddresses v1beta1.GroupMemberPodSet + // Source GroupMembers of this rule, can't coexist with ToAddresses. + FromAddresses v1beta1.GroupMemberSet + // Destination GroupMembers of this rule, can't coexist with FromAddresses. + ToAddresses v1beta1.GroupMemberSet // Target Pods of this rule. Pods v1beta1.GroupMemberPodSet } @@ -128,8 +128,8 @@ type ruleCache struct { addressSetLock sync.RWMutex // addressSetByGroup stores the AddressGroup members. - // It is a mapping from group name to a set of Pods. - addressSetByGroup map[string]v1beta1.GroupMemberPodSet + // It is a mapping from group name to a set of GroupMembers. + addressSetByGroup map[string]v1beta1.GroupMemberSet policyMapLock sync.RWMutex // policyMap is a map using NetworkPolicy UID as the key. @@ -252,14 +252,21 @@ func (c *ruleCache) GetAddressGroups() []v1beta1.AddressGroup { var ret []v1beta1.AddressGroup c.addressSetLock.RLock() defer c.addressSetLock.RUnlock() + for k, v := range c.addressSetByGroup { var pods []v1beta1.GroupMemberPod - for _, pod := range v { - pods = append(pods, *pod) + var groupMembers []v1beta1.GroupMember + for _, member := range v { + if member.Pod != nil { + pods = append(pods, *member.ToGroupMemberPod()) + } else if member.ExternalEntity != nil { + groupMembers = append(groupMembers, *member) + } } ret = append(ret, v1beta1.AddressGroup{ - ObjectMeta: metav1.ObjectMeta{Name: k}, - Pods: pods, + ObjectMeta: metav1.ObjectMeta{Name: k}, + Pods: pods, + GroupMembers: groupMembers, }) } return ret @@ -320,7 +327,7 @@ func newRuleCache(dirtyRuleHandler func(string), podUpdate <-chan v1beta1.PodRef ) cache := &ruleCache{ podSetByGroup: make(map[string]v1beta1.GroupMemberPodSet), - addressSetByGroup: make(map[string]v1beta1.GroupMemberPodSet), + addressSetByGroup: make(map[string]v1beta1.GroupMemberSet), policyMap: make(map[string]*types.NamespacedName), rules: rules, dirtyRuleHandler: dirtyRuleHandler, @@ -398,19 +405,27 @@ func (c *ruleCache) AddAddressGroup(group *v1beta1.AddressGroup) error { } func (c *ruleCache) addAddressGroupLocked(group *v1beta1.AddressGroup) error { - podSet := v1beta1.GroupMemberPodSet{} + groupMemberSet := v1beta1.GroupMemberSet{} for i := range group.Pods { // Must not store address of loop iterator variable as it's the same // address taking different values in each loop iteration, otherwise // podSet would eventually contain only the last value. // https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable - podSet.Insert(&group.Pods[i]) + groupMemberSet.Insert(group.Pods[i].ToGroupMember()) } - oldPodSet, exists := c.addressSetByGroup[group.Name] - if exists && oldPodSet.Equal(podSet) { + for i := range group.GroupMembers { + // Must not store address of loop iterator variable as it's the same + // address taking different values in each loop iteration, otherwise + // podSet would eventually contain only the last value. + // https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable + groupMemberSet.Insert(&group.GroupMembers[i]) + } + + oldGroupMemberSet, exists := c.addressSetByGroup[group.Name] + if exists && oldGroupMemberSet.Equal(groupMemberSet) { return nil } - c.addressSetByGroup[group.Name] = podSet + c.addressSetByGroup[group.Name] = groupMemberSet c.onAddressGroupUpdate(group.Name) return nil } @@ -421,16 +436,23 @@ func (c *ruleCache) PatchAddressGroup(patch *v1beta1.AddressGroupPatch) error { c.addressSetLock.Lock() defer c.addressSetLock.Unlock() - podSet, exists := c.addressSetByGroup[patch.Name] + groupMemberSet, exists := c.addressSetByGroup[patch.Name] if !exists { return fmt.Errorf("AddressGroup %v doesn't exist in cache, can't be patched", patch.Name) } for i := range patch.AddedPods { - podSet.Insert(&patch.AddedPods[i]) + groupMemberSet.Insert(patch.AddedPods[i].ToGroupMember()) } for i := range patch.RemovedPods { - podSet.Delete(&patch.RemovedPods[i]) + groupMemberSet.Delete(patch.RemovedPods[i].ToGroupMember()) + } + for i := range patch.AddedGroupMembers { + groupMemberSet.Insert(&patch.AddedGroupMembers[i]) + } + for i := range patch.RemovedGroupMembers { + groupMemberSet.Delete(&patch.RemovedGroupMembers[i]) } + c.onAddressGroupUpdate(patch.Name) return nil } @@ -680,7 +702,7 @@ func (c *ruleCache) GetCompletedRule(ruleID string) (completedRule *CompletedRul } r := obj.(*rule) - var fromAddresses, toAddresses v1beta1.GroupMemberPodSet + var fromAddresses, toAddresses v1beta1.GroupMemberSet if r.Direction == v1beta1.DirectionIn { fromAddresses, completed = c.unionAddressGroups(r.From.AddressGroups) } else { @@ -725,11 +747,11 @@ func (c *ruleCache) onAddressGroupUpdate(groupName string) { // unionAddressGroups gets the union of addresses of the provided address groups. // If any group is not found, nil and false will be returned to indicate the // set is not complete yet. -func (c *ruleCache) unionAddressGroups(groupNames []string) (v1beta1.GroupMemberPodSet, bool) { +func (c *ruleCache) unionAddressGroups(groupNames []string) (v1beta1.GroupMemberSet, bool) { c.addressSetLock.RLock() defer c.addressSetLock.RUnlock() - set := v1beta1.NewGroupMemberPodSet() + set := v1beta1.NewGroupMemberSet() for _, groupName := range groupNames { curSet, exists := c.addressSetByGroup[groupName] if !exists { diff --git a/pkg/agent/controller/networkpolicy/cache_test.go b/pkg/agent/controller/networkpolicy/cache_test.go index fd6c4d7bbbe..39062d31e81 100644 --- a/pkg/agent/controller/networkpolicy/cache_test.go +++ b/pkg/agent/controller/networkpolicy/cache_test.go @@ -124,7 +124,11 @@ func newAppliedToGroupMember(name, namespace string, containerPorts ...v1beta1.N return &v1beta1.GroupMemberPod{Pod: &v1beta1.PodReference{Name: name, Namespace: namespace}, Ports: containerPorts} } -func newAddressGroupMember(ip string) *v1beta1.GroupMemberPod { +func newAddressGroupMember(ip string) *v1beta1.GroupMember { + return (&v1beta1.GroupMemberPod{IP: v1beta1.IPAddress(net.ParseIP(ip))}).ToGroupMember() +} + +func newAddressGroupMemberPod(ip string) *v1beta1.GroupMemberPod { return &v1beta1.GroupMemberPod{IP: v1beta1.IPAddress(net.ParseIP(ip))} } @@ -141,7 +145,7 @@ func TestRuleCacheAddAddressGroup(t *testing.T) { name string rules []*rule args *v1beta1.AddressGroup - expectedAddresses []*v1beta1.GroupMemberPod + expectedAddresses []*v1beta1.GroupMember expectedDirtyRules sets.String }{ { @@ -159,9 +163,9 @@ func TestRuleCacheAddAddressGroup(t *testing.T) { []*rule{rule1, rule2}, &v1beta1.AddressGroup{ ObjectMeta: metav1.ObjectMeta{Name: "group2"}, - Pods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1")}, + Pods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1")}, }, - []*v1beta1.GroupMemberPod{newAddressGroupMember("1.1.1.1")}, + []*v1beta1.GroupMember{newAddressGroupMember("1.1.1.1")}, sets.NewString("rule2"), }, { @@ -169,9 +173,9 @@ func TestRuleCacheAddAddressGroup(t *testing.T) { []*rule{rule1, rule2}, &v1beta1.AddressGroup{ ObjectMeta: metav1.ObjectMeta{Name: "group1"}, - Pods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")}, + Pods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")}, }, - []*v1beta1.GroupMemberPod{newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")}, + []*v1beta1.GroupMember{newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")}, sets.NewString("rule1", "rule2"), }, } @@ -298,56 +302,56 @@ func TestRuleCacheReplaceAddressGroups(t *testing.T) { tests := []struct { name string rules []*rule - preExistingGroups map[string]v1beta1.GroupMemberPodSet + preExistingGroups map[string]v1beta1.GroupMemberSet args []*v1beta1.AddressGroup - expectedGroups map[string]v1beta1.GroupMemberPodSet + expectedGroups map[string]v1beta1.GroupMemberSet expectedDirtyRules sets.String }{ { "stale-group-can-be-cleaned", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, []*v1beta1.AddressGroup{}, - map[string]v1beta1.GroupMemberPodSet{}, + map[string]v1beta1.GroupMemberSet{}, sets.NewString(), }, { "existing-group-can-be-updated", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, []*v1beta1.AddressGroup{ { ObjectMeta: metav1.ObjectMeta{Name: "group1"}, - Pods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.2"), *newAddressGroupMember("1.1.1.3")}, + Pods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.2"), *newAddressGroupMemberPod("1.1.1.3")}, }, }, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.2"), newAddressGroupMember("1.1.1.3"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.2"), newAddressGroupMember("1.1.1.3"))}, sets.NewString("rule1", "rule2"), }, { "unchanged-group-can-be-skipped", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, []*v1beta1.AddressGroup{ { ObjectMeta: metav1.ObjectMeta{Name: "group1"}, - Pods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1")}, + Pods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1")}, }, }, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, sets.NewString(), }, { "new-group-can-be-added", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{}, + map[string]v1beta1.GroupMemberSet{}, []*v1beta1.AddressGroup{ { ObjectMeta: metav1.ObjectMeta{Name: "group2"}, - Pods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.2")}, + Pods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.2")}, }, }, - map[string]v1beta1.GroupMemberPodSet{"group2": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.2"))}, + map[string]v1beta1.GroupMemberSet{"group2": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.2"))}, sets.NewString("rule2"), }, } @@ -636,8 +640,8 @@ func TestRuleCacheDeleteNetworkPolicy(t *testing.T) { } func TestRuleCacheGetCompletedRule(t *testing.T) { - addressGroup1 := v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("1.1.1.2")) - addressGroup2 := v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.3"), newAddressGroupMember("1.1.1.2")) + addressGroup1 := v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("1.1.1.2")) + addressGroup2 := v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.3"), newAddressGroupMember("1.1.1.2")) appliedToGroup1 := v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1"), newAppliedToGroupMember("pod2", "ns1")) appliedToGroup2 := v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod3", "ns1"), newAppliedToGroupMember("pod2", "ns1")) rule1 := &rule{ @@ -818,9 +822,9 @@ func TestRuleCachePatchAddressGroup(t *testing.T) { tests := []struct { name string rules []*rule - addressSetByGroup map[string]v1beta1.GroupMemberPodSet + addressSetByGroup map[string]v1beta1.GroupMemberSet args *v1beta1.AddressGroupPatch - expectedAddresses []*v1beta1.GroupMemberPod + expectedAddresses []*v1beta1.GroupMember expectedDirtyRules sets.String expectedErr bool }{ @@ -830,7 +834,7 @@ func TestRuleCachePatchAddressGroup(t *testing.T) { nil, &v1beta1.AddressGroupPatch{ ObjectMeta: metav1.ObjectMeta{Name: "group0"}, - AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")}, + AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")}, }, nil, sets.NewString(), @@ -839,26 +843,26 @@ func TestRuleCachePatchAddressGroup(t *testing.T) { { "add-and-remove-addresses-affecting-one-rule", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{"group2": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group2": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, &v1beta1.AddressGroupPatch{ ObjectMeta: metav1.ObjectMeta{Name: "group2"}, - AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMember("2.2.2.2"), *newAddressGroupMember("3.3.3.3")}, - RemovedPods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1")}, + AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("2.2.2.2"), *newAddressGroupMemberPod("3.3.3.3")}, + RemovedPods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1")}, }, - []*v1beta1.GroupMemberPod{newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")}, + []*v1beta1.GroupMember{newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")}, sets.NewString("rule2"), false, }, { "add-and-remove-addresses-affecting-two-rule", []*rule{rule1, rule2}, - map[string]v1beta1.GroupMemberPodSet{"group1": v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"))}, + map[string]v1beta1.GroupMemberSet{"group1": v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"))}, &v1beta1.AddressGroupPatch{ ObjectMeta: metav1.ObjectMeta{Name: "group1"}, - AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMember("2.2.2.2"), *newAddressGroupMember("3.3.3.3")}, - RemovedPods: []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1")}, + AddedPods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("2.2.2.2"), *newAddressGroupMemberPod("3.3.3.3")}, + RemovedPods: []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1")}, }, - []*v1beta1.GroupMemberPod{newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")}, + []*v1beta1.GroupMember{newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")}, sets.NewString("rule1", "rule2"), false, }, diff --git a/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go index 4fef19fe6e1..f76ca8b4ff2 100644 --- a/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go @@ -165,8 +165,8 @@ func TestAddSingleGroupRule(t *testing.T) { services := []v1beta1.Service{{Protocol: &protocolTCP, Port: &port}} desiredRule := &CompletedRule{ rule: &rule{Direction: v1beta1.DirectionIn, Services: services}, - FromAddresses: v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), - ToAddresses: v1beta1.NewGroupMemberPodSet(), + FromAddresses: v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), + ToAddresses: v1beta1.NewGroupMemberSet(), Pods: v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1")), } stopCh := make(chan struct{}) @@ -188,7 +188,7 @@ func TestAddSingleGroupRule(t *testing.T) { assert.Equal(t, 0, controller.GetAppliedToGroupNum()) // addressGroup1 comes, no rule will be synced due to missing appliedToGroup1 data. - addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")})) addressGroupWatcher.Action(watch.Bookmark, nil) select { case ruleID := <-reconciler.updated: @@ -242,8 +242,8 @@ func TestAddMultipleGroupsRule(t *testing.T) { services := []v1beta1.Service{{Protocol: &protocolTCP, Port: &port}} desiredRule := &CompletedRule{ rule: &rule{Direction: v1beta1.DirectionIn, Services: services}, - FromAddresses: v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")), - ToAddresses: v1beta1.NewGroupMemberPodSet(), + FromAddresses: v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2"), newAddressGroupMember("3.3.3.3")), + ToAddresses: v1beta1.NewGroupMemberSet(), Pods: v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1"), newAppliedToGroupMember("pod2", "ns2")), } stopCh := make(chan struct{}) @@ -251,7 +251,7 @@ func TestAddMultipleGroupsRule(t *testing.T) { go controller.Run(stopCh) // addressGroup1 comes, no rule will be synced. - addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")})) addressGroupWatcher.Action(watch.Bookmark, nil) // appliedToGroup1 comes, no rule will be synced. appliedToGroupWatcher.Add(newAppliedToGroup("appliedToGroup1", []v1beta1.GroupMemberPod{*newAppliedToGroupMember("pod1", "ns1")})) @@ -271,7 +271,7 @@ func TestAddMultipleGroupsRule(t *testing.T) { assert.Equal(t, 1, controller.GetAppliedToGroupNum()) // addressGroup2 comes, no rule will be synced due to missing appliedToGroup2 data. - addressGroupWatcher.Add(newAddressGroup("addressGroup2", []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("3.3.3.3")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup2", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("3.3.3.3")})) select { case ruleID := <-reconciler.updated: t.Fatalf("Expected no update, got %v", ruleID) @@ -325,7 +325,7 @@ func TestDeleteRule(t *testing.T) { defer close(stopCh) go controller.Run(stopCh) - addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")})) addressGroupWatcher.Action(watch.Bookmark, nil) appliedToGroupWatcher.Add(newAppliedToGroup("appliedToGroup1", []v1beta1.GroupMemberPod{*newAppliedToGroupMember("pod1", "ns1")})) appliedToGroupWatcher.Action(watch.Bookmark, nil) @@ -370,14 +370,14 @@ func TestAddNetworkPolicyWithMultipleRules(t *testing.T) { services := []v1beta1.Service{{Protocol: &protocolTCP, Port: &port}} desiredRule1 := &CompletedRule{ rule: &rule{Direction: v1beta1.DirectionIn, Services: services}, - FromAddresses: v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), - ToAddresses: v1beta1.NewGroupMemberPodSet(), + FromAddresses: v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), + ToAddresses: v1beta1.NewGroupMemberSet(), Pods: v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1")), } desiredRule2 := &CompletedRule{ rule: &rule{Direction: v1beta1.DirectionOut, Services: services}, - FromAddresses: v1beta1.NewGroupMemberPodSet(), - ToAddresses: v1beta1.NewGroupMemberPodSet(newAddressGroupMember("3.3.3.3"), newAddressGroupMember("4.4.4.4")), + FromAddresses: v1beta1.NewGroupMemberSet(), + ToAddresses: v1beta1.NewGroupMemberSet(newAddressGroupMember("3.3.3.3"), newAddressGroupMember("4.4.4.4")), Pods: v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1")), } stopCh := make(chan struct{}) @@ -388,8 +388,8 @@ func TestAddNetworkPolicyWithMultipleRules(t *testing.T) { policy1 := getNetworkPolicyWithMultipleRules("policy1", []string{"addressGroup1"}, []string{"addressGroup2"}, []string{"appliedToGroup1"}, services) networkPolicyWatcher.Add(policy1) networkPolicyWatcher.Action(watch.Bookmark, nil) - addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")})) - addressGroupWatcher.Add(newAddressGroup("addressGroup2", []v1beta1.GroupMemberPod{*newAddressGroupMember("3.3.3.3"), *newAddressGroupMember("4.4.4.4")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup1", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")})) + addressGroupWatcher.Add(newAddressGroup("addressGroup2", []v1beta1.GroupMemberPod{*newAddressGroupMemberPod("3.3.3.3"), *newAddressGroupMemberPod("4.4.4.4")})) addressGroupWatcher.Action(watch.Bookmark, nil) appliedToGroupWatcher.Add(newAppliedToGroup("appliedToGroup1", []v1beta1.GroupMemberPod{*newAppliedToGroupMember("pod1", "ns1")})) appliedToGroupWatcher.Action(watch.Bookmark, nil) diff --git a/pkg/agent/controller/networkpolicy/reconciler.go b/pkg/agent/controller/networkpolicy/reconciler.go index e3ef6b3c869..2a2cc8a151c 100644 --- a/pkg/agent/controller/networkpolicy/reconciler.go +++ b/pkg/agent/controller/networkpolicy/reconciler.go @@ -368,8 +368,8 @@ func (r *reconciler) computeOFRulesForAdd(rule *CompletedRule, ofPriority *uint1 ofRuleByServicesMap := map[servicesKey]*types.PolicyRule{} if rule.Direction == v1beta1.DirectionIn { - // Addresses got from source Pod IPs. - from1 := podsToOFAddresses(rule.FromAddresses) + // Addresses got from source GroupMembers' IPs. + from1 := groupMembersToOFAddresses(rule.FromAddresses) // Get addresses that in From IPBlock but not in Except IPBlocks. from2 := ipBlocksToOFAddresses(rule.From.IPBlocks) @@ -392,13 +392,12 @@ func (r *reconciler) computeOFRulesForAdd(rule *CompletedRule, ofPriority *uint1 ips := r.getPodIPs(rule.Pods) lastRealized.podIPs = ips from := ipsToOFAddresses(ips) - - podsByServicesMap, servicesMap := groupPodsByServices(rule.Services, rule.ToAddresses) - for svcKey, pods := range podsByServicesMap { + memberByServicesMap, servicesMap := groupMembersByServices(rule.Services, rule.ToAddresses) + for svcKey, members := range memberByServicesMap { ofRuleByServicesMap[svcKey] = &types.PolicyRule{ Direction: v1beta1.DirectionOut, From: from, - To: podsToOFAddresses(pods), + To: groupMembersToOFAddresses(members), Service: filterUnresolvablePort(servicesMap[svcKey]), Action: rule.Action, Priority: ofPriority, @@ -492,10 +491,10 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, // As rule identifier is calculated from the rule's content, the update can // only happen to Group members. if newRule.Direction == v1beta1.DirectionIn { - from1 := podsToOFAddresses(newRule.FromAddresses) + from1 := groupMembersToOFAddresses(newRule.FromAddresses) from2 := ipBlocksToOFAddresses(newRule.From.IPBlocks) - addedFrom := podsToOFAddresses(newRule.FromAddresses.Difference(lastRealized.FromAddresses)) - deletedFrom := podsToOFAddresses(lastRealized.FromAddresses.Difference(newRule.FromAddresses)) + addedFrom := groupMembersToOFAddresses(newRule.FromAddresses.Difference(lastRealized.FromAddresses)) + deletedFrom := groupMembersToOFAddresses(lastRealized.FromAddresses.Difference(newRule.FromAddresses)) podsByServicesMap, servicesMap := groupPodsByServices(newRule.Services, newRule.Pods) for svcKey, pods := range podsByServicesMap { @@ -540,16 +539,16 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, addedFrom := ipsToOFAddresses(newIPs.Difference(lastRealized.podIPs)) deletedFrom := ipsToOFAddresses(lastRealized.podIPs.Difference(newIPs)) - podsByServicesMap, servicesMap := groupPodsByServices(newRule.Services, newRule.ToAddresses) + memberByServicesMap, servicesMap := groupMembersByServices(newRule.Services, newRule.ToAddresses) // Same as the process in `add`, we must ensure the group for the original services is present // in podsByServicesMap, so that this group won't be removed and its "From" will be updated. svcKey := normalizeServices(newRule.Services) - if _, exists := podsByServicesMap[svcKey]; !exists { - podsByServicesMap[svcKey] = v1beta1.NewGroupMemberPodSet() + if _, exists := memberByServicesMap[svcKey]; !exists { + memberByServicesMap[svcKey] = v1beta1.NewGroupMemberSet() servicesMap[svcKey] = newRule.Services } - prevPodsByServicesMap, _ := groupPodsByServices(lastRealized.Services, lastRealized.ToAddresses) - for svcKey, pods := range podsByServicesMap { + prevMembersByServicesMap, _ := groupMembersByServices(lastRealized.Services, lastRealized.ToAddresses) + for svcKey, members := range memberByServicesMap { ofID, exists := lastRealized.ofIDs[svcKey] if !exists { ofID, err := r.idAllocator.allocate() @@ -559,7 +558,7 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, ofRule := &types.PolicyRule{ Direction: v1beta1.DirectionOut, From: from, - To: podsToOFAddresses(pods), + To: groupMembersToOFAddresses(members), Service: filterUnresolvablePort(servicesMap[svcKey]), Action: newRule.Action, Priority: ofPriority, @@ -573,8 +572,8 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, } lastRealized.ofIDs[svcKey] = ofID } else { - addedTo := podsToOFAddresses(pods.Difference(prevPodsByServicesMap[svcKey])) - deletedTo := podsToOFAddresses(prevPodsByServicesMap[svcKey].Difference(pods)) + addedTo := groupMembersToOFAddresses(members.Difference(prevMembersByServicesMap[svcKey])) + deletedTo := groupMembersToOFAddresses(prevMembersByServicesMap[svcKey].Difference(members)) if err := r.updateOFRule(ofID, addedFrom, addedTo, deletedFrom, deletedTo, ofPriority); err != nil { return err } @@ -749,7 +748,7 @@ func groupPodsByServices(services []v1beta1.Service, pods v1beta1.GroupMemberPod resolvedServices := make([]v1beta1.Service, len(services)) for podKey, pod := range pods { for i := range services { - resolvedServices[i] = *resolveService(&services[i], pod) + resolvedServices[i] = *resolveService(&services[i], *pod.ToGroupMember()) } svcKey := normalizeServices(resolvedServices) if _, exists := podsByServicesMap[svcKey]; !exists { @@ -763,6 +762,46 @@ func groupPodsByServices(services []v1beta1.Service, pods v1beta1.GroupMemberPod return podsByServicesMap, servicesMap } +// groupMembersByServices groups the provided groupMembers based on their services resolving result. +// A map of servicesHash to the grouped members and a map of servicesHash to the services resolving result will be returned. +func groupMembersByServices(services []v1beta1.Service, memberSet v1beta1.GroupMemberSet) (map[servicesKey]v1beta1.GroupMemberSet, map[servicesKey][]v1beta1.Service) { + membersByServicesMap := map[servicesKey]v1beta1.GroupMemberSet{} + servicesMap := map[servicesKey][]v1beta1.Service{} + + // If there is no named port in services, all members are in same group. + namedPortServiceExist := false + for _, svc := range services { + if svc.Port != nil && svc.Port.Type == intstr.String { + namedPortServiceExist = true + break + } + } + if !namedPortServiceExist { + svcKey := normalizeServices(services) + membersByServicesMap[svcKey] = memberSet + servicesMap[svcKey] = services + return membersByServicesMap, servicesMap + } + // Reuse the slice to avoid memory reallocations in the following loop. The + // optimization makes difference as the number of group members might get up to tens + // of thousands. + resolvedServices := make([]v1beta1.Service, len(services)) + for memberKey, member := range memberSet { + for i := range services { + resolvedServices[i] = *resolveService(&services[i], *member) + } + svcKey := normalizeServices(resolvedServices) + if _, exists := membersByServicesMap[svcKey]; !exists { + membersByServicesMap[svcKey] = v1beta1.NewGroupMemberSet() + // Copy resolvedServices as it may be updated in next iteration. + servicesMap[svcKey] = make([]v1beta1.Service, len(resolvedServices)) + copy(servicesMap[svcKey], resolvedServices) + } + membersByServicesMap[svcKey][memberKey] = member + } + return membersByServicesMap, servicesMap +} + func ofPortsToOFAddresses(ofPorts sets.Int32) []types.Address { // Must not return nil as it means not restricted by addresses in Openflow implementation. addresses := make([]types.Address, 0, len(ofPorts)) @@ -772,11 +811,13 @@ func ofPortsToOFAddresses(ofPorts sets.Int32) []types.Address { return addresses } -func podsToOFAddresses(podSet v1beta1.GroupMemberPodSet) []types.Address { +func groupMembersToOFAddresses(groupMemberSet v1beta1.GroupMemberSet) []types.Address { // Must not return nil as it means not restricted by addresses in Openflow implementation. - addresses := make([]types.Address, 0, len(podSet)) - for _, p := range podSet { - addresses = append(addresses, openflow.NewIPAddress(net.IP(p.IP))) + addresses := make([]types.Address, 0, len(groupMemberSet)) + for _, member := range groupMemberSet { + for _, ep := range member.Endpoints { + addresses = append(addresses, openflow.NewIPAddress(net.IP(ep.IP))) + } } return addresses } @@ -814,8 +855,8 @@ func ipNetToOFAddress(in v1beta1.IPNet) *openflow.IPNetAddress { func ipsToOFAddresses(ips sets.String) []types.Address { // Must not return nil as it means not restricted by addresses in Openflow implementation. from := make([]types.Address, 0, len(ips)) - for ip := range ips { - from = append(from, openflow.NewIPAddress(net.ParseIP((ip)))) + for ipAddr := range ips { + from = append(from, openflow.NewIPAddress(net.ParseIP(ipAddr))) } return from } @@ -844,19 +885,21 @@ func filterUnresolvablePort(in []v1beta1.Service) []v1beta1.Service { } // resolveService resolves the port name of the provided service to a port number -// for the provided Pod. -func resolveService(service *v1beta1.Service, pod *v1beta1.GroupMemberPod) *v1beta1.Service { +// for the provided groupMember. +func resolveService(service *v1beta1.Service, member v1beta1.GroupMember) *v1beta1.Service { // If port is not specified or is already a number, return it as is. if service.Port == nil || service.Port.Type == intstr.Int { return service } - for _, port := range pod.Ports { - if port.Name == service.Port.StrVal && port.Protocol == *service.Protocol { - resolvedPort := intstr.FromInt(int(port.Port)) - return &v1beta1.Service{Protocol: service.Protocol, Port: &resolvedPort} + for _, ep := range member.Endpoints { + for _, port := range ep.Ports { + if port.Name == service.Port.StrVal && port.Protocol == *service.Protocol { + resolvedPort := intstr.FromInt(int(port.Port)) + return &v1beta1.Service{Protocol: service.Protocol, Port: &resolvedPort} + } } } - klog.Warningf("Can not resolve port %s for Pod %v", service.Port.StrVal, pod) + klog.Warningf("Can not resolve port %s for endpoints %v", service.Port.StrVal, member) // If not resolvable, return it as is. // The Pods that cannot resolve it will be grouped together. return service diff --git a/pkg/agent/controller/networkpolicy/reconciler_test.go b/pkg/agent/controller/networkpolicy/reconciler_test.go index bb4f9324464..55014a7cbac 100644 --- a/pkg/agent/controller/networkpolicy/reconciler_test.go +++ b/pkg/agent/controller/networkpolicy/reconciler_test.go @@ -33,8 +33,8 @@ import ( ) var ( - addressGroup1 = v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1")) - addressGroup2 = v1beta1.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.2")) + addressGroup1 = v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.1")) + addressGroup2 = v1beta1.NewGroupMemberSet(newAddressGroupMember("1.1.1.2")) appliedToGroup1 = v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod1", "ns1")) appliedToGroup2 = v1beta1.NewGroupMemberPodSet(newAppliedToGroupMember("pod2", "ns1")) diff --git a/pkg/apis/controlplane/v1beta1/sets.go b/pkg/apis/controlplane/v1beta1/sets.go index 64572e9c3e8..275c7466b24 100644 --- a/pkg/apis/controlplane/v1beta1/sets.go +++ b/pkg/apis/controlplane/v1beta1/sets.go @@ -14,7 +14,9 @@ package v1beta1 -import "strings" +import ( + "strings" +) // groupMemberPodKey is used to uniquely identify GroupMemberPod. Either Pod or // IP is used as unique key. @@ -115,3 +117,128 @@ func (s GroupMemberPodSet) Items() []*GroupMemberPod { } return res } + +// groupMemberKey is used to uniquely identify GroupMember. +type groupMemberKey string + +// GroupMemberSet is a set of GroupMembers. +// +k8s:openapi-gen=false +// +k8s:deepcopy-gen=false +type GroupMemberSet map[groupMemberKey]*GroupMember + +// normalizeGroupMember calculates the groupMemberKey of the provided +// GroupMember based on the Pod's namespaced name or IP. +func normalizeGroupMember(member *GroupMember) groupMemberKey { + // "/" is illegal in Namespace and name so is safe as the delimiter. + const delimiter = "/" + var b strings.Builder + if member.Pod != nil { + b.WriteString(member.Pod.Namespace) + b.WriteString(delimiter) + b.WriteString(member.Pod.Name) + } else if member.ExternalEntity != nil { + b.WriteString(member.ExternalEntity.Namespace) + b.WriteString(delimiter) + b.WriteString(member.ExternalEntity.Name) + } else if len(member.Endpoints) != 0 { + for _, ep := range member.Endpoints { + b.Write(ep.IP) + } + } + return groupMemberKey(b.String()) +} + +// NewGroupMemberSet builds a GroupMemberSet from a list of GroupMember. +func NewGroupMemberSet(items ...*GroupMember) GroupMemberSet { + m := GroupMemberSet{} + m.Insert(items...) + return m +} + +// Insert adds items to the set. +func (s GroupMemberSet) Insert(items ...*GroupMember) { + for _, item := range items { + s[normalizeGroupMember(item)] = item + } +} + +// Delete removes all items from the set. +func (s GroupMemberSet) Delete(items ...*GroupMember) { + for _, item := range items { + delete(s, normalizeGroupMember(item)) + } +} + +// Has returns true if and only if item is contained in the set. +func (s GroupMemberSet) Has(item *GroupMember) bool { + _, contained := s[normalizeGroupMember(item)] + return contained +} + +// Difference returns a set of GroupMembers that are not in o. +func (s GroupMemberSet) Difference(o GroupMemberSet) GroupMemberSet { + result := GroupMemberSet{} + for key, item := range s { + if _, contained := o[key]; !contained { + result[key] = item + } + } + return result +} + +// Union returns a new set which includes items in either m or o. +func (s GroupMemberSet) Union(o GroupMemberSet) GroupMemberSet { + result := GroupMemberSet{} + for key, item := range s { + result[key] = item + } + for key, item := range o { + result[key] = item + } + return result +} + +// IsSuperset returns true if and only if s1 is a superset of s2. +func (s GroupMemberSet) IsSuperset(o GroupMemberSet) bool { + for key := range o { + _, contained := s[key] + if !contained { + return false + } + } + return true +} + +// Equal returns true if and only if s1 is equal (as a set) to s2. +// Two sets are equal if their membership is identical. +// (In practice, this means same elements, order doesn't matter) +func (s GroupMemberSet) Equal(o GroupMemberSet) bool { + return len(s) == len(o) && s.IsSuperset(o) +} + +// Items returns the slice with contents in random order. +func (s GroupMemberSet) Items() []*GroupMember { + res := make([]*GroupMember, 0, len(s)) + for _, item := range s { + res = append(res, item) + } + return res +} + +// Conversion functions +func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { + return &GroupMemberPod{ + Pod: g.Pod, + IP: g.Endpoints[0].IP, + Ports: g.Endpoints[0].Ports, + } +} + +func (p *GroupMemberPod) ToGroupMember() *GroupMember { + return &GroupMember{ + Pod: p.Pod, + Endpoints: []Endpoint{ + {IP: p.IP, Ports: p.Ports}, + }, + } +} From a47f4eeb6921739325880d4bd023bea04e65326a Mon Sep 17 00:00:00 2001 From: Yang Ding Date: Tue, 2 Jun 2020 15:21:41 -0700 Subject: [PATCH 2/6] Add support for ANP and externalEntities in controller --- build/yamls/antrea-aks.yml | 12 + build/yamls/antrea-eks.yml | 12 + build/yamls/antrea-gke.yml | 12 + build/yamls/antrea-ipsec.yml | 12 + build/yamls/antrea.yml | 12 + build/yamls/base/controller-rbac.yml | 8 + build/yamls/base/crds.yml | 4 + cmd/antrea-controller/controller.go | 2 + pkg/apis/controlplane/sets.go | 125 ++++ pkg/apis/controlplane/v1beta1/generated.pb.go | 34 +- pkg/apis/controlplane/v1beta1/generated.proto | 8 +- pkg/apis/controlplane/v1beta1/types.go | 8 +- .../v1beta1/zz_generated.deepcopy.go | 10 +- .../v1beta1/zz_generated.conversion.go | 695 ++++++++++++++++++ pkg/apiserver/openapi/zz_generated.openapi.go | 12 +- .../networkpolicy/antreanetworkpolicy.go | 3 +- .../networkpolicy/clusternetworkpolicy.go | 2 +- .../clusternetworkpolicy_test.go | 48 +- pkg/controller/networkpolicy/crd_utils.go | 2 +- .../networkpolicy/crd_utils_test.go | 10 +- .../networkpolicy/networkpolicy_controller.go | 408 ++++++++-- .../networkpolicy_controller_test.go | 111 +-- .../networkpolicy/store/addressgroup.go | 21 +- .../networkpolicy/store/appliedtogroup.go | 34 +- pkg/controller/types/networkpolicy.go | 7 + 25 files changed, 1409 insertions(+), 203 deletions(-) create mode 100644 pkg/apis/networking/v1beta1/zz_generated.conversion.go diff --git a/build/yamls/antrea-aks.yml b/build/yamls/antrea-aks.yml index a9dbc4a4065..8b009cdc3a2 100644 --- a/build/yamls/antrea-aks.yml +++ b/build/yamls/antrea-aks.yml @@ -283,6 +283,8 @@ spec: to: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -308,6 +310,8 @@ spec: from: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -804,6 +808,14 @@ rules: - patch - create - delete +- apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/build/yamls/antrea-eks.yml b/build/yamls/antrea-eks.yml index 4ad4caca364..7c6c9df7eb5 100644 --- a/build/yamls/antrea-eks.yml +++ b/build/yamls/antrea-eks.yml @@ -283,6 +283,8 @@ spec: to: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -308,6 +310,8 @@ spec: from: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -804,6 +808,14 @@ rules: - patch - create - delete +- apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/build/yamls/antrea-gke.yml b/build/yamls/antrea-gke.yml index 570121e7b7f..1721bcc4ecf 100644 --- a/build/yamls/antrea-gke.yml +++ b/build/yamls/antrea-gke.yml @@ -283,6 +283,8 @@ spec: to: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -308,6 +310,8 @@ spec: from: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -804,6 +808,14 @@ rules: - patch - create - delete +- apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/build/yamls/antrea-ipsec.yml b/build/yamls/antrea-ipsec.yml index 64a80d1639c..8ab73780878 100644 --- a/build/yamls/antrea-ipsec.yml +++ b/build/yamls/antrea-ipsec.yml @@ -283,6 +283,8 @@ spec: to: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -308,6 +310,8 @@ spec: from: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -804,6 +808,14 @@ rules: - patch - create - delete +- apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/build/yamls/antrea.yml b/build/yamls/antrea.yml index b813bde94c3..9b3b4114d7e 100644 --- a/build/yamls/antrea.yml +++ b/build/yamls/antrea.yml @@ -283,6 +283,8 @@ spec: to: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -308,6 +310,8 @@ spec: from: items: properties: + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: properties: cidr: @@ -804,6 +808,14 @@ rules: - patch - create - delete +- apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/build/yamls/base/controller-rbac.yml b/build/yamls/base/controller-rbac.yml index 7352ed32b29..0241bfc68df 100644 --- a/build/yamls/base/controller-rbac.yml +++ b/build/yamls/base/controller-rbac.yml @@ -123,6 +123,14 @@ rules: - patch - create - delete + - apiGroups: + - core.antrea.tanzu.vmware.com + resources: + - externalentities + verbs: + - get + - watch + - list --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1beta1 diff --git a/build/yamls/base/crds.yml b/build/yamls/base/crds.yml index 852e5fb624a..dce56869107 100644 --- a/build/yamls/base/crds.yml +++ b/build/yamls/base/crds.yml @@ -427,6 +427,8 @@ spec: x-kubernetes-preserve-unknown-fields: true namespaceSelector: x-kubernetes-preserve-unknown-fields: true + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: type: object properties: @@ -462,6 +464,8 @@ spec: x-kubernetes-preserve-unknown-fields: true namespaceSelector: x-kubernetes-preserve-unknown-fields: true + externalEntitySelector: + x-kubernetes-preserve-unknown-fields: true ipBlock: type: object properties: diff --git a/cmd/antrea-controller/controller.go b/cmd/antrea-controller/controller.go index 0d2fabcafce..f23c60b88e4 100644 --- a/cmd/antrea-controller/controller.go +++ b/cmd/antrea-controller/controller.go @@ -84,6 +84,7 @@ func run(o *Options) error { networkPolicyInformer := informerFactory.Networking().V1().NetworkPolicies() nodeInformer := informerFactory.Core().V1().Nodes() cnpInformer := crdInformerFactory.Security().V1alpha1().ClusterNetworkPolicies() + externalEntityInformer := crdInformerFactory.Core().V1alpha1().ExternalEntities() anpInformer := crdInformerFactory.Security().V1alpha1().NetworkPolicies() traceflowInformer := crdInformerFactory.Ops().V1alpha1().Traceflows() @@ -96,6 +97,7 @@ func run(o *Options) error { crdClient, podInformer, namespaceInformer, + externalEntityInformer, networkPolicyInformer, cnpInformer, anpInformer, diff --git a/pkg/apis/controlplane/sets.go b/pkg/apis/controlplane/sets.go index e5f428df9e3..02f91bd67bc 100644 --- a/pkg/apis/controlplane/sets.go +++ b/pkg/apis/controlplane/sets.go @@ -106,3 +106,128 @@ func (s GroupMemberPodSet) IsSuperset(o GroupMemberPodSet) bool { func (s GroupMemberPodSet) Equal(o GroupMemberPodSet) bool { return len(s) == len(o) && s.IsSuperset(o) } + +// groupMemberKey is used to uniquely identify GroupMember. +type groupMemberKey string + +// GroupMemberSet is a set of GroupMembers. +// +k8s:openapi-gen=false +// +k8s:deepcopy-gen=false +type GroupMemberSet map[groupMemberKey]*GroupMember + +// normalizeGroupMember calculates the groupMemberKey of the provided +// GroupMember based on the Pod's namespaced name or IP. +func normalizeGroupMember(member *GroupMember) groupMemberKey { + // "/" is illegal in Namespace and name so is safe as the delimiter. + const delimiter = "/" + var b strings.Builder + if member.Pod != nil { + b.WriteString(member.Pod.Namespace) + b.WriteString(delimiter) + b.WriteString(member.Pod.Name) + } else if member.ExternalEntity != nil { + b.WriteString(member.ExternalEntity.Namespace) + b.WriteString(delimiter) + b.WriteString(member.ExternalEntity.Name) + } else if len(member.Endpoints) != 0 { + for _, ep := range member.Endpoints { + b.Write(ep.IP) + } + } + return groupMemberKey(b.String()) +} + +// NewGroupMemberSet builds a GroupMemberSet from a list of GroupMember. +func NewGroupMemberSet(items ...*GroupMember) GroupMemberSet { + m := GroupMemberSet{} + m.Insert(items...) + return m +} + +// Insert adds items to the set. +func (s GroupMemberSet) Insert(items ...*GroupMember) { + for _, item := range items { + s[normalizeGroupMember(item)] = item + } +} + +// Delete removes all items from the set. +func (s GroupMemberSet) Delete(items ...*GroupMember) { + for _, item := range items { + delete(s, normalizeGroupMember(item)) + } +} + +// Has returns true if and only if item is contained in the set. +func (s GroupMemberSet) Has(item *GroupMember) bool { + _, contained := s[normalizeGroupMember(item)] + return contained +} + +// Difference returns a set of GroupMembers that are not in o. +func (s GroupMemberSet) Difference(o GroupMemberSet) GroupMemberSet { + result := GroupMemberSet{} + for key, item := range s { + if _, contained := o[key]; !contained { + result[key] = item + } + } + return result +} + +// Union returns a new set which includes items in either m or o. +func (s GroupMemberSet) Union(o GroupMemberSet) GroupMemberSet { + result := GroupMemberSet{} + for key, item := range s { + result[key] = item + } + for key, item := range o { + result[key] = item + } + return result +} + +// IsSuperset returns true if and only if s1 is a superset of s2. +func (s GroupMemberSet) IsSuperset(o GroupMemberSet) bool { + for key := range o { + _, contained := s[key] + if !contained { + return false + } + } + return true +} + +// Equal returns true if and only if s1 is equal (as a set) to s2. +// Two sets are equal if their membership is identical. +// (In practice, this means same elements, order doesn't matter) +func (s GroupMemberSet) Equal(o GroupMemberSet) bool { + return len(s) == len(o) && s.IsSuperset(o) +} + +// Items returns the slice with contents in random order. +func (s GroupMemberSet) Items() []*GroupMember { + res := make([]*GroupMember, 0, len(s)) + for _, item := range s { + res = append(res, item) + } + return res +} + +// Conversion functions +func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { + return &GroupMemberPod{ + Pod: g.Pod, + IP: g.Endpoints[0].IP, + Ports: g.Endpoints[0].Ports, + } +} + +func (p *GroupMemberPod) ToGroupMember() *GroupMember { + return &GroupMember{ + Pod: p.Pod, + Endpoints: []Endpoint{ + {IP: p.IP, Ports: p.Ports}, + }, + } +} diff --git a/pkg/apis/controlplane/v1beta1/generated.pb.go b/pkg/apis/controlplane/v1beta1/generated.pb.go index 2cea4312a45..6b939097181 100644 --- a/pkg/apis/controlplane/v1beta1/generated.pb.go +++ b/pkg/apis/controlplane/v1beta1/generated.pb.go @@ -1196,9 +1196,9 @@ func (m *GroupMember) MarshalToSizedBuffer(dAtA []byte) (int, error) { dAtA[i] = 0x1a } } - if m.Pod != nil { + if m.ExternalEntity != nil { { - size, err := m.Pod.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.ExternalEntity.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -1208,9 +1208,9 @@ func (m *GroupMember) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x12 } - if m.ExternalEntity != nil { + if m.Pod != nil { { - size, err := m.ExternalEntity.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Pod.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -1901,14 +1901,14 @@ func (m *GroupMember) Size() (n int) { } var l int _ = l - if m.ExternalEntity != nil { - l = m.ExternalEntity.Size() - n += 1 + l + sovGenerated(uint64(l)) - } if m.Pod != nil { l = m.Pod.Size() n += 1 + l + sovGenerated(uint64(l)) } + if m.ExternalEntity != nil { + l = m.ExternalEntity.Size() + n += 1 + l + sovGenerated(uint64(l)) + } if len(m.Endpoints) > 0 { for _, e := range m.Endpoints { l = e.Size() @@ -2296,8 +2296,8 @@ func (this *GroupMember) String() string { } repeatedStringForEndpoints += "}" s := strings.Join([]string{`&GroupMember{`, - `ExternalEntity:` + strings.Replace(this.ExternalEntity.String(), "ExternalEntityReference", "ExternalEntityReference", 1) + `,`, `Pod:` + strings.Replace(this.Pod.String(), "PodReference", "PodReference", 1) + `,`, + `ExternalEntity:` + strings.Replace(this.ExternalEntity.String(), "ExternalEntityReference", "ExternalEntityReference", 1) + `,`, `Endpoints:` + repeatedStringForEndpoints + `,`, `}`, }, "") @@ -3721,7 +3721,7 @@ func (m *GroupMember) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExternalEntity", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pod", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3748,16 +3748,16 @@ func (m *GroupMember) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.ExternalEntity == nil { - m.ExternalEntity = &ExternalEntityReference{} + if m.Pod == nil { + m.Pod = &PodReference{} } - if err := m.ExternalEntity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Pod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pod", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ExternalEntity", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3784,10 +3784,10 @@ func (m *GroupMember) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Pod == nil { - m.Pod = &PodReference{} + if m.ExternalEntity == nil { + m.ExternalEntity = &ExternalEntityReference{} } - if err := m.Pod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ExternalEntity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/pkg/apis/controlplane/v1beta1/generated.proto b/pkg/apis/controlplane/v1beta1/generated.proto index 2bb5af67fdd..5b3f05b0f1c 100644 --- a/pkg/apis/controlplane/v1beta1/generated.proto +++ b/pkg/apis/controlplane/v1beta1/generated.proto @@ -119,11 +119,11 @@ message ExternalEntityReference { // GroupMember represents resource member to be populated in Groups. // This supersedes GroupMemberPod, and will eventually replace it. message GroupMember { - // ExternalEntity maintains the reference to the ExternalEntity. - optional ExternalEntityReference externalEntity = 1; - // Pod maintains the reference to the Pod. - optional PodReference pod = 2; + optional PodReference pod = 1; + + // ExternalEntity maintains the reference to the ExternalEntity. + optional ExternalEntityReference externalEntity = 2; // Endpoints maintains a list of EndPoints associated with this groupMember. repeated Endpoint endpoints = 3; diff --git a/pkg/apis/controlplane/v1beta1/types.go b/pkg/apis/controlplane/v1beta1/types.go index 3f8edd1d8b9..437aa1619dd 100644 --- a/pkg/apis/controlplane/v1beta1/types.go +++ b/pkg/apis/controlplane/v1beta1/types.go @@ -82,11 +82,11 @@ type Endpoint struct { // GroupMember represents resource member to be populated in Groups. // This supersedes GroupMemberPod, and will eventually replace it. type GroupMember struct { - // ExternalEntity maintains the reference to the ExternalEntity. - ExternalEntity *ExternalEntityReference `json:"externalEntity,omitempty" protobuf:"bytes,1,opt,name=externalEntity"` - // Pod maintains the reference to the Pod. - Pod *PodReference `json:"pod,omitempty" protobuf:"bytes,2,opt,name=pod"` + Pod *PodReference `json:"pod,omitempty" protobuf:"bytes,1,opt,name=pod"` + + // ExternalEntity maintains the reference to the ExternalEntity. + ExternalEntity *ExternalEntityReference `json:"externalEntity,omitempty" protobuf:"bytes,2,opt,name=externalEntity"` // Endpoints maintains a list of EndPoints associated with this groupMember. Endpoints []Endpoint `json:"endpoints,omitempty" protobuf:"bytes,3,rep,name=endpoints"` diff --git a/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go b/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go index d2c5dca9b93..8d10a6a863a 100644 --- a/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go +++ b/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go @@ -323,16 +323,16 @@ func (in *ExternalEntityReference) DeepCopy() *ExternalEntityReference { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GroupMember) DeepCopyInto(out *GroupMember) { *out = *in - if in.ExternalEntity != nil { - in, out := &in.ExternalEntity, &out.ExternalEntity - *out = new(ExternalEntityReference) - **out = **in - } if in.Pod != nil { in, out := &in.Pod, &out.Pod *out = new(PodReference) **out = **in } + if in.ExternalEntity != nil { + in, out := &in.ExternalEntity, &out.ExternalEntity + *out = new(ExternalEntityReference) + **out = **in + } if in.Endpoints != nil { in, out := &in.Endpoints, &out.Endpoints *out = make([]Endpoint, len(*in)) diff --git a/pkg/apis/networking/v1beta1/zz_generated.conversion.go b/pkg/apis/networking/v1beta1/zz_generated.conversion.go new file mode 100644 index 00000000000..a7afbfaf39f --- /dev/null +++ b/pkg/apis/networking/v1beta1/zz_generated.conversion.go @@ -0,0 +1,695 @@ +// +build !ignore_autogenerated + +// Copyright 2020 Antrea Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by conversion-gen. DO NOT EDIT. + +package v1beta1 + +import ( + unsafe "unsafe" + + networking "github.com/vmware-tanzu/antrea/pkg/apis/networking" + v1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" + intstr "k8s.io/apimachinery/pkg/util/intstr" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*AddressGroup)(nil), (*networking.AddressGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AddressGroup_To_networking_AddressGroup(a.(*AddressGroup), b.(*networking.AddressGroup), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AddressGroup)(nil), (*AddressGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AddressGroup_To_v1beta1_AddressGroup(a.(*networking.AddressGroup), b.(*AddressGroup), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*AddressGroupList)(nil), (*networking.AddressGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList(a.(*AddressGroupList), b.(*networking.AddressGroupList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AddressGroupList)(nil), (*AddressGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList(a.(*networking.AddressGroupList), b.(*AddressGroupList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*AddressGroupPatch)(nil), (*networking.AddressGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(a.(*AddressGroupPatch), b.(*networking.AddressGroupPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AddressGroupPatch)(nil), (*AddressGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(a.(*networking.AddressGroupPatch), b.(*AddressGroupPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*AppliedToGroup)(nil), (*networking.AppliedToGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(a.(*AppliedToGroup), b.(*networking.AppliedToGroup), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroup)(nil), (*AppliedToGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(a.(*networking.AppliedToGroup), b.(*AppliedToGroup), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*AppliedToGroupList)(nil), (*networking.AppliedToGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(a.(*AppliedToGroupList), b.(*networking.AppliedToGroupList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroupList)(nil), (*AppliedToGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(a.(*networking.AppliedToGroupList), b.(*AppliedToGroupList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*AppliedToGroupPatch)(nil), (*networking.AppliedToGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(a.(*AppliedToGroupPatch), b.(*networking.AppliedToGroupPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroupPatch)(nil), (*AppliedToGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(a.(*networking.AppliedToGroupPatch), b.(*AppliedToGroupPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Endpoint)(nil), (*networking.Endpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Endpoint_To_networking_Endpoint(a.(*Endpoint), b.(*networking.Endpoint), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.Endpoint)(nil), (*Endpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_Endpoint_To_v1beta1_Endpoint(a.(*networking.Endpoint), b.(*Endpoint), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ExternalEntityReference)(nil), (*networking.ExternalEntityReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(a.(*ExternalEntityReference), b.(*networking.ExternalEntityReference), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.ExternalEntityReference)(nil), (*ExternalEntityReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(a.(*networking.ExternalEntityReference), b.(*ExternalEntityReference), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*GroupMember)(nil), (*networking.GroupMember)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_GroupMember_To_networking_GroupMember(a.(*GroupMember), b.(*networking.GroupMember), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.GroupMember)(nil), (*GroupMember)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_GroupMember_To_v1beta1_GroupMember(a.(*networking.GroupMember), b.(*GroupMember), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*GroupMemberPod)(nil), (*networking.GroupMemberPod)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(a.(*GroupMemberPod), b.(*networking.GroupMemberPod), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.GroupMemberPod)(nil), (*GroupMemberPod)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(a.(*networking.GroupMemberPod), b.(*GroupMemberPod), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*IPBlock)(nil), (*networking.IPBlock)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_IPBlock_To_networking_IPBlock(a.(*IPBlock), b.(*networking.IPBlock), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.IPBlock)(nil), (*IPBlock)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_IPBlock_To_v1beta1_IPBlock(a.(*networking.IPBlock), b.(*IPBlock), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*IPNet)(nil), (*networking.IPNet)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_IPNet_To_networking_IPNet(a.(*IPNet), b.(*networking.IPNet), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.IPNet)(nil), (*IPNet)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_IPNet_To_v1beta1_IPNet(a.(*networking.IPNet), b.(*IPNet), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NamedPort)(nil), (*networking.NamedPort)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NamedPort_To_networking_NamedPort(a.(*NamedPort), b.(*networking.NamedPort), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.NamedPort)(nil), (*NamedPort)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_NamedPort_To_v1beta1_NamedPort(a.(*networking.NamedPort), b.(*NamedPort), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NetworkPolicy)(nil), (*networking.NetworkPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(a.(*NetworkPolicy), b.(*networking.NetworkPolicy), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicy)(nil), (*NetworkPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(a.(*networking.NetworkPolicy), b.(*NetworkPolicy), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NetworkPolicyList)(nil), (*networking.NetworkPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(a.(*NetworkPolicyList), b.(*networking.NetworkPolicyList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyList)(nil), (*NetworkPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(a.(*networking.NetworkPolicyList), b.(*NetworkPolicyList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NetworkPolicyPeer)(nil), (*networking.NetworkPolicyPeer)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(a.(*NetworkPolicyPeer), b.(*networking.NetworkPolicyPeer), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyPeer)(nil), (*NetworkPolicyPeer)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(a.(*networking.NetworkPolicyPeer), b.(*NetworkPolicyPeer), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NetworkPolicyRule)(nil), (*networking.NetworkPolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(a.(*NetworkPolicyRule), b.(*networking.NetworkPolicyRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyRule)(nil), (*NetworkPolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(a.(*networking.NetworkPolicyRule), b.(*NetworkPolicyRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PodReference)(nil), (*networking.PodReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PodReference_To_networking_PodReference(a.(*PodReference), b.(*networking.PodReference), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.PodReference)(nil), (*PodReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_PodReference_To_v1beta1_PodReference(a.(*networking.PodReference), b.(*PodReference), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Service)(nil), (*networking.Service)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Service_To_networking_Service(a.(*Service), b.(*networking.Service), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*networking.Service)(nil), (*Service)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_networking_Service_To_v1beta1_Service(a.(*networking.Service), b.(*Service), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_AddressGroup_To_networking_AddressGroup(in *AddressGroup, out *networking.AddressGroup, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Pods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.Pods)) + out.GroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.GroupMembers)) + return nil +} + +// Convert_v1beta1_AddressGroup_To_networking_AddressGroup is an autogenerated conversion function. +func Convert_v1beta1_AddressGroup_To_networking_AddressGroup(in *AddressGroup, out *networking.AddressGroup, s conversion.Scope) error { + return autoConvert_v1beta1_AddressGroup_To_networking_AddressGroup(in, out, s) +} + +func autoConvert_networking_AddressGroup_To_v1beta1_AddressGroup(in *networking.AddressGroup, out *AddressGroup, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Pods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.Pods)) + out.GroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.GroupMembers)) + return nil +} + +// Convert_networking_AddressGroup_To_v1beta1_AddressGroup is an autogenerated conversion function. +func Convert_networking_AddressGroup_To_v1beta1_AddressGroup(in *networking.AddressGroup, out *AddressGroup, s conversion.Scope) error { + return autoConvert_networking_AddressGroup_To_v1beta1_AddressGroup(in, out, s) +} + +func autoConvert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in *AddressGroupList, out *networking.AddressGroupList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]networking.AddressGroup)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList is an autogenerated conversion function. +func Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in *AddressGroupList, out *networking.AddressGroupList, s conversion.Scope) error { + return autoConvert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in, out, s) +} + +func autoConvert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in *networking.AddressGroupList, out *AddressGroupList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]AddressGroup)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList is an autogenerated conversion function. +func Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in *networking.AddressGroupList, out *AddressGroupList, s conversion.Scope) error { + return autoConvert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in, out, s) +} + +func autoConvert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in *AddressGroupPatch, out *networking.AddressGroupPatch, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.AddedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) + out.RemovedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) + out.AddedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) + out.RemovedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) + return nil +} + +// Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch is an autogenerated conversion function. +func Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in *AddressGroupPatch, out *networking.AddressGroupPatch, s conversion.Scope) error { + return autoConvert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in, out, s) +} + +func autoConvert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in *networking.AddressGroupPatch, out *AddressGroupPatch, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.AddedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) + out.RemovedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) + out.AddedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) + out.RemovedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) + return nil +} + +// Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch is an autogenerated conversion function. +func Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in *networking.AddressGroupPatch, out *AddressGroupPatch, s conversion.Scope) error { + return autoConvert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in, out, s) +} + +func autoConvert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in *AppliedToGroup, out *networking.AppliedToGroup, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Pods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.Pods)) + out.GroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.GroupMembers)) + return nil +} + +// Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup is an autogenerated conversion function. +func Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in *AppliedToGroup, out *networking.AppliedToGroup, s conversion.Scope) error { + return autoConvert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in, out, s) +} + +func autoConvert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in *networking.AppliedToGroup, out *AppliedToGroup, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Pods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.Pods)) + out.GroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.GroupMembers)) + return nil +} + +// Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup is an autogenerated conversion function. +func Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in *networking.AppliedToGroup, out *AppliedToGroup, s conversion.Scope) error { + return autoConvert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in, out, s) +} + +func autoConvert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in *AppliedToGroupList, out *networking.AppliedToGroupList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]networking.AppliedToGroup)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList is an autogenerated conversion function. +func Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in *AppliedToGroupList, out *networking.AppliedToGroupList, s conversion.Scope) error { + return autoConvert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in, out, s) +} + +func autoConvert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in *networking.AppliedToGroupList, out *AppliedToGroupList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]AppliedToGroup)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList is an autogenerated conversion function. +func Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in *networking.AppliedToGroupList, out *AppliedToGroupList, s conversion.Scope) error { + return autoConvert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in, out, s) +} + +func autoConvert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in *AppliedToGroupPatch, out *networking.AppliedToGroupPatch, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.AddedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) + out.RemovedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) + out.AddedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) + out.RemovedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) + return nil +} + +// Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch is an autogenerated conversion function. +func Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in *AppliedToGroupPatch, out *networking.AppliedToGroupPatch, s conversion.Scope) error { + return autoConvert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in, out, s) +} + +func autoConvert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in *networking.AppliedToGroupPatch, out *AppliedToGroupPatch, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.AddedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) + out.RemovedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) + out.AddedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) + out.RemovedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) + return nil +} + +// Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch is an autogenerated conversion function. +func Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in *networking.AppliedToGroupPatch, out *AppliedToGroupPatch, s conversion.Scope) error { + return autoConvert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in, out, s) +} + +func autoConvert_v1beta1_Endpoint_To_networking_Endpoint(in *Endpoint, out *networking.Endpoint, s conversion.Scope) error { + out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) + out.Ports = *(*[]networking.NamedPort)(unsafe.Pointer(&in.Ports)) + return nil +} + +// Convert_v1beta1_Endpoint_To_networking_Endpoint is an autogenerated conversion function. +func Convert_v1beta1_Endpoint_To_networking_Endpoint(in *Endpoint, out *networking.Endpoint, s conversion.Scope) error { + return autoConvert_v1beta1_Endpoint_To_networking_Endpoint(in, out, s) +} + +func autoConvert_networking_Endpoint_To_v1beta1_Endpoint(in *networking.Endpoint, out *Endpoint, s conversion.Scope) error { + out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) + out.Ports = *(*[]NamedPort)(unsafe.Pointer(&in.Ports)) + return nil +} + +// Convert_networking_Endpoint_To_v1beta1_Endpoint is an autogenerated conversion function. +func Convert_networking_Endpoint_To_v1beta1_Endpoint(in *networking.Endpoint, out *Endpoint, s conversion.Scope) error { + return autoConvert_networking_Endpoint_To_v1beta1_Endpoint(in, out, s) +} + +func autoConvert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in *ExternalEntityReference, out *networking.ExternalEntityReference, s conversion.Scope) error { + out.Name = in.Name + out.Namespace = in.Namespace + return nil +} + +// Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference is an autogenerated conversion function. +func Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in *ExternalEntityReference, out *networking.ExternalEntityReference, s conversion.Scope) error { + return autoConvert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in, out, s) +} + +func autoConvert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in *networking.ExternalEntityReference, out *ExternalEntityReference, s conversion.Scope) error { + out.Name = in.Name + out.Namespace = in.Namespace + return nil +} + +// Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference is an autogenerated conversion function. +func Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in *networking.ExternalEntityReference, out *ExternalEntityReference, s conversion.Scope) error { + return autoConvert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in, out, s) +} + +func autoConvert_v1beta1_GroupMember_To_networking_GroupMember(in *GroupMember, out *networking.GroupMember, s conversion.Scope) error { + out.Pod = (*networking.PodReference)(unsafe.Pointer(in.Pod)) + out.ExternalEntity = (*networking.ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) + out.Endpoints = *(*[]networking.Endpoint)(unsafe.Pointer(&in.Endpoints)) + return nil +} + +// Convert_v1beta1_GroupMember_To_networking_GroupMember is an autogenerated conversion function. +func Convert_v1beta1_GroupMember_To_networking_GroupMember(in *GroupMember, out *networking.GroupMember, s conversion.Scope) error { + return autoConvert_v1beta1_GroupMember_To_networking_GroupMember(in, out, s) +} + +func autoConvert_networking_GroupMember_To_v1beta1_GroupMember(in *networking.GroupMember, out *GroupMember, s conversion.Scope) error { + out.Pod = (*PodReference)(unsafe.Pointer(in.Pod)) + out.ExternalEntity = (*ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) + out.Endpoints = *(*[]Endpoint)(unsafe.Pointer(&in.Endpoints)) + return nil +} + +// Convert_networking_GroupMember_To_v1beta1_GroupMember is an autogenerated conversion function. +func Convert_networking_GroupMember_To_v1beta1_GroupMember(in *networking.GroupMember, out *GroupMember, s conversion.Scope) error { + return autoConvert_networking_GroupMember_To_v1beta1_GroupMember(in, out, s) +} + +func autoConvert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in *GroupMemberPod, out *networking.GroupMemberPod, s conversion.Scope) error { + out.Pod = (*networking.PodReference)(unsafe.Pointer(in.Pod)) + out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) + out.Ports = *(*[]networking.NamedPort)(unsafe.Pointer(&in.Ports)) + return nil +} + +// Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod is an autogenerated conversion function. +func Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in *GroupMemberPod, out *networking.GroupMemberPod, s conversion.Scope) error { + return autoConvert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in, out, s) +} + +func autoConvert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in *networking.GroupMemberPod, out *GroupMemberPod, s conversion.Scope) error { + out.Pod = (*PodReference)(unsafe.Pointer(in.Pod)) + out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) + out.Ports = *(*[]NamedPort)(unsafe.Pointer(&in.Ports)) + return nil +} + +// Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod is an autogenerated conversion function. +func Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in *networking.GroupMemberPod, out *GroupMemberPod, s conversion.Scope) error { + return autoConvert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in, out, s) +} + +func autoConvert_v1beta1_IPBlock_To_networking_IPBlock(in *IPBlock, out *networking.IPBlock, s conversion.Scope) error { + if err := Convert_v1beta1_IPNet_To_networking_IPNet(&in.CIDR, &out.CIDR, s); err != nil { + return err + } + out.Except = *(*[]networking.IPNet)(unsafe.Pointer(&in.Except)) + return nil +} + +// Convert_v1beta1_IPBlock_To_networking_IPBlock is an autogenerated conversion function. +func Convert_v1beta1_IPBlock_To_networking_IPBlock(in *IPBlock, out *networking.IPBlock, s conversion.Scope) error { + return autoConvert_v1beta1_IPBlock_To_networking_IPBlock(in, out, s) +} + +func autoConvert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *IPBlock, s conversion.Scope) error { + if err := Convert_networking_IPNet_To_v1beta1_IPNet(&in.CIDR, &out.CIDR, s); err != nil { + return err + } + out.Except = *(*[]IPNet)(unsafe.Pointer(&in.Except)) + return nil +} + +// Convert_networking_IPBlock_To_v1beta1_IPBlock is an autogenerated conversion function. +func Convert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *IPBlock, s conversion.Scope) error { + return autoConvert_networking_IPBlock_To_v1beta1_IPBlock(in, out, s) +} + +func autoConvert_v1beta1_IPNet_To_networking_IPNet(in *IPNet, out *networking.IPNet, s conversion.Scope) error { + out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) + out.PrefixLength = in.PrefixLength + return nil +} + +// Convert_v1beta1_IPNet_To_networking_IPNet is an autogenerated conversion function. +func Convert_v1beta1_IPNet_To_networking_IPNet(in *IPNet, out *networking.IPNet, s conversion.Scope) error { + return autoConvert_v1beta1_IPNet_To_networking_IPNet(in, out, s) +} + +func autoConvert_networking_IPNet_To_v1beta1_IPNet(in *networking.IPNet, out *IPNet, s conversion.Scope) error { + out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) + out.PrefixLength = in.PrefixLength + return nil +} + +// Convert_networking_IPNet_To_v1beta1_IPNet is an autogenerated conversion function. +func Convert_networking_IPNet_To_v1beta1_IPNet(in *networking.IPNet, out *IPNet, s conversion.Scope) error { + return autoConvert_networking_IPNet_To_v1beta1_IPNet(in, out, s) +} + +func autoConvert_v1beta1_NamedPort_To_networking_NamedPort(in *NamedPort, out *networking.NamedPort, s conversion.Scope) error { + out.Port = in.Port + out.Name = in.Name + out.Protocol = networking.Protocol(in.Protocol) + return nil +} + +// Convert_v1beta1_NamedPort_To_networking_NamedPort is an autogenerated conversion function. +func Convert_v1beta1_NamedPort_To_networking_NamedPort(in *NamedPort, out *networking.NamedPort, s conversion.Scope) error { + return autoConvert_v1beta1_NamedPort_To_networking_NamedPort(in, out, s) +} + +func autoConvert_networking_NamedPort_To_v1beta1_NamedPort(in *networking.NamedPort, out *NamedPort, s conversion.Scope) error { + out.Port = in.Port + out.Name = in.Name + out.Protocol = Protocol(in.Protocol) + return nil +} + +// Convert_networking_NamedPort_To_v1beta1_NamedPort is an autogenerated conversion function. +func Convert_networking_NamedPort_To_v1beta1_NamedPort(in *networking.NamedPort, out *NamedPort, s conversion.Scope) error { + return autoConvert_networking_NamedPort_To_v1beta1_NamedPort(in, out, s) +} + +func autoConvert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in *NetworkPolicy, out *networking.NetworkPolicy, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Rules = *(*[]networking.NetworkPolicyRule)(unsafe.Pointer(&in.Rules)) + out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) + out.Priority = (*float64)(unsafe.Pointer(in.Priority)) + out.TierPriority = (*networking.TierPriority)(unsafe.Pointer(in.TierPriority)) + return nil +} + +// Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy is an autogenerated conversion function. +func Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in *NetworkPolicy, out *networking.NetworkPolicy, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in, out, s) +} + +func autoConvert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in *networking.NetworkPolicy, out *NetworkPolicy, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + out.Rules = *(*[]NetworkPolicyRule)(unsafe.Pointer(&in.Rules)) + out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) + out.Priority = (*float64)(unsafe.Pointer(in.Priority)) + out.TierPriority = (*TierPriority)(unsafe.Pointer(in.TierPriority)) + return nil +} + +// Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy is an autogenerated conversion function. +func Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in *networking.NetworkPolicy, out *NetworkPolicy, s conversion.Scope) error { + return autoConvert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in, out, s) +} + +func autoConvert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in *NetworkPolicyList, out *networking.NetworkPolicyList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]networking.NetworkPolicy)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList is an autogenerated conversion function. +func Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in *NetworkPolicyList, out *networking.NetworkPolicyList, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in, out, s) +} + +func autoConvert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in *networking.NetworkPolicyList, out *NetworkPolicyList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]NetworkPolicy)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList is an autogenerated conversion function. +func Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in *networking.NetworkPolicyList, out *NetworkPolicyList, s conversion.Scope) error { + return autoConvert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in, out, s) +} + +func autoConvert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in *NetworkPolicyPeer, out *networking.NetworkPolicyPeer, s conversion.Scope) error { + out.AddressGroups = *(*[]string)(unsafe.Pointer(&in.AddressGroups)) + out.IPBlocks = *(*[]networking.IPBlock)(unsafe.Pointer(&in.IPBlocks)) + return nil +} + +// Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer is an autogenerated conversion function. +func Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in *NetworkPolicyPeer, out *networking.NetworkPolicyPeer, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in, out, s) +} + +func autoConvert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in *networking.NetworkPolicyPeer, out *NetworkPolicyPeer, s conversion.Scope) error { + out.AddressGroups = *(*[]string)(unsafe.Pointer(&in.AddressGroups)) + out.IPBlocks = *(*[]IPBlock)(unsafe.Pointer(&in.IPBlocks)) + return nil +} + +// Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer is an autogenerated conversion function. +func Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in *networking.NetworkPolicyPeer, out *NetworkPolicyPeer, s conversion.Scope) error { + return autoConvert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in, out, s) +} + +func autoConvert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in *NetworkPolicyRule, out *networking.NetworkPolicyRule, s conversion.Scope) error { + out.Direction = networking.Direction(in.Direction) + if err := Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(&in.From, &out.From, s); err != nil { + return err + } + if err := Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(&in.To, &out.To, s); err != nil { + return err + } + out.Services = *(*[]networking.Service)(unsafe.Pointer(&in.Services)) + out.Priority = in.Priority + out.Action = (*v1alpha1.RuleAction)(unsafe.Pointer(in.Action)) + return nil +} + +// Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule is an autogenerated conversion function. +func Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in *NetworkPolicyRule, out *networking.NetworkPolicyRule, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in, out, s) +} + +func autoConvert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in *networking.NetworkPolicyRule, out *NetworkPolicyRule, s conversion.Scope) error { + out.Direction = Direction(in.Direction) + if err := Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(&in.From, &out.From, s); err != nil { + return err + } + if err := Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(&in.To, &out.To, s); err != nil { + return err + } + out.Services = *(*[]Service)(unsafe.Pointer(&in.Services)) + out.Priority = in.Priority + out.Action = (*v1alpha1.RuleAction)(unsafe.Pointer(in.Action)) + return nil +} + +// Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule is an autogenerated conversion function. +func Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in *networking.NetworkPolicyRule, out *NetworkPolicyRule, s conversion.Scope) error { + return autoConvert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in, out, s) +} + +func autoConvert_v1beta1_PodReference_To_networking_PodReference(in *PodReference, out *networking.PodReference, s conversion.Scope) error { + out.Name = in.Name + out.Namespace = in.Namespace + return nil +} + +// Convert_v1beta1_PodReference_To_networking_PodReference is an autogenerated conversion function. +func Convert_v1beta1_PodReference_To_networking_PodReference(in *PodReference, out *networking.PodReference, s conversion.Scope) error { + return autoConvert_v1beta1_PodReference_To_networking_PodReference(in, out, s) +} + +func autoConvert_networking_PodReference_To_v1beta1_PodReference(in *networking.PodReference, out *PodReference, s conversion.Scope) error { + out.Name = in.Name + out.Namespace = in.Namespace + return nil +} + +// Convert_networking_PodReference_To_v1beta1_PodReference is an autogenerated conversion function. +func Convert_networking_PodReference_To_v1beta1_PodReference(in *networking.PodReference, out *PodReference, s conversion.Scope) error { + return autoConvert_networking_PodReference_To_v1beta1_PodReference(in, out, s) +} + +func autoConvert_v1beta1_Service_To_networking_Service(in *Service, out *networking.Service, s conversion.Scope) error { + out.Protocol = (*networking.Protocol)(unsafe.Pointer(in.Protocol)) + out.Port = (*intstr.IntOrString)(unsafe.Pointer(in.Port)) + return nil +} + +// Convert_v1beta1_Service_To_networking_Service is an autogenerated conversion function. +func Convert_v1beta1_Service_To_networking_Service(in *Service, out *networking.Service, s conversion.Scope) error { + return autoConvert_v1beta1_Service_To_networking_Service(in, out, s) +} + +func autoConvert_networking_Service_To_v1beta1_Service(in *networking.Service, out *Service, s conversion.Scope) error { + out.Protocol = (*Protocol)(unsafe.Pointer(in.Protocol)) + out.Port = (*intstr.IntOrString)(unsafe.Pointer(in.Port)) + return nil +} + +// Convert_networking_Service_To_v1beta1_Service is an autogenerated conversion function. +func Convert_networking_Service_To_v1beta1_Service(in *networking.Service, out *Service, s conversion.Scope) error { + return autoConvert_networking_Service_To_v1beta1_Service(in, out, s) +} diff --git a/pkg/apiserver/openapi/zz_generated.openapi.go b/pkg/apiserver/openapi/zz_generated.openapi.go index dc83a2450ac..d42a74ec1e7 100644 --- a/pkg/apiserver/openapi/zz_generated.openapi.go +++ b/pkg/apiserver/openapi/zz_generated.openapi.go @@ -1209,18 +1209,18 @@ func schema_pkg_apis_controlplane_v1beta1_GroupMember(ref common.ReferenceCallba Description: "GroupMember represents resource member to be populated in Groups. This supersedes GroupMemberPod, and will eventually replace it.", Type: []string{"object"}, Properties: map[string]spec.Schema{ - "externalEntity": { - SchemaProps: spec.SchemaProps{ - Description: "ExternalEntity maintains the reference to the ExternalEntity.", - Ref: ref("github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.ExternalEntityReference"), - }, - }, "pod": { SchemaProps: spec.SchemaProps{ Description: "Pod maintains the reference to the Pod.", Ref: ref("github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.PodReference"), }, }, + "externalEntity": { + SchemaProps: spec.SchemaProps{ + Description: "ExternalEntity maintains the reference to the ExternalEntity.", + Ref: ref("github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.ExternalEntityReference"), + }, + }, "endpoints": { SchemaProps: spec.SchemaProps{ Description: "Endpoints maintains a list of EndPoints associated with this groupMember.", diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy.go b/pkg/controller/networkpolicy/antreanetworkpolicy.go index e2776c9b719..35a1c66bfe5 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy.go @@ -127,7 +127,8 @@ func (n *NetworkPolicyController) processAntreaNetworkPolicy(np *secv1alpha1.Net // Create AppliedToGroup for each AppliedTo present in // AntreaNetworkPolicy spec. for _, at := range np.Spec.AppliedTo { - appliedToGroupNames = append(appliedToGroupNames, n.createAppliedToGroup(np.Namespace, at.PodSelector, at.NamespaceSelector)) + groupName := n.createAppliedToGroup(np.Namespace, at.PodSelector, at.NamespaceSelector, at.ExternalEntitySelector) + appliedToGroupNames = append(appliedToGroupNames, groupName) } rules := make([]controlplane.NetworkPolicyRule, 0, len(np.Spec.Ingress)+len(np.Spec.Egress)) // Compute NetworkPolicyRule for Egress Rule. diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy.go b/pkg/controller/networkpolicy/clusternetworkpolicy.go index 0a640c0b466..4012b97b08b 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy.go @@ -138,7 +138,7 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *secv1alpha1.C // Create AppliedToGroup for each AppliedTo present in // ClusterNetworkPolicy spec. for _, at := range cnp.Spec.AppliedTo { - appliedToGroupNames = append(appliedToGroupNames, n.createAppliedToGroup("", at.PodSelector, at.NamespaceSelector)) + appliedToGroupNames = append(appliedToGroupNames, n.createAppliedToGroup("", at.PodSelector, at.NamespaceSelector, at.ExternalEntitySelector)) } rules := make([]controlplane.NetworkPolicyRule, 0, len(cnp.Spec.Ingress)+len(cnp.Spec.Egress)) // Compute NetworkPolicyRule for Egress Rule. diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go index 633a420ce3d..26dbd67eaca 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go @@ -96,7 +96,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -110,7 +110,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -122,7 +122,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 1, @@ -176,7 +176,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, nil, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -190,7 +190,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -202,7 +202,7 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 2, @@ -243,7 +243,7 @@ func TestAddCNP(t *testing.T) { selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} selectorAll := metav1.LabelSelector{} matchAllPeerEgress := matchAllPeer - matchAllPeerEgress.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll).NormalizedName)} + matchAllPeerEgress.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll, nil).NormalizedName)} tests := []struct { name string inputPolicy *secv1alpha1.ClusterNetworkPolicy @@ -289,7 +289,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -301,7 +301,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -344,7 +344,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -356,7 +356,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -399,7 +399,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -411,7 +411,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -454,7 +454,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -466,7 +466,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -509,7 +509,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -521,7 +521,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -579,7 +579,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -593,7 +593,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -605,7 +605,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -659,7 +659,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, nil, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -673,7 +673,7 @@ func TestAddCNP(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -685,7 +685,7 @@ func TestAddCNP(t *testing.T) { Action: &allowAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 2, @@ -723,7 +723,7 @@ func TestAddCNP(t *testing.T) { func TestDeleteCNP(t *testing.T) { selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} cnpObj := getCNP() - apgID := getNormalizedUID(toGroupSelector("", &selectorA, nil).NormalizedName) + apgID := getNormalizedUID(toGroupSelector("", &selectorA, nil, nil).NormalizedName) _, npc := newController() npc.addCNP(cnpObj) npc.deleteCNP(cnpObj) diff --git a/pkg/controller/networkpolicy/crd_utils.go b/pkg/controller/networkpolicy/crd_utils.go index 75203f0f88d..9c326eb2134 100644 --- a/pkg/controller/networkpolicy/crd_utils.go +++ b/pkg/controller/networkpolicy/crd_utils.go @@ -111,7 +111,7 @@ func (n *NetworkPolicyController) toAntreaPeerForCRD(peers []secv1alpha1.Network // function simply creates the object without actually populating the // PodAddresses as the affected Pods are calculated during sync process. func (n *NetworkPolicyController) createAddressGroupForCRD(peer secv1alpha1.NetworkPolicyPeer, np metav1.Object) string { - groupSelector := toGroupSelector(np.GetNamespace(), peer.PodSelector, peer.NamespaceSelector) + groupSelector := toGroupSelector(np.GetNamespace(), peer.PodSelector, peer.NamespaceSelector, peer.ExternalEntitySelector) normalizedUID := getNormalizedUID(groupSelector.NormalizedName) // Get or create an AddressGroup for the generated UID. _, found, _ := n.addressGroupStore.Get(normalizedUID) diff --git a/pkg/controller/networkpolicy/crd_utils_test.go b/pkg/controller/networkpolicy/crd_utils_test.go index 4dd861f7d75..6364168ece6 100644 --- a/pkg/controller/networkpolicy/crd_utils_test.go +++ b/pkg/controller/networkpolicy/crd_utils_test.go @@ -132,7 +132,7 @@ func TestToAntreaPeerForCRD(t *testing.T) { selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} selectorAll := metav1.LabelSelector{} matchAllPodsPeer := matchAllPeer - matchAllPodsPeer.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll).NormalizedName)} + matchAllPodsPeer.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll, nil).NormalizedName)} tests := []struct { name string inPeers []secv1alpha1.NetworkPolicyPeer @@ -153,8 +153,8 @@ func TestToAntreaPeerForCRD(t *testing.T) { }, outPeer: controlplane.NetworkPolicyPeer{ AddressGroups: []string{ - getNormalizedUID(toGroupSelector("", &selectorA, &selectorB).NormalizedName), - getNormalizedUID(toGroupSelector("", &selectorC, nil).NormalizedName), + getNormalizedUID(toGroupSelector("", &selectorA, &selectorB, nil).NormalizedName), + getNormalizedUID(toGroupSelector("", &selectorC, nil, nil).NormalizedName), }, }, direction: controlplane.DirectionIn, @@ -172,8 +172,8 @@ func TestToAntreaPeerForCRD(t *testing.T) { }, outPeer: controlplane.NetworkPolicyPeer{ AddressGroups: []string{ - getNormalizedUID(toGroupSelector("", &selectorA, &selectorB).NormalizedName), - getNormalizedUID(toGroupSelector("", &selectorC, nil).NormalizedName), + getNormalizedUID(toGroupSelector("", &selectorA, &selectorB, nil).NormalizedName), + getNormalizedUID(toGroupSelector("", &selectorC, nil, nil).NormalizedName), }, }, direction: controlplane.DirectionOut, diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index 09ee95e492a..aba09565f39 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -46,10 +46,13 @@ import ( "k8s.io/klog" "github.com/vmware-tanzu/antrea/pkg/apis/controlplane" + "github.com/vmware-tanzu/antrea/pkg/apis/core/v1alpha1" secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" "github.com/vmware-tanzu/antrea/pkg/apiserver/storage" "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned" + corev1a1informers "github.com/vmware-tanzu/antrea/pkg/client/informers/externalversions/core/v1alpha1" secinformers "github.com/vmware-tanzu/antrea/pkg/client/informers/externalversions/security/v1alpha1" + corev1a1listers "github.com/vmware-tanzu/antrea/pkg/client/listers/core/v1alpha1" seclisters "github.com/vmware-tanzu/antrea/pkg/client/listers/security/v1alpha1" "github.com/vmware-tanzu/antrea/pkg/controller/metrics" "github.com/vmware-tanzu/antrea/pkg/controller/networkpolicy/store" @@ -119,6 +122,13 @@ type NetworkPolicyController struct { // namespaceListerSynced is a function which returns true if the Namespace shared informer has been synced at least once. namespaceListerSynced cache.InformerSynced + externalEntityInformer corev1a1informers.ExternalEntityInformer + // externalEntityLister is able to list/get ExternalEnitities and is populated by the shared informer passed to + // NewNetworkPolicyController. + externalEntityLister corev1a1listers.ExternalEntityLister + // externalEntitySynced is a function which returns true if the ExternalEntity shared informer has been synced at least once. + externalEntitySynced cache.InformerSynced + networkPolicyInformer networkinginformers.NetworkPolicyInformer // networkPolicyLister is able to list/get Network Policies and is populated by the shared informer passed to // NewNetworkPolicyController. @@ -137,6 +147,7 @@ type NetworkPolicyController struct { // anpLister is able to list/get AntreaNetworkPolicies and is populated by the shared informer passed to // NewNetworkPolicyController. anpLister seclisters.NetworkPolicyLister + // anpListerSynced is a function which returns true if the AntreaNetworkPolicies shared informer has been synced at least once. anpListerSynced cache.InformerSynced @@ -176,6 +187,7 @@ func NewNetworkPolicyController(kubeClient clientset.Interface, crdClient versioned.Interface, podInformer coreinformers.PodInformer, namespaceInformer coreinformers.NamespaceInformer, + externalEntityInformer corev1a1informers.ExternalEntityInformer, networkPolicyInformer networkinginformers.NetworkPolicyInformer, cnpInformer secinformers.ClusterNetworkPolicyInformer, anpInformer secinformers.NetworkPolicyInformer, @@ -191,6 +203,9 @@ func NewNetworkPolicyController(kubeClient clientset.Interface, namespaceInformer: namespaceInformer, namespaceLister: namespaceInformer.Lister(), namespaceListerSynced: namespaceInformer.Informer().HasSynced, + externalEntityInformer: externalEntityInformer, + externalEntityLister: externalEntityInformer.Lister(), + externalEntitySynced: externalEntityInformer.Informer().HasSynced, networkPolicyInformer: networkPolicyInformer, networkPolicyLister: networkPolicyInformer.Lister(), networkPolicyListerSynced: networkPolicyInformer.Informer().HasSynced, @@ -219,6 +234,14 @@ func NewNetworkPolicyController(kubeClient clientset.Interface, }, resyncPeriod, ) + externalEntityInformer.Informer().AddEventHandlerWithResyncPeriod( + cache.ResourceEventHandlerFuncs{ + AddFunc: n.addExternalEntity, + UpdateFunc: n.updateExternalEntity, + DeleteFunc: n.deleteExternalEntity, + }, + resyncPeriod, + ) // Add handlers for NetworkPolicy events. networkPolicyInformer.Informer().AddEventHandlerWithResyncPeriod( cache.ResourceEventHandlerFuncs{ @@ -285,14 +308,18 @@ func (n *NetworkPolicyController) GetConnectedAgentNum() int { return n.internalNetworkPolicyStore.GetWatchersNum() } -// toGroupSelector converts the podSelector and namespaceSelector +// toGroupSelector converts the podSelector, namespaceSelector and externalEntitySelector // and NetworkPolicy Namespace to a networkpolicy.GroupSelector object. -func toGroupSelector(namespace string, podSelector, nsSelector *metav1.LabelSelector) *antreatypes.GroupSelector { +func toGroupSelector(namespace string, podSelector, nsSelector, extEntitySelector *metav1.LabelSelector) *antreatypes.GroupSelector { groupSelector := antreatypes.GroupSelector{} if podSelector != nil { pSelector, _ := metav1.LabelSelectorAsSelector(podSelector) groupSelector.PodSelector = pSelector } + if extEntitySelector != nil { + eSelector, _ := metav1.LabelSelectorAsSelector(extEntitySelector) + groupSelector.ExternalEntitySelector = eSelector + } if nsSelector == nil { // No namespaceSelector indicates that the pods must be selected within // the NetworkPolicy's Namespace. @@ -301,7 +328,7 @@ func toGroupSelector(namespace string, podSelector, nsSelector *metav1.LabelSele nSelector, _ := metav1.LabelSelectorAsSelector(nsSelector) groupSelector.NamespaceSelector = nSelector } - name := generateNormalizedName(groupSelector.Namespace, groupSelector.PodSelector, groupSelector.NamespaceSelector) + name := generateNormalizedName(groupSelector.Namespace, groupSelector.PodSelector, groupSelector.NamespaceSelector, groupSelector.ExternalEntitySelector) groupSelector.NormalizedName = name return &groupSelector } @@ -317,7 +344,7 @@ func getNormalizedUID(name string) string { // the following format: "namespace=NamespaceName And podSelector=normalizedPodSelector". // Note: Namespace and nsSelector may or may not be set depending on the // selector. However, they cannot be set simultaneously. -func generateNormalizedName(namespace string, podSelector, nsSelector labels.Selector) string { +func generateNormalizedName(namespace string, podSelector, nsSelector, eeSelector labels.Selector) string { normalizedName := []string{} if nsSelector != nil { normalizedName = append(normalizedName, fmt.Sprintf("namespaceSelector=%s", nsSelector.String())) @@ -327,13 +354,16 @@ func generateNormalizedName(namespace string, podSelector, nsSelector labels.Sel if podSelector != nil { normalizedName = append(normalizedName, fmt.Sprintf("podSelector=%s", podSelector.String())) } + if eeSelector != nil { + normalizedName = append(normalizedName, fmt.Sprintf("eeSelector=%s", eeSelector.String())) + } sort.Strings(normalizedName) return strings.Join(normalizedName, " And ") } // createAppliedToGroup creates an AppliedToGroup object in store if it is not created already. -func (n *NetworkPolicyController) createAppliedToGroup(npNsName string, pSel, nSel *metav1.LabelSelector) string { - groupSelector := toGroupSelector(npNsName, pSel, nSel) +func (n *NetworkPolicyController) createAppliedToGroup(npNsName string, pSel, nSel, eSel *metav1.LabelSelector) string { + groupSelector := toGroupSelector(npNsName, pSel, nSel, eSel) appliedToGroupUID := getNormalizedUID(groupSelector.NormalizedName) // Get or create a AppliedToGroup for the generated UID. // Ignoring returned error (here and elsewhere in this file) as with the @@ -363,12 +393,12 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v // Pods must be matched within the same Namespace. return false } - if !sel.PodSelector.Matches(labels.Set(pod.Labels)) { - // podSelector does not match the Pod's labels. - return false + if sel.PodSelector != nil && sel.PodSelector.Matches(labels.Set(pod.Labels)) { + // podSelector matches the Pod's labels. + return true } - // podSelector matches the Pod's labels. - return true + // podSelector does not match the Pod's labels. + return false } else if sel.NamespaceSelector != nil && sel.PodSelector != nil { // Pod event may arrive before Pod's Namespace event. In this case, we must // ensure that the Pod Namespace is not nil. @@ -376,7 +406,7 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v // Pod's Namespace do not match namespaceSelector. return false } - if !sel.PodSelector.Matches(labels.Set(pod.Labels)) { + if sel.PodSelector != nil && !sel.PodSelector.Matches(labels.Set(pod.Labels)) { // Pod's Namespace matches namespaceSelector but Pod's labels do not match // the podSelector. return false @@ -384,7 +414,7 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v // Pod's Namespace matches namespaceSelector and Pod's labels matches // podSelector. return true - } else if sel.NamespaceSelector != nil { + } else if sel.NamespaceSelector != nil && sel.ExternalEntitySelector == nil { // Selector only has a NamespaceSelector. // Pod event may arrive before Pod's Namespace event. In this case, we must // ensure that the Pod Namespace is not nil. @@ -406,6 +436,47 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v return false } +func (n *NetworkPolicyController) eeLabelsMatchGroupSelector(ee *v1alpha1.ExternalEntity, eeNS *v1.Namespace, sel *antreatypes.GroupSelector) bool { + if sel.Namespace != "" { + if sel.Namespace != ee.Namespace { + // ExternalEntitys must be matched within the same Namespace. + return false + } + if sel.ExternalEntitySelector != nil && sel.ExternalEntitySelector.Matches(labels.Set(ee.Labels)) { + // externalEntitySelector matches the Pod's labels. + return true + } + // externalEntitySelector does not match the Pod's labels. + return false + } else if sel.NamespaceSelector != nil && sel.ExternalEntitySelector != nil { + // ExternalEntity event may arrive before ExternalEntity's Namespace event. In this case, we must + // ensure that the ExternalEntity Namespace is not nil. + if eeNS == nil || !sel.NamespaceSelector.Matches(labels.Set(eeNS.Labels)) { + // ExternalEntity's Namespace do not match namespaceSelector. + return false + } + if sel.ExternalEntitySelector != nil && !sel.ExternalEntitySelector.Matches(labels.Set(ee.Labels)) { + // ExternalEntity's Namespace matches namespaceSelector but ExternalEntity's labels do not match + // the ExternalEntitySelector. + return false + } + // ExternalEntity's Namespace matches namespaceSelector and ExternalEntity's labels matches + // externalEntitySelector. + return true + } else if sel.NamespaceSelector != nil && sel.PodSelector == nil { + // Selector only has a NamespaceSelector. + // ExternalEntity event may arrive before ExternalEntity's Namespace event. In this case, we must + // ensure that the ExternalEntity Namespace is not nil. + if eeNS == nil || !sel.NamespaceSelector.Matches(labels.Set(eeNS.Labels)) { + // Namespace labels do not match namespaceSelector. + return false + } + // Namespace labels match namespaceSelector. + return true + } + return false +} + // filterAddressGroupsForNamespace computes a list of AddressGroup keys which // match the Namespace's labels. func (n *NetworkPolicyController) filterAddressGroupsForNamespace(namespace *v1.Namespace) sets.String { @@ -461,12 +532,44 @@ func (n *NetworkPolicyController) filterAppliedToGroupsForPod(pod *v1.Pod) sets. return matchingKeySet } +// TODO: consider unifying with filterAppliedToGroupsForPod +func (n *NetworkPolicyController) filterAppliedToGroupsForExternalEntity(ee *v1alpha1.ExternalEntity) sets.String { + matchingKeySet := sets.String{} + appliedToGroups, _ := n.appliedToGroupStore.GetByIndex(cache.NamespaceIndex, ee.Namespace) + eeNS, _ := n.namespaceLister.Get(ee.Namespace) + for _, group := range appliedToGroups { + appGroup := group.(*antreatypes.AppliedToGroup) + if n.eeLabelsMatchGroupSelector(ee, eeNS, &appGroup.Selector) { + matchingKeySet.Insert(appGroup.Name) + klog.V(2).Infof("ExternalEntity %s/%s matched AppliedToGroup %s", ee.Namespace, ee.Name, appGroup.Name) + } + } + return matchingKeySet +} + +// TODO: consider unifying with filterAddressToGroupsForPod +func (n *NetworkPolicyController) filterAddressGroupsForExternalEntity(ee *v1alpha1.ExternalEntity) sets.String { + matchingKeySet := sets.String{} + // AddressGroups that are in this namespace or that are cluster scoped can possibly select this ExternalEntity. + localAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, ee.Namespace) + clusterScopedAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, "") + eeNS, _ := n.namespaceLister.Get(ee.Namespace) + for _, group := range append(localAddressGroups, clusterScopedAddressGroups...) { + addrGroup := group.(*antreatypes.AddressGroup) + if n.eeLabelsMatchGroupSelector(ee, eeNS, &addrGroup.Selector) { + matchingKeySet.Insert(addrGroup.Name) + klog.V(2).Infof("ExternalEntity %s/%s matched AddressGroup %s", ee.Namespace, ee.Name, addrGroup.Name) + } + } + return matchingKeySet +} + // createAddressGroup creates an AddressGroup object corresponding to a // NetworkPolicyPeer object in NetworkPolicyRule. This function simply // creates the object without actually populating the PodAddresses as the // affected Pods are calculated during sync process. func (n *NetworkPolicyController) createAddressGroup(peer networkingv1.NetworkPolicyPeer, np *networkingv1.NetworkPolicy) string { - groupSelector := toGroupSelector(np.ObjectMeta.Namespace, peer.PodSelector, peer.NamespaceSelector) + groupSelector := toGroupSelector(np.ObjectMeta.Namespace, peer.PodSelector, peer.NamespaceSelector, nil) normalizedUID := getNormalizedUID(groupSelector.NormalizedName) // Get or create an AddressGroup for the generated UID. _, found, _ := n.addressGroupStore.Get(normalizedUID) @@ -542,7 +645,7 @@ func toAntreaIPBlock(ipBlock *networkingv1.IPBlock) (*controlplane.IPBlock, erro // wherein, it will be either stored as a new Object in case of ADD event or // modified and store the updated instance, in case of an UPDATE event. func (n *NetworkPolicyController) processNetworkPolicy(np *networkingv1.NetworkPolicy) *antreatypes.NetworkPolicy { - appliedToGroupKey := n.createAppliedToGroup(np.Namespace, &np.Spec.PodSelector, nil) + appliedToGroupKey := n.createAppliedToGroup(np.Namespace, &np.Spec.PodSelector, nil, nil) appliedToGroupNames := []string{appliedToGroupKey} rules := make([]controlplane.NetworkPolicyRule, 0, len(np.Spec.Ingress)+len(np.Spec.Egress)) var ingressRuleExists, egressRuleExists bool @@ -841,6 +944,108 @@ func (n *NetworkPolicyController) deletePod(old interface{}) { } } +// addExternalEntity retrieves all AddressGroups and AppliedToGroups which match the ExternalEnitty's +// labels and enqueues the groups key for further processing. +func (n *NetworkPolicyController) addExternalEntity(obj interface{}) { + defer n.heartbeat("addExternalEntity") + ee := obj.(*v1alpha1.ExternalEntity) + klog.V(2).Infof("Processing External Entity %s/%s ADD event, labels: %v", ee.Namespace, ee.Name, ee.Labels) + // Find all AppliedToGroup keys which match the ExternalEntity's labels. + appliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(ee) + // Find all AddressGroup keys which match the ExternalEntity's labels. + addressGroupKeySet := n.filterAddressGroupsForExternalEntity(ee) + // Enqueue groups to their respective queues for group processing. + for group := range appliedToGroupKeySet { + n.enqueueAppliedToGroup(group) + } + for group := range addressGroupKeySet { + n.enqueueAddressGroup(group) + } +} + +// updateExternalEntity retrieves all AddressGroups and AppliedToGroups which match the +// updated and old ExternalEntity's labels and enqueues the group keys for further +// processing. +func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{}) { + defer n.heartbeat("updateExternalEntity") + oldEE := oldObj.(*v1alpha1.ExternalEntity) + curEE := curObj.(*v1alpha1.ExternalEntity) + klog.V(2).Infof("Processing Pod %s/%s UPDATE event, labels: %v", curEE.Namespace, curEE.Name, curEE.Labels) + // No need to trigger processing of groups if there is no change in the + // Pod labels or Pods Node or Pods IP. + labelsEqual := labels.Equals(labels.Set(oldEE.Labels), labels.Set(curEE.Labels)) + // TODO: Add util function to detect endpoint updates + if labelsEqual && oldEE.Spec.ExternalNode == curEE.Spec.ExternalNode { + klog.V(4).Infof("No change in Pod %s/%s. Skipping NetworkPolicy evaluation.", curEE.Namespace, curEE.Name) + return + } + // Find groups matching the old Pod's labels. + oldAddressGroupKeySet := n.filterAddressGroupsForExternalEntity(oldEE) + oldAppliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(oldEE) + // Find groups matching the new Pod's labels. + curAppliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(curEE) + curAddressGroupKeySet := n.filterAddressGroupsForExternalEntity(curEE) + // Create set to hold the group keys to enqueue. + var appliedToGroupKeys sets.String + var addressGroupKeys sets.String + // AppliedToGroup keys must be enqueued only if the Pod's Node or IP has changed or + // if Pod's label change causes it to match new Groups. + // TODO: Add util function to detect endpoint updates + if oldEE.Spec.ExternalNode != curEE.Spec.ExternalNode { + appliedToGroupKeys = oldAppliedToGroupKeySet.Union(curAppliedToGroupKeySet) + } else if !labelsEqual { + // No need to enqueue common AppliedToGroups as they already have latest Pod + // information. + appliedToGroupKeys = oldAppliedToGroupKeySet.Difference(curAppliedToGroupKeySet).Union(curAppliedToGroupKeySet.Difference(oldAppliedToGroupKeySet)) + } + // AddressGroup keys must be enqueued only if the Pod's IP has changed or + // if Pod's label change causes it to match new Groups. + // TODO: Add util function to detect endpoint updates + if !labelsEqual { + // No need to enqueue common AddressGroups as they already have latest Pod + // information. + addressGroupKeys = oldAddressGroupKeySet.Difference(curAddressGroupKeySet).Union(curAddressGroupKeySet.Difference(oldAddressGroupKeySet)) + } + for group := range appliedToGroupKeys { + n.enqueueAppliedToGroup(group) + } + for group := range addressGroupKeys { + n.enqueueAddressGroup(group) + } +} + +// deletePod retrieves all AddressGroups and AppliedToGroups which match the Pod's +// labels and enqueues the groups key for further processing. +func (n *NetworkPolicyController) deleteExternalEntity(old interface{}) { + ee, ok := old.(*v1alpha1.ExternalEntity) + if !ok { + tombstone, ok := old.(cache.DeletedFinalStateUnknown) + if !ok { + klog.Errorf("Error decoding object when deleting ExternalEntity, invalid type: %v", old) + return + } + ee, ok = tombstone.Obj.(*v1alpha1.ExternalEntity) + if !ok { + klog.Errorf("Error decoding object tombstone when deleting ExternalEntity, invalid type: %v", tombstone.Obj) + return + } + } + defer n.heartbeat("deleteExternalEntity") + + klog.V(2).Infof("Processing ExternalEntity %s/%s DELETE event, labels: %v", ee.Namespace, ee.Name, ee.Labels) + // Find all AppliedToGroup keys which match the Pod's labels. + appliedToGroupKeys := n.filterAppliedToGroupsForExternalEntity(ee) + // Find all AddressGroup keys which match the Pod's labels. + addressGroupKeys := n.filterAddressGroupsForExternalEntity(ee) + // Enqueue groups to their respective queues for group processing. + for group := range appliedToGroupKeys { + n.enqueueAppliedToGroup(group) + } + for group := range addressGroupKeys { + n.enqueueAddressGroup(group) + } +} + // addNamespace retrieves all AddressGroups which match the Namespace // labels and enqueues the group keys for further processing. func (n *NetworkPolicyController) addNamespace(obj interface{}) { @@ -1139,7 +1344,6 @@ func (n *NetworkPolicyController) syncAddressGroup(key string) error { return nil } addressGroup := addressGroupObj.(*antreatypes.AddressGroup) - var pods []*v1.Pod // NodeNames set must be considered immutable once generated and updated // in the store. If any change is needed, the set must be regenerated with // the new NodeNames and the store must be updated. @@ -1148,31 +1352,11 @@ func (n *NetworkPolicyController) syncAddressGroup(key string) error { internalNP := internalNPObj.(*antreatypes.NetworkPolicy) addrGroupNodeNames = addrGroupNodeNames.Union(internalNP.SpanMeta.NodeNames) } - // Find all Pods matching its selectors and update store. + // Find all Pods and ExternalEntities matching its selectors and update store. groupSelector := addressGroup.Selector - if groupSelector.Namespace != "" { - // Namespace presence indicates Pods must be selected from the same Namespace. - pods, _ = n.podLister.Pods(groupSelector.Namespace).List(groupSelector.PodSelector) - } else if groupSelector.NamespaceSelector != nil && groupSelector.PodSelector != nil { - // Pods must be selected from Namespaces matching nsSelector. - namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) - for _, ns := range namespaces { - nsPods, _ := n.podLister.Pods(ns.Name).List(groupSelector.PodSelector) - pods = append(pods, nsPods...) - } - } else if groupSelector.NamespaceSelector != nil { - // All the Pods from Namespaces matching the nsSelector must be selected. - namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) - for _, ns := range namespaces { - nsPods, _ := n.podLister.Pods(ns.Name).List(labels.Everything()) - pods = append(pods, nsPods...) - } - } else if groupSelector.PodSelector != nil { - // Lack of Namespace and NamespaceSelector indicates Pods must be selected - // from all Namespaces. - pods, _ = n.podLister.Pods("").List(groupSelector.PodSelector) - } + pods, externalEntities := n.processSelector(groupSelector) podSet := controlplane.GroupMemberPodSet{} + memberSet := controlplane.GroupMemberSet{} for _, pod := range pods { if pod.Status.PodIP == "" { // No need to insert Pod IPAddress when it is unset. @@ -1180,14 +1364,18 @@ func (n *NetworkPolicyController) syncAddressGroup(key string) error { } podSet.Insert(podToMemberPod(pod, true, false)) } - updatedAddressGroup := &antreatypes.AddressGroup{ - Name: addressGroup.Name, - UID: addressGroup.UID, - Selector: addressGroup.Selector, - Pods: podSet, - SpanMeta: antreatypes.SpanMeta{NodeNames: addrGroupNodeNames}, + for _, entity := range externalEntities { + memberSet.Insert(externalEntityToGroupMember(entity, true)) } - klog.V(2).Infof("Updating existing AddressGroup %s with %d addresses and %d Nodes", key, len(podSet), addrGroupNodeNames.Len()) + updatedAddressGroup := &antreatypes.AddressGroup{ + Name: addressGroup.Name, + UID: addressGroup.UID, + Selector: addressGroup.Selector, + Pods: podSet, + GroupMembers: memberSet, + SpanMeta: antreatypes.SpanMeta{NodeNames: addrGroupNodeNames}, + } + klog.V(2).Infof("Updating existing AddressGroup %s with %d pods, %d external entities and %d Nodes", key, len(podSet), len(memberSet), addrGroupNodeNames.Len()) n.addressGroupStore.Update(updatedAddressGroup) return nil } @@ -1225,6 +1413,76 @@ func podToMemberPod(pod *v1.Pod, includeIP, includePodRef bool) *controlplane.Gr return memberPod } +func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity, includeRef bool) *networking.GroupMember { + memberEntity := &networking.GroupMember{} + for _, endpoint := range ee.Spec.Endpoints { + var networkingPorts []networking.NamedPort + for _, port := range endpoint.Ports { + networkingPorts = append(networkingPorts, networking.NamedPort{ + Port: port.Port, + Name: port.Name, + Protocol: networking.Protocol(port.Protocol), + }) + } + ep := networking.Endpoint{ + IP: ipStrToIPAddress(endpoint.IP), + Ports: networkingPorts, + } + memberEntity.Endpoints = append(memberEntity.Endpoints, ep) + } + if includeRef { + entityRef := networking.ExternalEntityReference{ + Name: ee.Name, + Namespace: ee.Namespace, + } + memberEntity.ExternalEntity = &entityRef + } + return memberEntity +} + +func (n *NetworkPolicyController) processSelector(groupSelector antreatypes.GroupSelector) ([]*v1.Pod, []*v1alpha1.ExternalEntity) { + var pods []*v1.Pod + var externalEntities []*v1alpha1.ExternalEntity + if groupSelector.Namespace != "" { + // Namespace presence indicates Pods and ExternalEnitities must be selected from the same Namespace. + if groupSelector.PodSelector != nil { + pods, _ = n.podLister.Pods(groupSelector.Namespace).List(groupSelector.PodSelector) + } + if groupSelector.ExternalEntitySelector != nil { + externalEntities, _ = n.externalEntityLister.ExternalEntities(groupSelector.Namespace).List(groupSelector.ExternalEntitySelector) + } + } else if groupSelector.NamespaceSelector != nil && (groupSelector.PodSelector != nil || groupSelector.ExternalEntitySelector != nil) { + // Pods and ExternalEntities must be selected from Namespaces matching nsSelector. + namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) + for _, ns := range namespaces { + if groupSelector.PodSelector != nil { + nsPods, _ := n.podLister.Pods(ns.Name).List(groupSelector.PodSelector) + pods = append(pods, nsPods...) + } + if groupSelector.ExternalEntitySelector != nil { + nsExtEntities, _ := n.externalEntityLister.ExternalEntities(ns.Name).List(groupSelector.ExternalEntitySelector) + externalEntities = append(externalEntities, nsExtEntities...) + } + } + } else if groupSelector.NamespaceSelector != nil { + // All the Pods from Namespaces matching the nsSelector must be selected. + namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) + for _, ns := range namespaces { + nsPods, _ := n.podLister.Pods(ns.Name).List(labels.Everything()) + pods = append(pods, nsPods...) + nsExtEntities, _ := n.externalEntityLister.ExternalEntities(ns.Name).List(labels.Everything()) + externalEntities = append(externalEntities, nsExtEntities...) + } + } else if groupSelector.PodSelector != nil { + // Lack of Namespace and NamespaceSelector indicates Pods must be selected + // from all Namespaces. + pods, _ = n.podLister.Pods("").List(groupSelector.PodSelector) + } else if groupSelector.ExternalEntitySelector != nil { + externalEntities, _ = n.externalEntityLister.ExternalEntities("").List(groupSelector.ExternalEntitySelector) + } + return pods, externalEntities +} + // syncAppliedToGroup enqueues all the internal NetworkPolicy keys that // refer this AppliedToGroup and update the AppliedToGroup Pod // references by Node to reflect the latest set of affected Pods based @@ -1236,7 +1494,6 @@ func (n *NetworkPolicyController) syncAppliedToGroup(key string) error { metrics.DurationAppliedToGroupSyncing.Observe(float64(d.Milliseconds())) klog.V(2).Infof("Finished syncing AppliedToGroup %s. (%v)", key, d) }() - podSetByNode := make(map[string]controlplane.GroupMemberPodSet) var pods []*v1.Pod appGroupNodeNames := sets.String{} appliedToGroupObj, found, _ := n.appliedToGroupStore.Get(key) @@ -1244,31 +1501,13 @@ func (n *NetworkPolicyController) syncAppliedToGroup(key string) error { klog.V(2).Infof("AppliedToGroup %s not found.", key) return nil } + podSetByNode := make(map[string]controlplane.GroupMemberPodSet) + memberSetByNode := make(map[string]controlplane.GroupMemberSet) + scheduledPodNum, scheduledExtEntityNum := 0, 0 + appliedToGroup := appliedToGroupObj.(*antreatypes.AppliedToGroup) groupSelector := appliedToGroup.Selector - if groupSelector.Namespace != "" { - // AppliedTo Group was created for k8s networkpolicy and must select pods in its own namespace. - pods, _ = n.podLister.Pods(groupSelector.Namespace).List(groupSelector.PodSelector) - } else if groupSelector.NamespaceSelector != nil && groupSelector.PodSelector != nil { - // Pods must be selected from Namespaces matching nsSelector. - namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) - for _, ns := range namespaces { - nsPods, _ := n.podLister.Pods(ns.Name).List(groupSelector.PodSelector) - pods = append(pods, nsPods...) - } - } else if groupSelector.NamespaceSelector != nil { - // All the Pods from Namespaces matching the nsSelector must be selected. - namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) - for _, ns := range namespaces { - nsPods, _ := n.podLister.Pods(ns.Name).List(labels.Everything()) - pods = append(pods, nsPods...) - } - } else if groupSelector.PodSelector != nil && groupSelector.Namespace == "" { - // Lack of Namespace and NamespaceSelector indicates Pods must be selected - // from all Namespaces. - pods, _ = n.podLister.Pods("").List(groupSelector.PodSelector) - } - scheduledPodNum := 0 + pods, externalEntities := n.processSelector(groupSelector) for _, pod := range pods { if pod.Spec.NodeName == "" { // No need to process Pod when it's not scheduled. @@ -1285,14 +1524,29 @@ func (n *NetworkPolicyController) syncAppliedToGroup(key string) error { // Update the NodeNames in order to set the SpanMeta for AppliedToGroup. appGroupNodeNames.Insert(pod.Spec.NodeName) } - updatedAppliedToGroup := &antreatypes.AppliedToGroup{ - UID: appliedToGroup.UID, - Name: appliedToGroup.Name, - Selector: appliedToGroup.Selector, - PodsByNode: podSetByNode, - SpanMeta: antreatypes.SpanMeta{NodeNames: appGroupNodeNames}, + for _, extEntity := range externalEntities { + if extEntity.Spec.ExternalNode == "" { + continue + } + scheduledExtEntityNum++ + entitySet := memberSetByNode[extEntity.Spec.ExternalNode] + if entitySet == nil { + entitySet = networking.GroupMemberSet{} + } + entitySet.Insert(externalEntityToGroupMember(extEntity, true)) + memberSetByNode[extEntity.Spec.ExternalNode] = entitySet + appGroupNodeNames.Insert(extEntity.Spec.ExternalNode) } - klog.V(2).Infof("Updating existing AppliedToGroup %s with %d Pods and %d Nodes", key, scheduledPodNum, appGroupNodeNames.Len()) + updatedAppliedToGroup := &antreatypes.AppliedToGroup{ + UID: appliedToGroup.UID, + Name: appliedToGroup.Name, + Selector: appliedToGroup.Selector, + PodsByNode: podSetByNode, + GroupMemberByNode: memberSetByNode, + SpanMeta: antreatypes.SpanMeta{NodeNames: appGroupNodeNames}, + } + klog.V(2).Infof("Updating existing AppliedToGroup %s with %d Pods and %d External Entities on %d Nodes", + key, scheduledPodNum, scheduledExtEntityNum, appGroupNodeNames.Len()) n.appliedToGroupStore.Update(updatedAppliedToGroup) // Get all internal NetworkPolicy objects that refers this AppliedToGroup. diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index bf1c4681064..8589fdfb898 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -86,6 +86,7 @@ func newController(objects ...runtime.Object) (*fake.Clientset, *networkPolicyCo crdClient, informerFactory.Core().V1().Pods(), informerFactory.Core().V1().Namespaces(), + crdInformerFactory.Core().V1alpha1().ExternalEntities(), informerFactory.Networking().V1().NetworkPolicies(), crdInformerFactory.Security().V1alpha1().ClusterNetworkPolicies(), crdInformerFactory.Security().V1alpha1().NetworkPolicies(), @@ -133,7 +134,7 @@ func TestAddNetworkPolicy(t *testing.T) { selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} selectorAll := metav1.LabelSelector{} matchAllPeerEgress := matchAllPeer - matchAllPeerEgress.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll).NormalizedName)} + matchAllPeerEgress.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll, nil).NormalizedName)} tests := []struct { name string inputPolicy *networkingv1.NetworkPolicy @@ -162,7 +163,7 @@ func TestAddNetworkPolicy(t *testing.T) { Priority: defaultRulePriority, Action: &defaultAction, }}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 0, @@ -188,7 +189,7 @@ func TestAddNetworkPolicy(t *testing.T) { Priority: defaultRulePriority, Action: &defaultAction, }}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 0, @@ -228,7 +229,7 @@ func TestAddNetworkPolicy(t *testing.T) { Priority: defaultRulePriority, Action: &defaultAction, }}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -249,7 +250,7 @@ func TestAddNetworkPolicy(t *testing.T) { Rules: []controlplane.NetworkPolicyRule{ denyAllIngressRule, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 0, @@ -270,7 +271,7 @@ func TestAddNetworkPolicy(t *testing.T) { Rules: []controlplane.NetworkPolicyRule{ denyAllEgressRule, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 0, @@ -321,7 +322,7 @@ func TestAddNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -335,7 +336,7 @@ func TestAddNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -347,7 +348,7 @@ func TestAddNetworkPolicy(t *testing.T) { Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -394,7 +395,7 @@ func TestAddNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -408,7 +409,7 @@ func TestAddNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", nil, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", nil, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -420,7 +421,7 @@ func TestAddNetworkPolicy(t *testing.T) { Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 2, @@ -460,7 +461,7 @@ func TestDeleteNetworkPolicy(t *testing.T) { ns := npObj.ObjectMeta.Namespace pSelector := npObj.Spec.PodSelector pLabelSelector, _ := metav1.LabelSelectorAsSelector(&pSelector) - apgID := getNormalizedUID(generateNormalizedName(ns, pLabelSelector, nil)) + apgID := getNormalizedUID(generateNormalizedName(ns, pLabelSelector, nil, nil)) _, npc := newController() npc.addNetworkPolicy(npObj) npc.deleteNetworkPolicy(npObj) @@ -544,7 +545,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, @@ -552,13 +553,13 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 2, @@ -589,13 +590,13 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -626,13 +627,13 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 1, @@ -650,7 +651,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { Name: "npA", Namespace: "nsA", Rules: []controlplane.NetworkPolicyRule{}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 0, @@ -697,7 +698,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, @@ -705,7 +706,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorA).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorA, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, @@ -713,13 +714,13 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 3, @@ -759,7 +760,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, @@ -767,13 +768,13 @@ func TestUpdateNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, Priority: defaultRulePriority, Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expAppliedToGroups: 1, expAddressGroups: 2, @@ -1115,9 +1116,9 @@ func TestAddPod(t *testing.T) { _, npc := newController() npc.addNetworkPolicy(testNPObj) npc.podStore.Add(tt.addedPod) - appGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorSpec, nil).NormalizedName) - inGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorIn, nil).NormalizedName) - outGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorOut, nil).NormalizedName) + appGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorSpec, nil, nil).NormalizedName) + inGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorIn, nil, nil).NormalizedName) + outGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorOut, nil, nil).NormalizedName) npc.syncAppliedToGroup(appGroupID) npc.syncAddressGroup(inGroupID) npc.syncAddressGroup(outGroupID) @@ -1153,7 +1154,7 @@ func TestDeletePod(t *testing.T) { inPSelector := metav1.LabelSelector{ MatchLabels: ruleLabels, } - matchAppGID := getNormalizedUID(generateNormalizedName(ns, mLabelSelector, nil)) + matchAppGID := getNormalizedUID(generateNormalizedName(ns, mLabelSelector, nil, nil)) ingressRules := []networkingv1.NetworkPolicyIngressRule{ { From: []networkingv1.NetworkPolicyPeer{ @@ -1308,8 +1309,8 @@ func TestAddNamespace(t *testing.T) { p2 := getPod("p2", "nsA", "nodeA", "2.2.3.4", false) npc.podStore.Add(p1) npc.podStore.Add(p2) - inGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorIn).NormalizedName) - outGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorOut).NormalizedName) + inGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorIn, nil).NormalizedName) + outGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorOut, nil).NormalizedName) npc.syncAddressGroup(inGroupID) npc.syncAddressGroup(outGroupID) updatedInAddrGroupObj, _, _ := npc.addressGroupStore.Get(inGroupID) @@ -1425,8 +1426,8 @@ func TestDeleteNamespace(t *testing.T) { npc.podStore.Add(p1) npc.podStore.Add(p2) npc.namespaceStore.Delete(tt.deletedNamespace) - inGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorIn).NormalizedName) - outGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorOut).NormalizedName) + inGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorIn, nil).NormalizedName) + outGroupID := getNormalizedUID(toGroupSelector("", nil, &selectorOut, nil).NormalizedName) npc.syncAddressGroup(inGroupID) npc.syncAddressGroup(outGroupID) npc.podStore.Delete(p1) @@ -1473,7 +1474,7 @@ func TestToGroupSelector(t *testing.T) { Namespace: "nsName", NamespaceSelector: nil, PodSelector: pLabelSelector, - NormalizedName: generateNormalizedName("nsName", pLabelSelector, nil), + NormalizedName: generateNormalizedName("nsName", pLabelSelector, nil, nil), }, }, { @@ -1485,7 +1486,7 @@ func TestToGroupSelector(t *testing.T) { Namespace: "", NamespaceSelector: nLabelSelector, PodSelector: nil, - NormalizedName: generateNormalizedName("", nil, nLabelSelector), + NormalizedName: generateNormalizedName("", nil, nLabelSelector, nil), }, }, { @@ -1497,7 +1498,7 @@ func TestToGroupSelector(t *testing.T) { Namespace: "nsName", NamespaceSelector: nil, PodSelector: pLabelSelector, - NormalizedName: generateNormalizedName("nsName", pLabelSelector, nil), + NormalizedName: generateNormalizedName("nsName", pLabelSelector, nil, nil), }, }, { @@ -1509,13 +1510,13 @@ func TestToGroupSelector(t *testing.T) { Namespace: "", NamespaceSelector: nLabelSelector, PodSelector: pLabelSelector, - NormalizedName: generateNormalizedName("", pLabelSelector, nLabelSelector), + NormalizedName: generateNormalizedName("", pLabelSelector, nLabelSelector, nil), }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - group := toGroupSelector(tt.namespace, tt.podSelector, tt.nsSelector) + group := toGroupSelector(tt.namespace, tt.podSelector, tt.nsSelector, nil) if group.Namespace != tt.expGroupSelector.Namespace { t.Errorf("Group Namespace incorrectly set. Expected %s, got: %s", tt.expGroupSelector.Namespace, group.Namespace) } @@ -1595,7 +1596,7 @@ func TestGenerateNormalizedName(t *testing.T) { }, } for _, table := range tables { - name := generateNormalizedName(table.namespace, table.pSelector, table.nSelector) + name := generateNormalizedName(table.namespace, table.pSelector, table.nSelector, nil) if table.expName != name { t.Errorf("Unexpected normalized name. Expected %s, got %s", table.expName, name) } @@ -1733,7 +1734,7 @@ func TestToAntreaPeer(t *testing.T) { selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} selectorAll := metav1.LabelSelector{} matchAllPodsPeer := matchAllPeer - matchAllPodsPeer.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll).NormalizedName)} + matchAllPodsPeer.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll, nil).NormalizedName)} tests := []struct { name string inPeers []networkingv1.NetworkPolicyPeer @@ -1754,8 +1755,8 @@ func TestToAntreaPeer(t *testing.T) { }, outPeer: controlplane.NetworkPolicyPeer{ AddressGroups: []string{ - getNormalizedUID(toGroupSelector("nsA", &selectorA, &selectorB).NormalizedName), - getNormalizedUID(toGroupSelector("nsA", &selectorC, nil).NormalizedName), + getNormalizedUID(toGroupSelector("nsA", &selectorA, &selectorB, nil).NormalizedName), + getNormalizedUID(toGroupSelector("nsA", &selectorC, nil, nil).NormalizedName), }, }, direction: controlplane.DirectionIn, @@ -1773,8 +1774,8 @@ func TestToAntreaPeer(t *testing.T) { }, outPeer: controlplane.NetworkPolicyPeer{ AddressGroups: []string{ - getNormalizedUID(toGroupSelector("nsA", &selectorA, &selectorB).NormalizedName), - getNormalizedUID(toGroupSelector("nsA", &selectorC, nil).NormalizedName), + getNormalizedUID(toGroupSelector("nsA", &selectorA, &selectorB, nil).NormalizedName), + getNormalizedUID(toGroupSelector("nsA", &selectorC, nil, nil).NormalizedName), }, }, direction: controlplane.DirectionOut, @@ -1916,7 +1917,7 @@ func TestProcessNetworkPolicy(t *testing.T) { Priority: defaultRulePriority, Action: &defaultAction, }}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 0, @@ -1935,7 +1936,7 @@ func TestProcessNetworkPolicy(t *testing.T) { Name: "npA", Namespace: "nsA", Rules: []controlplane.NetworkPolicyRule{denyAllEgressRule}, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 0, @@ -1986,7 +1987,7 @@ func TestProcessNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -2000,7 +2001,7 @@ func TestProcessNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionOut, To: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -2012,7 +2013,7 @@ func TestProcessNetworkPolicy(t *testing.T) { Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 1, @@ -2059,7 +2060,7 @@ func TestProcessNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorB, nil, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -2073,7 +2074,7 @@ func TestProcessNetworkPolicy(t *testing.T) { { Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{ - AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", nil, &selectorC).NormalizedName)}, + AddressGroups: []string{getNormalizedUID(toGroupSelector("nsA", nil, &selectorC, nil).NormalizedName)}, }, Services: []controlplane.Service{ { @@ -2085,7 +2086,7 @@ func TestProcessNetworkPolicy(t *testing.T) { Action: &defaultAction, }, }, - AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil).NormalizedName)}, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, }, expectedAppliedToGroups: 1, expectedAddressGroups: 2, diff --git a/pkg/controller/networkpolicy/store/addressgroup.go b/pkg/controller/networkpolicy/store/addressgroup.go index 23a6bef76d4..eae182a36cb 100644 --- a/pkg/controller/networkpolicy/store/addressgroup.go +++ b/pkg/controller/networkpolicy/store/addressgroup.go @@ -88,6 +88,9 @@ func ToAddressGroupMsg(in *types.AddressGroup, out *controlplane.AddressGroup, i for _, p := range in.Pods { out.Pods = append(out.Pods, *p) } + for _, member := range in.GroupMembers { + out.GroupMembers = append(out.GroupMembers, *member) + } } var _ storage.GenEventFunc = genAddressGroupEvent @@ -118,7 +121,9 @@ func genAddressGroupEvent(key string, prevObj, currObj interface{}, rv uint64) ( // each watcher when generating *event.Event. if event.PrevGroup != nil && event.CurrGroup != nil { var addedPods, removedPods []controlplane.GroupMemberPod - + // TODO: Eventually pods should be unified as GroupMember + var addedMembers, removedMembers []controlplane.GroupMember + // TODO: Deprecate addedPods and removedPods for podHash, pod := range event.CurrGroup.Pods { if _, exists := event.PrevGroup.Pods[podHash]; !exists { addedPods = append(addedPods, *pod) @@ -129,13 +134,25 @@ func genAddressGroupEvent(key string, prevObj, currObj interface{}, rv uint64) ( removedPods = append(removedPods, *pod) } } + for memberHash, member := range event.CurrGroup.GroupMembers { + if _, exists := event.PrevGroup.GroupMembers[memberHash]; !exists { + addedMembers = append(addedMembers, *member) + } + } + for memberHash, member := range event.PrevGroup.GroupMembers { + if _, exists := event.CurrGroup.GroupMembers[memberHash]; !exists { + removedMembers = append(removedMembers, *member) + } + } // PatchObject will not be generated when only span changes. - if len(addedPods)+len(removedPods) > 0 { + if len(addedPods)+len(removedPods)+len(addedMembers)+len(removedMembers) > 0 { event.PatchObject = new(controlplane.AddressGroupPatch) event.PatchObject.UID = event.CurrGroup.UID event.PatchObject.Name = event.CurrGroup.Name event.PatchObject.AddedPods = addedPods event.PatchObject.RemovedPods = removedPods + event.PatchObject.AddedGroupMembers = addedMembers + event.PatchObject.RemovedGroupMembers = removedMembers } } diff --git a/pkg/controller/networkpolicy/store/appliedtogroup.go b/pkg/controller/networkpolicy/store/appliedtogroup.go index a52a4af2af5..23e18b158ac 100644 --- a/pkg/controller/networkpolicy/store/appliedtogroup.go +++ b/pkg/controller/networkpolicy/store/appliedtogroup.go @@ -70,18 +70,31 @@ func (event *appliedToGroupEvent) ToWatchEvent(selectors *storage.Selectors, isI obj.Name = event.CurrGroup.Name var currPods, prevPods controlplane.GroupMemberPodSet + // TODO: Eventually pods should be unified as GroupMember + var currMembers, prevMembers controlplane.GroupMemberSet if nodeSpecified { + // TODO: Deprecate currPods and prevPods currPods = event.CurrGroup.PodsByNode[nodeName] prevPods = event.PrevGroup.PodsByNode[nodeName] + currMembers = event.CurrGroup.GroupMemberByNode[nodeName] + prevMembers = event.PrevGroup.GroupMemberByNode[nodeName] } else { currPods = controlplane.GroupMemberPodSet{} + currMembers = controlplane.GroupMemberSet{} for _, pods := range event.CurrGroup.PodsByNode { currPods = currPods.Union(pods) } + for _, members := range event.CurrGroup.GroupMemberByNode { + currMembers = currMembers.Union(members) + } prevPods = controlplane.GroupMemberPodSet{} + prevMembers = controlplane.GroupMemberSet{} for _, pods := range event.PrevGroup.PodsByNode { prevPods = prevPods.Union(pods) } + for _, members := range event.PrevGroup.GroupMemberByNode { + prevMembers = prevMembers.Union(members) + } } for _, pod := range currPods.Difference(prevPods) { obj.AddedPods = append(obj.AddedPods, *pod) @@ -89,7 +102,14 @@ func (event *appliedToGroupEvent) ToWatchEvent(selectors *storage.Selectors, isI for _, pod := range prevPods.Difference(currPods) { obj.RemovedPods = append(obj.RemovedPods, *pod) } - if len(obj.AddedPods)+len(obj.RemovedPods) == 0 { + for _, member := range currMembers.Difference(prevMembers) { + obj.AddedGroupMembers = append(obj.AddedGroupMembers, *member) + } + for _, member := range prevMembers.Difference(currMembers) { + obj.RemovedGroupMembers = append(obj.RemovedGroupMembers, *member) + } + + if len(obj.AddedPods)+len(obj.RemovedPods)+len(obj.AddedGroupMembers)+len(obj.RemovedGroupMembers) == 0 { // No change for the watcher. return nil } @@ -141,17 +161,29 @@ func ToAppliedToGroupMsg(in *types.AppliedToGroup, out *controlplane.AppliedToGr return } if nodeName != nil { + // TODO: deprecate PodsByNode if pods, exists := in.PodsByNode[*nodeName]; exists { for _, pod := range pods { out.Pods = append(out.Pods, *pod) } } + if members, exists := in.GroupMemberByNode[*nodeName]; exists { + for _, member := range members { + out.GroupMembers = append(out.GroupMembers, *member) + } + } } else { + // TODO: deprecate PodsByNode for _, pods := range in.PodsByNode { for _, pod := range pods { out.Pods = append(out.Pods, *pod) } } + for _, members := range in.GroupMemberByNode { + for _, member := range members { + out.GroupMembers = append(out.GroupMembers, *member) + } + } } } diff --git a/pkg/controller/types/networkpolicy.go b/pkg/controller/types/networkpolicy.go index c1a814e00d0..6713c9f50ba 100644 --- a/pkg/controller/types/networkpolicy.go +++ b/pkg/controller/types/networkpolicy.go @@ -59,6 +59,8 @@ type GroupSelector struct { PodSelector labels.Selector // This is a label selector which selects Namespaces. It this field is set, Namespace can not be set. NamespaceSelector labels.Selector + // This is a label selector which selects external entities. + ExternalEntitySelector labels.Selector } // AppliedToGroup describes a set of Pods to apply Network Policies to. @@ -74,6 +76,8 @@ type AppliedToGroup struct { // It will be converted to a slice of GroupMemberPod for transferring according // to client's selection. PodsByNode map[string]controlplane.GroupMemberPodSet + // ExternalEntityByNode is a mapping from externalNodeName to a set of GroupMembers on that externalNode + GroupMemberByNode map[string]controlplane.GroupMemberSet } // AddressGroup describes a set of addresses used as source or destination of Network Policy rules. @@ -89,6 +93,9 @@ type AddressGroup struct { // It will be converted to a slice of GroupMemberPod for transferring according // to client's selection. Pods controlplane.GroupMemberPodSet + // GroupMembers is a set of GroupMembers selected by this group + // TODO: Eventually Pods should be unified into the GroupMembers field + GroupMembers controlplane.GroupMemberSet } // NetworkPolicy describes what network traffic is allowed for a set of Pods. From c10b522c2b54fb20909e406a6244c8229fec3256 Mon Sep 17 00:00:00 2001 From: Yang Ding Date: Wed, 26 Aug 2020 16:08:19 -0700 Subject: [PATCH 3/6] Unify functions for Pod and ExternalEntity in networkpolicy controller --- go.mod | 1 + .../networkpolicy/antreanetworkpolicy_test.go | 227 ++++++++++++++++++ .../clusternetworkpolicy_test.go | 2 +- .../networkpolicy/endpoint_querier.go | 4 +- .../networkpolicy/networkpolicy_controller.go | 219 ++++++----------- .../networkpolicy_controller_test.go | 106 ++++++++ .../networkpolicy/store/addressgroup_test.go | 78 +++--- .../store/appliedtogroup_test.go | 85 +++++-- 8 files changed, 522 insertions(+), 200 deletions(-) create mode 100644 pkg/controller/networkpolicy/antreanetworkpolicy_test.go diff --git a/go.mod b/go.mod index 8545151ed77..cb117f15217 100644 --- a/go.mod +++ b/go.mod @@ -25,6 +25,7 @@ require ( github.com/gogo/protobuf v1.3.1 github.com/golang/mock v1.4.3 github.com/golang/protobuf v1.3.2 + github.com/google/go-cmp v0.4.0 github.com/google/uuid v1.1.1 github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd github.com/pkg/errors v0.9.1 diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go new file mode 100644 index 00000000000..e5d0a965e3f --- /dev/null +++ b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go @@ -0,0 +1,227 @@ +// Copyright 2020 Antrea Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package networkpolicy + +import ( + "reflect" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" + + "github.com/vmware-tanzu/antrea/pkg/apis/networking" + secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" + antreatypes "github.com/vmware-tanzu/antrea/pkg/controller/types" +) + +func TestProcessAntreaNetworkPolicy(t *testing.T) { + p10 := float64(10) + appTier := antreatypes.TierApplication + allowAction := secv1alpha1.RuleActionAllow + protocolTCP := networking.ProtocolTCP + intstr80, intstr81 := intstr.FromInt(80), intstr.FromInt(81) + selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} + selectorB := metav1.LabelSelector{MatchLabels: map[string]string{"foo2": "bar2"}} + selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} + tests := []struct { + name string + inputPolicy *secv1alpha1.NetworkPolicy + expectedPolicy *antreatypes.NetworkPolicy + expectedAppliedToGroups int + expectedAddressGroups int + }{ + { + name: "rules-with-same-selectors", + inputPolicy: &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Namespace: "ns1", Name: "npA", UID: "uidA"}, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + {PodSelector: &selectorA}, + }, + Priority: p10, + Ingress: []secv1alpha1.Rule{ + { + Ports: []secv1alpha1.NetworkPolicyPort{ + { + Port: &intstr80, + }, + }, + From: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorB, + NamespaceSelector: &selectorC, + }, + }, + Action: &allowAction, + }, + }, + Egress: []secv1alpha1.Rule{ + { + Ports: []secv1alpha1.NetworkPolicyPort{ + { + Port: &intstr81, + }, + }, + To: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorB, + NamespaceSelector: &selectorC, + }, + }, + Action: &allowAction, + }, + }, + }, + }, + expectedPolicy: &antreatypes.NetworkPolicy{ + UID: "uidA", + Name: "npA", + Namespace: "ns1", + Priority: &p10, + TierPriority: &appTier, + Rules: []networking.NetworkPolicyRule{ + { + Direction: networking.DirectionIn, + From: networking.NetworkPolicyPeer{ + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, + }, + Services: []networking.Service{ + { + Protocol: &protocolTCP, + Port: &intstr80, + }, + }, + Priority: 0, + Action: &allowAction, + }, + { + Direction: networking.DirectionOut, + To: networking.NetworkPolicyPeer{ + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, + }, + Services: []networking.Service{ + { + Protocol: &protocolTCP, + Port: &intstr81, + }, + }, + Priority: 0, + Action: &allowAction, + }, + }, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("ns1", &selectorA, nil, nil).NormalizedName)}, + }, + expectedAppliedToGroups: 1, + expectedAddressGroups: 1, + }, + { + name: "rules-with-different-selectors", + inputPolicy: &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Namespace: "ns2", Name: "npB", UID: "uidB"}, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + {PodSelector: &selectorA}, + }, + Priority: p10, + Ingress: []secv1alpha1.Rule{ + { + Ports: []secv1alpha1.NetworkPolicyPort{ + { + Port: &intstr80, + }, + }, + From: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorB, + }, + }, + Action: &allowAction, + }, + { + Ports: []secv1alpha1.NetworkPolicyPort{ + { + Port: &intstr81, + }, + }, + From: []secv1alpha1.NetworkPolicyPeer{ + { + NamespaceSelector: &selectorC, + }, + }, + Action: &allowAction, + }, + }, + }, + }, + expectedPolicy: &antreatypes.NetworkPolicy{ + UID: "uidB", + Name: "npB", + Namespace: "ns2", + Priority: &p10, + TierPriority: &appTier, + Rules: []networking.NetworkPolicyRule{ + { + Direction: networking.DirectionIn, + From: networking.NetworkPolicyPeer{ + AddressGroups: []string{getNormalizedUID(toGroupSelector("ns2", &selectorB, nil, nil).NormalizedName)}, + }, + Services: []networking.Service{ + { + Protocol: &protocolTCP, + Port: &intstr80, + }, + }, + Priority: 0, + Action: &allowAction, + }, + { + Direction: networking.DirectionIn, + From: networking.NetworkPolicyPeer{ + AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC, nil).NormalizedName)}, + }, + Services: []networking.Service{ + { + Protocol: &protocolTCP, + Port: &intstr81, + }, + }, + Priority: 1, + Action: &allowAction, + }, + }, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("ns2", &selectorA, nil, nil).NormalizedName)}, + }, + expectedAppliedToGroups: 1, + expectedAddressGroups: 2, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, c := newController() + + if actualPolicy := c.processAntreaNetworkPolicy(tt.inputPolicy); !reflect.DeepEqual(actualPolicy, tt.expectedPolicy) { + t.Errorf("processClusterNetworkPolicy() got %v, want %v", actualPolicy, tt.expectedPolicy) + } + + if actualAddressGroups := len(c.addressGroupStore.List()); actualAddressGroups != tt.expectedAddressGroups { + t.Errorf("len(addressGroupStore.List()) got %v, want %v", actualAddressGroups, tt.expectedAddressGroups) + } + + if actualAppliedToGroups := len(c.appliedToGroupStore.List()); actualAppliedToGroups != tt.expectedAppliedToGroups { + t.Errorf("len(appliedToGroupStore.List()) got %v, want %v", actualAppliedToGroups, tt.expectedAppliedToGroups) + } + }) + } +} diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go index 26dbd67eaca..a1045ad4b09 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go @@ -1,4 +1,4 @@ -// Copyright 2019 Antrea Authors +// Copyright 2020 Antrea Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/pkg/controller/networkpolicy/endpoint_querier.go b/pkg/controller/networkpolicy/endpoint_querier.go index d05615a5790..70dd6c87645 100644 --- a/pkg/controller/networkpolicy/endpoint_querier.go +++ b/pkg/controller/networkpolicy/endpoint_querier.go @@ -95,7 +95,7 @@ func (eq *endpointQuerier) QueryNetworkPolicies(namespace string, podName string ingress := make([]*ruleTemp, 0) egress := make([]*ruleTemp, 0) // get all appliedToGroups using filter, then get applied policies using appliedToGroup - appliedToGroupKeys := eq.networkPolicyController.filterAppliedToGroupsForPod(pod) + appliedToGroupKeys := eq.networkPolicyController.filterAppliedToGroupsForPodOrExternalEntity(pod) if err != nil { return nil, err } @@ -118,7 +118,7 @@ func (eq *endpointQuerier) QueryNetworkPolicies(namespace string, podName string } } // get all addressGroups using filter, then get ingress and egress policies using addressGroup - addressGroupKeys := eq.networkPolicyController.filterAddressGroupsForPod(pod) + addressGroupKeys := eq.networkPolicyController.filterAddressGroupsForPodOrExternalEntity(pod) if err != nil { return nil, err } diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index aba09565f39..98fa64207cd 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -27,6 +27,7 @@ import ( "sync" "time" + "github.com/google/go-cmp/cmp" uuid "github.com/satori/go.uuid" v1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -384,51 +385,55 @@ func (n *NetworkPolicyController) createAppliedToGroup(npNsName string, pSel, nS return appliedToGroupUID } -// labelsMatchGroupSelector matches a Pod's labels to the +// labelsMatchGroupSelector matches a ExternalEntity or Pod's labels to the // GroupSelector object and returns true, if and only if the labels // match any of the selector criteria present in the GroupSelector. -func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v1.Namespace, sel *antreatypes.GroupSelector) bool { +func (n *NetworkPolicyController) labelsMatchGroupSelector(obj metav1.Object, ns *v1.Namespace, sel *antreatypes.GroupSelector) bool { + objSelector := sel.PodSelector + if _, ok := obj.(*v1alpha1.ExternalEntity); ok { + objSelector = sel.ExternalEntitySelector + } if sel.Namespace != "" { - if sel.Namespace != pod.Namespace { - // Pods must be matched within the same Namespace. + if sel.Namespace != obj.GetNamespace() { + // Pods or ExternalEntities must be matched within the same Namespace. return false } - if sel.PodSelector != nil && sel.PodSelector.Matches(labels.Set(pod.Labels)) { - // podSelector matches the Pod's labels. + if objSelector != nil && objSelector.Matches(labels.Set(obj.GetLabels())) { + // podSelector or externalEntitySelector matches the ExternalEntity or Pod's labels. return true } - // podSelector does not match the Pod's labels. + // selector does not match the ExternalEntity or Pod's labels. return false - } else if sel.NamespaceSelector != nil && sel.PodSelector != nil { - // Pod event may arrive before Pod's Namespace event. In this case, we must - // ensure that the Pod Namespace is not nil. - if podNS == nil || !sel.NamespaceSelector.Matches(labels.Set(podNS.Labels)) { + } else if sel.NamespaceSelector != nil && objSelector != nil { + // Pod or ExternalEntity event may arrive before Namespace event. In this case, we must + // ensure that the Namespace is not nil. + if ns == nil || !sel.NamespaceSelector.Matches(labels.Set(ns.Labels)) { // Pod's Namespace do not match namespaceSelector. return false } - if sel.PodSelector != nil && !sel.PodSelector.Matches(labels.Set(pod.Labels)) { - // Pod's Namespace matches namespaceSelector but Pod's labels do not match - // the podSelector. + if !objSelector.Matches(labels.Set(obj.GetLabels())) { + // ExternalEntity or Pod's Namespace matches namespaceSelector but + // labels do not match the podSelector or externalEntitySelector. return false } - // Pod's Namespace matches namespaceSelector and Pod's labels matches - // podSelector. + // ExternalEntity or Pod's Namespace matches namespaceSelector and labels matches + // podSelector or externalEntitySelector. return true - } else if sel.NamespaceSelector != nil && sel.ExternalEntitySelector == nil { + } else if sel.NamespaceSelector != nil && sel.ExternalEntitySelector == nil && sel.PodSelector == nil { // Selector only has a NamespaceSelector. - // Pod event may arrive before Pod's Namespace event. In this case, we must - // ensure that the Pod Namespace is not nil. - if podNS == nil || !sel.NamespaceSelector.Matches(labels.Set(podNS.Labels)) { + // Pod or ExternalEntity event may arrive before Namespace event. In this case, we must + // ensure that the Namespace is not nil. + if ns == nil || !sel.NamespaceSelector.Matches(labels.Set(ns.Labels)) { // Namespace labels do not match namespaceSelector. return false } // Namespace labels match namespaceSelector. return true - } else if sel.PodSelector != nil { - // Selector only has a PodSelector and no sel.Namespace. Pods must be matched - // from all Namespaces. - if !sel.PodSelector.Matches(labels.Set(pod.Labels)) { - // pod labels do not match PodSelector. + } else if objSelector != nil { + // Selector only has a PodSelector/ExternalEntitySelector and no sel.Namespace. + // Pods/ExternalEntities must be matched from all Namespaces. + if !sel.PodSelector.Matches(labels.Set(obj.GetLabels())) { + // pod/ee labels do not match PodSelector/ExternalEntitySelector. return false } return true @@ -436,47 +441,6 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(pod *v1.Pod, podNS *v return false } -func (n *NetworkPolicyController) eeLabelsMatchGroupSelector(ee *v1alpha1.ExternalEntity, eeNS *v1.Namespace, sel *antreatypes.GroupSelector) bool { - if sel.Namespace != "" { - if sel.Namespace != ee.Namespace { - // ExternalEntitys must be matched within the same Namespace. - return false - } - if sel.ExternalEntitySelector != nil && sel.ExternalEntitySelector.Matches(labels.Set(ee.Labels)) { - // externalEntitySelector matches the Pod's labels. - return true - } - // externalEntitySelector does not match the Pod's labels. - return false - } else if sel.NamespaceSelector != nil && sel.ExternalEntitySelector != nil { - // ExternalEntity event may arrive before ExternalEntity's Namespace event. In this case, we must - // ensure that the ExternalEntity Namespace is not nil. - if eeNS == nil || !sel.NamespaceSelector.Matches(labels.Set(eeNS.Labels)) { - // ExternalEntity's Namespace do not match namespaceSelector. - return false - } - if sel.ExternalEntitySelector != nil && !sel.ExternalEntitySelector.Matches(labels.Set(ee.Labels)) { - // ExternalEntity's Namespace matches namespaceSelector but ExternalEntity's labels do not match - // the ExternalEntitySelector. - return false - } - // ExternalEntity's Namespace matches namespaceSelector and ExternalEntity's labels matches - // externalEntitySelector. - return true - } else if sel.NamespaceSelector != nil && sel.PodSelector == nil { - // Selector only has a NamespaceSelector. - // ExternalEntity event may arrive before ExternalEntity's Namespace event. In this case, we must - // ensure that the ExternalEntity Namespace is not nil. - if eeNS == nil || !sel.NamespaceSelector.Matches(labels.Set(eeNS.Labels)) { - // Namespace labels do not match namespaceSelector. - return false - } - // Namespace labels match namespaceSelector. - return true - } - return false -} - // filterAddressGroupsForNamespace computes a list of AddressGroup keys which // match the Namespace's labels. func (n *NetworkPolicyController) filterAddressGroupsForNamespace(namespace *v1.Namespace) sets.String { @@ -494,71 +458,39 @@ func (n *NetworkPolicyController) filterAddressGroupsForNamespace(namespace *v1. return matchingKeys } -// filterAddressGroupsForPod computes a list of AddressGroup keys which -// match the Pod's labels. -func (n *NetworkPolicyController) filterAddressGroupsForPod(pod *v1.Pod) sets.String { +// filterAddressGroupsForPodOrExternalEntity computes a list of AddressGroup keys which +// match the ExternalEntity or Pod's labels. +func (n *NetworkPolicyController) filterAddressGroupsForPodOrExternalEntity(obj metav1.Object) sets.String { matchingKeySet := sets.String{} - // AddressGroups that are in this namespace or that are cluster scoped can possibly select this Pod. - localAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, pod.Namespace) + // AddressGroups that are in this namespace or that are cluster scoped can possibly select this Pod/ExternalEntity. + localAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, obj.GetNamespace()) clusterScopedAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, "") - podNS, _ := n.namespaceLister.Get(pod.Namespace) + ns, _ := n.namespaceLister.Get(obj.GetNamespace()) for _, group := range append(localAddressGroups, clusterScopedAddressGroups...) { addrGroup := group.(*antreatypes.AddressGroup) - if n.labelsMatchGroupSelector(pod, podNS, &addrGroup.Selector) { + if n.labelsMatchGroupSelector(obj, ns, &addrGroup.Selector) { matchingKeySet.Insert(addrGroup.Name) - klog.V(2).Infof("Pod %s/%s matched AddressGroup %s", pod.Namespace, pod.Name, addrGroup.Name) + klog.V(2).Infof("%s/%s matched AddressGroup %s", obj.GetNamespace(), obj.GetName(), addrGroup.Name) } } return matchingKeySet } -// filterAppliedToGroupsForPod computes a list of AppliedToGroup keys which -// match the Pod's labels. -func (n *NetworkPolicyController) filterAppliedToGroupsForPod(pod *v1.Pod) sets.String { +// filterAppliedToGroupsForPodOrExternalEntity computes a list of AppliedToGroup keys which +// match the ExternalEntity or Pod's labels. +func (n *NetworkPolicyController) filterAppliedToGroupsForPodOrExternalEntity(obj metav1.Object) sets.String { matchingKeySet := sets.String{} // Get appliedToGroups from the namespace level - appliedToGroups, _ := n.appliedToGroupStore.GetByIndex(cache.NamespaceIndex, pod.Namespace) + appliedToGroups, _ := n.appliedToGroupStore.GetByIndex(cache.NamespaceIndex, obj.GetNamespace()) // Get appliedToGroups from the cluster level clusterATGroups, _ := n.appliedToGroupStore.GetByIndex(cache.NamespaceIndex, "") appliedToGroups = append(appliedToGroups, clusterATGroups...) - podNS, _ := n.namespaceLister.Get(pod.Namespace) - for _, group := range appliedToGroups { - appGroup := group.(*antreatypes.AppliedToGroup) - if n.labelsMatchGroupSelector(pod, podNS, &appGroup.Selector) { - matchingKeySet.Insert(appGroup.Name) - klog.V(2).Infof("Pod %s/%s matched AppliedToGroup %s", pod.Namespace, pod.Name, appGroup.Name) - } - } - return matchingKeySet -} - -// TODO: consider unifying with filterAppliedToGroupsForPod -func (n *NetworkPolicyController) filterAppliedToGroupsForExternalEntity(ee *v1alpha1.ExternalEntity) sets.String { - matchingKeySet := sets.String{} - appliedToGroups, _ := n.appliedToGroupStore.GetByIndex(cache.NamespaceIndex, ee.Namespace) - eeNS, _ := n.namespaceLister.Get(ee.Namespace) + ns, _ := n.namespaceLister.Get(obj.GetNamespace()) for _, group := range appliedToGroups { appGroup := group.(*antreatypes.AppliedToGroup) - if n.eeLabelsMatchGroupSelector(ee, eeNS, &appGroup.Selector) { + if n.labelsMatchGroupSelector(obj, ns, &appGroup.Selector) { matchingKeySet.Insert(appGroup.Name) - klog.V(2).Infof("ExternalEntity %s/%s matched AppliedToGroup %s", ee.Namespace, ee.Name, appGroup.Name) - } - } - return matchingKeySet -} - -// TODO: consider unifying with filterAddressToGroupsForPod -func (n *NetworkPolicyController) filterAddressGroupsForExternalEntity(ee *v1alpha1.ExternalEntity) sets.String { - matchingKeySet := sets.String{} - // AddressGroups that are in this namespace or that are cluster scoped can possibly select this ExternalEntity. - localAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, ee.Namespace) - clusterScopedAddressGroups, _ := n.addressGroupStore.GetByIndex(cache.NamespaceIndex, "") - eeNS, _ := n.namespaceLister.Get(ee.Namespace) - for _, group := range append(localAddressGroups, clusterScopedAddressGroups...) { - addrGroup := group.(*antreatypes.AddressGroup) - if n.eeLabelsMatchGroupSelector(ee, eeNS, &addrGroup.Selector) { - matchingKeySet.Insert(addrGroup.Name) - klog.V(2).Infof("ExternalEntity %s/%s matched AddressGroup %s", ee.Namespace, ee.Name, addrGroup.Name) + klog.V(2).Infof("%s/%s matched AppliedToGroup %s", obj.GetNamespace(), obj.GetName(), appGroup.Name) } } return matchingKeySet @@ -850,9 +782,9 @@ func (n *NetworkPolicyController) addPod(obj interface{}) { pod := obj.(*v1.Pod) klog.V(2).Infof("Processing Pod %s/%s ADD event, labels: %v", pod.Namespace, pod.Name, pod.Labels) // Find all AppliedToGroup keys which match the Pod's labels. - appliedToGroupKeySet := n.filterAppliedToGroupsForPod(pod) + appliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(pod) // Find all AddressGroup keys which match the Pod's labels. - addressGroupKeySet := n.filterAddressGroupsForPod(pod) + addressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(pod) // Enqueue groups to their respective queues for group processing. for group := range appliedToGroupKeySet { n.enqueueAppliedToGroup(group) @@ -878,11 +810,11 @@ func (n *NetworkPolicyController) updatePod(oldObj, curObj interface{}) { return } // Find groups matching the old Pod's labels. - oldAddressGroupKeySet := n.filterAddressGroupsForPod(oldPod) - oldAppliedToGroupKeySet := n.filterAppliedToGroupsForPod(oldPod) + oldAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(oldPod) + oldAppliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(oldPod) // Find groups matching the new Pod's labels. - curAppliedToGroupKeySet := n.filterAppliedToGroupsForPod(curPod) - curAddressGroupKeySet := n.filterAddressGroupsForPod(curPod) + curAppliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(curPod) + curAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(curPod) // Create set to hold the group keys to enqueue. var appliedToGroupKeys sets.String var addressGroupKeys sets.String @@ -932,9 +864,9 @@ func (n *NetworkPolicyController) deletePod(old interface{}) { klog.V(2).Infof("Processing Pod %s/%s DELETE event, labels: %v", pod.Namespace, pod.Name, pod.Labels) // Find all AppliedToGroup keys which match the Pod's labels. - appliedToGroupKeys := n.filterAppliedToGroupsForPod(pod) + appliedToGroupKeys := n.filterAppliedToGroupsForPodOrExternalEntity(pod) // Find all AddressGroup keys which match the Pod's labels. - addressGroupKeys := n.filterAddressGroupsForPod(pod) + addressGroupKeys := n.filterAddressGroupsForPodOrExternalEntity(pod) // Enqueue groups to their respective queues for group processing. for group := range appliedToGroupKeys { n.enqueueAppliedToGroup(group) @@ -951,9 +883,9 @@ func (n *NetworkPolicyController) addExternalEntity(obj interface{}) { ee := obj.(*v1alpha1.ExternalEntity) klog.V(2).Infof("Processing External Entity %s/%s ADD event, labels: %v", ee.Namespace, ee.Name, ee.Labels) // Find all AppliedToGroup keys which match the ExternalEntity's labels. - appliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(ee) + appliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(ee) // Find all AddressGroup keys which match the ExternalEntity's labels. - addressGroupKeySet := n.filterAddressGroupsForExternalEntity(ee) + addressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(ee) // Enqueue groups to their respective queues for group processing. for group := range appliedToGroupKeySet { n.enqueueAppliedToGroup(group) @@ -970,38 +902,39 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ defer n.heartbeat("updateExternalEntity") oldEE := oldObj.(*v1alpha1.ExternalEntity) curEE := curObj.(*v1alpha1.ExternalEntity) - klog.V(2).Infof("Processing Pod %s/%s UPDATE event, labels: %v", curEE.Namespace, curEE.Name, curEE.Labels) + klog.V(2).Infof("Processing ExternalEntity %s/%s UPDATE event, labels: %v", curEE.Namespace, curEE.Name, curEE.Labels) // No need to trigger processing of groups if there is no change in the // Pod labels or Pods Node or Pods IP. labelsEqual := labels.Equals(labels.Set(oldEE.Labels), labels.Set(curEE.Labels)) - // TODO: Add util function to detect endpoint updates - if labelsEqual && oldEE.Spec.ExternalNode == curEE.Spec.ExternalNode { - klog.V(4).Infof("No change in Pod %s/%s. Skipping NetworkPolicy evaluation.", curEE.Namespace, curEE.Name) + // TODO: Right now two ExternalEntities are only considered equal if the list of Endpoints and + // all NamedPorts in each Endpoint are of the exact order. This constraint might be too strict. + if labelsEqual && cmp.Equal(oldEE.Spec, curEE.Spec) { + klog.V(4).Infof("No change in ExternalEntity %s/%s. Skipping NetworkPolicy evaluation.", curEE.Namespace, curEE.Name) return } - // Find groups matching the old Pod's labels. - oldAddressGroupKeySet := n.filterAddressGroupsForExternalEntity(oldEE) - oldAppliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(oldEE) - // Find groups matching the new Pod's labels. - curAppliedToGroupKeySet := n.filterAppliedToGroupsForExternalEntity(curEE) - curAddressGroupKeySet := n.filterAddressGroupsForExternalEntity(curEE) + // Find groups matching the old ExternalEntity's labels. + oldAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(oldEE) + oldAppliedToGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(oldEE) + // Find groups matching the new ExternalEntity's labels. + curAppliedToGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(curEE) + curAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(curEE) // Create set to hold the group keys to enqueue. var appliedToGroupKeys sets.String var addressGroupKeys sets.String - // AppliedToGroup keys must be enqueued only if the Pod's Node or IP has changed or - // if Pod's label change causes it to match new Groups. - // TODO: Add util function to detect endpoint updates - if oldEE.Spec.ExternalNode != curEE.Spec.ExternalNode { + // AppliedToGroup keys must be enqueued only if the ExternalEntity's spec has changed or + // if ExternalEntity's label change causes it to match new Groups. + if !cmp.Equal(oldEE.Spec, curEE.Spec) { appliedToGroupKeys = oldAppliedToGroupKeySet.Union(curAppliedToGroupKeySet) } else if !labelsEqual { // No need to enqueue common AppliedToGroups as they already have latest Pod // information. appliedToGroupKeys = oldAppliedToGroupKeySet.Difference(curAppliedToGroupKeySet).Union(curAppliedToGroupKeySet.Difference(oldAppliedToGroupKeySet)) } - // AddressGroup keys must be enqueued only if the Pod's IP has changed or - // if Pod's label change causes it to match new Groups. - // TODO: Add util function to detect endpoint updates - if !labelsEqual { + // AddressGroup keys must be enqueued only if the ExternalEntity's spec has changed or + // if ExternalEntity's label change causes it to match new Groups. + if !cmp.Equal(oldEE.Spec, curEE.Spec) { + addressGroupKeys = oldAddressGroupKeySet.Union(curAddressGroupKeySet) + } else if !labelsEqual { // No need to enqueue common AddressGroups as they already have latest Pod // information. addressGroupKeys = oldAddressGroupKeySet.Difference(curAddressGroupKeySet).Union(curAddressGroupKeySet.Difference(oldAddressGroupKeySet)) @@ -1034,9 +967,9 @@ func (n *NetworkPolicyController) deleteExternalEntity(old interface{}) { klog.V(2).Infof("Processing ExternalEntity %s/%s DELETE event, labels: %v", ee.Namespace, ee.Name, ee.Labels) // Find all AppliedToGroup keys which match the Pod's labels. - appliedToGroupKeys := n.filterAppliedToGroupsForExternalEntity(ee) + appliedToGroupKeys := n.filterAddressGroupsForPodOrExternalEntity(ee) // Find all AddressGroup keys which match the Pod's labels. - addressGroupKeys := n.filterAddressGroupsForExternalEntity(ee) + addressGroupKeys := n.filterAddressGroupsForPodOrExternalEntity(ee) // Enqueue groups to their respective queues for group processing. for group := range appliedToGroupKeys { n.enqueueAppliedToGroup(group) diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index 8589fdfb898..9af29e0d37b 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -30,12 +30,14 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/rand" + "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" k8stesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" "github.com/vmware-tanzu/antrea/pkg/apis/controlplane" + "github.com/vmware-tanzu/antrea/pkg/apis/core/v1alpha1" "github.com/vmware-tanzu/antrea/pkg/apiserver/storage" fakeversioned "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned/fake" crdinformers "github.com/vmware-tanzu/antrea/pkg/client/informers/externalversions" @@ -1453,6 +1455,110 @@ func TestDeleteNamespace(t *testing.T) { } } +func TestFilterAddressGroupsForPodOrExternalEntity(t *testing.T) { + selectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"purpose": "test-select"}, + } + eeSelectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"platform": "aws"}, + } + ns1 := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ns1", + Labels: map[string]string{"purpose": "test-select"}, + }, + } + ns2 := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ns2", + }, + } + addrGrp1 := &antreatypes.AddressGroup{ + UID: "uid1", + Name: "AddrGrp1", + Selector: *toGroupSelector("ns1", &selectorSpec, nil, nil), + } + addrGrp2 := &antreatypes.AddressGroup{ + UID: "uid2", + Name: "AddrGrp2", + Selector: *toGroupSelector("ns1", nil, nil, &eeSelectorSpec), + } + addrGrp3 := &antreatypes.AddressGroup{ + UID: "uid3", + Name: "AddrGrp3", + Selector: *toGroupSelector("", nil, &selectorSpec, nil), + } + addrGrp4 := &antreatypes.AddressGroup{ + UID: "uid4", + Name: "AddrGrp4", + Selector: *toGroupSelector("", &selectorSpec, &selectorSpec, nil), + } + + pod1 := getPod("pod1", "ns1", "node1", "1.1.1.1", false) + pod1.Labels = map[string]string{"purpose": "test-select"} + pod2 := getPod("pod2", "ns1", "node1", "1.1.1.2", false) + pod3 := getPod("pod3", "ns2", "node1", "1.1.1.3", false) + ee1 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ee1", + Namespace: "ns1", + Labels: map[string]string{"platform": "aws"}, + }, + } + ee2 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ee2", + Namespace: "ns1", + Labels: map[string]string{"platform": "gke"}, + }, + } + tests := []struct { + name string + toMatch metav1.Object + expectedGroups sets.String + }{ + { + "pod-match-selector-match-ns", + pod1, + sets.NewString("AddrGrp1", "AddrGrp3", "AddrGrp4"), + }, + { + "pod-unmatch-selector-match-ns", + pod2, + sets.NewString("AddrGrp3"), + }, + { + "pod-unmatch-selector-unmatch-ns", + pod3, + sets.String{}, + }, + { + "externalEntity-match-selector-match-ns", + ee1, + sets.NewString("AddrGrp2", "AddrGrp3"), + }, + { + "externalEntity-unmatch-selector-match-ns", + ee2, + sets.NewString("AddrGrp3"), + }, + } + _, npc := newController() + npc.addressGroupStore.Create(addrGrp1) + npc.addressGroupStore.Create(addrGrp2) + npc.addressGroupStore.Create(addrGrp3) + npc.addressGroupStore.Create(addrGrp4) + npc.namespaceStore.Add(ns1) + npc.namespaceStore.Add(ns2) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expectedGroups, npc.filterAddressGroupsForPodOrExternalEntity(tt.toMatch), + "Filtered AddressGroup does not match expectation") + }) + } +} + func TestToGroupSelector(t *testing.T) { pSelector := metav1.LabelSelector{} pLabelSelector, _ := metav1.LabelSelectorAsSelector(&pSelector) diff --git a/pkg/controller/networkpolicy/store/addressgroup_test.go b/pkg/controller/networkpolicy/store/addressgroup_test.go index f3b0daa9ba4..084016f30dd 100644 --- a/pkg/controller/networkpolicy/store/addressgroup_test.go +++ b/pkg/controller/networkpolicy/store/addressgroup_test.go @@ -31,10 +31,18 @@ import ( "github.com/vmware-tanzu/antrea/pkg/controller/types" ) -func newAddressGroupMember(ip string) *controlplane.GroupMemberPod { +func newAddressGroupMemberPod(ip string) *controlplane.GroupMemberPod { return &controlplane.GroupMemberPod{IP: controlplane.IPAddress(net.ParseIP(ip))} } +func newAddressGroupMemberExternalEntity(ip string) *controlplane.GroupMember { + return &controlplane.GroupMember{ + Endpoints: []controlplane.Endpoint{ + {IP: controlplane.IPAddress(net.ParseIP(ip))}, + }, + } +} + func TestWatchAddressGroupEvent(t *testing.T) { testCases := map[string]struct { fieldSelector fields.Selector @@ -48,26 +56,31 @@ func TestWatchAddressGroupEvent(t *testing.T) { fieldSelector: fields.Everything(), operations: func(store storage.Interface) { store.Create(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("2.2.2.2")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("6.6.6.6")), }) store.Update(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("3.3.3.3")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("3.3.3.3")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("7.7.7.7")), }) }, expected: []watch.Event{ {Type: watch.Bookmark, Object: nil}, {Type: watch.Added, Object: &controlplane.AddressGroup{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Pods: []controlplane.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + Pods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")}, + GroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("5.5.5.5"), *newAddressGroupMemberExternalEntity("6.6.6.6")}, }}, {Type: watch.Modified, Object: &controlplane.AddressGroupPatch{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - AddedPods: []controlplane.GroupMemberPod{*newAddressGroupMember("3.3.3.3")}, - RemovedPods: []controlplane.GroupMemberPod{*newAddressGroupMember("2.2.2.2")}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + AddedPods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("3.3.3.3")}, + RemovedPods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("2.2.2.2")}, + AddedGroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("7.7.7.7")}, + RemovedGroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("6.6.6.6")}, }}, }, }, @@ -77,39 +90,46 @@ func TestWatchAddressGroupEvent(t *testing.T) { operations: func(store storage.Interface) { // This should not be seen as it doesn't span node3. store.Create(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("2.2.2.2")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("6.6.6.6")), }) // This should be seen as an added event as it makes foo span node3 for the first time. store.Update(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("2.2.2.2")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("2.2.2.2")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("6.6.6.6")), }) // This should be seen as a modified event as it updates addressGroups of node3. store.Update(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("3.3.3.3")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("3.3.3.3")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("7.7.7.7")), }) // This should be seen as a deleted event as it makes foo not span node3 any more. store.Update(&types.AddressGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1")}, - Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMember("1.1.1.1"), newAddressGroupMember("3.3.3.3")), + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1")}, + Pods: controlplane.NewGroupMemberPodSet(newAddressGroupMemberPod("1.1.1.1"), newAddressGroupMemberPod("3.3.3.3")), + GroupMembers: controlplane.NewGroupMemberSet(newAddressGroupMemberExternalEntity("5.5.5.5"), newAddressGroupMemberExternalEntity("6.6.6.6")), }) }, expected: []watch.Event{ {Type: watch.Bookmark, Object: nil}, {Type: watch.Added, Object: &controlplane.AddressGroup{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Pods: []controlplane.GroupMemberPod{*newAddressGroupMember("1.1.1.1"), *newAddressGroupMember("2.2.2.2")}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + Pods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("1.1.1.1"), *newAddressGroupMemberPod("2.2.2.2")}, + GroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("5.5.5.5"), *newAddressGroupMemberExternalEntity("6.6.6.6")}, }}, {Type: watch.Modified, Object: &controlplane.AddressGroupPatch{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - AddedPods: []controlplane.GroupMemberPod{*newAddressGroupMember("3.3.3.3")}, - RemovedPods: []controlplane.GroupMemberPod{*newAddressGroupMember("2.2.2.2")}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + AddedPods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("3.3.3.3")}, + RemovedPods: []controlplane.GroupMemberPod{*newAddressGroupMemberPod("2.2.2.2")}, + AddedGroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("7.7.7.7")}, + RemovedGroupMembers: []controlplane.GroupMember{*newAddressGroupMemberExternalEntity("6.6.6.6")}, }}, {Type: watch.Deleted, Object: &controlplane.AddressGroup{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, diff --git a/pkg/controller/networkpolicy/store/appliedtogroup_test.go b/pkg/controller/networkpolicy/store/appliedtogroup_test.go index 27ddb7e9348..ce816cafec3 100644 --- a/pkg/controller/networkpolicy/store/appliedtogroup_test.go +++ b/pkg/controller/networkpolicy/store/appliedtogroup_test.go @@ -30,15 +30,23 @@ import ( "github.com/vmware-tanzu/antrea/pkg/controller/types" ) -func newAppliedToGroupMember(name, namespace string) *controlplane.GroupMemberPod { +func newAppliedToGroupPodMember(name, namespace string) *controlplane.GroupMemberPod { return &controlplane.GroupMemberPod{Pod: &controlplane.PodReference{Name: name, Namespace: namespace}} } +func newAppliedToGroupMemberExternalEntity(name, namespace string) *controlplane.GroupMember { + return &controlplane.GroupMember{ExternalEntity: &controlplane.ExternalEntityReference{Name: name, Namespace: namespace}} +} + func TestWatchAppliedToGroupEvent(t *testing.T) { - pod1 := newAppliedToGroupMember("pod1", "default") - pod2 := newAppliedToGroupMember("pod2", "default") - pod3 := newAppliedToGroupMember("pod3", "default") - pod4 := newAppliedToGroupMember("pod4", "default") + pod1 := newAppliedToGroupPodMember("pod1", "default") + pod2 := newAppliedToGroupPodMember("pod2", "default") + pod3 := newAppliedToGroupPodMember("pod3", "default") + pod4 := newAppliedToGroupPodMember("pod4", "default") + ee1 := newAppliedToGroupMemberExternalEntity("ee1", "default") + ee2 := newAppliedToGroupMemberExternalEntity("ee2", "default") + ee3 := newAppliedToGroupMemberExternalEntity("ee3", "default") + ee4 := newAppliedToGroupMemberExternalEntity("ee4", "default") testCases := map[string]struct { fieldSelector fields.Selector @@ -61,6 +69,16 @@ func TestWatchAppliedToGroupEvent(t *testing.T) { SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node2": controlplane.NewGroupMemberPodSet(pod3)}, }) + store.Create(&types.AppliedToGroup{ + Name: "bar", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1), "node2": controlplane.NewGroupMemberSet(ee2)}, + }) + store.Update(&types.AppliedToGroup{ + Name: "bar", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1), "node2": controlplane.NewGroupMemberSet(ee3)}, + }) }, expected: []watch.Event{ {Type: watch.Bookmark, Object: nil}, @@ -73,6 +91,15 @@ func TestWatchAppliedToGroupEvent(t *testing.T) { AddedPods: []controlplane.GroupMemberPod{*pod3}, RemovedPods: []controlplane.GroupMemberPod{*pod2}, }}, + {Type: watch.Added, Object: &controlplane.AppliedToGroup{ + ObjectMeta: metav1.ObjectMeta{Name: "bar"}, + GroupMembers: []controlplane.GroupMember{*ee1, *ee2}, + }}, + {Type: watch.Modified, Object: &controlplane.AppliedToGroupPatch{ + ObjectMeta: metav1.ObjectMeta{Name: "bar"}, + AddedGroupMembers: []controlplane.GroupMember{*ee3}, + RemovedGroupMembers: []controlplane.GroupMember{*ee2}, + }}, }, }, "node-scoped-watcher": { @@ -81,45 +108,53 @@ func TestWatchAppliedToGroupEvent(t *testing.T) { operations: func(store storage.Interface) { // This should not be seen as it doesn't span node3. store.Create(&types.AppliedToGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, - PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node2": controlplane.NewGroupMemberPodSet(pod2)}, + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, + PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node2": controlplane.NewGroupMemberPodSet(pod2)}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1), "node2": controlplane.NewGroupMemberSet(ee2)}, }) // This should be seen as an added event as it makes foo span node3 for the first time. store.Update(&types.AppliedToGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, - PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node3": controlplane.NewGroupMemberPodSet(pod3)}, + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, + PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node3": controlplane.NewGroupMemberPodSet(pod3)}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1), "node2": controlplane.NewGroupMemberSet(ee3)}, }) // This should be seen as a modified event as it updates appliedToGroups of node3. store.Update(&types.AppliedToGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, - PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node3": controlplane.NewGroupMemberPodSet(pod4)}, + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, + PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1), "node3": controlplane.NewGroupMemberPodSet(pod4)}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1), "node3": controlplane.NewGroupMemberSet(ee4)}, }) // This should not be seen as a modified event as the change doesn't span node3. store.Update(&types.AppliedToGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node3")}, - PodsByNode: map[string]controlplane.GroupMemberPodSet{"node3": controlplane.NewGroupMemberPodSet(pod4)}, + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node3")}, + PodsByNode: map[string]controlplane.GroupMemberPodSet{"node3": controlplane.NewGroupMemberPodSet(pod4)}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node3": controlplane.NewGroupMemberSet(ee4)}, }) // This should be seen as a deleted event as it makes foo not span node3 any more. store.Update(&types.AppliedToGroup{ - Name: "foo", - SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1")}, - PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1)}, + Name: "foo", + SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1")}, + PodsByNode: map[string]controlplane.GroupMemberPodSet{"node1": controlplane.NewGroupMemberPodSet(pod1)}, + GroupMemberByNode: map[string]controlplane.GroupMemberSet{"node1": controlplane.NewGroupMemberSet(ee1)}, }) }, expected: []watch.Event{ {Type: watch.Bookmark, Object: nil}, {Type: watch.Added, Object: &controlplane.AppliedToGroup{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Pods: []controlplane.GroupMemberPod{*pod3}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + Pods: []controlplane.GroupMemberPod{*pod3}, + GroupMembers: []controlplane.GroupMember{*ee3}, }}, {Type: watch.Modified, Object: &controlplane.AppliedToGroupPatch{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - AddedPods: []controlplane.GroupMemberPod{*pod4}, - RemovedPods: []controlplane.GroupMemberPod{*pod3}, + ObjectMeta: metav1.ObjectMeta{Name: "foo"}, + AddedPods: []controlplane.GroupMemberPod{*pod4}, + RemovedPods: []controlplane.GroupMemberPod{*pod3}, + AddedGroupMembers: []controlplane.GroupMember{*ee4}, + RemovedGroupMembers: []controlplane.GroupMember{*ee3}, }}, {Type: watch.Deleted, Object: &controlplane.AppliedToGroup{ ObjectMeta: metav1.ObjectMeta{Name: "foo"}, From 575371604705947042fe36cb527849507ed226d4 Mon Sep 17 00:00:00 2001 From: Yang Ding Date: Fri, 28 Aug 2020 14:17:24 -0700 Subject: [PATCH 4/6] Improve UT coverage --- pkg/apis/controlplane/v1beta1/generated.pb.go | 168 ++--- .../v1beta1/zz_generated.conversion.go | 2 +- .../v1beta1/zz_generated.conversion.go | 695 ------------------ .../networkpolicy/antreanetworkpolicy_test.go | 138 +++- .../networkpolicy/networkpolicy_controller.go | 16 +- .../networkpolicy_controller_test.go | 246 ++++++- 6 files changed, 457 insertions(+), 808 deletions(-) delete mode 100644 pkg/apis/networking/v1beta1/zz_generated.conversion.go diff --git a/pkg/apis/controlplane/v1beta1/generated.pb.go b/pkg/apis/controlplane/v1beta1/generated.pb.go index 6b939097181..5497e6979a5 100644 --- a/pkg/apis/controlplane/v1beta1/generated.pb.go +++ b/pkg/apis/controlplane/v1beta1/generated.pb.go @@ -603,92 +603,92 @@ func init() { } var fileDescriptor_345cd0a9074e5729 = []byte{ - // 1357 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x58, 0x4d, 0x6f, 0x1b, 0xc5, - 0x1b, 0xcf, 0xae, 0xed, 0x24, 0x9e, 0x38, 0x69, 0x33, 0xf9, 0x4b, 0x7f, 0x53, 0x90, 0x1d, 0x2d, + // 1359 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x58, 0xcf, 0x6f, 0x1b, 0xc5, + 0x17, 0xcf, 0xae, 0xed, 0x24, 0x9e, 0x38, 0x69, 0x33, 0xf9, 0x4a, 0x5f, 0x53, 0x90, 0x1d, 0x2d, 0x97, 0x1c, 0xe8, 0x2e, 0x29, 0x15, 0xf4, 0x50, 0x0e, 0x71, 0x93, 0x56, 0x86, 0x34, 0x5d, 0x4d, 0xcb, 0x05, 0x21, 0xc1, 0x64, 0x77, 0xe2, 0x6c, 0xbd, 0xbb, 0xb3, 0x9d, 0x1d, 0xbb, 0x2d, 0x12, - 0x12, 0x88, 0x13, 0x5c, 0x78, 0x39, 0x20, 0x2e, 0x7c, 0x01, 0xc4, 0x87, 0x80, 0x5b, 0x8f, 0x3d, - 0xf6, 0x82, 0x45, 0x5c, 0x81, 0xf8, 0x0c, 0x39, 0xa1, 0x99, 0x9d, 0xf5, 0xee, 0xda, 0x44, 0x8d, - 0xe4, 0x38, 0xe2, 0xd0, 0x53, 0x32, 0x33, 0xcf, 0x3c, 0xbf, 0xe7, 0xf5, 0x37, 0xcf, 0x1a, 0xec, - 0x76, 0x3c, 0x7e, 0xd8, 0xdb, 0x37, 0x1d, 0x1a, 0x58, 0xfd, 0xe0, 0x21, 0x66, 0xe4, 0x32, 0xc7, - 0xe1, 0xa7, 0x3d, 0x0b, 0x87, 0x9c, 0x11, 0x6c, 0x45, 0xdd, 0x8e, 0x85, 0x23, 0x2f, 0xb6, 0x1c, - 0x1a, 0x72, 0x46, 0xfd, 0xc8, 0xc7, 0x21, 0xb1, 0xfa, 0x9b, 0xfb, 0x84, 0xe3, 0x4d, 0xab, 0x43, - 0x42, 0xc2, 0x30, 0x27, 0xae, 0x19, 0x31, 0xca, 0x29, 0xbc, 0x9e, 0x69, 0x33, 0x13, 0x6d, 0x1f, - 0x4b, 0x6d, 0x66, 0xa2, 0xcd, 0x8c, 0xba, 0x1d, 0x53, 0x68, 0x33, 0xf3, 0xda, 0x4c, 0xa5, 0xed, - 0xd2, 0xe5, 0x9c, 0x2d, 0x1d, 0xda, 0xa1, 0x96, 0x54, 0xba, 0xdf, 0x3b, 0x90, 0x2b, 0xb9, 0x90, - 0xff, 0x25, 0x60, 0x97, 0xae, 0x76, 0xaf, 0xc5, 0xa6, 0x47, 0x85, 0x79, 0x01, 0x76, 0x0e, 0xbd, - 0x90, 0xb0, 0xc7, 0x99, 0xbd, 0x01, 0xe1, 0xd8, 0xea, 0x4f, 0x98, 0x78, 0xc9, 0x3a, 0xe9, 0x16, - 0xeb, 0x85, 0xdc, 0x0b, 0xc8, 0xc4, 0x85, 0xb7, 0x5f, 0x74, 0x21, 0x76, 0x0e, 0x49, 0x80, 0x27, - 0xee, 0xbd, 0x75, 0xd2, 0xbd, 0x1e, 0xf7, 0x7c, 0xcb, 0x0b, 0x79, 0xcc, 0xd9, 0xf8, 0x25, 0xe3, - 0x2f, 0x1d, 0xd4, 0xb6, 0x5c, 0x97, 0x91, 0x38, 0xbe, 0xc5, 0x68, 0x2f, 0x82, 0x9f, 0x80, 0x45, - 0xe1, 0x89, 0x8b, 0x39, 0xae, 0x6b, 0xeb, 0xda, 0xc6, 0xd2, 0x95, 0x37, 0xcd, 0x44, 0xb1, 0x99, - 0x57, 0x9c, 0x45, 0x56, 0x48, 0x9b, 0xfd, 0x4d, 0xf3, 0xce, 0xfe, 0x7d, 0xe2, 0xf0, 0xdb, 0x84, - 0xe3, 0x16, 0x7c, 0x32, 0x68, 0xce, 0x0d, 0x07, 0x4d, 0x90, 0xed, 0xa1, 0x91, 0x56, 0x18, 0x82, - 0x72, 0x44, 0xdd, 0xb8, 0xae, 0xaf, 0x97, 0x36, 0x96, 0xae, 0xec, 0x9a, 0xd3, 0xa4, 0xd0, 0x94, - 0x46, 0xdf, 0x26, 0xc1, 0x3e, 0x61, 0x36, 0x75, 0x5b, 0x35, 0x85, 0x5c, 0xb6, 0xa9, 0x1b, 0x23, - 0x89, 0x03, 0xbf, 0xd4, 0x40, 0xad, 0x93, 0x89, 0xc5, 0xf5, 0x92, 0x04, 0x6e, 0x9f, 0x19, 0x70, - 0xeb, 0x7f, 0x0a, 0xb5, 0x96, 0xdb, 0x8c, 0x51, 0x01, 0xd4, 0x38, 0xd2, 0xc0, 0xc5, 0x7c, 0xa0, - 0x77, 0xbd, 0x98, 0xc3, 0x8f, 0x26, 0x82, 0x6d, 0x9e, 0x2e, 0xd8, 0xe2, 0xb6, 0x0c, 0xf5, 0x45, - 0x05, 0xbd, 0x98, 0xee, 0xe4, 0x02, 0x4d, 0x41, 0xc5, 0xe3, 0x24, 0x48, 0x23, 0xfd, 0xde, 0x74, - 0x0e, 0xe7, 0x8d, 0x6f, 0x2d, 0x2b, 0xd8, 0x4a, 0x5b, 0x00, 0xa0, 0x04, 0xc7, 0xf8, 0xb9, 0x02, - 0x56, 0xf3, 0x62, 0x36, 0xe6, 0xce, 0xe1, 0x39, 0x54, 0xd4, 0x67, 0xa0, 0x8a, 0x5d, 0x97, 0xb8, - 0xf6, 0xac, 0xca, 0x6a, 0x55, 0xc1, 0x57, 0xb7, 0x52, 0x18, 0x94, 0x21, 0x8a, 0x02, 0x5b, 0x62, - 0x24, 0xa0, 0x7d, 0x65, 0x41, 0x69, 0x06, 0x16, 0xac, 0x29, 0x0b, 0x96, 0x50, 0x06, 0x84, 0xf2, - 0xa8, 0xf0, 0x7b, 0x0d, 0xac, 0x4a, 0x9b, 0xf2, 0x45, 0x58, 0x2f, 0x9f, 0x75, 0xad, 0xbf, 0xa2, - 0x0c, 0x59, 0xdd, 0x1a, 0xc7, 0x42, 0x93, 0xf0, 0xf0, 0x47, 0x0d, 0xac, 0x29, 0x23, 0x0b, 0x66, - 0x55, 0xce, 0xda, 0xac, 0x57, 0x95, 0x59, 0x6b, 0x68, 0x12, 0x0d, 0xfd, 0x9b, 0x09, 0xc6, 0xdf, - 0x3a, 0x58, 0xd9, 0x8a, 0x22, 0xdf, 0x23, 0xee, 0x3d, 0xfa, 0x92, 0xfb, 0x66, 0xc9, 0x7d, 0x7f, - 0x6a, 0x00, 0x16, 0x43, 0x7d, 0x0e, 0xec, 0xf7, 0xa0, 0xc8, 0x7e, 0x53, 0xc6, 0xba, 0x68, 0xfe, - 0x09, 0xfc, 0xf7, 0x4b, 0x05, 0xac, 0x15, 0x05, 0x5f, 0x32, 0xe0, 0x4b, 0x06, 0xfc, 0xcf, 0x32, - 0xe0, 0x4f, 0x1a, 0x58, 0xdc, 0x09, 0xdd, 0x88, 0x7a, 0x21, 0x87, 0xaf, 0x03, 0xdd, 0x8b, 0x64, - 0x75, 0xd6, 0x5a, 0x6b, 0xc3, 0x41, 0x53, 0x6f, 0xdb, 0xc7, 0x83, 0x66, 0xb5, 0x6d, 0xab, 0x07, - 0x1d, 0xe9, 0x5e, 0x04, 0x7d, 0x50, 0x89, 0x28, 0xe3, 0x69, 0x89, 0xdd, 0x9a, 0xce, 0xfa, 0x3d, - 0x1c, 0x88, 0xcc, 0x31, 0x9e, 0xb5, 0x93, 0x58, 0xc5, 0x28, 0x01, 0x31, 0x7c, 0xf0, 0xff, 0x9d, - 0x47, 0x9c, 0xb0, 0x10, 0xfb, 0x3b, 0x21, 0xf7, 0xf8, 0x63, 0x44, 0x0e, 0x08, 0x23, 0xa1, 0x43, - 0xe0, 0x3a, 0x28, 0x87, 0x38, 0x20, 0xd2, 0xde, 0x6a, 0xc6, 0x7c, 0x42, 0x23, 0x92, 0x27, 0xd0, - 0x02, 0x55, 0xf1, 0x37, 0x8e, 0xb0, 0x43, 0xea, 0xba, 0x14, 0x1b, 0xd5, 0xf0, 0x5e, 0x7a, 0x80, - 0x32, 0x19, 0xe3, 0x8b, 0x12, 0x58, 0xca, 0x85, 0x07, 0x7e, 0xa7, 0x81, 0x15, 0x52, 0x80, 0x57, - 0xbd, 0xfb, 0xc1, 0x74, 0x5e, 0x9f, 0xe0, 0x52, 0x0b, 0x0e, 0x07, 0xcd, 0x95, 0xb1, 0xc3, 0x31, - 0x03, 0x20, 0x01, 0xa5, 0x88, 0xba, 0xd2, 0x9d, 0xa9, 0xe7, 0x39, 0x9b, 0xba, 0x19, 0xf8, 0xc2, - 0x70, 0xd0, 0x2c, 0x89, 0x1d, 0xa1, 0x1f, 0x3e, 0x04, 0x55, 0xa2, 0xea, 0x22, 0xed, 0xe5, 0x9b, - 0x53, 0x3a, 0xad, 0xd4, 0x65, 0x39, 0x48, 0x77, 0x62, 0x94, 0x61, 0x19, 0x5f, 0xeb, 0x60, 0xa5, - 0xd8, 0xf6, 0xa9, 0xcb, 0xda, 0x8c, 0x5d, 0x4e, 0xca, 0x5f, 0x3f, 0x65, 0xf9, 0x97, 0xce, 0xa3, - 0xfc, 0x7f, 0xd7, 0xc0, 0x42, 0xdb, 0x6e, 0xf9, 0xd4, 0xe9, 0x42, 0x02, 0xca, 0x8e, 0xe7, 0x32, - 0x15, 0x86, 0x1b, 0xd3, 0x01, 0xb7, 0xed, 0x3d, 0xc2, 0xb3, 0xa6, 0xb9, 0xd1, 0xde, 0x46, 0x48, - 0xaa, 0x87, 0x5d, 0x30, 0x4f, 0x1e, 0x39, 0x24, 0xe2, 0xaa, 0xc1, 0xcf, 0x04, 0x68, 0x45, 0x01, - 0xcd, 0xef, 0x48, 0xd5, 0x48, 0x41, 0x18, 0x07, 0xa0, 0x22, 0x05, 0x4e, 0x47, 0x3d, 0xd7, 0x40, - 0x2d, 0x62, 0xe4, 0xc0, 0x7b, 0xb4, 0x4b, 0xc2, 0x0e, 0x3f, 0x94, 0xa9, 0xaa, 0x64, 0xd3, 0x87, - 0x9d, 0x3b, 0x43, 0x05, 0x49, 0xe3, 0x2b, 0x0d, 0x54, 0x47, 0xb1, 0x16, 0xcc, 0x21, 0xc2, 0x2b, - 0xe1, 0x2a, 0xf9, 0x99, 0x89, 0x71, 0x24, 0x4f, 0x46, 0xdc, 0xa2, 0x9f, 0xc8, 0x2d, 0xd7, 0xc0, - 0xa2, 0xfc, 0x7a, 0x76, 0xa8, 0x5f, 0x2f, 0x49, 0xa9, 0xd7, 0xd2, 0x41, 0xc4, 0x56, 0xfb, 0xc7, - 0xb9, 0xff, 0xd1, 0x48, 0xda, 0xf8, 0xa1, 0x04, 0x96, 0xf7, 0x08, 0x7f, 0x48, 0x59, 0xd7, 0xa6, - 0xbe, 0xe7, 0x3c, 0x3e, 0x87, 0xd9, 0x80, 0x83, 0x0a, 0xeb, 0xf9, 0x24, 0x25, 0xed, 0x3b, 0x53, - 0x56, 0x6d, 0xde, 0x7a, 0xd4, 0xf3, 0x49, 0x56, 0xbd, 0x62, 0x15, 0xa3, 0x04, 0x0c, 0xbe, 0x0b, - 0x2e, 0xe0, 0xc2, 0x28, 0x94, 0x74, 0x4d, 0x55, 0x66, 0xf8, 0x42, 0x71, 0x4a, 0x8a, 0xd1, 0xb8, - 0x2c, 0xdc, 0x10, 0x21, 0xf6, 0x28, 0x13, 0xb4, 0x5b, 0x5e, 0xd7, 0x36, 0xb4, 0x56, 0x2d, 0x09, - 0x6f, 0xb2, 0x87, 0x46, 0xa7, 0x70, 0x1b, 0xd4, 0xb8, 0x47, 0x58, 0x7a, 0x52, 0xaf, 0xac, 0x6b, - 0x1b, 0xcb, 0xad, 0x75, 0x51, 0x14, 0xf7, 0x72, 0xfb, 0xc7, 0x63, 0x6b, 0x54, 0xb8, 0x65, 0x3c, - 0xd7, 0xc0, 0x6a, 0xc1, 0xb5, 0x73, 0x98, 0x50, 0xa3, 0xe2, 0x84, 0xfa, 0xfe, 0x19, 0x26, 0xe6, - 0x84, 0x01, 0xf5, 0xb7, 0x71, 0x2f, 0x6d, 0x42, 0x18, 0x7c, 0x07, 0x2c, 0xe3, 0xdc, 0x57, 0x7b, - 0x5c, 0xd7, 0x64, 0xa2, 0x56, 0x87, 0x83, 0xe6, 0x72, 0xfe, 0x73, 0x3e, 0x46, 0x45, 0x39, 0x18, - 0x83, 0x45, 0x2f, 0x92, 0x04, 0x95, 0xfa, 0xb0, 0x33, 0x2d, 0x61, 0x48, 0x6d, 0x59, 0xd4, 0xd4, - 0x46, 0x8c, 0x46, 0x40, 0xc6, 0xaf, 0xe5, 0x31, 0x1f, 0x44, 0xd9, 0xc1, 0xeb, 0xa0, 0xea, 0x7a, - 0x8c, 0x38, 0xdc, 0xa3, 0xa1, 0x9a, 0x0a, 0x1a, 0xe9, 0x53, 0xb3, 0x9d, 0x1e, 0x1c, 0xe7, 0x17, - 0x28, 0xbb, 0x00, 0x1f, 0x80, 0xf2, 0x01, 0xa3, 0x81, 0x7a, 0x58, 0xcf, 0xb2, 0x43, 0x44, 0x80, - 0x33, 0x0e, 0xb9, 0xc9, 0x68, 0x80, 0x24, 0x14, 0xec, 0x02, 0x9d, 0x53, 0xc9, 0x1e, 0x33, 0x00, - 0x04, 0x0a, 0x50, 0xbf, 0x47, 0x91, 0xce, 0xa9, 0x48, 0x54, 0x4c, 0x58, 0xdf, 0x73, 0x48, 0x3a, - 0x0f, 0x4f, 0x99, 0xa8, 0xbb, 0x89, 0xb6, 0x2c, 0x51, 0x6a, 0x23, 0x46, 0x23, 0x20, 0xf8, 0x46, - 0xae, 0x85, 0x2b, 0x92, 0x6d, 0x2f, 0x66, 0x2c, 0x39, 0xd1, 0xc6, 0xf7, 0xc1, 0x3c, 0x4e, 0xb2, - 0x37, 0x2f, 0xb3, 0x87, 0xc4, 0x8b, 0xb1, 0x95, 0xa6, 0x6d, 0xfb, 0xb4, 0xbf, 0x1a, 0xc7, 0xc4, - 0xe9, 0x09, 0x7d, 0x56, 0x7f, 0x13, 0xfb, 0xd1, 0x21, 0xde, 0x34, 0x45, 0x79, 0x24, 0x7a, 0x90, - 0x42, 0x30, 0x30, 0xa8, 0xe5, 0x47, 0x81, 0x59, 0x4c, 0x93, 0xdf, 0x68, 0x60, 0x41, 0xc5, 0x04, - 0x5e, 0xcd, 0x3d, 0x17, 0x09, 0x44, 0xfd, 0xc5, 0x4f, 0x05, 0xdc, 0x53, 0x0f, 0x95, 0xfe, 0x82, - 0x47, 0xa1, 0xc7, 0x3d, 0xdf, 0x4c, 0x7e, 0xdd, 0x35, 0xdb, 0x21, 0xbf, 0xc3, 0xee, 0x72, 0xe6, - 0x85, 0x9d, 0xd6, 0x62, 0xf1, 0x59, 0x6b, 0x5d, 0x7e, 0x72, 0xd4, 0x98, 0x7b, 0x7a, 0xd4, 0x98, - 0x7b, 0x76, 0xd4, 0x98, 0xfb, 0x7c, 0xd8, 0xd0, 0x9e, 0x0c, 0x1b, 0xda, 0xd3, 0x61, 0x43, 0x7b, - 0x36, 0x6c, 0x68, 0x7f, 0x0c, 0x1b, 0xda, 0xb7, 0xcf, 0x1b, 0x73, 0x1f, 0x2e, 0xa8, 0x0c, 0xff, - 0x13, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x8c, 0x09, 0xb4, 0xa8, 0x17, 0x00, 0x00, + 0x12, 0x88, 0x13, 0x5c, 0xf8, 0x71, 0x40, 0x5c, 0xf8, 0x07, 0x10, 0x7f, 0x04, 0xdc, 0x7a, 0xec, + 0xb1, 0x17, 0x2c, 0xe2, 0x0a, 0xc4, 0xdf, 0x90, 0x13, 0x9a, 0xd9, 0x59, 0xef, 0xae, 0x4d, 0xd4, + 0x48, 0x4e, 0x2c, 0x0e, 0x3d, 0x25, 0x33, 0xf3, 0xe6, 0x7d, 0x3e, 0xf3, 0xde, 0x9b, 0xcf, 0xbc, + 0x35, 0xd8, 0xed, 0x78, 0xfc, 0xb0, 0xb7, 0x6f, 0x3a, 0x34, 0xb0, 0xfa, 0xc1, 0x43, 0xcc, 0xc8, + 0x65, 0x8e, 0xc3, 0x4f, 0x7b, 0x16, 0x0e, 0x39, 0x23, 0xd8, 0x8a, 0xba, 0x1d, 0x0b, 0x47, 0x5e, + 0x6c, 0x39, 0x34, 0xe4, 0x8c, 0xfa, 0x91, 0x8f, 0x43, 0x62, 0xf5, 0x37, 0xf7, 0x09, 0xc7, 0x9b, + 0x56, 0x87, 0x84, 0x84, 0x61, 0x4e, 0x5c, 0x33, 0x62, 0x94, 0x53, 0x78, 0x3d, 0xf3, 0x66, 0x26, + 0xde, 0x3e, 0x96, 0xde, 0xcc, 0xc4, 0x9b, 0x19, 0x75, 0x3b, 0xa6, 0xf0, 0x66, 0xe6, 0xbd, 0x99, + 0xca, 0xdb, 0xa5, 0xcb, 0x39, 0x2e, 0x1d, 0xda, 0xa1, 0x96, 0x74, 0xba, 0xdf, 0x3b, 0x90, 0x23, + 0x39, 0x90, 0xff, 0x25, 0x60, 0x97, 0xae, 0x76, 0xaf, 0xc5, 0xa6, 0x47, 0x05, 0xbd, 0x00, 0x3b, + 0x87, 0x5e, 0x48, 0xd8, 0xe3, 0x8c, 0x6f, 0x40, 0x38, 0xb6, 0xfa, 0x13, 0x14, 0x2f, 0x59, 0x27, + 0xed, 0x62, 0xbd, 0x90, 0x7b, 0x01, 0x99, 0xd8, 0xf0, 0xf6, 0x8b, 0x36, 0xc4, 0xce, 0x21, 0x09, + 0xf0, 0xc4, 0xbe, 0xb7, 0x4e, 0xda, 0xd7, 0xe3, 0x9e, 0x6f, 0x79, 0x21, 0x8f, 0x39, 0x1b, 0xdf, + 0x64, 0xfc, 0xa5, 0x83, 0xda, 0x96, 0xeb, 0x32, 0x12, 0xc7, 0xb7, 0x18, 0xed, 0x45, 0xf0, 0x13, + 0xb0, 0x28, 0x4e, 0xe2, 0x62, 0x8e, 0xeb, 0xda, 0xba, 0xb6, 0xb1, 0x74, 0xe5, 0x4d, 0x33, 0x71, + 0x6c, 0xe6, 0x1d, 0x67, 0x91, 0x15, 0xd6, 0x66, 0x7f, 0xd3, 0xbc, 0xb3, 0x7f, 0x9f, 0x38, 0xfc, + 0x36, 0xe1, 0xb8, 0x05, 0x9f, 0x0c, 0x9a, 0x73, 0xc3, 0x41, 0x13, 0x64, 0x73, 0x68, 0xe4, 0x15, + 0x86, 0xa0, 0x1c, 0x51, 0x37, 0xae, 0xeb, 0xeb, 0xa5, 0x8d, 0xa5, 0x2b, 0xbb, 0xe6, 0x34, 0x29, + 0x34, 0x25, 0xe9, 0xdb, 0x24, 0xd8, 0x27, 0xcc, 0xa6, 0x6e, 0xab, 0xa6, 0x90, 0xcb, 0x36, 0x75, + 0x63, 0x24, 0x71, 0xe0, 0x97, 0x1a, 0xa8, 0x75, 0x32, 0xb3, 0xb8, 0x5e, 0x92, 0xc0, 0xed, 0x33, + 0x03, 0x6e, 0xfd, 0x4f, 0xa1, 0xd6, 0x72, 0x93, 0x31, 0x2a, 0x80, 0x1a, 0x47, 0x1a, 0xb8, 0x98, + 0x0f, 0xf4, 0xae, 0x17, 0x73, 0xf8, 0xd1, 0x44, 0xb0, 0xcd, 0xd3, 0x05, 0x5b, 0xec, 0x96, 0xa1, + 0xbe, 0xa8, 0xa0, 0x17, 0xd3, 0x99, 0x5c, 0xa0, 0x29, 0xa8, 0x78, 0x9c, 0x04, 0x69, 0xa4, 0xdf, + 0x9b, 0xee, 0xc0, 0x79, 0xf2, 0xad, 0x65, 0x05, 0x5b, 0x69, 0x0b, 0x00, 0x94, 0xe0, 0x18, 0x3f, + 0x57, 0xc0, 0x6a, 0xde, 0xcc, 0xc6, 0xdc, 0x39, 0x9c, 0x41, 0x45, 0x7d, 0x06, 0xaa, 0xd8, 0x75, + 0x89, 0x6b, 0x9f, 0x57, 0x59, 0xad, 0x2a, 0xf8, 0xea, 0x56, 0x0a, 0x83, 0x32, 0x44, 0x51, 0x60, + 0x4b, 0x8c, 0x04, 0xb4, 0xaf, 0x18, 0x94, 0xce, 0x81, 0xc1, 0x9a, 0x62, 0xb0, 0x84, 0x32, 0x20, + 0x94, 0x47, 0x85, 0xdf, 0x6b, 0x60, 0x55, 0x72, 0xca, 0x17, 0x61, 0xbd, 0x7c, 0xd6, 0xb5, 0xfe, + 0x8a, 0x22, 0xb2, 0xba, 0x35, 0x8e, 0x85, 0x26, 0xe1, 0xe1, 0x8f, 0x1a, 0x58, 0x53, 0x24, 0x0b, + 0xb4, 0x2a, 0x67, 0x4d, 0xeb, 0x55, 0x45, 0x6b, 0x0d, 0x4d, 0xa2, 0xa1, 0x7f, 0xa3, 0x60, 0xfc, + 0xad, 0x83, 0x95, 0xad, 0x28, 0xf2, 0x3d, 0xe2, 0xde, 0xa3, 0x2f, 0xb5, 0xef, 0x3c, 0xb5, 0xef, + 0x4f, 0x0d, 0xc0, 0x62, 0xa8, 0x67, 0xa0, 0x7e, 0x0f, 0x8a, 0xea, 0x37, 0x65, 0xac, 0x8b, 0xf4, + 0x4f, 0xd0, 0xbf, 0x5f, 0x2a, 0x60, 0xad, 0x68, 0xf8, 0x52, 0x01, 0x5f, 0x2a, 0xe0, 0x7f, 0x56, + 0x01, 0x7f, 0xd2, 0xc0, 0xe2, 0x4e, 0xe8, 0x46, 0xd4, 0x0b, 0x39, 0x7c, 0x1d, 0xe8, 0x5e, 0x24, + 0xab, 0xb3, 0xd6, 0x5a, 0x1b, 0x0e, 0x9a, 0x7a, 0xdb, 0x3e, 0x1e, 0x34, 0xab, 0x6d, 0x5b, 0x3d, + 0xe8, 0x48, 0xf7, 0x22, 0xe8, 0x83, 0x4a, 0x44, 0x19, 0x4f, 0x4b, 0xec, 0xd6, 0x74, 0xec, 0xf7, + 0x70, 0x20, 0x32, 0xc7, 0x78, 0x76, 0x9d, 0xc4, 0x28, 0x46, 0x09, 0x88, 0xe1, 0x83, 0xff, 0xef, + 0x3c, 0xe2, 0x84, 0x85, 0xd8, 0xdf, 0x09, 0xb9, 0xc7, 0x1f, 0x23, 0x72, 0x40, 0x18, 0x09, 0x1d, + 0x02, 0xd7, 0x41, 0x39, 0xc4, 0x01, 0x91, 0x7c, 0xab, 0x99, 0xf2, 0x09, 0x8f, 0x48, 0xae, 0x40, + 0x0b, 0x54, 0xc5, 0xdf, 0x38, 0xc2, 0x0e, 0xa9, 0xeb, 0xd2, 0x6c, 0x54, 0xc3, 0x7b, 0xe9, 0x02, + 0xca, 0x6c, 0x8c, 0x2f, 0x4a, 0x60, 0x29, 0x17, 0x1e, 0x48, 0x40, 0x29, 0xa2, 0xae, 0xba, 0xaf, + 0x53, 0xf6, 0x4e, 0x36, 0x75, 0x47, 0xdc, 0x5b, 0x0b, 0xc3, 0x41, 0xb3, 0x24, 0x66, 0x84, 0x7f, + 0xf8, 0x9d, 0x06, 0x56, 0x48, 0xe1, 0x94, 0x92, 0xed, 0xd2, 0x95, 0x0f, 0xa6, 0x83, 0x3c, 0x21, + 0x72, 0x2d, 0x38, 0x1c, 0x34, 0x57, 0xc6, 0x16, 0xc7, 0x08, 0xc0, 0x87, 0xa0, 0x4a, 0x54, 0x5d, + 0xa4, 0x77, 0xf9, 0xe6, 0x94, 0x6c, 0x94, 0xbb, 0x2c, 0x07, 0xe9, 0x4c, 0x8c, 0x32, 0x2c, 0xe3, + 0x6b, 0x1d, 0xac, 0x14, 0xaf, 0xfd, 0xac, 0xd2, 0x90, 0x94, 0xbf, 0x7e, 0xca, 0xf2, 0x2f, 0xcd, + 0xa2, 0xfc, 0x7f, 0xd7, 0xc0, 0x42, 0xdb, 0x6e, 0xf9, 0xd4, 0xe9, 0x42, 0x02, 0xca, 0x8e, 0xe7, + 0x32, 0x15, 0x86, 0x1b, 0xd3, 0x01, 0xb7, 0xed, 0x3d, 0xc2, 0xb3, 0x4b, 0x73, 0xa3, 0xbd, 0x8d, + 0x90, 0x74, 0x0f, 0xbb, 0x60, 0x9e, 0x3c, 0x72, 0x48, 0xc4, 0xd5, 0x05, 0x3f, 0x13, 0xa0, 0x15, + 0x05, 0x34, 0xbf, 0x23, 0x5d, 0x23, 0x05, 0x61, 0x1c, 0x80, 0x8a, 0x34, 0x38, 0x9d, 0xf4, 0x5c, + 0x03, 0xb5, 0x88, 0x91, 0x03, 0xef, 0xd1, 0x2e, 0x09, 0x3b, 0xfc, 0x50, 0xa6, 0xaa, 0x92, 0x75, + 0x1f, 0x76, 0x6e, 0x0d, 0x15, 0x2c, 0x8d, 0xaf, 0x34, 0x50, 0x1d, 0xc5, 0x5a, 0x28, 0x87, 0x08, + 0xaf, 0x84, 0xab, 0xe4, 0x7b, 0x26, 0xc6, 0x91, 0x5c, 0x19, 0x69, 0x8b, 0x7e, 0xa2, 0xb6, 0x5c, + 0x03, 0x8b, 0xf2, 0xeb, 0xd9, 0xa1, 0x7e, 0xbd, 0x24, 0xad, 0x5e, 0x4b, 0x1b, 0x11, 0x5b, 0xcd, + 0x1f, 0xe7, 0xfe, 0x47, 0x23, 0x6b, 0xe3, 0x87, 0x12, 0x58, 0xde, 0x23, 0xfc, 0x21, 0x65, 0x5d, + 0x9b, 0xfa, 0x9e, 0xf3, 0x78, 0x06, 0xbd, 0x01, 0x07, 0x15, 0xd6, 0xf3, 0x49, 0x2a, 0xda, 0x77, + 0xa6, 0xac, 0xda, 0x3c, 0x7b, 0xd4, 0xf3, 0x49, 0x56, 0xbd, 0x62, 0x14, 0xa3, 0x04, 0x0c, 0xbe, + 0x0b, 0x2e, 0xe0, 0x42, 0x2b, 0x94, 0xdc, 0x9a, 0xaa, 0xcc, 0xf0, 0x85, 0x62, 0x97, 0x14, 0xa3, + 0x71, 0x5b, 0xb8, 0x21, 0x42, 0xec, 0x51, 0x26, 0xf4, 0xb0, 0xbc, 0xae, 0x6d, 0x68, 0xad, 0x5a, + 0x12, 0xde, 0x64, 0x0e, 0x8d, 0x56, 0xe1, 0x36, 0xa8, 0x71, 0x8f, 0xb0, 0x74, 0xa5, 0x5e, 0x59, + 0xd7, 0x36, 0x96, 0x5b, 0xeb, 0xa2, 0x28, 0xee, 0xe5, 0xe6, 0x8f, 0xc7, 0xc6, 0xa8, 0xb0, 0xcb, + 0x78, 0xae, 0x81, 0xd5, 0xc2, 0xd1, 0x66, 0xd0, 0xa1, 0x46, 0xc5, 0x0e, 0xf5, 0xfd, 0x33, 0x4c, + 0xcc, 0x09, 0x0d, 0xea, 0x6f, 0xe3, 0xa7, 0xb4, 0x09, 0x61, 0xf0, 0x1d, 0xb0, 0x8c, 0x73, 0x5f, + 0xed, 0x71, 0x5d, 0x93, 0x89, 0x5a, 0x1d, 0x0e, 0x9a, 0xcb, 0xf9, 0xcf, 0xf9, 0x18, 0x15, 0xed, + 0x60, 0x0c, 0x16, 0xbd, 0x48, 0x0a, 0x54, 0x7a, 0x86, 0x9d, 0x69, 0x05, 0x43, 0x7a, 0xcb, 0xa2, + 0xa6, 0x26, 0x62, 0x34, 0x02, 0x32, 0x7e, 0x2d, 0x8f, 0x9d, 0x41, 0x94, 0x1d, 0xbc, 0x0e, 0xaa, + 0xae, 0xc7, 0x88, 0xc3, 0x3d, 0x1a, 0xaa, 0xae, 0xa0, 0x91, 0x3e, 0x35, 0xdb, 0xe9, 0xc2, 0x71, + 0x7e, 0x80, 0xb2, 0x0d, 0xf0, 0x01, 0x28, 0x1f, 0x30, 0x1a, 0xa8, 0x97, 0xf7, 0x2c, 0x6f, 0x88, + 0x08, 0x70, 0xa6, 0x21, 0x37, 0x19, 0x0d, 0x90, 0x84, 0x82, 0x5d, 0xa0, 0x73, 0x2a, 0xd5, 0xe3, + 0x1c, 0x00, 0x81, 0x02, 0xd4, 0xef, 0x51, 0xa4, 0x73, 0x2a, 0x12, 0x15, 0x13, 0xd6, 0xf7, 0x1c, + 0x92, 0xf6, 0xc3, 0x53, 0x26, 0xea, 0x6e, 0xe2, 0x2d, 0x4b, 0x94, 0x9a, 0x88, 0xd1, 0x08, 0x08, + 0xbe, 0x91, 0xbb, 0xc2, 0x15, 0xa9, 0xb6, 0x17, 0x33, 0x95, 0x9c, 0xb8, 0xc6, 0xf7, 0xc1, 0x3c, + 0x4e, 0xb2, 0x37, 0x2f, 0xb3, 0x87, 0xc4, 0x8b, 0xb1, 0x95, 0xa6, 0x6d, 0xfb, 0xb4, 0xbf, 0x1a, + 0xc7, 0xc4, 0xe9, 0x09, 0x7f, 0x56, 0x7f, 0x13, 0xfb, 0xd1, 0x21, 0xde, 0x34, 0x45, 0x79, 0x24, + 0x7e, 0x90, 0x42, 0x30, 0x30, 0xa8, 0xe5, 0x5b, 0x81, 0xf3, 0xe8, 0x26, 0xbf, 0xd1, 0xc0, 0x82, + 0x8a, 0x09, 0xbc, 0x9a, 0x7b, 0x2e, 0x12, 0x88, 0xfa, 0x8b, 0x9f, 0x0a, 0xb8, 0xa7, 0x1e, 0x2a, + 0xfd, 0x05, 0x8f, 0x42, 0x8f, 0x7b, 0xbe, 0x99, 0xfc, 0xba, 0x6b, 0xb6, 0x43, 0x7e, 0x87, 0xdd, + 0xe5, 0xcc, 0x0b, 0x3b, 0xad, 0xc5, 0xe2, 0xb3, 0xd6, 0xba, 0xfc, 0xe4, 0xa8, 0x31, 0xf7, 0xf4, + 0xa8, 0x31, 0xf7, 0xec, 0xa8, 0x31, 0xf7, 0xf9, 0xb0, 0xa1, 0x3d, 0x19, 0x36, 0xb4, 0xa7, 0xc3, + 0x86, 0xf6, 0x6c, 0xd8, 0xd0, 0xfe, 0x18, 0x36, 0xb4, 0x6f, 0x9f, 0x37, 0xe6, 0x3e, 0x5c, 0x50, + 0x19, 0xfe, 0x27, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x01, 0xe0, 0x3e, 0xa8, 0x17, 0x00, 0x00, } func (m *AddressGroup) Marshal() (dAtA []byte, err error) { diff --git a/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go b/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go index 9144ed91588..abf52d54b7e 100644 --- a/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go +++ b/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go @@ -421,8 +421,8 @@ func Convert_controlplane_ExternalEntityReference_To_v1beta1_ExternalEntityRefer } func autoConvert_v1beta1_GroupMember_To_controlplane_GroupMember(in *GroupMember, out *controlplane.GroupMember, s conversion.Scope) error { - out.ExternalEntity = (*controlplane.ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) out.Pod = (*controlplane.PodReference)(unsafe.Pointer(in.Pod)) + out.ExternalEntity = (*controlplane.ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) out.Endpoints = *(*[]controlplane.Endpoint)(unsafe.Pointer(&in.Endpoints)) return nil } diff --git a/pkg/apis/networking/v1beta1/zz_generated.conversion.go b/pkg/apis/networking/v1beta1/zz_generated.conversion.go deleted file mode 100644 index a7afbfaf39f..00000000000 --- a/pkg/apis/networking/v1beta1/zz_generated.conversion.go +++ /dev/null @@ -1,695 +0,0 @@ -// +build !ignore_autogenerated - -// Copyright 2020 Antrea Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Code generated by conversion-gen. DO NOT EDIT. - -package v1beta1 - -import ( - unsafe "unsafe" - - networking "github.com/vmware-tanzu/antrea/pkg/apis/networking" - v1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" - conversion "k8s.io/apimachinery/pkg/conversion" - runtime "k8s.io/apimachinery/pkg/runtime" - intstr "k8s.io/apimachinery/pkg/util/intstr" -) - -func init() { - localSchemeBuilder.Register(RegisterConversions) -} - -// RegisterConversions adds conversion functions to the given scheme. -// Public to allow building arbitrary schemes. -func RegisterConversions(s *runtime.Scheme) error { - if err := s.AddGeneratedConversionFunc((*AddressGroup)(nil), (*networking.AddressGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AddressGroup_To_networking_AddressGroup(a.(*AddressGroup), b.(*networking.AddressGroup), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AddressGroup)(nil), (*AddressGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AddressGroup_To_v1beta1_AddressGroup(a.(*networking.AddressGroup), b.(*AddressGroup), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AddressGroupList)(nil), (*networking.AddressGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList(a.(*AddressGroupList), b.(*networking.AddressGroupList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AddressGroupList)(nil), (*AddressGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList(a.(*networking.AddressGroupList), b.(*AddressGroupList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AddressGroupPatch)(nil), (*networking.AddressGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(a.(*AddressGroupPatch), b.(*networking.AddressGroupPatch), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AddressGroupPatch)(nil), (*AddressGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(a.(*networking.AddressGroupPatch), b.(*AddressGroupPatch), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AppliedToGroup)(nil), (*networking.AppliedToGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(a.(*AppliedToGroup), b.(*networking.AppliedToGroup), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroup)(nil), (*AppliedToGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(a.(*networking.AppliedToGroup), b.(*AppliedToGroup), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AppliedToGroupList)(nil), (*networking.AppliedToGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(a.(*AppliedToGroupList), b.(*networking.AppliedToGroupList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroupList)(nil), (*AppliedToGroupList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(a.(*networking.AppliedToGroupList), b.(*AppliedToGroupList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AppliedToGroupPatch)(nil), (*networking.AppliedToGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(a.(*AppliedToGroupPatch), b.(*networking.AppliedToGroupPatch), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.AppliedToGroupPatch)(nil), (*AppliedToGroupPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(a.(*networking.AppliedToGroupPatch), b.(*AppliedToGroupPatch), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Endpoint)(nil), (*networking.Endpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_Endpoint_To_networking_Endpoint(a.(*Endpoint), b.(*networking.Endpoint), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.Endpoint)(nil), (*Endpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_Endpoint_To_v1beta1_Endpoint(a.(*networking.Endpoint), b.(*Endpoint), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*ExternalEntityReference)(nil), (*networking.ExternalEntityReference)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(a.(*ExternalEntityReference), b.(*networking.ExternalEntityReference), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.ExternalEntityReference)(nil), (*ExternalEntityReference)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(a.(*networking.ExternalEntityReference), b.(*ExternalEntityReference), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*GroupMember)(nil), (*networking.GroupMember)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_GroupMember_To_networking_GroupMember(a.(*GroupMember), b.(*networking.GroupMember), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.GroupMember)(nil), (*GroupMember)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_GroupMember_To_v1beta1_GroupMember(a.(*networking.GroupMember), b.(*GroupMember), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*GroupMemberPod)(nil), (*networking.GroupMemberPod)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(a.(*GroupMemberPod), b.(*networking.GroupMemberPod), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.GroupMemberPod)(nil), (*GroupMemberPod)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(a.(*networking.GroupMemberPod), b.(*GroupMemberPod), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*IPBlock)(nil), (*networking.IPBlock)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_IPBlock_To_networking_IPBlock(a.(*IPBlock), b.(*networking.IPBlock), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.IPBlock)(nil), (*IPBlock)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_IPBlock_To_v1beta1_IPBlock(a.(*networking.IPBlock), b.(*IPBlock), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*IPNet)(nil), (*networking.IPNet)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_IPNet_To_networking_IPNet(a.(*IPNet), b.(*networking.IPNet), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.IPNet)(nil), (*IPNet)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_IPNet_To_v1beta1_IPNet(a.(*networking.IPNet), b.(*IPNet), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*NamedPort)(nil), (*networking.NamedPort)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_NamedPort_To_networking_NamedPort(a.(*NamedPort), b.(*networking.NamedPort), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.NamedPort)(nil), (*NamedPort)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_NamedPort_To_v1beta1_NamedPort(a.(*networking.NamedPort), b.(*NamedPort), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*NetworkPolicy)(nil), (*networking.NetworkPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(a.(*NetworkPolicy), b.(*networking.NetworkPolicy), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicy)(nil), (*NetworkPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(a.(*networking.NetworkPolicy), b.(*NetworkPolicy), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*NetworkPolicyList)(nil), (*networking.NetworkPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(a.(*NetworkPolicyList), b.(*networking.NetworkPolicyList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyList)(nil), (*NetworkPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(a.(*networking.NetworkPolicyList), b.(*NetworkPolicyList), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*NetworkPolicyPeer)(nil), (*networking.NetworkPolicyPeer)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(a.(*NetworkPolicyPeer), b.(*networking.NetworkPolicyPeer), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyPeer)(nil), (*NetworkPolicyPeer)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(a.(*networking.NetworkPolicyPeer), b.(*NetworkPolicyPeer), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*NetworkPolicyRule)(nil), (*networking.NetworkPolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(a.(*NetworkPolicyRule), b.(*networking.NetworkPolicyRule), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.NetworkPolicyRule)(nil), (*NetworkPolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(a.(*networking.NetworkPolicyRule), b.(*NetworkPolicyRule), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*PodReference)(nil), (*networking.PodReference)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_PodReference_To_networking_PodReference(a.(*PodReference), b.(*networking.PodReference), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.PodReference)(nil), (*PodReference)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_PodReference_To_v1beta1_PodReference(a.(*networking.PodReference), b.(*PodReference), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Service)(nil), (*networking.Service)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_Service_To_networking_Service(a.(*Service), b.(*networking.Service), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*networking.Service)(nil), (*Service)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_networking_Service_To_v1beta1_Service(a.(*networking.Service), b.(*Service), scope) - }); err != nil { - return err - } - return nil -} - -func autoConvert_v1beta1_AddressGroup_To_networking_AddressGroup(in *AddressGroup, out *networking.AddressGroup, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Pods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.Pods)) - out.GroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.GroupMembers)) - return nil -} - -// Convert_v1beta1_AddressGroup_To_networking_AddressGroup is an autogenerated conversion function. -func Convert_v1beta1_AddressGroup_To_networking_AddressGroup(in *AddressGroup, out *networking.AddressGroup, s conversion.Scope) error { - return autoConvert_v1beta1_AddressGroup_To_networking_AddressGroup(in, out, s) -} - -func autoConvert_networking_AddressGroup_To_v1beta1_AddressGroup(in *networking.AddressGroup, out *AddressGroup, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Pods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.Pods)) - out.GroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.GroupMembers)) - return nil -} - -// Convert_networking_AddressGroup_To_v1beta1_AddressGroup is an autogenerated conversion function. -func Convert_networking_AddressGroup_To_v1beta1_AddressGroup(in *networking.AddressGroup, out *AddressGroup, s conversion.Scope) error { - return autoConvert_networking_AddressGroup_To_v1beta1_AddressGroup(in, out, s) -} - -func autoConvert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in *AddressGroupList, out *networking.AddressGroupList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]networking.AddressGroup)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList is an autogenerated conversion function. -func Convert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in *AddressGroupList, out *networking.AddressGroupList, s conversion.Scope) error { - return autoConvert_v1beta1_AddressGroupList_To_networking_AddressGroupList(in, out, s) -} - -func autoConvert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in *networking.AddressGroupList, out *AddressGroupList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]AddressGroup)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList is an autogenerated conversion function. -func Convert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in *networking.AddressGroupList, out *AddressGroupList, s conversion.Scope) error { - return autoConvert_networking_AddressGroupList_To_v1beta1_AddressGroupList(in, out, s) -} - -func autoConvert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in *AddressGroupPatch, out *networking.AddressGroupPatch, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.AddedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) - out.RemovedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) - out.AddedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) - out.RemovedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) - return nil -} - -// Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch is an autogenerated conversion function. -func Convert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in *AddressGroupPatch, out *networking.AddressGroupPatch, s conversion.Scope) error { - return autoConvert_v1beta1_AddressGroupPatch_To_networking_AddressGroupPatch(in, out, s) -} - -func autoConvert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in *networking.AddressGroupPatch, out *AddressGroupPatch, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.AddedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) - out.RemovedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) - out.AddedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) - out.RemovedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) - return nil -} - -// Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch is an autogenerated conversion function. -func Convert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in *networking.AddressGroupPatch, out *AddressGroupPatch, s conversion.Scope) error { - return autoConvert_networking_AddressGroupPatch_To_v1beta1_AddressGroupPatch(in, out, s) -} - -func autoConvert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in *AppliedToGroup, out *networking.AppliedToGroup, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Pods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.Pods)) - out.GroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.GroupMembers)) - return nil -} - -// Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup is an autogenerated conversion function. -func Convert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in *AppliedToGroup, out *networking.AppliedToGroup, s conversion.Scope) error { - return autoConvert_v1beta1_AppliedToGroup_To_networking_AppliedToGroup(in, out, s) -} - -func autoConvert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in *networking.AppliedToGroup, out *AppliedToGroup, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Pods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.Pods)) - out.GroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.GroupMembers)) - return nil -} - -// Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup is an autogenerated conversion function. -func Convert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in *networking.AppliedToGroup, out *AppliedToGroup, s conversion.Scope) error { - return autoConvert_networking_AppliedToGroup_To_v1beta1_AppliedToGroup(in, out, s) -} - -func autoConvert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in *AppliedToGroupList, out *networking.AppliedToGroupList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]networking.AppliedToGroup)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList is an autogenerated conversion function. -func Convert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in *AppliedToGroupList, out *networking.AppliedToGroupList, s conversion.Scope) error { - return autoConvert_v1beta1_AppliedToGroupList_To_networking_AppliedToGroupList(in, out, s) -} - -func autoConvert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in *networking.AppliedToGroupList, out *AppliedToGroupList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]AppliedToGroup)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList is an autogenerated conversion function. -func Convert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in *networking.AppliedToGroupList, out *AppliedToGroupList, s conversion.Scope) error { - return autoConvert_networking_AppliedToGroupList_To_v1beta1_AppliedToGroupList(in, out, s) -} - -func autoConvert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in *AppliedToGroupPatch, out *networking.AppliedToGroupPatch, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.AddedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) - out.RemovedPods = *(*[]networking.GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) - out.AddedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) - out.RemovedGroupMembers = *(*[]networking.GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) - return nil -} - -// Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch is an autogenerated conversion function. -func Convert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in *AppliedToGroupPatch, out *networking.AppliedToGroupPatch, s conversion.Scope) error { - return autoConvert_v1beta1_AppliedToGroupPatch_To_networking_AppliedToGroupPatch(in, out, s) -} - -func autoConvert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in *networking.AppliedToGroupPatch, out *AppliedToGroupPatch, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.AddedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.AddedPods)) - out.RemovedPods = *(*[]GroupMemberPod)(unsafe.Pointer(&in.RemovedPods)) - out.AddedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.AddedGroupMembers)) - out.RemovedGroupMembers = *(*[]GroupMember)(unsafe.Pointer(&in.RemovedGroupMembers)) - return nil -} - -// Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch is an autogenerated conversion function. -func Convert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in *networking.AppliedToGroupPatch, out *AppliedToGroupPatch, s conversion.Scope) error { - return autoConvert_networking_AppliedToGroupPatch_To_v1beta1_AppliedToGroupPatch(in, out, s) -} - -func autoConvert_v1beta1_Endpoint_To_networking_Endpoint(in *Endpoint, out *networking.Endpoint, s conversion.Scope) error { - out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) - out.Ports = *(*[]networking.NamedPort)(unsafe.Pointer(&in.Ports)) - return nil -} - -// Convert_v1beta1_Endpoint_To_networking_Endpoint is an autogenerated conversion function. -func Convert_v1beta1_Endpoint_To_networking_Endpoint(in *Endpoint, out *networking.Endpoint, s conversion.Scope) error { - return autoConvert_v1beta1_Endpoint_To_networking_Endpoint(in, out, s) -} - -func autoConvert_networking_Endpoint_To_v1beta1_Endpoint(in *networking.Endpoint, out *Endpoint, s conversion.Scope) error { - out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) - out.Ports = *(*[]NamedPort)(unsafe.Pointer(&in.Ports)) - return nil -} - -// Convert_networking_Endpoint_To_v1beta1_Endpoint is an autogenerated conversion function. -func Convert_networking_Endpoint_To_v1beta1_Endpoint(in *networking.Endpoint, out *Endpoint, s conversion.Scope) error { - return autoConvert_networking_Endpoint_To_v1beta1_Endpoint(in, out, s) -} - -func autoConvert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in *ExternalEntityReference, out *networking.ExternalEntityReference, s conversion.Scope) error { - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} - -// Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference is an autogenerated conversion function. -func Convert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in *ExternalEntityReference, out *networking.ExternalEntityReference, s conversion.Scope) error { - return autoConvert_v1beta1_ExternalEntityReference_To_networking_ExternalEntityReference(in, out, s) -} - -func autoConvert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in *networking.ExternalEntityReference, out *ExternalEntityReference, s conversion.Scope) error { - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} - -// Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference is an autogenerated conversion function. -func Convert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in *networking.ExternalEntityReference, out *ExternalEntityReference, s conversion.Scope) error { - return autoConvert_networking_ExternalEntityReference_To_v1beta1_ExternalEntityReference(in, out, s) -} - -func autoConvert_v1beta1_GroupMember_To_networking_GroupMember(in *GroupMember, out *networking.GroupMember, s conversion.Scope) error { - out.Pod = (*networking.PodReference)(unsafe.Pointer(in.Pod)) - out.ExternalEntity = (*networking.ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) - out.Endpoints = *(*[]networking.Endpoint)(unsafe.Pointer(&in.Endpoints)) - return nil -} - -// Convert_v1beta1_GroupMember_To_networking_GroupMember is an autogenerated conversion function. -func Convert_v1beta1_GroupMember_To_networking_GroupMember(in *GroupMember, out *networking.GroupMember, s conversion.Scope) error { - return autoConvert_v1beta1_GroupMember_To_networking_GroupMember(in, out, s) -} - -func autoConvert_networking_GroupMember_To_v1beta1_GroupMember(in *networking.GroupMember, out *GroupMember, s conversion.Scope) error { - out.Pod = (*PodReference)(unsafe.Pointer(in.Pod)) - out.ExternalEntity = (*ExternalEntityReference)(unsafe.Pointer(in.ExternalEntity)) - out.Endpoints = *(*[]Endpoint)(unsafe.Pointer(&in.Endpoints)) - return nil -} - -// Convert_networking_GroupMember_To_v1beta1_GroupMember is an autogenerated conversion function. -func Convert_networking_GroupMember_To_v1beta1_GroupMember(in *networking.GroupMember, out *GroupMember, s conversion.Scope) error { - return autoConvert_networking_GroupMember_To_v1beta1_GroupMember(in, out, s) -} - -func autoConvert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in *GroupMemberPod, out *networking.GroupMemberPod, s conversion.Scope) error { - out.Pod = (*networking.PodReference)(unsafe.Pointer(in.Pod)) - out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) - out.Ports = *(*[]networking.NamedPort)(unsafe.Pointer(&in.Ports)) - return nil -} - -// Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod is an autogenerated conversion function. -func Convert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in *GroupMemberPod, out *networking.GroupMemberPod, s conversion.Scope) error { - return autoConvert_v1beta1_GroupMemberPod_To_networking_GroupMemberPod(in, out, s) -} - -func autoConvert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in *networking.GroupMemberPod, out *GroupMemberPod, s conversion.Scope) error { - out.Pod = (*PodReference)(unsafe.Pointer(in.Pod)) - out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) - out.Ports = *(*[]NamedPort)(unsafe.Pointer(&in.Ports)) - return nil -} - -// Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod is an autogenerated conversion function. -func Convert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in *networking.GroupMemberPod, out *GroupMemberPod, s conversion.Scope) error { - return autoConvert_networking_GroupMemberPod_To_v1beta1_GroupMemberPod(in, out, s) -} - -func autoConvert_v1beta1_IPBlock_To_networking_IPBlock(in *IPBlock, out *networking.IPBlock, s conversion.Scope) error { - if err := Convert_v1beta1_IPNet_To_networking_IPNet(&in.CIDR, &out.CIDR, s); err != nil { - return err - } - out.Except = *(*[]networking.IPNet)(unsafe.Pointer(&in.Except)) - return nil -} - -// Convert_v1beta1_IPBlock_To_networking_IPBlock is an autogenerated conversion function. -func Convert_v1beta1_IPBlock_To_networking_IPBlock(in *IPBlock, out *networking.IPBlock, s conversion.Scope) error { - return autoConvert_v1beta1_IPBlock_To_networking_IPBlock(in, out, s) -} - -func autoConvert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *IPBlock, s conversion.Scope) error { - if err := Convert_networking_IPNet_To_v1beta1_IPNet(&in.CIDR, &out.CIDR, s); err != nil { - return err - } - out.Except = *(*[]IPNet)(unsafe.Pointer(&in.Except)) - return nil -} - -// Convert_networking_IPBlock_To_v1beta1_IPBlock is an autogenerated conversion function. -func Convert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *IPBlock, s conversion.Scope) error { - return autoConvert_networking_IPBlock_To_v1beta1_IPBlock(in, out, s) -} - -func autoConvert_v1beta1_IPNet_To_networking_IPNet(in *IPNet, out *networking.IPNet, s conversion.Scope) error { - out.IP = *(*networking.IPAddress)(unsafe.Pointer(&in.IP)) - out.PrefixLength = in.PrefixLength - return nil -} - -// Convert_v1beta1_IPNet_To_networking_IPNet is an autogenerated conversion function. -func Convert_v1beta1_IPNet_To_networking_IPNet(in *IPNet, out *networking.IPNet, s conversion.Scope) error { - return autoConvert_v1beta1_IPNet_To_networking_IPNet(in, out, s) -} - -func autoConvert_networking_IPNet_To_v1beta1_IPNet(in *networking.IPNet, out *IPNet, s conversion.Scope) error { - out.IP = *(*IPAddress)(unsafe.Pointer(&in.IP)) - out.PrefixLength = in.PrefixLength - return nil -} - -// Convert_networking_IPNet_To_v1beta1_IPNet is an autogenerated conversion function. -func Convert_networking_IPNet_To_v1beta1_IPNet(in *networking.IPNet, out *IPNet, s conversion.Scope) error { - return autoConvert_networking_IPNet_To_v1beta1_IPNet(in, out, s) -} - -func autoConvert_v1beta1_NamedPort_To_networking_NamedPort(in *NamedPort, out *networking.NamedPort, s conversion.Scope) error { - out.Port = in.Port - out.Name = in.Name - out.Protocol = networking.Protocol(in.Protocol) - return nil -} - -// Convert_v1beta1_NamedPort_To_networking_NamedPort is an autogenerated conversion function. -func Convert_v1beta1_NamedPort_To_networking_NamedPort(in *NamedPort, out *networking.NamedPort, s conversion.Scope) error { - return autoConvert_v1beta1_NamedPort_To_networking_NamedPort(in, out, s) -} - -func autoConvert_networking_NamedPort_To_v1beta1_NamedPort(in *networking.NamedPort, out *NamedPort, s conversion.Scope) error { - out.Port = in.Port - out.Name = in.Name - out.Protocol = Protocol(in.Protocol) - return nil -} - -// Convert_networking_NamedPort_To_v1beta1_NamedPort is an autogenerated conversion function. -func Convert_networking_NamedPort_To_v1beta1_NamedPort(in *networking.NamedPort, out *NamedPort, s conversion.Scope) error { - return autoConvert_networking_NamedPort_To_v1beta1_NamedPort(in, out, s) -} - -func autoConvert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in *NetworkPolicy, out *networking.NetworkPolicy, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Rules = *(*[]networking.NetworkPolicyRule)(unsafe.Pointer(&in.Rules)) - out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) - out.Priority = (*float64)(unsafe.Pointer(in.Priority)) - out.TierPriority = (*networking.TierPriority)(unsafe.Pointer(in.TierPriority)) - return nil -} - -// Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy is an autogenerated conversion function. -func Convert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in *NetworkPolicy, out *networking.NetworkPolicy, s conversion.Scope) error { - return autoConvert_v1beta1_NetworkPolicy_To_networking_NetworkPolicy(in, out, s) -} - -func autoConvert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in *networking.NetworkPolicy, out *NetworkPolicy, s conversion.Scope) error { - out.ObjectMeta = in.ObjectMeta - out.Rules = *(*[]NetworkPolicyRule)(unsafe.Pointer(&in.Rules)) - out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) - out.Priority = (*float64)(unsafe.Pointer(in.Priority)) - out.TierPriority = (*TierPriority)(unsafe.Pointer(in.TierPriority)) - return nil -} - -// Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy is an autogenerated conversion function. -func Convert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in *networking.NetworkPolicy, out *NetworkPolicy, s conversion.Scope) error { - return autoConvert_networking_NetworkPolicy_To_v1beta1_NetworkPolicy(in, out, s) -} - -func autoConvert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in *NetworkPolicyList, out *networking.NetworkPolicyList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]networking.NetworkPolicy)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList is an autogenerated conversion function. -func Convert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in *NetworkPolicyList, out *networking.NetworkPolicyList, s conversion.Scope) error { - return autoConvert_v1beta1_NetworkPolicyList_To_networking_NetworkPolicyList(in, out, s) -} - -func autoConvert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in *networking.NetworkPolicyList, out *NetworkPolicyList, s conversion.Scope) error { - out.ListMeta = in.ListMeta - out.Items = *(*[]NetworkPolicy)(unsafe.Pointer(&in.Items)) - return nil -} - -// Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList is an autogenerated conversion function. -func Convert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in *networking.NetworkPolicyList, out *NetworkPolicyList, s conversion.Scope) error { - return autoConvert_networking_NetworkPolicyList_To_v1beta1_NetworkPolicyList(in, out, s) -} - -func autoConvert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in *NetworkPolicyPeer, out *networking.NetworkPolicyPeer, s conversion.Scope) error { - out.AddressGroups = *(*[]string)(unsafe.Pointer(&in.AddressGroups)) - out.IPBlocks = *(*[]networking.IPBlock)(unsafe.Pointer(&in.IPBlocks)) - return nil -} - -// Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer is an autogenerated conversion function. -func Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in *NetworkPolicyPeer, out *networking.NetworkPolicyPeer, s conversion.Scope) error { - return autoConvert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(in, out, s) -} - -func autoConvert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in *networking.NetworkPolicyPeer, out *NetworkPolicyPeer, s conversion.Scope) error { - out.AddressGroups = *(*[]string)(unsafe.Pointer(&in.AddressGroups)) - out.IPBlocks = *(*[]IPBlock)(unsafe.Pointer(&in.IPBlocks)) - return nil -} - -// Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer is an autogenerated conversion function. -func Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in *networking.NetworkPolicyPeer, out *NetworkPolicyPeer, s conversion.Scope) error { - return autoConvert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in, out, s) -} - -func autoConvert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in *NetworkPolicyRule, out *networking.NetworkPolicyRule, s conversion.Scope) error { - out.Direction = networking.Direction(in.Direction) - if err := Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(&in.From, &out.From, s); err != nil { - return err - } - if err := Convert_v1beta1_NetworkPolicyPeer_To_networking_NetworkPolicyPeer(&in.To, &out.To, s); err != nil { - return err - } - out.Services = *(*[]networking.Service)(unsafe.Pointer(&in.Services)) - out.Priority = in.Priority - out.Action = (*v1alpha1.RuleAction)(unsafe.Pointer(in.Action)) - return nil -} - -// Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule is an autogenerated conversion function. -func Convert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in *NetworkPolicyRule, out *networking.NetworkPolicyRule, s conversion.Scope) error { - return autoConvert_v1beta1_NetworkPolicyRule_To_networking_NetworkPolicyRule(in, out, s) -} - -func autoConvert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in *networking.NetworkPolicyRule, out *NetworkPolicyRule, s conversion.Scope) error { - out.Direction = Direction(in.Direction) - if err := Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(&in.From, &out.From, s); err != nil { - return err - } - if err := Convert_networking_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(&in.To, &out.To, s); err != nil { - return err - } - out.Services = *(*[]Service)(unsafe.Pointer(&in.Services)) - out.Priority = in.Priority - out.Action = (*v1alpha1.RuleAction)(unsafe.Pointer(in.Action)) - return nil -} - -// Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule is an autogenerated conversion function. -func Convert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in *networking.NetworkPolicyRule, out *NetworkPolicyRule, s conversion.Scope) error { - return autoConvert_networking_NetworkPolicyRule_To_v1beta1_NetworkPolicyRule(in, out, s) -} - -func autoConvert_v1beta1_PodReference_To_networking_PodReference(in *PodReference, out *networking.PodReference, s conversion.Scope) error { - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} - -// Convert_v1beta1_PodReference_To_networking_PodReference is an autogenerated conversion function. -func Convert_v1beta1_PodReference_To_networking_PodReference(in *PodReference, out *networking.PodReference, s conversion.Scope) error { - return autoConvert_v1beta1_PodReference_To_networking_PodReference(in, out, s) -} - -func autoConvert_networking_PodReference_To_v1beta1_PodReference(in *networking.PodReference, out *PodReference, s conversion.Scope) error { - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} - -// Convert_networking_PodReference_To_v1beta1_PodReference is an autogenerated conversion function. -func Convert_networking_PodReference_To_v1beta1_PodReference(in *networking.PodReference, out *PodReference, s conversion.Scope) error { - return autoConvert_networking_PodReference_To_v1beta1_PodReference(in, out, s) -} - -func autoConvert_v1beta1_Service_To_networking_Service(in *Service, out *networking.Service, s conversion.Scope) error { - out.Protocol = (*networking.Protocol)(unsafe.Pointer(in.Protocol)) - out.Port = (*intstr.IntOrString)(unsafe.Pointer(in.Port)) - return nil -} - -// Convert_v1beta1_Service_To_networking_Service is an autogenerated conversion function. -func Convert_v1beta1_Service_To_networking_Service(in *Service, out *networking.Service, s conversion.Scope) error { - return autoConvert_v1beta1_Service_To_networking_Service(in, out, s) -} - -func autoConvert_networking_Service_To_v1beta1_Service(in *networking.Service, out *Service, s conversion.Scope) error { - out.Protocol = (*Protocol)(unsafe.Pointer(in.Protocol)) - out.Port = (*intstr.IntOrString)(unsafe.Pointer(in.Port)) - return nil -} - -// Convert_networking_Service_To_v1beta1_Service is an autogenerated conversion function. -func Convert_networking_Service_To_v1beta1_Service(in *networking.Service, out *Service, s conversion.Scope) error { - return autoConvert_networking_Service_To_v1beta1_Service(in, out, s) -} diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go index e5d0a965e3f..bcb78a85ac7 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go @@ -21,20 +21,24 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "github.com/vmware-tanzu/antrea/pkg/apis/networking" + "github.com/vmware-tanzu/antrea/pkg/apis/controlplane" secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" antreatypes "github.com/vmware-tanzu/antrea/pkg/controller/types" ) +var ( + selectorA = metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} + selectorB = metav1.LabelSelector{MatchLabels: map[string]string{"foo2": "bar2"}} + selectorC = metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} + selectorD = metav1.LabelSelector{MatchLabels: map[string]string{"foo4": "bar4"}} +) + func TestProcessAntreaNetworkPolicy(t *testing.T) { p10 := float64(10) appTier := antreatypes.TierApplication allowAction := secv1alpha1.RuleActionAllow - protocolTCP := networking.ProtocolTCP + protocolTCP := controlplane.ProtocolTCP intstr80, intstr81 := intstr.FromInt(80), intstr.FromInt(81) - selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} - selectorB := metav1.LabelSelector{MatchLabels: map[string]string{"foo2": "bar2"}} - selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} tests := []struct { name string inputPolicy *secv1alpha1.NetworkPolicy @@ -91,13 +95,13 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { Namespace: "ns1", Priority: &p10, TierPriority: &appTier, - Rules: []networking.NetworkPolicyRule{ + Rules: []controlplane.NetworkPolicyRule{ { - Direction: networking.DirectionIn, - From: networking.NetworkPolicyPeer{ + Direction: controlplane.DirectionIn, + From: controlplane.NetworkPolicyPeer{ AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, - Services: []networking.Service{ + Services: []controlplane.Service{ { Protocol: &protocolTCP, Port: &intstr80, @@ -107,11 +111,11 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { Action: &allowAction, }, { - Direction: networking.DirectionOut, - To: networking.NetworkPolicyPeer{ + Direction: controlplane.DirectionOut, + To: controlplane.NetworkPolicyPeer{ AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, nil).NormalizedName)}, }, - Services: []networking.Service{ + Services: []controlplane.Service{ { Protocol: &protocolTCP, Port: &intstr81, @@ -171,13 +175,13 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { Namespace: "ns2", Priority: &p10, TierPriority: &appTier, - Rules: []networking.NetworkPolicyRule{ + Rules: []controlplane.NetworkPolicyRule{ { - Direction: networking.DirectionIn, - From: networking.NetworkPolicyPeer{ + Direction: controlplane.DirectionIn, + From: controlplane.NetworkPolicyPeer{ AddressGroups: []string{getNormalizedUID(toGroupSelector("ns2", &selectorB, nil, nil).NormalizedName)}, }, - Services: []networking.Service{ + Services: []controlplane.Service{ { Protocol: &protocolTCP, Port: &intstr80, @@ -187,11 +191,11 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { Action: &allowAction, }, { - Direction: networking.DirectionIn, - From: networking.NetworkPolicyPeer{ + Direction: controlplane.DirectionIn, + From: controlplane.NetworkPolicyPeer{ AddressGroups: []string{getNormalizedUID(toGroupSelector("", nil, &selectorC, nil).NormalizedName)}, }, - Services: []networking.Service{ + Services: []controlplane.Service{ { Protocol: &protocolTCP, Port: &intstr81, @@ -225,3 +229,99 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { }) } } + +func TestAddANP(t *testing.T) { + p10 := float64(10) + appTier := antreatypes.TierApplication + allowAction := secv1alpha1.RuleActionAllow + protocolTCP := controlplane.ProtocolTCP + intstr80 := intstr.FromInt(80) + int80 := intstr.FromInt(80) + selectorAll := metav1.LabelSelector{} + matchAllPeerEgress := matchAllPeer + matchAllPeerEgress.AddressGroups = []string{getNormalizedUID(toGroupSelector("", nil, &selectorAll, nil).NormalizedName)} + tests := []struct { + name string + inputPolicy *secv1alpha1.NetworkPolicy + expPolicy *antreatypes.NetworkPolicy + expAppliedToGroups int + expAddressGroups int + }{ + { + name: "application-tier-policy", + inputPolicy: &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Namespace: "nsA", Name: "anpA", UID: "uidA"}, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + {PodSelector: &selectorA}, + }, + Priority: p10, + Tier: "Application", + Ingress: []secv1alpha1.Rule{ + { + Ports: []secv1alpha1.NetworkPolicyPort{ + { + Port: &intstr80, + }, + }, + From: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorB, + NamespaceSelector: &selectorC, + ExternalEntitySelector: &selectorD, + }, + }, + Action: &allowAction, + }, + }, + }, + }, + expPolicy: &antreatypes.NetworkPolicy{ + UID: "uidA", + Name: "anpA", + Namespace: "nsA", + Priority: &p10, + TierPriority: &appTier, + Rules: []controlplane.NetworkPolicyRule{ + { + Direction: controlplane.DirectionIn, + From: controlplane.NetworkPolicyPeer{ + AddressGroups: []string{getNormalizedUID(toGroupSelector("", &selectorB, &selectorC, &selectorD).NormalizedName)}, + }, + Services: []controlplane.Service{ + { + Protocol: &protocolTCP, + Port: &int80, + }, + }, + Priority: 0, + Action: &allowAction, + }, + }, + AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &selectorA, nil, nil).NormalizedName)}, + }, + expAppliedToGroups: 1, + expAddressGroups: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, npc := newController() + npc.addANP(tt.inputPolicy) + key, _ := keyFunc(tt.inputPolicy) + actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(key) + actualPolicy := actualPolicyObj.(*antreatypes.NetworkPolicy) + if !reflect.DeepEqual(actualPolicy, tt.expPolicy) { + t.Errorf("addANP() got %v, want %v", actualPolicy, tt.expPolicy) + } + + if actualAddressGroups := len(npc.addressGroupStore.List()); actualAddressGroups != tt.expAddressGroups { + t.Errorf("len(addressGroupStore.List()) got %v, want %v", actualAddressGroups, tt.expAddressGroups) + } + + if actualAppliedToGroups := len(npc.appliedToGroupStore.List()); actualAppliedToGroups != tt.expAppliedToGroups { + t.Errorf("len(appliedToGroupStore.List()) got %v, want %v", actualAppliedToGroups, tt.expAppliedToGroups) + } + }) + } +} diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index 98fa64207cd..a9c683d2f54 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -1346,25 +1346,25 @@ func podToMemberPod(pod *v1.Pod, includeIP, includePodRef bool) *controlplane.Gr return memberPod } -func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity, includeRef bool) *networking.GroupMember { - memberEntity := &networking.GroupMember{} +func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity, includeRef bool) *controlplane.GroupMember { + memberEntity := &controlplane.GroupMember{} for _, endpoint := range ee.Spec.Endpoints { - var networkingPorts []networking.NamedPort + var networkingPorts []controlplane.NamedPort for _, port := range endpoint.Ports { - networkingPorts = append(networkingPorts, networking.NamedPort{ + networkingPorts = append(networkingPorts, controlplane.NamedPort{ Port: port.Port, Name: port.Name, - Protocol: networking.Protocol(port.Protocol), + Protocol: controlplane.Protocol(port.Protocol), }) } - ep := networking.Endpoint{ + ep := controlplane.Endpoint{ IP: ipStrToIPAddress(endpoint.IP), Ports: networkingPorts, } memberEntity.Endpoints = append(memberEntity.Endpoints, ep) } if includeRef { - entityRef := networking.ExternalEntityReference{ + entityRef := controlplane.ExternalEntityReference{ Name: ee.Name, Namespace: ee.Namespace, } @@ -1464,7 +1464,7 @@ func (n *NetworkPolicyController) syncAppliedToGroup(key string) error { scheduledExtEntityNum++ entitySet := memberSetByNode[extEntity.Spec.ExternalNode] if entitySet == nil { - entitySet = networking.GroupMemberSet{} + entitySet = controlplane.GroupMemberSet{} } entitySet.Insert(externalEntityToGroupMember(extEntity, true)) memberSetByNode[extEntity.Spec.ExternalNode] = entitySet diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index 9af29e0d37b..0fd76bfa590 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -38,6 +38,7 @@ import ( "github.com/vmware-tanzu/antrea/pkg/apis/controlplane" "github.com/vmware-tanzu/antrea/pkg/apis/core/v1alpha1" + secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" "github.com/vmware-tanzu/antrea/pkg/apiserver/storage" fakeversioned "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned/fake" crdinformers "github.com/vmware-tanzu/antrea/pkg/client/informers/externalversions" @@ -65,6 +66,7 @@ var ( type networkPolicyController struct { *NetworkPolicyController podStore cache.Store + externalEntityStore cache.Store namespaceStore cache.Store networkPolicyStore cache.Store cnpStore cache.Store @@ -102,6 +104,7 @@ func newController(objects ...runtime.Object) (*fake.Clientset, *networkPolicyCo return client, &networkPolicyController{ npController, informerFactory.Core().V1().Pods().Informer().GetStore(), + crdInformerFactory.Core().V1alpha1().ExternalEntities().Informer().GetStore(), informerFactory.Core().V1().Namespaces().Informer().GetStore(), informerFactory.Networking().V1().NetworkPolicies().Informer().GetStore(), crdInformerFactory.Security().V1alpha1().ClusterNetworkPolicies().Informer().GetStore(), @@ -1213,6 +1216,143 @@ func TestDeletePod(t *testing.T) { assert.False(t, updatedAddrGroup.Pods.Has(memberPod2)) } +func TestAddExternalEntity(t *testing.T) { + selectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"group": "appliedTo"}, + } + selectorIn := metav1.LabelSelector{ + MatchLabels: map[string]string{"inGroup": "inAddress"}, + } + selectorOut := metav1.LabelSelector{ + MatchLabels: map[string]string{"outGroup": "outAddress"}, + } + allowAction := secv1alpha1.RuleActionAllow + appliedPod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "podA", + Namespace: "nsA", + Labels: map[string]string{ + "group": "appliedTo", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{{ + Name: "container-1", + }}, + NodeName: "nodeA", + }, + Status: corev1.PodStatus{ + Conditions: []corev1.PodCondition{ + { + Type: corev1.PodReady, + Status: corev1.ConditionTrue, + }, + }, + PodIP: "1.2.3.4", + }, + } + testANPObj := &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "anpA", + Namespace: "nsA", + }, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorSpec, + }, + }, + Ingress: []secv1alpha1.Rule{ + { + From: []secv1alpha1.NetworkPolicyPeer{ + { + ExternalEntitySelector: &selectorIn, + }, + }, + Action: &allowAction, + }, + }, + Egress: []secv1alpha1.Rule{ + { + To: []secv1alpha1.NetworkPolicyPeer{ + { + ExternalEntitySelector: &selectorOut, + }, + }, + Action: &allowAction, + }, + }, + }, + } + tests := []struct { + name string + addedExternalEntity *v1alpha1.ExternalEntity + inAddressGroupMatch bool + outAddressGroupMatch bool + }{ + { + "no-match-ee", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeA", + Namespace: "nsA", + Labels: map[string]string{"group": "none"}, + }, + }, + false, + false, + }, + { + "ee-match-ingress", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeB", + Namespace: "nsA", + Labels: map[string]string{"inGroup": "inAddress"}, + }, + }, + true, + false, + }, + { + "ee-match-ingress-egress", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeC", + Namespace: "nsA", + Labels: map[string]string{ + "inGroup": "inAddress", + "outGroup": "outAddress", + }, + }, + }, + true, + true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, npc := newController() + npc.addANP(testANPObj) + npc.podStore.Add(appliedPod) + npc.externalEntityStore.Add(tt.addedExternalEntity) + appGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorSpec, nil, nil).NormalizedName) + inGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorIn).NormalizedName) + outGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorOut).NormalizedName) + npc.syncAppliedToGroup(appGroupID) + npc.syncAddressGroup(inGroupID) + npc.syncAddressGroup(outGroupID) + updatedInAddrGroupObj, _, _ := npc.addressGroupStore.Get(inGroupID) + updatedInAddrGroup := updatedInAddrGroupObj.(*antreatypes.AddressGroup) + updatedOutAddrGroupObj, _, _ := npc.addressGroupStore.Get(outGroupID) + updatedOutAddrGroup := updatedOutAddrGroupObj.(*antreatypes.AddressGroup) + member := externalEntityToGroupMember(tt.addedExternalEntity, true) + assert.Equal(t, tt.inAddressGroupMatch, updatedInAddrGroup.GroupMembers.Has(member)) + assert.Equal(t, tt.outAddressGroupMatch, updatedOutAddrGroup.GroupMembers.Has(member)) + }) + } +} + func TestAddNamespace(t *testing.T) { selectorSpec := metav1.LabelSelector{} selectorIn := metav1.LabelSelector{ @@ -1554,7 +1694,111 @@ func TestFilterAddressGroupsForPodOrExternalEntity(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expectedGroups, npc.filterAddressGroupsForPodOrExternalEntity(tt.toMatch), - "Filtered AddressGroup does not match expectation") + "Filtered AddressGroups does not match expectation") + }) + } +} + +func TestFilterAppliedToGroupsForPodOrExternalEntity(t *testing.T) { + selectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"purpose": "test-select"}, + } + eeSelectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"platform": "aws"}, + } + ns1 := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ns1", + Labels: map[string]string{"purpose": "test-select"}, + }, + } + ns2 := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ns2", + }, + } + atGrp1 := &antreatypes.AppliedToGroup{ + UID: "uid1", + Name: "ATGrp1", + Selector: *toGroupSelector("ns1", &selectorSpec, nil, nil), + } + atGrp2 := &antreatypes.AppliedToGroup{ + UID: "uid2", + Name: "ATGrp2", + Selector: *toGroupSelector("ns1", nil, nil, &eeSelectorSpec), + } + atGrp3 := &antreatypes.AppliedToGroup{ + UID: "uid3", + Name: "ATGrp3", + Selector: *toGroupSelector("", nil, &selectorSpec, nil), + } + atGrp4 := &antreatypes.AppliedToGroup{ + UID: "uid4", + Name: "ATGrp4", + Selector: *toGroupSelector("", &selectorSpec, &selectorSpec, nil), + } + + pod1 := getPod("pod1", "ns1", "node1", "1.1.1.1", false) + pod1.Labels = map[string]string{"purpose": "test-select"} + pod2 := getPod("pod2", "ns1", "node1", "1.1.1.2", false) + pod3 := getPod("pod3", "ns2", "node1", "1.1.1.3", false) + ee1 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ee1", + Namespace: "ns1", + Labels: map[string]string{"platform": "aws"}, + }, + } + ee2 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ee2", + Namespace: "ns1", + Labels: map[string]string{"platform": "gke"}, + }, + } + tests := []struct { + name string + toMatch metav1.Object + expectedGroups sets.String + }{ + { + "pod-match-selector-match-ns", + pod1, + sets.NewString("ATGrp1", "ATGrp3", "ATGrp4"), + }, + { + "pod-unmatch-selector-match-ns", + pod2, + sets.NewString("ATGrp3"), + }, + { + "pod-unmatch-selector-unmatch-ns", + pod3, + sets.String{}, + }, + { + "externalEntity-match-selector-match-ns", + ee1, + sets.NewString("ATGrp2", "ATGrp3"), + }, + { + "externalEntity-unmatch-selector-match-ns", + ee2, + sets.NewString("ATGrp3"), + }, + } + _, npc := newController() + npc.appliedToGroupStore.Create(atGrp1) + npc.appliedToGroupStore.Create(atGrp2) + npc.appliedToGroupStore.Create(atGrp3) + npc.appliedToGroupStore.Create(atGrp4) + npc.namespaceStore.Add(ns1) + npc.namespaceStore.Add(ns2) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expectedGroups, npc.filterAppliedToGroupsForPodOrExternalEntity(tt.toMatch), + "Filtered AppliedTo Groups does not match expectation") }) } } From 8781e7e4b94d85d1c4f8e4401322ec2af3f68674 Mon Sep 17 00:00:00 2001 From: Yang Ding Date: Wed, 2 Sep 2020 11:46:05 -0700 Subject: [PATCH 5/6] Address comments --- go.mod | 1 - pkg/agent/controller/networkpolicy/cache.go | 6 +- .../controller/networkpolicy/reconciler.go | 2 +- .../networkpolicy/antreanetworkpolicy.go | 4 +- .../networkpolicy/antreanetworkpolicy_test.go | 58 +++++++++++++++++ .../networkpolicy/networkpolicy_controller.go | 64 +++++++++---------- .../networkpolicy_controller_test.go | 2 +- pkg/controller/types/networkpolicy.go | 8 ++- 8 files changed, 100 insertions(+), 45 deletions(-) diff --git a/go.mod b/go.mod index cb117f15217..8545151ed77 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,6 @@ require ( github.com/gogo/protobuf v1.3.1 github.com/golang/mock v1.4.3 github.com/golang/protobuf v1.3.2 - github.com/google/go-cmp v0.4.0 github.com/google/uuid v1.1.1 github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd github.com/pkg/errors v0.9.1 diff --git a/pkg/agent/controller/networkpolicy/cache.go b/pkg/agent/controller/networkpolicy/cache.go index 9e89b1cde02..94240c29894 100644 --- a/pkg/agent/controller/networkpolicy/cache.go +++ b/pkg/agent/controller/networkpolicy/cache.go @@ -409,15 +409,11 @@ func (c *ruleCache) addAddressGroupLocked(group *v1beta1.AddressGroup) error { for i := range group.Pods { // Must not store address of loop iterator variable as it's the same // address taking different values in each loop iteration, otherwise - // podSet would eventually contain only the last value. + // groupMemberSet would eventually contain only the last value. // https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable groupMemberSet.Insert(group.Pods[i].ToGroupMember()) } for i := range group.GroupMembers { - // Must not store address of loop iterator variable as it's the same - // address taking different values in each loop iteration, otherwise - // podSet would eventually contain only the last value. - // https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable groupMemberSet.Insert(&group.GroupMembers[i]) } diff --git a/pkg/agent/controller/networkpolicy/reconciler.go b/pkg/agent/controller/networkpolicy/reconciler.go index 2a2cc8a151c..46b7116c548 100644 --- a/pkg/agent/controller/networkpolicy/reconciler.go +++ b/pkg/agent/controller/networkpolicy/reconciler.go @@ -541,7 +541,7 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, memberByServicesMap, servicesMap := groupMembersByServices(newRule.Services, newRule.ToAddresses) // Same as the process in `add`, we must ensure the group for the original services is present - // in podsByServicesMap, so that this group won't be removed and its "From" will be updated. + // in memberByServicesMap, so that this group won't be removed and its "From" will be updated. svcKey := normalizeServices(newRule.Services) if _, exists := memberByServicesMap[svcKey]; !exists { memberByServicesMap[svcKey] = v1beta1.NewGroupMemberSet() diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy.go b/pkg/controller/networkpolicy/antreanetworkpolicy.go index 35a1c66bfe5..f5fa10d6750 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy.go @@ -127,8 +127,8 @@ func (n *NetworkPolicyController) processAntreaNetworkPolicy(np *secv1alpha1.Net // Create AppliedToGroup for each AppliedTo present in // AntreaNetworkPolicy spec. for _, at := range np.Spec.AppliedTo { - groupName := n.createAppliedToGroup(np.Namespace, at.PodSelector, at.NamespaceSelector, at.ExternalEntitySelector) - appliedToGroupNames = append(appliedToGroupNames, groupName) + appliedToGroupNames = append(appliedToGroupNames, n.createAppliedToGroup( + np.Namespace, at.PodSelector, at.NamespaceSelector, at.ExternalEntitySelector)) } rules := make([]controlplane.NetworkPolicyRule, 0, len(np.Spec.Ingress)+len(np.Spec.Egress)) // Compute NetworkPolicyRule for Egress Rule. diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go index bcb78a85ac7..8a49206efcd 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go @@ -18,6 +18,7 @@ import ( "reflect" "testing" + "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" @@ -325,3 +326,60 @@ func TestAddANP(t *testing.T) { }) } } + +func TestDeleteANP(t *testing.T) { + selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} + anpObj := getANP() + apgID := getNormalizedUID(toGroupSelector("test-ns", &selectorA, nil, nil).NormalizedName) + _, npc := newController() + npc.addANP(anpObj) + npc.deleteANP(anpObj) + _, found, _ := npc.appliedToGroupStore.Get(apgID) + assert.False(t, found, "expected AppliedToGroup to be deleted") + adgs := npc.addressGroupStore.List() + assert.Len(t, adgs, 0, "expected empty AddressGroup list") + key, _ := keyFunc(anpObj) + _, found, _ = npc.internalNetworkPolicyStore.Get(key) + assert.False(t, found, "expected internal NetworkPolicy to be deleted") +} + +// util functions for testing. +func getANP() *secv1alpha1.NetworkPolicy { + p10 := float64(10) + allowAction := secv1alpha1.RuleActionAllow + selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} + selectorB := metav1.LabelSelector{MatchLabels: map[string]string{"foo2": "bar2"}} + selectorC := metav1.LabelSelector{MatchLabels: map[string]string{"foo3": "bar3"}} + ingressRules := []secv1alpha1.Rule{ + { + From: []secv1alpha1.NetworkPolicyPeer{ + { + NamespaceSelector: &selectorB, + }, + }, + Action: &allowAction, + }, + } + egressRules := []secv1alpha1.Rule{ + { + To: []secv1alpha1.NetworkPolicyPeer{ + { + ExternalEntitySelector: &selectorC, + }, + }, + Action: &allowAction, + }, + } + npObj := &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Namespace: "test-ns", Name: "test-anp"}, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + {PodSelector: &selectorA}, + }, + Priority: p10, + Ingress: ingressRules, + Egress: egressRules, + }, + } + return npObj +} diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index a9c683d2f54..6cb5a943f9c 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -21,13 +21,13 @@ package networkpolicy import ( "fmt" "net" + "reflect" "sort" "strconv" "strings" "sync" "time" - "github.com/google/go-cmp/cmp" uuid "github.com/satori/go.uuid" v1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -124,7 +124,7 @@ type NetworkPolicyController struct { namespaceListerSynced cache.InformerSynced externalEntityInformer corev1a1informers.ExternalEntityInformer - // externalEntityLister is able to list/get ExternalEnitities and is populated by the shared informer passed to + // externalEntityLister is able to list/get ExternalEntities and is populated by the shared informer passed to // NewNetworkPolicyController. externalEntityLister corev1a1listers.ExternalEntityLister // externalEntitySynced is a function which returns true if the ExternalEntity shared informer has been synced at least once. @@ -235,14 +235,6 @@ func NewNetworkPolicyController(kubeClient clientset.Interface, }, resyncPeriod, ) - externalEntityInformer.Informer().AddEventHandlerWithResyncPeriod( - cache.ResourceEventHandlerFuncs{ - AddFunc: n.addExternalEntity, - UpdateFunc: n.updateExternalEntity, - DeleteFunc: n.deleteExternalEntity, - }, - resyncPeriod, - ) // Add handlers for NetworkPolicy events. networkPolicyInformer.Informer().AddEventHandlerWithResyncPeriod( cache.ResourceEventHandlerFuncs{ @@ -276,6 +268,14 @@ func NewNetworkPolicyController(kubeClient clientset.Interface, }, resyncPeriod, ) + externalEntityInformer.Informer().AddEventHandlerWithResyncPeriod( + cache.ResourceEventHandlerFuncs{ + AddFunc: n.addExternalEntity, + UpdateFunc: n.updateExternalEntity, + DeleteFunc: n.deleteExternalEntity, + }, + resyncPeriod, + ) } return n } @@ -385,7 +385,7 @@ func (n *NetworkPolicyController) createAppliedToGroup(npNsName string, pSel, nS return appliedToGroupUID } -// labelsMatchGroupSelector matches a ExternalEntity or Pod's labels to the +// labelsMatchGroupSelector matches an ExternalEntity or Pod's labels to the // GroupSelector object and returns true, if and only if the labels // match any of the selector criteria present in the GroupSelector. func (n *NetworkPolicyController) labelsMatchGroupSelector(obj metav1.Object, ns *v1.Namespace, sel *antreatypes.GroupSelector) bool { @@ -432,7 +432,7 @@ func (n *NetworkPolicyController) labelsMatchGroupSelector(obj metav1.Object, ns } else if objSelector != nil { // Selector only has a PodSelector/ExternalEntitySelector and no sel.Namespace. // Pods/ExternalEntities must be matched from all Namespaces. - if !sel.PodSelector.Matches(labels.Set(obj.GetLabels())) { + if !objSelector.Matches(labels.Set(obj.GetLabels())) { // pod/ee labels do not match PodSelector/ExternalEntitySelector. return false } @@ -881,7 +881,7 @@ func (n *NetworkPolicyController) deletePod(old interface{}) { func (n *NetworkPolicyController) addExternalEntity(obj interface{}) { defer n.heartbeat("addExternalEntity") ee := obj.(*v1alpha1.ExternalEntity) - klog.V(2).Infof("Processing External Entity %s/%s ADD event, labels: %v", ee.Namespace, ee.Name, ee.Labels) + klog.V(2).Infof("Processing ExternalEntity %s/%s ADD event, labels: %v", ee.Namespace, ee.Name, ee.Labels) // Find all AppliedToGroup keys which match the ExternalEntity's labels. appliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(ee) // Find all AddressGroup keys which match the ExternalEntity's labels. @@ -904,11 +904,13 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ curEE := curObj.(*v1alpha1.ExternalEntity) klog.V(2).Infof("Processing ExternalEntity %s/%s UPDATE event, labels: %v", curEE.Namespace, curEE.Name, curEE.Labels) // No need to trigger processing of groups if there is no change in the - // Pod labels or Pods Node or Pods IP. + // ExternalEntity labels or ExternalEntity's Endpoints. labelsEqual := labels.Equals(labels.Set(oldEE.Labels), labels.Set(curEE.Labels)) + specEqual := reflect.DeepEqual(oldEE.Spec, curEE.Spec) // TODO: Right now two ExternalEntities are only considered equal if the list of Endpoints and - // all NamedPorts in each Endpoint are of the exact order. This constraint might be too strict. - if labelsEqual && cmp.Equal(oldEE.Spec, curEE.Spec) { + // all NamedPorts in each Endpoint are of the exact order. Considering implementing custom compare + // method for the ExternalEntity spec to solve this and improve performance. + if labelsEqual && specEqual { klog.V(4).Infof("No change in ExternalEntity %s/%s. Skipping NetworkPolicy evaluation.", curEE.Namespace, curEE.Name) return } @@ -923,7 +925,7 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ var addressGroupKeys sets.String // AppliedToGroup keys must be enqueued only if the ExternalEntity's spec has changed or // if ExternalEntity's label change causes it to match new Groups. - if !cmp.Equal(oldEE.Spec, curEE.Spec) { + if !specEqual { appliedToGroupKeys = oldAppliedToGroupKeySet.Union(curAppliedToGroupKeySet) } else if !labelsEqual { // No need to enqueue common AppliedToGroups as they already have latest Pod @@ -932,7 +934,7 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ } // AddressGroup keys must be enqueued only if the ExternalEntity's spec has changed or // if ExternalEntity's label change causes it to match new Groups. - if !cmp.Equal(oldEE.Spec, curEE.Spec) { + if !specEqual { addressGroupKeys = oldAddressGroupKeySet.Union(curAddressGroupKeySet) } else if !labelsEqual { // No need to enqueue common AddressGroups as they already have latest Pod @@ -947,7 +949,7 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ } } -// deletePod retrieves all AddressGroups and AppliedToGroups which match the Pod's +// deleteExternalEntity retrieves all AddressGroups and AppliedToGroups which match the ExternalEntity's // labels and enqueues the groups key for further processing. func (n *NetworkPolicyController) deleteExternalEntity(old interface{}) { ee, ok := old.(*v1alpha1.ExternalEntity) @@ -1298,7 +1300,7 @@ func (n *NetworkPolicyController) syncAddressGroup(key string) error { podSet.Insert(podToMemberPod(pod, true, false)) } for _, entity := range externalEntities { - memberSet.Insert(externalEntityToGroupMember(entity, true)) + memberSet.Insert(externalEntityToGroupMember(entity)) } updatedAddressGroup := &antreatypes.AddressGroup{ Name: addressGroup.Name, @@ -1346,7 +1348,7 @@ func podToMemberPod(pod *v1.Pod, includeIP, includePodRef bool) *controlplane.Gr return memberPod } -func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity, includeRef bool) *controlplane.GroupMember { +func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity) *controlplane.GroupMember { memberEntity := &controlplane.GroupMember{} for _, endpoint := range ee.Spec.Endpoints { var networkingPorts []controlplane.NamedPort @@ -1363,13 +1365,11 @@ func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity, includeRef bool) * } memberEntity.Endpoints = append(memberEntity.Endpoints, ep) } - if includeRef { - entityRef := controlplane.ExternalEntityReference{ - Name: ee.Name, - Namespace: ee.Namespace, - } - memberEntity.ExternalEntity = &entityRef + entityRef := controlplane.ExternalEntityReference{ + Name: ee.Name, + Namespace: ee.Namespace, } + memberEntity.ExternalEntity = &entityRef return memberEntity } @@ -1380,8 +1380,7 @@ func (n *NetworkPolicyController) processSelector(groupSelector antreatypes.Grou // Namespace presence indicates Pods and ExternalEnitities must be selected from the same Namespace. if groupSelector.PodSelector != nil { pods, _ = n.podLister.Pods(groupSelector.Namespace).List(groupSelector.PodSelector) - } - if groupSelector.ExternalEntitySelector != nil { + } else if groupSelector.ExternalEntitySelector != nil { externalEntities, _ = n.externalEntityLister.ExternalEntities(groupSelector.Namespace).List(groupSelector.ExternalEntitySelector) } } else if groupSelector.NamespaceSelector != nil && (groupSelector.PodSelector != nil || groupSelector.ExternalEntitySelector != nil) { @@ -1391,14 +1390,13 @@ func (n *NetworkPolicyController) processSelector(groupSelector antreatypes.Grou if groupSelector.PodSelector != nil { nsPods, _ := n.podLister.Pods(ns.Name).List(groupSelector.PodSelector) pods = append(pods, nsPods...) - } - if groupSelector.ExternalEntitySelector != nil { + } else if groupSelector.ExternalEntitySelector != nil { nsExtEntities, _ := n.externalEntityLister.ExternalEntities(ns.Name).List(groupSelector.ExternalEntitySelector) externalEntities = append(externalEntities, nsExtEntities...) } } } else if groupSelector.NamespaceSelector != nil { - // All the Pods from Namespaces matching the nsSelector must be selected. + // All the Pods and EEs from Namespaces matching the nsSelector must be selected. namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) for _, ns := range namespaces { nsPods, _ := n.podLister.Pods(ns.Name).List(labels.Everything()) @@ -1466,7 +1464,7 @@ func (n *NetworkPolicyController) syncAppliedToGroup(key string) error { if entitySet == nil { entitySet = controlplane.GroupMemberSet{} } - entitySet.Insert(externalEntityToGroupMember(extEntity, true)) + entitySet.Insert(externalEntityToGroupMember(extEntity)) memberSetByNode[extEntity.Spec.ExternalNode] = entitySet appGroupNodeNames.Insert(extEntity.Spec.ExternalNode) } diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index 0fd76bfa590..89b009f51fd 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -1346,7 +1346,7 @@ func TestAddExternalEntity(t *testing.T) { updatedInAddrGroup := updatedInAddrGroupObj.(*antreatypes.AddressGroup) updatedOutAddrGroupObj, _, _ := npc.addressGroupStore.Get(outGroupID) updatedOutAddrGroup := updatedOutAddrGroupObj.(*antreatypes.AddressGroup) - member := externalEntityToGroupMember(tt.addedExternalEntity, true) + member := externalEntityToGroupMember(tt.addedExternalEntity) assert.Equal(t, tt.inAddressGroupMatch, updatedInAddrGroup.GroupMembers.Has(member)) assert.Equal(t, tt.outAddressGroupMatch, updatedOutAddrGroup.GroupMembers.Has(member)) }) diff --git a/pkg/controller/types/networkpolicy.go b/pkg/controller/types/networkpolicy.go index 6713c9f50ba..b740177117b 100644 --- a/pkg/controller/types/networkpolicy.go +++ b/pkg/controller/types/networkpolicy.go @@ -54,12 +54,16 @@ type GroupSelector struct { // If Namespace is set, NamespaceSelector can not be set. It means only Pods in this Namespace will be matched. Namespace string // This is a label selector which selects Pods. If Namespace is also set, it selects the Pods in the Namespace. - // If NamespaceSelector is also set, it selects the Pods in the Namespaces selected by NamespaceSelector. + // If NamespaceSelector is set instead, it selects the Pods in the Namespaces selected by NamespaceSelector. // If Namespace and NamespaceSelector both are unset, it selects the Pods in all the Namespaces. PodSelector labels.Selector // This is a label selector which selects Namespaces. It this field is set, Namespace can not be set. NamespaceSelector labels.Selector - // This is a label selector which selects external entities. + // This is a label selector which selects ExternalEntities. Within a group, ExternalEntitySelector cannot be + // set concurrently with PodSelector. If Namespace is also set, it selects the ExternalEntities in the Namespace. + // If NamespaceSelector is set instead, it selects ExternalEntities in the Namespaces selected by NamespaceSelector. + // If Namespace and NamespaceSelector both are unset, it selects the ExternalEntities in all the Namespaces. + // TODO: Add validation in API to not allow externalEntitySelector and podSelector in the same group. ExternalEntitySelector labels.Selector } From e0b53a9ce1fec37f1811a53e44f01784d520970a Mon Sep 17 00:00:00 2001 From: Yang Ding Date: Tue, 8 Sep 2020 16:32:55 -0700 Subject: [PATCH 6/6] Resolve more comments --- .../controller/networkpolicy/reconciler.go | 31 ++- pkg/apis/controlplane/helper.go | 33 +++ pkg/apis/controlplane/sets.go | 18 -- pkg/apis/controlplane/v1beta1/helper.go | 33 +++ pkg/apis/controlplane/v1beta1/sets.go | 18 -- .../networkpolicy/antreanetworkpolicy_test.go | 37 ++++ .../networkpolicy/networkpolicy_controller.go | 17 +- .../networkpolicy_controller_test.go | 204 +++++++++++++++--- pkg/controller/types/networkpolicy.go | 2 +- 9 files changed, 309 insertions(+), 84 deletions(-) create mode 100644 pkg/apis/controlplane/helper.go create mode 100644 pkg/apis/controlplane/v1beta1/helper.go diff --git a/pkg/agent/controller/networkpolicy/reconciler.go b/pkg/agent/controller/networkpolicy/reconciler.go index 46b7116c548..6c496e78f07 100644 --- a/pkg/agent/controller/networkpolicy/reconciler.go +++ b/pkg/agent/controller/networkpolicy/reconciler.go @@ -748,7 +748,7 @@ func groupPodsByServices(services []v1beta1.Service, pods v1beta1.GroupMemberPod resolvedServices := make([]v1beta1.Service, len(services)) for podKey, pod := range pods { for i := range services { - resolvedServices[i] = *resolveService(&services[i], *pod.ToGroupMember()) + resolvedServices[i] = *resolveServiceForPod(&services[i], pod) } svcKey := normalizeServices(resolvedServices) if _, exists := podsByServicesMap[svcKey]; !exists { @@ -788,7 +788,7 @@ func groupMembersByServices(services []v1beta1.Service, memberSet v1beta1.GroupM resolvedServices := make([]v1beta1.Service, len(services)) for memberKey, member := range memberSet { for i := range services { - resolvedServices[i] = *resolveService(&services[i], *member) + resolvedServices[i] = *resolveService(&services[i], member) } svcKey := normalizeServices(resolvedServices) if _, exists := membersByServicesMap[svcKey]; !exists { @@ -884,9 +884,28 @@ func filterUnresolvablePort(in []v1beta1.Service) []v1beta1.Service { return out } -// resolveService resolves the port name of the provided service to a port number -// for the provided groupMember. -func resolveService(service *v1beta1.Service, member v1beta1.GroupMember) *v1beta1.Service { +// resolveServiceForPod resolves the port name of the provided service to a port number +// for the provided Pod. +func resolveServiceForPod(service *v1beta1.Service, pod *v1beta1.GroupMemberPod) *v1beta1.Service { + // If port is not specified or is already a number, return it as is. + if service.Port == nil || service.Port.Type == intstr.Int { + return service + } + for _, port := range pod.Ports { + if port.Name == service.Port.StrVal && port.Protocol == *service.Protocol { + resolvedPort := intstr.FromInt(int(port.Port)) + return &v1beta1.Service{Protocol: service.Protocol, Port: &resolvedPort} + } + } + klog.Warningf("Can not resolve port %s for Pod %v", service.Port.StrVal, pod) + // If not resolvable, return it as is. + // The Pods that cannot resolve it will be grouped together. + return service +} + +// resolveService resolves the port name of the provided service to a port number for the provided groupMember. +// This function should eventually supersede resolveServiceForPod. +func resolveService(service *v1beta1.Service, member *v1beta1.GroupMember) *v1beta1.Service { // If port is not specified or is already a number, return it as is. if service.Port == nil || service.Port.Type == intstr.Int { return service @@ -901,6 +920,6 @@ func resolveService(service *v1beta1.Service, member v1beta1.GroupMember) *v1bet } klog.Warningf("Can not resolve port %s for endpoints %v", service.Port.StrVal, member) // If not resolvable, return it as is. - // The Pods that cannot resolve it will be grouped together. + // The group members that cannot resolve it will be grouped together. return service } diff --git a/pkg/apis/controlplane/helper.go b/pkg/apis/controlplane/helper.go new file mode 100644 index 00000000000..20ddb4d9c0f --- /dev/null +++ b/pkg/apis/controlplane/helper.go @@ -0,0 +1,33 @@ +// Copyright 2020 Antrea Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package controlplane + +// Conversion functions between GroupMember and GroupMemberPod +func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { + return &GroupMemberPod{ + Pod: g.Pod, + IP: g.Endpoints[0].IP, + Ports: g.Endpoints[0].Ports, + } +} + +func (p *GroupMemberPod) ToGroupMember() *GroupMember { + return &GroupMember{ + Pod: p.Pod, + Endpoints: []Endpoint{ + {IP: p.IP, Ports: p.Ports}, + }, + } +} diff --git a/pkg/apis/controlplane/sets.go b/pkg/apis/controlplane/sets.go index 02f91bd67bc..9a2d341fffd 100644 --- a/pkg/apis/controlplane/sets.go +++ b/pkg/apis/controlplane/sets.go @@ -213,21 +213,3 @@ func (s GroupMemberSet) Items() []*GroupMember { } return res } - -// Conversion functions -func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { - return &GroupMemberPod{ - Pod: g.Pod, - IP: g.Endpoints[0].IP, - Ports: g.Endpoints[0].Ports, - } -} - -func (p *GroupMemberPod) ToGroupMember() *GroupMember { - return &GroupMember{ - Pod: p.Pod, - Endpoints: []Endpoint{ - {IP: p.IP, Ports: p.Ports}, - }, - } -} diff --git a/pkg/apis/controlplane/v1beta1/helper.go b/pkg/apis/controlplane/v1beta1/helper.go new file mode 100644 index 00000000000..5a3d4c2dd2c --- /dev/null +++ b/pkg/apis/controlplane/v1beta1/helper.go @@ -0,0 +1,33 @@ +// Copyright 2020 Antrea Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +// Conversion functions between GroupMember and GroupMemberPod +func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { + return &GroupMemberPod{ + Pod: g.Pod, + IP: g.Endpoints[0].IP, + Ports: g.Endpoints[0].Ports, + } +} + +func (p *GroupMemberPod) ToGroupMember() *GroupMember { + return &GroupMember{ + Pod: p.Pod, + Endpoints: []Endpoint{ + {IP: p.IP, Ports: p.Ports}, + }, + } +} diff --git a/pkg/apis/controlplane/v1beta1/sets.go b/pkg/apis/controlplane/v1beta1/sets.go index 275c7466b24..41b716ba1e1 100644 --- a/pkg/apis/controlplane/v1beta1/sets.go +++ b/pkg/apis/controlplane/v1beta1/sets.go @@ -224,21 +224,3 @@ func (s GroupMemberSet) Items() []*GroupMember { } return res } - -// Conversion functions -func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { - return &GroupMemberPod{ - Pod: g.Pod, - IP: g.Endpoints[0].IP, - Ports: g.Endpoints[0].Ports, - } -} - -func (p *GroupMemberPod) ToGroupMember() *GroupMember { - return &GroupMember{ - Pod: p.Pod, - Endpoints: []Endpoint{ - {IP: p.IP, Ports: p.Ports}, - }, - } -} diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go index 8a49206efcd..34458a0aa6a 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go @@ -383,3 +383,40 @@ func getANP() *secv1alpha1.NetworkPolicy { } return npObj } + +func getEETestANP(selectorAppliedTo, selectorIn, selectorOut metav1.LabelSelector) *secv1alpha1.NetworkPolicy { + allowAction := secv1alpha1.RuleActionAllow + return &secv1alpha1.NetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "anpA", + Namespace: "nsA", + }, + Spec: secv1alpha1.NetworkPolicySpec{ + AppliedTo: []secv1alpha1.NetworkPolicyPeer{ + { + PodSelector: &selectorAppliedTo, + }, + }, + Ingress: []secv1alpha1.Rule{ + { + From: []secv1alpha1.NetworkPolicyPeer{ + { + ExternalEntitySelector: &selectorIn, + }, + }, + Action: &allowAction, + }, + }, + Egress: []secv1alpha1.Rule{ + { + To: []secv1alpha1.NetworkPolicyPeer{ + { + ExternalEntitySelector: &selectorOut, + }, + }, + Action: &allowAction, + }, + }, + }, + } +} diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index 6cb5a943f9c..d6f94e149fd 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -148,7 +148,6 @@ type NetworkPolicyController struct { // anpLister is able to list/get AntreaNetworkPolicies and is populated by the shared informer passed to // NewNetworkPolicyController. anpLister seclisters.NetworkPolicyLister - // anpListerSynced is a function which returns true if the AntreaNetworkPolicies shared informer has been synced at least once. anpListerSynced cache.InformerSynced @@ -915,10 +914,10 @@ func (n *NetworkPolicyController) updateExternalEntity(oldObj, curObj interface{ return } // Find groups matching the old ExternalEntity's labels. + oldAppliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(oldEE) oldAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(oldEE) - oldAppliedToGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(oldEE) // Find groups matching the new ExternalEntity's labels. - curAppliedToGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(curEE) + curAppliedToGroupKeySet := n.filterAppliedToGroupsForPodOrExternalEntity(curEE) curAddressGroupKeySet := n.filterAddressGroupsForPodOrExternalEntity(curEE) // Create set to hold the group keys to enqueue. var appliedToGroupKeys sets.String @@ -969,7 +968,7 @@ func (n *NetworkPolicyController) deleteExternalEntity(old interface{}) { klog.V(2).Infof("Processing ExternalEntity %s/%s DELETE event, labels: %v", ee.Namespace, ee.Name, ee.Labels) // Find all AppliedToGroup keys which match the Pod's labels. - appliedToGroupKeys := n.filterAddressGroupsForPodOrExternalEntity(ee) + appliedToGroupKeys := n.filterAppliedToGroupsForPodOrExternalEntity(ee) // Find all AddressGroup keys which match the Pod's labels. addressGroupKeys := n.filterAddressGroupsForPodOrExternalEntity(ee) // Enqueue groups to their respective queues for group processing. @@ -1351,9 +1350,9 @@ func podToMemberPod(pod *v1.Pod, includeIP, includePodRef bool) *controlplane.Gr func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity) *controlplane.GroupMember { memberEntity := &controlplane.GroupMember{} for _, endpoint := range ee.Spec.Endpoints { - var networkingPorts []controlplane.NamedPort + var namedPorts []controlplane.NamedPort for _, port := range endpoint.Ports { - networkingPorts = append(networkingPorts, controlplane.NamedPort{ + namedPorts = append(namedPorts, controlplane.NamedPort{ Port: port.Port, Name: port.Name, Protocol: controlplane.Protocol(port.Protocol), @@ -1361,7 +1360,7 @@ func externalEntityToGroupMember(ee *v1alpha1.ExternalEntity) *controlplane.Grou } ep := controlplane.Endpoint{ IP: ipStrToIPAddress(endpoint.IP), - Ports: networkingPorts, + Ports: namedPorts, } memberEntity.Endpoints = append(memberEntity.Endpoints, ep) } @@ -1396,13 +1395,11 @@ func (n *NetworkPolicyController) processSelector(groupSelector antreatypes.Grou } } } else if groupSelector.NamespaceSelector != nil { - // All the Pods and EEs from Namespaces matching the nsSelector must be selected. + // All the Pods from Namespaces matching the nsSelector must be selected. namespaces, _ := n.namespaceLister.List(groupSelector.NamespaceSelector) for _, ns := range namespaces { nsPods, _ := n.podLister.Pods(ns.Name).List(labels.Everything()) pods = append(pods, nsPods...) - nsExtEntities, _ := n.externalEntityLister.ExternalEntities(ns.Name).List(labels.Everything()) - externalEntities = append(externalEntities, nsExtEntities...) } } else if groupSelector.PodSelector != nil { // Lack of Namespace and NamespaceSelector indicates Pods must be selected diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index 89b009f51fd..b3cee0aa46f 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -38,7 +38,6 @@ import ( "github.com/vmware-tanzu/antrea/pkg/apis/controlplane" "github.com/vmware-tanzu/antrea/pkg/apis/core/v1alpha1" - secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" "github.com/vmware-tanzu/antrea/pkg/apiserver/storage" fakeversioned "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned/fake" crdinformers "github.com/vmware-tanzu/antrea/pkg/client/informers/externalversions" @@ -1226,7 +1225,6 @@ func TestAddExternalEntity(t *testing.T) { selectorOut := metav1.LabelSelector{ MatchLabels: map[string]string{"outGroup": "outAddress"}, } - allowAction := secv1alpha1.RuleActionAllow appliedPod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "podA", @@ -1251,39 +1249,159 @@ func TestAddExternalEntity(t *testing.T) { PodIP: "1.2.3.4", }, } - testANPObj := &secv1alpha1.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{ - Name: "anpA", - Namespace: "nsA", - }, - Spec: secv1alpha1.NetworkPolicySpec{ - AppliedTo: []secv1alpha1.NetworkPolicyPeer{ - { - PodSelector: &selectorSpec, + testANPObj := getEETestANP(selectorSpec, selectorIn, selectorOut) + tests := []struct { + name string + addedExternalEntity *v1alpha1.ExternalEntity + inAddressGroupMatch bool + outAddressGroupMatch bool + }{ + { + "no-match-ee", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeA", + Namespace: "nsA", + Labels: map[string]string{"group": "none"}, }, }, - Ingress: []secv1alpha1.Rule{ - { - From: []secv1alpha1.NetworkPolicyPeer{ - { - ExternalEntitySelector: &selectorIn, - }, - }, - Action: &allowAction, + false, + false, + }, + { + "ee-match-ingress", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeB", + Namespace: "nsA", + Labels: map[string]string{"inGroup": "inAddress"}, }, }, - Egress: []secv1alpha1.Rule{ - { - To: []secv1alpha1.NetworkPolicyPeer{ - { - ExternalEntitySelector: &selectorOut, - }, + true, + false, + }, + { + "ee-match-ingress-egress", + &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeC", + Namespace: "nsA", + Labels: map[string]string{ + "inGroup": "inAddress", + "outGroup": "outAddress", }, - Action: &allowAction, }, }, + true, + true, }, } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, npc := newController() + npc.addANP(testANPObj) + npc.podStore.Add(appliedPod) + npc.externalEntityStore.Add(tt.addedExternalEntity) + appGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorSpec, nil, nil).NormalizedName) + inGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorIn).NormalizedName) + outGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorOut).NormalizedName) + + npc.addPod(appliedPod) + npc.addExternalEntity(tt.addedExternalEntity) + atGroups, addrGroups := getQueuedGroups(npc) + assert.Equal(t, true, atGroups.Has(appGroupID)) + assert.Equal(t, tt.inAddressGroupMatch, addrGroups.Has(inGroupID)) + assert.Equal(t, tt.outAddressGroupMatch, addrGroups.Has(outGroupID)) + + npc.syncAppliedToGroup(appGroupID) + npc.syncAddressGroup(inGroupID) + npc.syncAddressGroup(outGroupID) + updatedInAddrGroupObj, _, _ := npc.addressGroupStore.Get(inGroupID) + updatedInAddrGroup := updatedInAddrGroupObj.(*antreatypes.AddressGroup) + updatedOutAddrGroupObj, _, _ := npc.addressGroupStore.Get(outGroupID) + updatedOutAddrGroup := updatedOutAddrGroupObj.(*antreatypes.AddressGroup) + member := externalEntityToGroupMember(tt.addedExternalEntity) + assert.Equal(t, tt.inAddressGroupMatch, updatedInAddrGroup.GroupMembers.Has(member)) + assert.Equal(t, tt.outAddressGroupMatch, updatedOutAddrGroup.GroupMembers.Has(member)) + }) + } +} + +func TestUpdateExternalEntity(t *testing.T) { + selectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"group": "appliedTo"}, + } + selectorIn := metav1.LabelSelector{ + MatchLabels: map[string]string{"inGroup": "inAddress"}, + } + selectorOut := metav1.LabelSelector{ + MatchLabels: map[string]string{"outGroup": "outAddress"}, + } + selectorOut2 := metav1.LabelSelector{ + MatchLabels: map[string]string{"outGroup": "outAddress2"}, + } + testANPObj := getEETestANP(selectorSpec, selectorIn, selectorOut) + testANPObj2 := getEETestANP(selectorSpec, selectorIn, selectorOut2) + ee1 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeC", + Namespace: "nsA", + Labels: map[string]string{ + "outGroup": "outAddress", + }, + }, + } + ee2 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeC", + Namespace: "nsA", + Labels: map[string]string{ + "outGroup": "outAddress2", + }, + }, + } + ee3 := &v1alpha1.ExternalEntity{ + ObjectMeta: metav1.ObjectMeta{ + Name: "eeC", + Namespace: "nsA", + Labels: map[string]string{ + "outGroup": "outAddress3", + }, + }, + } + outGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorOut).NormalizedName) + outGroupID2 := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorOut2).NormalizedName) + _, npc := newController() + npc.addANP(testANPObj) + npc.addANP(testANPObj2) + npc.updateExternalEntity(ee3, ee1) + _, addrGroups := getQueuedGroups(npc) + assert.Equal(t, true, addrGroups.Has(outGroupID)) + assert.Equal(t, false, addrGroups.Has(outGroupID2)) + // outGroupID and outGroupID2 should both be queued (EE removed and EE added) + npc.updateExternalEntity(ee1, ee2) + _, addrGroups = getQueuedGroups(npc) + assert.Equal(t, true, addrGroups.Has(outGroupID)) + assert.Equal(t, true, addrGroups.Has(outGroupID2)) + // only outGroupID2 should be queued (EE removed) + npc.updateExternalEntity(ee2, ee3) + _, addrGroups = getQueuedGroups(npc) + assert.Equal(t, false, addrGroups.Has(outGroupID)) + assert.Equal(t, true, addrGroups.Has(outGroupID2)) + +} + +func TestDeleteExternalEntity(t *testing.T) { + selectorSpec := metav1.LabelSelector{ + MatchLabels: map[string]string{"group": "appliedTo"}, + } + selectorIn := metav1.LabelSelector{ + MatchLabels: map[string]string{"inGroup": "inAddress"}, + } + selectorOut := metav1.LabelSelector{ + MatchLabels: map[string]string{"outGroup": "outAddress"}, + } + testANPObj := getEETestANP(selectorSpec, selectorIn, selectorOut) tests := []struct { name string addedExternalEntity *v1alpha1.ExternalEntity @@ -1334,12 +1452,15 @@ func TestAddExternalEntity(t *testing.T) { t.Run(tt.name, func(t *testing.T) { _, npc := newController() npc.addANP(testANPObj) - npc.podStore.Add(appliedPod) npc.externalEntityStore.Add(tt.addedExternalEntity) - appGroupID := getNormalizedUID(toGroupSelector("nsA", &selectorSpec, nil, nil).NormalizedName) + npc.addExternalEntity(tt.addedExternalEntity) inGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorIn).NormalizedName) outGroupID := getNormalizedUID(toGroupSelector("nsA", nil, nil, &selectorOut).NormalizedName) - npc.syncAppliedToGroup(appGroupID) + npc.syncAddressGroup(inGroupID) + npc.syncAddressGroup(outGroupID) + + npc.externalEntityStore.Delete(tt.addedExternalEntity) + npc.deleteExternalEntity(tt.addedExternalEntity) npc.syncAddressGroup(inGroupID) npc.syncAddressGroup(outGroupID) updatedInAddrGroupObj, _, _ := npc.addressGroupStore.Get(inGroupID) @@ -1347,8 +1468,13 @@ func TestAddExternalEntity(t *testing.T) { updatedOutAddrGroupObj, _, _ := npc.addressGroupStore.Get(outGroupID) updatedOutAddrGroup := updatedOutAddrGroupObj.(*antreatypes.AddressGroup) member := externalEntityToGroupMember(tt.addedExternalEntity) - assert.Equal(t, tt.inAddressGroupMatch, updatedInAddrGroup.GroupMembers.Has(member)) - assert.Equal(t, tt.outAddressGroupMatch, updatedOutAddrGroup.GroupMembers.Has(member)) + + if tt.inAddressGroupMatch { + assert.Equal(t, false, updatedInAddrGroup.GroupMembers.Has(member)) + } + if tt.outAddressGroupMatch { + assert.Equal(t, false, updatedOutAddrGroup.GroupMembers.Has(member)) + } }) } } @@ -2725,6 +2851,22 @@ func TestDeleteFinalStateUnknownNetworkPolicy(t *testing.T) { assert.True(t, ok, "Missing event on channel") } +func getQueuedGroups(npc *networkPolicyController) (atGroups, addrGroups sets.String) { + atGroups, addrGroups = sets.NewString(), sets.NewString() + atLen, addrLen := npc.appliedToGroupQueue.Len(), npc.addressGroupQueue.Len() + for i := 0; i < atLen; i++ { + id, _ := npc.appliedToGroupQueue.Get() + atGroups.Insert(id.(string)) + npc.appliedToGroupQueue.Done(id) + } + for i := 0; i < addrLen; i++ { + id, _ := npc.addressGroupQueue.Get() + addrGroups.Insert(id.(string)) + npc.addressGroupQueue.Done(id) + } + return +} + func getK8sNetworkPolicyObj() *networkingv1.NetworkPolicy { ns := metav1.NamespaceDefault npName := "testing-1" diff --git a/pkg/controller/types/networkpolicy.go b/pkg/controller/types/networkpolicy.go index b740177117b..8ac68f38f8b 100644 --- a/pkg/controller/types/networkpolicy.go +++ b/pkg/controller/types/networkpolicy.go @@ -47,7 +47,7 @@ const ( // GroupSelector describes how to select Pods. type GroupSelector struct { - // The normalized name is calculated from Namespace, PodSelector, and NamespaceSelector. + // The normalized name is calculated from Namespace, PodSelector, ExternalEntitySelector and NamespaceSelector. // If multiple policies have same selectors, they should share this group by comparing NormalizedName. // It's also used to generate Name and UUID of group. NormalizedName string