From f098889a6bd02777883150da228c3a217b064443 Mon Sep 17 00:00:00 2001 From: Evan Baker Date: Tue, 19 Dec 2023 16:58:53 +0000 Subject: [PATCH] chore: automated lint fixes Signed-off-by: Evan Baker --- aitelemetry/telemetrywrapper.go | 2 +- cni/ipam/ipam_test.go | 2 +- cni/network/multitenancy.go | 2 +- cni/network/network.go | 14 +-- cnm/ipam/ipam_test.go | 6 +- cnm/network/network_linux_test.go | 4 +- cnm/plugin_linux.go | 1 + cnms/cnmspackage/monitor2rules_linux.go | 12 +-- cns/NetworkContainerContract.go | 18 ++-- cns/api.go | 6 +- cns/client/client.go | 4 +- cns/dockerclient/api.go | 2 +- cns/dockerclient/dockerclient.go | 2 +- cns/dockerclient/dockerclient_linux.go | 1 + cns/hnsclient/hnsclient_linux.go | 6 +- cns/ipamclient/ipamclient.go | 10 +-- cns/ipamclient/ipamclient_linux.go | 1 + cns/networkcontainers/networkcontainers.go | 2 +- cns/restserver/api_test.go | 4 +- cns/restserver/internalapi.go | 2 +- cns/restserver/internalapi_test.go | 2 +- cns/restserver/util.go | 2 +- cns/routes/routes_linux.go | 1 + cns/service/main.go | 2 +- common/args.go | 2 +- common/utils.go | 7 +- crd/clustersubnetstate/embed.go | 1 + crd/nodenetworkconfig/embed.go | 1 + ipam/ipv6Ipam_test.go | 3 +- ipam/manager_ipv6Ipam_test.go | 3 +- ipam/manager_test.go | 5 +- ipam/pool_test.go | 4 +- netio/netio.go | 6 +- netlink/protocol.go | 2 +- network/manager_test.go | 7 +- network/namespace_linux.go | 1 - network/networkutils/networkutils_linux.go | 2 +- ...nsparent_vlan_endpointclient_linux_test.go | 8 +- nns/grpcclient.go | 12 +-- nns/mockgrpcclient.go | 7 +- npm/daemon/daemon.go | 1 - npm/http/client/client.go | 5 +- npm/http/server/server.go | 3 +- npm/http/server/server_test.go | 2 +- npm/ipsm/ipsm.go | 1 - npm/ipsm/ipsm_test.go | 2 +- npm/iptm/iptm.go | 1 - npm/iptm/iptm_linux.go | 1 + npm/metrics/prometheus-values.go | 10 +-- npm/metrics/prometheus_metrics_test.go | 4 +- npm/npm.go | 3 +- .../controllers/v1/networkPolicyController.go | 2 +- .../v1/networkPolicyController_test.go | 1 - .../controllers/v1/parseSelector.go | 9 +- .../controllers/v1/parseSelector_test.go | 4 +- .../controllers/v1/podController.go | 6 +- .../controllers/v1/podController_test.go | 1 - .../controllers/v2/podController.go | 3 +- .../goalstateprocessor/goalstateprocessor.go | 4 +- .../controlplane/translation/parseSelector.go | 1 - .../translation/translatePolicy.go | 3 +- npm/pkg/dataplane/debug/converter.go | 32 ++++--- npm/pkg/dataplane/debug/trafficanalyzer.go | 89 +++++++++---------- .../dataplane/debug/trafficanalyzer_test.go | 2 +- npm/pkg/dataplane/ipsets/dirtycache.go | 38 ++++---- .../dataplane/ipsets/ipsetmanager_linux.go | 63 ++++++------- npm/pkg/dataplane/parse/parser.go | 1 - npm/pkg/dataplane/policies/policy.go | 4 +- .../tlscertificate_retriever_linux_test.go | 2 +- test/integration/npm/main.go | 1 - test/nnsmockserver/nnsmockserver.go | 18 ++-- test/utils/utils.go | 1 - tools/acncli/cmd/npm/npm.go | 1 - tools/acncli/cmd/root.go | 6 +- tools/acncli/main.go | 3 +- 75 files changed, 252 insertions(+), 255 deletions(-) diff --git a/aitelemetry/telemetrywrapper.go b/aitelemetry/telemetrywrapper.go index 36c59c212a7..56a18d291d0 100644 --- a/aitelemetry/telemetrywrapper.go +++ b/aitelemetry/telemetrywrapper.go @@ -333,7 +333,7 @@ func (th *telemetryHandle) Close(timeout int) { // wait for items to be sent otherwise timeout <-th.client.Channel().Close(time.Duration(timeout) * time.Second) - // Remove diganostic message listener + // Remove diagnostic message listener if th.diagListener != nil { th.diagListener.Remove() th.diagListener = nil diff --git a/cni/ipam/ipam_test.go b/cni/ipam/ipam_test.go index 577865c6497..4095027c90b 100644 --- a/cni/ipam/ipam_test.go +++ b/cni/ipam/ipam_test.go @@ -276,7 +276,7 @@ var ( }) Context("When pool is not use", func() { - It("Confirm pool was released by succesfully requesting pool", func() { + It("Confirm pool was released by successfully requesting pool", func() { arg.StdinData = getStdinData("0.4.0", "", "") err = plugin.Add(arg) Expect(err).ShouldNot(HaveOccurred()) diff --git a/cni/network/multitenancy.go b/cni/network/multitenancy.go index 33d161b78be..28687e12d0a 100644 --- a/cni/network/multitenancy.go +++ b/cni/network/multitenancy.go @@ -95,7 +95,7 @@ func (m *Multitenancy) DetermineSnatFeatureOnHost(snatFile, nmAgentSupportedApis // If we weren't able to retrieve snatConfiguration, query NMAgent if retrieveSnatConfigErr != nil { var resp *http.Response - req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, nmAgentSupportedApisURL, nil) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, nmAgentSupportedApisURL, http.NoBody) if err != nil { logger.Error("failed creating http request", zap.Error(err)) return false, false, fmt.Errorf("%w", err) diff --git a/cni/network/network.go b/cni/network/network.go index 2381b8ffc4e..efa136e74c6 100644 --- a/cni/network/network.go +++ b/cni/network/network.go @@ -1321,15 +1321,15 @@ func convertNnsToIPConfigs( // method of ADD method var ipConfigs []*network.IPConfig - if netRes.Interfaces != nil { - for _, ni := range netRes.Interfaces { - for _, ip := range ni.Ipaddresses { - ipAddr := net.ParseIP(ip.Ip) + if netRes.GetInterfaces() != nil { + for _, ni := range netRes.GetInterfaces() { + for _, ip := range ni.GetIpaddresses() { + ipAddr := net.ParseIP(ip.GetIp()) - prefixLength, err := strconv.Atoi(ip.PrefixLength) + prefixLength, err := strconv.Atoi(ip.GetPrefixLength()) if err != nil { logger.Error("Error parsing prefix length while converting to cni result", - zap.String("prefixLength", ip.PrefixLength), + zap.String("prefixLength", ip.GetPrefixLength()), zap.String("operation", operationName), zap.String("pod", podName), zap.Error(err)) @@ -1345,7 +1345,7 @@ func convertNnsToIPConfigs( address.Mask = net.CIDRMask(prefixLength, ipv4FullMask) } - gateway := net.ParseIP(ip.DefaultGateway) + gateway := net.ParseIP(ip.GetDefaultGateway()) ipConfigs = append(ipConfigs, &network.IPConfig{ Address: address, diff --git a/cnm/ipam/ipam_test.go b/cnm/ipam/ipam_test.go index 534fcbc6385..e419c8f5550 100644 --- a/cnm/ipam/ipam_test.go +++ b/cnm/ipam/ipam_test.go @@ -123,7 +123,7 @@ func decodeResponse(w *httptest.ResponseRecorder, response interface{}) error { func TestActivate(t *testing.T) { var resp cnm.ActivateResponse - req, err := http.NewRequest(http.MethodGet, "/Plugin.Activate", nil) + req, err := http.NewRequest(http.MethodGet, "/Plugin.Activate", http.NoBody) if err != nil { t.Fatal(err) } @@ -142,7 +142,7 @@ func TestActivate(t *testing.T) { func TestGetCapabilities(t *testing.T) { var resp GetCapabilitiesResponse - req, err := http.NewRequest(http.MethodGet, GetCapabilitiesPath, nil) + req, err := http.NewRequest(http.MethodGet, GetCapabilitiesPath, http.NoBody) if err != nil { t.Fatal(err) } @@ -161,7 +161,7 @@ func TestGetCapabilities(t *testing.T) { func TestGetDefaultAddressSpaces(t *testing.T) { var resp GetDefaultAddressSpacesResponse - req, err := http.NewRequest(http.MethodGet, GetAddressSpacesPath, nil) + req, err := http.NewRequest(http.MethodGet, GetAddressSpacesPath, http.NoBody) if err != nil { t.Fatal(err) } diff --git a/cnm/network/network_linux_test.go b/cnm/network/network_linux_test.go index 5592d6d793e..b39a013f345 100644 --- a/cnm/network/network_linux_test.go +++ b/cnm/network/network_linux_test.go @@ -124,7 +124,7 @@ func decodeResponse(w *httptest.ResponseRecorder, response interface{}) error { func TestActivate(t *testing.T) { var resp cnm.ActivateResponse - req, err := http.NewRequest(http.MethodGet, "/Plugin.Activate", nil) + req, err := http.NewRequest(http.MethodGet, "/Plugin.Activate", http.NoBody) if err != nil { t.Fatal(err) } @@ -143,7 +143,7 @@ func TestActivate(t *testing.T) { func TestGetCapabilities(t *testing.T) { var resp remoteApi.GetCapabilityResponse - req, err := http.NewRequest(http.MethodGet, getCapabilitiesPath, nil) + req, err := http.NewRequest(http.MethodGet, getCapabilitiesPath, http.NoBody) if err != nil { t.Fatal(err) } diff --git a/cnm/plugin_linux.go b/cnm/plugin_linux.go index e552c98b406..2293937c9d8 100644 --- a/cnm/plugin_linux.go +++ b/cnm/plugin_linux.go @@ -1,6 +1,7 @@ // Copyright 2017 Microsoft. All rights reserved. // MIT License +//go:build linux // +build linux package cnm diff --git a/cnms/cnmspackage/monitor2rules_linux.go b/cnms/cnmspackage/monitor2rules_linux.go index 3b3ffb6a7f9..901cc13eddf 100644 --- a/cnms/cnmspackage/monitor2rules_linux.go +++ b/cnms/cnmspackage/monitor2rules_linux.go @@ -35,8 +35,8 @@ func (networkMonitor *NetworkMonitor) deleteRulesNotExistInMap(chainRules map[st // addRulesNotExistInMap adds rules to nat Ebtable if rule was in stateRules and not in current chain rules after a certain number of iterations. func (networkMonitor *NetworkMonitor) addRulesNotExistInMap( stateRules map[string]string, - chainRules map[string]string) { - + chainRules map[string]string, +) { table := ebtables.Nat action := ebtables.Append @@ -63,8 +63,8 @@ func (networkMonitor *NetworkMonitor) addRulesNotExistInMap( // CreateRequiredL2Rules finds the rules that should be in nat ebtable based on state. func (networkMonitor *NetworkMonitor) CreateRequiredL2Rules( currentEbtableRulesMap map[string]string, - currentStateRulesMap map[string]string) error { - + currentStateRulesMap map[string]string, +) error { for rule := range networkMonitor.AddRulesToBeValidated { if _, ok := currentStateRulesMap[rule]; !ok { delete(networkMonitor.AddRulesToBeValidated, rule) @@ -79,8 +79,8 @@ func (networkMonitor *NetworkMonitor) CreateRequiredL2Rules( // RemoveInvalidL2Rules removes rules that should not be in nat ebtable based on state. func (networkMonitor *NetworkMonitor) RemoveInvalidL2Rules( currentEbtableRulesMap map[string]string, - currentStateRulesMap map[string]string) error { - + currentStateRulesMap map[string]string, +) error { for rule := range networkMonitor.DeleteRulesToBeValidated { if _, ok := currentEbtableRulesMap[rule]; !ok { delete(networkMonitor.DeleteRulesToBeValidated, rule) diff --git a/cns/NetworkContainerContract.go b/cns/NetworkContainerContract.go index be33c105e3a..eac88a56586 100644 --- a/cns/NetworkContainerContract.go +++ b/cns/NetworkContainerContract.go @@ -640,15 +640,15 @@ func (u UnpublishNetworkContainerResponse) String() string { // ValidAclPolicySetting - Used to validate ACL policy type ValidAclPolicySetting struct { - Protocols string `json:","` - Action string `json:","` - Direction string `json:","` - LocalAddresses string `json:","` - RemoteAddresses string `json:","` - LocalPorts string `json:","` - RemotePorts string `json:","` - RuleType string `json:","` - Priority uint16 `json:","` + Protocols string `json:""` + Action string `json:""` + Direction string `json:""` + LocalAddresses string `json:""` + RemoteAddresses string `json:""` + LocalPorts string `json:""` + RemotePorts string `json:""` + RuleType string `json:""` + Priority uint16 `json:""` } const ( diff --git a/cns/api.go b/cns/api.go index 4bafd3d8ba7..166ae7f039e 100644 --- a/cns/api.go +++ b/cns/api.go @@ -213,7 +213,7 @@ type CreateHnsNetworkRequest struct { AutomaticDNS bool `json:",omitempty"` } -// SubnetInfo is assoicated with HNS network and represents a list +// SubnetInfo is associated with HNS network and represents a list // of subnets available to the network type SubnetInfo struct { AddressPrefix string @@ -221,7 +221,7 @@ type SubnetInfo struct { Policies []json.RawMessage `json:",omitempty"` } -// MacPool is assoicated with HNS network and represents a list +// MacPool is associated with HNS network and represents a list // of macaddresses available to the network type MacPool struct { StartMacAddress string @@ -263,7 +263,7 @@ type GetIPAddressesResponse struct { IPAddresses []string } -// HostLocalIPAddressResponse describes reponse that returns the host local IP Address. +// HostLocalIPAddressResponse describes response that returns the host local IP Address. type HostLocalIPAddressResponse struct { Response Response IPAddress string diff --git a/cns/client/client.go b/cns/client/client.go index 2ee524cfb99..9a9ea805623 100644 --- a/cns/client/client.go +++ b/cns/client/client.go @@ -536,7 +536,7 @@ func (c *Client) GetIPAddressesMatchingStates(ctx context.Context, stateFilter . // GetPodOrchestratorContext calls GetPodIpOrchestratorContext API on CNS func (c *Client) GetPodOrchestratorContext(ctx context.Context) (map[string][]string, error) { u := c.routes[cns.PathDebugPodContext] - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody) if err != nil { return nil, errors.Wrap(err, "failed to build request") } @@ -565,7 +565,7 @@ func (c *Client) GetPodOrchestratorContext(ctx context.Context) (map[string][]st // GetHTTPServiceData gets all public in-memory struct details for debugging purpose func (c *Client) GetHTTPServiceData(ctx context.Context) (*restserver.GetHTTPServiceDataResponse, error) { u := c.routes[cns.PathDebugRestData] - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody) if err != nil { return nil, errors.Wrap(err, "failed to build request") } diff --git a/cns/dockerclient/api.go b/cns/dockerclient/api.go index 9f38d06ee3a..017ae2426fa 100644 --- a/cns/dockerclient/api.go +++ b/cns/dockerclient/api.go @@ -30,7 +30,7 @@ type NetworkConfiguration struct { Options map[string]interface{} } -// DockerErrorResponse defines the error response retunred by docker. +// DockerErrorResponse defines the error response returned by docker. type DockerErrorResponse struct { message string } diff --git a/cns/dockerclient/dockerclient.go b/cns/dockerclient/dockerclient.go index 2e4686d16b9..3a3837bf6a4 100644 --- a/cns/dockerclient/dockerclient.go +++ b/cns/dockerclient/dockerclient.go @@ -152,7 +152,7 @@ func (c *Client) DeleteNetwork(networkName string) error { logger.Printf("[Azure CNS] DeleteNetwork") url := c.connectionURL + inspectNetworkPath + networkName - req, err := http.NewRequest("DELETE", url, nil) + req, err := http.NewRequest("DELETE", url, http.NoBody) if err != nil { logger.Printf("[Azure CNS] Error received while creating http DELETE request for network delete %v %v", networkName, err.Error()) return err diff --git a/cns/dockerclient/dockerclient_linux.go b/cns/dockerclient/dockerclient_linux.go index 18eadf5eee1..134200380cd 100644 --- a/cns/dockerclient/dockerclient_linux.go +++ b/cns/dockerclient/dockerclient_linux.go @@ -1,6 +1,7 @@ // Copyright 2017 Microsoft. All rights reserved. // MIT License +//go:build linux // +build linux package dockerclient diff --git a/cns/hnsclient/hnsclient_linux.go b/cns/hnsclient/hnsclient_linux.go index 0a9d62c3c78..643757b359b 100644 --- a/cns/hnsclient/hnsclient_linux.go +++ b/cns/hnsclient/hnsclient_linux.go @@ -39,7 +39,8 @@ func CreateHostNCApipaEndpoint( localIPConfiguration cns.IPConfiguration, allowNCToHostCommunication bool, allowHostToNCCommunication bool, - ncPolicies []cns.NetworkContainerRequestPolicies) (string, error) { + ncPolicies []cns.NetworkContainerRequestPolicies, +) (string, error) { return "", nil } @@ -47,6 +48,7 @@ func CreateHostNCApipaEndpoint( // created for host container connectivity // This is windows platform specific. func DeleteHostNCApipaEndpoint( - networkContainerID string) error { + networkContainerID string, +) error { return nil } diff --git a/cns/ipamclient/ipamclient.go b/cns/ipamclient/ipamclient.go index 369a3c41934..be948dc1c03 100644 --- a/cns/ipamclient/ipamclient.go +++ b/cns/ipamclient/ipamclient.go @@ -57,7 +57,7 @@ func (ic *IpamClient) GetAddressSpace() (string, error) { if resp.Err != "" { log.Printf("[Azure CNS] GetAddressSpace received error response :%v", resp.Err) - return "", fmt.Errorf(resp.Err) + return "", errors.New(resp.Err) } return resp.LocalDefaultAddressSpace, nil @@ -103,7 +103,7 @@ func (ic *IpamClient) GetPoolID(asID, subnet string) (string, error) { if resp.Err != "" { log.Printf("[Azure CNS] GetPoolID received error response :%v", resp.Err) - return "", fmt.Errorf(resp.Err) + return "", errors.New(resp.Err) } return resp.PoolID, nil @@ -151,7 +151,7 @@ func (ic *IpamClient) ReserveIPAddress(poolID string, reservationID string) (str if reserveResp.Err != "" { log.Printf("[Azure CNS] ReserveIP received error response :%v", reserveResp.Err) - return "", fmt.Errorf(reserveResp.Err) + return "", errors.New(reserveResp.Err) } return reserveResp.Address, nil @@ -201,7 +201,7 @@ func (ic *IpamClient) ReleaseIPAddress(poolID string, reservationID string) erro if releaseResp.Err != "" { log.Printf("[Azure CNS] ReleaseIP received error response :%v", releaseResp.Err) - return fmt.Errorf(releaseResp.Err) + return errors.New(releaseResp.Err) } return nil @@ -245,7 +245,7 @@ func (ic *IpamClient) GetIPAddressUtilization(poolID string) (int, int, []string if poolInfoResp.Err != "" { log.Printf("[Azure CNS] GetIPUtilization received error response :%v", poolInfoResp.Err) - return 0, 0, nil, fmt.Errorf(poolInfoResp.Err) + return 0, 0, nil, errors.New(poolInfoResp.Err) } return poolInfoResp.Capacity, poolInfoResp.Available, poolInfoResp.UnhealthyAddresses, nil diff --git a/cns/ipamclient/ipamclient_linux.go b/cns/ipamclient/ipamclient_linux.go index cb3afbd3004..f910153e2fa 100644 --- a/cns/ipamclient/ipamclient_linux.go +++ b/cns/ipamclient/ipamclient_linux.go @@ -1,6 +1,7 @@ // Copyright 2017 Microsoft. All rights reserved. // MIT License +//go:build linux // +build linux package ipamclient diff --git a/cns/networkcontainers/networkcontainers.go b/cns/networkcontainers/networkcontainers.go index 19dc99f34c0..58cab11d47f 100644 --- a/cns/networkcontainers/networkcontainers.go +++ b/cns/networkcontainers/networkcontainers.go @@ -187,7 +187,7 @@ func execPlugin(rt *libcni.RuntimeConf, netconf []byte, operation, path string) environ := args(operation, path, rt).AsEnv() logger.Printf("[Azure CNS] CNI called with environ variables %v", environ) stdout := &bytes.Buffer{} - command := exec.Command(path + string(os.PathSeparator) + "azure-vnet") + command := exec.Command(filepath.Join(path, "azure-vnet")) command.Env = environ command.Stdin = bytes.NewBuffer(netconf) command.Stdout = stdout diff --git a/cns/restserver/api_test.go b/cns/restserver/api_test.go index 38d25d208c1..77b2522dc00 100644 --- a/cns/restserver/api_test.go +++ b/cns/restserver/api_test.go @@ -643,7 +643,7 @@ func TestGetNumOfCPUCores(t *testing.T) { req *http.Request ) - req, err = http.NewRequest(http.MethodGet, cns.NumberOfCPUCoresPath, nil) + req, err = http.NewRequest(http.MethodGet, cns.NumberOfCPUCoresPath, http.NoBody) if err != nil { t.Fatal(err) } @@ -1030,7 +1030,7 @@ func publishNCViaCNS( } } - fmt.Printf("PublishNetworkContainer succeded with response %+v, raw:%+v\n", resp, w.Body) + fmt.Printf("PublishNetworkContainer succeeded with response %+v, raw:%+v\n", resp, w.Body) return nil } diff --git a/cns/restserver/internalapi.go b/cns/restserver/internalapi.go index 904cc339749..54b91d14280 100644 --- a/cns/restserver/internalapi.go +++ b/cns/restserver/internalapi.go @@ -55,7 +55,7 @@ func (service *HTTPRestService) SyncNodeStatus(dncEP, infraVnet, nodeID string, // try to retrieve NodeInfoResponse from mDNC url := fmt.Sprintf(common.SyncNodeNetworkContainersURLFmt, dncEP, infraVnet, nodeID, dncApiVersion) - req, _ := http.NewRequestWithContext(context.TODO(), http.MethodGet, url, nil) + req, _ := http.NewRequestWithContext(context.TODO(), http.MethodGet, url, http.NoBody) resp, err := httpc.Do(req) if err == nil { if resp.StatusCode == http.StatusOK { diff --git a/cns/restserver/internalapi_test.go b/cns/restserver/internalapi_test.go index 0d26e0f2f06..f91b5cceb05 100644 --- a/cns/restserver/internalapi_test.go +++ b/cns/restserver/internalapi_test.go @@ -172,7 +172,7 @@ func TestCreateAndUpdateNCWithSecondaryIPNCVersion(t *testing.T) { // Validate secondary IPs' NC version has been updated by NC request receivedSecondaryIPConfigs := containerStatus.CreateNetworkContainerRequest.SecondaryIPConfigs if len(receivedSecondaryIPConfigs) != 1 { - t.Fatalf("receivedSecondaryIPConfigs lenth must be 1, but recieved %d", len(receivedSecondaryIPConfigs)) + t.Fatalf("receivedSecondaryIPConfigs lenth must be 1, but received %d", len(receivedSecondaryIPConfigs)) } for _, secIPConfig := range receivedSecondaryIPConfigs { if secIPConfig.IPAddress != "10.0.0.16" || secIPConfig.NCVersion != 0 { diff --git a/cns/restserver/util.go b/cns/restserver/util.go index a3b8baaad17..a9a831f0a4f 100644 --- a/cns/restserver/util.go +++ b/cns/restserver/util.go @@ -130,7 +130,7 @@ func (service *HTTPRestService) saveNetworkContainerGoalState(req cns.CreateNetw } if hostVersion == "" { // Host version is the NC version from NMAgent, set it -1 to indicate no result from NMAgent yet. - // TODO, query NMAgent and with aggresive time out and assign latest host version. + // TODO, query NMAgent and with aggressive time out and assign latest host version. hostVersion = "-1" } diff --git a/cns/routes/routes_linux.go b/cns/routes/routes_linux.go index 404facdc4db..4a54b6e509a 100644 --- a/cns/routes/routes_linux.go +++ b/cns/routes/routes_linux.go @@ -1,6 +1,7 @@ // Copyright 2017 Microsoft. All rights reserved. // MIT License +//go:build linux // +build linux package routes diff --git a/cns/service/main.go b/cns/service/main.go index 93081b9d593..42250e6ae67 100644 --- a/cns/service/main.go +++ b/cns/service/main.go @@ -219,7 +219,7 @@ var args = acn.ArgumentList{ Shorthand: acn.OptNetPluginConfigFileAlias, Description: "Set network plugin configuration file absolute path", Type: "string", - DefaultValue: platform.K8SNetConfigPath + string(os.PathSeparator) + defaultCNINetworkConfigFileName, + DefaultValue: filepath.Join(platform.K8SNetConfigPath, defaultCNINetworkConfigFileName), }, { Name: acn.OptCreateDefaultExtNetworkType, diff --git a/common/args.go b/common/args.go index de9b637fea8..1f915994577 100644 --- a/common/args.go +++ b/common/args.go @@ -106,7 +106,7 @@ func printErrorForArg(arg *Argument) { // printHelpForArg prints the help line for the given argument. func printHelpForArg(arg *Argument) { left := fmt.Sprintf(" -%v, --%v", arg.Shorthand, arg.Name) - right := fmt.Sprintf("%v", arg.Description) + right := arg.Description if arg.ValueMap != nil { left += fmt.Sprintf("=%v", arg.DefaultValue) diff --git a/common/utils.go b/common/utils.go index cd6a5bffa0b..c2fcb6aa13d 100644 --- a/common/utils.go +++ b/common/utils.go @@ -86,7 +86,8 @@ var httpClient *http.Client // InitHttpClient initializes the httpClient object func InitHttpClient( connectionTimeoutSec int, - responseHeaderTimeoutSec int) *http.Client { + responseHeaderTimeoutSec int, +) *http.Client { log.Printf("[Utils] Initializing HTTP client with connection timeout: %d, response header timeout: %d", connectionTimeoutSec, responseHeaderTimeoutSec) httpClient = &http.Client{ @@ -180,7 +181,7 @@ func GetHostMetadata(fileName string) (Metadata, error) { log.Printf("[Telemetry] Request metadata from wireserver") - req, err := http.NewRequest("GET", metadataURL, nil) + req, err := http.NewRequest("GET", metadataURL, http.NoBody) if err != nil { return Metadata{}, err } @@ -239,7 +240,7 @@ func GetAzureCloud(url string) (string, error) { } log.Printf("GetAzureCloud querying url: %s", url) - req, err := http.NewRequest("GET", url, nil) + req, err := http.NewRequest("GET", url, http.NoBody) if err != nil { return "", err } diff --git a/crd/clustersubnetstate/embed.go b/crd/clustersubnetstate/embed.go index 10683f91a8c..ff4262869ff 100644 --- a/crd/clustersubnetstate/embed.go +++ b/crd/clustersubnetstate/embed.go @@ -11,6 +11,7 @@ import ( ) // ClusterSubnetStatesYAML embeds the CRD YAML for downstream consumers. +// //go:embed manifests/acn.azure.com_clustersubnetstates.yaml var ClusterSubnetStatesYAML []byte diff --git a/crd/nodenetworkconfig/embed.go b/crd/nodenetworkconfig/embed.go index 30d07b31455..d2cfc373858 100644 --- a/crd/nodenetworkconfig/embed.go +++ b/crd/nodenetworkconfig/embed.go @@ -11,6 +11,7 @@ import ( ) // NodeNetworkConfigsYAML embeds the CRD YAML for downstream consumers. +// //go:embed manifests/acn.azure.com_nodenetworkconfigs.yaml var NodeNetworkConfigsYAML []byte diff --git a/ipam/ipv6Ipam_test.go b/ipam/ipv6Ipam_test.go index 20cbd663de5..5cd969db02a 100644 --- a/ipam/ipv6Ipam_test.go +++ b/ipam/ipv6Ipam_test.go @@ -9,14 +9,13 @@ import ( "runtime" "testing" + "github.com/Azure/azure-container-networking/common" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" testclient "k8s.io/client-go/kubernetes/fake" - - "github.com/Azure/azure-container-networking/common" ) const ( diff --git a/ipam/manager_ipv6Ipam_test.go b/ipam/manager_ipv6Ipam_test.go index 14d56a2cc5f..1be6b90e27f 100644 --- a/ipam/manager_ipv6Ipam_test.go +++ b/ipam/manager_ipv6Ipam_test.go @@ -6,10 +6,9 @@ package ipam import ( "testing" + "github.com/Azure/azure-container-networking/common" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/Azure/azure-container-networking/common" ) var ( diff --git a/ipam/manager_test.go b/ipam/manager_test.go index 8e3c4591f70..34559b95bcf 100644 --- a/ipam/manager_test.go +++ b/ipam/manager_test.go @@ -10,13 +10,12 @@ import ( "testing" "time" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/Azure/azure-container-networking/common" "github.com/Azure/azure-container-networking/platform" "github.com/Azure/azure-container-networking/store" "github.com/Azure/azure-container-networking/testutils" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" ) var ( diff --git a/ipam/pool_test.go b/ipam/pool_test.go index 722c4fa9da8..62ed93234ec 100644 --- a/ipam/pool_test.go +++ b/ipam/pool_test.go @@ -4,12 +4,10 @@ import ( "net" "testing" + "github.com/Azure/azure-container-networking/testutils" "github.com/google/uuid" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "github.com/Azure/azure-container-networking/testutils" ) func TestPool(t *testing.T) { diff --git a/netio/netio.go b/netio/netio.go index 9462c8ed332..24396011d34 100644 --- a/netio/netio.go +++ b/netio/netio.go @@ -15,8 +15,10 @@ type NetIOInterface interface { } // ErrInterfaceNil - errors out when interface is nil -var ErrInterfaceNil = errors.New("Interface is nil") -var ErrInterfaceNotFound = errors.New("Inteface not found") +var ( + ErrInterfaceNil = errors.New("Interface is nil") + ErrInterfaceNotFound = errors.New("Inteface not found") +) type NetIO struct{} diff --git a/netlink/protocol.go b/netlink/protocol.go index 6efc2cd63c8..8c603d9fd46 100644 --- a/netlink/protocol.go +++ b/netlink/protocol.go @@ -1,6 +1,7 @@ // Copyright 2017 Microsoft. All rights reserved. // MIT License +//go:build linux // +build linux package netlink @@ -182,7 +183,6 @@ func (msg *message) getAttributes(body serializable) []*attribute { return attrs } -// // Netlink message attribute // // Creates a new attribute. diff --git a/network/manager_test.go b/network/manager_test.go index 567ef7c30c3..f1208c73a1b 100644 --- a/network/manager_test.go +++ b/network/manager_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/Azure/azure-container-networking/store" "github.com/Azure/azure-container-networking/testutils" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" ) func TestManager(t *testing.T) { @@ -204,7 +203,7 @@ var _ = Describe("Test Manager", func() { }) }) - Context("When ifName not specifed in GetNumberofEndpoints", func() { + Context("When ifName not specified in GetNumberofEndpoints", func() { It("Should range the nm.ExternalInterfaces", func() { ifName := "eth0" nwId := "nwId" diff --git a/network/namespace_linux.go b/network/namespace_linux.go index bc682ded3bb..0cd1b5bd7bf 100644 --- a/network/namespace_linux.go +++ b/network/namespace_linux.go @@ -9,7 +9,6 @@ import ( "runtime" "github.com/Azure/azure-container-networking/netlink" - "golang.org/x/sys/unix" ) diff --git a/network/networkutils/networkutils_linux.go b/network/networkutils/networkutils_linux.go index 519da94f9c7..2dfc005d142 100644 --- a/network/networkutils/networkutils_linux.go +++ b/network/networkutils/networkutils_linux.go @@ -222,7 +222,7 @@ func (nu NetworkUtils) EnableIPV4Forwarding() error { } func (nu NetworkUtils) EnableIPV6Forwarding() error { - cmd := fmt.Sprint(enableIPV6ForwardCmd) + cmd := enableIPV6ForwardCmd _, err := nu.plClient.ExecuteCommand(cmd) if err != nil { logger.Error("Enable ipv6 forwarding failed with", zap.Error(err)) diff --git a/network/transparent_vlan_endpointclient_linux_test.go b/network/transparent_vlan_endpointclient_linux_test.go index be64142bc59..1099b97f129 100644 --- a/network/transparent_vlan_endpointclient_linux_test.go +++ b/network/transparent_vlan_endpointclient_linux_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/require" ) -var errNetnsMock = errors.New("mock netns error") -var errMockNetIOFail = errors.New("netio fail") -var errMockNetIONoIfFail = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errors.New("no such network interface")} +var ( + errNetnsMock = errors.New("mock netns error") + errMockNetIOFail = errors.New("netio fail") + errMockNetIONoIfFail = &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errors.New("no such network interface")} +) func newNetnsErrorMock(errStr string) error { return errors.Wrap(errNetnsMock, errStr) diff --git a/nns/grpcclient.go b/nns/grpcclient.go index c1745781ec8..0aac1a631f6 100644 --- a/nns/grpcclient.go +++ b/nns/grpcclient.go @@ -22,8 +22,8 @@ type GrpcClient struct{} // Add container to the network. Container Id is appended to the podName func (c *GrpcClient) AddContainerNetworking( ctx context.Context, - podName, nwNamespace string) (*contracts.ConfigureContainerNetworkingResponse, error) { - + podName, nwNamespace string, +) (*contracts.ConfigureContainerNetworkingResponse, error) { err, resp := configureContainerNetworking(ctx, contracts.RequestType_Setup, podName, nwNamespace) return resp, err } @@ -31,8 +31,8 @@ func (c *GrpcClient) AddContainerNetworking( // Add container to the network. Container Id is appended to the podName func (c *GrpcClient) DeleteContainerNetworking( ctx context.Context, - podName, nwNamespace string) (*contracts.ConfigureContainerNetworkingResponse, error) { - + podName, nwNamespace string, +) (*contracts.ConfigureContainerNetworkingResponse, error) { err, resp := configureContainerNetworking(ctx, contracts.RequestType_Teardown, podName, nwNamespace) return resp, err } @@ -42,8 +42,8 @@ func (c *GrpcClient) DeleteContainerNetworking( func configureContainerNetworking( ctx context.Context, reqtype contracts.RequestType, - podName, nwNamespace string) (error, *contracts.ConfigureContainerNetworkingResponse) { - + podName, nwNamespace string, +) (error, *contracts.ConfigureContainerNetworkingResponse) { // create a client. This also establishes grpc connection with nns client, conn, err := newGrpcClient(ctx) if err != nil { diff --git a/nns/mockgrpcclient.go b/nns/mockgrpcclient.go index 598a8d19965..86af1742e4d 100644 --- a/nns/mockgrpcclient.go +++ b/nns/mockgrpcclient.go @@ -18,7 +18,8 @@ var ErrMockNnsAdd = errors.New("mock nns add fail") // AddContainerNetworking - Mock nns add func (c *MockGrpcClient) AddContainerNetworking( ctx context.Context, - podName, nwNamespace string) (*contracts.ConfigureContainerNetworkingResponse, error) { + podName, nwNamespace string, +) (*contracts.ConfigureContainerNetworkingResponse, error) { if c.Fail { return nil, ErrMockNnsAdd } @@ -29,7 +30,7 @@ func (c *MockGrpcClient) AddContainerNetworking( // DeleteContainerNetworking - Mock nns delete func (c *MockGrpcClient) DeleteContainerNetworking( ctx context.Context, - podName, nwNamespace string) (*contracts.ConfigureContainerNetworkingResponse, error) { - + podName, nwNamespace string, +) (*contracts.ConfigureContainerNetworkingResponse, error) { return &contracts.ConfigureContainerNetworkingResponse{}, nil } diff --git a/npm/daemon/daemon.go b/npm/daemon/daemon.go index b261dbc3083..90d912c57df 100644 --- a/npm/daemon/daemon.go +++ b/npm/daemon/daemon.go @@ -33,7 +33,6 @@ func NewNetworkPolicyDaemon( client *transport.EventsClient, npmVersion string, ) (*NetworkPolicyDaemon, error) { - if dp == nil { return nil, ErrDataplaneNotInitialized } diff --git a/npm/http/client/client.go b/npm/http/client/client.go index 3a3bf731688..203d51294d6 100644 --- a/npm/http/client/client.go +++ b/npm/http/client/client.go @@ -5,9 +5,8 @@ import ( "net/http" "time" - "github.com/Azure/azure-container-networking/npm/http/api" - "github.com/Azure/azure-container-networking/npm" + "github.com/Azure/azure-container-networking/npm/http/api" ) type NPMHttpClient struct { @@ -26,7 +25,7 @@ func NewNPMHttpClient(endpoint string) *NPMHttpClient { func (n *NPMHttpClient) GetNpmMgr() (*npm.NetworkPolicyManager, error) { url := n.endpoint + api.NPMMgrPath - req, err := http.NewRequest(http.MethodGet, url, nil) + req, err := http.NewRequest(http.MethodGet, url, http.NoBody) if err != nil { return nil, err } diff --git a/npm/http/server/server.go b/npm/http/server/server.go index d20db191038..e4524d9c5f1 100644 --- a/npm/http/server/server.go +++ b/npm/http/server/server.go @@ -11,9 +11,8 @@ import ( npmconfig "github.com/Azure/azure-container-networking/npm/config" "github.com/Azure/azure-container-networking/npm/http/api" "github.com/Azure/azure-container-networking/npm/metrics" - "k8s.io/klog" - "github.com/gorilla/mux" + "k8s.io/klog" ) type NPMRestServer struct { diff --git a/npm/http/server/server_test.go b/npm/http/server/server_test.go index 0cfe2333e63..e04bf0690a4 100644 --- a/npm/http/server/server_test.go +++ b/npm/http/server/server_test.go @@ -21,7 +21,7 @@ func TestGetNPMCacheHandler(t *testing.T) { n := &NPMRestServer{} handler := n.npmCacheHandler(npmCacheEncoder) - req, err := http.NewRequest(http.MethodGet, api.NPMMgrPath, nil) + req, err := http.NewRequest(http.MethodGet, api.NPMMgrPath, http.NoBody) if err != nil { t.Fatal(err) } diff --git a/npm/ipsm/ipsm.go b/npm/ipsm/ipsm.go index 05074223e04..a8a92b25e8a 100644 --- a/npm/ipsm/ipsm.go +++ b/npm/ipsm/ipsm.go @@ -226,7 +226,6 @@ func (ipsMgr *IpsetManager) run(entry *ipsEntry) (int, error) { // CreateListNoLock is identical to CreateList except it does not lock the ipsMgr. func (ipsMgr *IpsetManager) CreateListNoLock(listName string) error { - if _, exists := ipsMgr.listMap[listName]; exists { return nil } diff --git a/npm/ipsm/ipsm_test.go b/npm/ipsm/ipsm_test.go index 7987b518cfb..4f159fbaea2 100644 --- a/npm/ipsm/ipsm_test.go +++ b/npm/ipsm/ipsm_test.go @@ -693,7 +693,7 @@ func TestElemSeparatorSupportsNone(t *testing.T) { } if _, err := ipsMgr.Run(entry); err == nil || err.ErrID != ElemSeperatorNotSupported { - t.Errorf("Expected elem seperator error: %+v", err) + t.Errorf("Expected elem separator error: %+v", err) } } diff --git a/npm/iptm/iptm.go b/npm/iptm/iptm.go index 45421ede86c..db9828e7fd2 100644 --- a/npm/iptm/iptm.go +++ b/npm/iptm/iptm.go @@ -15,7 +15,6 @@ import ( "github.com/Azure/azure-container-networking/npm/util" "github.com/Azure/azure-container-networking/npm/util/ioutil" utilexec "k8s.io/utils/exec" - // utiliptables "k8s.io/kubernetes/pkg/util/iptables" ) const ( diff --git a/npm/iptm/iptm_linux.go b/npm/iptm/iptm_linux.go index 90fb049664d..7ccc706a168 100644 --- a/npm/iptm/iptm_linux.go +++ b/npm/iptm/iptm_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package iptm diff --git a/npm/metrics/prometheus-values.go b/npm/metrics/prometheus-values.go index df23b622a6c..896c6c956e0 100644 --- a/npm/metrics/prometheus-values.go +++ b/npm/metrics/prometheus-values.go @@ -14,7 +14,7 @@ func counterValue(counter prometheus.Counter) (int, error) { if err != nil { return 0, err } - return int(dtoMetric.Counter.GetValue()), nil + return int(dtoMetric.GetCounter().GetValue()), nil } func histogramVecCount(histogramVec *prometheus.HistogramVec, labels prometheus.Labels) (int, error) { @@ -30,7 +30,7 @@ func histogramCount(histogram prometheus.Collector) (int, error) { if err != nil { return 0, err } - return int(dtoMetric.Histogram.GetSampleCount()), nil + return int(dtoMetric.GetHistogram().GetSampleCount()), nil } // getValue returns a Gauge metric's value. @@ -40,7 +40,7 @@ func getValue(gaugeMetric prometheus.Gauge) (int, error) { if err != nil { return 0, err } - return int(dtoMetric.Gauge.GetValue()), nil + return int(dtoMetric.GetGauge().GetValue()), nil } // getVecValue returns a Gauge Vec metric's value, or 0 if the label doesn't exist for the metric. @@ -56,7 +56,7 @@ func getCountValue(collector prometheus.Collector) (int, error) { if err != nil { return 0, err } - return int(dtoMetric.Summary.GetSampleCount()), nil + return int(dtoMetric.GetSummary().GetSampleCount()), nil } func getCountVecValue(summaryVecMetric *prometheus.SummaryVec, labels prometheus.Labels) (int, error) { @@ -92,7 +92,7 @@ func getQuantiles(summaryMetric prometheus.Summary) ([]*dto.Quantile, error) { if err != nil { return nil, err } - return dtoMetric.Summary.GetQuantile(), nil + return dtoMetric.GetSummary().GetQuantile(), nil } // This function is slow. diff --git a/npm/metrics/prometheus_metrics_test.go b/npm/metrics/prometheus_metrics_test.go index edc6e1e98e2..40888cf122c 100644 --- a/npm/metrics/prometheus_metrics_test.go +++ b/npm/metrics/prometheus_metrics_test.go @@ -14,7 +14,7 @@ func TestPrometheusNodeHandler(t *testing.T) { assert := assert.New(t) InitializeAll() handler := GetHandler(NodeMetrics) - req, err := http.NewRequest(http.MethodGet, api.NodeMetricsPath, nil) + req, err := http.NewRequest(http.MethodGet, api.NodeMetricsPath, http.NoBody) if err != nil { t.Fatal(err) } @@ -29,7 +29,7 @@ func TestPrometheusClusterHandler(t *testing.T) { assert := assert.New(t) InitializeAll() handler := GetHandler(ClusterMetrics) - req, err := http.NewRequest(http.MethodGet, api.ClusterMetricsPath, nil) + req, err := http.NewRequest(http.MethodGet, api.ClusterMetricsPath, http.NoBody) if err != nil { t.Fatal(err) } diff --git a/npm/npm.go b/npm/npm.go index ef3554aa558..f2dc50bf080 100644 --- a/npm/npm.go +++ b/npm/npm.go @@ -61,7 +61,8 @@ func NewNetworkPolicyManager(config npmconfig.Config, dp dataplane.GenericDataplane, exec utilexec.Interface, npmVersion string, - k8sServerVersion *version.Info) *NetworkPolicyManager { + k8sServerVersion *version.Info, +) *NetworkPolicyManager { klog.Infof("API server version: %+v AI metadata %+v", k8sServerVersion, aiMetadata) npMgr := &NetworkPolicyManager{ diff --git a/npm/pkg/controlplane/controllers/v1/networkPolicyController.go b/npm/pkg/controlplane/controllers/v1/networkPolicyController.go index 628d66db01c..8fa5190ebb9 100644 --- a/npm/pkg/controlplane/controllers/v1/networkPolicyController.go +++ b/npm/pkg/controlplane/controllers/v1/networkPolicyController.go @@ -461,7 +461,7 @@ func (c *NetworkPolicyController) cleanUpNetworkPolicy(netPolKey string, isSafeC return fmt.Errorf("[cleanUpNetworkPolicy] Error: removeCidrsRule out due to %w", err) } - // Sucess to clean up ipset and iptables operations in kernel and delete the cached network policy from RawNpMap + // Success to clean up ipset and iptables operations in kernel and delete the cached network policy from RawNpMap delete(c.rawNpMap, netPolKey) metrics.DecNumPolicies() diff --git a/npm/pkg/controlplane/controllers/v1/networkPolicyController_test.go b/npm/pkg/controlplane/controllers/v1/networkPolicyController_test.go index ba5cd79efff..03595c3c3b7 100644 --- a/npm/pkg/controlplane/controllers/v1/networkPolicyController_test.go +++ b/npm/pkg/controlplane/controllers/v1/networkPolicyController_test.go @@ -12,7 +12,6 @@ import ( "github.com/Azure/azure-container-networking/npm/metrics/promutil" "github.com/Azure/azure-container-networking/npm/util" "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/npm/pkg/controlplane/controllers/v1/parseSelector.go b/npm/pkg/controlplane/controllers/v1/parseSelector.go index 9b5dc821a46..e5f7ed72d04 100644 --- a/npm/pkg/controlplane/controllers/v1/parseSelector.go +++ b/npm/pkg/controlplane/controllers/v1/parseSelector.go @@ -5,10 +5,9 @@ import ( "fmt" "sort" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/Azure/azure-container-networking/log" "github.com/Azure/azure-container-networking/npm/util" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // An ReqHeap is a min-heap of labelSelectorRequirements. @@ -133,7 +132,7 @@ func getSetNameForMultiValueSelector(key string, vals []string) string { // HashSelector returns the hash value of the selector. func HashSelector(selector *metav1.LabelSelector) string { sortSelector(selector) - return util.Hash(fmt.Sprintf("%v", selector)) + return util.Hash(selector.String()) } // flattenNameSpaceSelector will help flatten multiple NameSpace selector match Expressions values @@ -141,7 +140,7 @@ func HashSelector(selector *metav1.LabelSelector) string { func FlattenNameSpaceSelector(nsSelector *metav1.LabelSelector) []metav1.LabelSelector { /* This function helps to create multiple labelSelectors when given a single multivalue nsSelector - Take below exmaple: this nsSelector has 2 values in a matchSelector. + Take below example: this nsSelector has 2 values in a matchSelector. - namespaceSelector: matchExpressions: - key: ns @@ -291,7 +290,7 @@ func parseSelector(selector *metav1.LabelSelector) ([]string, map[string][]strin labels = append(labels, k+":"+req.Values[0]) } else { // We are not adding the k:v to labels for multiple values, because, labels are used - // to contruct partial IptEntries and if these below labels are added then we are inducing + // to construct partial IptEntries and if these below labels are added then we are inducing // AND condition on values of a match expression instead of OR vals[k] = append(vals[k], req.Values...) } diff --git a/npm/pkg/controlplane/controllers/v1/parseSelector_test.go b/npm/pkg/controlplane/controllers/v1/parseSelector_test.go index 8207c27dd71..7034c50cf83 100644 --- a/npm/pkg/controlplane/controllers/v1/parseSelector_test.go +++ b/npm/pkg/controlplane/controllers/v1/parseSelector_test.go @@ -114,11 +114,11 @@ func TestGetOperatorsAndLabels(t *testing.T) { } if !reflect.DeepEqual(resultOps, expectedOps) { - t.Errorf("TestGetOperatorsAndLabels failed @ op comparision") + t.Errorf("TestGetOperatorsAndLabels failed @ op comparison") } if !reflect.DeepEqual(resultLabels, expectedLabels) { - t.Errorf("TestGetOperatorsAndLabels failed @ label comparision") + t.Errorf("TestGetOperatorsAndLabels failed @ label comparison") } } diff --git a/npm/pkg/controlplane/controllers/v1/podController.go b/npm/pkg/controlplane/controllers/v1/podController.go index 1d38baa683e..36f62b8fbbf 100644 --- a/npm/pkg/controlplane/controllers/v1/podController.go +++ b/npm/pkg/controlplane/controllers/v1/podController.go @@ -20,7 +20,6 @@ import ( "k8s.io/apimachinery/pkg/util/wait" coreinformer "k8s.io/client-go/informers/core/v1" corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/klog" @@ -407,7 +406,7 @@ func (c *PodController) syncAddAndUpdatePod(newPodObj *corev1.Pod) (metrics.Oper // now we know this is an update event, and we'll return metrics.UpdateOp // Dealing with "updatePod" event - Compare last applied states against current Pod states - // There are two possiblities for npmPodObj and newPodObj + // There are two possibilities for npmPodObj and newPodObj // #1 case The same object with the same UID and the same key (namespace + name) // #2 case Different objects with different UID, but the same key (namespace + name) due to missing some events for the old object @@ -536,7 +535,8 @@ func (c *PodController) cleanUpDeletedPod(cachedNpmPodKey string) error { // manageNamedPortIpsets helps with adding or deleting Pod namedPort IPsets. func (c *PodController) manageNamedPortIpsets(portList []corev1.ContainerPort, podKey string, - podIP string, namedPortOperation NamedPortOperation) error { + podIP string, namedPortOperation NamedPortOperation, +) error { for _, port := range portList { klog.Infof("port is %+v", port) if port.Name == "" { diff --git a/npm/pkg/controlplane/controllers/v1/podController_test.go b/npm/pkg/controlplane/controllers/v1/podController_test.go index 40bc7a88bc8..c12d705d5b1 100644 --- a/npm/pkg/controlplane/controllers/v1/podController_test.go +++ b/npm/pkg/controlplane/controllers/v1/podController_test.go @@ -753,7 +753,6 @@ func TestIsCompletePod(t *testing.T) { podState podState expectedCompletedPod bool }{ - { name: "pod is in running status", podState: podState{ diff --git a/npm/pkg/controlplane/controllers/v2/podController.go b/npm/pkg/controlplane/controllers/v2/podController.go index 47b4f0c2964..944b4984b59 100644 --- a/npm/pkg/controlplane/controllers/v2/podController.go +++ b/npm/pkg/controlplane/controllers/v2/podController.go @@ -587,7 +587,8 @@ func (c *PodController) cleanUpDeletedPod(cachedNpmPodKey string) error { // manageNamedPortIpsets helps with adding or deleting Pod namedPort IPsets. func (c *PodController) manageNamedPortIpsets(portList []corev1.ContainerPort, podKey, - podIP, nodeName string, namedPortOperation NamedPortOperation) error { + podIP, nodeName string, namedPortOperation NamedPortOperation, +) error { if util.IsWindowsDP() { // NOTE: if we support namedport operations, need to be careful of implications of including the node name in the pod metadata below // since we say the node name is "" in cleanUpDeletedPod diff --git a/npm/pkg/controlplane/goalstateprocessor/goalstateprocessor.go b/npm/pkg/controlplane/goalstateprocessor/goalstateprocessor.go index d3a34e92831..f92e7651654 100644 --- a/npm/pkg/controlplane/goalstateprocessor/goalstateprocessor.go +++ b/npm/pkg/controlplane/goalstateprocessor/goalstateprocessor.go @@ -31,8 +31,8 @@ func NewGoalStateProcessor( nodeID string, podName string, inputChan chan *protos.Events, - dp dataplane.GenericDataplane) (*GoalStateProcessor, error) { - + dp dataplane.GenericDataplane, +) (*GoalStateProcessor, error) { if nodeID == "" || podName == "" { return nil, ErrPodOrNodeNameNil } diff --git a/npm/pkg/controlplane/translation/parseSelector.go b/npm/pkg/controlplane/translation/parseSelector.go index e3fce8056c0..788893faa61 100644 --- a/npm/pkg/controlplane/translation/parseSelector.go +++ b/npm/pkg/controlplane/translation/parseSelector.go @@ -2,7 +2,6 @@ package translation import ( "fmt" - "regexp" "github.com/Azure/azure-container-networking/log" diff --git a/npm/pkg/controlplane/translation/translatePolicy.go b/npm/pkg/controlplane/translation/translatePolicy.go index 6cd5e740140..dac0cd9cb02 100644 --- a/npm/pkg/controlplane/translation/translatePolicy.go +++ b/npm/pkg/controlplane/translation/translatePolicy.go @@ -356,7 +356,8 @@ func peerAndPortRule(npmNetPol *policies.NPMNetworkPolicy, direction policies.Di // translateRule translates ingress or egress rules and update npmNetPol object. func translateRule(npmNetPol *policies.NPMNetworkPolicy, netPolName string, direction policies.Direction, matchType policies.MatchType, ruleIndex int, - ports []networkingv1.NetworkPolicyPort, peers []networkingv1.NetworkPolicyPeer) error { + ports []networkingv1.NetworkPolicyPort, peers []networkingv1.NetworkPolicyPeer, +) error { // TODO(jungukcho): need to clean up it. // Leave allowExternal variable now while the condition is checked before calling this function. allowExternal, portRuleExists, peerRuleExists := ruleExists(ports, peers) diff --git a/npm/pkg/dataplane/debug/converter.go b/npm/pkg/dataplane/debug/converter.go index e8e27a961cd..f3e9c97d76c 100644 --- a/npm/pkg/dataplane/debug/converter.go +++ b/npm/pkg/dataplane/debug/converter.go @@ -217,7 +217,6 @@ func (c *Converter) GetProtobufRulesFromIptableFile( npmCacheFile string, iptableSaveFile string, ) (map[*pb.RuleResponse]struct{}, error) { - err := c.initConverterFile(npmCacheFile) if err != nil { return nil, fmt.Errorf("error occurred during getting protobuf rules from iptables from file: %w", err) @@ -291,19 +290,19 @@ func (c *Converter) pbRuleList(ipTable *NPMIPtable.Table) (map[*pb.RuleResponse] // if rule is a string-int, we need to find the parent jump // to add the src for egress and dst for ingress - if strings.HasPrefix(childRule.Chain, EgressChainPrefix) { + if strings.HasPrefix(childRule.GetChain(), EgressChainPrefix) { for parentRule := range allRulesInNPMChains { - if strings.HasPrefix(parentRule.Chain, EgressChain) && parentRule.JumpTo == childRule.Chain { - childRule.SrcList = append(childRule.SrcList, parentRule.SrcList...) + if strings.HasPrefix(parentRule.GetChain(), EgressChain) && parentRule.JumpTo == childRule.GetChain() { + childRule.SrcList = append(childRule.GetSrcList(), parentRule.GetSrcList()...) childRule.Comment = parentRule.Comment parentRules = append(parentRules, parentRule) } } } - if strings.HasPrefix(childRule.Chain, IngressChainPrefix) { + if strings.HasPrefix(childRule.GetChain(), IngressChainPrefix) { for parentRule := range allRulesInNPMChains { - if strings.HasPrefix(parentRule.Chain, IngressChain) && parentRule.JumpTo == childRule.Chain { - childRule.DstList = append(childRule.DstList, parentRule.DstList...) + if strings.HasPrefix(parentRule.GetChain(), IngressChain) && parentRule.JumpTo == childRule.GetChain() { + childRule.DstList = append(childRule.GetDstList(), parentRule.GetDstList()...) childRule.Comment = parentRule.Comment parentRules = append(parentRules, parentRule) } @@ -404,8 +403,8 @@ func (c *Converter) getSetType(name string, m string) pb.SetType { if strings.Contains(name, util.IpsetLabelDelimter) { return pb.SetType_KEYVALUELABELOFPOD } - matcher.Match([]byte(name)) - if matched := matcher.Match([]byte(name)); matched { + matcher.MatchString(name) + if matched := matcher.MatchString(name); matched { return pb.SetType_CIDRBLOCKS } return pb.SetType_KEYLABELOFPOD @@ -502,16 +501,15 @@ func (c *Converter) getModulesFromRule(moduleList []*NPMIPtable.Module, ruleRes } func (c *Converter) populateSetInfo(setInfo *pb.RuleResponse_SetInfo, values []string, ruleRes *pb.RuleResponse) error { - ipsetHashedName := values[0] ipsetOrigin := values[1] setInfo.HashedSetName = ipsetHashedName if c.EnableV2NPM { setInfo.Name = c.SetMap[ipsetHashedName] - settype, _ := c.getSetTypeV2(setInfo.Name) + settype, _ := c.getSetTypeV2(setInfo.GetName()) if settype == pb.SetType_UNKNOWN { - return errors.Wrapf(ErrUnknownSetType, "unknown set type for set: %s", setInfo.Name) + return errors.Wrapf(ErrUnknownSetType, "unknown set type for set: %s", setInfo.GetName()) } setInfo.Type = settype @@ -522,7 +520,7 @@ func (c *Converter) populateSetInfo(setInfo *pb.RuleResponse_SetInfo, values []s } else if v, ok := c.SetMap[ipsetHashedName]; ok { setInfo.Name = v setInfo.Type = c.getSetType(v, "SetMap") - if setInfo.Type == pb.SetType_CIDRBLOCKS { + if setInfo.GetType() == pb.SetType_CIDRBLOCKS { populateCIDRBlockSet(setInfo) } } else { @@ -534,9 +532,9 @@ func (c *Converter) populateSetInfo(setInfo *pb.RuleResponse_SetInfo, values []s ruleRes.UnsortedIpset[ipsetHashedName] = ipsetOrigin } if strings.Contains(ipsetOrigin, "src") { - ruleRes.SrcList = append(ruleRes.SrcList, setInfo) + ruleRes.SrcList = append(ruleRes.GetSrcList(), setInfo) } else { - ruleRes.DstList = append(ruleRes.DstList, setInfo) + ruleRes.DstList = append(ruleRes.GetDstList(), setInfo) } return nil } @@ -544,7 +542,7 @@ func (c *Converter) populateSetInfo(setInfo *pb.RuleResponse_SetInfo, values []s // populate CIDRBlock set's content with ip addresses func populateCIDRBlockSet(setInfo *pb.RuleResponse_SetInfo) { ipsetBuffer := bytes.NewBuffer(nil) - cmdArgs := []string{"list", setInfo.HashedSetName} + cmdArgs := []string{"list", setInfo.GetHashedSetName()} cmd := exec.Command(util.Ipset, cmdArgs...) //nolint:gosec cmd.Stdout = ipsetBuffer @@ -570,7 +568,7 @@ func populateCIDRBlockSet(setInfo *pb.RuleResponse_SetInfo) { } for curReadIndex < len(ipsetBuffer.Bytes()) { member, nextReadIndex := parse.Line(curReadIndex, ipsetBuffer.Bytes()) - setInfo.Contents = append(setInfo.Contents, string(member)) + setInfo.Contents = append(setInfo.GetContents(), string(member)) curReadIndex = nextReadIndex } } diff --git a/npm/pkg/dataplane/debug/trafficanalyzer.go b/npm/pkg/dataplane/debug/trafficanalyzer.go index 2462989e12f..1b684bfd218 100644 --- a/npm/pkg/dataplane/debug/trafficanalyzer.go +++ b/npm/pkg/dataplane/debug/trafficanalyzer.go @@ -61,14 +61,14 @@ func PrettyPrintTuples(tuples []*TupleAndRule, srcList map[string]*pb.RuleRespon t := *tuple if chain, ok := tuplechains[*t.Tuple]; ok { // doesn't exist in map - if chain != t.Rule.Chain { + if chain != t.Rule.GetChain() { // we've seen this tuple before with a different chain, need to print - fmt.Printf("\t\tProtocol: %s, Port: %s, Chain: %v, Comment: %v\n", tuple.Tuple.Protocol, tuple.Tuple.DstPort, tuple.Rule.Chain, tuple.Rule.Comment) + fmt.Printf("\t\tProtocol: %s, Port: %s, Chain: %v, Comment: %v\n", tuple.Tuple.Protocol, tuple.Tuple.DstPort, tuple.Rule.GetChain(), tuple.Rule.Comment) } } else { // we haven't seen this tuple before, print everything - tuplechains[*t.Tuple] = t.Rule.Chain - fmt.Printf("\t\tProtocol: %s, Port: %s, Chain: %v, Comment: %v\n", tuple.Tuple.Protocol, tuple.Tuple.DstPort, tuple.Rule.Chain, tuple.Rule.Comment) + tuplechains[*t.Tuple] = t.Rule.GetChain() + fmt.Printf("\t\tProtocol: %s, Port: %s, Chain: %v, Comment: %v\n", tuple.Tuple.Protocol, tuple.Tuple.DstPort, tuple.Rule.GetChain(), tuple.Rule.Comment) } @@ -77,11 +77,11 @@ func PrettyPrintTuples(tuples []*TupleAndRule, srcList map[string]*pb.RuleRespon fmt.Printf("IPSets:") fmt.Printf("\tSource IPSets:\n") for i := range srcList { - fmt.Printf("\t\tName: %s, HashedName: %s,\n", srcList[i].Name, srcList[i].HashedSetName) + fmt.Printf("\t\tName: %s, HashedName: %s,\n", srcList[i].GetName(), srcList[i].GetHashedSetName()) } fmt.Printf("\tDestination IPSets:\n") for i := range dstList { - fmt.Printf("\t\tName: %s, HashedName: %s,\n", dstList[i].Name, dstList[i].HashedSetName) + fmt.Printf("\t\tName: %s, HashedName: %s,\n", dstList[i].GetName(), dstList[i].GetHashedSetName()) } } @@ -121,7 +121,6 @@ func getNetworkTupleCommon( npmCache common.GenericCache, allRules map[*pb.RuleResponse]struct{}, ) ([][]byte, []*TupleAndRule, map[string]*pb.RuleResponse_SetInfo, map[string]*pb.RuleResponse_SetInfo, error) { - srcPod, err := npmCache.GetPod(src) if err != nil { return nil, nil, nil, nil, fmt.Errorf("error occurred during get source pod : %w", err) @@ -140,7 +139,7 @@ func getNetworkTupleCommon( ruleResListJSON := make([][]byte, 0) m := protojson.MarshalOptions{ - Indent: " ", + Indent: " ", EmitUnpopulated: true, } for _, rule := range hitRules { @@ -169,12 +168,12 @@ func getNetworkTupleCommon( func generateTuple(src, dst *common.NpmPod, rule *pb.RuleResponse) *TupleAndRule { tuple := &Tuple{} - if rule.Allowed { + if rule.GetAllowed() { tuple.RuleType = "ALLOWED" } else { tuple.RuleType = "NOT ALLOWED" } - switch rule.Direction { + switch rule.GetDirection() { case pb.Direction_EGRESS: tuple.Direction = "EGRESS" case pb.Direction_INGRESS: @@ -185,28 +184,28 @@ func generateTuple(src, dst *common.NpmPod, rule *pb.RuleResponse) *TupleAndRule default: tuple.Direction = ANY } - if len(rule.SrcList) == 0 { + if len(rule.GetSrcList()) == 0 { tuple.SrcIP = ANY } else { tuple.SrcIP = src.IP() } - if rule.SPort != 0 { - tuple.SrcPort = strconv.Itoa(int(rule.SPort)) + if rule.GetSPort() != 0 { + tuple.SrcPort = strconv.Itoa(int(rule.GetSPort())) } else { tuple.SrcPort = ANY } - if len(rule.DstList) == 0 { + if len(rule.GetDstList()) == 0 { tuple.DstIP = ANY } else { tuple.DstIP = dst.IP() } - if rule.DPort != 0 { - tuple.DstPort = strconv.Itoa(int(rule.DPort)) + if rule.GetDPort() != 0 { + tuple.DstPort = strconv.Itoa(int(rule.GetDPort())) } else { tuple.DstPort = ANY } - if rule.Protocol != "" { - tuple.Protocol = rule.Protocol + if rule.GetProtocol() != "" { + tuple.Protocol = rule.GetProtocol() } else { tuple.Protocol = ANY } @@ -221,7 +220,6 @@ func getHitRules( rules map[*pb.RuleResponse]struct{}, npmCache common.GenericCache, ) ([]*pb.RuleResponse, map[string]*pb.RuleResponse_SetInfo, map[string]*pb.RuleResponse_SetInfo, error) { - res := make([]*pb.RuleResponse, 0) srcSets := make(map[string]*pb.RuleResponse_SetInfo, 0) dstSets := make(map[string]*pb.RuleResponse_SetInfo, 0) @@ -230,7 +228,7 @@ func getHitRules( matchedSrc := false matchedDst := false // evalute all match set in src - for _, setInfo := range rule.SrcList { + for _, setInfo := range rule.GetSrcList() { if src.Namespace == "" { // internet break @@ -242,13 +240,13 @@ func getHitRules( } if matchedSource { matchedSrc = true - srcSets[setInfo.HashedSetName] = setInfo + srcSets[setInfo.GetHashedSetName()] = setInfo break } } // evaluate all match set in dst - for _, setInfo := range rule.DstList { + for _, setInfo := range rule.GetDstList() { if dst.Namespace == "" { // internet break @@ -260,7 +258,7 @@ func getHitRules( } if matchedDestination { - dstSets[setInfo.HashedSetName] = setInfo + dstSets[setInfo.GetHashedSetName()] = setInfo matchedDst = true break } @@ -271,8 +269,8 @@ func getHitRules( // add if dst matches and there's no src // add if src and dst match with both src and dst specified - if (matchedSrc && len(rule.DstList) == 0) || - (matchedDst && len(rule.SrcList) == 0) || + if (matchedSrc && len(rule.GetDstList()) == 0) || + (matchedDst && len(rule.GetSrcList()) == 0) || (matchedSrc && matchedDst) { res = append(res, rule) } @@ -293,8 +291,7 @@ func evaluateSetInfo( rule *pb.RuleResponse, npmCache common.GenericCache, ) (bool, error) { - - switch setInfo.Type { + switch setInfo.GetType() { case pb.SetType_KEYVALUELABELOFNAMESPACE: return matchKEYVALUELABELOFNAMESPACE(pod, npmCache, setInfo), nil case pb.SetType_NESTEDLABELOFPOD: @@ -318,15 +315,15 @@ func evaluateSetInfo( func matchKEYVALUELABELOFNAMESPACE(pod *common.NpmPod, npmCache common.GenericCache, setInfo *pb.RuleResponse_SetInfo) bool { srcNamespace := util.NamespacePrefix + pod.Namespace - key, expectedValue := processKeyValueLabelOfNameSpace(setInfo.Name) + key, expectedValue := processKeyValueLabelOfNameSpace(setInfo.GetName()) actualValue := npmCache.GetNamespaceLabel(srcNamespace, key) if expectedValue != actualValue { // if the value is required but does not match - if setInfo.Included { + if setInfo.GetIncluded() { return false } } else { - if !setInfo.Included { + if !setInfo.GetIncluded() { return false } } @@ -338,19 +335,19 @@ func matchNESTEDLABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) // a function to split the key and the values and then combine the key with each value // return list of key value pairs which are keyvaluelabel of pod // one match then break - kvList := processNestedLabelOfPod(setInfo.Name) + kvList := processNestedLabelOfPod(setInfo.GetName()) hasOneKeyValuePair := false for _, kvPair := range kvList { key, value := processKeyValueLabelOfPod(kvPair) if pod.Labels[key] == value { - if !setInfo.Included { + if !setInfo.GetIncluded() { return false } hasOneKeyValuePair = true break } } - if !hasOneKeyValuePair && setInfo.Included { + if !hasOneKeyValuePair && setInfo.GetIncluded() { return false } @@ -359,12 +356,12 @@ func matchNESTEDLABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) func matchKEYLABELOFNAMESPACE(pod *common.NpmPod, npmCache common.GenericCache, setInfo *pb.RuleResponse_SetInfo) bool { srcNamespace := pod.Namespace - key := strings.Split(strings.TrimPrefix(setInfo.Name, util.NamespaceLabelPrefix), ":") + key := strings.Split(strings.TrimPrefix(setInfo.GetName(), util.NamespaceLabelPrefix), ":") included := npmCache.GetNamespaceLabel(srcNamespace, key[0]) if included != "" && included == key[1] { - return setInfo.Included + return setInfo.GetIncluded() } - if setInfo.Included { + if setInfo.GetIncluded() { // if key does not exist but required in rule return false } @@ -373,15 +370,15 @@ func matchKEYLABELOFNAMESPACE(pod *common.NpmPod, npmCache common.GenericCache, func matchNAMESPACE(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) bool { srcNamespace := util.NamespacePrefix + pod.Namespace - if setInfo.Name != srcNamespace || (setInfo.Name == srcNamespace && !setInfo.Included) { + if setInfo.GetName() != srcNamespace || (setInfo.GetName() == srcNamespace && !setInfo.GetIncluded()) { return false } return true } func matchKEYVALUELABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) bool { - key, value := processKeyValueLabelOfPod(setInfo.Name) - if pod.Labels[key] != value || (pod.Labels[key] == value && !setInfo.Included) { + key, value := processKeyValueLabelOfPod(setInfo.GetName()) + if pod.Labels[key] != value || (pod.Labels[key] == value && !setInfo.GetIncluded()) { return false } log.Printf("matched key value label of pod") @@ -389,11 +386,11 @@ func matchKEYVALUELABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInf } func matchKEYLABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) bool { - key := setInfo.Name + key := setInfo.GetName() if _, ok := pod.Labels[key]; ok { - return setInfo.Included + return setInfo.GetIncluded() } - if setInfo.Included { + if setInfo.GetIncluded() { // if key does not exist but required in rule return false } @@ -402,16 +399,16 @@ func matchKEYLABELOFPOD(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) bo } func matchNAMEDPORTS(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo, rule *pb.RuleResponse, origin string) bool { - portname := strings.TrimPrefix(setInfo.Name, util.NamedPortIPSetPrefix) + portname := strings.TrimPrefix(setInfo.GetName(), util.NamedPortIPSetPrefix) for _, namedPort := range pod.ContainerPorts { if namedPort.Name == portname { - if !setInfo.Included { + if !setInfo.GetIncluded() { return false } if rule.Protocol != "" && rule.Protocol != strings.ToLower(string(namedPort.Protocol)) { return false } - if rule.Protocol == "" { + if rule.GetProtocol() == "" { rule.Protocol = strings.ToLower(string(namedPort.Protocol)) } if origin == "src" { @@ -428,7 +425,7 @@ func matchNAMEDPORTS(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo, rule func matchCIDRBLOCKS(pod *common.NpmPod, setInfo *pb.RuleResponse_SetInfo) bool { matched := false - for _, entry := range setInfo.Contents { + for _, entry := range setInfo.GetContents() { entrySplitted := strings.Split(entry, " ") if len(entrySplitted) > 1 { // nomatch condition. i.e [172.17.1.0/24 nomatch] _, ipnet, _ := net.ParseCIDR(strings.TrimSpace(entrySplitted[0])) diff --git a/npm/pkg/dataplane/debug/trafficanalyzer_test.go b/npm/pkg/dataplane/debug/trafficanalyzer_test.go index 0e21bb172a7..6d857526841 100644 --- a/npm/pkg/dataplane/debug/trafficanalyzer_test.go +++ b/npm/pkg/dataplane/debug/trafficanalyzer_test.go @@ -13,7 +13,7 @@ import ( func AsSha256(o interface{}) string { h := sha256.New() - h.Write([]byte(fmt.Sprintf("%v", o))) + fmt.Fprintf(h, "%v", o) return fmt.Sprintf("%x", h.Sum(nil)) } diff --git a/npm/pkg/dataplane/ipsets/dirtycache.go b/npm/pkg/dataplane/ipsets/dirtycache.go index ae35486ef2f..86b0a646e72 100644 --- a/npm/pkg/dataplane/ipsets/dirtycache.go +++ b/npm/pkg/dataplane/ipsets/dirtycache.go @@ -10,25 +10,25 @@ import ( ) /* - dirtyCacheInterface will maintain the dirty cache. - It may maintain membersToAdd and membersToDelete. - Members are either IPs, CIDRs, IP-Port pairs, or prefixed set names if the parent is a list. - - Assumptions: - - if the set becomes dirty via update or destroy, then the set WAS in the kernel before - - if the set becomes dirty via create, then the set was NOT in the kernel before - - Usage: - - create, addMember, deleteMember, and destroy are idempotent - - create should not be called if the set becomes dirty via add/delete or the set is removed from the deleteCache via add/update - - deleteMember should not be called if the set is in the deleteCache - - deleteMember is safe to call on members in the kernel and members added via addMember - - deleteMember is also safe to call on members not in the kernel if the set isn't in the kernel yet (became dirty via create) - - Examples of Expected Behavior: - - if a set is created and then destroyed, that set will not be in the dirty cache anymore - - if a set is updated and then destroyed, that set will be in the delete cache - - if the only operations on a set are adding and removing the same member, the set may still be in the dirty cache, but the member will be untracked +dirtyCacheInterface will maintain the dirty cache. +It may maintain membersToAdd and membersToDelete. +Members are either IPs, CIDRs, IP-Port pairs, or prefixed set names if the parent is a list. + +Assumptions: +- if the set becomes dirty via update or destroy, then the set WAS in the kernel before +- if the set becomes dirty via create, then the set was NOT in the kernel before + +Usage: +- create, addMember, deleteMember, and destroy are idempotent +- create should not be called if the set becomes dirty via add/delete or the set is removed from the deleteCache via add/update +- deleteMember should not be called if the set is in the deleteCache +- deleteMember is safe to call on members in the kernel and members added via addMember +- deleteMember is also safe to call on members not in the kernel if the set isn't in the kernel yet (became dirty via create) + +Examples of Expected Behavior: +- if a set is created and then destroyed, that set will not be in the dirty cache anymore +- if a set is updated and then destroyed, that set will be in the delete cache +- if the only operations on a set are adding and removing the same member, the set may still be in the dirty cache, but the member will be untracked */ type dirtyCacheInterface interface { // reset empties dirty cache diff --git a/npm/pkg/dataplane/ipsets/ipsetmanager_linux.go b/npm/pkg/dataplane/ipsets/ipsetmanager_linux.go index 6d83ef47903..cda9a31cad3 100644 --- a/npm/pkg/dataplane/ipsets/ipsetmanager_linux.go +++ b/npm/pkg/dataplane/ipsets/ipsetmanager_linux.go @@ -65,36 +65,38 @@ var ( ) /* - based on ipset list output with azure-npm- prefix, create an ipset restore file where we flush all sets first, then destroy all sets - - NOTE: the behavior has changed to run two separate restore files. The first to flush all, the second to destroy all. In between restores, - we determine if there are any sets with leaked ipset reference counts. We ignore destroys for those sets in-line with v1. - - overall error handling: - - if flush fails because the set doesn't exist (should never happen because we're listing sets right before), then ignore it and the destroy - - if flush fails otherwise, then add to destroyFailureCount and continue (aborting the destroy too) - - if destroy fails because the set doesn't exist (should never happen since the flush operation would have worked), then ignore it - - if destroy fails for another reason, then ignore it and add to destroyFailureCount and mark for reconcile (TODO) - - example: - grep output: - azure-npm-123456 - azure-npm-987654 - azure-npm-777777 - - example restore file [flag meanings: -F (flush), -X (destroy)]: - -F azure-npm-123456 - -F azure-npm-987654 - -F azure-npm-777777 - -X azure-npm-123456 - -X azure-npm-987654 - -X azure-npm-777777 - - prometheus metrics: - After this function, NumIPSets should be 0 or the number of NPM IPSets that existed and failed to be destroyed. - When NPM restarts, Prometheus metrics will initialize at 0, but NPM IPSets may exist. - We will reset ipset entry metrics if the restore succeeds whether or not some flushes/destroys failed (NOTE: this is different behavior than v1). - If a flush fails, we could update the num entries for that set, but that would be a lot of overhead. +based on ipset list output with azure-npm- prefix, create an ipset restore file where we flush all sets first, then destroy all sets + +NOTE: the behavior has changed to run two separate restore files. The first to flush all, the second to destroy all. In between restores, +we determine if there are any sets with leaked ipset reference counts. We ignore destroys for those sets in-line with v1. + +overall error handling: +- if flush fails because the set doesn't exist (should never happen because we're listing sets right before), then ignore it and the destroy +- if flush fails otherwise, then add to destroyFailureCount and continue (aborting the destroy too) +- if destroy fails because the set doesn't exist (should never happen since the flush operation would have worked), then ignore it +- if destroy fails for another reason, then ignore it and add to destroyFailureCount and mark for reconcile (TODO) + +example: + + grep output: + azure-npm-123456 + azure-npm-987654 + azure-npm-777777 + + example restore file [flag meanings: -F (flush), -X (destroy)]: + -F azure-npm-123456 + -F azure-npm-987654 + -F azure-npm-777777 + -X azure-npm-123456 + -X azure-npm-987654 + -X azure-npm-777777 + +prometheus metrics: + + After this function, NumIPSets should be 0 or the number of NPM IPSets that existed and failed to be destroyed. + When NPM restarts, Prometheus metrics will initialize at 0, but NPM IPSets may exist. + We will reset ipset entry metrics if the restore succeeds whether or not some flushes/destroys failed (NOTE: this is different behavior than v1). + If a flush fails, we could update the num entries for that set, but that would be a lot of overhead. */ func (iMgr *IPSetManager) resetIPSets() error { if success := iMgr.resetWithoutRestore(); success { @@ -376,6 +378,7 @@ func (iMgr *IPSetManager) applyIPSetsWithSaveFile() error { See error handling in applyIPSetsWithSaveFile(). overall format for ipset restore file: + [creates] (random order) [deletes and adds] (sets in random order, where each set has deletes first (random order), then adds (random order)) [flushes] (random order) diff --git a/npm/pkg/dataplane/parse/parser.go b/npm/pkg/dataplane/parse/parser.go index 1f7f747bbc7..d28d277fa31 100644 --- a/npm/pkg/dataplane/parse/parser.go +++ b/npm/pkg/dataplane/parse/parser.go @@ -337,7 +337,6 @@ func parseModuleOptionAndValue( ruleLine []byte, included bool, ) int { - spaceIndex := bytes.Index(ruleLine[nextIndex:], SpaceBytes) currentOption := curOption if spaceIndex == -1 { diff --git a/npm/pkg/dataplane/policies/policy.go b/npm/pkg/dataplane/policies/policy.go index b411a7407bc..03dc21eefcd 100644 --- a/npm/pkg/dataplane/policies/policy.go +++ b/npm/pkg/dataplane/policies/policy.go @@ -273,7 +273,9 @@ func translatedIPSetsToString(items []*ipsets.TranslatedIPSet) string { // Included is false when match set have "!". // MatchType captures match direction flags. // For example match set in linux: -// ! azure-npm-123 src +// +// ! azure-npm-123 src +// // "!" this indicates a negative match (Included is false) of an azure-npm-123 // MatchType is "src" type SetInfo struct { diff --git a/server/tls/tlscertificate_retriever_linux_test.go b/server/tls/tlscertificate_retriever_linux_test.go index 135ca73396f..4fb5a50bc58 100644 --- a/server/tls/tlscertificate_retriever_linux_test.go +++ b/server/tls/tlscertificate_retriever_linux_test.go @@ -41,7 +41,7 @@ func TestPemConsumptionLinux(t *testing.T) { t.Fatalf("Failed to get certificate %+v", err) } if certificate.Subject.CommonName != commonName { - t.Fatalf("Recieved a unexpected subject name %+v", err) + t.Fatalf("Received a unexpected subject name %+v", err) } _, err = fileCertRetriever.GetPrivateKey() if err != nil { diff --git a/test/integration/npm/main.go b/test/integration/npm/main.go index de3ca6556e7..ed11ca64eee 100644 --- a/test/integration/npm/main.go +++ b/test/integration/npm/main.go @@ -186,7 +186,6 @@ func main() { fmt.Printf("\ncreating an unused set %s. The prior empty set %s should be deleted on this apply\n", unusedSet2.GetHashedName(), unusedSet1.GetHashedName()) dp.CreateIPSets([]*ipsets.IPSetMetadata{unusedSet2}) panicOnError(dp.ApplyDataPlane()) - } func panicOnError(err error) { diff --git a/test/nnsmockserver/nnsmockserver.go b/test/nnsmockserver/nnsmockserver.go index e373041c607..0ffa3329707 100644 --- a/test/nnsmockserver/nnsmockserver.go +++ b/test/nnsmockserver/nnsmockserver.go @@ -24,11 +24,11 @@ type serverApi struct{} func (s *serverApi) ConfigureContainerNetworking( ctx context.Context, - req *nns.ConfigureContainerNetworkingRequest) (*nns.ConfigureContainerNetworkingResponse, error) { - - fmt.Printf("Received request of type :%s \n", req.RequestType) - if err := isValidPodName(req.ContainerId); err != nil { - return nil, fmt.Errorf("NnsMockServer: RequestType:%s failed with error: %v", req.RequestType, err) + req *nns.ConfigureContainerNetworkingRequest, +) (*nns.ConfigureContainerNetworkingResponse, error) { + fmt.Printf("Received request of type :%s \n", req.GetRequestType()) + if err := isValidPodName(req.GetContainerId()); err != nil { + return nil, fmt.Errorf("NnsMockServer: RequestType:%s failed with error: %v", req.GetRequestType(), err) } ipaddress := &nns.ContainerIPAddress{ @@ -40,7 +40,7 @@ func (s *serverApi) ConfigureContainerNetworking( contTnterface := &nns.ContainerNetworkInterface{ Name: "azurevnet_45830dd4-1778-4735-9173-bba59b74cc8b_4ab80fb9-147e-4461-a213-56f4d44e806f", - NetworkNamespaceId: req.NetworkNamespaceId, + NetworkNamespaceId: req.GetNetworkNamespaceId(), Ipaddresses: []*nns.ContainerIPAddress{ipaddress}, MacAddress: "0036578BB0F1", } @@ -54,13 +54,15 @@ func (s *serverApi) ConfigureContainerNetworking( func (s *serverApi) ConfigureNetworking( context.Context, - *nns.ConfigureNetworkingRequest) (*nns.ConfigureNetworkingResponse, error) { + *nns.ConfigureNetworkingRequest, +) (*nns.ConfigureNetworkingResponse, error) { return nil, nil } func (s *serverApi) PingNodeNetworkService( context.Context, - *nns.PingNodeNetworkServiceRequest) (*nns.PingNodeNetworkServiceResponse, error) { + *nns.PingNodeNetworkServiceRequest, +) (*nns.PingNodeNetworkServiceResponse, error) { return nil, nil } diff --git a/test/utils/utils.go b/test/utils/utils.go index 276bb0afdf0..347f118008c 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/require" "k8s.io/utils/exec" - fakeexec "k8s.io/utils/exec/testing" ) diff --git a/tools/acncli/cmd/npm/npm.go b/tools/acncli/cmd/npm/npm.go index 67f69f6f9c7..fb94413e593 100644 --- a/tools/acncli/cmd/npm/npm.go +++ b/tools/acncli/cmd/npm/npm.go @@ -7,7 +7,6 @@ import ( "fmt" "github.com/Azure/azure-container-networking/npm/http/api" - npm "github.com/Azure/azure-container-networking/npm/http/client" c "github.com/Azure/azure-container-networking/tools/acncli/api" "github.com/Azure/azure-container-networking/tools/acncli/cmd/npm/get" diff --git a/tools/acncli/cmd/root.go b/tools/acncli/cmd/root.go index ee653de695d..194ceaeb991 100644 --- a/tools/acncli/cmd/root.go +++ b/tools/acncli/cmd/root.go @@ -6,11 +6,9 @@ package cmd import ( "fmt" - "github.com/Azure/azure-container-networking/tools/acncli/cmd/npm" - - "github.com/Azure/azure-container-networking/tools/acncli/cmd/cni" - c "github.com/Azure/azure-container-networking/tools/acncli/api" + "github.com/Azure/azure-container-networking/tools/acncli/cmd/cni" + "github.com/Azure/azure-container-networking/tools/acncli/cmd/npm" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/tools/acncli/main.go b/tools/acncli/main.go index 72336fb49a2..257ca2fb4bd 100644 --- a/tools/acncli/main.go +++ b/tools/acncli/main.go @@ -4,12 +4,11 @@ package main import ( + c "github.com/Azure/azure-container-networking/tools/acncli/api" "github.com/Azure/azure-container-networking/tools/acncli/cmd" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" - - c "github.com/Azure/azure-container-networking/tools/acncli/api" ) var (