From 904615f1f907480e701e1464be609c38a77444f9 Mon Sep 17 00:00:00 2001 From: Quan Tian Date: Tue, 15 Sep 2020 18:01:08 +0800 Subject: [PATCH] Fix name collision between Antrea NetworkPolicy and K8s NetworkPolicy NetworkPolicy in controlplane API group is the object that consumed by antrea-agents. Both Antrea NetworkPolicy and K8s NetworkPolicy will be converted to it. Currently, the namespace and name of the original NetworkPolicy are copied to the controlplane NetworkPolicy and / is used as the key func. Therefore, one K8s NetworkPolicy may overwrite the controlplane NetworkPolicy mapping to a Antrea NetworkPolicy that has the same namespace and name. This patch changes to use the UID of the original NetworkPolicy as the name and UID of the controlplane NetworkPolicy and keeps the namespace, name, UID, and type of the original NetworkPolicy in a new field "SourceRef". Besides, the controlplane NetworkPolicy is changed to cluster scoped like AppliedToGroups and AddressGroups. --- pkg/agent/controller/networkpolicy/cache.go | 133 ++--- .../controller/networkpolicy/cache_test.go | 181 +++--- .../networkpolicy/networkpolicy_controller.go | 8 +- .../networkpolicy_controller_test.go | 24 +- .../controller/networkpolicy/reconciler.go | 49 +- .../networkpolicy/reconciler_test.go | 94 +++- pkg/agent/controller/traceflow/packetin.go | 12 +- pkg/agent/openflow/client.go | 3 +- pkg/agent/openflow/network_policy.go | 22 +- pkg/agent/openflow/network_policy_test.go | 104 ++-- pkg/agent/openflow/testing/mock_openflow.go | 8 +- pkg/agent/types/networkpolicy.go | 19 +- pkg/apis/controlplane/helper.go | 10 + pkg/apis/controlplane/types.go | 25 + pkg/apis/controlplane/v1beta1/generated.pb.go | 520 +++++++++++++++--- pkg/apis/controlplane/v1beta1/generated.proto | 18 + pkg/apis/controlplane/v1beta1/helper.go | 10 + pkg/apis/controlplane/v1beta1/types.go | 26 + .../v1beta1/zz_generated.conversion.go | 39 ++ .../v1beta1/zz_generated.deepcopy.go | 21 + .../controlplane/zz_generated.deepcopy.go | 21 + pkg/apiserver/openapi/zz_generated.openapi.go | 50 +- .../networkpolicy/networkpolicy/rest.go | 20 +- .../v1beta1/controlplane_client.go | 4 +- .../v1beta1/fake/fake_controlplane_client.go | 4 +- .../v1beta1/fake/fake_networkpolicy.go | 10 +- .../controlplane/v1beta1/networkpolicy.go | 9 +- .../networkpolicy/antreanetworkpolicy.go | 18 +- .../networkpolicy/antreanetworkpolicy_test.go | 40 +- .../networkpolicy/clusternetworkpolicy.go | 17 +- .../clusternetworkpolicy_test.go | 95 +++- .../networkpolicy/endpoint_querier.go | 18 +- .../networkpolicy/networkpolicy_controller.go | 30 +- .../networkpolicy_controller_test.go | 210 ++++--- .../networkpolicy/store/networkpolicy.go | 5 +- .../networkpolicy/store/networkpolicy_test.go | 58 +- pkg/controller/types/networkpolicy.go | 9 +- 37 files changed, 1350 insertions(+), 594 deletions(-) diff --git a/pkg/agent/controller/networkpolicy/cache.go b/pkg/agent/controller/networkpolicy/cache.go index 94240c29894..831da42da55 100644 --- a/pkg/agent/controller/networkpolicy/cache.go +++ b/pkg/agent/controller/networkpolicy/cache.go @@ -23,7 +23,6 @@ import ( "sync" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/tools/cache" "k8s.io/klog" @@ -38,6 +37,7 @@ const ( appliedToGroupIndex = "appliedToGroup" addressGroupIndex = "addressGroup" policyIndex = "policy" + namespaceIndex = "namespace" ) // rule is the struct stored in ruleCache, it contains necessary information @@ -52,6 +52,8 @@ const ( type rule struct { // ID is calculated from the hash value of all other fields. ID string + // Reference to the original NetworkPolicy that the rule belongs to. + PolicyRef *v1beta1.NetworkPolicyReference // Direction of this rule. Direction v1beta1.Direction // Source Address of this rule, can't coexist with To. @@ -70,14 +72,6 @@ type rule struct { TierPriority *v1beta1.TierPriority // Targets of this rule. AppliedToGroups []string - // The parent Policy ID. Used to identify rules belong to a specified - // policy for deletion. - PolicyUID types.UID - // The metadata of parent Policy. Used to associate the rule with Policy - // for troubleshooting purpose (logging and CLI). - PolicyName string - // PolicyNamespace is empty for ClusterNetworkPolicy. - PolicyNamespace string } // hashRule calculates a string based on the rule's content. @@ -115,7 +109,7 @@ func (r *CompletedRule) String() string { // isAntreaNetworkPolicyRule returns true if the rule is part of a ClusterNetworkPolicy. func (r *CompletedRule) isAntreaNetworkPolicyRule() bool { - return r.PolicyPriority != nil + return r.PolicyRef.Type != v1beta1.K8sNetworkPolicy } // ruleCache caches Antrea AddressGroups, AppliedToGroups and NetworkPolicies, @@ -131,10 +125,6 @@ type ruleCache struct { // 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. - policyMap map[string]*types.NamespacedName - // rules is a storage that supports listing rules using multiple indexing functions. // rules is thread-safe. rules cache.Indexer @@ -146,13 +136,20 @@ type ruleCache struct { } func (c *ruleCache) getNetworkPolicies(namespace string) []v1beta1.NetworkPolicy { - ret := []v1beta1.NetworkPolicy{} - c.policyMapLock.RLock() - defer c.policyMapLock.RUnlock() - for uid, np := range c.policyMap { - if namespace == "" || np.Namespace == namespace { - ret = append(ret, *c.buildNetworkPolicyFromRules(uid)) - } + var ret []v1beta1.NetworkPolicy + rulesByPolicy := map[v1beta1.NetworkPolicyReference][]*rule{} + var objs []interface{} + if namespace == "" { + objs = c.rules.List() + } else { + objs, _ = c.rules.ByIndex(namespaceIndex, namespace) + } + for _, obj := range objs { + rule := obj.(*rule) + rulesByPolicy[*rule.PolicyRef] = append(rulesByPolicy[*rule.PolicyRef], rule) + } + for _, rules := range rulesByPolicy { + ret = append(ret, *c.buildNetworkPolicyFromRules(rules)) } return ret } @@ -160,34 +157,30 @@ func (c *ruleCache) getNetworkPolicies(namespace string) []v1beta1.NetworkPolicy // getNetworkPolicy looks up and returns the cached NetworkPolicy. // nil is returned if the specified NetworkPolicy is not found. func (c *ruleCache) getNetworkPolicy(npName, npNamespace string) *v1beta1.NetworkPolicy { - var npUID string - c.policyMapLock.Lock() - defer c.policyMapLock.Unlock() - for uid, np := range c.policyMap { - if np.Name == npName && np.Namespace == npNamespace { - npUID = uid - break + objs, _ := c.rules.ByIndex(namespaceIndex, npNamespace) + var rules []*rule + for _, obj := range objs { + rule := obj.(*rule) + if rule.PolicyRef.Name == npName { + rules = append(rules, rule) } } - if npUID == "" { + if len(rules) == 0 { // NetworkPolicy not found. return nil } - return c.buildNetworkPolicyFromRules(npUID) + return c.buildNetworkPolicyFromRules(rules) } -func (c *ruleCache) buildNetworkPolicyFromRules(uid string) *v1beta1.NetworkPolicy { +func (c *ruleCache) buildNetworkPolicyFromRules(rules []*rule) *v1beta1.NetworkPolicy { var np *v1beta1.NetworkPolicy - rules, _ := c.rules.ByIndex(policyIndex, uid) // Sort the rules by priority sort.Slice(rules, func(i, j int) bool { - r1 := rules[i].(*rule) - r2 := rules[j].(*rule) - return r1.Priority < r2.Priority + return rules[i].Priority < rules[j].Priority }) - for _, ruleObj := range rules { - np = addRuleToNetworkPolicy(np, ruleObj.(*rule)) + for _, rule := range rules { + np = addRuleToNetworkPolicy(np, rule) } return np } @@ -197,9 +190,11 @@ func (c *ruleCache) buildNetworkPolicyFromRules(uid string) *v1beta1.NetworkPoli func addRuleToNetworkPolicy(np *v1beta1.NetworkPolicy, rule *rule) *v1beta1.NetworkPolicy { if np == nil { np = &v1beta1.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{UID: rule.PolicyUID, - Name: rule.PolicyName, - Namespace: rule.PolicyNamespace}, + ObjectMeta: metav1.ObjectMeta{ + UID: rule.PolicyRef.UID, + Name: string(rule.PolicyRef.UID), + }, + SourceRef: rule.PolicyRef, AppliedToGroups: rule.AppliedToGroups, Priority: rule.PolicyPriority, TierPriority: rule.TierPriority, @@ -232,11 +227,11 @@ func (c *ruleCache) getAppliedNetworkPolicies(pod, namespace string) []v1beta1.N rules, _ := c.rules.ByIndex(appliedToGroupIndex, group) for _, ruleObj := range rules { rule := ruleObj.(*rule) - np, ok := npMap[string(rule.PolicyUID)] + np, ok := npMap[string(rule.PolicyRef.UID)] np = addRuleToNetworkPolicy(np, rule) if !ok { // First rule for this NetworkPolicy - npMap[string(rule.PolicyUID)] = np + npMap[string(rule.PolicyRef.UID)] = np } } } @@ -316,19 +311,25 @@ func appliedToGroupIndexFunc(obj interface{}) ([]string, error) { // It's provided to cache.Indexer to build an index of NetworkPolicy. func policyIndexFunc(obj interface{}) ([]string, error) { rule := obj.(*rule) - return []string{string(rule.PolicyUID)}, nil + return []string{string(rule.PolicyRef.UID)}, nil +} + +// namespaceIndexFunc knows how to get NetworkPolicy Namespace of a *rule. +// It's provided to cache.Indexer to build an index of NetworkPolicy. +func namespaceIndexFunc(obj interface{}) ([]string, error) { + rule := obj.(*rule) + return []string{rule.PolicyRef.Namespace}, nil } // newRuleCache returns a new *ruleCache. func newRuleCache(dirtyRuleHandler func(string), podUpdate <-chan v1beta1.PodReference) *ruleCache { rules := cache.NewIndexer( ruleKeyFunc, - cache.Indexers{addressGroupIndex: addressGroupIndexFunc, appliedToGroupIndex: appliedToGroupIndexFunc, policyIndex: policyIndexFunc}, + cache.Indexers{addressGroupIndex: addressGroupIndexFunc, appliedToGroupIndex: appliedToGroupIndexFunc, policyIndex: policyIndexFunc, namespaceIndex: namespaceIndexFunc}, ) cache := &ruleCache{ podSetByGroup: make(map[string]v1beta1.GroupMemberPodSet), addressSetByGroup: make(map[string]v1beta1.GroupMemberSet), - policyMap: make(map[string]*types.NamespacedName), rules: rules, dirtyRuleHandler: dirtyRuleHandler, podUpdates: podUpdate, @@ -563,41 +564,31 @@ func toRule(r *v1beta1.NetworkPolicyRule, policy *v1beta1.NetworkPolicy) *rule { PolicyPriority: policy.Priority, TierPriority: policy.TierPriority, AppliedToGroups: policy.AppliedToGroups, - PolicyUID: policy.UID, + PolicyRef: policy.SourceRef, } rule.ID = hashRule(rule) - rule.PolicyNamespace = policy.Namespace - rule.PolicyName = policy.Name return rule } // GetNetworkPolicyNum gets the number of NetworkPolicy. func (c *ruleCache) GetNetworkPolicyNum() int { - c.policyMapLock.RLock() - defer c.policyMapLock.RUnlock() - - return len(c.policyMap) + return len(c.rules.ListIndexFuncValues(policyIndex)) } // ReplaceNetworkPolicies atomically adds the given policies to the cache and deletes // the pre-existing policies that are not in the given policies from the cache. // It makes the cache in sync with the apiserver when restarting a watch. func (c *ruleCache) ReplaceNetworkPolicies(policies []*v1beta1.NetworkPolicy) { - c.policyMapLock.Lock() - defer c.policyMapLock.Unlock() - - oldKeys := make(sets.String, len(c.policyMap)) - for key := range c.policyMap { - oldKeys.Insert(key) - } + oldUIDs := c.rules.ListIndexFuncValues(policyIndex) + oldUIDSet := sets.NewString(oldUIDs...) for i := range policies { - oldKeys.Delete(string(policies[i].UID)) - c.addNetworkPolicyLocked(policies[i]) + oldUIDSet.Delete(string(policies[i].UID)) + c.AddNetworkPolicy(policies[i]) } - for key := range oldKeys { - c.deleteNetworkPolicyLocked(key) + for key := range oldUIDSet { + c.deleteNetworkPolicy(key) } return } @@ -607,14 +598,6 @@ func (c *ruleCache) ReplaceNetworkPolicies(policies []*v1beta1.NetworkPolicy) { // watcher reconnects to the Apiserver, we use the same processing as // UpdateNetworkPolicy to ensure orphan rules are removed. func (c *ruleCache) AddNetworkPolicy(policy *v1beta1.NetworkPolicy) error { - c.policyMapLock.Lock() - defer c.policyMapLock.Unlock() - - return c.addNetworkPolicyLocked(policy) -} - -func (c *ruleCache) addNetworkPolicyLocked(policy *v1beta1.NetworkPolicy) error { - c.policyMap[string(policy.UID)] = &types.NamespacedName{Namespace: policy.Namespace, Name: policy.Name} metrics.NetworkPolicyCount.Inc() return c.UpdateNetworkPolicy(policy) } @@ -664,14 +647,10 @@ func (c *ruleCache) UpdateNetworkPolicy(policy *v1beta1.NetworkPolicy) error { // DeleteNetworkPolicy deletes a cached *v1beta1.NetworkPolicy. // All its rules will be regarded as dirty. func (c *ruleCache) DeleteNetworkPolicy(policy *v1beta1.NetworkPolicy) error { - c.policyMapLock.Lock() - defer c.policyMapLock.Unlock() - - return c.deleteNetworkPolicyLocked(string(policy.UID)) + return c.deleteNetworkPolicy(string(policy.UID)) } -func (c *ruleCache) deleteNetworkPolicyLocked(uid string) error { - delete(c.policyMap, uid) +func (c *ruleCache) deleteNetworkPolicy(uid string) error { existingRules, _ := c.rules.ByIndex(policyIndex, uid) for _, r := range existingRules { ruleID := r.(*rule).ID diff --git a/pkg/agent/controller/networkpolicy/cache_test.go b/pkg/agent/controller/networkpolicy/cache_test.go index 39062d31e81..33fa10b506c 100644 --- a/pkg/agent/controller/networkpolicy/cache_test.go +++ b/pkg/agent/controller/networkpolicy/cache_test.go @@ -132,15 +132,34 @@ func newAddressGroupMemberPod(ip string) *v1beta1.GroupMemberPod { return &v1beta1.GroupMemberPod{IP: v1beta1.IPAddress(net.ParseIP(ip))} } -func TestRuleCacheAddAddressGroup(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1"}}, - } - rule2 := &rule{ - ID: "rule2", - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1", "group2"}}, +func newRule(id string, + policyType v1beta1.NetworkPolicyType, + policyNamespace string, + policyName string, + policyUID types.UID, + fromGroups []string, + toGroups []string, + appliedToGroups []string, + direction v1beta1.Direction, +) *rule { + return &rule{ + ID: id, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: policyType, + Namespace: policyNamespace, + Name: policyName, + UID: policyUID, + }, + Direction: direction, + From: v1beta1.NetworkPolicyPeer{AddressGroups: fromGroups}, + To: v1beta1.NetworkPolicyPeer{AddressGroups: toGroups}, + AppliedToGroups: appliedToGroups, } +} + +func TestRuleCacheAddAddressGroup(t *testing.T) { + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", []string{"group1"}, nil, nil, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", []string{"group1", "group2"}, nil, nil, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -207,14 +226,8 @@ func newFakeRuleCache() (*ruleCache, *dirtyRuleRecorder, chan v1beta1.PodReferen } func TestRuleCacheReplaceAppliedToGroups(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - AppliedToGroups: []string{"group1"}, - } - rule2 := &rule{ - ID: "rule2", - AppliedToGroups: []string{"group1", "group2"}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1"}, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1", "group2"}, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -291,14 +304,8 @@ func TestRuleCacheReplaceAppliedToGroups(t *testing.T) { } func TestRuleCacheReplaceAddressGroups(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1"}}, - } - rule2 := &rule{ - ID: "rule2", - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1", "group2"}}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", []string{"group1"}, nil, nil, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", []string{"group1", "group2"}, nil, nil, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -385,11 +392,23 @@ func TestRuleCacheReplaceNetworkPolicies(t *testing.T) { ObjectMeta: metav1.ObjectMeta{UID: "policy1"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1}, AppliedToGroups: []string{"addressGroup1"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } networkPolicy2 := &v1beta1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{UID: "policy1"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1}, AppliedToGroups: []string{"addressGroup2"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } rule1 := toRule(networkPolicyRule1, networkPolicy1) rule2 := toRule(networkPolicyRule1, networkPolicy2) @@ -434,7 +453,6 @@ func TestRuleCacheReplaceNetworkPolicies(t *testing.T) { c, recorder, _ := newFakeRuleCache() for _, rule := range tt.rules { c.rules.Add(rule) - c.policyMap[string(rule.PolicyUID)] = &types.NamespacedName{Namespace: rule.PolicyNamespace, Name: rule.PolicyName} } c.ReplaceNetworkPolicies(tt.args) @@ -447,14 +465,8 @@ func TestRuleCacheReplaceNetworkPolicies(t *testing.T) { } func TestRuleCacheAddAppliedToGroup(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - AppliedToGroups: []string{"group1"}, - } - rule2 := &rule{ - ID: "rule2", - AppliedToGroups: []string{"group1", "group2"}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1"}, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1", "group2"}, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -527,14 +539,26 @@ func TestRuleCacheAddNetworkPolicy(t *testing.T) { Services: nil, } networkPolicy1 := &v1beta1.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{UID: "policy1", Namespace: "ns1", Name: "name1"}, + ObjectMeta: metav1.ObjectMeta{UID: "policy1", Name: "policy1"}, Rules: nil, AppliedToGroups: []string{"appliedToGroup1"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } networkPolicy2 := &v1beta1.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{UID: "policy2", Namespace: "ns2", Name: "name2"}, + ObjectMeta: metav1.ObjectMeta{UID: "policy2", Name: "policy2"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1, *networkPolicyRule2}, AppliedToGroups: []string{"appliedToGroup1"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns2", + Name: "name2", + UID: "policy2", + }, } rule1 := toRule(networkPolicyRule1, networkPolicy2) rule2 := toRule(networkPolicyRule2, networkPolicy2) @@ -574,16 +598,22 @@ func TestRuleCacheAddNetworkPolicy(t *testing.T) { func TestRuleCacheDeleteNetworkPolicy(t *testing.T) { rule1 := &rule{ - ID: "rule1", - PolicyUID: "policy1", + ID: "rule1", + PolicyRef: &v1beta1.NetworkPolicyReference{ + UID: "policy1", + }, } rule2 := &rule{ - ID: "rule2", - PolicyUID: "policy2", + ID: "rule2", + PolicyRef: &v1beta1.NetworkPolicyReference{ + UID: "policy2", + }, } rule3 := &rule{ - ID: "rule3", - PolicyUID: "policy2", + ID: "rule3", + PolicyRef: &v1beta1.NetworkPolicyReference{ + UID: "policy2", + }, } tests := []struct { name string @@ -644,24 +674,9 @@ func TestRuleCacheGetCompletedRule(t *testing.T) { 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{ - ID: "rule1", - Direction: v1beta1.DirectionIn, - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"addressGroup1"}}, - AppliedToGroups: []string{"appliedToGroup1"}, - } - rule2 := &rule{ - ID: "rule2", - Direction: v1beta1.DirectionOut, - To: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"addressGroup1", "addressGroup2"}}, - AppliedToGroups: []string{"appliedToGroup1", "appliedToGroup2"}, - } - rule3 := &rule{ - ID: "rule3", - Direction: v1beta1.DirectionIn, - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"addressGroup1", "addressGroup2", "addressGroup3"}}, - AppliedToGroups: []string{"appliedToGroup1", "appliedToGroup2"}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "", "", "", []string{"addressGroup1"}, nil, []string{"appliedToGroup1"}, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "", "", "", nil, []string{"addressGroup1", "addressGroup2"}, []string{"appliedToGroup1", "appliedToGroup2"}, v1beta1.DirectionOut) + rule3 := newRule("rule3", v1beta1.K8sNetworkPolicy, "", "", "", []string{"addressGroup1", "addressGroup2", "addressGroup3"}, nil, []string{"appliedToGroup1", "appliedToGroup2"}, v1beta1.DirectionIn) tests := []struct { name string args string @@ -734,14 +749,8 @@ func TestRuleCacheGetCompletedRule(t *testing.T) { } func TestRuleCachePatchAppliedToGroup(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - AppliedToGroups: []string{"group1"}, - } - rule2 := &rule{ - ID: "rule2", - AppliedToGroups: []string{"group1", "group2"}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1"}, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1", "group2"}, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -811,14 +820,8 @@ func TestRuleCachePatchAppliedToGroup(t *testing.T) { } func TestRuleCachePatchAddressGroup(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - From: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1"}}, - } - rule2 := &rule{ - ID: "rule2", - To: v1beta1.NetworkPolicyPeer{AddressGroups: []string{"group1", "group2"}}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", []string{"group1"}, nil, nil, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, []string{"group1", "group2"}, nil, v1beta1.DirectionIn) tests := []struct { name string rules []*rule @@ -904,16 +907,34 @@ func TestRuleCacheUpdateNetworkPolicy(t *testing.T) { ObjectMeta: metav1.ObjectMeta{UID: "policy1"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1}, AppliedToGroups: []string{"addressGroup1"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } networkPolicy2 := &v1beta1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{UID: "policy1"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1}, AppliedToGroups: []string{"addressGroup2"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } networkPolicy3 := &v1beta1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{UID: "policy1"}, Rules: []v1beta1.NetworkPolicyRule{*networkPolicyRule1, *networkPolicyRule2}, AppliedToGroups: []string{"addressGroup1"}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "policy1", + }, } rule1 := toRule(networkPolicyRule1, networkPolicy1) rule2 := toRule(networkPolicyRule1, networkPolicy2) @@ -960,14 +981,8 @@ func TestRuleCacheUpdateNetworkPolicy(t *testing.T) { } func TestRuleCacheProcessPodUpdates(t *testing.T) { - rule1 := &rule{ - ID: "rule1", - AppliedToGroups: []string{"group1"}, - } - rule2 := &rule{ - ID: "rule2", - AppliedToGroups: []string{"group1", "group2"}, - } + rule1 := newRule("rule1", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1"}, v1beta1.DirectionIn) + rule2 := newRule("rule2", v1beta1.K8sNetworkPolicy, "ns1", "np1", "id1", nil, nil, []string{"group1", "group2"}, v1beta1.DirectionIn) tests := []struct { name string rules []*rule diff --git a/pkg/agent/controller/networkpolicy/networkpolicy_controller.go b/pkg/agent/controller/networkpolicy/networkpolicy_controller.go index c664b337e1b..5223095941f 100644 --- a/pkg/agent/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/agent/controller/networkpolicy/networkpolicy_controller.go @@ -106,7 +106,7 @@ func NewNetworkPolicyController(antreaClientGetter agent.AntreaClientProvider, if err != nil { return nil, err } - return antreaClient.ControlplaneV1beta1().NetworkPolicies("").Watch(context.TODO(), options) + return antreaClient.ControlplaneV1beta1().NetworkPolicies().Watch(context.TODO(), options) }, AddFunc: func(obj runtime.Object) error { policy, ok := obj.(*v1beta1.NetworkPolicy) @@ -114,7 +114,7 @@ func NewNetworkPolicyController(antreaClientGetter agent.AntreaClientProvider, return fmt.Errorf("cannot convert to *v1beta1.NetworkPolicy: %v", obj) } c.ruleCache.AddNetworkPolicy(policy) - klog.Infof("NetworkPolicy %s/%s applied to Pods on this Node", policy.Namespace, policy.Name) + klog.Infof("NetworkPolicy %s applied to Pods on this Node", policy.SourceRef.ToString()) return nil }, UpdateFunc: func(obj runtime.Object) error { @@ -131,7 +131,7 @@ func NewNetworkPolicyController(antreaClientGetter agent.AntreaClientProvider, return fmt.Errorf("cannot convert to *v1beta1.NetworkPolicy: %v", obj) } c.ruleCache.DeleteNetworkPolicy(policy) - klog.Infof("NetworkPolicy %s/%s no longer applied to Pods on this Node", policy.Namespace, policy.Name) + klog.Infof("NetworkPolicy %s no longer applied to Pods on this Node", policy.SourceRef.ToString()) return nil }, ReplaceFunc: func(objs []runtime.Object) error { @@ -142,7 +142,7 @@ func NewNetworkPolicyController(antreaClientGetter agent.AntreaClientProvider, if !ok { return fmt.Errorf("cannot convert to *v1beta1.NetworkPolicy: %v", objs[i]) } - klog.Infof("NetworkPolicy %s/%s applied to Pods on this Node", policies[i].Namespace, policies[i].Name) + klog.Infof("NetworkPolicy %s applied to Pods on this Node", policies[i].SourceRef.ToString()) } c.ruleCache.ReplaceNetworkPolicies(policies) return nil diff --git a/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go index f76ca8b4ff2..820919b1807 100644 --- a/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/agent/controller/networkpolicy/networkpolicy_controller_test.go @@ -125,7 +125,13 @@ func newNetworkPolicy(uid string, from, to, appliedTo []string, services []v1bet Services: services, } return &v1beta1.NetworkPolicy{ - ObjectMeta: v1.ObjectMeta{UID: types.UID(uid), Name: uid, Namespace: testNamespace}, + ObjectMeta: v1.ObjectMeta{UID: types.UID(uid), Name: uid}, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: testNamespace, + Name: uid, + UID: types.UID(uid), + }, Rules: []v1beta1.NetworkPolicyRule{networkPolicyRule1}, AppliedToGroups: appliedTo, } @@ -145,9 +151,15 @@ func getNetworkPolicyWithMultipleRules(uid string, from, to, appliedTo []string, Services: services, } return &v1beta1.NetworkPolicy{ - ObjectMeta: v1.ObjectMeta{UID: types.UID(uid), Name: uid, Namespace: testNamespace}, + ObjectMeta: v1.ObjectMeta{UID: types.UID(uid), Name: uid}, Rules: []v1beta1.NetworkPolicyRule{networkPolicyRule1, networkPolicyRule2}, AppliedToGroups: appliedTo, + SourceRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: testNamespace, + Name: uid, + UID: types.UID(uid), + }, } } @@ -182,7 +194,7 @@ func TestAddSingleGroupRule(t *testing.T) { t.Fatalf("Expected no update, got %v", ruleID) case <-time.After(time.Millisecond * 100): } - assert.Equal(t, policy1, controller.GetNetworkPolicy(policy1.Name, policy1.Namespace)) + assert.Equal(t, policy1, controller.GetNetworkPolicy(policy1.Name, testNamespace)) assert.Equal(t, 1, controller.GetNetworkPolicyNum()) assert.Equal(t, 0, controller.GetAddressGroupNum()) assert.Equal(t, 0, controller.GetAppliedToGroupNum()) @@ -265,7 +277,7 @@ func TestAddMultipleGroupsRule(t *testing.T) { t.Fatalf("Expected no update, got %v", ruleID) case <-time.After(time.Millisecond * 100): } - assert.Equal(t, policy1, controller.GetNetworkPolicy(policy1.Name, policy1.Namespace)) + assert.Equal(t, policy1, controller.GetNetworkPolicy(policy1.Name, testNamespace)) assert.Equal(t, 1, controller.GetNetworkPolicyNum()) assert.Equal(t, 1, controller.GetAddressGroupNum()) assert.Equal(t, 1, controller.GetAppliedToGroupNum()) @@ -430,8 +442,8 @@ func TestAddNetworkPolicyWithMultipleRules(t *testing.T) { t.Fatal("Expected two rule updates, got timeout") } } - assert.ElementsMatch(t, policy1.Rules, controller.GetNetworkPolicy(policy1.Name, policy1.Namespace).Rules) - assert.ElementsMatch(t, policy1.AppliedToGroups, controller.GetNetworkPolicy(policy1.Name, policy1.Namespace).AppliedToGroups) + assert.ElementsMatch(t, policy1.Rules, controller.GetNetworkPolicy(policy1.Name, testNamespace).Rules) + assert.ElementsMatch(t, policy1.AppliedToGroups, controller.GetNetworkPolicy(policy1.Name, testNamespace).AppliedToGroups) assert.Equal(t, 1, controller.GetNetworkPolicyNum()) assert.Equal(t, 2, controller.GetAddressGroupNum()) assert.Equal(t, 1, controller.GetAppliedToGroupNum()) diff --git a/pkg/agent/controller/networkpolicy/reconciler.go b/pkg/agent/controller/networkpolicy/reconciler.go index 4d5e58acfd4..c04b77006ed 100644 --- a/pkg/agent/controller/networkpolicy/reconciler.go +++ b/pkg/agent/controller/networkpolicy/reconciler.go @@ -197,7 +197,7 @@ func newReconciler(ofClient openflow.Client, ifaceStore interfacestore.Interface // Reconcile checks whether the provided rule have been enforced or not, and // invoke the add or update method accordingly. func (r *reconciler) Reconcile(rule *CompletedRule) error { - klog.Infof("Reconciling rule %s of NetworkPolicy %s/%s", rule.ID, rule.PolicyNamespace, rule.PolicyName) + klog.Infof("Reconciling rule %s of NetworkPolicy %s", rule.ID, rule.PolicyRef.ToString()) var err error var ofPriority *uint16 @@ -295,7 +295,7 @@ func (r *reconciler) BatchReconcile(rules []*CompletedRule) error { for _, rule := range rulesToInstall { ruleTable := r.getOFRuleTable(rule) priorityAssigner := r.priorityAssigners[ruleTable] - klog.V(2).Infof("Adding rule %s of NetworkPolicy %s/%s to be reconciled in batch", rule.ID, rule.PolicyNamespace, rule.PolicyName) + klog.V(2).Infof("Adding rule %s of NetworkPolicy %s to be reconciled in batch", rule.ID, rule.PolicyRef.ToString()) ofPriority, _ := r.getOFPriority(rule, ruleTable, priorityAssigner) priorities = append(priorities, ofPriority) if ofPriority != nil { @@ -348,8 +348,6 @@ func (r *reconciler) add(rule *CompletedRule, ofPriority *uint16, table binding. return fmt.Errorf("error allocating Openflow ID") } ofRule.FlowID = ofID - ofRule.PolicyName = lastRealized.CompletedRule.PolicyName - ofRule.PolicyNamespace = lastRealized.CompletedRule.PolicyNamespace if err = r.installOFRule(ofRule); err != nil { return err } @@ -386,6 +384,7 @@ func (r *reconciler) computeOFRulesForAdd(rule *CompletedRule, ofPriority *uint1 Action: rule.Action, Priority: ofPriority, TableID: table, + PolicyRef: rule.PolicyRef, } } } else { @@ -402,6 +401,7 @@ func (r *reconciler) computeOFRulesForAdd(rule *CompletedRule, ofPriority *uint1 Action: rule.Action, Priority: ofPriority, TableID: table, + PolicyRef: rule.PolicyRef, } } @@ -423,6 +423,7 @@ func (r *reconciler) computeOFRulesForAdd(rule *CompletedRule, ofPriority *uint1 Action: rule.Action, Priority: nil, TableID: table, + PolicyRef: rule.PolicyRef, } ofRuleByServicesMap[svcKey] = ofRule } @@ -453,8 +454,6 @@ func (r *reconciler) batchAdd(rules []*CompletedRule, ofPriorities []*uint16) er return fmt.Errorf("error allocating Openflow ID") } ofRule.FlowID = ofID - ofRule.PolicyName = lastRealized.CompletedRule.PolicyName - ofRule.PolicyNamespace = lastRealized.CompletedRule.PolicyNamespace allOFRules = append(allOFRules, ofRule) if ofIDUpdateMaps[idx] == nil { ofIDUpdateMaps[idx] = make(map[servicesKey]uint32) @@ -507,16 +506,15 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, return fmt.Errorf("error allocating Openflow ID") } ofRule := &types.PolicyRule{ - Direction: v1beta1.DirectionIn, - From: append(from1, from2...), - To: ofPortsToOFAddresses(newOFPorts), - Service: filterUnresolvablePort(servicesMap[svcKey]), - Action: newRule.Action, - Priority: ofPriority, - FlowID: ofID, - TableID: table, - PolicyName: newRule.PolicyName, - PolicyNamespace: newRule.PolicyNamespace, + Direction: v1beta1.DirectionIn, + From: append(from1, from2...), + To: ofPortsToOFAddresses(newOFPorts), + Service: filterUnresolvablePort(servicesMap[svcKey]), + Action: newRule.Action, + Priority: ofPriority, + FlowID: ofID, + TableID: table, + PolicyRef: newRule.PolicyRef, } if err = r.installOFRule(ofRule); err != nil { return err @@ -556,16 +554,15 @@ func (r *reconciler) update(lastRealized *lastRealized, newRule *CompletedRule, return fmt.Errorf("error allocating Openflow ID") } ofRule := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: from, - To: groupMembersToOFAddresses(members), - Service: filterUnresolvablePort(servicesMap[svcKey]), - Action: newRule.Action, - Priority: ofPriority, - FlowID: ofID, - TableID: table, - PolicyName: newRule.PolicyName, - PolicyNamespace: newRule.PolicyNamespace, + Direction: v1beta1.DirectionOut, + From: from, + To: groupMembersToOFAddresses(members), + Service: filterUnresolvablePort(servicesMap[svcKey]), + Action: newRule.Action, + Priority: ofPriority, + FlowID: ofID, + TableID: table, + PolicyRef: newRule.PolicyRef, } if err = r.installOFRule(ofRule); err != nil { return err diff --git a/pkg/agent/controller/networkpolicy/reconciler_test.go b/pkg/agent/controller/networkpolicy/reconciler_test.go index 387bf7d4e27..72f21903447 100644 --- a/pkg/agent/controller/networkpolicy/reconciler_test.go +++ b/pkg/agent/controller/networkpolicy/reconciler_test.go @@ -72,6 +72,18 @@ var ( policyPriority = float64(1) tierPriority = v1beta1.TierPriority(1) + + np1 = v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "uid1", + } + cnp1 = v1beta1.NetworkPolicyReference{ + Type: v1beta1.ClusterNetworkPolicy, + Name: "name1", + UID: "uid1", + } ) func newCIDR(cidrStr string) *net.IPNet { @@ -93,7 +105,7 @@ func TestReconcilerForget(t *testing.T) { "foo": { ofIDs: map[servicesKey]uint32{servicesKey1: 8}, CompletedRule: &CompletedRule{ - rule: &rule{Direction: v1beta1.DirectionIn, PolicyPriority: nil}, + rule: &rule{Direction: v1beta1.DirectionIn, PolicyRef: &np1}, }, }, }, @@ -107,7 +119,7 @@ func TestReconcilerForget(t *testing.T) { "foo": { ofIDs: map[servicesKey]uint32{servicesKey1: 8}, CompletedRule: &CompletedRule{ - rule: &rule{Direction: v1beta1.DirectionIn, PolicyPriority: nil}, + rule: &rule{Direction: v1beta1.DirectionIn, PolicyRef: &np1}, }, }, }, @@ -121,7 +133,7 @@ func TestReconcilerForget(t *testing.T) { "foo": { ofIDs: map[servicesKey]uint32{servicesKey1: 8, servicesKey2: 9}, CompletedRule: &CompletedRule{ - rule: &rule{Direction: v1beta1.DirectionIn, PolicyPriority: nil}, + rule: &rule{Direction: v1beta1.DirectionIn, PolicyRef: &np1}, }, }, }, @@ -135,7 +147,7 @@ func TestReconcilerForget(t *testing.T) { "foo": { ofIDs: map[servicesKey]uint32{servicesKey1: 8, servicesKey2: 9}, CompletedRule: &CompletedRule{ - rule: &rule{Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority}, + rule: &rule{Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, PolicyRef: &cnp1}, }, }, }, @@ -219,7 +231,7 @@ func TestReconcilerReconcile(t *testing.T) { { "ingress-rule", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceTCP80, serviceTCP}}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceTCP80, serviceTCP}, PolicyRef: &np1}, FromAddresses: addressGroup1, ToAddresses: nil, Pods: appliedToGroup1, @@ -230,6 +242,7 @@ func TestReconcilerReconcile(t *testing.T) { From: ipsToOFAddresses(sets.NewString("1.1.1.1")), To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: []v1beta1.Service{serviceTCP80, serviceTCP}, + PolicyRef: &np1, }, }, false, @@ -237,7 +250,7 @@ func TestReconcilerReconcile(t *testing.T) { { "ingress-rule-with-missing-ofport", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: addressGroup1, ToAddresses: nil, Pods: appliedToGroup2, @@ -248,6 +261,7 @@ func TestReconcilerReconcile(t *testing.T) { From: ipsToOFAddresses(sets.NewString("1.1.1.1")), To: []types.Address{}, Service: nil, + PolicyRef: &np1, }, }, false, @@ -260,6 +274,7 @@ func TestReconcilerReconcile(t *testing.T) { Direction: v1beta1.DirectionIn, From: v1beta1.NetworkPolicyPeer{IPBlocks: []v1beta1.IPBlock{ipBlock1, ipBlock2}}, Services: []v1beta1.Service{serviceTCP80, serviceTCP}, + PolicyRef: &np1, }, FromAddresses: addressGroup1, ToAddresses: nil, @@ -284,8 +299,9 @@ func TestReconcilerReconcile(t *testing.T) { openflow.NewIPNetAddress(*diffNet11), openflow.NewIPNetAddress(*diffNet12), }, - To: ofPortsToOFAddresses(sets.NewInt32(1)), - Service: []v1beta1.Service{serviceTCP80, serviceTCP}, + To: ofPortsToOFAddresses(sets.NewInt32(1)), + Service: []v1beta1.Service{serviceTCP80, serviceTCP}, + PolicyRef: &np1, }, }, false, @@ -297,6 +313,7 @@ func TestReconcilerReconcile(t *testing.T) { ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{}, + PolicyRef: &np1, }, Pods: appliedToGroup1, }, @@ -306,6 +323,7 @@ func TestReconcilerReconcile(t *testing.T) { From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: nil, + PolicyRef: &np1, }, }, false, @@ -317,6 +335,7 @@ func TestReconcilerReconcile(t *testing.T) { ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceHTTP}, + PolicyRef: &np1, }, Pods: appliedToGroup1, }, @@ -326,6 +345,7 @@ func TestReconcilerReconcile(t *testing.T) { From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: []v1beta1.Service{}, + PolicyRef: &np1, }, }, false, @@ -337,6 +357,7 @@ func TestReconcilerReconcile(t *testing.T) { ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceHTTP}, + PolicyRef: &np1, }, Pods: appliedToGroupWithSameContainerPort, }, @@ -346,6 +367,7 @@ func TestReconcilerReconcile(t *testing.T) { From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1, 3)), Service: []v1beta1.Service{serviceTCP80}, + PolicyRef: &np1, }, }, false, @@ -357,6 +379,7 @@ func TestReconcilerReconcile(t *testing.T) { ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceHTTP}, + PolicyRef: &np1, }, Pods: appliedToGroupWithDiffContainerPort, }, @@ -366,12 +389,14 @@ func TestReconcilerReconcile(t *testing.T) { From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: []v1beta1.Service{serviceTCP80}, + PolicyRef: &np1, }, { Direction: v1beta1.DirectionIn, From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(3)), Service: []v1beta1.Service{serviceTCP443}, + PolicyRef: &np1, }, }, false, @@ -379,7 +404,7 @@ func TestReconcilerReconcile(t *testing.T) { { "ingress-rule-deny-all", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: nil, ToAddresses: nil, Pods: appliedToGroup1, @@ -390,6 +415,7 @@ func TestReconcilerReconcile(t *testing.T) { From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: nil, + PolicyRef: &np1, }, }, false, @@ -397,7 +423,7 @@ func TestReconcilerReconcile(t *testing.T) { { "egress-rule", &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, FromAddresses: nil, ToAddresses: addressGroup1, Pods: appliedToGroup1, @@ -408,6 +434,7 @@ func TestReconcilerReconcile(t *testing.T) { From: ipsToOFAddresses(sets.NewString("2.2.2.2")), To: ipsToOFAddresses(sets.NewString("1.1.1.1")), Service: nil, + PolicyRef: &np1, }, }, false, @@ -419,6 +446,7 @@ func TestReconcilerReconcile(t *testing.T) { ID: "egress-rule", Direction: v1beta1.DirectionOut, To: v1beta1.NetworkPolicyPeer{IPBlocks: []v1beta1.IPBlock{ipBlock1, ipBlock2}}, + PolicyRef: &np1, }, FromAddresses: nil, ToAddresses: addressGroup1, @@ -444,7 +472,8 @@ func TestReconcilerReconcile(t *testing.T) { openflow.NewIPNetAddress(*diffNet11), openflow.NewIPNetAddress(*diffNet12), }, - Service: nil, + Service: nil, + PolicyRef: &np1, }, }, false, @@ -455,6 +484,7 @@ func TestReconcilerReconcile(t *testing.T) { rule: &rule{ ID: "egress-rule", Direction: v1beta1.DirectionOut, + PolicyRef: &np1, }, FromAddresses: nil, ToAddresses: nil, @@ -466,6 +496,7 @@ func TestReconcilerReconcile(t *testing.T) { From: ipsToOFAddresses(sets.NewString("2.2.2.2")), To: []types.Address{}, Service: nil, + PolicyRef: &np1, }, }, false, @@ -504,21 +535,21 @@ func TestReconcilerBatchReconcile(t *testing.T) { }) completedRules := []*CompletedRule{ { - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceTCP80, serviceTCP}}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceTCP80, serviceTCP}, PolicyRef: &np1}, FromAddresses: addressGroup1, ToAddresses: nil, Pods: appliedToGroup1, }, { - rule: &rule{ID: "ingress-rule-no-ports", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{}}, + rule: &rule{ID: "ingress-rule-no-ports", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{}, PolicyRef: &np1}, Pods: appliedToGroup1, }, { - rule: &rule{ID: "ingress-rule-diff-named-port", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceHTTP}}, + rule: &rule{ID: "ingress-rule-diff-named-port", Direction: v1beta1.DirectionIn, Services: []v1beta1.Service{serviceHTTP}, PolicyRef: &np1}, Pods: appliedToGroupWithDiffContainerPort, }, { - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, FromAddresses: nil, ToAddresses: addressGroup1, Pods: appliedToGroup1, @@ -530,30 +561,35 @@ func TestReconcilerBatchReconcile(t *testing.T) { From: ipsToOFAddresses(sets.NewString("1.1.1.1")), To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: []v1beta1.Service{serviceTCP80, serviceTCP}, + PolicyRef: &np1, }, { Direction: v1beta1.DirectionIn, From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: nil, + PolicyRef: &np1, }, { Direction: v1beta1.DirectionIn, From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(1)), Service: []v1beta1.Service{serviceTCP80}, + PolicyRef: &np1, }, { Direction: v1beta1.DirectionIn, From: []types.Address{}, To: ofPortsToOFAddresses(sets.NewInt32(3)), Service: []v1beta1.Service{serviceTCP443}, + PolicyRef: &np1, }, { Direction: v1beta1.DirectionOut, From: ipsToOFAddresses(sets.NewString("2.2.2.2")), To: ipsToOFAddresses(sets.NewString("1.1.1.1")), Service: nil, + PolicyRef: &np1, }, } tests := []struct { @@ -641,12 +677,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-ingress-rule", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: addressGroup1, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: addressGroup2, Pods: appliedToGroup2, }, @@ -660,12 +696,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-egress-rule", &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: addressGroup1, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: addressGroup2, Pods: appliedToGroup2, }, @@ -679,12 +715,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-ingress-rule-with-missing-ofport", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: addressGroup1, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyRef: &np1}, FromAddresses: addressGroup2, Pods: appliedToGroup3, }, @@ -698,12 +734,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-egress-rule-with-missing-ip", &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: addressGroup1, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: addressGroup2, Pods: appliedToGroup3, }, @@ -717,12 +753,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-egress-rule-deny-all", &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: nil, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut}, + rule: &rule{ID: "egress-rule", Direction: v1beta1.DirectionOut, PolicyRef: &np1}, ToAddresses: nil, Pods: appliedToGroup2, }, @@ -736,12 +772,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-cnp-ingress-rule", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, PolicyRef: &cnp1}, FromAddresses: addressGroup1, Pods: appliedToGroup1, }, &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, PolicyRef: &cnp1}, FromAddresses: addressGroup2, Pods: appliedToGroup2, }, @@ -755,12 +791,12 @@ func TestReconcilerUpdate(t *testing.T) { { "updating-cnp-ingress-rule-uninstall", &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, Services: []v1beta1.Service{serviceHTTP}}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, Services: []v1beta1.Service{serviceHTTP}, PolicyRef: &cnp1}, FromAddresses: addressGroup1, Pods: appliedToGroupWithDiffContainerPort, }, &CompletedRule{ - rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, Services: []v1beta1.Service{serviceHTTP}}, + rule: &rule{ID: "ingress-rule", Direction: v1beta1.DirectionIn, PolicyPriority: &policyPriority, TierPriority: &tierPriority, Services: []v1beta1.Service{serviceHTTP}, PolicyRef: &cnp1}, FromAddresses: addressGroup1, Pods: appliedToGroupWithSingleContainerPort, }, diff --git a/pkg/agent/controller/traceflow/packetin.go b/pkg/agent/controller/traceflow/packetin.go index 7f02446f878..e3644dc8b29 100644 --- a/pkg/agent/controller/traceflow/packetin.go +++ b/pkg/agent/controller/traceflow/packetin.go @@ -133,9 +133,9 @@ func (c *Controller) parsePacketIn(pktIn *ofctrl.PacketIn) (*opsv1alpha1.Tracefl ob.Component = opsv1alpha1.NetworkPolicy ob.ComponentInfo = openflow.GetFlowTableName(openflow.EgressRuleTable) ob.Action = opsv1alpha1.Forwarded - npName, npNamespace := c.ofClient.GetPolicyFromConjunction(egressInfo) - if npName != "" { - ob.NetworkPolicy = fmt.Sprintf("%s/%s", npNamespace, npName) + npRef := c.ofClient.GetPolicyFromConjunction(egressInfo) + if npRef != nil { + ob.NetworkPolicy = npRef.ToString() } obs = append(obs, *ob) } @@ -150,9 +150,9 @@ func (c *Controller) parsePacketIn(pktIn *ofctrl.PacketIn) (*opsv1alpha1.Tracefl ob.Component = opsv1alpha1.NetworkPolicy ob.ComponentInfo = openflow.GetFlowTableName(openflow.IngressRuleTable) ob.Action = opsv1alpha1.Forwarded - npName, npNamespace := c.ofClient.GetPolicyFromConjunction(ingressInfo) - if npName != "" { - ob.NetworkPolicy = fmt.Sprintf("%s/%s", npNamespace, npName) + npRef := c.ofClient.GetPolicyFromConjunction(ingressInfo) + if npRef != nil { + ob.NetworkPolicy = npRef.ToString() } obs = append(obs, *ob) } diff --git a/pkg/agent/openflow/client.go b/pkg/agent/openflow/client.go index 159ef0cd851..3565f8a3946 100644 --- a/pkg/agent/openflow/client.go +++ b/pkg/agent/openflow/client.go @@ -25,6 +25,7 @@ import ( "github.com/vmware-tanzu/antrea/pkg/agent/config" "github.com/vmware-tanzu/antrea/pkg/agent/openflow/cookie" "github.com/vmware-tanzu/antrea/pkg/agent/types" + "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1" binding "github.com/vmware-tanzu/antrea/pkg/ovs/openflow" "github.com/vmware-tanzu/antrea/third_party/proxy" ) @@ -217,7 +218,7 @@ type Client interface { InitialTLVMap() error // Find network policy and namespace by conjunction ID. - GetPolicyFromConjunction(ruleID uint32) (string, string) + GetPolicyFromConjunction(ruleID uint32) *v1beta1.NetworkPolicyReference // RegisterPacketInHandler registers PacketIn handler to process PacketIn event. RegisterPacketInHandler(packetHandlerName string, packetInHandler interface{}) diff --git a/pkg/agent/openflow/network_policy.go b/pkg/agent/openflow/network_policy.go index be4f00e8647..93339c0613c 100644 --- a/pkg/agent/openflow/network_policy.go +++ b/pkg/agent/openflow/network_policy.go @@ -453,9 +453,8 @@ type policyRuleConjunction struct { serviceClause *clause actionFlows []binding.Flow metricFlows []binding.Flow - // NetworkPolicy name and Namespace information for debugging usage. - npName string - npNamespace string + // NetworkPolicy reference information for debugging usage. + npRef *v1beta1.NetworkPolicyReference ruleTableID binding.TableIDType } @@ -749,9 +748,9 @@ func (c *client) calculateActionFlowChangesForRule(rule *types.PolicyRule) *poli return nil } conj = &policyRuleConjunction{ - id: ruleID, - npName: rule.PolicyName, - npNamespace: rule.PolicyNamespace} + id: ruleID, + npRef: rule.PolicyRef, + } nClause, ruleTable, dropTable := conj.calculateClauses(rule, c) conj.ruleTableID = rule.TableID _, isEgress := egressTables[rule.TableID] @@ -1008,12 +1007,12 @@ func (c *client) getPolicyRuleConjunction(ruleID uint32) *policyRuleConjunction return conj.(*policyRuleConjunction) } -func (c *client) GetPolicyFromConjunction(ruleID uint32) (string, string) { +func (c *client) GetPolicyFromConjunction(ruleID uint32) *v1beta1.NetworkPolicyReference { conjunction := c.getPolicyRuleConjunction(ruleID) if conjunction == nil { - return "", "" + return nil } - return conjunction.npName, conjunction.npNamespace + return conjunction.npRef } // UninstallPolicyRuleFlows removes the Openflow entry relevant to the specified NetworkPolicy rule. @@ -1183,7 +1182,7 @@ func (c *client) GetNetworkPolicyFlowKeys(npName, npNamespace string) []string { for _, conjObj := range c.policyCache.List() { conj := conjObj.(*policyRuleConjunction) - if conj.npName == npName && conj.npNamespace == npNamespace { + if conj.npRef.Name == npName && conj.npRef.Namespace == npNamespace { // There can be duplicated flows added due to conjunctive matches // shared by multiple policy rules (clauses). flowKeys = append(flowKeys, conj.getAllFlowKeys()...) @@ -1254,8 +1253,7 @@ func (c *client) updateConjunctionActionFlows(conj *policyRuleConjunction, updat toClause: conj.toClause, serviceClause: conj.serviceClause, actionFlows: newActionFlows, - npName: conj.npName, - npNamespace: conj.npNamespace, + npRef: conj.npRef, ruleTableID: conj.ruleTableID, } return newConj diff --git a/pkg/agent/openflow/network_policy_test.go b/pkg/agent/openflow/network_policy_test.go index 7caf5d9d640..50bac4b1908 100644 --- a/pkg/agent/openflow/network_policy_test.go +++ b/pkg/agent/openflow/network_policy_test.go @@ -142,14 +142,18 @@ func TestInstallPolicyRuleFlows(t *testing.T) { defaultAction := secv1alpha1.RuleActionAllow ruleID1 := uint32(101) rule1 := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: parseAddresses([]string{"192.168.1.30", "192.168.1.50"}), - Action: &defaultAction, - Priority: nil, - FlowID: ruleID1, - TableID: EgressRuleTable, - PolicyName: "np1", - PolicyNamespace: "ns1", + Direction: v1beta1.DirectionOut, + From: parseAddresses([]string{"192.168.1.30", "192.168.1.50"}), + Action: &defaultAction, + Priority: nil, + FlowID: ruleID1, + TableID: EgressRuleTable, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "np1", + UID: "id1", + }, } outDropTable.EXPECT().BuildFlow(gomock.Any()).Return(newMockDropFlowBuilder(ctrl)).AnyTimes() @@ -171,14 +175,18 @@ func TestInstallPolicyRuleFlows(t *testing.T) { ruleID2 := uint32(102) rule2 := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: parseAddresses([]string{"192.168.1.40", "192.168.1.50"}), - Action: &defaultAction, - To: parseAddresses([]string{"0.0.0.0/0"}), - FlowID: ruleID2, - TableID: EgressRuleTable, - PolicyName: "np1", - PolicyNamespace: "ns1", + Direction: v1beta1.DirectionOut, + From: parseAddresses([]string{"192.168.1.40", "192.168.1.50"}), + Action: &defaultAction, + To: parseAddresses([]string{"0.0.0.0/0"}), + FlowID: ruleID2, + TableID: EgressRuleTable, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "np1", + UID: "id1", + }, } conj2 := &policyRuleConjunction{id: ruleID2} conj2.calculateClauses(rule2, c) @@ -209,15 +217,19 @@ func TestInstallPolicyRuleFlows(t *testing.T) { npPort1 := v1beta1.Service{Protocol: &tcpProtocol, Port: &port1} npPort2 := v1beta1.Service{Protocol: &tcpProtocol, Port: &port2} rule3 := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: parseAddresses([]string{"192.168.1.40", "192.168.1.60"}), - To: parseAddresses([]string{"192.168.2.0/24"}), - Action: &defaultAction, - Service: []v1beta1.Service{npPort1, npPort2}, - FlowID: ruleID3, - TableID: EgressRuleTable, - PolicyName: "np1", - PolicyNamespace: "ns1", + Direction: v1beta1.DirectionOut, + From: parseAddresses([]string{"192.168.1.40", "192.168.1.60"}), + To: parseAddresses([]string{"192.168.2.0/24"}), + Action: &defaultAction, + Service: []v1beta1.Service{npPort1, npPort2}, + FlowID: ruleID3, + TableID: EgressRuleTable, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "np1", + UID: "id1", + }, } conj3 := &policyRuleConjunction{id: ruleID3} conj3.calculateClauses(rule3, c) @@ -270,26 +282,34 @@ func TestBatchInstallPolicyRuleFlows(t *testing.T) { ruleID1 := uint32(10) rule1 := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: parseAddresses([]string{"192.168.1.40", "192.168.1.50"}), - Action: &defaultAction, - To: parseAddresses([]string{"0.0.0.0/0"}), - FlowID: ruleID1, - TableID: EgressRuleTable, - PolicyName: "np1", - PolicyNamespace: "ns1", + Direction: v1beta1.DirectionOut, + From: parseAddresses([]string{"192.168.1.40", "192.168.1.50"}), + Action: &defaultAction, + To: parseAddresses([]string{"0.0.0.0/0"}), + FlowID: ruleID1, + TableID: EgressRuleTable, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "np1", + UID: "id1", + }, } ruleID2 := uint32(20) rule2 := &types.PolicyRule{ - Direction: v1beta1.DirectionOut, - From: parseAddresses([]string{"192.168.1.60"}), - Action: &defaultAction, - Priority: &priorityRule2, - To: parseAddresses([]string{"192.168.1.70"}), - FlowID: ruleID2, - TableID: ApplicationEgressRuleTable, - PolicyName: "np2", - PolicyNamespace: "ns1", + Direction: v1beta1.DirectionOut, + From: parseAddresses([]string{"192.168.1.60"}), + Action: &defaultAction, + Priority: &priorityRule2, + To: parseAddresses([]string{"192.168.1.70"}), + FlowID: ruleID2, + TableID: ApplicationEgressRuleTable, + PolicyRef: &v1beta1.NetworkPolicyReference{ + Type: v1beta1.K8sNetworkPolicy, + Namespace: "ns1", + Name: "np2", + UID: "id2", + }, } outDropTable.EXPECT().BuildFlow(gomock.Any()).Return(newMockDropFlowBuilder(ctrl)).AnyTimes() diff --git a/pkg/agent/openflow/testing/mock_openflow.go b/pkg/agent/openflow/testing/mock_openflow.go index 2ad8c655661..8b95bdfe140 100644 --- a/pkg/agent/openflow/testing/mock_openflow.go +++ b/pkg/agent/openflow/testing/mock_openflow.go @@ -24,6 +24,7 @@ import ( gomock "github.com/golang/mock/gomock" config "github.com/vmware-tanzu/antrea/pkg/agent/config" types "github.com/vmware-tanzu/antrea/pkg/agent/types" + v1beta1 "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1" openflow "github.com/vmware-tanzu/antrea/pkg/ovs/openflow" proxy "github.com/vmware-tanzu/antrea/third_party/proxy" net "net" @@ -166,12 +167,11 @@ func (mr *MockClientMockRecorder) GetPodFlowKeys(arg0 interface{}) *gomock.Call } // GetPolicyFromConjunction mocks base method -func (m *MockClient) GetPolicyFromConjunction(arg0 uint32) (string, string) { +func (m *MockClient) GetPolicyFromConjunction(arg0 uint32) *v1beta1.NetworkPolicyReference { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPolicyFromConjunction", arg0) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(string) - return ret0, ret1 + ret0, _ := ret[0].(*v1beta1.NetworkPolicyReference) + return ret0 } // GetPolicyFromConjunction indicates an expected call of GetPolicyFromConjunction diff --git a/pkg/agent/types/networkpolicy.go b/pkg/agent/types/networkpolicy.go index 487d30e4299..bbcde10bbbd 100644 --- a/pkg/agent/types/networkpolicy.go +++ b/pkg/agent/types/networkpolicy.go @@ -43,16 +43,15 @@ type Address interface { // PolicyRule groups configurations to set up conjunctive match for egress/ingress policy rules. type PolicyRule struct { - Direction v1beta1.Direction - From []Address - To []Address - Service []v1beta1.Service - Action *secv1alpha1.RuleAction - Priority *uint16 - FlowID uint32 - TableID binding.TableIDType - PolicyName string - PolicyNamespace string + Direction v1beta1.Direction + From []Address + To []Address + Service []v1beta1.Service + Action *secv1alpha1.RuleAction + Priority *uint16 + FlowID uint32 + TableID binding.TableIDType + PolicyRef *v1beta1.NetworkPolicyReference } // IsAntreaNetworkPolicyRule returns if a PolicyRule is created for Antrea NetworkPolicy types. diff --git a/pkg/apis/controlplane/helper.go b/pkg/apis/controlplane/helper.go index 20ddb4d9c0f..43d42d5fd36 100644 --- a/pkg/apis/controlplane/helper.go +++ b/pkg/apis/controlplane/helper.go @@ -14,6 +14,8 @@ package controlplane +import "fmt" + // Conversion functions between GroupMember and GroupMemberPod func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { return &GroupMemberPod{ @@ -31,3 +33,11 @@ func (p *GroupMemberPod) ToGroupMember() *GroupMember { }, } } + +func (r *NetworkPolicyReference) ToString() string { + if r.Type == ClusterNetworkPolicy { + return fmt.Sprintf("%s:%s", r.Type, r.Name) + } else { + return fmt.Sprintf("%s:%s/%s", r.Type, r.Namespace, r.Name) + } +} diff --git a/pkg/apis/controlplane/types.go b/pkg/apis/controlplane/types.go index c4392a8d456..985429da86c 100644 --- a/pkg/apis/controlplane/types.go +++ b/pkg/apis/controlplane/types.go @@ -16,6 +16,7 @@ package controlplane import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" @@ -150,6 +151,28 @@ type AddressGroupList struct { // TierPriority indicates higher precedence. type TierPriority uint32 +type NetworkPolicyType string + +const ( + // It represents the K8s NetworkPolicy. + K8sNetworkPolicy NetworkPolicyType = "K8sNetworkPolicy" + // It represents the Antrea ClusterNetworkPolicy. + ClusterNetworkPolicy NetworkPolicyType = "ClusterNetworkPolicy" + // It represents the Antrea NetworkPolicy. + AntreaNetworkPolicy NetworkPolicyType = "AntreaNetworkPolicy" +) + +type NetworkPolicyReference struct { + // Type of the NetworkPolicy. + Type NetworkPolicyType + // Namespace of the NetworkPolicy. It's empty for ClusterNetworkPolicy. + Namespace string + // Name of the NetworkPolicy. + Name string + // UID of the NetworkPolicy. + UID types.UID +} + // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // NetworkPolicy is the message format of antrea/pkg/controller/types.NetworkPolicy in an API response. type NetworkPolicy struct { @@ -165,6 +188,8 @@ type NetworkPolicy struct { // TierPriority represents the priority of the Tier associated with this NetworkPolicy. // The TierPriority will remain nil for K8s NetworkPolicy. TierPriority *TierPriority + // Reference to the original NetworkPolicy that the internal NetworkPolicy is created for. + SourceRef *NetworkPolicyReference } // Direction defines traffic direction of NetworkPolicyRule. diff --git a/pkg/apis/controlplane/v1beta1/generated.pb.go b/pkg/apis/controlplane/v1beta1/generated.pb.go index 5497e6979a5..1ef5eda1002 100644 --- a/pkg/apis/controlplane/v1beta1/generated.pb.go +++ b/pkg/apis/controlplane/v1beta1/generated.pb.go @@ -30,6 +30,7 @@ import ( reflect "reflect" strings "strings" + k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" intstr "k8s.io/apimachinery/pkg/util/intstr" ) @@ -492,10 +493,38 @@ func (m *NetworkPolicyPeer) XXX_DiscardUnknown() { var xxx_messageInfo_NetworkPolicyPeer proto.InternalMessageInfo +func (m *NetworkPolicyReference) Reset() { *m = NetworkPolicyReference{} } +func (*NetworkPolicyReference) ProtoMessage() {} +func (*NetworkPolicyReference) Descriptor() ([]byte, []int) { + return fileDescriptor_345cd0a9074e5729, []int{16} +} +func (m *NetworkPolicyReference) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *NetworkPolicyReference) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil +} +func (m *NetworkPolicyReference) XXX_Merge(src proto.Message) { + xxx_messageInfo_NetworkPolicyReference.Merge(m, src) +} +func (m *NetworkPolicyReference) XXX_Size() int { + return m.Size() +} +func (m *NetworkPolicyReference) XXX_DiscardUnknown() { + xxx_messageInfo_NetworkPolicyReference.DiscardUnknown(m) +} + +var xxx_messageInfo_NetworkPolicyReference proto.InternalMessageInfo + func (m *NetworkPolicyRule) Reset() { *m = NetworkPolicyRule{} } func (*NetworkPolicyRule) ProtoMessage() {} func (*NetworkPolicyRule) Descriptor() ([]byte, []int) { - return fileDescriptor_345cd0a9074e5729, []int{16} + return fileDescriptor_345cd0a9074e5729, []int{17} } func (m *NetworkPolicyRule) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -523,7 +552,7 @@ var xxx_messageInfo_NetworkPolicyRule proto.InternalMessageInfo func (m *PodReference) Reset() { *m = PodReference{} } func (*PodReference) ProtoMessage() {} func (*PodReference) Descriptor() ([]byte, []int) { - return fileDescriptor_345cd0a9074e5729, []int{17} + return fileDescriptor_345cd0a9074e5729, []int{18} } func (m *PodReference) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -551,7 +580,7 @@ var xxx_messageInfo_PodReference proto.InternalMessageInfo func (m *Service) Reset() { *m = Service{} } func (*Service) ProtoMessage() {} func (*Service) Descriptor() ([]byte, []int) { - return fileDescriptor_345cd0a9074e5729, []int{18} + return fileDescriptor_345cd0a9074e5729, []int{19} } func (m *Service) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -593,6 +622,7 @@ func init() { proto.RegisterType((*NetworkPolicy)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.NetworkPolicy") proto.RegisterType((*NetworkPolicyList)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.NetworkPolicyList") proto.RegisterType((*NetworkPolicyPeer)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.NetworkPolicyPeer") + proto.RegisterType((*NetworkPolicyReference)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.NetworkPolicyReference") proto.RegisterType((*NetworkPolicyRule)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.NetworkPolicyRule") proto.RegisterType((*PodReference)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.PodReference") proto.RegisterType((*Service)(nil), "github.aaakk.us.kg.vmware_tanzu.antrea.pkg.apis.controlplane.v1beta1.Service") @@ -603,92 +633,99 @@ func init() { } var fileDescriptor_345cd0a9074e5729 = []byte{ - // 1359 bytes of a gzipped FileDescriptorProto + // 1461 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, 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,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x73, 0x5d, 0xe7, 0xe5, 0x11, 0xf9, 0x41, 0x12, 0x41, 0x33, 0x41, 0x29, 0xdd, 0x77, 0x9d, + 0x44, 0xeb, 0xfe, 0xad, 0x02, 0xe6, 0x64, 0x4c, 0xe0, 0xd5, 0xd4, 0xdb, 0x1c, 0x41, 0x94, 0x5f, + 0xfd, 0x2e, 0xc3, 0x6d, 0xd9, 0x15, 0xa8, 0xaf, 0x78, 0x81, 0x3b, 0xcc, 0x71, 0xf5, 0xe8, 0x53, + 0xba, 0xde, 0xf0, 0xd9, 0x1d, 0x7a, 0x97, 0x51, 0xc7, 0x6f, 0x19, 0xf3, 0xd9, 0x1e, 0xc2, 0xb8, + 0xf4, 0xe4, 0xb0, 0x32, 0xf3, 0xf4, 0xb0, 0x32, 0xf3, 0xec, 0xb0, 0x32, 0xf3, 0x65, 0xbf, 0xa2, + 0x3c, 0xe9, 0x57, 0x94, 0xa7, 0xfd, 0x8a, 0xf2, 0xac, 0x5f, 0x51, 0xfe, 0xec, 0x57, 0x94, 0xef, + 0x9e, 0x57, 0x66, 0x3e, 0x9e, 0x93, 0x19, 0xfe, 0x27, 0x00, 0x00, 0xff, 0xff, 0x71, 0xb9, 0xee, + 0xef, 0x15, 0x19, 0x00, 0x00, } func (m *AddressGroup) Marshal() (dAtA []byte, err error) { @@ -1415,6 +1452,18 @@ func (m *NetworkPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.SourceRef != nil { + { + size, err := m.SourceRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } if m.TierPriority != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.TierPriority)) i-- @@ -1555,6 +1604,49 @@ func (m *NetworkPolicyPeer) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *NetworkPolicyReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NetworkPolicyReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NetworkPolicyReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.UID) + copy(dAtA[i:], m.UID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) + i-- + dAtA[i] = 0x22 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x1a + i -= len(m.Namespace) + copy(dAtA[i:], m.Namespace) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Namespace))) + i-- + dAtA[i] = 0x12 + i -= len(m.Type) + copy(dAtA[i:], m.Type) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *NetworkPolicyRule) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2012,6 +2104,10 @@ func (m *NetworkPolicy) Size() (n int) { if m.TierPriority != nil { n += 1 + sovGenerated(uint64(*m.TierPriority)) } + if m.SourceRef != nil { + l = m.SourceRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -2053,6 +2149,23 @@ func (m *NetworkPolicyPeer) Size() (n int) { return n } +func (m *NetworkPolicyReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Type) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Namespace) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.UID) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *NetworkPolicyRule) Size() (n int) { if m == nil { return 0 @@ -2374,6 +2487,7 @@ func (this *NetworkPolicy) String() string { `AppliedToGroups:` + fmt.Sprintf("%v", this.AppliedToGroups) + `,`, `Priority:` + valueToStringGenerated(this.Priority) + `,`, `TierPriority:` + valueToStringGenerated(this.TierPriority) + `,`, + `SourceRef:` + strings.Replace(this.SourceRef.String(), "NetworkPolicyReference", "NetworkPolicyReference", 1) + `,`, `}`, }, "") return s @@ -2410,6 +2524,19 @@ func (this *NetworkPolicyPeer) String() string { }, "") return s } +func (this *NetworkPolicyReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicyReference{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `}`, + }, "") + return s +} func (this *NetworkPolicyRule) String() string { if this == nil { return "nil" @@ -4528,6 +4655,42 @@ func (m *NetworkPolicy) Unmarshal(dAtA []byte) error { } } m.TierPriority = &v + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SourceRef", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SourceRef == nil { + m.SourceRef = &NetworkPolicyReference{} + } + if err := m.SourceRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -4791,6 +4954,187 @@ func (m *NetworkPolicyPeer) Unmarshal(dAtA []byte) error { } return nil } +func (m *NetworkPolicyReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NetworkPolicyReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NetworkPolicyReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Type = NetworkPolicyType(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Namespace = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *NetworkPolicyRule) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/pkg/apis/controlplane/v1beta1/generated.proto b/pkg/apis/controlplane/v1beta1/generated.proto index 5b3f05b0f1c..9e5952c3507 100644 --- a/pkg/apis/controlplane/v1beta1/generated.proto +++ b/pkg/apis/controlplane/v1beta1/generated.proto @@ -173,6 +173,7 @@ message NamedPort { } // +genclient +// +genclient:nonNamespaced // +genclient:onlyVerbs=list,get,watch // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // NetworkPolicy is the message format of antrea/pkg/controller/types.NetworkPolicy in an API response. @@ -192,6 +193,9 @@ message NetworkPolicy { // TierPriority represents the priority of the Tier associated with this Network // Policy. The TierPriority will remain nil for K8s NetworkPolicy. optional uint32 tierPriority = 5; + + // Reference to the original NetworkPolicy that the internal NetworkPolicy is created for. + optional NetworkPolicyReference sourceRef = 6; } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -212,6 +216,20 @@ message NetworkPolicyPeer { repeated IPBlock ipBlocks = 2; } +message NetworkPolicyReference { + // Type of the NetworkPolicy. + optional string type = 1; + + // Namespace of the NetworkPolicy. It's empty for ClusterNetworkPolicy. + optional string namespace = 2; + + // Name of the NetworkPolicy. + optional string name = 3; + + // UID of the NetworkPolicy. + optional string uID = 4; +} + // NetworkPolicyRule describes a particular set of traffic that is allowed. message NetworkPolicyRule { // The direction of this rule. diff --git a/pkg/apis/controlplane/v1beta1/helper.go b/pkg/apis/controlplane/v1beta1/helper.go index 5a3d4c2dd2c..a409e66af75 100644 --- a/pkg/apis/controlplane/v1beta1/helper.go +++ b/pkg/apis/controlplane/v1beta1/helper.go @@ -14,6 +14,8 @@ package v1beta1 +import "fmt" + // Conversion functions between GroupMember and GroupMemberPod func (g *GroupMember) ToGroupMemberPod() *GroupMemberPod { return &GroupMemberPod{ @@ -31,3 +33,11 @@ func (p *GroupMemberPod) ToGroupMember() *GroupMember { }, } } + +func (r *NetworkPolicyReference) ToString() string { + if r.Type == ClusterNetworkPolicy { + return fmt.Sprintf("%s:%s", r.Type, r.Name) + } else { + return fmt.Sprintf("%s:%s/%s", r.Type, r.Namespace, r.Name) + } +} diff --git a/pkg/apis/controlplane/v1beta1/types.go b/pkg/apis/controlplane/v1beta1/types.go index 437aa1619dd..467754c1a3b 100644 --- a/pkg/apis/controlplane/v1beta1/types.go +++ b/pkg/apis/controlplane/v1beta1/types.go @@ -16,6 +16,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" @@ -155,7 +156,30 @@ type AddressGroupList struct { // TierPriority indicates higher precedence. type TierPriority uint32 +type NetworkPolicyType string + +const ( + // It represents the K8s NetworkPolicy. + K8sNetworkPolicy NetworkPolicyType = "K8sNetworkPolicy" + // It represents the Antrea ClusterNetworkPolicy. + ClusterNetworkPolicy NetworkPolicyType = "ClusterNetworkPolicy" + // It represents the Antrea NetworkPolicy. + AntreaNetworkPolicy NetworkPolicyType = "AntreaNetworkPolicy" +) + +type NetworkPolicyReference struct { + // Type of the NetworkPolicy. + Type NetworkPolicyType `protobuf:"bytes,1,opt,name=type,casttype=NetworkPolicyType"` + // Namespace of the NetworkPolicy. It's empty for ClusterNetworkPolicy. + Namespace string `protobuf:"bytes,2,opt,name=namespace"` + // Name of the NetworkPolicy. + Name string `protobuf:"bytes,3,opt,name=name"` + // UID of the NetworkPolicy. + UID types.UID `protobuf:"bytes,4,opt,name=uID,casttype=k8s.io/apimachinery/pkg/types.UID"` +} + // +genclient +// +genclient:nonNamespaced // +genclient:onlyVerbs=list,get,watch // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // NetworkPolicy is the message format of antrea/pkg/controller/types.NetworkPolicy in an API response. @@ -172,6 +196,8 @@ type NetworkPolicy struct { // TierPriority represents the priority of the Tier associated with this Network // Policy. The TierPriority will remain nil for K8s NetworkPolicy. TierPriority *TierPriority `json:"tierPriority,omitempty" protobuf:"varint,5,opt,name=tierPriority"` + // Reference to the original NetworkPolicy that the internal NetworkPolicy is created for. + SourceRef *NetworkPolicyReference `json:"sourceRef,omitempty" protobuf:"bytes,6,opt,name=sourceRef"` } // Direction defines traffic direction of NetworkPolicyRule. diff --git a/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go b/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go index abf52d54b7e..e66541de3f0 100644 --- a/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go +++ b/pkg/apis/controlplane/v1beta1/zz_generated.conversion.go @@ -25,6 +25,7 @@ import ( v1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" + types "k8s.io/apimachinery/pkg/types" intstr "k8s.io/apimachinery/pkg/util/intstr" ) @@ -195,6 +196,16 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } + if err := s.AddGeneratedConversionFunc((*NetworkPolicyReference)(nil), (*controlplane.NetworkPolicyReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkPolicyReference_To_controlplane_NetworkPolicyReference(a.(*NetworkPolicyReference), b.(*controlplane.NetworkPolicyReference), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*controlplane.NetworkPolicyReference)(nil), (*NetworkPolicyReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_controlplane_NetworkPolicyReference_To_v1beta1_NetworkPolicyReference(a.(*controlplane.NetworkPolicyReference), b.(*NetworkPolicyReference), scope) + }); err != nil { + return err + } if err := s.AddGeneratedConversionFunc((*NetworkPolicyRule)(nil), (*controlplane.NetworkPolicyRule)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_NetworkPolicyRule_To_controlplane_NetworkPolicyRule(a.(*NetworkPolicyRule), b.(*controlplane.NetworkPolicyRule), scope) }); err != nil { @@ -546,6 +557,7 @@ func autoConvert_v1beta1_NetworkPolicy_To_controlplane_NetworkPolicy(in *Network out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) out.Priority = (*float64)(unsafe.Pointer(in.Priority)) out.TierPriority = (*controlplane.TierPriority)(unsafe.Pointer(in.TierPriority)) + out.SourceRef = (*controlplane.NetworkPolicyReference)(unsafe.Pointer(in.SourceRef)) return nil } @@ -560,6 +572,7 @@ func autoConvert_controlplane_NetworkPolicy_To_v1beta1_NetworkPolicy(in *control out.AppliedToGroups = *(*[]string)(unsafe.Pointer(&in.AppliedToGroups)) out.Priority = (*float64)(unsafe.Pointer(in.Priority)) out.TierPriority = (*TierPriority)(unsafe.Pointer(in.TierPriority)) + out.SourceRef = (*NetworkPolicyReference)(unsafe.Pointer(in.SourceRef)) return nil } @@ -612,6 +625,32 @@ func Convert_controlplane_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in *con return autoConvert_controlplane_NetworkPolicyPeer_To_v1beta1_NetworkPolicyPeer(in, out, s) } +func autoConvert_v1beta1_NetworkPolicyReference_To_controlplane_NetworkPolicyReference(in *NetworkPolicyReference, out *controlplane.NetworkPolicyReference, s conversion.Scope) error { + out.Type = controlplane.NetworkPolicyType(in.Type) + out.Namespace = in.Namespace + out.Name = in.Name + out.UID = types.UID(in.UID) + return nil +} + +// Convert_v1beta1_NetworkPolicyReference_To_controlplane_NetworkPolicyReference is an autogenerated conversion function. +func Convert_v1beta1_NetworkPolicyReference_To_controlplane_NetworkPolicyReference(in *NetworkPolicyReference, out *controlplane.NetworkPolicyReference, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkPolicyReference_To_controlplane_NetworkPolicyReference(in, out, s) +} + +func autoConvert_controlplane_NetworkPolicyReference_To_v1beta1_NetworkPolicyReference(in *controlplane.NetworkPolicyReference, out *NetworkPolicyReference, s conversion.Scope) error { + out.Type = NetworkPolicyType(in.Type) + out.Namespace = in.Namespace + out.Name = in.Name + out.UID = types.UID(in.UID) + return nil +} + +// Convert_controlplane_NetworkPolicyReference_To_v1beta1_NetworkPolicyReference is an autogenerated conversion function. +func Convert_controlplane_NetworkPolicyReference_To_v1beta1_NetworkPolicyReference(in *controlplane.NetworkPolicyReference, out *NetworkPolicyReference, s conversion.Scope) error { + return autoConvert_controlplane_NetworkPolicyReference_To_v1beta1_NetworkPolicyReference(in, out, s) +} + func autoConvert_v1beta1_NetworkPolicyRule_To_controlplane_NetworkPolicyRule(in *NetworkPolicyRule, out *controlplane.NetworkPolicyRule, s conversion.Scope) error { out.Direction = controlplane.Direction(in.Direction) if err := Convert_v1beta1_NetworkPolicyPeer_To_controlplane_NetworkPolicyPeer(&in.From, &out.From, s); err != nil { diff --git a/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go b/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go index 8d10a6a863a..ce3e86afd3b 100644 --- a/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go +++ b/pkg/apis/controlplane/v1beta1/zz_generated.deepcopy.go @@ -522,6 +522,11 @@ func (in *NetworkPolicy) DeepCopyInto(out *NetworkPolicy) { *out = new(TierPriority) **out = **in } + if in.SourceRef != nil { + in, out := &in.SourceRef, &out.SourceRef + *out = new(NetworkPolicyReference) + **out = **in + } return } @@ -604,6 +609,22 @@ func (in *NetworkPolicyPeer) DeepCopy() *NetworkPolicyPeer { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NetworkPolicyReference) DeepCopyInto(out *NetworkPolicyReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkPolicyReference. +func (in *NetworkPolicyReference) DeepCopy() *NetworkPolicyReference { + if in == nil { + return nil + } + out := new(NetworkPolicyReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkPolicyRule) DeepCopyInto(out *NetworkPolicyRule) { *out = *in diff --git a/pkg/apis/controlplane/zz_generated.deepcopy.go b/pkg/apis/controlplane/zz_generated.deepcopy.go index 58723dab101..de1b3cc6885 100644 --- a/pkg/apis/controlplane/zz_generated.deepcopy.go +++ b/pkg/apis/controlplane/zz_generated.deepcopy.go @@ -522,6 +522,11 @@ func (in *NetworkPolicy) DeepCopyInto(out *NetworkPolicy) { *out = new(TierPriority) **out = **in } + if in.SourceRef != nil { + in, out := &in.SourceRef, &out.SourceRef + *out = new(NetworkPolicyReference) + **out = **in + } return } @@ -604,6 +609,22 @@ func (in *NetworkPolicyPeer) DeepCopy() *NetworkPolicyPeer { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NetworkPolicyReference) DeepCopyInto(out *NetworkPolicyReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkPolicyReference. +func (in *NetworkPolicyReference) DeepCopy() *NetworkPolicyReference { + if in == nil { + return nil + } + out := new(NetworkPolicyReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NetworkPolicyRule) DeepCopyInto(out *NetworkPolicyRule) { *out = *in diff --git a/pkg/apiserver/openapi/zz_generated.openapi.go b/pkg/apiserver/openapi/zz_generated.openapi.go index d42a74ec1e7..9c27adb9e43 100644 --- a/pkg/apiserver/openapi/zz_generated.openapi.go +++ b/pkg/apiserver/openapi/zz_generated.openapi.go @@ -53,6 +53,7 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicy": schema_pkg_apis_controlplane_v1beta1_NetworkPolicy(ref), "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyList": schema_pkg_apis_controlplane_v1beta1_NetworkPolicyList(ref), "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyPeer": schema_pkg_apis_controlplane_v1beta1_NetworkPolicyPeer(ref), + "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyReference": schema_pkg_apis_controlplane_v1beta1_NetworkPolicyReference(ref), "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyRule": schema_pkg_apis_controlplane_v1beta1_NetworkPolicyRule(ref), "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.PodReference": schema_pkg_apis_controlplane_v1beta1_PodReference(ref), "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.Service": schema_pkg_apis_controlplane_v1beta1_Service(ref), @@ -1444,11 +1445,17 @@ func schema_pkg_apis_controlplane_v1beta1_NetworkPolicy(ref common.ReferenceCall Format: "int64", }, }, + "sourceRef": { + SchemaProps: spec.SchemaProps{ + Description: "Reference to the original NetworkPolicy that the internal NetworkPolicy is created for.", + Ref: ref("github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyReference"), + }, + }, }, }, }, Dependencies: []string{ - "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyReference", "github.com/vmware-tanzu/antrea/pkg/apis/controlplane/v1beta1.NetworkPolicyRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, } } @@ -1541,6 +1548,47 @@ func schema_pkg_apis_controlplane_v1beta1_NetworkPolicyPeer(ref common.Reference } } +func schema_pkg_apis_controlplane_v1beta1_NetworkPolicyReference(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "Type": { + SchemaProps: spec.SchemaProps{ + Description: "Type of the NetworkPolicy.", + Type: []string{"string"}, + Format: "", + }, + }, + "Namespace": { + SchemaProps: spec.SchemaProps{ + Description: "Namespace of the NetworkPolicy. It's empty for ClusterNetworkPolicy.", + Type: []string{"string"}, + Format: "", + }, + }, + "Name": { + SchemaProps: spec.SchemaProps{ + Description: "Name of the NetworkPolicy.", + Type: []string{"string"}, + Format: "", + }, + }, + "UID": { + SchemaProps: spec.SchemaProps{ + Description: "UID of the NetworkPolicy.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"Type", "Namespace", "Name", "UID"}, + }, + }, + } +} + func schema_pkg_apis_controlplane_v1beta1_NetworkPolicyRule(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ diff --git a/pkg/apiserver/registry/networkpolicy/networkpolicy/rest.go b/pkg/apiserver/registry/networkpolicy/networkpolicy/rest.go index 06f4fdeca01..c64765e696c 100644 --- a/pkg/apiserver/registry/networkpolicy/networkpolicy/rest.go +++ b/pkg/apiserver/registry/networkpolicy/networkpolicy/rest.go @@ -78,32 +78,22 @@ func (r *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) } func (r *REST) List(ctx context.Context, options *internalversion.ListOptions) (runtime.Object, error) { - ns, namespaceScoped := request.NamespaceFrom(ctx) networkPolicies := r.networkPolicyStore.List() - list := new(controlplane.NetworkPolicyList) + list := &controlplane.NetworkPolicyList{ + Items: make([]controlplane.NetworkPolicy, len(networkPolicies)), + } for i := range networkPolicies { - if !namespaceScoped || len(ns) == 0 || networkPolicies[i].(*types.NetworkPolicy).Namespace == ns { - policy := controlplane.NetworkPolicy{} - store.ToNetworkPolicyMsg(networkPolicies[i].(*types.NetworkPolicy), &policy, true) - list.Items = append(list.Items, policy) - } + store.ToNetworkPolicyMsg(networkPolicies[i].(*types.NetworkPolicy), &list.Items[i], true) } return list, nil } func (r *REST) NamespaceScoped() bool { - return true + return false } func (r *REST) Watch(ctx context.Context, options *internalversion.ListOptions) (watch.Interface, error) { key, label, field := networkpolicy.GetSelectors(options) - if len(key) > 0 { - ns, ok := request.NamespaceFrom(ctx) - if !ok || len(ns) == 0 { - return nil, errors.NewBadRequest("Namespace parameter required.") - } - key = k8s.NamespacedName(ns, key) - } return r.networkPolicyStore.Watch(ctx, key, label, field) } diff --git a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/controlplane_client.go b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/controlplane_client.go index caeb306ddfd..6a92a637c8b 100644 --- a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/controlplane_client.go +++ b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/controlplane_client.go @@ -42,8 +42,8 @@ func (c *ControlplaneV1beta1Client) AppliedToGroups() AppliedToGroupInterface { return newAppliedToGroups(c) } -func (c *ControlplaneV1beta1Client) NetworkPolicies(namespace string) NetworkPolicyInterface { - return newNetworkPolicies(c, namespace) +func (c *ControlplaneV1beta1Client) NetworkPolicies() NetworkPolicyInterface { + return newNetworkPolicies(c) } // NewForConfig creates a new ControlplaneV1beta1Client for the given config. diff --git a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_controlplane_client.go b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_controlplane_client.go index 5e1079ac184..3b563dd2393 100644 --- a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_controlplane_client.go +++ b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_controlplane_client.go @@ -34,8 +34,8 @@ func (c *FakeControlplaneV1beta1) AppliedToGroups() v1beta1.AppliedToGroupInterf return &FakeAppliedToGroups{c} } -func (c *FakeControlplaneV1beta1) NetworkPolicies(namespace string) v1beta1.NetworkPolicyInterface { - return &FakeNetworkPolicies{c, namespace} +func (c *FakeControlplaneV1beta1) NetworkPolicies() v1beta1.NetworkPolicyInterface { + return &FakeNetworkPolicies{c} } // RESTClient returns a RESTClient that is used to communicate diff --git a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_networkpolicy.go b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_networkpolicy.go index 95237367bf0..f1e8b937c85 100644 --- a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_networkpolicy.go +++ b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/fake/fake_networkpolicy.go @@ -30,7 +30,6 @@ import ( // FakeNetworkPolicies implements NetworkPolicyInterface type FakeNetworkPolicies struct { Fake *FakeControlplaneV1beta1 - ns string } var networkpoliciesResource = schema.GroupVersionResource{Group: "controlplane.antrea.tanzu.vmware.com", Version: "v1beta1", Resource: "networkpolicies"} @@ -40,8 +39,7 @@ var networkpoliciesKind = schema.GroupVersionKind{Group: "controlplane.antrea.ta // Get takes name of the networkPolicy, and returns the corresponding networkPolicy object, and an error if there is any. func (c *FakeNetworkPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NetworkPolicy, err error) { obj, err := c.Fake. - Invokes(testing.NewGetAction(networkpoliciesResource, c.ns, name), &v1beta1.NetworkPolicy{}) - + Invokes(testing.NewRootGetAction(networkpoliciesResource, name), &v1beta1.NetworkPolicy{}) if obj == nil { return nil, err } @@ -51,8 +49,7 @@ func (c *FakeNetworkPolicies) Get(ctx context.Context, name string, options v1.G // List takes label and field selectors, and returns the list of NetworkPolicies that match those selectors. func (c *FakeNetworkPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.NetworkPolicyList, err error) { obj, err := c.Fake. - Invokes(testing.NewListAction(networkpoliciesResource, networkpoliciesKind, c.ns, opts), &v1beta1.NetworkPolicyList{}) - + Invokes(testing.NewRootListAction(networkpoliciesResource, networkpoliciesKind, opts), &v1beta1.NetworkPolicyList{}) if obj == nil { return nil, err } @@ -73,6 +70,5 @@ func (c *FakeNetworkPolicies) List(ctx context.Context, opts v1.ListOptions) (re // Watch returns a watch.Interface that watches the requested networkPolicies. func (c *FakeNetworkPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { return c.Fake. - InvokesWatch(testing.NewWatchAction(networkpoliciesResource, c.ns, opts)) - + InvokesWatch(testing.NewRootWatchAction(networkpoliciesResource, opts)) } diff --git a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/networkpolicy.go b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/networkpolicy.go index f5a47610117..811fd1f3920 100644 --- a/pkg/client/clientset/versioned/typed/controlplane/v1beta1/networkpolicy.go +++ b/pkg/client/clientset/versioned/typed/controlplane/v1beta1/networkpolicy.go @@ -30,7 +30,7 @@ import ( // NetworkPoliciesGetter has a method to return a NetworkPolicyInterface. // A group's client should implement this interface. type NetworkPoliciesGetter interface { - NetworkPolicies(namespace string) NetworkPolicyInterface + NetworkPolicies() NetworkPolicyInterface } // NetworkPolicyInterface has methods to work with NetworkPolicy resources. @@ -44,14 +44,12 @@ type NetworkPolicyInterface interface { // networkPolicies implements NetworkPolicyInterface type networkPolicies struct { client rest.Interface - ns string } // newNetworkPolicies returns a NetworkPolicies -func newNetworkPolicies(c *ControlplaneV1beta1Client, namespace string) *networkPolicies { +func newNetworkPolicies(c *ControlplaneV1beta1Client) *networkPolicies { return &networkPolicies{ client: c.RESTClient(), - ns: namespace, } } @@ -59,7 +57,6 @@ func newNetworkPolicies(c *ControlplaneV1beta1Client, namespace string) *network func (c *networkPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NetworkPolicy, err error) { result = &v1beta1.NetworkPolicy{} err = c.client.Get(). - Namespace(c.ns). Resource("networkpolicies"). Name(name). VersionedParams(&options, scheme.ParameterCodec). @@ -76,7 +73,6 @@ func (c *networkPolicies) List(ctx context.Context, opts v1.ListOptions) (result } result = &v1beta1.NetworkPolicyList{} err = c.client.Get(). - Namespace(c.ns). Resource("networkpolicies"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). @@ -93,7 +89,6 @@ func (c *networkPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch } opts.Watch = true return c.client.Get(). - Namespace(c.ns). Resource("networkpolicies"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy.go b/pkg/controller/networkpolicy/antreanetworkpolicy.go index f5fa10d6750..cfa6e375a11 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy.go @@ -34,8 +34,7 @@ func (n *NetworkPolicyController) addANP(obj interface{}) { internalNP := n.processAntreaNetworkPolicy(np) klog.Infof("Creating new internal NetworkPolicy %#v", internalNP) n.internalNetworkPolicyStore.Create(internalNP) - key, _ := keyFunc(np) - n.enqueueInternalNetworkPolicy(key) + n.enqueueInternalNetworkPolicy(internalNetworkPolicyKeyFunc(np)) } // updateANP receives AntreaNetworkPolicy UPDATE events and updates resources @@ -48,10 +47,8 @@ func (n *NetworkPolicyController) updateANP(old, cur interface{}) { // enqueue task to internal NetworkPolicy Workqueue. curInternalNP := n.processAntreaNetworkPolicy(curNP) klog.V(2).Infof("Updating existing internal NetworkPolicy %s", curInternalNP.Name) - // Retrieve old secv1alpha1.NetworkPolicy object. - oldNP := old.(*secv1alpha1.NetworkPolicy) // Old and current NetworkPolicy share the same key. - key, _ := keyFunc(oldNP) + key := internalNetworkPolicyKeyFunc(curNP) // Lock access to internal NetworkPolicy store such that concurrent access // to an internal NetworkPolicy is not allowed. This will avoid the // case in which an Update to an internal NetworkPolicy object may @@ -101,7 +98,7 @@ func (n *NetworkPolicyController) deleteANP(old interface{}) { } defer n.heartbeat("deleteANP") klog.Infof("Processing Antrea NetworkPolicy %s/%s DELETE event", np.Namespace, np.Name) - key, _ := keyFunc(np) + key := internalNetworkPolicyKeyFunc(np) oldInternalNPObj, _, _ := n.internalNetworkPolicyStore.Get(key) oldInternalNP := oldInternalNPObj.(*antreatypes.NetworkPolicy) klog.V(4).Infof("Old internal NetworkPolicy %#v", oldInternalNP) @@ -157,8 +154,13 @@ func (n *NetworkPolicyController) processAntreaNetworkPolicy(np *secv1alpha1.Net } tierPriority := getTierPriority(np.Spec.Tier) internalNetworkPolicy := &antreatypes.NetworkPolicy{ - Name: np.Name, - Namespace: np.Namespace, + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.AntreaNetworkPolicy, + Namespace: np.Namespace, + Name: np.Name, + UID: np.UID, + }, + Name: internalNetworkPolicyKeyFunc(np), UID: np.UID, AppliedToGroups: appliedToGroupNames, Rules: rules, diff --git a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go index 34458a0aa6a..794bd0ae10d 100644 --- a/pkg/controller/networkpolicy/antreanetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/antreanetworkpolicy_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" @@ -91,9 +92,14 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "ns1", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.AntreaNetworkPolicy, + Namespace: "ns1", + Name: "npA", + UID: "uidA", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -171,9 +177,14 @@ func TestProcessAntreaNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidB", - Name: "npB", - Namespace: "ns2", + UID: "uidB", + Name: "uidB", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.AntreaNetworkPolicy, + Namespace: "ns2", + Name: "npB", + UID: "uidB", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -278,9 +289,14 @@ func TestAddANP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "anpA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.AntreaNetworkPolicy, + Namespace: "nsA", + Name: "anpA", + UID: "uidA", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -309,8 +325,8 @@ func TestAddANP(t *testing.T) { t.Run(tt.name, func(t *testing.T) { _, npc := newController() npc.addANP(tt.inputPolicy) - key, _ := keyFunc(tt.inputPolicy) - actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(key) + actualPolicyObj, exists, _ := npc.internalNetworkPolicyStore.Get(internalNetworkPolicyKeyFunc(tt.inputPolicy)) + require.True(t, exists) actualPolicy := actualPolicyObj.(*antreatypes.NetworkPolicy) if !reflect.DeepEqual(actualPolicy, tt.expPolicy) { t.Errorf("addANP() got %v, want %v", actualPolicy, tt.expPolicy) @@ -371,7 +387,7 @@ func getANP() *secv1alpha1.NetworkPolicy { }, } npObj := &secv1alpha1.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "test-ns", Name: "test-anp"}, + ObjectMeta: metav1.ObjectMeta{Namespace: "test-ns", Name: "test-anp", UID: "test-id"}, Spec: secv1alpha1.NetworkPolicySpec{ AppliedTo: []secv1alpha1.NetworkPolicyPeer{ {PodSelector: &selectorA}, diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy.go b/pkg/controller/networkpolicy/clusternetworkpolicy.go index 4012b97b08b..bb427eee55f 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy.go @@ -45,8 +45,7 @@ func (n *NetworkPolicyController) addCNP(obj interface{}) { internalNP := n.processClusterNetworkPolicy(cnp) klog.Infof("Creating new internal NetworkPolicy %#v", internalNP) n.internalNetworkPolicyStore.Create(internalNP) - key, _ := keyFunc(cnp) - n.enqueueInternalNetworkPolicy(key) + n.enqueueInternalNetworkPolicy(internalNetworkPolicyKeyFunc(cnp)) } // updateCNP receives ClusterNetworkPolicy UPDATE events and updates resources @@ -59,10 +58,8 @@ func (n *NetworkPolicyController) updateCNP(old, cur interface{}) { // enqueue task to internal NetworkPolicy Workqueue. curInternalNP := n.processClusterNetworkPolicy(curCNP) klog.V(2).Infof("Updating existing internal NetworkPolicy %s", curInternalNP.Name) - // Retrieve old secv1alpha1.NetworkPolicy object. - oldCNP := old.(*secv1alpha1.ClusterNetworkPolicy) // Old and current NetworkPolicy share the same key. - key, _ := keyFunc(oldCNP) + key := internalNetworkPolicyKeyFunc(curCNP) // Lock access to internal NetworkPolicy store such that concurrent access // to an internal NetworkPolicy is not allowed. This will avoid the // case in which an Update to an internal NetworkPolicy object may @@ -112,7 +109,7 @@ func (n *NetworkPolicyController) deleteCNP(old interface{}) { } defer n.heartbeat("deleteCNP") klog.Infof("Processing ClusterNetworkPolicy %s DELETE event", cnp.Name) - key, _ := keyFunc(cnp) + key := internalNetworkPolicyKeyFunc(cnp) oldInternalNPObj, _, _ := n.internalNetworkPolicyStore.Get(key) oldInternalNP := oldInternalNPObj.(*antreatypes.NetworkPolicy) klog.Infof("Old internal NetworkPolicy %#v", oldInternalNP) @@ -167,8 +164,12 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *secv1alpha1.C } tierPriority := getTierPriority(cnp.Spec.Tier) internalNetworkPolicy := &antreatypes.NetworkPolicy{ - Name: cnp.Name, - Namespace: "", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: cnp.Name, + UID: cnp.UID, + }, + Name: internalNetworkPolicyKeyFunc(cnp), UID: cnp.UID, AppliedToGroups: appliedToGroupNames, Rules: rules, diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go index a1045ad4b09..506a709413d 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go @@ -15,6 +15,7 @@ package networkpolicy import ( + "github.com/stretchr/testify/require" "reflect" "testing" @@ -87,9 +88,13 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "cnpA", - Namespace: "", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpA", + UID: "uidA", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -167,9 +172,13 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "cnpA", - Namespace: "", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpA", + UID: "uidA", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -280,9 +289,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "cnpA", - Namespace: "", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpA", + UID: "uidA", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -335,9 +348,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidB", - Name: "cnpB", - Namespace: "", + UID: "uidB", + Name: "uidB", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpB", + UID: "uidB", + }, Priority: &p10, TierPriority: &secOpsTier, Rules: []controlplane.NetworkPolicyRule{ @@ -390,9 +407,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidC", - Name: "cnpC", - Namespace: "", + UID: "uidC", + Name: "uidC", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpC", + UID: "uidC", + }, Priority: &p10, TierPriority: &netOpsTier, Rules: []controlplane.NetworkPolicyRule{ @@ -445,9 +466,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidD", - Name: "cnpD", - Namespace: "", + UID: "uidD", + Name: "uidD", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpD", + UID: "uidD", + }, Priority: &p10, TierPriority: &emergencyTier, Rules: []controlplane.NetworkPolicyRule{ @@ -500,9 +525,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidE", - Name: "cnpE", - Namespace: "", + UID: "uidE", + Name: "uidE", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpE", + UID: "uidE", + }, Priority: &p10, TierPriority: &platformTier, Rules: []controlplane.NetworkPolicyRule{ @@ -570,9 +599,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidF", - Name: "cnpF", - Namespace: "", + UID: "uidF", + Name: "uidF", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpF", + UID: "uidF", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -650,9 +683,13 @@ func TestAddCNP(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidG", - Name: "cnpG", - Namespace: "", + UID: "uidG", + Name: "uidG", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.ClusterNetworkPolicy, + Name: "cnpG", + UID: "uidG", + }, Priority: &p10, TierPriority: &appTier, Rules: []controlplane.NetworkPolicyRule{ @@ -695,8 +732,8 @@ func TestAddCNP(t *testing.T) { t.Run(tt.name, func(t *testing.T) { _, npc := newController() npc.addCNP(tt.inputPolicy) - key, _ := keyFunc(tt.inputPolicy) - actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(key) + actualPolicyObj, exists, _ := npc.internalNetworkPolicyStore.Get(internalNetworkPolicyKeyFunc(tt.inputPolicy)) + require.True(t, exists) actualPolicy := actualPolicyObj.(*antreatypes.NetworkPolicy) if !reflect.DeepEqual(actualPolicy, tt.expPolicy) { t.Errorf("addCNP() got %v, want %v", actualPolicy, tt.expPolicy) diff --git a/pkg/controller/networkpolicy/endpoint_querier.go b/pkg/controller/networkpolicy/endpoint_querier.go index 70dd6c87645..154bb09faaf 100644 --- a/pkg/controller/networkpolicy/endpoint_querier.go +++ b/pkg/controller/networkpolicy/endpoint_querier.go @@ -162,9 +162,9 @@ func (eq *endpointQuerier) QueryNetworkPolicies(namespace string, podName string for _, internalPolicy := range applied { responsePolicy := Policy{ PolicyRef: PolicyRef{ - Namespace: internalPolicy.Namespace, - Name: internalPolicy.Name, - UID: internalPolicy.UID, + Namespace: internalPolicy.SourceRef.Namespace, + Name: internalPolicy.SourceRef.Name, + UID: internalPolicy.SourceRef.UID, }, } responsePolicies = append(responsePolicies, responsePolicy) @@ -174,9 +174,9 @@ func (eq *endpointQuerier) QueryNetworkPolicies(namespace string, podName string for _, internalPolicy := range egress { newRule := Rule{ PolicyRef: PolicyRef{ - Namespace: internalPolicy.policy.Namespace, - Name: internalPolicy.policy.Name, - UID: internalPolicy.policy.UID, + Namespace: internalPolicy.policy.SourceRef.Namespace, + Name: internalPolicy.policy.SourceRef.Name, + UID: internalPolicy.policy.SourceRef.UID, }, Direction: cpv1beta1.DirectionOut, RuleIndex: internalPolicy.index, @@ -186,9 +186,9 @@ func (eq *endpointQuerier) QueryNetworkPolicies(namespace string, podName string for _, internalPolicy := range ingress { newRule := Rule{ PolicyRef: PolicyRef{ - Namespace: internalPolicy.policy.Namespace, - Name: internalPolicy.policy.Name, - UID: internalPolicy.policy.UID, + Namespace: internalPolicy.policy.SourceRef.Namespace, + Name: internalPolicy.policy.SourceRef.Name, + UID: internalPolicy.policy.SourceRef.UID, }, Direction: cpv1beta1.DirectionIn, RuleIndex: internalPolicy.index, diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index d6f94e149fd..cd7bf5854f6 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -627,9 +627,14 @@ func (n *NetworkPolicyController) processNetworkPolicy(np *networkingv1.NetworkP } internalNetworkPolicy := &antreatypes.NetworkPolicy{ - Name: np.ObjectMeta.Name, - Namespace: np.ObjectMeta.Namespace, - UID: np.ObjectMeta.UID, + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: np.Namespace, + Name: np.Name, + UID: np.UID, + }, + Name: internalNetworkPolicyKeyFunc(np), + UID: np.UID, AppliedToGroups: appliedToGroupNames, Rules: rules, } @@ -684,10 +689,9 @@ func (n *NetworkPolicyController) addNetworkPolicy(obj interface{}) { // Create an internal NetworkPolicy object corresponding to this NetworkPolicy // and enqueue task to internal NetworkPolicy Workqueue. internalNP := n.processNetworkPolicy(np) - klog.Infof("Creating new internal NetworkPolicy %s/%s", internalNP.Namespace, internalNP.Name) + klog.Infof("Creating new internal NetworkPolicy %s for %s", internalNP.Name, internalNP.SourceRef.ToString()) n.internalNetworkPolicyStore.Create(internalNP) - key, _ := keyFunc(np) - n.enqueueInternalNetworkPolicy(key) + n.enqueueInternalNetworkPolicy(internalNetworkPolicyKeyFunc(np)) } // updateNetworkPolicy receives NetworkPolicy UPDATE events and updates resources @@ -699,11 +703,9 @@ func (n *NetworkPolicyController) updateNetworkPolicy(old, cur interface{}) { // Update an internal NetworkPolicy ID, corresponding to this NetworkPolicy and // enqueue task to internal NetworkPolicy Workqueue. curInternalNP := n.processNetworkPolicy(np) - klog.V(2).Infof("Updating existing internal NetworkPolicy %s/%s", curInternalNP.Namespace, curInternalNP.Name) - // Retrieve old networkingv1.NetworkPolicy object. - oldNP := old.(*networkingv1.NetworkPolicy) + klog.V(2).Infof("Updating existing internal NetworkPolicy %s for %s", curInternalNP.Name, curInternalNP.SourceRef.ToString()) // Old and current NetworkPolicy share the same key. - key, _ := keyFunc(oldNP) + key := internalNetworkPolicyKeyFunc(np) // Lock access to internal NetworkPolicy store such that concurrent access // to an internal NetworkPolicy is not allowed. This will avoid the // case in which an Update to an internal NetworkPolicy object may @@ -758,7 +760,7 @@ func (n *NetworkPolicyController) deleteNetworkPolicy(old interface{}) { defer n.heartbeat("deleteNetworkPolicy") klog.V(2).Infof("Processing NetworkPolicy %s/%s DELETE event", np.Namespace, np.Name) - key, _ := keyFunc(np) + key := internalNetworkPolicyKeyFunc(np) oldInternalNPObj, _, _ := n.internalNetworkPolicyStore.Get(key) oldInternalNP := oldInternalNPObj.(*antreatypes.NetworkPolicy) // AppliedToGroups currently only supports a single member. @@ -1531,9 +1533,9 @@ func (n *NetworkPolicyController) syncInternalNetworkPolicy(key string) error { nodeNames = nodeNames.Union(appGroup.SpanMeta.NodeNames) } updatedNetworkPolicy := &antreatypes.NetworkPolicy{ + SourceRef: internalNP.SourceRef, UID: internalNP.UID, Name: internalNP.Name, - Namespace: internalNP.Namespace, Rules: internalNP.Rules, AppliedToGroups: internalNP.AppliedToGroups, Priority: internalNP.Priority, @@ -1587,3 +1589,7 @@ func cidrStrToIPNet(cidr string) (*controlplane.IPNet, error) { } return ipNet, nil } + +func internalNetworkPolicyKeyFunc(np metav1.Object) string { + return string(np.GetUID()) +} diff --git a/pkg/controller/networkpolicy/networkpolicy_controller_test.go b/pkg/controller/networkpolicy/networkpolicy_controller_test.go index b3cee0aa46f..7d26c064dca 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller_test.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller_test.go @@ -157,9 +157,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, From: matchAllPeer, @@ -183,9 +188,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidB", - Name: "npB", - Namespace: "nsA", + UID: "uidB", + Name: "uidB", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npB", + UID: "uidB", + }, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionOut, To: matchAllPeer, @@ -218,9 +228,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidB", - Name: "npB", - Namespace: "nsA", + UID: "uidB", + Name: "uidB", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npB", + UID: "uidB", + }, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionOut, To: matchAllPeerEgress, @@ -248,9 +263,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidC", - Name: "npC", - Namespace: "nsA", + UID: "uidC", + Name: "uidC", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npC", + UID: "uidC", + }, Rules: []controlplane.NetworkPolicyRule{ denyAllIngressRule, }, @@ -269,9 +289,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidD", - Name: "npD", - Namespace: "nsA", + UID: "uidD", + Name: "uidD", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npD", + UID: "uidD", + }, Rules: []controlplane.NetworkPolicyRule{ denyAllEgressRule, }, @@ -319,9 +344,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidE", - Name: "npE", - Namespace: "nsA", + UID: "uidE", + Name: "uidE", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npE", + UID: "uidE", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -392,9 +422,14 @@ func TestAddNetworkPolicy(t *testing.T) { }, }, expPolicy: &antreatypes.NetworkPolicy{ - UID: "uidF", - Name: "npF", - Namespace: "nsA", + UID: "uidF", + Name: "uidF", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npF", + UID: "uidF", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -435,20 +470,11 @@ func TestAddNetworkPolicy(t *testing.T) { t.Run(tt.name, func(t *testing.T) { _, npc := newController() npc.addNetworkPolicy(tt.inputPolicy) - key, _ := keyFunc(tt.inputPolicy) - actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(key) + actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(internalNetworkPolicyKeyFunc(tt.inputPolicy)) actualPolicy := actualPolicyObj.(*antreatypes.NetworkPolicy) - if !reflect.DeepEqual(actualPolicy, tt.expPolicy) { - t.Errorf("addNetworkPolicy() 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) - } + assert.Equal(t, tt.expPolicy, actualPolicy) + assert.Equal(t, tt.expAddressGroups, len(npc.addressGroupStore.List())) + assert.Equal(t, tt.expAppliedToGroups, len(npc.appliedToGroupStore.List())) }) } _, npc := newController() @@ -473,8 +499,7 @@ func TestDeleteNetworkPolicy(t *testing.T) { assert.False(t, found, "expected AppliedToGroup to be deleted") adgs := npc.addressGroupStore.List() assert.Len(t, adgs, 0, "expected empty AddressGroup list") - key, _ := keyFunc(npObj) - _, found, _ = npc.internalNetworkPolicyStore.Get(key) + _, found, _ = npc.internalNetworkPolicyStore.Get(internalNetworkPolicyKeyFunc(npObj)) assert.False(t, found, "expected internal NetworkPolicy to be deleted") } @@ -542,9 +567,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -587,9 +617,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionOut, @@ -624,9 +659,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -651,9 +691,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{}, AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, @@ -695,9 +740,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -757,9 +807,14 @@ func TestUpdateNetworkPolicy(t *testing.T) { }, }, expNetworkPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -789,8 +844,7 @@ func TestUpdateNetworkPolicy(t *testing.T) { _, npc := newController() npc.addNetworkPolicy(oldNP) npc.updateNetworkPolicy(oldNP, tt.updatedNetworkPolicy) - key, _ := keyFunc(oldNP) - actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(key) + actualPolicyObj, _, _ := npc.internalNetworkPolicyStore.Get(internalNetworkPolicyKeyFunc(oldNP)) actualPolicy := actualPolicyObj.(*antreatypes.NetworkPolicy) if actualAppliedToGroups := len(npc.appliedToGroupStore.List()); actualAppliedToGroups != tt.expAppliedToGroups { t.Errorf("updateNetworkPolicy() got %v, want %v", actualAppliedToGroups, tt.expAppliedToGroups) @@ -2383,9 +2437,14 @@ func TestProcessNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, From: matchAllPeer, @@ -2408,9 +2467,14 @@ func TestProcessNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{denyAllEgressRule}, AppliedToGroups: []string{getNormalizedUID(toGroupSelector("nsA", &metav1.LabelSelector{}, nil, nil).NormalizedName)}, }, @@ -2456,9 +2520,14 @@ func TestProcessNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, @@ -2529,9 +2598,14 @@ func TestProcessNetworkPolicy(t *testing.T) { }, }, expectedPolicy: &antreatypes.NetworkPolicy{ - UID: "uidA", - Name: "npA", - Namespace: "nsA", + UID: "uidA", + Name: "uidA", + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "nsA", + Name: "npA", + UID: "uidA", + }, Rules: []controlplane.NetworkPolicyRule{ { Direction: controlplane.DirectionIn, diff --git a/pkg/controller/networkpolicy/store/networkpolicy.go b/pkg/controller/networkpolicy/store/networkpolicy.go index 0b17f900951..26926bd7714 100644 --- a/pkg/controller/networkpolicy/store/networkpolicy.go +++ b/pkg/controller/networkpolicy/store/networkpolicy.go @@ -26,7 +26,6 @@ import ( "github.com/vmware-tanzu/antrea/pkg/apiserver/storage" "github.com/vmware-tanzu/antrea/pkg/apiserver/storage/ram" "github.com/vmware-tanzu/antrea/pkg/controller/types" - "github.com/vmware-tanzu/antrea/pkg/k8s" ) const ( @@ -103,13 +102,13 @@ func genNetworkPolicyEvent(key string, prevObj, currObj interface{}, rv uint64) // ToNetworkPolicyMsg converts the stored NetworkPolicy to its message form. // If includeBody is true, Rules and AppliedToGroups will be copied. func ToNetworkPolicyMsg(in *types.NetworkPolicy, out *controlplane.NetworkPolicy, includeBody bool) { - out.Namespace = in.Namespace out.Name = in.Name out.UID = in.UID if !includeBody { return } // Since stored objects are immutable, we just reference the fields here. + out.SourceRef = in.SourceRef out.Rules = in.Rules out.AppliedToGroups = in.AppliedToGroups out.Priority = in.Priority @@ -122,7 +121,7 @@ func NetworkPolicyKeyFunc(obj interface{}) (string, error) { if !ok { return "", fmt.Errorf("object is not *types.NetworkPolicy: %v", obj) } - return k8s.NamespacedName(policy.Namespace, policy.Name), nil + return policy.Name, nil } // NewNetworkPolicyStore creates a store of NetworkPolicy. diff --git a/pkg/controller/networkpolicy/store/networkpolicy_test.go b/pkg/controller/networkpolicy/store/networkpolicy_test.go index fd09bf1ffd6..957d761c924 100644 --- a/pkg/controller/networkpolicy/store/networkpolicy_test.go +++ b/pkg/controller/networkpolicy/store/networkpolicy_test.go @@ -22,7 +22,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" - apitypes "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/watch" @@ -33,9 +32,16 @@ import ( func TestWatchNetworkPolicyEvent(t *testing.T) { protocolTCP := controlplane.ProtocolTCP + npRef := controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "id1", + } policyV1 := &types.NetworkPolicy{ - Namespace: "foo", - Name: "bar", + SourceRef: &npRef, + UID: npRef.UID, + Name: string(npRef.UID), SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node2")}, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, @@ -46,8 +52,9 @@ func TestWatchNetworkPolicyEvent(t *testing.T) { AppliedToGroups: []string{"appliedToGroup1"}, } policyV2 := &types.NetworkPolicy{ - Namespace: "foo", - Name: "bar", + SourceRef: &npRef, + UID: npRef.UID, + Name: string(npRef.UID), SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, @@ -58,8 +65,9 @@ func TestWatchNetworkPolicyEvent(t *testing.T) { AppliedToGroups: []string{"appliedToGroup1"}, } policyV3 := &types.NetworkPolicy{ - Namespace: "foo", - Name: "bar", + SourceRef: &npRef, + UID: npRef.UID, + Name: string(npRef.UID), SpanMeta: types.SpanMeta{NodeNames: sets.NewString("node1", "node3")}, Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, @@ -87,12 +95,14 @@ func TestWatchNetworkPolicyEvent(t *testing.T) { expected: []watch.Event{ {Type: watch.Bookmark, Object: &controlplane.NetworkPolicy{}}, {Type: watch.Added, Object: &controlplane.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}, + ObjectMeta: metav1.ObjectMeta{Name: string(npRef.UID), UID: npRef.UID}, + SourceRef: &npRef, Rules: policyV1.Rules, AppliedToGroups: policyV1.AppliedToGroups, }}, {Type: watch.Modified, Object: &controlplane.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}, + ObjectMeta: metav1.ObjectMeta{Name: string(npRef.UID), UID: npRef.UID}, + SourceRef: &npRef, Rules: policyV2.Rules, AppliedToGroups: policyV2.AppliedToGroups, }}, @@ -114,17 +124,19 @@ func TestWatchNetworkPolicyEvent(t *testing.T) { expected: []watch.Event{ {Type: watch.Bookmark, Object: &controlplane.NetworkPolicy{}}, {Type: watch.Added, Object: &controlplane.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}, + ObjectMeta: metav1.ObjectMeta{Name: string(npRef.UID), UID: npRef.UID}, + SourceRef: &npRef, Rules: policyV2.Rules, AppliedToGroups: policyV2.AppliedToGroups, }}, {Type: watch.Modified, Object: &controlplane.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}, + ObjectMeta: metav1.ObjectMeta{Name: string(npRef.UID), UID: npRef.UID}, + SourceRef: &npRef, Rules: policyV3.Rules, AppliedToGroups: policyV3.AppliedToGroups, }}, {Type: watch.Deleted, Object: &controlplane.NetworkPolicy{ - ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "bar"}, + ObjectMeta: metav1.ObjectMeta{Name: string(npRef.UID), UID: npRef.UID}, }}, }, }, @@ -155,9 +167,14 @@ func TestWatchNetworkPolicyEvent(t *testing.T) { func TestGetNetworkPolicyByIndex(t *testing.T) { policy1 := &types.NetworkPolicy{ - Namespace: "foo", - Name: "bar", - UID: apitypes.UID("uid-1"), + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "ns1", + Name: "name1", + UID: "id1", + }, + Name: "id1", + UID: "id1", Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{AddressGroups: []string{"addressGroup1"}}, @@ -166,9 +183,14 @@ func TestGetNetworkPolicyByIndex(t *testing.T) { AppliedToGroups: []string{"appliedToGroup1"}, } policy2 := &types.NetworkPolicy{ - Namespace: "foo2", - Name: "bar2", - UID: apitypes.UID("uid-2"), + SourceRef: &controlplane.NetworkPolicyReference{ + Type: controlplane.K8sNetworkPolicy, + Namespace: "ns2", + Name: "name2", + UID: "id2", + }, + Name: "id2", + UID: "id2", Rules: []controlplane.NetworkPolicyRule{{ Direction: controlplane.DirectionIn, From: controlplane.NetworkPolicyPeer{AddressGroups: []string{"addressGroup1", "addressGroup2"}}, diff --git a/pkg/controller/types/networkpolicy.go b/pkg/controller/types/networkpolicy.go index 8ac68f38f8b..e8185de21e3 100644 --- a/pkg/controller/types/networkpolicy.go +++ b/pkg/controller/types/networkpolicy.go @@ -105,13 +105,12 @@ type AddressGroup struct { // NetworkPolicy describes what network traffic is allowed for a set of Pods. type NetworkPolicy struct { SpanMeta - // UID of the original K8s Network Policy. + // Reference to the original Network Policy. + SourceRef *controlplane.NetworkPolicyReference + // UID of the internal Network Policy. UID types.UID - // Name of the original K8s Network Policy. + // Name of the internal Network Policy. currently it's same as UID. Name string - // Namespace of the original K8s Network Policy. - // An empty value indicates that the Network Policy is Cluster scoped. - Namespace string // Priority represents the relative priority of this Network Policy as compared to // other Network Policies. Priority will be unset (nil) for K8s Network Policy. Priority *float64