-
Notifications
You must be signed in to change notification settings - Fork 366
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add networkpolicyanalysis antctl query
Adds the antctl networkpolicyanalysis query that returns the predicted effective NetworkPolicy rule, which affects traffic from ns1/pod1 to ns2/pod2. Signed-off-by: Qiyue Yao <yaoq@vmware.com>
- Loading branch information
Showing
10 changed files
with
756 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
179 changes: 179 additions & 0 deletions
179
pkg/apiserver/handlers/networkpolicyanalysis/handler.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
// Copyright 2023 Antrea Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package networkpolicyanalysis | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
"strings" | ||
|
||
"k8s.io/apimachinery/pkg/types" | ||
"k8s.io/apimachinery/pkg/util/sets" | ||
|
||
"antrea.io/antrea/pkg/apis/controlplane" | ||
"antrea.io/antrea/pkg/apis/controlplane/v1beta2" | ||
"antrea.io/antrea/pkg/controller/networkpolicy" | ||
) | ||
|
||
// parsePeer parses Namespace/Pod name, empty string is returned if the argument is not of a | ||
// valid Namespace/Pod reference (missing pod name or invalid format). Namespace will be set | ||
// as default if missing, string without separator will be considered as pod name. | ||
func parsePeer(str string) (string, string) { | ||
parts := strings.Split(str, "/") | ||
ns, pod := "", "" | ||
if len(parts) == 1 { | ||
ns, pod = "default", parts[0] | ||
} else if len(parts) == 2 { | ||
ns, pod = parts[0], parts[1] | ||
} | ||
return ns, pod | ||
} | ||
|
||
// ruleKey returns policyUID+direction+ruleIndex as the key | ||
func ruleKey(uid types.UID, direction v1beta2.Direction, idx int) string { | ||
return fmt.Sprintf("%s/%s%d", uid, direction, idx) | ||
} | ||
|
||
// higherPrecedence compares the two rules and returns if newRule has a higher precedence than oldRule. | ||
func higherPrecedence(oldRule, newRule *networkpolicy.RuleInfo) bool { | ||
if oldRule == nil { | ||
return true | ||
} | ||
// compare tier priorities | ||
effectiveTierPriorityK8sNP := (networkpolicy.DefaultTierPriority + networkpolicy.BaselineTierPriority) / 2 | ||
oldTierPriority, newTierPriority := effectiveTierPriorityK8sNP, effectiveTierPriorityK8sNP | ||
if oldRule.Policy.TierPriority != nil { | ||
oldTierPriority = *oldRule.Policy.TierPriority | ||
} | ||
if newRule.Policy.TierPriority != nil { | ||
newTierPriority = *newRule.Policy.TierPriority | ||
} | ||
if oldTierPriority != newTierPriority { | ||
return oldTierPriority > newTierPriority | ||
} | ||
// compare policy priorities if tier priorities equal | ||
if oldRule.Policy.Priority != nil && newRule.Policy.Priority != nil && *newRule.Policy.Priority != *oldRule.Policy.Priority { | ||
return *oldRule.Policy.Priority > *newRule.Policy.Priority | ||
} | ||
// compare rule priorities further as previous steps have confirmed policy priorities are equal | ||
// Kubernetes NetworkPolicies rules have the same default priorities, so rule index is hacked for comparison | ||
// "-1" indicates default isolation, which has a lower precedence than KNP policy rules with ">=0" rule indexes | ||
if oldRule.Index != newRule.Index { | ||
if newRule.Policy.SourceRef.Type == controlplane.K8sNetworkPolicy && oldRule.Policy.SourceRef.Type == controlplane.K8sNetworkPolicy { | ||
return oldRule.Index < newRule.Index | ||
} else { | ||
return oldRule.Index > newRule.Index | ||
} | ||
} | ||
// use policy name as the tie-breaker if all priorities are equal | ||
return oldRule.Policy.Name > newRule.Policy.Name | ||
} | ||
|
||
// predictEndpointsRules returns the predicted rules effective from srcEndpoints to dstEndpoints. | ||
// Rules returned satisfy a. in source applied policies and destination egress rules, | ||
// or b. in source ingress rules and destination applied policies or c. applied to KNP default isolation. | ||
func predictEndpointsRules(srcEndpoints, dstEndpoints *networkpolicy.EndpointRuleAnalysis) *networkpolicy.Rule { | ||
var commonRule *networkpolicy.RuleInfo | ||
dstEgressRules, srcIngressRules := sets.New[string](), sets.New[string]() | ||
compareRules := func(commonRule, rule *networkpolicy.RuleInfo) *networkpolicy.RuleInfo { | ||
if higherPrecedence(commonRule, rule) { | ||
return rule | ||
} | ||
return commonRule | ||
} | ||
if srcEndpoints != nil && dstEndpoints != nil { | ||
for _, rule := range dstEndpoints.EgressRules { | ||
if srcEndpoints.PolicyUIDs.Has(rule.Policy.SourceRef.UID) { | ||
dstEgressRules.Insert(ruleKey(rule.Policy.SourceRef.UID, rule.Direction, rule.Index)) | ||
commonRule = compareRules(commonRule, rule) | ||
} | ||
} | ||
for _, rule := range srcEndpoints.IngressRules { | ||
if dstEndpoints.PolicyUIDs.Has(rule.Policy.SourceRef.UID) { | ||
srcIngressRules.Insert(ruleKey(rule.Policy.SourceRef.UID, rule.Direction, rule.Index)) | ||
commonRule = compareRules(commonRule, rule) | ||
} | ||
} | ||
// Manually insert Kubernetes NetworkPolicy default isolation rules if exists. | ||
// Default isolation rules has the index of -1 to indicate lower precedence. | ||
for _, rule := range srcEndpoints.EgressIsolated { | ||
if !dstEgressRules.Has(ruleKey(rule.Policy.SourceRef.UID, rule.Direction, rule.Index)) { | ||
defaultDropRule := &networkpolicy.RuleInfo{ | ||
Policy: rule.Policy, | ||
Index: -1, | ||
Direction: v1beta2.DirectionOut, | ||
} | ||
commonRule = compareRules(commonRule, defaultDropRule) | ||
} | ||
} | ||
for _, rule := range dstEndpoints.IngressIsolated { | ||
if !srcIngressRules.Has(ruleKey(rule.Policy.SourceRef.UID, rule.Direction, rule.Index)) { | ||
defaultDropRule := &networkpolicy.RuleInfo{ | ||
Policy: rule.Policy, | ||
Index: -1, | ||
Direction: v1beta2.DirectionIn, | ||
} | ||
commonRule = compareRules(commonRule, defaultDropRule) | ||
} | ||
} | ||
} | ||
// if no common rule or default isolation is found, return empty result | ||
if commonRule == nil { | ||
return &networkpolicy.Rule{} | ||
} | ||
return &networkpolicy.Rule{ | ||
PolicyRef: networkpolicy.PolicyRef{ | ||
Namespace: commonRule.Policy.SourceRef.Namespace, | ||
Name: commonRule.Policy.SourceRef.Name, | ||
UID: commonRule.Policy.SourceRef.UID, | ||
}, | ||
Direction: commonRule.Direction, | ||
RuleIndex: commonRule.Index, | ||
} | ||
} | ||
|
||
// HandleFunc creates a http.HandlerFunc which uses an AgentNetworkPolicyInfoQuerier | ||
// to query network policy rules in current agent. | ||
func HandleFunc(eq networkpolicy.EndpointQuerier) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
src := r.URL.Query().Get("source") | ||
dst := r.URL.Query().Get("destination") | ||
|
||
var srcNS, srcPod, dstNS, dstPod string | ||
srcNS, srcPod = parsePeer(src) | ||
dstNS, dstPod = parsePeer(dst) | ||
if srcPod == "" || dstPod == "" { | ||
http.Error(w, "invalid command argument format", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// query endpoints and handle response errors | ||
endpointAnalysisSource, err := eq.QueryNetworkPolicyRules(srcNS, srcPod) | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
endpointAnalysisDestination, err := eq.QueryNetworkPolicyRules(dstNS, dstPod) | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
endpointAnalysisRule := predictEndpointsRules(endpointAnalysisSource, endpointAnalysisDestination) | ||
if err := json.NewEncoder(w).Encode(endpointAnalysisRule); err != nil { | ||
http.Error(w, "failed to encode response: "+err.Error(), http.StatusInternalServerError) | ||
} | ||
} | ||
} |
Oops, something went wrong.