diff --git a/aitelemetry/telemetrywrapper.go b/aitelemetry/telemetrywrapper.go index e247028cfd..00148572aa 100644 --- a/aitelemetry/telemetrywrapper.go +++ b/aitelemetry/telemetrywrapper.go @@ -96,7 +96,7 @@ func getMetadata(th *telemetryHandle) { return } - //acquire write lock before writing metadata to telemetry handle + // acquire write lock before writing metadata to telemetry handle th.rwmutex.Lock() th.metadata = metadata th.rwmutex.Unlock() @@ -188,7 +188,7 @@ func (th *telemetryHandle) TrackLog(report Report) { // Initialize new trace message trace := appinsights.NewTraceTelemetry(report.Message, appinsights.Warning) - //Override few of existing columns with metadata + // Override few of existing columns with metadata trace.Tags.User().SetAuthUserId(runtime.GOOS) trace.Tags.Operation().SetId(report.Context) trace.Tags.Operation().SetParentId(th.appVersion) diff --git a/aitelemetry/telemetrywrapper_windows.go b/aitelemetry/telemetrywrapper_windows.go index f8a337c4c2..cd49357705 100644 --- a/aitelemetry/telemetrywrapper_windows.go +++ b/aitelemetry/telemetrywrapper_windows.go @@ -5,6 +5,4 @@ import ( "path/filepath" ) -var ( - metadataFile = filepath.FromSlash(os.Getenv("TEMP")) + "\\azuremetadata.json" -) +var metadataFile = filepath.FromSlash(os.Getenv("TEMP")) + "\\azuremetadata.json" diff --git a/cni/client/client_integration_test.go b/cni/client/client_integration_test.go index 5472b7e7e6..6ecf50200f 100644 --- a/cni/client/client_integration_test.go +++ b/cni/client/client_integration_test.go @@ -104,5 +104,4 @@ func TestGetStateWithEmptyStateFile(t *testing.T) { state, err := c.GetEndpointState() require.NoError(t, err) require.Exactly(t, 0, len(state.ContainerInterfaces)) - } diff --git a/cni/ipam/ipam_test.go b/cni/ipam/ipam_test.go index cc6c32ef17..759767c8d7 100644 --- a/cni/ipam/ipam_test.go +++ b/cni/ipam/ipam_test.go @@ -21,18 +21,20 @@ import ( "github.com/Azure/azure-container-networking/common" ) -var ipamQueryUrl = "localhost:42424" -var ipamQueryResponse = "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "" +var ( + ipamQueryUrl = "localhost:42424" + ipamQueryResponse = "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" +) func TestIpam(t *testing.T) { RegisterFailHandler(Fail) @@ -73,11 +75,11 @@ var ( err error endpointID1 = uuid.New().String() - //this usedAddresses map is to test not duplicate IP's + // this usedAddresses map is to test not duplicate IP's // have been provided throughout this test execution UsedAddresses = map[string]string{} - //below is the network,used to test if the IP's provided by IPAM + // below is the network,used to test if the IP's provided by IPAM // is in the the space requested. network = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(16, 32)} @@ -104,9 +106,7 @@ var ( }) _ = Describe("Test IPAM", func() { - Context("IPAM start", func() { - var config common.PluginConfig It("Create IPAM plugin", func() { @@ -127,7 +127,6 @@ var ( }) Describe("Test IPAM ADD and DELETE pool", func() { - var result *cniTypesCurr.Result Context("When ADD with nothing, call for ipam triggering request pool and address", func() { @@ -153,7 +152,6 @@ var ( Expect(err).ShouldNot(HaveOccurred()) delete(UsedAddresses, result.IPs[0].Address.IP.String()) - }) }) @@ -167,7 +165,6 @@ var ( }) Describe("Test IPAM ADD and DELETE address", func() { - Context("When address is given", func() { It("Request pool and address successfully", func() { arg.StdinData = getStdinData("0.4.0", "", "10.0.0.6") @@ -217,14 +214,13 @@ var ( AssertProperAddressSpace(result.IPs[0].Address) - //release the container ID for next test + // release the container ID for next test arg.ContainerID = "" }) }) }) Describe("Test IPAM DELETE", func() { - Context("Delete when only container id is given", func() { It("Deleted", func() { arg.StdinData = getStdinData("0.4.0", "10.0.0.0/16", "") @@ -236,13 +232,11 @@ var ( address := UsedAddresses[arg.ContainerID] RemoveAddressUsage(address, arg.ContainerID) - }) }) Context("When address and subnet is given", func() { It("Release address successfully", func() { - nextAddress := GetNextAddress() arg.StdinData = getStdinData("0.4.0", "10.0.0.0/16", nextAddress) err = plugin.Delete(arg) @@ -291,7 +285,7 @@ var ( ) func GetNextAddress() string { - //return first value + // return first value for a := range UsedAddresses { return a } @@ -299,7 +293,7 @@ func GetNextAddress() string { } func AssertAddressNotInUse(address string) { - //confirm if IP is in use by other invocation + // confirm if IP is in use by other invocation _, exists := UsedAddresses[address] Expect(exists).Should(BeFalse()) @@ -325,7 +319,7 @@ func RemoveAddressUsage(address, containerId string) { } func AssertProperAddressSpace(address net.IPNet) { - //validate the IP is part of this network IP space + // validate the IP is part of this network IP space Expect(network.Contains(address.IP)).Should(Equal(true)) Expect(address.Mask).Should(Equal(network.Mask)) } diff --git a/cni/netconfig.go b/cni/netconfig.go index 240c19011e..cde3d8accb 100644 --- a/cni/netconfig.go +++ b/cni/netconfig.go @@ -28,6 +28,7 @@ type PortMapping struct { Protocol string `json:"protocol"` HostIp string `json:"hostIP,omitempty"` } + type RuntimeConfig struct { PortMappings []PortMapping `json:"portMappings,omitempty"` DNS RuntimeDNSConfig `json:"dns,omitempty"` diff --git a/cni/network/invoker.go b/cni/network/invoker.go index aceb3e242a..42b06b2ab5 100644 --- a/cni/network/invoker.go +++ b/cni/network/invoker.go @@ -13,9 +13,9 @@ import ( // or simply act as a client to an external ipam, such as azure-cns. type IPAMInvoker interface { - //Add returns two results, one IPv4, the other IPv6. + // Add returns two results, one IPv4, the other IPv6. Add(nwCfg *cni.NetworkConfig, args *cniSkel.CmdArgs, subnetPrefix *net.IPNet, options map[string]interface{}) (*cniTypesCurr.Result, *cniTypesCurr.Result, error) - //Delete calls to the invoker source, and returns error. Returning an error here will fail the CNI Delete call. + // Delete calls to the invoker source, and returns error. Returning an error here will fail the CNI Delete call. Delete(address *net.IPNet, nwCfg *cni.NetworkConfig, args *cniSkel.CmdArgs, options map[string]interface{}) error } diff --git a/cni/network/invoker_azure.go b/cni/network/invoker_azure.go index 0850755977..595f1986de 100644 --- a/cni/network/invoker_azure.go +++ b/cni/network/invoker_azure.go @@ -45,7 +45,7 @@ func (invoker *AzureIPAMInvoker) Add(nwCfg *cni.NetworkConfig, _ *cniSkel.CmdArg result, err = invoker.plugin.DelegateAdd(nwCfg.Ipam.Type, nwCfg) if err != nil { err = invoker.plugin.Errorf("Failed to allocate pool: %v", err) - return nil, nil, err + return nil, nil, err } defer func() { @@ -83,7 +83,6 @@ func (invoker *AzureIPAMInvoker) Add(nwCfg *cni.NetworkConfig, _ *cniSkel.CmdArg } func (invoker *AzureIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkConfig, _ *cniSkel.CmdArgs, options map[string]interface{}) error { - if nwCfg == nil { return invoker.plugin.Errorf("nil nwCfg passed to CNI ADD, stack: %+v", string(debug.Stack())) } diff --git a/cni/network/invoker_cns.go b/cni/network/invoker_cns.go index c95fbe7a58..68a4c95bf9 100644 --- a/cni/network/invoker_cns.go +++ b/cni/network/invoker_cns.go @@ -48,7 +48,7 @@ func NewCNSInvoker(podName, namespace string) (*CNSIPAMInvoker, error) { }, err } -//Add uses the requestipconfig API in cns, and returns ipv4 and a nil ipv6 as CNS doesn't support IPv6 yet +// Add uses the requestipconfig API in cns, and returns ipv4 and a nil ipv6 as CNS doesn't support IPv6 yet func (invoker *CNSIPAMInvoker) Add(nwCfg *cni.NetworkConfig, args *cniSkel.CmdArgs, hostSubnetPrefix *net.IPNet, options map[string]interface{}) (*cniTypesCurr.Result, *cniTypesCurr.Result, error) { // Parse Pod arguments. podInfo := cns.KubernetesPodInfo{ diff --git a/cni/network/network.go b/cni/network/network.go index 85b79353fd..5e0a9e7f8e 100644 --- a/cni/network/network.go +++ b/cni/network/network.go @@ -1201,7 +1201,7 @@ func determineSnat() (bool, bool, error) { } jsonStr, _ := json.Marshal(snatConfig) - fp, err := os.OpenFile(snatConfigFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0664)) + fp, err := os.OpenFile(snatConfigFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0o664)) if err == nil { fp.Write(jsonStr) fp.Close() diff --git a/cni/network/network_windows.go b/cni/network/network_windows.go index 5de1b9d38b..6b0e487f5b 100644 --- a/cni/network/network_windows.go +++ b/cni/network/network_windows.go @@ -29,8 +29,6 @@ var ( win1903Version = 18362 ) - - /* handleConsecutiveAdd handles consecutive add calls for infrastructure containers on Windows platform. * This is a temporary work around for issue #57253 of Kubernetes. * We can delete this if statement once they fix it. @@ -289,9 +287,7 @@ func getPoliciesFromRuntimeCfg(nwCfg *cni.NetworkConfig) []policy.Policy { } func addIPV6EndpointPolicy(nwInfo network.NetworkInfo) (policy.Policy, error) { - var ( - eppolicy policy.Policy - ) + var eppolicy policy.Policy if len(nwInfo.Subnets) < 2 { return eppolicy, fmt.Errorf("network state doesn't have ipv6 subnet") diff --git a/cnm/api.go b/cnm/api.go index 80a3c00dac..5c6a7c76dc 100644 --- a/cnm/api.go +++ b/cnm/api.go @@ -23,8 +23,7 @@ type errorResponse struct { } // Request sent by libnetwork for activation. -type activateRequest struct { -} +type activateRequest struct{} // Response sent by plugin for activation. type ActivateResponse struct { diff --git a/cnm/ipam/api.go b/cnm/ipam/api.go index d112158055..a5aa8d673f 100644 --- a/cnm/ipam/api.go +++ b/cnm/ipam/api.go @@ -22,8 +22,7 @@ const ( ) // Request sent by libnetwork when querying plugin capabilities. -type GetCapabilitiesRequest struct { -} +type GetCapabilitiesRequest struct{} // Response sent by plugin when registering its capabilities with libnetwork. type GetCapabilitiesResponse struct { @@ -33,8 +32,7 @@ type GetCapabilitiesResponse struct { } // Request sent by libnetwork when querying the default address space names. -type GetDefaultAddressSpacesRequest struct { -} +type GetDefaultAddressSpacesRequest struct{} // Response sent by plugin when returning the default address space names. type GetDefaultAddressSpacesResponse struct { diff --git a/cnm/ipam/ipam_test.go b/cnm/ipam/ipam_test.go index 018296cc44..534fcbc638 100644 --- a/cnm/ipam/ipam_test.go +++ b/cnm/ipam/ipam_test.go @@ -20,27 +20,30 @@ import ( "github.com/Azure/azure-container-networking/ipam" ) -var plugin IpamPlugin -var mux *http.ServeMux - -var ipamQueryUrl = "localhost:42424" -var ipamQueryResponse = "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "" - -var localAsId string -var poolId1 string -var address1 string +var ( + plugin IpamPlugin + mux *http.ServeMux +) + +var ( + ipamQueryUrl = "localhost:42424" + ipamQueryResponse = "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" + localAsId string + poolId1 string + address1 string +) // Wraps the test run with plugin setup and teardown. func TestMain(m *testing.M) { diff --git a/cnm/network/api.go b/cnm/network/api.go index ee2e95f267..d11f667124 100644 --- a/cnm/network/api.go +++ b/cnm/network/api.go @@ -22,8 +22,7 @@ const ( ) // Request sent by libnetwork when querying plugin capabilities. -type getCapabilitiesRequest struct { -} +type getCapabilitiesRequest struct{} // Response sent by plugin when registering its capabilities with libnetwork. type getCapabilitiesResponse struct { diff --git a/cnm/network/network_test.go b/cnm/network/network_test.go index 475f8f9b93..a75f466a39 100644 --- a/cnm/network/network_test.go +++ b/cnm/network/network_test.go @@ -22,14 +22,18 @@ import ( remoteApi "github.com/docker/libnetwork/drivers/remote/api" ) -var plugin NetPlugin -var mux *http.ServeMux +var ( + plugin NetPlugin + mux *http.ServeMux +) -var anyInterface = "dummy" -var anySubnet = "192.168.1.0/24" -var ipnet = net.IPNet{IP: net.ParseIP("192.168.1.0"), Mask: net.IPv4Mask(255, 255, 255, 0)} -var networkID = "N1" -var netns = "22212" +var ( + anyInterface = "dummy" + anySubnet = "192.168.1.0/24" + ipnet = net.IPNet{IP: net.ParseIP("192.168.1.0"), Mask: net.IPv4Mask(255, 255, 255, 0)} + networkID = "N1" + netns = "22212" +) // endpoint ID must contain 7 characters var endpointID = "E1-xxxx" @@ -178,7 +182,7 @@ func TestCNM(t *testing.T) { log.Printf("###DeleteEndpoint#####################################################################################") deleteEndpointT(t) log.Printf("###DeleteNetwork#####################################################################################") - //deleteNetworkT(t) + // deleteNetworkT(t) } // Tests NetworkDriver.CreateNetwork functionality. diff --git a/cnm/plugin.go b/cnm/plugin.go index 7b08981062..9c2fe07e34 100644 --- a/cnm/plugin.go +++ b/cnm/plugin.go @@ -85,12 +85,12 @@ func (plugin *Plugin) EnableDiscovery() error { // Create the spec directory. path := plugin.getSpecPath() - os.MkdirAll(path, 0755) + os.MkdirAll(path, 0o755) // Write the listener URL to the spec file. fileName := path + plugin.Name + ".spec" url := plugin.Listener.URL.String() - err := ioutil.WriteFile(fileName, []byte(url), 0644) + err := ioutil.WriteFile(fileName, []byte(url), 0o644) return err } diff --git a/cnm/plugin_linux.go b/cnm/plugin_linux.go index ebadfb30f5..e552c98b40 100644 --- a/cnm/plugin_linux.go +++ b/cnm/plugin_linux.go @@ -27,7 +27,7 @@ func (plugin *Plugin) getAPIServerURL() string { urls = defaultAPIServerURL + plugin.Name + ".sock" } - os.MkdirAll(pluginSocketPath, 0755) + os.MkdirAll(pluginSocketPath, 0o755) return urls } diff --git a/cnms/cnmspackage/monitor2rules_linux.go b/cnms/cnmspackage/monitor2rules_linux.go index 23d95bdf3d..3b3ffb6a7f 100644 --- a/cnms/cnmspackage/monitor2rules_linux.go +++ b/cnms/cnmspackage/monitor2rules_linux.go @@ -9,7 +9,6 @@ import ( // deleteRulesNotExistInMap deletes rules from nat Ebtable if rule was not in stateRules after a certain number of iterations. func (networkMonitor *NetworkMonitor) deleteRulesNotExistInMap(chainRules map[string]string, stateRules map[string]string) { - table := ebtables.Nat action := ebtables.Delete diff --git a/cns/cnireconciler/statefile.go b/cns/cnireconciler/statefile.go index 4e702084d9..5dcc128a46 100644 --- a/cns/cnireconciler/statefile.go +++ b/cns/cnireconciler/statefile.go @@ -38,5 +38,5 @@ func writeObjectToFile(filename string) error { logger.Printf("Writing {} to CNI statefile %s", filename) b, _ := json.Marshal(map[string]string{}) - return os.WriteFile(filename, b, os.FileMode(0666)) + return os.WriteFile(filename, b, os.FileMode(0o666)) } diff --git a/cns/cnireconciler/statefile_test.go b/cns/cnireconciler/statefile_test.go index e53aaeca5c..335ad20918 100644 --- a/cns/cnireconciler/statefile_test.go +++ b/cns/cnireconciler/statefile_test.go @@ -12,7 +12,7 @@ import ( func TestWriteObjectToFile(t *testing.T) { name := "testdata/test" - err := os.MkdirAll(path.Dir(name), 0666) + err := os.MkdirAll(path.Dir(name), 0o666) require.NoError(t, err) _, err = os.Stat(name) diff --git a/cns/dockerclient/dockerclient.go b/cns/dockerclient/dockerclient.go index ac4ab06a1d..1c43cada6f 100644 --- a/cns/dockerclient/dockerclient.go +++ b/cns/dockerclient/dockerclient.go @@ -50,7 +50,6 @@ func (dockerClient *DockerClient) NetworkExists(networkName string) error { res, err := http.Get( dockerClient.connectionURL + inspectNetworkPath + networkName) - if err != nil { logger.Errorf("[Azure CNS] Error received from http Post for docker network inspect %v %v", networkName, err.Error()) return err @@ -120,7 +119,6 @@ func (dockerClient *DockerClient) CreateNetwork(networkName string, nicInfo *imd dockerClient.connectionURL+createNetworkPath, common.JsonContent, netConfigJSON) - if err != nil { logger.Printf("[Azure CNS] Error received from http Post for docker network create %v", networkName) return err diff --git a/cns/fakes/imdsclientfake.go b/cns/fakes/imdsclientfake.go index 29655d26be..70d51db81c 100644 --- a/cns/fakes/imdsclientfake.go +++ b/cns/fakes/imdsclientfake.go @@ -14,8 +14,7 @@ var ( ) // ImdsClient can be used to connect to VM Host agent in Azure. -type ImdsClientTest struct { -} +type ImdsClientTest struct{} func NewFakeImdsClient() *ImdsClientTest { return &ImdsClientTest{} @@ -23,7 +22,6 @@ func NewFakeImdsClient() *ImdsClientTest { // GetNetworkContainerInfoFromHost - Mock implementation to return Container version info. func (imdsClient *ImdsClientTest) GetNetworkContainerInfoFromHost(networkContainerID string, primaryAddress string, authToken string, apiVersion string) (*imdsclient.ContainerVersion, error) { - ret := &imdsclient.ContainerVersion{} return ret, nil diff --git a/cns/fakes/nmagentclientfake.go b/cns/fakes/nmagentclientfake.go index 5cf601f7b1..5bfa9b523e 100644 --- a/cns/fakes/nmagentclientfake.go +++ b/cns/fakes/nmagentclientfake.go @@ -4,8 +4,7 @@ package fakes // NMAgentClientTest can be used to query to VM Host info. -type NMAgentClientTest struct { -} +type NMAgentClientTest struct{} // NewFakeNMAgentClient return a mock implemetation of NMAgentClient func NewFakeNMAgentClient() *NMAgentClientTest { diff --git a/cns/hnsclient/hnsclient_windows.go b/cns/hnsclient/hnsclient_windows.go index 87a28fd238..cc24b7917a 100644 --- a/cns/hnsclient/hnsclient_windows.go +++ b/cns/hnsclient/hnsclient_windows.go @@ -73,14 +73,12 @@ const ( // aclPolicyType indicates a ACL policy aclPolicyType = "ACLPolicy" - //signals a APIPA endpoint type + // signals a APIPA endpoint type apipaEndpointType = "APIPA" ) -var ( - // Named Lock for network and endpoint creation/deletion - namedLock = common.InitNamedLock() -) +// Named Lock for network and endpoint creation/deletion +var namedLock = common.InitNamedLock() // CreateHnsNetwork creates the HNS network with the provided configuration func CreateHnsNetwork(nwConfig cns.CreateHnsNetworkRequest) error { @@ -215,7 +213,7 @@ func configureHostNCApipaNetwork(localIPConfiguration cns.IPConfiguration) (*hcn network := &hcn.HostComputeNetwork{ Name: hostNCApipaNetworkName, Ipams: []hcn.Ipam{ - hcn.Ipam{ + { Type: hcnIpamTypeStatic, }, }, @@ -259,7 +257,7 @@ func configureHostNCApipaNetwork(localIPConfiguration cns.IPConfiguration) (*hcn subnet := hcn.Subnet{ IpAddressPrefix: subnetPrefixStr, Routes: []hcn.Route{ - hcn.Route{ + { NextHop: localIPConfiguration.GatewayIPAddress, DestinationPrefix: "0.0.0.0/0", }, @@ -467,11 +465,11 @@ func configureAclSettingHostNCApipaEndpoint( if err = json.Unmarshal(requestedPolicy.Settings, &requestedAclPolicy); err != nil { return nil, fmt.Errorf("Failed to Unmarshal requested ACL policy: %+v with error: %+v", requestedPolicy.Settings, err) } - //Using {NetworkContainerIP} as a placeholder to signal using Network Container IP + // Using {NetworkContainerIP} as a placeholder to signal using Network Container IP if strings.EqualFold(requestedAclPolicy.LocalAddresses, "{NetworkContainerIP}") { requestedAclPolicy.LocalAddresses = networkContainerApipaIP } - //Using {HostApipaIP} as a placeholder to signal using Host Apipa IP + // Using {HostApipaIP} as a placeholder to signal using Host Apipa IP if strings.EqualFold(requestedAclPolicy.RemoteAddresses, "{HostApipaIP}") { requestedAclPolicy.RemoteAddresses = hostApipaIP } @@ -512,7 +510,6 @@ func configureHostNCApipaEndpoint( allowNCToHostCommunication, allowHostToNCCommunication, ncPolicies) - if err != nil { logger.Errorf("[Azure CNS] Failed to configure ACL for HostNCApipaEndpoint. Error: %v", err) return nil, err @@ -687,4 +684,4 @@ func DeleteHostNCApipaEndpoint( logger.Debugf("[Azure CNS] Successfully deleted HostNCApipaEndpoint: %s", endpointName) return nil -} \ No newline at end of file +} diff --git a/cns/ipamclient/ipamclient.go b/cns/ipamclient/ipamclient.go index ae52f143f6..a325667c9e 100644 --- a/cns/ipamclient/ipamclient.go +++ b/cns/ipamclient/ipamclient.go @@ -110,7 +110,6 @@ func (ic *IpamClient) GetPoolID(asID, subnet string) (string, error) { } log.Printf("[Azure CNS] GetPoolID invalid http status code: %v err:%v", res.StatusCode, err.Error()) return "", err - } // ReserveIPAddress request an Ip address for the reservation id. @@ -209,7 +208,6 @@ func (ic *IpamClient) ReleaseIPAddress(poolID string, reservationID string) erro } log.Printf("[Azure CNS] ReleaseIP invalid http status code: %v", res.StatusCode) return err - } // GetIPAddressUtilization - returns number of available, reserved and unhealthy addresses list. @@ -254,5 +252,4 @@ func (ic *IpamClient) GetIPAddressUtilization(poolID string) (int, int, []string } log.Printf("[Azure CNS] GetIPUtilization invalid http status code: %v err:%v", res.StatusCode, err.Error()) return 0, 0, nil, err - } diff --git a/cns/ipamclient/ipamclient_linux.go b/cns/ipamclient/ipamclient_linux.go index efef23b517..cb3afbd300 100644 --- a/cns/ipamclient/ipamclient_linux.go +++ b/cns/ipamclient/ipamclient_linux.go @@ -18,7 +18,7 @@ const ( pluginSockPath = "/run/docker/plugins/azure-vnet.sock" ) -//getClient - returns unix http client +// getClient - returns unix http client func getClient(url string) (*http.Client, error) { var httpc *http.Client if url == defaultIpamPluginURL { diff --git a/cns/ipamclient/ipamclient_test.go b/cns/ipamclient/ipamclient_test.go index 0819b9103c..3aea708110 100644 --- a/cns/ipamclient/ipamclient_test.go +++ b/cns/ipamclient/ipamclient_test.go @@ -1,11 +1,9 @@ package ipamclient import ( - "encoding/json" "fmt" "log" "net/http" - "net/http/httptest" "net/url" "os" "testing" @@ -14,12 +12,13 @@ import ( "github.com/Azure/azure-container-networking/common" ) -var ipamQueryUrl = "localhost:42424" -var ic *IpamClient +var ( + ipamQueryUrl = "localhost:42424" + ic *IpamClient +) // Wraps the test run with service setup and teardown. func TestMain(m *testing.M) { - // Create a fake IPAM plugin to handle requests from CNS plugin. u, _ := url.Parse("tcp://" + ipamQueryUrl) ipamAgent, err := common.NewListener(u) @@ -49,24 +48,23 @@ func TestMain(m *testing.M) { ipamAgent.Stop() os.Exit(exitCode) - } // Handles queries from GetAddressSpace. func handleIpamAsIDQuery(w http.ResponseWriter, r *http.Request) { - var addressSpaceResp = "{\"LocalDefaultAddressSpace\": \"local\", \"GlobalDefaultAddressSpace\": \"global\"}" + addressSpaceResp := "{\"LocalDefaultAddressSpace\": \"local\", \"GlobalDefaultAddressSpace\": \"global\"}" w.Write([]byte(addressSpaceResp)) } // Handles queries from GetPoolID func handlePoolIDQuery(w http.ResponseWriter, r *http.Request) { - var requestPoolResp = "{\"PoolID\":\"10.0.0.0/16\", \"Pool\": \"\"}" + requestPoolResp := "{\"PoolID\":\"10.0.0.0/16\", \"Pool\": \"\"}" w.Write([]byte(requestPoolResp)) } // Handles queries from ReserveIPAddress. func handleReserveIPQuery(w http.ResponseWriter, r *http.Request) { - var reserveIPResp = "{\"Address\":\"10.0.0.2/16\"}" + reserveIPResp := "{\"Address\":\"10.0.0.2/16\"}" w.Write([]byte(reserveIPResp)) } @@ -77,23 +75,10 @@ func handleReleaseIPQuery(w http.ResponseWriter, r *http.Request) { // Handles queries from GetIPAddressUtiltization. func handleIPUtilizationQuery(w http.ResponseWriter, r *http.Request) { - var ipUtilizationResp = "{\"Capacity\":10, \"Available\":7, \"UnhealthyAddresses\":[\"10.0.0.5\",\"10.0.0.6\",\"10.0.0.7\"]}" + ipUtilizationResp := "{\"Capacity\":10, \"Available\":7, \"UnhealthyAddresses\":[\"10.0.0.5\",\"10.0.0.6\",\"10.0.0.7\"]}" w.Write([]byte(ipUtilizationResp)) } -// Decodes plugin's responses to test requests. -func decodeResponse(w *httptest.ResponseRecorder, response interface{}) error { - if w.Code != http.StatusOK { - return fmt.Errorf("Request failed with HTTP error %d", w.Code) - } - - if w.Body == nil { - return fmt.Errorf("Response body is empty") - } - - return json.NewDecoder(w.Body).Decode(&response) -} - // Tests IpamClient GetAddressSpace function to get AddressSpaceID. func TestAddressSpaces(t *testing.T) { asID, err := ic.GetAddressSpace() @@ -162,7 +147,6 @@ func TestReserveIP(t *testing.T) { t.Errorf("GetReserveIP with id returned ivnvalid IP1 %s IP2 %s\n", addr1, addr2) return } - } // Tests IpamClient ReleaseIPAddress function to release IP associated with ID. diff --git a/cns/logger/constants.go b/cns/logger/constants.go index 3ece449301..4abb6b22ec 100644 --- a/cns/logger/constants.go +++ b/cns/logger/constants.go @@ -2,10 +2,10 @@ package logger const ( - //Metrics + // Metrics HeartBeatMetricStr = "HeartBeat" - //Dimensions + // Dimensions OrchestratorTypeStr = "OrchestratorType" NodeIDStr = "NodeID" // CNS Snspshot properties diff --git a/cns/networkcontainers/networkcontainers.go b/cns/networkcontainers/networkcontainers.go index 0ac7208684..872349e5d3 100644 --- a/cns/networkcontainers/networkcontainers.go +++ b/cns/networkcontainers/networkcontainers.go @@ -33,8 +33,7 @@ const ( ) // NetworkContainers can be used to perform operations on network containers. -type NetworkContainers struct { -} +type NetworkContainers struct{} // NetPluginConfiguration represent network plugin configuration that is used during CNI ADD/DELETE/UPDATE operation type NetPluginConfiguration struct { diff --git a/cns/networkcontainers/networkcontainers_windows.go b/cns/networkcontainers/networkcontainers_windows.go index 9db81b67a2..77f0c02bf2 100644 --- a/cns/networkcontainers/networkcontainers_windows.go +++ b/cns/networkcontainers/networkcontainers_windows.go @@ -97,7 +97,8 @@ func setWeakHostOnInterface(ipAddress, ncID string) error { ethIndexString := strconv.Itoa(targetIface.Index) - args := []string{"/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), + args := []string{ + "/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), "/index", ethIndexString, "/operation", @@ -105,7 +106,8 @@ func setWeakHostOnInterface(ipAddress, ncID string) error { "/weakhostsend", "true", "/weakhostreceive", - "true"} + "true", + } logger.Printf("[Azure CNS] Going to enable weak host send/receive on interface: %v for NC: %s", args, ncID) c := exec.Command("cmd", args...) @@ -147,7 +149,8 @@ func createOrUpdateWithOperation( ipv4NetStr := fmt.Sprintf("%d.%d.%d.%d", ipv4NetInt[0], ipv4NetInt[1], ipv4NetInt[2], ipv4NetInt[3]) logger.Printf("[Azure CNS] Created netmask in string format %v", ipv4NetStr) - args := []string{"/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), + args := []string{ + "/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), "/name", adapterName, "/operation", @@ -161,7 +164,8 @@ func createOrUpdateWithOperation( "/weakhostsend", "true", "/weakhostreceive", - "true"} + "true", + } c := exec.Command("cmd", args...) @@ -194,11 +198,13 @@ func deleteInterface(interfaceName string) error { return fmt.Errorf("[Azure CNS] Interface name is nil") } - args := []string{"/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), + args := []string{ + "/C", acnBinaryPath, "/logpath", log.GetLogDirectory(), "/name", interfaceName, "/operation", - "DELETE"} + "DELETE", + } c := exec.Command("cmd", args...) @@ -225,7 +231,9 @@ func configureNetworkContainerNetworking(operation, podName, podNamespace, docke IfName: "eth0", Args: [][2]string{ {k8sPodNamespaceStr, podNamespace}, - {k8sPodNameStr, podName}}} + {k8sPodNameStr, podName}, + }, + } logger.Printf("[Azure CNS] run time conf info %+v", cniRtConf) netConfig, err := getNetworkConfig(netPluginConfig.networkConfigPath) diff --git a/cns/nmagentclient/nmagentclient.go b/cns/nmagentclient/nmagentclient.go index 9b2b8f4237..3c95d7c1eb 100644 --- a/cns/nmagentclient/nmagentclient.go +++ b/cns/nmagentclient/nmagentclient.go @@ -15,15 +15,17 @@ import ( ) const ( - //GetNmAgentSupportedApiURLFmt Api endpoint to get supported Apis of NMAgent + // GetNmAgentSupportedApiURLFmt Api endpoint to get supported Apis of NMAgent GetNmAgentSupportedApiURLFmt = "http://%s/machine/plugins/?comp=nmagent&type=GetSupportedApis" GetNetworkContainerVersionURLFmt = "http://%s/machine/plugins/?comp=nmagent&type=NetworkManagement/interfaces/%s/networkContainers/%s/version/authenticationToken/%s/api-version/1" GetNcVersionListWithOutTokenURLFmt = "http://%s/machine/plugins/?comp=nmagent&type=NetworkManagement/interfaces/api-version/%s" ) -//WireServerIP - wire server ip -var WireserverIP = "168.63.129.16" -var getNcVersionListWithOutTokenURLVersion = "2" +// WireServerIP - wire server ip +var ( + WireserverIP = "168.63.129.16" + getNcVersionListWithOutTokenURLVersion = "2" +) // NMANetworkContainerResponse - NMAgent response. type NMANetworkContainerResponse struct { @@ -137,9 +139,7 @@ func GetNetworkContainerVersion( func GetNmAgentSupportedApis( httpc *http.Client, getNmAgentSupportedApisURL string) ([]string, error) { - var ( - returnErr error - ) + var returnErr error if getNmAgentSupportedApisURL == "" { getNmAgentSupportedApisURL = fmt.Sprintf( @@ -206,7 +206,7 @@ func (nmagentclient *NMAgentClient) GetNcVersionListWithOutToken(ncNeedUpdateLis } logger.Printf("NMAgent NC List Response is %s", nmaNcListResponse) - var receivedNcVersionListInMap = make(map[string]string) + receivedNcVersionListInMap := make(map[string]string) for _, containers := range nmaNcListResponse.Containers { receivedNcVersionListInMap[containers.NetworkContainerID] = containers.Version } diff --git a/cns/restserver/internalapi_test.go b/cns/restserver/internalapi_test.go index d68097da6e..a272059d8d 100644 --- a/cns/restserver/internalapi_test.go +++ b/cns/restserver/internalapi_test.go @@ -29,9 +29,7 @@ const ( initPoolSize = 10 ) -var ( - dnsservers = []string{"8.8.8.8", "8.8.4.4"} -) +var dnsservers = []string{"8.8.8.8", "8.8.4.4"} func TestCreateOrUpdateNetworkContainerInternal(t *testing.T) { restartService() diff --git a/cns/routes/routes_linux.go b/cns/routes/routes_linux.go index c4c9681b31..404facdc4d 100644 --- a/cns/routes/routes_linux.go +++ b/cns/routes/routes_linux.go @@ -5,8 +5,6 @@ package routes -const () - func getRoutes() ([]Route, error) { return nil, nil } diff --git a/cns/routes/routes_test.go b/cns/routes/routes_test.go index 9bebd85026..2dac6caac7 100644 --- a/cns/routes/routes_test.go +++ b/cns/routes/routes_test.go @@ -6,10 +6,11 @@ package routes import ( - "github.com/Azure/azure-container-networking/log" "os" "os/exec" "testing" + + "github.com/Azure/azure-container-networking/log" ) const ( @@ -27,8 +28,10 @@ func TestMain(m *testing.M) { } func addTestRoute() error { - arg := []string{"/C", "route", "ADD", testDest, - "MASK", testMask, testGateway, "METRIC", testMetric} + arg := []string{ + "/C", "route", "ADD", testDest, + "MASK", testMask, testGateway, "METRIC", testMetric, + } log.Printf("[Azure CNS] Adding missing route: %v", arg) c := exec.Command("cmd", arg...) @@ -46,8 +49,10 @@ func addTestRoute() error { } func deleteTestRoute() error { - args := []string{"/C", "route", "DELETE", testDest, "MASK", testMask, - testGateway, "METRIC", testMetric} + args := []string{ + "/C", "route", "DELETE", testDest, "MASK", testMask, + testGateway, "METRIC", testMetric, + } log.Printf("[Azure CNS] Deleting route: %v", args) c := exec.Command("cmd", args...) diff --git a/cns/routes/routes_windows.go b/cns/routes/routes_windows.go index 46776b2697..02a8da93a5 100644 --- a/cns/routes/routes_windows.go +++ b/cns/routes/routes_windows.go @@ -152,7 +152,8 @@ func putRoutes(routes []Route) error { for _, route := range routes { exists, err := containsRoute(currentRoutes, route) if err == nil && !exists { - args := []string{"/C", "route", "ADD", + args := []string{ + "/C", "route", "ADD", route.destination, "MASK", route.mask, @@ -160,7 +161,8 @@ func putRoutes(routes []Route) error { "METRIC", route.metric, "IF", - fmt.Sprintf("%d", route.ifaceIndex)} + fmt.Sprintf("%d", route.ifaceIndex), + } logger.Printf("[Azure CNS] Adding missing route: %v", args) c := exec.Command("cmd", args...) diff --git a/cns/service.go b/cns/service.go index 03e07e0097..b9e1555d49 100644 --- a/cns/service.go +++ b/cns/service.go @@ -33,7 +33,6 @@ type Service struct { // NewService creates a new Service object. func NewService(name, version, channelMode string, store store.KeyValueStore) (*Service, error) { service, err := common.NewService(name, version, channelMode, store) - if err != nil { return nil, err } diff --git a/common/args.go b/common/args.go index ef3909d2a0..de9b637fea 100644 --- a/common/args.go +++ b/common/args.go @@ -27,8 +27,10 @@ type Argument struct { // ArgumentList represents a set of command line arguments. type ArgumentList []*Argument -var argList *ArgumentList -var usageFunc func() +var ( + argList *ArgumentList + usageFunc func() +) // ParseArgs parses and validates command line arguments based on rules in the given ArgumentList. func ParseArgs(args *ArgumentList, usage func()) { @@ -133,5 +135,6 @@ func printHelp() { printHelpForArg(&Argument{ Name: "help", Shorthand: "h", - Description: "Print usage information"}) + Description: "Print usage information", + }) } diff --git a/common/plugin.go b/common/plugin.go index cecdbb6614..fc781a04fa 100644 --- a/common/plugin.go +++ b/common/plugin.go @@ -30,8 +30,7 @@ type NetApi interface { } // IPAM internal interface. -type IpamApi interface { -} +type IpamApi interface{} // Plugin common configuration. type PluginConfig struct { diff --git a/common/utils.go b/common/utils.go index d5687e58c4..12d922b968 100644 --- a/common/utils.go +++ b/common/utils.go @@ -77,12 +77,10 @@ type metadataWrapper struct { Metadata Metadata `json:"compute"` } -var ( - // Creating http client object to be reused instead of creating one every time. - // This helps make use of the cached tcp connections. - // Clients are safe for concurrent use by multiple goroutines. - httpClient *http.Client -) +// Creating http client object to be reused instead of creating one every time. +// This helps make use of the cached tcp connections. +// Clients are safe for concurrent use by multiple goroutines. +var httpClient *http.Client // InitHttpClient initializes the httpClient object func InitHttpClient( @@ -150,7 +148,7 @@ func GetInterfaceSubnetWithSpecificIp(ipAddr string) *net.IPNet { } func StartProcess(path string, args []string) error { - var attr = os.ProcAttr{ + attr := os.ProcAttr{ Env: os.Environ(), Files: []*os.File{ os.Stdin, @@ -227,7 +225,7 @@ func SaveHostMetadata(metadata Metadata, fileName string) error { return fmt.Errorf("[Telemetry] marshal data failed with err %+v", err) } - if err = ioutil.WriteFile(fileName, dataBytes, 0644); err != nil { + if err = ioutil.WriteFile(fileName, dataBytes, 0o644); err != nil { log.Printf("[Telemetry] Writing metadata to file failed: %v", err) } diff --git a/ipam/azure.go b/ipam/azure.go index 0a80370feb..67371093a5 100644 --- a/ipam/azure.go +++ b/ipam/azure.go @@ -68,7 +68,6 @@ func (s *azureSource) stop() { // Refreshes configuration. func (s *azureSource) refresh() error { - // Refresh only if enough time has passed since the last query. if time.Since(s.lastRefresh) < s.queryInterval { return nil diff --git a/ipam/azure_test.go b/ipam/azure_test.go index 0553dedca7..8e09b6c71b 100644 --- a/ipam/azure_test.go +++ b/ipam/azure_test.go @@ -17,19 +17,21 @@ import ( "github.com/Azure/azure-container-networking/common" ) -var ipamQueryUrl = "localhost:42424" -var ipamQueryResponse = "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "" +var ( + ipamQueryUrl = "localhost:42424" + ipamQueryResponse = "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" +) // Handles queries from IPAM source. func handleIpamQuery(w http.ResponseWriter, r *http.Request) { @@ -49,166 +51,162 @@ func TestAzure(t *testing.T) { RunSpecs(t, "Azure source Suite") } -var ( - _ = Describe("Test azure source", func() { - - var ( - testAgent *common.Listener - source *azureSource - err error - ) +var _ = Describe("Test azure source", func() { + var ( + testAgent *common.Listener + source *azureSource + err error + ) - BeforeSuite(func() { - // Create a fake local agent to handle requests from IPAM plugin. - u, _ := url.Parse("tcp://" + ipamQueryUrl) - testAgent, err = common.NewListener(u) - Expect(err).NotTo(HaveOccurred()) + BeforeSuite(func() { + // Create a fake local agent to handle requests from IPAM plugin. + u, _ := url.Parse("tcp://" + ipamQueryUrl) + testAgent, err = common.NewListener(u) + Expect(err).NotTo(HaveOccurred()) - testAgent.AddHandler("/", handleIpamQuery) + testAgent.AddHandler("/", handleIpamQuery) - err = testAgent.Start(make(chan error, 1)) - Expect(err).NotTo(HaveOccurred()) - }) + err = testAgent.Start(make(chan error, 1)) + Expect(err).NotTo(HaveOccurred()) + }) - AfterSuite(func() { - // Cleanup. - testAgent.Stop() - }) + AfterSuite(func() { + // Cleanup. + testAgent.Stop() + }) - Describe("Test create Azure source", func() { - - Context("When create new azure source with empty options", func() { - It("Should return as default", func() { - options := make(map[string]interface{}) - source, err = newAzureSource(options) - Expect(err).ShouldNot(HaveOccurred()) - Expect(source.name).Should(Equal("Azure")) - Expect(source.queryUrl).Should(Equal(azureQueryUrl)) - Expect(source.queryInterval).Should(Equal(azureQueryInterval)) - }) + Describe("Test create Azure source", func() { + Context("When create new azure source with empty options", func() { + It("Should return as default", func() { + options := make(map[string]interface{}) + source, err = newAzureSource(options) + Expect(err).ShouldNot(HaveOccurred()) + Expect(source.name).Should(Equal("Azure")) + Expect(source.queryUrl).Should(Equal(azureQueryUrl)) + Expect(source.queryInterval).Should(Equal(azureQueryInterval)) }) + }) - Context("When create new azure source with options", func() { - It("Should return with default queryInterval", func() { - options := make(map[string]interface{}) - second := 7 - queryInterval := time.Duration(second) * time.Second - queryUrl := "http://testqueryurl:12121/test" - options[common.OptIpamQueryInterval] = second - options[common.OptIpamQueryUrl] = queryUrl - source, err = newAzureSource(options) - Expect(err).ShouldNot(HaveOccurred()) - Expect(source.name).Should(Equal("Azure")) - Expect(source.queryUrl).Should(Equal(queryUrl)) - Expect(source.queryInterval).Should(Equal(queryInterval)) - }) + Context("When create new azure source with options", func() { + It("Should return with default queryInterval", func() { + options := make(map[string]interface{}) + second := 7 + queryInterval := time.Duration(second) * time.Second + queryUrl := "http://testqueryurl:12121/test" + options[common.OptIpamQueryInterval] = second + options[common.OptIpamQueryUrl] = queryUrl + source, err = newAzureSource(options) + Expect(err).ShouldNot(HaveOccurred()) + Expect(source.name).Should(Equal("Azure")) + Expect(source.queryUrl).Should(Equal(queryUrl)) + Expect(source.queryInterval).Should(Equal(queryInterval)) }) }) + }) - Describe("Test Azure source refresh", func() { - Context("Create source for testing refresh", func() { - It("Should create successfully", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentAzure - options[common.OptAPIServerURL] = "null" - options[common.OptIpamQueryUrl] = "http://" + ipamQueryUrl - source, err = newAzureSource(options) - Expect(err).ShouldNot(HaveOccurred()) - Expect(source.name).Should(Equal("Azure")) - Expect(source.queryUrl).Should(Equal("http://" + ipamQueryUrl)) - Expect(source.queryInterval).Should(Equal(azureQueryInterval)) - }) + Describe("Test Azure source refresh", func() { + Context("Create source for testing refresh", func() { + It("Should create successfully", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentAzure + options[common.OptAPIServerURL] = "null" + options[common.OptIpamQueryUrl] = "http://" + ipamQueryUrl + source, err = newAzureSource(options) + Expect(err).ShouldNot(HaveOccurred()) + Expect(source.name).Should(Equal("Azure")) + Expect(source.queryUrl).Should(Equal("http://" + ipamQueryUrl)) + Expect(source.queryInterval).Should(Equal(azureQueryInterval)) }) + }) - Context("When refresh interval is too short", func() { - It("Skip refresh and return nil", func() { - source.lastRefresh = time.Now() - source.queryInterval = time.Hour - err = source.refresh() - Expect(err).To(BeNil()) - source.queryInterval = time.Nanosecond - }) + Context("When refresh interval is too short", func() { + It("Skip refresh and return nil", func() { + source.lastRefresh = time.Now() + source.queryInterval = time.Hour + err = source.refresh() + Expect(err).To(BeNil()) + source.queryInterval = time.Nanosecond }) + }) - Context("When newAddressSpace err", func() { - It("Exit with error when refresh", func() { - sink := &addressManagerMock{ - newAddressSpaceSuccess: false, - setAddressSpaceSuccess: true, - } - err = source.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(source.sink).NotTo(BeNil()) - // this is to avoid a race condition that fails this test - //source.queryInterval defaults to 1 nanosecond - // if this test moves fast enough, it will have the refresh method - // return on this check if time.Since(s.lastRefresh) < s.queryInterval - - source.lastRefresh = time.Now().Add(-1 * time.Second) - err = source.refresh() - Expect(err).To(HaveOccurred()) - }) + Context("When newAddressSpace err", func() { + It("Exit with error when refresh", func() { + sink := &addressManagerMock{ + newAddressSpaceSuccess: false, + setAddressSpaceSuccess: true, + } + err = source.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(source.sink).NotTo(BeNil()) + // this is to avoid a race condition that fails this test + // source.queryInterval defaults to 1 nanosecond + // if this test moves fast enough, it will have the refresh method + // return on this check if time.Since(s.lastRefresh) < s.queryInterval + + source.lastRefresh = time.Now().Add(-1 * time.Second) + err = source.refresh() + Expect(err).To(HaveOccurred()) }) + }) - Context("When setAddressSpace err", func() { - It("Exit with error when refresh", func() { - sink := &addressManagerMock{ - newAddressSpaceSuccess: true, - setAddressSpaceSuccess: false, - } - err = source.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(source.sink).NotTo(BeNil()) - - // this is to avoid a race condition that fails this test - //source.queryInterval defaults to 1 nanosecond - // if this test moves fast enough, it will have the refresh method - // return on this check if time.Since(s.lastRefresh) < s.queryInterval - - source.lastRefresh = time.Now().Add(-1 * time.Second) - - err = source.refresh() - Expect(err).To(HaveOccurred()) - }) + Context("When setAddressSpace err", func() { + It("Exit with error when refresh", func() { + sink := &addressManagerMock{ + newAddressSpaceSuccess: true, + setAddressSpaceSuccess: false, + } + err = source.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(source.sink).NotTo(BeNil()) + + // this is to avoid a race condition that fails this test + // source.queryInterval defaults to 1 nanosecond + // if this test moves fast enough, it will have the refresh method + // return on this check if time.Since(s.lastRefresh) < s.queryInterval + + source.lastRefresh = time.Now().Add(-1 * time.Second) + + err = source.refresh() + Expect(err).To(HaveOccurred()) }) + }) - Context("When create new azure source with options", func() { - It("Should return with default queryInterval", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentAzure - options[common.OptAPIServerURL] = "null" - options[common.OptIpamQueryUrl] = "http://" + ipamQueryUrl + Context("When create new azure source with options", func() { + It("Should return with default queryInterval", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentAzure + options[common.OptAPIServerURL] = "null" + options[common.OptIpamQueryUrl] = "http://" + ipamQueryUrl - am, err := createAddressManager(options) - Expect(err).ToNot(HaveOccurred()) + am, err := createAddressManager(options) + Expect(err).ToNot(HaveOccurred()) - amImpl := am.(*addressManager) + amImpl := am.(*addressManager) - err = amImpl.source.refresh() - Expect(err).ToNot(HaveOccurred()) + err = amImpl.source.refresh() + Expect(err).ToNot(HaveOccurred()) - as, ok := amImpl.AddrSpaces["local"] - Expect(ok).To(BeTrue()) + as, ok := amImpl.AddrSpaces["local"] + Expect(ok).To(BeTrue()) - pool, ok := as.Pools["10.0.0.0/16"] - Expect(ok).To(BeTrue()) + pool, ok := as.Pools["10.0.0.0/16"] + Expect(ok).To(BeTrue()) - _, ok = pool.Addresses["10.0.0.4"] - Expect(ok).NotTo(BeTrue()) + _, ok = pool.Addresses["10.0.0.4"] + Expect(ok).NotTo(BeTrue()) - _, ok = pool.Addresses["10.0.0.5"] - Expect(ok).To(BeTrue()) + _, ok = pool.Addresses["10.0.0.5"] + Expect(ok).To(BeTrue()) - _, ok = pool.Addresses["10.1.0.4"] - Expect(ok).NotTo(BeTrue()) + _, ok = pool.Addresses["10.1.0.4"] + Expect(ok).NotTo(BeTrue()) - pool, ok = as.Pools["10.1.0.0/16"] - Expect(ok).To(BeTrue()) + pool, ok = as.Pools["10.1.0.0/16"] + Expect(ok).To(BeTrue()) - _, ok = pool.Addresses["10.1.0.4"] - Expect(ok).To(BeTrue()) - }) + _, ok = pool.Addresses["10.1.0.4"] + Expect(ok).To(BeTrue()) }) }) }) -) +}) diff --git a/ipam/fileIpam.go b/ipam/fileIpam.go index 358e9c8133..216460c911 100644 --- a/ipam/fileIpam.go +++ b/ipam/fileIpam.go @@ -137,7 +137,7 @@ func getSDNInterfaces(fileLocation string) (*NetworkInterfaces, error) { } func populateAddressSpace(localAddressSpace *addressSpace, sdnInterfaces *NetworkInterfaces, localInterfaces []net.Interface) error { - //Find the interface with matching MacAddress or Name + // Find the interface with matching MacAddress or Name for _, sdnIf := range sdnInterfaces.Interfaces { ifName := "" diff --git a/ipam/fileIpam_test.go b/ipam/fileIpam_test.go index f449935efb..87f960c9d7 100644 --- a/ipam/fileIpam_test.go +++ b/ipam/fileIpam_test.go @@ -5,13 +5,14 @@ package ipam import ( "errors" - "github.com/Azure/azure-container-networking/common" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" "net" "reflect" "runtime" "testing" + + "github.com/Azure/azure-container-networking/common" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" ) func TestFileIpam(t *testing.T) { @@ -42,326 +43,322 @@ func (sink *addressManagerMock) setAddressSpace(*addressSpace) error { return errors.New("setAddressSpace fail") } -const validFileName = "testfiles/masInterfaceConfig.json" -const invalidFileName = "mas_test.go" -const nonexistentFileName = "bad" - -var ( - _ = Describe("Test MAS", func() { - - var ( - mas *fileIpamSource - err error - ) - - Describe("Test masSource", func() { - Context("Create MAS with empty options", func() { - It("Should return as default", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentFileIpam - mas, err = newFileIpamSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(mas.name).Should(Equal("fileIpam")) - if runtime.GOOS == windows { - Expect(mas.filePath).Should(Equal(defaultWindowsFilePath)) - } else { - Expect(mas.filePath).Should(Equal(defaultLinuxFilePath)) - } - }) +const ( + validFileName = "testfiles/masInterfaceConfig.json" + invalidFileName = "mas_test.go" + nonexistentFileName = "bad" +) + +var _ = Describe("Test MAS", func() { + var ( + mas *fileIpamSource + err error + ) + + Describe("Test masSource", func() { + Context("Create MAS with empty options", func() { + It("Should return as default", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentFileIpam + mas, err = newFileIpamSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(mas.name).Should(Equal("fileIpam")) + if runtime.GOOS == windows { + Expect(mas.filePath).Should(Equal(defaultWindowsFilePath)) + } else { + Expect(mas.filePath).Should(Equal(defaultLinuxFilePath)) + } }) + }) - Context("Create MAS with empty options", func() { - It("Should return as default", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentMAS - mas, err = newFileIpamSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(mas.name).Should(Equal("mas")) - if runtime.GOOS == windows { - Expect(mas.filePath).Should(Equal(defaultWindowsFilePath)) - } else { - Expect(mas.filePath).Should(Equal(defaultLinuxFilePath)) - } - mas.filePath = validFileName - }) + Context("Create MAS with empty options", func() { + It("Should return as default", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentMAS + mas, err = newFileIpamSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(mas.name).Should(Equal("mas")) + if runtime.GOOS == windows { + Expect(mas.filePath).Should(Equal(defaultWindowsFilePath)) + } else { + Expect(mas.filePath).Should(Equal(defaultLinuxFilePath)) + } + mas.filePath = validFileName }) + }) - Context("When fileLoaded", func() { - It("refresh return with nil", func() { - mas.fileLoaded = true - err = mas.refresh() - Expect(err).To(BeNil()) - mas.fileLoaded = false - }) + Context("When fileLoaded", func() { + It("refresh return with nil", func() { + mas.fileLoaded = true + err = mas.refresh() + Expect(err).To(BeNil()) + mas.fileLoaded = false }) + }) - Context("When getSDNInterfaces error", func() { - It("Error when refresh", func() { - filePath := mas.filePath - mas.filePath = invalidFileName - err = mas.refresh() - Expect(err).To(HaveOccurred()) - mas.filePath = filePath - }) + Context("When getSDNInterfaces error", func() { + It("Error when refresh", func() { + filePath := mas.filePath + mas.filePath = invalidFileName + err = mas.refresh() + Expect(err).To(HaveOccurred()) + mas.filePath = filePath }) + }) - Context("When newAddressSpace err", func() { - It("Exit with error when refresh", func() { - sink := &addressManagerMock{false, true} - err = mas.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(mas.sink).NotTo(BeNil()) - err = mas.refresh() - Expect(err).To(HaveOccurred()) - }) + Context("When newAddressSpace err", func() { + It("Exit with error when refresh", func() { + sink := &addressManagerMock{false, true} + err = mas.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(mas.sink).NotTo(BeNil()) + err = mas.refresh() + Expect(err).To(HaveOccurred()) }) + }) - Context("When setAddressSpace err", func() { - It("Exit with error when refresh", func() { - sink := &addressManagerMock{true, false} - err = mas.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(mas.sink).NotTo(BeNil()) - err = mas.refresh() - Expect(err).To(HaveOccurred()) - }) + Context("When setAddressSpace err", func() { + It("Exit with error when refresh", func() { + sink := &addressManagerMock{true, false} + err = mas.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(mas.sink).NotTo(BeNil()) + err = mas.refresh() + Expect(err).To(HaveOccurred()) }) + }) - Context("With no error", func() { - It("refresh successfully", func() { - sink := &addressManagerMock{true, true} - err = mas.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(mas.sink).NotTo(BeNil()) - err = mas.refresh() - Expect(err).NotTo(HaveOccurred()) - mas.stop() - Expect(mas.sink).To(BeNil()) - }) + Context("With no error", func() { + It("refresh successfully", func() { + sink := &addressManagerMock{true, true} + err = mas.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(mas.sink).NotTo(BeNil()) + err = mas.refresh() + Expect(err).NotTo(HaveOccurred()) + mas.stop() + Expect(mas.sink).To(BeNil()) }) }) + }) - Describe("Test GetSDNInterfaces", func() { - Context("GetSDNInterfaces on interfaces", func() { - It("interfaces should be equaled", func() { - - interfaces, err := getSDNInterfaces(validFileName) - Expect(err).ShouldNot(HaveOccurred()) - - correctInterfaces := &NetworkInterfaces{ - Interfaces: []Interface{ - { - MacAddress: "000D3A6E1825", - IsPrimary: true, - IPSubnets: []IPSubnet{ - { - Prefix: "1.0.0.0/12", - IPAddresses: []IPAddress{ - {Address: "1.0.0.4", IsPrimary: true}, - {Address: "1.0.0.5", IsPrimary: false}, - {Address: "1.0.0.6", IsPrimary: false}, - {Address: "1.0.0.7", IsPrimary: false}, - }, + Describe("Test GetSDNInterfaces", func() { + Context("GetSDNInterfaces on interfaces", func() { + It("interfaces should be equaled", func() { + interfaces, err := getSDNInterfaces(validFileName) + Expect(err).ShouldNot(HaveOccurred()) + + correctInterfaces := &NetworkInterfaces{ + Interfaces: []Interface{ + { + MacAddress: "000D3A6E1825", + IsPrimary: true, + IPSubnets: []IPSubnet{ + { + Prefix: "1.0.0.0/12", + IPAddresses: []IPAddress{ + {Address: "1.0.0.4", IsPrimary: true}, + {Address: "1.0.0.5", IsPrimary: false}, + {Address: "1.0.0.6", IsPrimary: false}, + {Address: "1.0.0.7", IsPrimary: false}, }, }, }, }, - } + }, + } - equal := reflect.DeepEqual(interfaces, correctInterfaces) - Expect(equal).To(BeTrue()) - }) + equal := reflect.DeepEqual(interfaces, correctInterfaces) + Expect(equal).To(BeTrue()) }) + }) - Context("GetSDNInterfaces on invalid filename", func() { - It("Should throw error on invalid filename", func() { - interfaces, err := getSDNInterfaces(invalidFileName) - if interfaces != nil { - Expect(err).To(HaveOccurred()) - } - }) + Context("GetSDNInterfaces on invalid filename", func() { + It("Should throw error on invalid filename", func() { + interfaces, err := getSDNInterfaces(invalidFileName) + if interfaces != nil { + Expect(err).To(HaveOccurred()) + } }) + }) - Context("GetSDNInterfaces on nonexistent fileName", func() { - It("Should throw error on nonexistent filename", func() { - interfaces, err := getSDNInterfaces(nonexistentFileName) - if interfaces != nil { - Expect(err).To(HaveOccurred()) - } - }) + Context("GetSDNInterfaces on nonexistent fileName", func() { + It("Should throw error on nonexistent filename", func() { + interfaces, err := getSDNInterfaces(nonexistentFileName) + if interfaces != nil { + Expect(err).To(HaveOccurred()) + } }) }) + }) - Describe("Test PopulateAddressSpace", func() { - Context("Simple interface", func() { - It("Simple interface should run successfully", func() { - - hardwareAddress0, _ := net.ParseMAC("00:00:00:00:00:00") - hardwareAddress1, _ := net.ParseMAC("11:11:11:11:11:11") - hardwareAddress2, _ := net.ParseMAC("00:0d:3a:6e:18:25") - - localInterfaces := []net.Interface{ - {HardwareAddr: hardwareAddress0, Name: "eth0"}, - {HardwareAddr: hardwareAddress1, Name: "eth1"}, - {HardwareAddr: hardwareAddress2, Name: "eth2"}, - } - - local := &addressSpace{ - Id: LocalDefaultAddressSpaceId, - Scope: LocalScope, - Pools: make(map[string]*addressPool), - } - - sdnInterfaces := &NetworkInterfaces{ - Interfaces: []Interface{ - { - MacAddress: "000D3A6E1825", - IsPrimary: true, - IPSubnets: []IPSubnet{ - { - Prefix: "1.0.0.0/12", - IPAddresses: []IPAddress{ - {Address: "1.1.1.5", IsPrimary: true}, - {Address: "1.1.1.6", IsPrimary: false}, - {Address: "1.1.1.6", IsPrimary: false}, - {Address: "1.1.1.7", IsPrimary: false}, - {Address: "invalid", IsPrimary: false}, - }, + Describe("Test PopulateAddressSpace", func() { + Context("Simple interface", func() { + It("Simple interface should run successfully", func() { + hardwareAddress0, _ := net.ParseMAC("00:00:00:00:00:00") + hardwareAddress1, _ := net.ParseMAC("11:11:11:11:11:11") + hardwareAddress2, _ := net.ParseMAC("00:0d:3a:6e:18:25") + + localInterfaces := []net.Interface{ + {HardwareAddr: hardwareAddress0, Name: "eth0"}, + {HardwareAddr: hardwareAddress1, Name: "eth1"}, + {HardwareAddr: hardwareAddress2, Name: "eth2"}, + } + + local := &addressSpace{ + Id: LocalDefaultAddressSpaceId, + Scope: LocalScope, + Pools: make(map[string]*addressPool), + } + + sdnInterfaces := &NetworkInterfaces{ + Interfaces: []Interface{ + { + MacAddress: "000D3A6E1825", + IsPrimary: true, + IPSubnets: []IPSubnet{ + { + Prefix: "1.0.0.0/12", + IPAddresses: []IPAddress{ + {Address: "1.1.1.5", IsPrimary: true}, + {Address: "1.1.1.6", IsPrimary: false}, + {Address: "1.1.1.6", IsPrimary: false}, + {Address: "1.1.1.7", IsPrimary: false}, + {Address: "invalid", IsPrimary: false}, }, }, }, }, - } + }, + } - err := populateAddressSpace(local, sdnInterfaces, localInterfaces) - Expect(err).ToNot(HaveOccurred()) + err := populateAddressSpace(local, sdnInterfaces, localInterfaces) + Expect(err).ToNot(HaveOccurred()) - Expect(len(local.Pools)).To(Equal(1)) + Expect(len(local.Pools)).To(Equal(1)) - pool, ok := local.Pools["1.0.0.0/12"] - Expect(ok).To(BeTrue()) + pool, ok := local.Pools["1.0.0.0/12"] + Expect(ok).To(BeTrue()) - Expect(pool.IfName).To(Equal("eth2")) - Expect(pool.Priority).To(Equal(0)) - Expect(len(pool.Addresses)).To(Equal(2)) + Expect(pool.IfName).To(Equal("eth2")) + Expect(pool.Priority).To(Equal(0)) + Expect(len(pool.Addresses)).To(Equal(2)) - _, ok = pool.Addresses["1.1.1.6"] - Expect(ok).To(BeTrue()) + _, ok = pool.Addresses["1.1.1.6"] + Expect(ok).To(BeTrue()) - _, ok = pool.Addresses["1.1.1.7"] - Expect(ok).To(BeTrue()) - }) + _, ok = pool.Addresses["1.1.1.7"] + Expect(ok).To(BeTrue()) }) + }) - Context("Multiple interface", func() { - It("Multiple interface should run successfully", func() { - - hardwareAddress0, _ := net.ParseMAC("00:00:00:00:00:00") - hardwareAddress1, _ := net.ParseMAC("11:11:11:11:11:11") - localInterfaces := []net.Interface{ - {HardwareAddr: hardwareAddress0, Name: "eth0"}, - {HardwareAddr: hardwareAddress1, Name: "eth1"}, - } - - local := &addressSpace{ - Id: LocalDefaultAddressSpaceId, - Scope: LocalScope, - Pools: make(map[string]*addressPool), - } - - sdnInterfaces := &NetworkInterfaces{ - Interfaces: []Interface{ - { - MacAddress: "000000000000", - IsPrimary: true, - IPSubnets: []IPSubnet{ - { - Prefix: "0.0.0.0/24", - IPAddresses: []IPAddress{}, - }, - { - Prefix: "0.1.0.0/24", - IPAddresses: []IPAddress{}, - }, - { - Prefix: "0.0.0.0/24", - }, - { - Prefix: "invalid", - }, + Context("Multiple interface", func() { + It("Multiple interface should run successfully", func() { + hardwareAddress0, _ := net.ParseMAC("00:00:00:00:00:00") + hardwareAddress1, _ := net.ParseMAC("11:11:11:11:11:11") + localInterfaces := []net.Interface{ + {HardwareAddr: hardwareAddress0, Name: "eth0"}, + {HardwareAddr: hardwareAddress1, Name: "eth1"}, + } + + local := &addressSpace{ + Id: LocalDefaultAddressSpaceId, + Scope: LocalScope, + Pools: make(map[string]*addressPool), + } + + sdnInterfaces := &NetworkInterfaces{ + Interfaces: []Interface{ + { + MacAddress: "000000000000", + IsPrimary: true, + IPSubnets: []IPSubnet{ + { + Prefix: "0.0.0.0/24", + IPAddresses: []IPAddress{}, }, - }, - { - MacAddress: "111111111111", - IsPrimary: false, - IPSubnets: []IPSubnet{ - { - Prefix: "1.0.0.0/24", - IPAddresses: []IPAddress{}, - }, - { - Prefix: "1.1.0.0/24", - IPAddresses: []IPAddress{}, - }, + { + Prefix: "0.1.0.0/24", + IPAddresses: []IPAddress{}, + }, + { + Prefix: "0.0.0.0/24", + }, + { + Prefix: "invalid", }, }, - { - MacAddress: "222222222222", - IsPrimary: false, - IPSubnets: []IPSubnet{}, + }, + { + MacAddress: "111111111111", + IsPrimary: false, + IPSubnets: []IPSubnet{ + { + Prefix: "1.0.0.0/24", + IPAddresses: []IPAddress{}, + }, + { + Prefix: "1.1.0.0/24", + IPAddresses: []IPAddress{}, + }, }, }, - } + { + MacAddress: "222222222222", + IsPrimary: false, + IPSubnets: []IPSubnet{}, + }, + }, + } - err := populateAddressSpace(local, sdnInterfaces, localInterfaces) - Expect(err).ToNot(HaveOccurred()) + err := populateAddressSpace(local, sdnInterfaces, localInterfaces) + Expect(err).ToNot(HaveOccurred()) - Expect(len(local.Pools)).To(Equal(4)) + Expect(len(local.Pools)).To(Equal(4)) - pool, ok := local.Pools["0.0.0.0/24"] - Expect(ok).To(BeTrue()) - Expect(pool.IfName).To(Equal("eth0")) - Expect(pool.Priority).To(Equal(0)) + pool, ok := local.Pools["0.0.0.0/24"] + Expect(ok).To(BeTrue()) + Expect(pool.IfName).To(Equal("eth0")) + Expect(pool.Priority).To(Equal(0)) - pool, ok = local.Pools["0.1.0.0/24"] - Expect(ok).To(BeTrue()) - Expect(pool.IfName).To(Equal("eth0")) - Expect(pool.Priority).To(Equal(0)) + pool, ok = local.Pools["0.1.0.0/24"] + Expect(ok).To(BeTrue()) + Expect(pool.IfName).To(Equal("eth0")) + Expect(pool.Priority).To(Equal(0)) - pool, ok = local.Pools["1.0.0.0/24"] - Expect(ok).To(BeTrue()) - Expect(pool.IfName).To(Equal("eth1")) - Expect(pool.Priority).To(Equal(1)) + pool, ok = local.Pools["1.0.0.0/24"] + Expect(ok).To(BeTrue()) + Expect(pool.IfName).To(Equal("eth1")) + Expect(pool.Priority).To(Equal(1)) - pool, ok = local.Pools["1.1.0.0/24"] - Expect(ok).To(BeTrue()) - Expect(pool.IfName).To(Equal("eth1")) - Expect(pool.Priority).To(Equal(1)) - }) + pool, ok = local.Pools["1.1.0.0/24"] + Expect(ok).To(BeTrue()) + Expect(pool.IfName).To(Equal("eth1")) + Expect(pool.Priority).To(Equal(1)) }) }) + }) - Describe("Test macAddressesEqual", func() { - var equal bool - macAddress := "abc" - macAddressCorrect := "A:b:C" - macAddressIncorrect := "a:B:d" - Context("When equal", func() { - It("return true", func() { - equal = macAddressesEqual(macAddress, macAddressCorrect) - Expect(equal).To(BeTrue()) - equal = macAddressesEqual(macAddressCorrect, macAddress) - Expect(equal).To(BeTrue()) - }) + Describe("Test macAddressesEqual", func() { + var equal bool + macAddress := "abc" + macAddressCorrect := "A:b:C" + macAddressIncorrect := "a:B:d" + Context("When equal", func() { + It("return true", func() { + equal = macAddressesEqual(macAddress, macAddressCorrect) + Expect(equal).To(BeTrue()) + equal = macAddressesEqual(macAddressCorrect, macAddress) + Expect(equal).To(BeTrue()) }) - Context("When not equal", func() { - It("return false", func() { - equal = macAddressesEqual(macAddress, macAddressIncorrect) - Expect(equal).To(BeFalse()) - equal = macAddressesEqual(macAddressIncorrect, macAddress) - Expect(equal).To(BeFalse()) - }) + }) + Context("When not equal", func() { + It("return false", func() { + equal = macAddressesEqual(macAddress, macAddressIncorrect) + Expect(equal).To(BeFalse()) + equal = macAddressesEqual(macAddressIncorrect, macAddress) + Expect(equal).To(BeFalse()) }) }) }) -) +}) diff --git a/ipam/ipv6Ipam_test.go b/ipam/ipv6Ipam_test.go index aada3d9f36..20cbd663de 100644 --- a/ipam/ipv6Ipam_test.go +++ b/ipam/ipv6Ipam_test.go @@ -45,104 +45,99 @@ func TestIpv6Ipam(t *testing.T) { RunSpecs(t, "Ipv6Ipam Suite") } -var ( - _ = Describe("Test ipv6Ipam", func() { - - Describe("Test newIPv6IpamSource", func() { - - Context("When creating with current environment", func() { - It("Should create successfully", func() { - name := common.OptEnvironmentIPv6NodeIpam - options := map[string]interface{}{} - options[common.OptEnvironment] = name - kubeConfigPath := defaultLinuxKubeConfigFilePath - if runtime.GOOS == windows { - kubeConfigPath = defaultWindowsKubeConfigFilePath - } - isLoaded := true - ipv6IpamSource, err := newIPv6IpamSource(options, isLoaded) - Expect(err).NotTo(HaveOccurred()) - Expect(ipv6IpamSource.name).To(Equal(name)) - Expect(ipv6IpamSource.kubeConfigPath).To(Equal(kubeConfigPath)) - Expect(ipv6IpamSource.isLoaded).To(Equal(isLoaded)) - }) +var _ = Describe("Test ipv6Ipam", func() { + Describe("Test newIPv6IpamSource", func() { + Context("When creating with current environment", func() { + It("Should create successfully", func() { + name := common.OptEnvironmentIPv6NodeIpam + options := map[string]interface{}{} + options[common.OptEnvironment] = name + kubeConfigPath := defaultLinuxKubeConfigFilePath + if runtime.GOOS == windows { + kubeConfigPath = defaultWindowsKubeConfigFilePath + } + isLoaded := true + ipv6IpamSource, err := newIPv6IpamSource(options, isLoaded) + Expect(err).NotTo(HaveOccurred()) + Expect(ipv6IpamSource.name).To(Equal(name)) + Expect(ipv6IpamSource.kubeConfigPath).To(Equal(kubeConfigPath)) + Expect(ipv6IpamSource.isLoaded).To(Equal(isLoaded)) }) }) + }) - Describe("Test start and stop", func() { - - source := &ipv6IpamSource{} + Describe("Test start and stop", func() { + source := &ipv6IpamSource{} - Context("Start the source with sink", func() { - It("Should set the sink of source", func() { - sink := &addressManagerMock{} - err := source.start(sink) - Expect(err).NotTo(HaveOccurred()) - Expect(source.sink).NotTo(BeNil()) - }) + Context("Start the source with sink", func() { + It("Should set the sink of source", func() { + sink := &addressManagerMock{} + err := source.start(sink) + Expect(err).NotTo(HaveOccurred()) + Expect(source.sink).NotTo(BeNil()) }) + }) - Context("Stop the source", func() { - It("Should remove the sink of source", func() { - source.stop() - Expect(source.sink).To(BeNil()) - }) + Context("Stop the source", func() { + It("Should remove the sink of source", func() { + source.stop() + Expect(source.sink).To(BeNil()) }) }) + }) - Describe("TestIPv6Ipam", func() { - Context("When node have IPv6 subnet", func() { - It("Carve addresses successfully and Network interface match", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentIPv6NodeIpam - - client := newKubernetesTestClient() - node, _ := client.CoreV1().Nodes().Get(context.TODO(), testNodeName, metav1.GetOptions{}) - - testInterfaces, err := retrieveKubernetesPodIPs(node, testSubnetSize) - Expect(err).NotTo(HaveOccurred()) - - correctInterfaces := &NetworkInterfaces{ - Interfaces: []Interface{ - { - IsPrimary: true, - IPSubnets: []IPSubnet{ - { - Prefix: "ace:cab:deca:deed::/126", - IPAddresses: []IPAddress{ - {Address: "ace:cab:deca:deed::2", IsPrimary: false}, - {Address: "ace:cab:deca:deed::3", IsPrimary: false}, - }, + Describe("TestIPv6Ipam", func() { + Context("When node have IPv6 subnet", func() { + It("Carve addresses successfully and Network interface match", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentIPv6NodeIpam + + client := newKubernetesTestClient() + node, _ := client.CoreV1().Nodes().Get(context.TODO(), testNodeName, metav1.GetOptions{}) + + testInterfaces, err := retrieveKubernetesPodIPs(node, testSubnetSize) + Expect(err).NotTo(HaveOccurred()) + + correctInterfaces := &NetworkInterfaces{ + Interfaces: []Interface{ + { + IsPrimary: true, + IPSubnets: []IPSubnet{ + { + Prefix: "ace:cab:deca:deed::/126", + IPAddresses: []IPAddress{ + {Address: "ace:cab:deca:deed::2", IsPrimary: false}, + {Address: "ace:cab:deca:deed::3", IsPrimary: false}, }, }, }, }, - } + }, + } - equal := reflect.DeepEqual(testInterfaces, correctInterfaces) - Expect(equal).To(BeTrue()) - }) + equal := reflect.DeepEqual(testInterfaces, correctInterfaces) + Expect(equal).To(BeTrue()) }) + }) - Context("When node doesn't have IPv6 subnet", func() { - It("Should fail to retrieve the IPv6 address", func() { - options := make(map[string]interface{}) - options[common.OptEnvironment] = common.OptEnvironmentIPv6NodeIpam - - testnode := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: testNodeName, - }, - Spec: v1.NodeSpec{ - PodCIDR: "10.0.0.1/24", - PodCIDRs: []string{"10.0.0.1/24"}, - }, - } - - _, err := retrieveKubernetesPodIPs(testnode, testSubnetSize) - Expect(err).To(HaveOccurred()) - }) + Context("When node doesn't have IPv6 subnet", func() { + It("Should fail to retrieve the IPv6 address", func() { + options := make(map[string]interface{}) + options[common.OptEnvironment] = common.OptEnvironmentIPv6NodeIpam + + testnode := &v1.Node{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNodeName, + }, + Spec: v1.NodeSpec{ + PodCIDR: "10.0.0.1/24", + PodCIDRs: []string{"10.0.0.1/24"}, + }, + } + + _, err := retrieveKubernetesPodIPs(testnode, testSubnetSize) + Expect(err).To(HaveOccurred()) }) }) }) -) +}) diff --git a/ipam/manager_ipv6Ipam_test.go b/ipam/manager_ipv6Ipam_test.go index b014cfb638..14d56a2cc5 100644 --- a/ipam/manager_ipv6Ipam_test.go +++ b/ipam/manager_ipv6Ipam_test.go @@ -48,74 +48,69 @@ func createTestIpv6AddressManager() (AddressManager, error) { return am, nil } -var ( - _ = Describe("Test manager ipv6Ipam", func() { - - Describe("Test IPv6 get address pool and address", func() { - - var ( - am AddressManager - err error - poolID1 string - subnet1 string - address2 string - address3 string - ) - - Context("Start with the test address space", func() { - It("Should create AddressManager successfully", func() { - am, err = createTestIpv6AddressManager() - Expect(err).NotTo(HaveOccurred()) - }) +var _ = Describe("Test manager ipv6Ipam", func() { + Describe("Test IPv6 get address pool and address", func() { + var ( + am AddressManager + err error + poolID1 string + subnet1 string + address2 string + address3 string + ) + + Context("Start with the test address space", func() { + It("Should create AddressManager successfully", func() { + am, err = createTestIpv6AddressManager() + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When test if the address spaces are returned correctly", func() { - It("GetDefaultAddressSpaces returned valid local address space", func() { - local, _ := am.GetDefaultAddressSpaces() - Expect(local).To(Equal(LocalDefaultAddressSpaceId)) - }) + Context("When test if the address spaces are returned correctly", func() { + It("GetDefaultAddressSpaces returned valid local address space", func() { + local, _ := am.GetDefaultAddressSpaces() + Expect(local).To(Equal(LocalDefaultAddressSpaceId)) }) + }) - Context("When request two separate address pools", func() { - It("Should request pool successfully and return subnet matched ipv6subnet1", func() { - poolID1, subnet1, err = am.RequestPool(LocalDefaultAddressSpaceId, "", "", nil, true) - Expect(err).NotTo(HaveOccurred()) - Expect(subnet1).To(Equal(ipv6subnet1)) - - }) + Context("When request two separate address pools", func() { + It("Should request pool successfully and return subnet matched ipv6subnet1", func() { + poolID1, subnet1, err = am.RequestPool(LocalDefaultAddressSpaceId, "", "", nil, true) + Expect(err).NotTo(HaveOccurred()) + Expect(subnet1).To(Equal(ipv6subnet1)) }) + }) - Context("When test with a specified address", func() { - It("Should request address successfully", func() { - address2, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, ipv6addr2, nil) - Expect(err).NotTo(HaveOccurred()) - Expect(address2).To(Equal(ipv6addr2 + testSubnetSize)) - }) + Context("When test with a specified address", func() { + It("Should request address successfully", func() { + address2, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, ipv6addr2, nil) + Expect(err).NotTo(HaveOccurred()) + Expect(address2).To(Equal(ipv6addr2 + testSubnetSize)) }) + }) - Context("When test without requesting address explicitly", func() { - It("Should request address successfully", func() { - address3, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, "", nil) - Expect(err).NotTo(HaveOccurred()) - Expect(address3).To(Equal(ipv6addr3 + testSubnetSize)) - }) + Context("When test without requesting address explicitly", func() { + It("Should request address successfully", func() { + address3, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, "", nil) + Expect(err).NotTo(HaveOccurred()) + Expect(address3).To(Equal(ipv6addr3 + testSubnetSize)) }) + }) - Context("When release address2", func() { - It("Should release successfully", func() { - err = am.ReleaseAddress(LocalDefaultAddressSpaceId, poolID1, address2, nil) - Expect(err).NotTo(HaveOccurred()) - }) + Context("When release address2", func() { + It("Should release successfully", func() { + err = am.ReleaseAddress(LocalDefaultAddressSpaceId, poolID1, address2, nil) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When release address3 and the pool", func() { - It("Should release successfully", func() { - err = am.ReleaseAddress(LocalDefaultAddressSpaceId, poolID1, address3, nil) - Expect(err).NotTo(HaveOccurred()) - err = am.ReleasePool(LocalDefaultAddressSpaceId, poolID1) - Expect(err).NotTo(HaveOccurred()) - }) + Context("When release address3 and the pool", func() { + It("Should release successfully", func() { + err = am.ReleaseAddress(LocalDefaultAddressSpaceId, poolID1, address3, nil) + Expect(err).NotTo(HaveOccurred()) + err = am.ReleasePool(LocalDefaultAddressSpaceId, poolID1) + Expect(err).NotTo(HaveOccurred()) }) }) }) -) +}) diff --git a/ipam/manager_test.go b/ipam/manager_test.go index 879a7180a1..46266e7a25 100644 --- a/ipam/manager_test.go +++ b/ipam/manager_test.go @@ -77,8 +77,8 @@ func dumpAddressManager(am AddressManager) { // setupTestAddressSpace creates a simple address space used by various tests. func setupTestAddressSpace(am AddressManager) error { - var anyInterface = "any" - var anyPriority = 42 + anyInterface := "any" + anyPriority := 42 amImpl := am.(*addressManager) @@ -151,242 +151,239 @@ func TestManager(t *testing.T) { RunSpecs(t, "Manager Suite") } -var ( - _ = Describe("Test Manager", func() { - - Describe("Test Initialize", func() { - Context("When store is nil", func() { - It("Initialize return nil", func() { - var config common.PluginConfig - config.Store = nil - options := map[string]interface{}{} - options[common.OptEnvironment] = "" - am, err := NewAddressManager() - Expect(am).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - err = am.Initialize(&config, false,options) - Expect(err).To(BeNil()) - }) +var _ = Describe("Test Manager", func() { + Describe("Test Initialize", func() { + Context("When store is nil", func() { + It("Initialize return nil", func() { + var config common.PluginConfig + config.Store = nil + options := map[string]interface{}{} + options[common.OptEnvironment] = "" + am, err := NewAddressManager() + Expect(am).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + err = am.Initialize(&config, false, options) + Expect(err).To(BeNil()) }) + }) - Context("When restore key not found", func() { - It("Initialize return nil", func() { - var config common.PluginConfig - storeMock := &testutils.KeyValueStoreMock{} - storeMock.ReadError = store.ErrKeyNotFound - config.Store = storeMock - options := map[string]interface{}{} - options[common.OptEnvironment] = "" - am, err := NewAddressManager() - Expect(am).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - err = am.Initialize(&config, false,options) - Expect(err).To(BeNil()) - }) + Context("When restore key not found", func() { + It("Initialize return nil", func() { + var config common.PluginConfig + storeMock := &testutils.KeyValueStoreMock{} + storeMock.ReadError = store.ErrKeyNotFound + config.Store = storeMock + options := map[string]interface{}{} + options[common.OptEnvironment] = "" + am, err := NewAddressManager() + Expect(am).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + err = am.Initialize(&config, false, options) + Expect(err).To(BeNil()) }) + }) - Context("When restore return error", func() { - It("Initialize return error", func() { - var config common.PluginConfig - storeMock := &testutils.KeyValueStoreMock{} - storeMock.ReadError = errors.New("Error") - config.Store = storeMock - options := map[string]interface{}{} - options[common.OptEnvironment] = "" - am, err := NewAddressManager() - Expect(am).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - err = am.Initialize(&config, false, options) - Expect(err).To(HaveOccurred()) - }) + Context("When restore return error", func() { + It("Initialize return error", func() { + var config common.PluginConfig + storeMock := &testutils.KeyValueStoreMock{} + storeMock.ReadError = errors.New("Error") + config.Store = storeMock + options := map[string]interface{}{} + options[common.OptEnvironment] = "" + am, err := NewAddressManager() + Expect(am).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + err = am.Initialize(&config, false, options) + Expect(err).To(HaveOccurred()) }) + }) - Context("When StartSource fail", func() { - It("Initialize return error", func() { - var config common.PluginConfig - options := map[string]interface{}{} - options[common.OptEnvironment] = "Invalid" - am, err := NewAddressManager() - Expect(am).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - err = am.Initialize(&config, false,options) - Expect(err).To(HaveOccurred()) - }) + Context("When StartSource fail", func() { + It("Initialize return error", func() { + var config common.PluginConfig + options := map[string]interface{}{} + options[common.OptEnvironment] = "Invalid" + am, err := NewAddressManager() + Expect(am).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + err = am.Initialize(&config, false, options) + Expect(err).To(HaveOccurred()) }) }) + }) - Describe("Test restore", func() { - Context("When store is nil", func() { - It("restore return nil", func() { - am := &addressManager{ - AddrSpaces: make(map[string]*addressSpace), - } - err := am.restore(false) - Expect(err).To(BeNil()) - }) + Describe("Test restore", func() { + Context("When store is nil", func() { + It("restore return nil", func() { + am := &addressManager{ + AddrSpaces: make(map[string]*addressSpace), + } + err := am.restore(false) + Expect(err).To(BeNil()) }) + }) - Context("Test Populate pointers", func() { - It("Should build addrsByID successfully", func() { - am := &addressManager{ - AddrSpaces: make(map[string]*addressSpace), - } - timeReboot, _ := platform.GetLastRebootTime() - am.store = &testutils.KeyValueStoreMock{ - ModificationTime: timeReboot.Add(time.Hour), - } - ap := &addressPool{ - Id: "ap-test", - RefCount: 1, - Addresses: make(map[string]*addressRecord), - } - ap.Addresses["ar-test"] = &addressRecord{ - ID: "ar-test", - InUse: true, - } - as := &addressSpace{ - Id: "as-test", - Pools: make(map[string]*addressPool), - } - as.Pools["ap-test"] = ap - am.AddrSpaces["as-test"] = as - err := am.restore(false) - Expect(err).To(BeNil()) - as = am.AddrSpaces["as-test"] - ap = as.Pools["ap-test"] - ar := ap.addrsByID["ar-test"] - Expect(ar.ID).To(Equal("ar-test")) - Expect(ap.RefCount).To(Equal(1)) - Expect(ar.InUse).To(BeTrue()) - }) + Context("Test Populate pointers", func() { + It("Should build addrsByID successfully", func() { + am := &addressManager{ + AddrSpaces: make(map[string]*addressSpace), + } + timeReboot, _ := platform.GetLastRebootTime() + am.store = &testutils.KeyValueStoreMock{ + ModificationTime: timeReboot.Add(time.Hour), + } + ap := &addressPool{ + Id: "ap-test", + RefCount: 1, + Addresses: make(map[string]*addressRecord), + } + ap.Addresses["ar-test"] = &addressRecord{ + ID: "ar-test", + InUse: true, + } + as := &addressSpace{ + Id: "as-test", + Pools: make(map[string]*addressPool), + } + as.Pools["ap-test"] = ap + am.AddrSpaces["as-test"] = as + err := am.restore(false) + Expect(err).To(BeNil()) + as = am.AddrSpaces["as-test"] + ap = as.Pools["ap-test"] + ar := ap.addrsByID["ar-test"] + Expect(ar.ID).To(Equal("ar-test")) + Expect(ap.RefCount).To(Equal(1)) + Expect(ar.InUse).To(BeTrue()) }) + }) - Context("When GetModificationTime return error", func() { - It("Should not clear the RefCount and InUse", func() { - am := &addressManager{ - AddrSpaces: make(map[string]*addressSpace), - } - am.store = &testutils.KeyValueStoreMock{ - GetModificationTimeError: errors.New("Error"), - } - ap := &addressPool{ - Id: "ap-test", - RefCount: 1, - Addresses: make(map[string]*addressRecord), - } - ap.Addresses["ar-test"] = &addressRecord{ - ID: "ar-test", - InUse: true, - } - as := &addressSpace{ - Id: "as-test", - Pools: make(map[string]*addressPool), - } - as.Pools["ap-test"] = ap - am.AddrSpaces["as-test"] = as - err := am.restore(false) - Expect(err).To(BeNil()) - as = am.AddrSpaces["as-test"] - ap = as.Pools["ap-test"] - ar := ap.addrsByID["ar-test"] - Expect(ar.ID).To(Equal("ar-test")) - Expect(ap.RefCount).To(Equal(1)) - Expect(ar.InUse).To(BeTrue()) - }) + Context("When GetModificationTime return error", func() { + It("Should not clear the RefCount and InUse", func() { + am := &addressManager{ + AddrSpaces: make(map[string]*addressSpace), + } + am.store = &testutils.KeyValueStoreMock{ + GetModificationTimeError: errors.New("Error"), + } + ap := &addressPool{ + Id: "ap-test", + RefCount: 1, + Addresses: make(map[string]*addressRecord), + } + ap.Addresses["ar-test"] = &addressRecord{ + ID: "ar-test", + InUse: true, + } + as := &addressSpace{ + Id: "as-test", + Pools: make(map[string]*addressPool), + } + as.Pools["ap-test"] = ap + am.AddrSpaces["as-test"] = as + err := am.restore(false) + Expect(err).To(BeNil()) + as = am.AddrSpaces["as-test"] + ap = as.Pools["ap-test"] + ar := ap.addrsByID["ar-test"] + Expect(ar.ID).To(Equal("ar-test")) + Expect(ap.RefCount).To(Equal(1)) + Expect(ar.InUse).To(BeTrue()) }) }) + }) - Describe("Test save", func() { - Context("When store is nill", func() { - It("Should return nil", func() { - am := &addressManager{} - err := am.save() - Expect(err).NotTo(HaveOccurred()) - }) + Describe("Test save", func() { + Context("When store is nill", func() { + It("Should return nil", func() { + am := &addressManager{} + err := am.save() + Expect(err).NotTo(HaveOccurred()) }) }) + }) - Describe("Test StartSource", func() { - Context("When environment is azure", func() { - It("Should return azure source", func() { - am := &addressManager{} - options := map[string]interface{}{} - options[common.OptEnvironment] = common.OptEnvironmentAzure - err := am.StartSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(am.source).NotTo(BeNil()) - }) + Describe("Test StartSource", func() { + Context("When environment is azure", func() { + It("Should return azure source", func() { + am := &addressManager{} + options := map[string]interface{}{} + options[common.OptEnvironment] = common.OptEnvironmentAzure + err := am.StartSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(am.source).NotTo(BeNil()) }) + }) - Context("When environment is mas", func() { - It("Should return mas", func() { - am := &addressManager{} - options := map[string]interface{}{} - options[common.OptEnvironment] = common.OptEnvironmentMAS - err := am.StartSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(am.source).NotTo(BeNil()) - }) + Context("When environment is mas", func() { + It("Should return mas", func() { + am := &addressManager{} + options := map[string]interface{}{} + options[common.OptEnvironment] = common.OptEnvironmentMAS + err := am.StartSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(am.source).NotTo(BeNil()) }) + }) - Context("When environment is null", func() { - It("Should return null source", func() { - am := &addressManager{} - options := map[string]interface{}{} - options[common.OptEnvironment] = "null" - err := am.StartSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(am.source).NotTo(BeNil()) - }) + Context("When environment is null", func() { + It("Should return null source", func() { + am := &addressManager{} + options := map[string]interface{}{} + options[common.OptEnvironment] = "null" + err := am.StartSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(am.source).NotTo(BeNil()) }) + }) - Context("When environment is nil", func() { - It("Should return nil", func() { - am := &addressManager{} - options := map[string]interface{}{} - options[common.OptEnvironment] = "" - err := am.StartSource(options) - Expect(err).NotTo(HaveOccurred()) - Expect(am.source).To(BeNil()) - }) + Context("When environment is nil", func() { + It("Should return nil", func() { + am := &addressManager{} + options := map[string]interface{}{} + options[common.OptEnvironment] = "" + err := am.StartSource(options) + Expect(err).NotTo(HaveOccurred()) + Expect(am.source).To(BeNil()) }) + }) - Context("When environment is nil", func() { - It("Should return nil", func() { - am := &addressManager{} - options := map[string]interface{}{} - options[common.OptEnvironment] = "Invalid" - err := am.StartSource(options) - Expect(err).To(HaveOccurred()) - Expect(am.source).To(BeNil()) - }) + Context("When environment is nil", func() { + It("Should return nil", func() { + am := &addressManager{} + options := map[string]interface{}{} + options[common.OptEnvironment] = "Invalid" + err := am.StartSource(options) + Expect(err).To(HaveOccurred()) + Expect(am.source).To(BeNil()) }) }) + }) - Describe("Test GetDefaultAddressSpaces", func() { - Context("When local and global are nil", func() { - It("Should return empty string", func() { - am := &addressManager{ - AddrSpaces: make(map[string]*addressSpace), - } - localId, globalId := am.GetDefaultAddressSpaces() - Expect(localId).To(BeEmpty()) - Expect(globalId).To(BeEmpty()) - }) + Describe("Test GetDefaultAddressSpaces", func() { + Context("When local and global are nil", func() { + It("Should return empty string", func() { + am := &addressManager{ + AddrSpaces: make(map[string]*addressSpace), + } + localId, globalId := am.GetDefaultAddressSpaces() + Expect(localId).To(BeEmpty()) + Expect(globalId).To(BeEmpty()) }) + }) - Context("When local and global are nil", func() { - It("Should return empty string", func() { - am := &addressManager{ - AddrSpaces: make(map[string]*addressSpace), - } - am.AddrSpaces[LocalDefaultAddressSpaceId] = &addressSpace{Id: "localId"} - am.AddrSpaces[GlobalDefaultAddressSpaceId] = &addressSpace{Id: "globalId"} - localId, globalId := am.GetDefaultAddressSpaces() - Expect(localId).To(Equal("localId")) - Expect(globalId).To(Equal("globalId")) - }) + Context("When local and global are nil", func() { + It("Should return empty string", func() { + am := &addressManager{ + AddrSpaces: make(map[string]*addressSpace), + } + am.AddrSpaces[LocalDefaultAddressSpaceId] = &addressSpace{Id: "localId"} + am.AddrSpaces[GlobalDefaultAddressSpaceId] = &addressSpace{Id: "globalId"} + localId, globalId := am.GetDefaultAddressSpaces() + Expect(localId).To(Equal("localId")) + Expect(globalId).To(Equal("globalId")) }) }) }) -) +}) diff --git a/ipam/null.go b/ipam/null.go index 8fa16ba95c..215f48fafa 100644 --- a/ipam/null.go +++ b/ipam/null.go @@ -34,7 +34,6 @@ func (s *nullSource) stop() { // Refreshes configuration. func (s *nullSource) refresh() error { - // Initialize once. if s.initialized { return nil diff --git a/ipam/pool_test.go b/ipam/pool_test.go index 438a5cec71..02204b7492 100644 --- a/ipam/pool_test.go +++ b/ipam/pool_test.go @@ -1,10 +1,11 @@ package ipam import ( - "github.com/google/uuid" "net" "testing" + "github.com/google/uuid" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -16,1103 +17,1097 @@ func TestPool(t *testing.T) { RunSpecs(t, "Pool Suite") } -var ( - _ = Describe("Test Pool", func() { - - Describe("Test addressPoolId", func() { - Context("Creates a new address pool ID object", func() { - It("Should create a pool ID with given parameters", func() { - asId := "eth0" - subnet := "10.0.0.0/16" - childSubnet := "10.0.1.0/8" - apId := NewAddressPoolId(asId, subnet, childSubnet) - Expect(apId.AsId).To(Equal(asId)) - Expect(apId.Subnet).To(Equal(subnet)) - Expect(apId.ChildSubnet).To(Equal(childSubnet)) - }) +var _ = Describe("Test Pool", func() { + Describe("Test addressPoolId", func() { + Context("Creates a new address pool ID object", func() { + It("Should create a pool ID with given parameters", func() { + asId := "eth0" + subnet := "10.0.0.0/16" + childSubnet := "10.0.1.0/8" + apId := NewAddressPoolId(asId, subnet, childSubnet) + Expect(apId.AsId).To(Equal(asId)) + Expect(apId.Subnet).To(Equal(subnet)) + Expect(apId.ChildSubnet).To(Equal(childSubnet)) }) + }) - Context("Create a new pool ID when string format is incorrect", func() { - It("Should raise an error", func() { - s := "eth0|10.0.0.0/16|10.0.1.0/8|test" - apId, err := NewAddressPoolIdFromString(s) - Expect(apId).To(BeNil()) - Expect(err).To(HaveOccurred()) - }) + Context("Create a new pool ID when string format is incorrect", func() { + It("Should raise an error", func() { + s := "eth0|10.0.0.0/16|10.0.1.0/8|test" + apId, err := NewAddressPoolIdFromString(s) + Expect(apId).To(BeNil()) + Expect(err).To(HaveOccurred()) }) + }) - Context("Create a new pool ID when string only contains addressSpace Id", func() { - It("Should create a pool ID by parsing the string", func() { - s := "local" - apId, err := NewAddressPoolIdFromString(s) - Expect(apId).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - Expect(apId.AsId).To(Equal(s)) - Expect(apId.Subnet).To(BeEmpty()) - Expect(apId.ChildSubnet).To(BeEmpty()) - }) + Context("Create a new pool ID when string only contains addressSpace Id", func() { + It("Should create a pool ID by parsing the string", func() { + s := "local" + apId, err := NewAddressPoolIdFromString(s) + Expect(apId).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + Expect(apId.AsId).To(Equal(s)) + Expect(apId.Subnet).To(BeEmpty()) + Expect(apId.ChildSubnet).To(BeEmpty()) }) + }) - Context("Create a new pool ID when the string has addrspace and subnet", func() { - It("Should create a pool ID by parsing the string", func() { - s := "eth0|10.0.0.0/16" - apId, err := NewAddressPoolIdFromString(s) - Expect(apId).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - Expect(apId.AsId).To(Equal("eth0")) - Expect(apId.Subnet).To(Equal("10.0.0.0/16")) - Expect(apId.ChildSubnet).To(BeEmpty()) - }) + Context("Create a new pool ID when the string has addrspace and subnet", func() { + It("Should create a pool ID by parsing the string", func() { + s := "eth0|10.0.0.0/16" + apId, err := NewAddressPoolIdFromString(s) + Expect(apId).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + Expect(apId.AsId).To(Equal("eth0")) + Expect(apId.Subnet).To(Equal("10.0.0.0/16")) + Expect(apId.ChildSubnet).To(BeEmpty()) }) + }) - Context("Create a new pool ID when string has addrspace, subnet and child subnet", func() { - It("Should create a pool ID by parsing the string", func() { - s := "eth0|10.0.0.0/16|10.0.1.0/8" - apId, err := NewAddressPoolIdFromString(s) - Expect(apId).NotTo(BeNil()) - Expect(err).NotTo(HaveOccurred()) - Expect(apId.AsId).To(Equal("eth0")) - Expect(apId.Subnet).To(Equal("10.0.0.0/16")) - Expect(apId.ChildSubnet).To(Equal("10.0.1.0/8")) - }) + Context("Create a new pool ID when string has addrspace, subnet and child subnet", func() { + It("Should create a pool ID by parsing the string", func() { + s := "eth0|10.0.0.0/16|10.0.1.0/8" + apId, err := NewAddressPoolIdFromString(s) + Expect(apId).NotTo(BeNil()) + Expect(err).NotTo(HaveOccurred()) + Expect(apId.AsId).To(Equal("eth0")) + Expect(apId.Subnet).To(Equal("10.0.0.0/16")) + Expect(apId.ChildSubnet).To(Equal("10.0.1.0/8")) }) + }) - Context("Returns the string representation of a pool ID with childSubnet", func() { - It("Should return string with asID|subnet|childsubnet", func() { - apId := &addressPoolId{ - AsId: "eth0", - Subnet: "10.0.0.0/16", - ChildSubnet: "10.0.1.0/8", - } - s := apId.String() - Expect(s).To(Equal("eth0|10.0.0.0/16|10.0.1.0/8")) - }) + Context("Returns the string representation of a pool ID with childSubnet", func() { + It("Should return string with asID|subnet|childsubnet", func() { + apId := &addressPoolId{ + AsId: "eth0", + Subnet: "10.0.0.0/16", + ChildSubnet: "10.0.1.0/8", + } + s := apId.String() + Expect(s).To(Equal("eth0|10.0.0.0/16|10.0.1.0/8")) }) + }) - Context("Returns the string representation of a pool ID without childSubnet", func() { - It("Should return a string without childSubnet", func() { - apId := &addressPoolId{ - AsId: "eth0", - Subnet: "10.0.0.0/16", - } - s := apId.String() - Expect(s).To(Equal("eth0|10.0.0.0/16")) - }) + Context("Returns the string representation of a pool ID without childSubnet", func() { + It("Should return a string without childSubnet", func() { + apId := &addressPoolId{ + AsId: "eth0", + Subnet: "10.0.0.0/16", + } + s := apId.String() + Expect(s).To(Equal("eth0|10.0.0.0/16")) }) }) + }) - Describe("Test newAddressSpace", func() { - - am := &addressManager{} - - Context("When scope is LocalScope", func() { - It("Should create an addressSpace with LocalScope", func() { - asId := "local" - scope := LocalScope - as, err := am.newAddressSpace(asId, scope) - Expect(err).NotTo(HaveOccurred()) - Expect(as.Id).To(Equal(asId)) - Expect(as.Scope).To(Equal(scope)) - }) + Describe("Test newAddressSpace", func() { + am := &addressManager{} + + Context("When scope is LocalScope", func() { + It("Should create an addressSpace with LocalScope", func() { + asId := "local" + scope := LocalScope + as, err := am.newAddressSpace(asId, scope) + Expect(err).NotTo(HaveOccurred()) + Expect(as.Id).To(Equal(asId)) + Expect(as.Scope).To(Equal(scope)) }) + }) - Context("When scope is GlobalScope", func() { - It("Should create an addressSpace with GlobalScope", func() { - asId := "local" - scope := GlobalScope - as, err := am.newAddressSpace(asId, scope) - Expect(err).NotTo(HaveOccurred()) - Expect(as.Id).To(Equal(asId)) - Expect(as.Scope).To(Equal(scope)) - }) + Context("When scope is GlobalScope", func() { + It("Should create an addressSpace with GlobalScope", func() { + asId := "local" + scope := GlobalScope + as, err := am.newAddressSpace(asId, scope) + Expect(err).NotTo(HaveOccurred()) + Expect(as.Id).To(Equal(asId)) + Expect(as.Scope).To(Equal(scope)) }) + }) - Context("When scope is not GlobalScope or LocalScope", func() { - It("Should raise an error", func() { - asId := "local" - scope := 127 - as, err := am.newAddressSpace(asId, scope) - Expect(err).To(HaveOccurred()) - Expect(as).To(BeNil()) - }) + Context("When scope is not GlobalScope or LocalScope", func() { + It("Should raise an error", func() { + asId := "local" + scope := 127 + as, err := am.newAddressSpace(asId, scope) + Expect(err).To(HaveOccurred()) + Expect(as).To(BeNil()) }) }) + }) - Describe("Test getAddressSpace and setAddressSpace", func() { - - am := &addressManager{ - AddrSpaces: map[string]*addressSpace{}, - } + Describe("Test getAddressSpace and setAddressSpace", func() { + am := &addressManager{ + AddrSpaces: map[string]*addressSpace{}, + } - Context("When addressSpace not exists", func() { - It("Should raise an error", func() { - as, err := am.getAddressSpace("lo") - Expect(err).To(Equal(errInvalidAddressSpace)) - Expect(as).To(BeNil()) - }) + Context("When addressSpace not exists", func() { + It("Should raise an error", func() { + as, err := am.getAddressSpace("lo") + Expect(err).To(Equal(errInvalidAddressSpace)) + Expect(as).To(BeNil()) }) + }) - Context("When addressSpace exists", func() { - It("Should return the addressSpace", func() { - asId := "local" - am.AddrSpaces[asId] = &addressSpace{Id: asId} - as, err := am.getAddressSpace(asId) - Expect(err).NotTo(HaveOccurred()) - Expect(as.Id).To(Equal(asId)) - }) + Context("When addressSpace exists", func() { + It("Should return the addressSpace", func() { + asId := "local" + am.AddrSpaces[asId] = &addressSpace{Id: asId} + as, err := am.getAddressSpace(asId) + Expect(err).NotTo(HaveOccurred()) + Expect(as.Id).To(Equal(asId)) }) }) + }) - Describe("Test setAddressSpace", func() { - - am := &addressManager{ - AddrSpaces: map[string]*addressSpace{}, - } - am.netApi = &testutils.NetApiMock{} - asId := "local" - - Context("When addressSpace not exists", func() { - It("Should be added to the am", func() { - err := am.setAddressSpace(&addressSpace{Id: asId}) - Expect(err).NotTo(HaveOccurred()) - Expect(am.AddrSpaces[asId].Id).To(Equal(asId)) - }) + Describe("Test setAddressSpace", func() { + am := &addressManager{ + AddrSpaces: map[string]*addressSpace{}, + } + am.netApi = &testutils.NetApiMock{} + asId := "local" + + Context("When addressSpace not exists", func() { + It("Should be added to the am", func() { + err := am.setAddressSpace(&addressSpace{Id: asId}) + Expect(err).NotTo(HaveOccurred()) + Expect(am.AddrSpaces[asId].Id).To(Equal(asId)) }) + }) - Context("When addressSpace already exists", func() { - It("Should be merged", func() { - err := am.setAddressSpace(&addressSpace{Id: asId}) - Expect(err).NotTo(HaveOccurred()) - Expect(am.AddrSpaces[asId].Id).To(Equal(asId)) - }) + Context("When addressSpace already exists", func() { + It("Should be merged", func() { + err := am.setAddressSpace(&addressSpace{Id: asId}) + Expect(err).NotTo(HaveOccurred()) + Expect(am.AddrSpaces[asId].Id).To(Equal(asId)) }) }) + }) - Describe("Test merge", func() { - Context("When only new addressSpace contains the pool", func() { - It("The pool should be merged to the origin addressSpace", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - pool := &addressPool{ - Id: poolId, - as: originAs, - } - newAs.Pools[poolId] = pool - originAs.merge(newAs) - pool = originAs.Pools[poolId] - Expect(pool.as.Id).To(Equal(asId)) - Expect(pool.epoch).To(Equal(4)) - Expect(newAs.Pools[poolId]).To(BeNil()) - }) + Describe("Test merge", func() { + Context("When only new addressSpace contains the pool", func() { + It("The pool should be merged to the origin addressSpace", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + pool := &addressPool{ + Id: poolId, + as: originAs, + } + newAs.Pools[poolId] = pool + originAs.merge(newAs) + pool = originAs.Pools[poolId] + Expect(pool.as.Id).To(Equal(asId)) + Expect(pool.epoch).To(Equal(4)) + Expect(newAs.Pools[poolId]).To(BeNil()) }) + }) - Context("When only new addressSpace contains the addressRecord", func() { - It("The addressRecord should be merged to the origin addressSpace", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - arId := "10.0.0.1/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool1 := &addressPool{ - Id: poolId, - as: originAs, - Addresses: map[string]*addressRecord{}, - } - originAs.Pools[poolId] = pool1 - - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - pool2 := &addressPool{ - Id: poolId, - as: newAs, - Addresses: map[string]*addressRecord{}, - } - pool2.Addresses[arId] = &addressRecord{InUse: true} - newAs.Pools[poolId] = pool2 - originAs.merge(newAs) - pool1 = originAs.Pools[poolId] - Expect(pool1.as.Id).To(Equal(asId)) - ar := pool1.Addresses[arId] - Expect(ar.epoch).To(Equal(4)) - Expect(ar.InUse).To(BeTrue()) - Expect(newAs.Pools[poolId]).To(BeNil()) - }) + Context("When only new addressSpace contains the addressRecord", func() { + It("The addressRecord should be merged to the origin addressSpace", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + arId := "10.0.0.1/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool1 := &addressPool{ + Id: poolId, + as: originAs, + Addresses: map[string]*addressRecord{}, + } + originAs.Pools[poolId] = pool1 + + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + pool2 := &addressPool{ + Id: poolId, + as: newAs, + Addresses: map[string]*addressRecord{}, + } + pool2.Addresses[arId] = &addressRecord{InUse: true} + newAs.Pools[poolId] = pool2 + originAs.merge(newAs) + pool1 = originAs.Pools[poolId] + Expect(pool1.as.Id).To(Equal(asId)) + ar := pool1.Addresses[arId] + Expect(ar.epoch).To(Equal(4)) + Expect(ar.InUse).To(BeTrue()) + Expect(newAs.Pools[poolId]).To(BeNil()) }) + }) - Context("When addressRecord is contained in both new addressSpace and origin addressSpace", func() { - It("The addressRecord of origin addressSpace should be updated", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - arId := "10.0.0.1/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool1 := &addressPool{ - Id: poolId, - as: originAs, - Addresses: map[string]*addressRecord{}, - } - pool1.Addresses[arId] = &addressRecord{InUse: true, unhealthy: true} - originAs.Pools[poolId] = pool1 - - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - pool2 := &addressPool{ - Id: poolId, - as: newAs, - Addresses: map[string]*addressRecord{}, - } - pool2.Addresses[arId] = &addressRecord{InUse: true} - newAs.Pools[poolId] = pool2 - originAs.merge(newAs) - pool1 = originAs.Pools[poolId] - Expect(pool1.as.Id).To(Equal(asId)) - ar := pool1.Addresses[arId] - Expect(ar.epoch).To(Equal(4)) - Expect(ar.InUse).To(BeTrue()) - Expect(ar.unhealthy).To(BeFalse()) - Expect(newAs.Pools[poolId]).To(BeNil()) - }) + Context("When addressRecord is contained in both new addressSpace and origin addressSpace", func() { + It("The addressRecord of origin addressSpace should be updated", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + arId := "10.0.0.1/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool1 := &addressPool{ + Id: poolId, + as: originAs, + Addresses: map[string]*addressRecord{}, + } + pool1.Addresses[arId] = &addressRecord{InUse: true, unhealthy: true} + originAs.Pools[poolId] = pool1 + + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + pool2 := &addressPool{ + Id: poolId, + as: newAs, + Addresses: map[string]*addressRecord{}, + } + pool2.Addresses[arId] = &addressRecord{InUse: true} + newAs.Pools[poolId] = pool2 + originAs.merge(newAs) + pool1 = originAs.Pools[poolId] + Expect(pool1.as.Id).To(Equal(asId)) + ar := pool1.Addresses[arId] + Expect(ar.epoch).To(Equal(4)) + Expect(ar.InUse).To(BeTrue()) + Expect(ar.unhealthy).To(BeFalse()) + Expect(newAs.Pools[poolId]).To(BeNil()) }) + }) - Context("When addressRecord epoch is correct and pool epoch is less", func() { - It("Should update the pool epoch", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - arId := "10.0.0.1/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool1 := &addressPool{ - Id: poolId, - as: originAs, - epoch: 3, - Addresses: map[string]*addressRecord{}, - } - pool1.Addresses[arId] = &addressRecord{ - epoch: 4, - InUse: true, - } - originAs.Pools[poolId] = pool1 - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - originAs.merge(newAs) - pool1 = originAs.Pools[poolId] - Expect(pool1.epoch).To(Equal(4)) - ar := pool1.Addresses[arId] - Expect(ar.epoch).To(Equal(4)) - Expect(ar.InUse).To(BeTrue()) - Expect(ar.unhealthy).To(BeFalse()) - }) + Context("When addressRecord epoch is correct and pool epoch is less", func() { + It("Should update the pool epoch", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + arId := "10.0.0.1/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool1 := &addressPool{ + Id: poolId, + as: originAs, + epoch: 3, + Addresses: map[string]*addressRecord{}, + } + pool1.Addresses[arId] = &addressRecord{ + epoch: 4, + InUse: true, + } + originAs.Pools[poolId] = pool1 + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + originAs.merge(newAs) + pool1 = originAs.Pools[poolId] + Expect(pool1.epoch).To(Equal(4)) + ar := pool1.Addresses[arId] + Expect(ar.epoch).To(Equal(4)) + Expect(ar.InUse).To(BeTrue()) + Expect(ar.unhealthy).To(BeFalse()) }) + }) - Context("When addressRecord is in use", func() { - It("The addressRecord should be set to unhealthy", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - arId := "10.0.0.1/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool1 := &addressPool{ - Id: poolId, - as: originAs, - epoch: 3, - Addresses: map[string]*addressRecord{}, - } - pool1.Addresses[arId] = &addressRecord{ - epoch: 3, - InUse: true, - } - originAs.Pools[poolId] = pool1 - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - originAs.merge(newAs) - pool1 = originAs.Pools[poolId] - Expect(pool1.epoch).To(Equal(4)) - ar := pool1.Addresses[arId] - Expect(ar.epoch).To(Equal(3)) - Expect(ar.InUse).To(BeTrue()) - Expect(ar.unhealthy).To(BeTrue()) - }) + Context("When addressRecord is in use", func() { + It("The addressRecord should be set to unhealthy", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + arId := "10.0.0.1/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool1 := &addressPool{ + Id: poolId, + as: originAs, + epoch: 3, + Addresses: map[string]*addressRecord{}, + } + pool1.Addresses[arId] = &addressRecord{ + epoch: 3, + InUse: true, + } + originAs.Pools[poolId] = pool1 + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + originAs.merge(newAs) + pool1 = originAs.Pools[poolId] + Expect(pool1.epoch).To(Equal(4)) + ar := pool1.Addresses[arId] + Expect(ar.epoch).To(Equal(3)) + Expect(ar.InUse).To(BeTrue()) + Expect(ar.unhealthy).To(BeTrue()) }) + }) - Context("When addressRecord is not in use but pool is in use", func() { - It("The addressRecord should be deleted", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - arId := "10.0.0.1/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool := &addressPool{ - Id: poolId, - as: originAs, - epoch: 3, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - pool.Addresses[arId] = &addressRecord{ - epoch: 3, - InUse: false, - } - originAs.Pools[poolId] = pool - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - originAs.merge(newAs) - pool = originAs.Pools[poolId] - Expect(pool.epoch).To(Equal(3)) - ar := pool.Addresses[arId] - Expect(ar).To(BeNil()) - }) + Context("When addressRecord is not in use but pool is in use", func() { + It("The addressRecord should be deleted", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + arId := "10.0.0.1/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool := &addressPool{ + Id: poolId, + as: originAs, + epoch: 3, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + pool.Addresses[arId] = &addressRecord{ + epoch: 3, + InUse: false, + } + originAs.Pools[poolId] = pool + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + originAs.merge(newAs) + pool = originAs.Pools[poolId] + Expect(pool.epoch).To(Equal(3)) + ar := pool.Addresses[arId] + Expect(ar).To(BeNil()) }) + }) - Context("When pool is not in use", func() { - It("The pool should be deleted", func() { - asId := "local" - epoch := 3 - poolId := "10.0.0.0/16" - - originAs := &addressSpace{ - Id: asId, - epoch: epoch, - Pools: map[string]*addressPool{}, - } - pool := &addressPool{ - Id: poolId, - as: originAs, - epoch: 3, - RefCount: 0, - Addresses: map[string]*addressRecord{}, - } - originAs.Pools[poolId] = pool - newAs := &addressSpace{ - Id: asId, - Pools: map[string]*addressPool{}, - } - originAs.merge(newAs) - pool = originAs.Pools[poolId] - Expect(pool).To(BeNil()) - }) + Context("When pool is not in use", func() { + It("The pool should be deleted", func() { + asId := "local" + epoch := 3 + poolId := "10.0.0.0/16" + + originAs := &addressSpace{ + Id: asId, + epoch: epoch, + Pools: map[string]*addressPool{}, + } + pool := &addressPool{ + Id: poolId, + as: originAs, + epoch: 3, + RefCount: 0, + Addresses: map[string]*addressRecord{}, + } + originAs.Pools[poolId] = pool + newAs := &addressSpace{ + Id: asId, + Pools: map[string]*addressPool{}, + } + originAs.merge(newAs) + pool = originAs.Pools[poolId] + Expect(pool).To(BeNil()) }) }) + }) - Describe("Test newAddressPool", func() { - Context("When pool already exists", func() { - It("Should raise an error", func() { - subnet := &net.IPNet{ - IP: net.IPv4(10, 0, 0, 1), - Mask: net.IPv4Mask(255, 255, 0, 0), - } - poolId := subnet.String() - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - as.Pools[poolId] = &addressPool{Id: poolId} - pool, err := as.newAddressPool("", 0, subnet) - Expect(err).To(Equal(errAddressPoolExists)) - Expect(pool.Id).To(Equal(poolId)) - }) + Describe("Test newAddressPool", func() { + Context("When pool already exists", func() { + It("Should raise an error", func() { + subnet := &net.IPNet{ + IP: net.IPv4(10, 0, 0, 1), + Mask: net.IPv4Mask(255, 255, 0, 0), + } + poolId := subnet.String() + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + as.Pools[poolId] = &addressPool{Id: poolId} + pool, err := as.newAddressPool("", 0, subnet) + Expect(err).To(Equal(errAddressPoolExists)) + Expect(pool.Id).To(Equal(poolId)) }) + }) - Context("When pool not exists", func() { - It("Should create pool successfully", func() { - subnet := &net.IPNet{ - IP: net.IPv4(10, 0, 0, 1), - Mask: net.IPv4Mask(255, 255, 0, 0), - } - poolId := subnet.String() - as := &addressSpace{ - Id: "local", - Pools: map[string]*addressPool{}, - } - pool, err := as.newAddressPool("local", 1, subnet) - Expect(err).NotTo(HaveOccurred()) - Expect(pool.Id).To(Equal(poolId)) - Expect(pool.as.Id).To(Equal(as.Id)) - Expect(pool.IfName).To(Equal("local")) - Expect(pool.Subnet.String()).To(Equal(poolId)) - Expect(pool.IsIPv6).To(BeFalse()) - Expect(pool.Priority).To(Equal(1)) - Expect(as.Pools[poolId]).NotTo(BeNil()) - }) + Context("When pool not exists", func() { + It("Should create pool successfully", func() { + subnet := &net.IPNet{ + IP: net.IPv4(10, 0, 0, 1), + Mask: net.IPv4Mask(255, 255, 0, 0), + } + poolId := subnet.String() + as := &addressSpace{ + Id: "local", + Pools: map[string]*addressPool{}, + } + pool, err := as.newAddressPool("local", 1, subnet) + Expect(err).NotTo(HaveOccurred()) + Expect(pool.Id).To(Equal(poolId)) + Expect(pool.as.Id).To(Equal(as.Id)) + Expect(pool.IfName).To(Equal("local")) + Expect(pool.Subnet.String()).To(Equal(poolId)) + Expect(pool.IsIPv6).To(BeFalse()) + Expect(pool.Priority).To(Equal(1)) + Expect(as.Pools[poolId]).NotTo(BeNil()) }) + }) - Context("When pool is ipv6", func() { - It("Should create pool successfully", func() { - subnet := &net.IPNet{ - IP: net.IPv6zero, - Mask: net.IPv6zero.DefaultMask(), - } - poolId := subnet.String() - as := &addressSpace{ - Id: "local", - Pools: map[string]*addressPool{}, - } - pool, err := as.newAddressPool("local", 1, subnet) - Expect(err).NotTo(HaveOccurred()) - Expect(pool.Id).To(Equal(poolId)) - Expect(pool.as.Id).To(Equal(as.Id)) - Expect(pool.IfName).To(Equal("local")) - Expect(pool.Subnet.String()).To(Equal(poolId)) - Expect(pool.IsIPv6).To(BeTrue()) - Expect(pool.Priority).To(Equal(1)) - Expect(as.Pools[poolId]).NotTo(BeNil()) - }) + Context("When pool is ipv6", func() { + It("Should create pool successfully", func() { + subnet := &net.IPNet{ + IP: net.IPv6zero, + Mask: net.IPv6zero.DefaultMask(), + } + poolId := subnet.String() + as := &addressSpace{ + Id: "local", + Pools: map[string]*addressPool{}, + } + pool, err := as.newAddressPool("local", 1, subnet) + Expect(err).NotTo(HaveOccurred()) + Expect(pool.Id).To(Equal(poolId)) + Expect(pool.as.Id).To(Equal(as.Id)) + Expect(pool.IfName).To(Equal("local")) + Expect(pool.Subnet.String()).To(Equal(poolId)) + Expect(pool.IsIPv6).To(BeTrue()) + Expect(pool.Priority).To(Equal(1)) + Expect(as.Pools[poolId]).NotTo(BeNil()) }) }) + }) - Describe("Test getAddressPool", func() { - Context("When pool not find", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - pool, _ := as.getAddressPool("10.0.0.0/16") - Expect(pool).To(BeNil()) - }) + Describe("Test getAddressPool", func() { + Context("When pool not find", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + pool, _ := as.getAddressPool("10.0.0.0/16") + Expect(pool).To(BeNil()) }) + }) - Context("When pool is found", func() { - It("Should return the pool", func() { - poolId := "10.0.0.0/16" - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - as.Pools[poolId] = &addressPool{Id: poolId} - pool, err := as.getAddressPool(poolId) - Expect(err).NotTo(HaveOccurred()) - Expect(pool.Id).To(Equal(poolId)) - }) + Context("When pool is found", func() { + It("Should return the pool", func() { + poolId := "10.0.0.0/16" + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + as.Pools[poolId] = &addressPool{Id: poolId} + pool, err := as.getAddressPool(poolId) + Expect(err).NotTo(HaveOccurred()) + Expect(pool.Id).To(Equal(poolId)) }) }) + }) - Describe("Test requestPool", func() { - Context("When poolId is explicitly specified and not found in addressSpace", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - ap, err := as.requestPool("10.0.0.0/16", "", nil, false) - Expect(err).To(Equal(errAddressPoolNotFound)) - Expect(ap).To(BeNil()) - }) + Describe("Test requestPool", func() { + Context("When poolId is explicitly specified and not found in addressSpace", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + ap, err := as.requestPool("10.0.0.0/16", "", nil, false) + Expect(err).To(Equal(errAddressPoolNotFound)) + Expect(ap).To(BeNil()) }) + }) - Context("When poolId is explicitly specified and found in addressSpace", func() { - It("Should return the pool", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - RefCount: 0, - } - ap, err := as.requestPool(poolId, "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Id).To(Equal(poolId)) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When poolId is explicitly specified and found in addressSpace", func() { + It("Should return the pool", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + RefCount: 0, + } + ap, err := as.requestPool(poolId, "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Id).To(Equal(poolId)) + Expect(ap.RefCount).To(Equal(1)) }) + }) - Context("When pool is in use and it has no ips allocated", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - ap, err := as.requestPool("", "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Id).To(Equal(poolId)) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When pool is in use and it has no ips allocated", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + ap, err := as.requestPool("", "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Id).To(Equal(poolId)) + Expect(ap.RefCount).To(Equal(1)) }) + }) - Context("When pool is in use and it has ips allocated", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ - InUse: true, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - ap, err := as.requestPool("", "", nil, false) - Expect(err).To(HaveOccurred()) - Expect(ap).To(BeNil()) - Expect(err).To(Equal(errNoAvailableAddressPools)) - }) + Context("When pool is in use and it has ips allocated", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ + InUse: true, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + ap, err := as.requestPool("", "", nil, false) + Expect(err).To(HaveOccurred()) + Expect(ap).To(BeNil()) + Expect(err).To(Equal(errNoAvailableAddressPools)) }) + }) - Context("When pool is in use and request same pool explicitly", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ - InUse: true, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - ap, err := as.requestPool(poolId, "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap).NotTo(BeNil()) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When pool is in use and request same pool explicitly", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ + InUse: true, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + ap, err := as.requestPool(poolId, "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap).NotTo(BeNil()) + Expect(ap.RefCount).To(Equal(1)) }) + }) - Context("When pool is ipv4 and ipv6 is wanted", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - IsIPv6: false, - } - ap, err := as.requestPool("", "", nil, true) - Expect(err).To(Equal(errNoAvailableAddressPools)) - Expect(ap).To(BeNil()) - }) + Context("When pool is ipv4 and ipv6 is wanted", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + IsIPv6: false, + } + ap, err := as.requestPool("", "", nil, true) + Expect(err).To(Equal(errNoAvailableAddressPools)) + Expect(ap).To(BeNil()) }) + }) - Context("When the requested interface name does not exist", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - ifName := "local" - as.Pools[poolId] = &addressPool{ - Id: poolId, - IfName: ifName, - } - options := map[string]string{} - options[OptInterfaceName] = "en0" - ap, err := as.requestPool("", "", options, false) - Expect(err).To(Equal(errNoAvailableAddressPools)) - Expect(ap).To(BeNil()) - }) + Context("When the requested interface name does not exist", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + ifName := "local" + as.Pools[poolId] = &addressPool{ + Id: poolId, + IfName: ifName, + } + options := map[string]string{} + options[OptInterfaceName] = "en0" + ap, err := as.requestPool("", "", options, false) + Expect(err).To(Equal(errNoAvailableAddressPools)) + Expect(ap).To(BeNil()) }) + }) - Context("When addressSpace has one pool available", func() { - It("Should return the pool", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - poolId := "10.0.0.0/16" - as.Pools[poolId] = &addressPool{ - Id: poolId, - } - ap, err := as.requestPool("", "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Id).To(Equal(poolId)) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When addressSpace has one pool available", func() { + It("Should return the pool", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + poolId := "10.0.0.0/16" + as.Pools[poolId] = &addressPool{ + Id: poolId, + } + ap, err := as.requestPool("", "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Id).To(Equal(poolId)) + Expect(ap.RefCount).To(Equal(1)) }) + }) - Context("When addressSpace has pools with different priority", func() { - It("Should return the pool with the highest priority", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - as.Pools["10.0.0.0/16"] = &addressPool{ - Id: "10.0.0.0/16", - Priority: 1, - } - as.Pools["10.1.0.0/16"] = &addressPool{ - Id: "10.1.0.0/16", - Priority: 2, - } - ap, err := as.requestPool("", "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Id).To(Equal("10.1.0.0/16")) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When addressSpace has pools with different priority", func() { + It("Should return the pool with the highest priority", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + as.Pools["10.0.0.0/16"] = &addressPool{ + Id: "10.0.0.0/16", + Priority: 1, + } + as.Pools["10.1.0.0/16"] = &addressPool{ + Id: "10.1.0.0/16", + Priority: 2, + } + ap, err := as.requestPool("", "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Id).To(Equal("10.1.0.0/16")) + Expect(ap.RefCount).To(Equal(1)) }) + }) - Context("When addressSpace has pools with different addresses", func() { - It("Should return the pool with the highest number of addresses", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - as.Pools["10.0.0.0/16"] = &addressPool{ - Id: "10.0.0.0/16", - Addresses: map[string]*addressRecord{}, - } - as.Pools["10.1.0.0/16"] = &addressPool{ - Id: "10.1.0.0/16", - Addresses: map[string]*addressRecord{ - "10.1.0.1/16": &addressRecord{}, - }, - } - ap, err := as.requestPool("", "", nil, false) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Id).To(Equal("10.1.0.0/16")) - Expect(ap.RefCount).To(Equal(1)) - }) + Context("When addressSpace has pools with different addresses", func() { + It("Should return the pool with the highest number of addresses", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + as.Pools["10.0.0.0/16"] = &addressPool{ + Id: "10.0.0.0/16", + Addresses: map[string]*addressRecord{}, + } + as.Pools["10.1.0.0/16"] = &addressPool{ + Id: "10.1.0.0/16", + Addresses: map[string]*addressRecord{ + "10.1.0.1/16": {}, + }, + } + ap, err := as.requestPool("", "", nil, false) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Id).To(Equal("10.1.0.0/16")) + Expect(ap.RefCount).To(Equal(1)) }) }) + }) - Describe("Test releasePool", func() { - Context("When pool not found", func() { - It("Should raise an error", func() { - as := &addressSpace{ - Pools: map[string]*addressPool{}, - } - err := as.releasePool("10.0.0.0/16") - Expect(err).To(Equal(errAddressPoolNotFound)) - }) + Describe("Test releasePool", func() { + Context("When pool not found", func() { + It("Should raise an error", func() { + as := &addressSpace{ + Pools: map[string]*addressPool{}, + } + err := as.releasePool("10.0.0.0/16") + Expect(err).To(Equal(errAddressPoolNotFound)) }) + }) - Context("When pool's addresses are all not in use", func() { - It("Should release the pool ", func() { - poolId := "10.0.0.0/16" - as := &addressSpace{ - epoch: 2, - Pools: map[string]*addressPool{}, - } - as.Pools[poolId] = &addressPool{ - epoch: 1, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - - as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.3"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - - err := as.releasePool("10.0.0.0/16") - Expect(err).NotTo(HaveOccurred()) - Expect(as.Pools[poolId].isInUse()).To(BeFalse()) - }) + Context("When pool's addresses are all not in use", func() { + It("Should release the pool ", func() { + poolId := "10.0.0.0/16" + as := &addressSpace{ + epoch: 2, + Pools: map[string]*addressPool{}, + } + as.Pools[poolId] = &addressPool{ + epoch: 1, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + + as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.3"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + + err := as.releasePool("10.0.0.0/16") + Expect(err).NotTo(HaveOccurred()) + Expect(as.Pools[poolId].isInUse()).To(BeFalse()) }) + }) - Context("When the pool has in use addresses", func() { - It("Should not delete the pool", func() { - poolId := "10.0.0.0/16" - as := &addressSpace{ - epoch: 1, - Pools: map[string]*addressPool{}, - } - as.Pools[poolId] = &addressPool{ - epoch: 1, - RefCount: 1, - Addresses: map[string]*addressRecord{}, - } - - as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ - InUse: true, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - as.Pools[poolId].Addresses["10.0.0.3"] = &addressRecord{ - InUse: false, - Addr: net.IPv4zero, - } - - err := as.releasePool("10.0.0.0/16") - Expect(err).NotTo(HaveOccurred()) - Expect(as.Pools[poolId]).NotTo(BeNil()) - }) + Context("When the pool has in use addresses", func() { + It("Should not delete the pool", func() { + poolId := "10.0.0.0/16" + as := &addressSpace{ + epoch: 1, + Pools: map[string]*addressPool{}, + } + as.Pools[poolId] = &addressPool{ + epoch: 1, + RefCount: 1, + Addresses: map[string]*addressRecord{}, + } + + as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{ + InUse: true, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + as.Pools[poolId].Addresses["10.0.0.3"] = &addressRecord{ + InUse: false, + Addr: net.IPv4zero, + } + + err := as.releasePool("10.0.0.0/16") + Expect(err).NotTo(HaveOccurred()) + Expect(as.Pools[poolId]).NotTo(BeNil()) }) + }) - Context("When pool is still in use", func() { - It("Should not delete the pool", func() { - poolId := "10.0.0.0/16" - as := &addressSpace{ - epoch: 2, - Pools: map[string]*addressPool{}, - } - as.Pools[poolId] = &addressPool{ - epoch: 1, - RefCount: 2, - } - err := as.releasePool("10.0.0.0/16") - Expect(err).NotTo(HaveOccurred()) - Expect(as.Pools[poolId]).NotTo(BeNil()) - }) + Context("When pool is still in use", func() { + It("Should not delete the pool", func() { + poolId := "10.0.0.0/16" + as := &addressSpace{ + epoch: 2, + Pools: map[string]*addressPool{}, + } + as.Pools[poolId] = &addressPool{ + epoch: 1, + RefCount: 2, + } + err := as.releasePool("10.0.0.0/16") + Expect(err).NotTo(HaveOccurred()) + Expect(as.Pools[poolId]).NotTo(BeNil()) }) }) + }) - Describe("Test getInfo", func() { - Context("When addressRecord is not in use", func() { - It("Should add the available", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: false} - ap.Addresses["10.0.0.2/16"] = &addressRecord{InUse: true} - ap.Addresses["10.0.0.3/16"] = &addressRecord{InUse: false} - apInfo := ap.getInfo() - Expect(apInfo.Available).To(Equal(2)) - }) + Describe("Test getInfo", func() { + Context("When addressRecord is not in use", func() { + It("Should add the available", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: false} + ap.Addresses["10.0.0.2/16"] = &addressRecord{InUse: true} + ap.Addresses["10.0.0.3/16"] = &addressRecord{InUse: false} + apInfo := ap.getInfo() + Expect(apInfo.Available).To(Equal(2)) }) + }) - Context("When addressRecords are unhealthy", func() { - It("Should append the unhealthyAddrs", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - ap.Addresses["10.0.0.1/16"] = &addressRecord{ - unhealthy: true, - Addr: net.IPv4zero, - } - ap.Addresses["10.0.0.2/16"] = &addressRecord{ - unhealthy: false, - Addr: net.IPv4zero, - } - ap.Addresses["10.0.0.3/16"] = &addressRecord{ - unhealthy: true, - Addr: net.IPv4zero, - } - apInfo := ap.getInfo() - Expect(len(apInfo.UnhealthyAddrs)).To(Equal(2)) - }) + Context("When addressRecords are unhealthy", func() { + It("Should append the unhealthyAddrs", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + ap.Addresses["10.0.0.1/16"] = &addressRecord{ + unhealthy: true, + Addr: net.IPv4zero, + } + ap.Addresses["10.0.0.2/16"] = &addressRecord{ + unhealthy: false, + Addr: net.IPv4zero, + } + ap.Addresses["10.0.0.3/16"] = &addressRecord{ + unhealthy: true, + Addr: net.IPv4zero, + } + apInfo := ap.getInfo() + Expect(len(apInfo.UnhealthyAddrs)).To(Equal(2)) }) }) + }) - Describe("Test isInUse", func() { - Context("When RefCount is set to some value", func() { - It("Should return true when RefCount > 0", func() { - ap := &addressPool{RefCount: 0} - Expect(ap.isInUse()).To(BeFalse()) - ap.RefCount = 1 - Expect(ap.isInUse()).To(BeTrue()) - ap.RefCount = 10000 - Expect(ap.isInUse()).To(BeTrue()) - ap.RefCount = -1 - Expect(ap.isInUse()).To(BeFalse()) - }) + Describe("Test isInUse", func() { + Context("When RefCount is set to some value", func() { + It("Should return true when RefCount > 0", func() { + ap := &addressPool{RefCount: 0} + Expect(ap.isInUse()).To(BeFalse()) + ap.RefCount = 1 + Expect(ap.isInUse()).To(BeTrue()) + ap.RefCount = 10000 + Expect(ap.isInUse()).To(BeTrue()) + ap.RefCount = -1 + Expect(ap.isInUse()).To(BeFalse()) }) }) + }) - Describe("Test requestAddress", func() { - Context("When addressRecord not found", func() { - It("Should raise errAddressNotFound", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - addr, err := ap.requestAddress("10.0.0.1/16", nil) - Expect(err).To(Equal(errAddressNotFound)) - Expect(addr).To(BeEmpty()) - }) + Describe("Test requestAddress", func() { + Context("When addressRecord not found", func() { + It("Should raise errAddressNotFound", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + addr, err := ap.requestAddress("10.0.0.1/16", nil) + Expect(err).To(Equal(errAddressNotFound)) + Expect(addr).To(BeEmpty()) }) + }) - Context("When addressRecord is in use and id match", func() { - It("Should return the same addressRecord", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - addrsByID: map[string]*addressRecord{}, - } - arId := "10.0.0.1/16" - ap.Addresses[arId] = &addressRecord{ - ID: arId, - InUse: true, - } - options := map[string]string{} - options[OptAddressID] = arId - addr, err := ap.requestAddress("10.0.0.1/16", options) - Expect(err).NotTo(HaveOccurred()) - Expect(addr).NotTo(BeEmpty()) - Expect(ap.addrsByID[arId].ID).To(Equal(arId)) - }) + Context("When addressRecord is in use and id match", func() { + It("Should return the same addressRecord", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + addrsByID: map[string]*addressRecord{}, + } + arId := "10.0.0.1/16" + ap.Addresses[arId] = &addressRecord{ + ID: arId, + InUse: true, + } + options := map[string]string{} + options[OptAddressID] = arId + addr, err := ap.requestAddress("10.0.0.1/16", options) + Expect(err).NotTo(HaveOccurred()) + Expect(addr).NotTo(BeEmpty()) + Expect(ap.addrsByID[arId].ID).To(Equal(arId)) }) + }) - Context("When id is not found and a address is available", func() { - It("Should return a new address", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - addrsByID: map[string]*addressRecord{}, - Subnet: subnet1, - } - arId := uuid.New().String() - - ap.Addresses["0"] = &addressRecord{ - ID: "", - Addr: addr11, - InUse: false, - } - - ap.Addresses["1"] = &addressRecord{ - ID: "", - Addr: addr12, - InUse: false, - } - - ap.Addresses["3"] = &addressRecord{ - ID: "", - Addr: addr13, - InUse: false, - } - - options := map[string]string{} - options[OptAddressID] = arId - - addr, err := ap.requestAddress("", options) - Expect(err).NotTo(HaveOccurred()) - Expect(addr).NotTo(BeEmpty()) - Expect(ap.addrsByID[arId].ID).To(Equal(arId)) - }) + Context("When id is not found and a address is available", func() { + It("Should return a new address", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + addrsByID: map[string]*addressRecord{}, + Subnet: subnet1, + } + arId := uuid.New().String() + + ap.Addresses["0"] = &addressRecord{ + ID: "", + Addr: addr11, + InUse: false, + } + + ap.Addresses["1"] = &addressRecord{ + ID: "", + Addr: addr12, + InUse: false, + } + + ap.Addresses["3"] = &addressRecord{ + ID: "", + Addr: addr13, + InUse: false, + } + + options := map[string]string{} + options[OptAddressID] = arId + + addr, err := ap.requestAddress("", options) + Expect(err).NotTo(HaveOccurred()) + Expect(addr).NotTo(BeEmpty()) + Expect(ap.addrsByID[arId].ID).To(Equal(arId)) }) + }) - Context("When addressRecord is in use and id is empty", func() { - It("Should raise errAddressInUse", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: true} - addr, err := ap.requestAddress("10.0.0.1/16", nil) - Expect(err).To(Equal(errAddressInUse)) - Expect(addr).To(BeEmpty()) - }) + Context("When addressRecord is in use and id is empty", func() { + It("Should raise errAddressInUse", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: true} + addr, err := ap.requestAddress("10.0.0.1/16", nil) + Expect(err).To(Equal(errAddressInUse)) + Expect(addr).To(BeEmpty()) }) + }) - Context("When addressRecord is in use and id is not equal to the addressRecord's id", func() { - It("Should raise errAddressInUse", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - arId := "10.0.0.1/16" - ap.Addresses[arId] = &addressRecord{ - ID: arId, - InUse: true, - } - options := map[string]string{} - options[OptAddressID] = "10.0.0.2/16" - addr, err := ap.requestAddress("10.0.0.1/16", options) - Expect(err).To(Equal(errAddressInUse)) - Expect(addr).To(BeEmpty()) - }) + Context("When addressRecord is in use and id is not equal to the addressRecord's id", func() { + It("Should raise errAddressInUse", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + arId := "10.0.0.1/16" + ap.Addresses[arId] = &addressRecord{ + ID: arId, + InUse: true, + } + options := map[string]string{} + options[OptAddressID] = "10.0.0.2/16" + addr, err := ap.requestAddress("10.0.0.1/16", options) + Expect(err).To(Equal(errAddressInUse)) + Expect(addr).To(BeEmpty()) }) + }) - Context("When OptAddressType is OptAddressTypeGateway", func() { - It("Should raise errAddressInUse", func() { - ap := &addressPool{ - Gateway: net.IPv4(10, 0, 0, 1), - } - options := map[string]string{} - options[OptAddressType] = OptAddressTypeGateway - addr, err := ap.requestAddress("", options) - Expect(err).NotTo(HaveOccurred()) - Expect(addr).NotTo(BeEmpty()) - }) + Context("When OptAddressType is OptAddressTypeGateway", func() { + It("Should raise errAddressInUse", func() { + ap := &addressPool{ + Gateway: net.IPv4(10, 0, 0, 1), + } + options := map[string]string{} + options[OptAddressType] = OptAddressTypeGateway + addr, err := ap.requestAddress("", options) + Expect(err).NotTo(HaveOccurred()) + Expect(addr).NotTo(BeEmpty()) }) + }) - Context("When id match", func() { - It("Should return the addressRecord with given id", func() { - ap := &addressPool{ - addrsByID: map[string]*addressRecord{}, - } - arId := "10.0.0.1/16" - ap.addrsByID[arId] = &addressRecord{ - ID: arId, - InUse: true, - } - options := map[string]string{} - options[OptAddressID] = arId - addr, err := ap.requestAddress("", options) - Expect(err).NotTo(HaveOccurred()) - Expect(addr).NotTo(BeEmpty()) - Expect(ap.addrsByID[arId].ID).To(Equal(arId)) - }) + Context("When id match", func() { + It("Should return the addressRecord with given id", func() { + ap := &addressPool{ + addrsByID: map[string]*addressRecord{}, + } + arId := "10.0.0.1/16" + ap.addrsByID[arId] = &addressRecord{ + ID: arId, + InUse: true, + } + options := map[string]string{} + options[OptAddressID] = arId + addr, err := ap.requestAddress("", options) + Expect(err).NotTo(HaveOccurred()) + Expect(addr).NotTo(BeEmpty()) + Expect(ap.addrsByID[arId].ID).To(Equal(arId)) }) + }) - Context("When no available address", func() { - It("Should raise errNoAvailableAddresses", func() { - ap := &addressPool{ - addrsByID: map[string]*addressRecord{}, - } - // ar.InUse is true - ap.addrsByID["10.0.0.1/16"] = &addressRecord{ - ID: "", - InUse: true, - } - // ad.Id != "" - ap.addrsByID["10.0.0.2/16"] = &addressRecord{ - ID: "10.0.0.2/16", - InUse: false, - } - addr, err := ap.requestAddress("", nil) - Expect(err).To(Equal(errNoAvailableAddresses)) - Expect(addr).To(BeEmpty()) - }) + Context("When no available address", func() { + It("Should raise errNoAvailableAddresses", func() { + ap := &addressPool{ + addrsByID: map[string]*addressRecord{}, + } + // ar.InUse is true + ap.addrsByID["10.0.0.1/16"] = &addressRecord{ + ID: "", + InUse: true, + } + // ad.Id != "" + ap.addrsByID["10.0.0.2/16"] = &addressRecord{ + ID: "10.0.0.2/16", + InUse: false, + } + addr, err := ap.requestAddress("", nil) + Expect(err).To(Equal(errNoAvailableAddresses)) + Expect(addr).To(BeEmpty()) }) + }) - Context("Check if the InUse is set to true", func() { - It("InUse should be set to true", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - arId := "10.0.0.1/16" - ap.Addresses[arId] = &addressRecord{ - InUse: false, - } - addr, err := ap.requestAddress("", nil) - Expect(err).NotTo(HaveOccurred()) - Expect(addr).NotTo(BeEmpty()) - Expect(ap.Addresses[arId].InUse).To(BeTrue()) - }) + Context("Check if the InUse is set to true", func() { + It("InUse should be set to true", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + arId := "10.0.0.1/16" + ap.Addresses[arId] = &addressRecord{ + InUse: false, + } + addr, err := ap.requestAddress("", nil) + Expect(err).NotTo(HaveOccurred()) + Expect(addr).NotTo(BeEmpty()) + Expect(ap.Addresses[arId].InUse).To(BeTrue()) }) }) + }) - Describe("Test releaseAddress", func() { - Context("When address is equal to the gateway", func() { - It("Should return nil", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - Gateway: net.IPv4zero, - } - ar := ap.Gateway.String() - err := ap.releaseAddress(ar, nil) - Expect(err).NotTo(HaveOccurred()) - }) + Describe("Test releaseAddress", func() { + Context("When address is equal to the gateway", func() { + It("Should return nil", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + Gateway: net.IPv4zero, + } + ar := ap.Gateway.String() + err := ap.releaseAddress(ar, nil) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When address is equal to the gateway", func() { - It("Should return nil", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - Gateway: net.IPv4zero, - } - ar := ap.Gateway.String() - err := ap.releaseAddress(ar, nil) - Expect(err).NotTo(HaveOccurred()) - }) + Context("When address is equal to the gateway", func() { + It("Should return nil", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + Gateway: net.IPv4zero, + } + ar := ap.Gateway.String() + err := ap.releaseAddress(ar, nil) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When addr is not in use", func() { - It("Should return nil", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - } - ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: false} - err := ap.releaseAddress("10.0.0.1/16", nil) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Addresses["10.0.0.1/16"]).NotTo(BeNil()) - }) + Context("When addr is not in use", func() { + It("Should return nil", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + } + ap.Addresses["10.0.0.1/16"] = &addressRecord{InUse: false} + err := ap.releaseAddress("10.0.0.1/16", nil) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Addresses["10.0.0.1/16"]).NotTo(BeNil()) }) + }) - Context("When delete by id", func() { - It("Should return nil", func() { - ap := &addressPool{ - addrsByID: map[string]*addressRecord{}, - Addresses: map[string]*addressRecord{}, - as: &addressSpace{epoch: 1}, - } - arId := "10.0.0.1/16" - ap.addrsByID[arId] = &addressRecord{ - ID: arId, - Addr: net.IPv4zero, - InUse: true, - epoch: 1, - } - options := map[string]string{} - options[OptAddressID] = arId - err := ap.releaseAddress("", options) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.addrsByID[arId]).To(BeNil()) - }) + Context("When delete by id", func() { + It("Should return nil", func() { + ap := &addressPool{ + addrsByID: map[string]*addressRecord{}, + Addresses: map[string]*addressRecord{}, + as: &addressSpace{epoch: 1}, + } + arId := "10.0.0.1/16" + ap.addrsByID[arId] = &addressRecord{ + ID: arId, + Addr: net.IPv4zero, + InUse: true, + epoch: 1, + } + options := map[string]string{} + options[OptAddressID] = arId + err := ap.releaseAddress("", options) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.addrsByID[arId]).To(BeNil()) }) + }) - Context("When delete by address", func() { - It("Should return nil", func() { - ap := &addressPool{ - Addresses: map[string]*addressRecord{}, - as: &addressSpace{epoch: 2}, - } - ap.Addresses["10.0.0.1/16"] = &addressRecord{ - InUse: true, - epoch: 1, - } - err := ap.releaseAddress("10.0.0.1/16", nil) - Expect(err).NotTo(HaveOccurred()) - Expect(ap.Addresses["10.0.0.1/16"]).To(BeNil()) - }) + Context("When delete by address", func() { + It("Should return nil", func() { + ap := &addressPool{ + Addresses: map[string]*addressRecord{}, + as: &addressSpace{epoch: 2}, + } + ap.Addresses["10.0.0.1/16"] = &addressRecord{ + InUse: true, + epoch: 1, + } + err := ap.releaseAddress("10.0.0.1/16", nil) + Expect(err).NotTo(HaveOccurred()) + Expect(ap.Addresses["10.0.0.1/16"]).To(BeNil()) }) }) }) -) +}) diff --git a/iptables/iptables.go b/iptables/iptables.go index 2f3abf9eb0..dfb02e8682 100644 --- a/iptables/iptables.go +++ b/iptables/iptables.go @@ -81,9 +81,7 @@ const ( AzureDNS = "168.63.129.16" ) -var ( - DisableIPTableLock bool -) +var DisableIPTableLock bool type IPTableEntry struct { Version string @@ -121,6 +119,7 @@ func ChainExists(version, tableName, chainName string) bool { return true } + func GetCreateChainCmd(version, tableName, chainName string) IPTableEntry { return IPTableEntry{ Version: version, diff --git a/log/logger.go b/log/logger.go index 485db76841..9381ca4a65 100644 --- a/log/logger.go +++ b/log/logger.go @@ -34,7 +34,7 @@ const ( // Log file properties. logPrefix = "" logFileExtension = ".log" - logFilePerm = os.FileMode(0664) + logFilePerm = os.FileMode(0o664) // Log file rotation default limits, in bytes. maxLogFileSize = 5 * 1024 * 1024 diff --git a/netlink/ip.go b/netlink/ip.go index 1db1e58c4b..720b141666 100644 --- a/netlink/ip.go +++ b/netlink/ip.go @@ -18,6 +18,7 @@ const ( RT_SCOPE_HOST = 254 RT_SCOPE_NOWHERE = 255 ) + const ( RTPROT_KERNEL = 2 ) diff --git a/netlink/netlink_test.go b/netlink/netlink_test.go index c4630b7eff..48b73536bb 100644 --- a/netlink/netlink_test.go +++ b/netlink/netlink_test.go @@ -24,7 +24,6 @@ func addDummyInterface(name string) (*net.Interface, error) { Name: name, }, }) - if err != nil { return nil, err } @@ -40,7 +39,6 @@ func addDummyInterface(name string) (*net.Interface, error) { // TestEcho tests basic netlink messaging via echo. func TestEcho(t *testing.T) { err := Echo("this is a test") - if err != nil { t.Errorf("Echo failed: %+v", err) } diff --git a/netlink/socket.go b/netlink/socket.go index 25ccdc29c6..d4caf7078e 100644 --- a/netlink/socket.go +++ b/netlink/socket.go @@ -25,8 +25,10 @@ type socket struct { } // Default netlink socket. -var s *socket -var m sync.Mutex +var ( + s *socket + m sync.Mutex +) // Returns a reference to the default netlink socket. func getSocket() (*socket, error) { @@ -114,7 +116,6 @@ func (s *socket) sendAndWaitForAck(msg *message) error { func (s *socket) receive() ([]syscall.NetlinkMessage, error) { buffer := make([]byte, unix.Getpagesize()) n, _, err := unix.Recvfrom(s.fd, buffer, 0) - if err != nil { return nil, err } diff --git a/network/endpoint_test.go b/network/endpoint_test.go index 13bdba5d5b..4b4c744351 100644 --- a/network/endpoint_test.go +++ b/network/endpoint_test.go @@ -15,188 +15,180 @@ func TestEndpoint(t *testing.T) { RunSpecs(t, "Endpoint Suite") } -var ( - _ = Describe("Test Endpoint", func() { - - Describe("Test getEndpoint", func() { - - Context("When endpoint not exists", func() { - It("Should raise errEndpointNotFound", func() { - nw := &network{ - Endpoints: map[string]*endpoint{}, - } - ep, err := nw.getEndpoint("invalid") - Expect(err).To(Equal(errEndpointNotFound)) - Expect(ep).To(BeNil()) - }) +var _ = Describe("Test Endpoint", func() { + Describe("Test getEndpoint", func() { + Context("When endpoint not exists", func() { + It("Should raise errEndpointNotFound", func() { + nw := &network{ + Endpoints: map[string]*endpoint{}, + } + ep, err := nw.getEndpoint("invalid") + Expect(err).To(Equal(errEndpointNotFound)) + Expect(ep).To(BeNil()) }) + }) - Context("When endpoint exists", func() { - It("Should return endpoint with no err", func() { - epId := "epId" - nw := &network{ - Endpoints: map[string]*endpoint{}, - } - nw.Endpoints[epId] = &endpoint{ - Id: epId, - } - ep, err := nw.getEndpoint(epId) - Expect(err).NotTo(HaveOccurred()) - Expect(ep.Id).To(Equal(epId)) - }) + Context("When endpoint exists", func() { + It("Should return endpoint with no err", func() { + epId := "epId" + nw := &network{ + Endpoints: map[string]*endpoint{}, + } + nw.Endpoints[epId] = &endpoint{ + Id: epId, + } + ep, err := nw.getEndpoint(epId) + Expect(err).NotTo(HaveOccurred()) + Expect(ep.Id).To(Equal(epId)) }) }) + }) - Describe("Test getEndpointByPOD", func() { - - Context("When multiple endpoints found", func() { - It("Should raise errMultipleEndpointsFound", func() { - podName := "test" - podNS := "ns" - nw := &network{ - Endpoints: map[string]*endpoint{}, - } - nw.Endpoints["pod1"] = &endpoint{ - PODName: podName, - PODNameSpace: podNS, - } - nw.Endpoints["pod2"] = &endpoint{ - PODName: podName, - PODNameSpace: podNS, - } - ep, err := nw.getEndpointByPOD(podName, podNS, true) - Expect(err).To(Equal(errMultipleEndpointsFound)) - Expect(ep).To(BeNil()) - }) + Describe("Test getEndpointByPOD", func() { + Context("When multiple endpoints found", func() { + It("Should raise errMultipleEndpointsFound", func() { + podName := "test" + podNS := "ns" + nw := &network{ + Endpoints: map[string]*endpoint{}, + } + nw.Endpoints["pod1"] = &endpoint{ + PODName: podName, + PODNameSpace: podNS, + } + nw.Endpoints["pod2"] = &endpoint{ + PODName: podName, + PODNameSpace: podNS, + } + ep, err := nw.getEndpointByPOD(podName, podNS, true) + Expect(err).To(Equal(errMultipleEndpointsFound)) + Expect(ep).To(BeNil()) }) + }) - Context("When endpoint not found", func() { - It("Should raise errEndpointNotFound", func() { - nw := &network{ - Endpoints: map[string]*endpoint{}, - } - ep, err := nw.getEndpointByPOD("invalid", "", false) - Expect(err).To(Equal(errEndpointNotFound)) - Expect(ep).To(BeNil()) - }) + Context("When endpoint not found", func() { + It("Should raise errEndpointNotFound", func() { + nw := &network{ + Endpoints: map[string]*endpoint{}, + } + ep, err := nw.getEndpointByPOD("invalid", "", false) + Expect(err).To(Equal(errEndpointNotFound)) + Expect(ep).To(BeNil()) }) + }) - Context("When one endpoint found", func() { - It("Should return endpoint", func() { - podName := "test" - podNS := "ns" - nw := &network{ - Endpoints: map[string]*endpoint{}, - } - nw.Endpoints["pod"] = &endpoint{ - PODName: podName, - PODNameSpace: podNS, - } - ep, err := nw.getEndpointByPOD(podName, podNS, true) - Expect(err).NotTo(HaveOccurred()) - Expect(ep.PODName).To(Equal(podName)) - }) + Context("When one endpoint found", func() { + It("Should return endpoint", func() { + podName := "test" + podNS := "ns" + nw := &network{ + Endpoints: map[string]*endpoint{}, + } + nw.Endpoints["pod"] = &endpoint{ + PODName: podName, + PODNameSpace: podNS, + } + ep, err := nw.getEndpointByPOD(podName, podNS, true) + Expect(err).NotTo(HaveOccurred()) + Expect(ep.PODName).To(Equal(podName)) }) }) + }) - Describe("Test podNameMatches", func() { - - Context("When doExactMatch flag is set", func() { - It("Should exact match", func() { - actual := "nginx" - valid := "nginx" - invalid := "nginx-deployment-5c689d88bb" - Expect(podNameMatches(valid, actual, true)).To(BeTrue()) - Expect(podNameMatches(invalid, actual, true)).To(BeFalse()) - }) + Describe("Test podNameMatches", func() { + Context("When doExactMatch flag is set", func() { + It("Should exact match", func() { + actual := "nginx" + valid := "nginx" + invalid := "nginx-deployment-5c689d88bb" + Expect(podNameMatches(valid, actual, true)).To(BeTrue()) + Expect(podNameMatches(invalid, actual, true)).To(BeFalse()) }) + }) - Context("When doExactMatch flag is not set", func() { - It("Should not exact match", func() { - actual := "nginx" - valid1 := "nginx" - valid2 := "nginx-deployment-5c689d88bb" - invalid := "nginx-deployment-5c689d88bb-qwq47" - Expect(podNameMatches(valid1, actual, false)).To(BeTrue()) - Expect(podNameMatches(valid2, actual, false)).To(BeTrue()) - Expect(podNameMatches(invalid, actual, false)).To(BeFalse()) - }) + Context("When doExactMatch flag is not set", func() { + It("Should not exact match", func() { + actual := "nginx" + valid1 := "nginx" + valid2 := "nginx-deployment-5c689d88bb" + invalid := "nginx-deployment-5c689d88bb-qwq47" + Expect(podNameMatches(valid1, actual, false)).To(BeTrue()) + Expect(podNameMatches(valid2, actual, false)).To(BeTrue()) + Expect(podNameMatches(invalid, actual, false)).To(BeFalse()) }) }) + }) - Describe("Test attach", func() { - - Context("When SandboxKey in use", func() { - It("Should raise errEndpointInUse", func() { - ep := &endpoint{ - SandboxKey: "key", - } - err := ep.attach("") - Expect(err).To(Equal(errEndpointInUse)) - }) + Describe("Test attach", func() { + Context("When SandboxKey in use", func() { + It("Should raise errEndpointInUse", func() { + ep := &endpoint{ + SandboxKey: "key", + } + err := ep.attach("") + Expect(err).To(Equal(errEndpointInUse)) }) + }) - Context("When SandboxKey not in use", func() { - It("Should set SandboxKey", func() { - sandboxKey := "key" - ep := &endpoint{} - err := ep.attach(sandboxKey) - Expect(err).NotTo(HaveOccurred()) - Expect(ep.SandboxKey).To(Equal(sandboxKey)) - }) + Context("When SandboxKey not in use", func() { + It("Should set SandboxKey", func() { + sandboxKey := "key" + ep := &endpoint{} + err := ep.attach(sandboxKey) + Expect(err).NotTo(HaveOccurred()) + Expect(ep.SandboxKey).To(Equal(sandboxKey)) }) }) + }) - Describe("Test detach", func() { - - Context("When SandboxKey not in use", func() { - It("Should raise errEndpointNotInUse", func() { - ep := &endpoint{} - err := ep.detach() - Expect(err).To(Equal(errEndpointNotInUse)) - }) + Describe("Test detach", func() { + Context("When SandboxKey not in use", func() { + It("Should raise errEndpointNotInUse", func() { + ep := &endpoint{} + err := ep.detach() + Expect(err).To(Equal(errEndpointNotInUse)) }) + }) - Context("When SandboxKey in use", func() { - It("Should set SandboxKey empty", func() { - ep := &endpoint{ - SandboxKey: "key", - } - err := ep.detach() - Expect(err).NotTo(HaveOccurred()) - Expect(ep.SandboxKey).To(BeEmpty()) - }) + Context("When SandboxKey in use", func() { + It("Should set SandboxKey empty", func() { + ep := &endpoint{ + SandboxKey: "key", + } + err := ep.detach() + Expect(err).NotTo(HaveOccurred()) + Expect(ep.SandboxKey).To(BeEmpty()) }) }) + }) - Describe("Test updateEndpoint", func() { - Context("When endpoint not found", func() { - It("Should raise errEndpointNotFound", func() { - nw := &network{} - existingEpInfo := &EndpointInfo{ - Id: "test", - } - targetEpInfo := &EndpointInfo{} - _, err := nw.updateEndpoint(existingEpInfo, targetEpInfo) - Expect(err).To(Equal(errEndpointNotFound)) - }) + Describe("Test updateEndpoint", func() { + Context("When endpoint not found", func() { + It("Should raise errEndpointNotFound", func() { + nw := &network{} + existingEpInfo := &EndpointInfo{ + Id: "test", + } + targetEpInfo := &EndpointInfo{} + _, err := nw.updateEndpoint(existingEpInfo, targetEpInfo) + Expect(err).To(Equal(errEndpointNotFound)) }) }) + }) - Describe("Test GetPodNameWithoutSuffix", func() { - Context("When podnames have suffix or not", func() { - It("Should return podname without suffix", func() { - testData := map[string]string{ - "nginx-deployment-5c689d88bb": "nginx", - "nginx-deployment-5c689d88bb-qwq47": "nginx-deployment", - "nginx": "nginx", - } - for testValue, expectedPodName := range testData { - podName := GetPodNameWithoutSuffix(testValue) - Expect(podName).To(Equal(expectedPodName)) - } - }) + Describe("Test GetPodNameWithoutSuffix", func() { + Context("When podnames have suffix or not", func() { + It("Should return podname without suffix", func() { + testData := map[string]string{ + "nginx-deployment-5c689d88bb": "nginx", + "nginx-deployment-5c689d88bb-qwq47": "nginx-deployment", + "nginx": "nginx", + } + for testValue, expectedPodName := range testData { + podName := GetPodNameWithoutSuffix(testValue) + Expect(podName).To(Equal(expectedPodName)) + } }) }) }) -) +}) diff --git a/network/manager.go b/network/manager.go index 0b910c305f..a19ddb0798 100644 --- a/network/manager.go +++ b/network/manager.go @@ -26,12 +26,10 @@ const ( genericData = "com.docker.network.generic" ) -var ( - Ipv4DefaultRouteDstPrefix = net.IPNet{ - IP: net.IPv4zero, - Mask: net.IPv4Mask(0, 0, 0, 0), - } -) +var Ipv4DefaultRouteDstPrefix = net.IPNet{ + IP: net.IPv4zero, + Mask: net.IPv4Mask(0, 0, 0, 0), +} type NetworkClient interface { CreateBridge() error diff --git a/network/manager_mock.go b/network/manager_mock.go index 6d49722591..8f659c4ab9 100644 --- a/network/manager_mock.go +++ b/network/manager_mock.go @@ -7,13 +7,13 @@ import ( "github.com/Azure/azure-container-networking/common" ) -//MockNetworkManager is a mock structure for Network Manager +// MockNetworkManager is a mock structure for Network Manager type MockNetworkManager struct { TestNetworkInfoMap map[string]*NetworkInfo TestEndpointInfoMap map[string]*EndpointInfo } -//NewMockNetworkmanager returns a new mock +// NewMockNetworkmanager returns a new mock func NewMockNetworkmanager() *MockNetworkManager { return &MockNetworkManager{ TestNetworkInfoMap: make(map[string]*NetworkInfo), @@ -21,31 +21,31 @@ func NewMockNetworkmanager() *MockNetworkManager { } } -//Initialize mock +// Initialize mock func (nm *MockNetworkManager) Initialize(config *common.PluginConfig, isRehydrationRequired bool) error { return nil } -//Uninitialize mock +// Uninitialize mock func (nm *MockNetworkManager) Uninitialize() {} -//AddExternalInterface mock +// AddExternalInterface mock func (nm *MockNetworkManager) AddExternalInterface(ifName string, subnet string) error { return nil } -//CreateNetwork mock +// CreateNetwork mock func (nm *MockNetworkManager) CreateNetwork(nwInfo *NetworkInfo) error { nm.TestNetworkInfoMap[nwInfo.Id] = nwInfo return nil } -//DeleteNetwork mock +// DeleteNetwork mock func (nm *MockNetworkManager) DeleteNetwork(networkID string) error { return nil } -//GetNetworkInfo mock +// GetNetworkInfo mock func (nm *MockNetworkManager) GetNetworkInfo(networkID string) (NetworkInfo, error) { if info, exists := nm.TestNetworkInfoMap[networkID]; exists { return *info, nil @@ -53,13 +53,13 @@ func (nm *MockNetworkManager) GetNetworkInfo(networkID string) (NetworkInfo, err return NetworkInfo{}, fmt.Errorf("Not found") } -//CreateEndpoint mock +// CreateEndpoint mock func (nm *MockNetworkManager) CreateEndpoint(networkID string, epInfo *EndpointInfo) error { nm.TestEndpointInfoMap[epInfo.Id] = epInfo return nil } -//DeleteEndpoint mock +// DeleteEndpoint mock func (nm *MockNetworkManager) DeleteEndpoint(networkID string, endpointID string) error { return nil } @@ -68,37 +68,37 @@ func (nm *MockNetworkManager) GetAllEndpoints(networkID string) (map[string]*End return nm.TestEndpointInfoMap, nil } -//GetEndpointInfo mock +// GetEndpointInfo mock func (nm *MockNetworkManager) GetEndpointInfo(networkID string, endpointID string) (*EndpointInfo, error) { return nm.TestEndpointInfoMap[networkID], nil } -//GetEndpointInfoBasedOnPODDetails mock +// GetEndpointInfoBasedOnPODDetails mock func (nm *MockNetworkManager) GetEndpointInfoBasedOnPODDetails(networkID string, podName string, podNameSpace string, doExactMatchForPodName bool) (*EndpointInfo, error) { return &EndpointInfo{}, nil } -//AttachEndpoint mock +// AttachEndpoint mock func (nm *MockNetworkManager) AttachEndpoint(networkID string, endpointID string, sandboxKey string) (*endpoint, error) { return &endpoint{}, nil } -//DetachEndpoint mock +// DetachEndpoint mock func (nm *MockNetworkManager) DetachEndpoint(networkID string, endpointID string) error { return nil } -//UpdateEndpoint mock +// UpdateEndpoint mock func (nm *MockNetworkManager) UpdateEndpoint(networkID string, existingEpInfo *EndpointInfo, targetEpInfo *EndpointInfo) error { return nil } -//GetNumberOfEndpoints mock +// GetNumberOfEndpoints mock func (nm *MockNetworkManager) GetNumberOfEndpoints(ifName string, networkID string) int { return 0 } -//SetupNetworkUsingState mock +// SetupNetworkUsingState mock func (nm *MockNetworkManager) SetupNetworkUsingState(networkMonitor *cnms.NetworkMonitor) error { return nil } diff --git a/network/manager_test.go b/network/manager_test.go index 0040ebd855..567ef7c30c 100644 --- a/network/manager_test.go +++ b/network/manager_test.go @@ -17,219 +17,213 @@ func TestManager(t *testing.T) { RunSpecs(t, "Manager Suite") } -var ( - _ = Describe("Test Manager", func() { - - Describe("Test deleteExternalInterface", func() { - - Context("When external interface not found", func() { - It("Should return nil", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - err := nm.deleteExternalInterface(ifName) - Expect(err).NotTo(HaveOccurred()) - }) +var _ = Describe("Test Manager", func() { + Describe("Test deleteExternalInterface", func() { + Context("When external interface not found", func() { + It("Should return nil", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + err := nm.deleteExternalInterface(ifName) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When external interface found", func() { - It("Should delete external interface", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{} - err := nm.deleteExternalInterface(ifName) - Expect(err).NotTo(HaveOccurred()) - }) + Context("When external interface found", func() { + It("Should delete external interface", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{} + err := nm.deleteExternalInterface(ifName) + Expect(err).NotTo(HaveOccurred()) }) }) + }) - Describe("Test restore", func() { - - Context("When restore is nil", func() { - It("Should return nil", func() { - nm := &networkManager{} - err := nm.restore(false) - Expect(err).NotTo(HaveOccurred()) - }) + Describe("Test restore", func() { + Context("When restore is nil", func() { + It("Should return nil", func() { + nm := &networkManager{} + err := nm.restore(false) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When store.Read return ErrKeyNotFound", func() { - It("Should return nil", func() { - nm := &networkManager{ - store: &testutils.KeyValueStoreMock{ - ReadError: store.ErrKeyNotFound, - }, - } - err := nm.restore(false) - Expect(err).NotTo(HaveOccurred()) - }) + Context("When store.Read return ErrKeyNotFound", func() { + It("Should return nil", func() { + nm := &networkManager{ + store: &testutils.KeyValueStoreMock{ + ReadError: store.ErrKeyNotFound, + }, + } + err := nm.restore(false) + Expect(err).NotTo(HaveOccurred()) }) + }) - Context("When store.Read return error", func() { - It("Should raise error", func() { - nm := &networkManager{ - store: &testutils.KeyValueStoreMock{ - ReadError: errors.New("error for test"), - }, - } - err := nm.restore(false) - Expect(err).To(HaveOccurred()) - }) + Context("When store.Read return error", func() { + It("Should raise error", func() { + nm := &networkManager{ + store: &testutils.KeyValueStoreMock{ + ReadError: errors.New("error for test"), + }, + } + err := nm.restore(false) + Expect(err).To(HaveOccurred()) }) + }) - Context("When GetModificationTime error and not rebooted", func() { - It("Should populate pointers", func() { - extIfName := "eth0" - nwId := "nwId" - nm := &networkManager{ - store: &testutils.KeyValueStoreMock{ - GetModificationTimeError: errors.New("error for test"), - }, - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[extIfName] = &externalInterface{ - Name: extIfName, - Networks: map[string]*network{}, - } - nm.ExternalInterfaces[extIfName].Networks[nwId] = &network{} - err := nm.restore(false) - Expect(err).NotTo(HaveOccurred()) - Expect(nm.ExternalInterfaces[extIfName].Networks[nwId].extIf.Name).To(Equal(extIfName)) - }) + Context("When GetModificationTime error and not rebooted", func() { + It("Should populate pointers", func() { + extIfName := "eth0" + nwId := "nwId" + nm := &networkManager{ + store: &testutils.KeyValueStoreMock{ + GetModificationTimeError: errors.New("error for test"), + }, + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[extIfName] = &externalInterface{ + Name: extIfName, + Networks: map[string]*network{}, + } + nm.ExternalInterfaces[extIfName].Networks[nwId] = &network{} + err := nm.restore(false) + Expect(err).NotTo(HaveOccurred()) + Expect(nm.ExternalInterfaces[extIfName].Networks[nwId].extIf.Name).To(Equal(extIfName)) }) }) + }) - Describe("Test save", func() { - Context("When store is nil", func() { - It("Should return nil", func() { - nm := &networkManager{} - err := nm.save() - Expect(err).NotTo(HaveOccurred()) - Expect(nm.TimeStamp).To(Equal(time.Time{})) - }) + Describe("Test save", func() { + Context("When store is nil", func() { + It("Should return nil", func() { + nm := &networkManager{} + err := nm.save() + Expect(err).NotTo(HaveOccurred()) + Expect(nm.TimeStamp).To(Equal(time.Time{})) }) - Context("When store.Write return error", func() { - It("Should raise error", func() { - nm := &networkManager{ - store: &testutils.KeyValueStoreMock{ - WriteError: errors.New("error for test"), - }, - } - err := nm.save() - Expect(err).To(HaveOccurred()) - Expect(nm.TimeStamp).NotTo(Equal(time.Time{})) - }) + }) + Context("When store.Write return error", func() { + It("Should raise error", func() { + nm := &networkManager{ + store: &testutils.KeyValueStoreMock{ + WriteError: errors.New("error for test"), + }, + } + err := nm.save() + Expect(err).To(HaveOccurred()) + Expect(nm.TimeStamp).NotTo(Equal(time.Time{})) }) }) + }) - Describe("Test GetNumberOfEndpoints", func() { - - Context("When ExternalInterfaces is nil", func() { - It("Should return 0", func() { - nm := &networkManager{} - num := nm.GetNumberOfEndpoints("", "") - Expect(num).To(Equal(0)) - }) + Describe("Test GetNumberOfEndpoints", func() { + Context("When ExternalInterfaces is nil", func() { + It("Should return 0", func() { + nm := &networkManager{} + num := nm.GetNumberOfEndpoints("", "") + Expect(num).To(Equal(0)) }) + }) - Context("When extIf not found", func() { - It("Should return 0", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - num := nm.GetNumberOfEndpoints("eth0", "") - Expect(num).To(Equal(0)) - }) + Context("When extIf not found", func() { + It("Should return 0", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + num := nm.GetNumberOfEndpoints("eth0", "") + Expect(num).To(Equal(0)) }) + }) - Context("When Networks is nil", func() { - It("Should return 0", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{} - num := nm.GetNumberOfEndpoints(ifName, "") - Expect(num).To(Equal(0)) - }) + Context("When Networks is nil", func() { + It("Should return 0", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{} + num := nm.GetNumberOfEndpoints(ifName, "") + Expect(num).To(Equal(0)) }) + }) - Context("When network not found", func() { - It("Should return 0", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Networks: map[string]*network{}, - } - num := nm.GetNumberOfEndpoints(ifName, "nwId") - Expect(num).To(Equal(0)) - }) + Context("When network not found", func() { + It("Should return 0", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Networks: map[string]*network{}, + } + num := nm.GetNumberOfEndpoints(ifName, "nwId") + Expect(num).To(Equal(0)) }) + }) - Context("When endpoints is nil", func() { - It("Should return 0", func() { - ifName := "eth0" - nwId := "nwId" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Networks: map[string]*network{}, - } - nm.ExternalInterfaces[ifName].Networks[nwId] = &network{} - num := nm.GetNumberOfEndpoints(ifName, nwId) - Expect(num).To(Equal(0)) - }) + Context("When endpoints is nil", func() { + It("Should return 0", func() { + ifName := "eth0" + nwId := "nwId" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Networks: map[string]*network{}, + } + nm.ExternalInterfaces[ifName].Networks[nwId] = &network{} + num := nm.GetNumberOfEndpoints(ifName, nwId) + Expect(num).To(Equal(0)) }) + }) - Context("When endpoints is found", func() { - It("Should return the length of endpoints", func() { - ifName := "eth0" - nwId := "nwId" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Networks: map[string]*network{}, - } - nm.ExternalInterfaces[ifName].Networks[nwId] = &network{ - Endpoints: map[string]*endpoint{ - "ep1": &endpoint{}, - "ep2": &endpoint{}, - "ep3": &endpoint{}, - }, - } - num := nm.GetNumberOfEndpoints(ifName, nwId) - Expect(num).To(Equal(3)) - }) + Context("When endpoints is found", func() { + It("Should return the length of endpoints", func() { + ifName := "eth0" + nwId := "nwId" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Networks: map[string]*network{}, + } + nm.ExternalInterfaces[ifName].Networks[nwId] = &network{ + Endpoints: map[string]*endpoint{ + "ep1": {}, + "ep2": {}, + "ep3": {}, + }, + } + num := nm.GetNumberOfEndpoints(ifName, nwId) + Expect(num).To(Equal(3)) }) + }) - Context("When ifName not specifed in GetNumberofEndpoints", func() { - It("Should range the nm.ExternalInterfaces", func() { - ifName := "eth0" - nwId := "nwId" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Networks: map[string]*network{}, - } - nm.ExternalInterfaces[ifName].Networks[nwId] = &network{ - Endpoints: map[string]*endpoint{ - "ep1": &endpoint{}, - "ep2": &endpoint{}, - "ep3": &endpoint{}, - }, - } - num := nm.GetNumberOfEndpoints("", nwId) - Expect(num).To(Equal(3)) - }) + Context("When ifName not specifed in GetNumberofEndpoints", func() { + It("Should range the nm.ExternalInterfaces", func() { + ifName := "eth0" + nwId := "nwId" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Networks: map[string]*network{}, + } + nm.ExternalInterfaces[ifName].Networks[nwId] = &network{ + Endpoints: map[string]*endpoint{ + "ep1": {}, + "ep2": {}, + "ep3": {}, + }, + } + num := nm.GetNumberOfEndpoints("", nwId) + Expect(num).To(Equal(3)) }) }) }) -) +}) diff --git a/network/network_test.go b/network/network_test.go index 9fdebcd792..ec4f691843 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -13,184 +13,181 @@ func TestNetwork(t *testing.T) { RunSpecs(t, "Network Suite") } -var ( - _ = Describe("Test Network", func() { - - Describe("Test newExternalInterface", func() { - Context("When external interface already exists", func() { - It("Should return nil without update", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Name: ifName, - Subnets: []string{"10.0.0.0/16"}, - } - err := nm.newExternalInterface(ifName, "10.1.0.0/16") - Expect(err).To(BeNil()) - Expect(nm.ExternalInterfaces[ifName].Subnets).To(ContainElement("10.0.0.0/16")) - Expect(nm.ExternalInterfaces[ifName].Subnets).NotTo(ContainElement("10.1.0.0/16")) - }) +var _ = Describe("Test Network", func() { + Describe("Test newExternalInterface", func() { + Context("When external interface already exists", func() { + It("Should return nil without update", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Name: ifName, + Subnets: []string{"10.0.0.0/16"}, + } + err := nm.newExternalInterface(ifName, "10.1.0.0/16") + Expect(err).To(BeNil()) + Expect(nm.ExternalInterfaces[ifName].Subnets).To(ContainElement("10.0.0.0/16")) + Expect(nm.ExternalInterfaces[ifName].Subnets).NotTo(ContainElement("10.1.0.0/16")) }) }) + }) - Describe("Test deleteExternalInterface", func() { - Context("Delete external interface from network manager", func() { - It("Interface should be deleted", func() { - ifName := "eth0" - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces[ifName] = &externalInterface{ - Name: ifName, - Subnets: []string{"10.0.0.0/16", "10.1.0.0/16"}, - } - err := nm.deleteExternalInterface(ifName) - Expect(err).NotTo(HaveOccurred()) - Expect(nm.ExternalInterfaces[ifName]).To(BeNil()) - }) + Describe("Test deleteExternalInterface", func() { + Context("Delete external interface from network manager", func() { + It("Interface should be deleted", func() { + ifName := "eth0" + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces[ifName] = &externalInterface{ + Name: ifName, + Subnets: []string{"10.0.0.0/16", "10.1.0.0/16"}, + } + err := nm.deleteExternalInterface(ifName) + Expect(err).NotTo(HaveOccurred()) + Expect(nm.ExternalInterfaces[ifName]).To(BeNil()) }) }) + }) - Describe("Test findExternalInterfaceBySubnet", func() { - Context("When subnet was found or nor found in external interfaces", func() { - It("Should return the external interface when found and nil when not found", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces["eth0"] = &externalInterface{ - Name: "eth0", - Subnets: []string{"subnet1", "subnet2"}, - } - nm.ExternalInterfaces["en0"] = &externalInterface{ - Name: "en0", - Subnets: []string{"subnet3", "subnet4"}, - } - exInterface := nm.findExternalInterfaceBySubnet("subnet4") - Expect(exInterface.Name).To(Equal("en0")) - exInterface = nm.findExternalInterfaceBySubnet("subnet0") - Expect(exInterface).To(BeNil()) - }) + Describe("Test findExternalInterfaceBySubnet", func() { + Context("When subnet was found or nor found in external interfaces", func() { + It("Should return the external interface when found and nil when not found", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces["eth0"] = &externalInterface{ + Name: "eth0", + Subnets: []string{"subnet1", "subnet2"}, + } + nm.ExternalInterfaces["en0"] = &externalInterface{ + Name: "en0", + Subnets: []string{"subnet3", "subnet4"}, + } + exInterface := nm.findExternalInterfaceBySubnet("subnet4") + Expect(exInterface.Name).To(Equal("en0")) + exInterface = nm.findExternalInterfaceBySubnet("subnet0") + Expect(exInterface).To(BeNil()) }) }) + }) - Describe("Test findExternalInterfaceByName", func() { - Context("When ifName found or nor found", func() { - It("Should return the external interface when found and nil when not found", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces["eth0"] = &externalInterface{ - Name: "eth0", - } - nm.ExternalInterfaces["en0"] = nil - exInterface := nm.findExternalInterfaceByName("eth0") - Expect(exInterface.Name).To(Equal("eth0")) - exInterface = nm.findExternalInterfaceByName("en0") - Expect(exInterface).To(BeNil()) - exInterface = nm.findExternalInterfaceByName("lo") - Expect(exInterface).To(BeNil()) - }) + Describe("Test findExternalInterfaceByName", func() { + Context("When ifName found or nor found", func() { + It("Should return the external interface when found and nil when not found", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces["eth0"] = &externalInterface{ + Name: "eth0", + } + nm.ExternalInterfaces["en0"] = nil + exInterface := nm.findExternalInterfaceByName("eth0") + Expect(exInterface.Name).To(Equal("eth0")) + exInterface = nm.findExternalInterfaceByName("en0") + Expect(exInterface).To(BeNil()) + exInterface = nm.findExternalInterfaceByName("lo") + Expect(exInterface).To(BeNil()) }) }) + }) - Describe("Test newNetwork", func() { - Context("When nwInfo.Mode is empty", func() { - It("Should set as defalut mode", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nwInfo := &NetworkInfo{ - MasterIfName: "eth0", - } - _, _ = nm.newNetwork(nwInfo) - Expect(nwInfo.Mode).To(Equal(opModeDefault)) - }) + Describe("Test newNetwork", func() { + Context("When nwInfo.Mode is empty", func() { + It("Should set as defalut mode", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nwInfo := &NetworkInfo{ + MasterIfName: "eth0", + } + _, _ = nm.newNetwork(nwInfo) + Expect(nwInfo.Mode).To(Equal(opModeDefault)) }) + }) - Context("When extIf not found by name", func() { - It("Should raise errSubnetNotFound", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nwInfo := &NetworkInfo{ - MasterIfName: "eth0", - } - nw, err := nm.newNetwork(nwInfo) - Expect(err).To(Equal(errSubnetNotFound)) - Expect(nw).To(BeNil()) - }) + Context("When extIf not found by name", func() { + It("Should raise errSubnetNotFound", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nwInfo := &NetworkInfo{ + MasterIfName: "eth0", + } + nw, err := nm.newNetwork(nwInfo) + Expect(err).To(Equal(errSubnetNotFound)) + Expect(nw).To(BeNil()) }) + }) - Context("When extIf not found by subnet", func() { - It("Should raise errSubnetNotFound", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nwInfo := &NetworkInfo{ - Subnets: []SubnetInfo{{ - Prefix: net.IPNet{ - IP: net.IPv4(10, 0, 0, 1), - Mask: net.IPv4Mask(255, 255, 0, 0), - }, - }}, - } - nw, err := nm.newNetwork(nwInfo) - Expect(err).To(Equal(errSubnetNotFound)) - Expect(nw).To(BeNil()) - }) + Context("When extIf not found by subnet", func() { + It("Should raise errSubnetNotFound", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nwInfo := &NetworkInfo{ + Subnets: []SubnetInfo{{ + Prefix: net.IPNet{ + IP: net.IPv4(10, 0, 0, 1), + Mask: net.IPv4Mask(255, 255, 0, 0), + }, + }}, + } + nw, err := nm.newNetwork(nwInfo) + Expect(err).To(Equal(errSubnetNotFound)) + Expect(nw).To(BeNil()) }) + }) - Context("When network already exist", func() { - It("Should raise errNetworkExists", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces["eth0"] = &externalInterface{ - Networks: map[string]*network{}, - } - nm.ExternalInterfaces["eth0"].Networks["nw"] = &network{} - nwInfo := &NetworkInfo{ - Id: "nw", - MasterIfName: "eth0", - } - nw, err := nm.newNetwork(nwInfo) - Expect(err).To(Equal(errNetworkExists)) - Expect(nw).To(BeNil()) - }) + Context("When network already exist", func() { + It("Should raise errNetworkExists", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces["eth0"] = &externalInterface{ + Networks: map[string]*network{}, + } + nm.ExternalInterfaces["eth0"].Networks["nw"] = &network{} + nwInfo := &NetworkInfo{ + Id: "nw", + MasterIfName: "eth0", + } + nw, err := nm.newNetwork(nwInfo) + Expect(err).To(Equal(errNetworkExists)) + Expect(nw).To(BeNil()) }) }) + }) - Describe("Test deleteNetwork", func() { - Context("When network not found", func() { - It("Should raise errNetworkNotFound", func() { - nm := &networkManager{} - err := nm.deleteNetwork("invalid") - Expect(err).To(Equal(errNetworkNotFound)) - }) + Describe("Test deleteNetwork", func() { + Context("When network not found", func() { + It("Should raise errNetworkNotFound", func() { + nm := &networkManager{} + err := nm.deleteNetwork("invalid") + Expect(err).To(Equal(errNetworkNotFound)) }) }) + }) - Describe("Test getNetwork", func() { - Context("When network found or nor found", func() { - It("Should return the network when found and nil when not found", func() { - nm := &networkManager{ - ExternalInterfaces: map[string]*externalInterface{}, - } - nm.ExternalInterfaces["eth0"] = &externalInterface{ - Name: "eth0", - Networks: map[string]*network{}, - } - nm.ExternalInterfaces["eth0"].Networks["nw1"] = &network{} - nw, err := nm.getNetwork("nw1") - Expect(err).NotTo(HaveOccurred()) - Expect(nw).NotTo(BeNil()) - nw, err = nm.getNetwork("invalid") - Expect(err).To(Equal(errNetworkNotFound)) - Expect(nw).To(BeNil()) - }) + Describe("Test getNetwork", func() { + Context("When network found or nor found", func() { + It("Should return the network when found and nil when not found", func() { + nm := &networkManager{ + ExternalInterfaces: map[string]*externalInterface{}, + } + nm.ExternalInterfaces["eth0"] = &externalInterface{ + Name: "eth0", + Networks: map[string]*network{}, + } + nm.ExternalInterfaces["eth0"].Networks["nw1"] = &network{} + nw, err := nm.getNetwork("nw1") + Expect(err).NotTo(HaveOccurred()) + Expect(nw).NotTo(BeNil()) + nw, err = nm.getNetwork("invalid") + Expect(err).To(Equal(errNetworkNotFound)) + Expect(nw).To(BeNil()) }) }) }) -) +}) diff --git a/network/network_windows.go b/network/network_windows.go index c003032f12..843b9c8d86 100644 --- a/network/network_windows.go +++ b/network/network_windows.go @@ -216,7 +216,7 @@ func (nm *networkManager) configureHcnNetwork(nwInfo *NetworkInfo, extIf *extern ServerList: nwInfo.DNS.Servers, }, Ipams: []hcn.Ipam{ - hcn.Ipam{ + { Type: hcnIpamTypeStatic, }, }, @@ -285,7 +285,7 @@ func (nm *networkManager) configureHcnNetwork(nwInfo *NetworkInfo, extIf *extern IpAddressPrefix: subnet.Prefix.String(), // Set the Gateway route Routes: []hcn.Route{ - hcn.Route{ + { NextHop: subnet.Gateway.String(), DestinationPrefix: defaultRouteCIDR, }, @@ -314,7 +314,6 @@ func (nm *networkManager) newNetworkImplHnsV2(nwInfo *NetworkInfo, extIf *extern // Create the HNS network. log.Printf("[net] Creating hcn network: %+v", hcnNetwork) hnsResponse, err := hcnNetwork.Create() - if err != nil { return nil, fmt.Errorf("Failed to create hcn network: %s due to error: %v", hcnNetwork.Name, err) } diff --git a/network/ovs_endpointclient_linux.go b/network/ovs_endpointclient_linux.go index 1fac3e7fea..a70049982a 100644 --- a/network/ovs_endpointclient_linux.go +++ b/network/ovs_endpointclient_linux.go @@ -180,11 +180,9 @@ func (client *OVSEndpointClient) MoveEndpointsToContainerNS(epInfo *EndpointInfo } return MoveInfraEndpointToContainerNS(client, epInfo.NetNsPath, nsID) - } func (client *OVSEndpointClient) SetupContainerInterfaces(epInfo *EndpointInfo) error { - if err := epcommon.SetupContainerInterface(client.containerVethName, epInfo.IfName); err != nil { return err } diff --git a/network/ovs_networkclient_linux.go b/network/ovs_networkclient_linux.go index dc48b72ed4..83cfa8b248 100644 --- a/network/ovs_networkclient_linux.go +++ b/network/ovs_networkclient_linux.go @@ -21,7 +21,7 @@ const ( ) func updateOVSConfig(option string) error { - f, err := os.OpenFile(ovsConfigFile, os.O_APPEND|os.O_RDWR, 0666) + f, err := os.OpenFile(ovsConfigFile, os.O_APPEND|os.O_RDWR, 0o666) if err != nil { log.Printf("Error while opening ovs config %v", err) return err diff --git a/network/ovsinfravnet/infravnet.go b/network/ovsinfravnet/infravnet.go index df22fa399b..3599abfae3 100644 --- a/network/ovsinfravnet/infravnet.go +++ b/network/ovsinfravnet/infravnet.go @@ -1,11 +1,11 @@ package ovsinfravnet import ( + "net" + "github.com/Azure/azure-container-networking/log" "github.com/Azure/azure-container-networking/netlink" - "net" - "github.com/Azure/azure-container-networking/network/epcommon" "github.com/Azure/azure-container-networking/ovsctl" ) diff --git a/network/policy/policy_windows.go b/network/policy/policy_windows.go index 03055320e2..ca425dce63 100644 --- a/network/policy/policy_windows.go +++ b/network/policy/policy_windows.go @@ -442,7 +442,8 @@ func GetHcnEndpointPolicies(policyType CNIPolicyType, policies []Policy, epInfoD func AddDnsNATPolicyV1() (json.RawMessage, error) { outBoundNatPolicy := hcsshim.OutboundNatPolicy{ Policy: hcsshim.Policy{Type: hcsshim.OutboundNat}, - Destinations: []string{"168.63.129.16"}} + Destinations: []string{"168.63.129.16"}, + } serializedPolicy, err := json.Marshal(outBoundNatPolicy) return serializedPolicy, err } @@ -453,6 +454,7 @@ func AddDnsNATPolicyV2() (hcn.EndpointPolicy, error) { outBoundNatPolicySettingsBytes, err := json.Marshal(outBoundNatPolicySettings) endpointPolicy := hcn.EndpointPolicy{ Type: hcn.OutBoundNAT, - Settings: outBoundNatPolicySettingsBytes} + Settings: outBoundNatPolicySettingsBytes, + } return endpointPolicy, err } diff --git a/network/transparent_endpointclient_linux.go b/network/transparent_endpointclient_linux.go index 5f7d2b9fd9..753582ad4d 100644 --- a/network/transparent_endpointclient_linux.go +++ b/network/transparent_endpointclient_linux.go @@ -53,7 +53,6 @@ func setArpProxy(ifName string) error { } func (client *TransparentEndpointClient) AddEndpoints(epInfo *EndpointInfo) error { - if _, err := net.InterfaceByName(client.hostVethName); err == nil { log.Printf("Deleting old host veth %v", client.hostVethName) if err = netlink.DeleteLink(client.hostVethName); err != nil { @@ -148,7 +147,7 @@ func (client *TransparentEndpointClient) ConfigureContainerInterfacesAndRoutes(e return err } - //ip route del 10.240.0.0/12 dev eth0 (removing kernel subnet route added by above call) + // ip route del 10.240.0.0/12 dev eth0 (removing kernel subnet route added by above call) for _, ipAddr := range epInfo.IPAddresses { _, ipnet, _ := net.ParseCIDR(ipAddr.String()) routeInfo := RouteInfo{ @@ -161,8 +160,8 @@ func (client *TransparentEndpointClient) ConfigureContainerInterfacesAndRoutes(e } } - //add route for virtualgwip - //ip route add 169.254.1.1/32 dev eth0 + // add route for virtualgwip + // ip route add 169.254.1.1/32 dev eth0 virtualGwIP, virtualGwNet, _ := net.ParseCIDR(virtualGwIPString) routeInfo := RouteInfo{ Dst: *virtualGwNet, @@ -172,7 +171,7 @@ func (client *TransparentEndpointClient) ConfigureContainerInterfacesAndRoutes(e return err } - //ip route add default via 169.254.1.1 dev eth0 + // ip route add default via 169.254.1.1 dev eth0 _, defaultIPNet, _ := net.ParseCIDR(defaultGwCidr) dstIP := net.IPNet{IP: net.ParseIP(defaultGw), Mask: defaultIPNet.Mask} routeInfo = RouteInfo{ @@ -183,7 +182,7 @@ func (client *TransparentEndpointClient) ConfigureContainerInterfacesAndRoutes(e return err } - //arp -s 169.254.1.1 e3:45:f4:ac:34:12 - add static arp entry for virtualgwip to hostveth interface mac + // arp -s 169.254.1.1 e3:45:f4:ac:34:12 - add static arp entry for virtualgwip to hostveth interface mac log.Printf("[net] Adding static arp for IP address %v and MAC %v in Container namespace", virtualGwNet.String(), client.hostVethMac) return netlink.AddOrRemoveStaticArp(netlink.ADD, client.containerVethName, virtualGwNet.IP, client.hostVethMac, false) } diff --git a/nns/grpcclient.go b/nns/grpcclient.go index af5f77057c..012731baf4 100644 --- a/nns/grpcclient.go +++ b/nns/grpcclient.go @@ -3,10 +3,11 @@ package nns import ( "context" "fmt" + "time" + "github.com/Azure/azure-container-networking/log" contracts "github.com/Azure/azure-container-networking/proto/nodenetworkservice/3.302.0.744" "google.golang.org/grpc" - "time" ) const ( @@ -16,8 +17,7 @@ const ( ) // client to invoke Node network service APIs using grpc -type GrpcClient struct { -} +type GrpcClient struct{} // Add container to the network. Container Id is appended to the podName func (c *GrpcClient) AddContainerNetworking( @@ -80,7 +80,6 @@ func configureContainerNetworking( // create a connection to the node network service listening at localhost:6678 // and return nns client that encapsulates that connection func newGrpcClient(ctx context.Context) (contracts.NodeNetworkServiceClient, *grpc.ClientConn, error) { - localCtx, cancel := context.WithTimeout(ctx, connectionTimeout) defer cancel() diff --git a/nns/grpcclient_test.go b/nns/grpcclient_test.go index e2d7ff80b9..efbc8efa51 100644 --- a/nns/grpcclient_test.go +++ b/nns/grpcclient_test.go @@ -3,11 +3,12 @@ package nns import ( "context" "fmt" - "github.com/Azure/azure-container-networking/test/nnsmockserver" "os" "strings" "testing" "time" + + "github.com/Azure/azure-container-networking/test/nnsmockserver" ) var mockserver *nnsmockserver.NnsMockServer @@ -32,7 +33,6 @@ func teardown() { // CNI ADD to add container to network func TestAddContainerNetworking(t *testing.T) { - client := &GrpcClient{} if err, _ := client.AddContainerNetworking( context.Background(), @@ -44,7 +44,6 @@ func TestAddContainerNetworking(t *testing.T) { // CNI DEL to delete container from network func TestDeleteContainerNetworking(t *testing.T) { - client := &GrpcClient{} if err, _ := client.DeleteContainerNetworking( context.Background(), @@ -56,7 +55,6 @@ func TestDeleteContainerNetworking(t *testing.T) { // CNI ADD to add container to network - failure case func TestAddContainerNetworkingFailure(t *testing.T) { - client := &GrpcClient{} var err error @@ -71,7 +69,6 @@ func TestAddContainerNetworkingFailure(t *testing.T) { // CNI DEL to add container to network - failure case func TestDeleteContainerNetworkingFailure(t *testing.T) { - client := &GrpcClient{} var err error @@ -86,7 +83,6 @@ func TestDeleteContainerNetworkingFailure(t *testing.T) { // CNI ADD to add container to network - grpc server was down temporarily and client reconnects well func TestAddContainerNetworkingGrpcServerDown(t *testing.T) { - // shutdown server to simulate connection error teardown() @@ -101,7 +97,6 @@ func TestAddContainerNetworkingGrpcServerDown(t *testing.T) { var err error if err, _ = client.AddContainerNetworking( context.Background(), "sf_8e9961f4-5b4f-4b3c-a9ae-c3294b0d9681", "testnwspace"); err != nil { - t.Fatalf("TestAddContainerNetworkingGrpcServerDown failed. %s", err) } } diff --git a/nns/mockgrpcclient.go b/nns/mockgrpcclient.go index 8976e30f64..371144b7be 100644 --- a/nns/mockgrpcclient.go +++ b/nns/mockgrpcclient.go @@ -2,12 +2,12 @@ package nns import ( "context" + contracts "github.com/Azure/azure-container-networking/proto/nodenetworkservice/3.302.0.744" ) // Mock client to simulate Node network service APIs -type MockGrpcClient struct { -} +type MockGrpcClient struct{} // Add container to the network. Container Id is appended to the podName func (c *MockGrpcClient) AddContainerNetworking( diff --git a/npm/http/api/api.go b/npm/http/api/api.go index 5a7aa37137..195364a655 100644 --- a/npm/http/api/api.go +++ b/npm/http/api/api.go @@ -8,8 +8,6 @@ const ( NPMMgrPath = "/npm/v1/debug/manager" ) -type DescribeIPSetRequest struct { -} +type DescribeIPSetRequest struct{} -type DescribeIPSetResponse struct { -} +type DescribeIPSetResponse struct{} diff --git a/npm/http/server/server.go b/npm/http/server/server.go index d4e18964e5..56706959d9 100644 --- a/npm/http/server/server.go +++ b/npm/http/server/server.go @@ -26,7 +26,7 @@ func NPMRestServerListenAndServe(config npmconfig.Config, npmEncoder npm.Network rs.router = mux.NewRouter() - //prometheus handlers + // prometheus handlers if config.Toggles.EnablePrometheusMetrics { rs.router.Handle(api.NodeMetricsPath, metrics.GetHandler(true)) rs.router.Handle(api.ClusterMetricsPath, metrics.GetHandler(false)) diff --git a/npm/ipsm/ipsm_test.go b/npm/ipsm/ipsm_test.go index 96ae499735..d18f1a2f4d 100644 --- a/npm/ipsm/ipsm_test.go +++ b/npm/ipsm/ipsm_test.go @@ -15,7 +15,7 @@ import ( ) func TestCreateList(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-list"), "setlist"}}, } @@ -28,7 +28,7 @@ func TestCreateList(t *testing.T) { } func TestDeleteList(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-list"), "setlist"}}, {Cmd: []string{"ipset", "-X", "-exist", util.GetHashedName("test-list")}}, } @@ -45,7 +45,7 @@ func TestDeleteList(t *testing.T) { } func TestAddToList(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-set"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-list"), "setlist"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName("test-list"), util.GetHashedName("test-set")}}, @@ -60,11 +60,10 @@ func TestAddToList(t *testing.T) { err = ipsMgr.AddToList("test-list", "test-set") require.NoError(t, err) - } func TestDeleteFromList(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-set"), "nethash"}}, {Cmd: []string{"ipset", "list", "-exist", util.GetHashedName("test-set")}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-list"), "setlist"}}, @@ -166,7 +165,7 @@ func TestCreateSet(t *testing.T) { testSet3Name = "test-set-with-port" ) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSet1Name), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSet2Name), "nethash", "maxelem", "4294967295"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSet3Name), "hash:ip,port"}}, @@ -222,7 +221,7 @@ func TestCreateSet(t *testing.T) { func TestDeleteSet(t *testing.T) { metrics.NumIPSetEntries.Set(0) testSetName := "test-delete-set" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSetName), "nethash"}}, {Cmd: []string{"ipset", "-X", "-exist", util.GetHashedName(testSetName)}}, } @@ -255,7 +254,7 @@ func TestAddToSet(t *testing.T) { metrics.NumIPSetEntries.Set(0) testSetName := "test-set" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSetName), "nethash"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(testSetName), "1.2.3.4"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(testSetName), "1.2.3.4/", "nomatch"}}, @@ -299,12 +298,12 @@ func TestAddToSet(t *testing.T) { } func TestAddToSetWithCachePodInfo(t *testing.T) { - var pod1 = "pod1" - var setname = "test-podcache_new" - var ip = "10.0.2.7" - var pod2 = "pod2" + pod1 := "pod1" + setname := "test-podcache_new" + ip := "10.0.2.7" + pod2 := "pod2" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(setname), "nethash"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(setname), ip}}, {Cmd: []string{"ipset", "-D", "-exist", util.GetHashedName(setname), ip}}, @@ -346,7 +345,7 @@ func TestDeleteFromSet(t *testing.T) { metrics.NumIPSetEntries.Set(0) testSetName := "test-delete-from-set" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(testSetName), "nethash"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(testSetName), "1.2.3.4"}}, {Cmd: []string{"ipset", "-D", "-exist", util.GetHashedName(testSetName), "1.2.3.4"}}, @@ -381,12 +380,12 @@ func TestDeleteFromSet(t *testing.T) { } func TestDeleteFromSetWithPodCache(t *testing.T) { - var setname = "test-deleteset-withcache" - var ip = "10.0.2.8" - var pod1 = "pod1" - var pod2 = "pod2" + setname := "test-deleteset-withcache" + ip := "10.0.2.8" + pod1 := "pod1" + pod2 := "pod2" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(setname), "nethash"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(setname), ip}}, {Cmd: []string{"ipset", "-D", "-exist", util.GetHashedName(setname), ip}}, @@ -471,7 +470,7 @@ func TestDestroy(t *testing.T) { setName := "test-destroy" testIP := "1.2.3.4" - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName(setName), "nethash"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName(setName), testIP}}, {Cmd: []string{"ipset", "-F", "-exist"}}, @@ -513,7 +512,7 @@ func TestDestroy(t *testing.T) { } func TestRun(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("test-set"), "nethash"}}, } @@ -532,7 +531,7 @@ func TestRun(t *testing.T) { } func TestRunErrorWithNonZeroExitCode(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName("test-set"), "nethash"}, Stdout: "test failure", ExitCode: 2}, } @@ -550,7 +549,7 @@ func TestRunErrorWithNonZeroExitCode(t *testing.T) { } func TestDestroyNpmIpsets(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("azure-npm-123456"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("azure-npm-56543"), "nethash"}}, {Cmd: []string{"ipset", "list"}}, diff --git a/npm/iptm/ioshim.go b/npm/iptm/ioshim.go index afc48a7102..b62e79b6f2 100644 --- a/npm/iptm/ioshim.go +++ b/npm/iptm/ioshim.go @@ -64,7 +64,7 @@ func (i *iptOperationShim) lockIptables() error { // Grab 1.6.x style lock. var err error - i.iptablesLockFile, err = os.OpenFile(util.IptablesLockFile, os.O_CREATE, 0600) + i.iptablesLockFile, err = os.OpenFile(util.IptablesLockFile, os.O_CREATE, 0o600) if err != nil { metrics.SendErrorLogAndMetric(util.IptmID, "Error: failed to open iptables lock file %s.", util.IptablesLockFile) return err diff --git a/npm/iptm/ioshim_fake.go b/npm/iptm/ioshim_fake.go index bfd1326f8a..d6885688d2 100644 --- a/npm/iptm/ioshim_fake.go +++ b/npm/iptm/ioshim_fake.go @@ -18,8 +18,7 @@ const ( testFileName = "iptables-test.conf" ) -var ( - testIPTablesData = `Chain INPUT (policy ACCEPT) +var testIPTablesData = `Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) @@ -28,7 +27,6 @@ target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination ` -) // TODO: we can use this method down the road for testing iptables restore func NewFakeIptOperationShim() *fakeIptOperationShim { diff --git a/npm/iptm/iptm.go b/npm/iptm/iptm.go index 95419d88df..79376a7bcd 100644 --- a/npm/iptm/iptm.go +++ b/npm/iptm/iptm.go @@ -22,21 +22,19 @@ const ( reconcileChainTimeInMinutes = 5 ) -var ( - // IptablesAzureChainList contains list of all NPM chains - IptablesAzureChainList = []string{ - util.IptablesAzureChain, - util.IptablesAzureAcceptChain, - util.IptablesAzureIngressChain, - util.IptablesAzureEgressChain, - util.IptablesAzureIngressPortChain, - util.IptablesAzureIngressFromChain, - util.IptablesAzureEgressPortChain, - util.IptablesAzureEgressToChain, - util.IptablesAzureIngressDropsChain, - util.IptablesAzureEgressDropsChain, - } -) +// IptablesAzureChainList contains list of all NPM chains +var IptablesAzureChainList = []string{ + util.IptablesAzureChain, + util.IptablesAzureAcceptChain, + util.IptablesAzureIngressChain, + util.IptablesAzureEgressChain, + util.IptablesAzureIngressPortChain, + util.IptablesAzureIngressFromChain, + util.IptablesAzureEgressPortChain, + util.IptablesAzureEgressToChain, + util.IptablesAzureIngressDropsChain, + util.IptablesAzureEgressDropsChain, +} // IptEntry represents an iptables rule. type IptEntry struct { @@ -56,7 +54,6 @@ type IptablesManager struct { } func isDropsChain(chainName string) bool { - // Check if the chain name is one of the two DROP chains if (chainName == util.IptablesAzureIngressDropsChain) || (chainName == util.IptablesAzureEgressDropsChain) { @@ -193,7 +190,6 @@ func (iptMgr *IptablesManager) ReconcileIPTables(stopCh <-chan struct{}) { // checkAndAddForwardChain initializes and reconciles Azure-NPM chain in right order func (iptMgr *IptablesManager) checkAndAddForwardChain() error { - // TODO Adding this chain is printing error messages try to clean it up if err := iptMgr.addChain(util.IptablesAzureChain); err != nil { return err @@ -289,7 +285,6 @@ func (iptMgr *IptablesManager) reconcileChains(stopCh <-chan struct{}) { // addAllRulesToChains checks and adds all the rules in NPM chains func (iptMgr *IptablesManager) addAllRulesToChains() error { - allDefaultRules := getAllDefaultRules() for _, rule := range allDefaultRules { entry := &IptEntry{ @@ -374,7 +369,6 @@ func (iptMgr *IptablesManager) addChain(chain string) error { // GetChainLineNumber given a Chain and its parent chain returns line number func (iptMgr *IptablesManager) getChainLineNumber(chain string, parentChain string) (int, error) { - var ( output []byte err error diff --git a/npm/iptm/iptm_linux.go b/npm/iptm/iptm_linux.go index 3f2747035a..90fb049664 100644 --- a/npm/iptm/iptm_linux.go +++ b/npm/iptm/iptm_linux.go @@ -3,8 +3,9 @@ package iptm import ( - "golang.org/x/sys/unix" "os" + + "golang.org/x/sys/unix" ) func grabIptablesFileLock(f *os.File) error { diff --git a/npm/iptm/iptm_test.go b/npm/iptm/iptm_test.go index 74437da5b8..e7ef6eec07 100644 --- a/npm/iptm/iptm_test.go +++ b/npm/iptm/iptm_test.go @@ -90,7 +90,7 @@ var ( ) func TestInitNpmChains(t *testing.T) { - var calls = initCalls + calls := initCalls fexec := testutils.GetFakeExecWithScripts(calls) defer testutils.VerifyCalls(t, fexec, calls) @@ -101,7 +101,7 @@ func TestInitNpmChains(t *testing.T) { } func TestUninitNpmChains(t *testing.T) { - var calls = unInitCalls + calls := unInitCalls fexec := testutils.GetFakeExecWithScripts(calls) defer testutils.VerifyCalls(t, fexec, calls) @@ -113,7 +113,7 @@ func TestUninitNpmChains(t *testing.T) { } func TestExists(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-C", "FORWARD", "-j", "ACCEPT"}}, } @@ -135,7 +135,7 @@ func TestExists(t *testing.T) { } func TestAddChain(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-N", "TEST-CHAIN"}}, } @@ -149,7 +149,7 @@ func TestAddChain(t *testing.T) { } func TestDeleteChain(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-N", "TEST-CHAIN"}}, {Cmd: []string{"iptables", "-w", "60", "-X", "TEST-CHAIN"}}, } @@ -168,7 +168,7 @@ func TestDeleteChain(t *testing.T) { } func TestAdd(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-I", "FORWARD", "-j", "REJECT"}}, } @@ -203,7 +203,7 @@ func TestAdd(t *testing.T) { } func TestDelete(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-I", "FORWARD", "-j", "REJECT"}}, {Cmd: []string{"iptables", "-w", "60", "-C", "FORWARD", "-j", "REJECT"}}, {Cmd: []string{"iptables", "-w", "60", "-D", "FORWARD", "-j", "REJECT"}}, @@ -238,7 +238,7 @@ func TestDelete(t *testing.T) { } func TestRun(t *testing.T) { - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"iptables", "-w", "60", "-N", "TEST-CHAIN"}}, } @@ -253,7 +253,6 @@ func TestRun(t *testing.T) { if _, err := iptMgr.run(entry); err != nil { t.Errorf("TestRun failed @ iptMgr.run") } - } func TestGetChainLineNumber(t *testing.T) { diff --git a/npm/metrics/ai-utils.go b/npm/metrics/ai-utils.go index bf86746e21..119b192294 100644 --- a/npm/metrics/ai-utils.go +++ b/npm/metrics/ai-utils.go @@ -10,13 +10,10 @@ import ( "github.com/Azure/azure-container-networking/npm/util" ) -var ( - th aitelemetry.TelemetryHandle -) +var th aitelemetry.TelemetryHandle // CreateTelemetryHandle creates a handler to initialize AI telemetry func CreateTelemetryHandle(version, aiMetadata string) error { - aiConfig := aitelemetry.AIConfig{ AppName: util.AzureNpmFlag, AppVersion: version, diff --git a/npm/metrics/prometheus_metrics.go b/npm/metrics/prometheus_metrics.go index 852b5db6bd..795d1f63dd 100644 --- a/npm/metrics/prometheus_metrics.go +++ b/npm/metrics/prometheus_metrics.go @@ -57,9 +57,11 @@ const ( SetHashLabel = "set_hash" ) -var nodeLevelRegistry = prometheus.NewRegistry() -var clusterLevelRegistry = prometheus.NewRegistry() -var haveInitialized = false +var ( + nodeLevelRegistry = prometheus.NewRegistry() + clusterLevelRegistry = prometheus.NewRegistry() + haveInitialized = false +) func ReInitializeAllMetrics() { haveInitialized = false diff --git a/npm/metrics/prometheus_metrics_test.go b/npm/metrics/prometheus_metrics_test.go index 829a428d8a..b1021b838f 100644 --- a/npm/metrics/prometheus_metrics_test.go +++ b/npm/metrics/prometheus_metrics_test.go @@ -27,7 +27,7 @@ func TestPrometheusNodeHandler(t *testing.T) { // TODO: evaluate why cluster metrics are nil func TestPrometheusClusterHandler(t *testing.T) { - //assert := assert.New(t) + // assert := assert.New(t) InitializeAll() handler := GetHandler(false) req, err := http.NewRequest(http.MethodGet, api.ClusterMetricsPath, nil) @@ -38,5 +38,5 @@ func TestPrometheusClusterHandler(t *testing.T) { rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) - //assert.Contains(string(rr.Body.Bytes()), fmt.Sprintf("%s_%s", namespace, addPolicyExecTimeName)) + // assert.Contains(string(rr.Body.Bytes()), fmt.Sprintf("%s_%s", namespace, addPolicyExecTimeName)) } diff --git a/npm/nameSpaceController.go b/npm/nameSpaceController.go index 1874f67168..716d844779 100644 --- a/npm/nameSpaceController.go +++ b/npm/nameSpaceController.go @@ -233,7 +233,6 @@ func (nsc *nameSpaceController) processNextWorkItem() bool { klog.Infof("Successfully synced '%s'", key) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -350,7 +349,7 @@ func (nsc *nameSpaceController) syncUpdateNameSpace(newNsObj *corev1.Namespace) return nil } - //If the Namespace is not deleted, delete removed labels and create new labels + // If the Namespace is not deleted, delete removed labels and create new labels addToIPSets, deleteFromIPSets := util.GetIPSetListCompareLabels(curNsObj.LabelsMap, newNsLabel) // Delete the namespace from its label's ipset list. for _, nsLabelVal := range deleteFromIPSets { diff --git a/npm/nameSpaceController_test.go b/npm/nameSpaceController_test.go index d10b192934..cbfa27713d 100644 --- a/npm/nameSpaceController_test.go +++ b/npm/nameSpaceController_test.go @@ -70,7 +70,7 @@ func (f *nameSpaceFixture) newNsController(stopCh chan struct{}) { } // Do not start informer to avoid unnecessary event triggers. // (TODO) Leave stopCh and below commented code to enhance UTs to even check event triggers as well later if possible - //f.kubeInformer.Start() + // f.kubeInformer.Start() } func newNameSpace(name, rv string, labels map[string]string) *corev1.Namespace { diff --git a/npm/networkPolicyController.go b/npm/networkPolicyController.go index b7fd632fc8..62941c39e8 100644 --- a/npm/networkPolicyController.go +++ b/npm/networkPolicyController.go @@ -226,7 +226,6 @@ func (c *networkPolicyController) processNextWorkItem() bool { klog.Infof("Successfully synced '%s'", key) return nil }(obj) - if err != nil { utilruntime.HandleError(err) metrics.SendErrorLogAndMetric(util.NetpolID, "syncNetPol error due to %v", err) diff --git a/npm/networkPolicyController_test.go b/npm/networkPolicyController_test.go index 54ad9551e2..948122b40c 100644 --- a/npm/networkPolicyController_test.go +++ b/npm/networkPolicyController_test.go @@ -68,7 +68,7 @@ func (f *netPolFixture) newNetPolController(stopCh chan struct{}) { // Do not start informer to avoid unnecessary event triggers // (TODO): Leave stopCh and below commented code to enhance UTs to even check event triggers as well later if possible - //f.kubeInformer.Start(stopCh) + // f.kubeInformer.Start(stopCh) } // (TODO): make createNetPol flexible diff --git a/npm/npm.go b/npm/npm.go index 2264baf65b..bc038ab3e0 100644 --- a/npm/npm.go +++ b/npm/npm.go @@ -182,8 +182,10 @@ func GetAIMetadata() string { func (npMgr *NetworkPolicyManager) SendClusterMetrics() { var ( heartbeat = time.NewTicker(time.Minute * heartbeatIntervalInMinutes).C - customDimensions = map[string]string{"ClusterID": util.GetClusterID(npMgr.NodeName), - "APIServer": npMgr.k8sServerVersion.String()} + customDimensions = map[string]string{ + "ClusterID": util.GetClusterID(npMgr.NodeName), + "APIServer": npMgr.k8sServerVersion.String(), + } podCount = aitelemetry.Metric{ Name: "PodCount", CustomDimensions: customDimensions, diff --git a/npm/parsePolicy_test.go b/npm/parsePolicy_test.go index 54ed6258a7..f6da37e86e 100644 --- a/npm/parsePolicy_test.go +++ b/npm/parsePolicy_test.go @@ -18,7 +18,7 @@ func TestAddPolicy(t *testing.T) { "app": "db", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -33,7 +33,7 @@ func TestAddPolicy(t *testing.T) { "ns": "dev", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -48,7 +48,7 @@ func TestAddPolicy(t *testing.T) { "app": "sql", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testNotIn", Operator: metav1.LabelSelectorOpNotIn, Values: []string{ @@ -69,28 +69,28 @@ func TestAddPolicy(t *testing.T) { }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{ - networkingv1.NetworkPolicyIngressRule{ + { Ports: []networkingv1.NetworkPolicyPort{ - networkingv1.NetworkPolicyPort{ + { Protocol: &tcp, Port: &port6783, }, }, From: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldIngressPodSelector, }, - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldIngressNamespaceSelector, }, }, }, }, Egress: []networkingv1.NetworkPolicyEgressRule{ - networkingv1.NetworkPolicyEgressRule{ + { Ports: []networkingv1.NetworkPolicyPort{}, To: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldEgressPodSelector, }, }, @@ -114,7 +114,7 @@ func TestAddPolicy(t *testing.T) { "ns": "new", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testNotIn", Operator: metav1.LabelSelectorOpNotIn, Values: []string{ @@ -160,7 +160,7 @@ func TestDeductPolicy(t *testing.T) { "app": "db", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -175,7 +175,7 @@ func TestDeductPolicy(t *testing.T) { "ns": "dev", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -190,7 +190,7 @@ func TestDeductPolicy(t *testing.T) { "app": "sql", }, MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testNotIn", Operator: metav1.LabelSelectorOpNotIn, Values: []string{ @@ -211,28 +211,28 @@ func TestDeductPolicy(t *testing.T) { }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{ - networkingv1.NetworkPolicyIngressRule{ + { Ports: []networkingv1.NetworkPolicyPort{ - networkingv1.NetworkPolicyPort{ + { Protocol: &tcp, Port: &port6783, }, }, From: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldIngressPodSelector, }, - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldIngressNamespaceSelector, }, }, }, }, Egress: []networkingv1.NetworkPolicyEgressRule{ - networkingv1.NetworkPolicyEgressRule{ + { Ports: []networkingv1.NetworkPolicyPort{}, To: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldEgressPodSelector, }, }, @@ -255,25 +255,25 @@ func TestDeductPolicy(t *testing.T) { }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{ - networkingv1.NetworkPolicyIngressRule{ + { Ports: []networkingv1.NetworkPolicyPort{ - networkingv1.NetworkPolicyPort{ + { Protocol: &tcp, Port: &port6783, }, }, From: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldIngressPodSelector, }, }, }, }, Egress: []networkingv1.NetworkPolicyEgressRule{ - networkingv1.NetworkPolicyEgressRule{ + { Ports: []networkingv1.NetworkPolicyPort{}, To: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: &metav1.LabelSelector{}, }, }, @@ -323,10 +323,10 @@ func TestDeductPolicy(t *testing.T) { }, }, Egress: []networkingv1.NetworkPolicyEgressRule{ - networkingv1.NetworkPolicyEgressRule{ + { Ports: []networkingv1.NetworkPolicyPort{}, To: []networkingv1.NetworkPolicyPeer{ - networkingv1.NetworkPolicyPeer{ + { PodSelector: oldEgressPodSelector, }, }, diff --git a/npm/parseSelector.go b/npm/parseSelector.go index 594b60e5c9..a6392c5515 100644 --- a/npm/parseSelector.go +++ b/npm/parseSelector.go @@ -70,8 +70,8 @@ func (h *ReqHeap) Pop() interface{} { // ParseLabel takes a Azure-NPM processed label then returns if it's referring to complement set, // and if so, returns the original set as well. func ParseLabel(label string) (string, bool) { - //The input label is guaranteed to have a non-zero length validated by k8s. - //For label definition, see below parseSelector() function. + // The input label is guaranteed to have a non-zero length validated by k8s. + // For label definition, see below parseSelector() function. if label[0:1] == util.IptablesNotFlag { return label[1:], true } @@ -116,7 +116,6 @@ func sortSelector(selector *metav1.LabelSelector) { var sortedReqs []metav1.LabelSelectorRequirement for reqHeap.Len() > 0 { sortedReqs = append(sortedReqs, heap.Pop(reqHeap).(metav1.LabelSelectorRequirement)) - } selector.MatchExpressions = sortedReqs } @@ -193,7 +192,6 @@ func FlattenNameSpaceSelector(nsSelector *metav1.LabelSelector) []metav1.LabelSe multiValuePresent := false multiValueMatchExprs := []metav1.LabelSelectorRequirement{} for _, req := range nsSelector.MatchExpressions { - // Only In and NotIn operators of matchExprs have multiple values // NPM will ignore single value matchExprs of these operators. // for multiple values, it will create a slice of them to be used for Zipping with baseSelector diff --git a/npm/parseSelector_test.go b/npm/parseSelector_test.go index cdfd6d2f77..077a2cf3f5 100644 --- a/npm/parseSelector_test.go +++ b/npm/parseSelector_test.go @@ -200,7 +200,7 @@ func TestReqHeap(t *testing.T) { func TestSortSelector(t *testing.T) { selector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -208,7 +208,7 @@ func TestSortSelector(t *testing.T) { "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "a", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -225,14 +225,14 @@ func TestSortSelector(t *testing.T) { sortSelector(selector) expectedSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "a", Operator: metav1.LabelSelectorOpIn, Values: []string{ "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -257,7 +257,7 @@ func TestSortSelector(t *testing.T) { func TestHashSelector(t *testing.T) { firstSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -274,7 +274,7 @@ func TestHashSelector(t *testing.T) { secondSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -329,7 +329,7 @@ func TestParseSelector(t *testing.T) { selector = &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -487,11 +487,9 @@ func TestFlattenNameSpaceSelectorCases(t *testing.T) { if len(testSelectors) > 0 { t.Errorf("TestFlattenNameSpaceSelectorCases failed @ 1st selector length check %+v", testSelectors) } - } func TestFlattenNameSpaceSelector(t *testing.T) { - commonMatchLabel := map[string]string{ "c": "d", "a": "b", @@ -499,26 +497,26 @@ func TestFlattenNameSpaceSelector(t *testing.T) { firstSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -540,7 +538,7 @@ func TestFlattenNameSpaceSelector(t *testing.T) { secondSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -548,7 +546,7 @@ func TestFlattenNameSpaceSelector(t *testing.T) { "frontend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -556,12 +554,12 @@ func TestFlattenNameSpaceSelector(t *testing.T) { "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -579,28 +577,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { } expectedSelectors := []metav1.LabelSelector{ - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -610,28 +608,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -641,28 +639,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -672,28 +670,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -703,28 +701,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "frontend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -734,28 +732,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "frontend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -765,28 +763,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "frontend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -796,28 +794,28 @@ func TestFlattenNameSpaceSelector(t *testing.T) { }, MatchLabels: commonMatchLabel, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "frontend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "b", }, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -837,26 +835,26 @@ func TestFlattenNameSpaceSelector(t *testing.T) { func TestFlattenNameSpaceSelectorWoMatchLabels(t *testing.T) { firstSelector := &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -873,28 +871,28 @@ func TestFlattenNameSpaceSelectorWoMatchLabels(t *testing.T) { } expectedSelectors := []metav1.LabelSelector{ - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ @@ -903,28 +901,28 @@ func TestFlattenNameSpaceSelectorWoMatchLabels(t *testing.T) { }, }, }, - metav1.LabelSelector{ + { MatchExpressions: []metav1.LabelSelectorRequirement{ - metav1.LabelSelectorRequirement{ + { Key: "testIn", Operator: metav1.LabelSelectorOpIn, Values: []string{ "backend", }, }, - metav1.LabelSelectorRequirement{ + { Key: "pod", Operator: metav1.LabelSelectorOpIn, Values: []string{ "a", }, }, - metav1.LabelSelectorRequirement{ + { Key: "testExists", Operator: metav1.LabelSelectorOpExists, Values: []string{}, }, - metav1.LabelSelectorRequirement{ + { Key: "ns", Operator: metav1.LabelSelectorOpIn, Values: []string{ diff --git a/npm/pkg/dataplane/pb/rule.pb.go b/npm/pkg/dataplane/pb/rule.pb.go index bb473b96a6..e15818f9e2 100644 --- a/npm/pkg/dataplane/pb/rule.pb.go +++ b/npm/pkg/dataplane/pb/rule.pb.go @@ -7,11 +7,12 @@ package pb import ( + reflect "reflect" + sync "sync" + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" ) const ( @@ -398,15 +399,18 @@ func file_rule_proto_rawDescGZIP() []byte { return file_rule_proto_rawDescData } -var file_rule_proto_enumTypes = make([]protoimpl.EnumInfo, 2) -var file_rule_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_rule_proto_goTypes = []interface{}{ - (SetType)(0), // 0: pb.SetType - (Direction)(0), // 1: pb.Direction - (*RuleResponse)(nil), // 2: pb.RuleResponse - (*RuleResponse_SetInfo)(nil), // 3: pb.RuleResponse.SetInfo - nil, // 4: pb.RuleResponse.UnsortedIpsetEntry -} +var ( + file_rule_proto_enumTypes = make([]protoimpl.EnumInfo, 2) + file_rule_proto_msgTypes = make([]protoimpl.MessageInfo, 3) + file_rule_proto_goTypes = []interface{}{ + (SetType)(0), // 0: pb.SetType + (Direction)(0), // 1: pb.Direction + (*RuleResponse)(nil), // 2: pb.RuleResponse + (*RuleResponse_SetInfo)(nil), // 3: pb.RuleResponse.SetInfo + nil, // 4: pb.RuleResponse.UnsortedIpsetEntry + } +) + var file_rule_proto_depIdxs = []int32{ 3, // 0: pb.RuleResponse.SrcList:type_name -> pb.RuleResponse.SetInfo 3, // 1: pb.RuleResponse.DstList:type_name -> pb.RuleResponse.SetInfo diff --git a/npm/podController.go b/npm/podController.go index 5edbc63da0..780966fd94 100644 --- a/npm/podController.go +++ b/npm/podController.go @@ -312,7 +312,6 @@ func (c *podController) processNextWorkItem() bool { klog.Infof("Successfully synced '%s'", key) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true diff --git a/npm/podController_test.go b/npm/podController_test.go index 510e142d64..a4bd62f744 100644 --- a/npm/podController_test.go +++ b/npm/podController_test.go @@ -66,7 +66,7 @@ func (f *podFixture) newPodController(stopCh chan struct{}) { // Do not start informer to avoid unnecessary event triggers // (TODO): Leave stopCh and below commented code to enhance UTs to even check event triggers as well later if possible - //f.kubeInformer.Start(stopCh) + // f.kubeInformer.Start(stopCh) } func createPod(name, ns, rv, podIP string, labels map[string]string, isHostNewtwork bool, podPhase corev1.PodPhase) *corev1.Pod { @@ -80,12 +80,12 @@ func createPod(name, ns, rv, podIP string, labels map[string]string, isHostNewtw Spec: corev1.PodSpec{ HostNetwork: isHostNewtwork, Containers: []corev1.Container{ - corev1.Container{ + { Ports: []corev1.ContainerPort{ - corev1.ContainerPort{ + { Name: fmt.Sprintf("app:%s", name), ContainerPort: 8080, - //Protocol: "TCP", + // Protocol: "TCP", }, }, }, @@ -198,7 +198,7 @@ func TestAddMultiplePods(t *testing.T) { podObj1 := createPod("test-pod-1", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) podObj2 := createPod("test-pod-2", "test-namespace", "0", "1.2.3.5", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName("all-namespaces"), util.GetHashedName("ns-test-namespace")}}, @@ -243,7 +243,7 @@ func TestAddPod(t *testing.T) { } podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, {Cmd: []string{"ipset", "-A", "-exist", util.GetHashedName("all-namespaces"), util.GetHashedName("ns-test-namespace")}}, @@ -281,7 +281,7 @@ func TestAddHostNetworkPod(t *testing.T) { podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, HostNetwork, corev1.PodRunning) podKey := getKey(podObj, t) - var calls = []testutils.TestCmd{} + calls := []testutils.TestCmd{} fexec := testutils.GetFakeExecWithScripts(calls) defer testutils.VerifyCalls(t, fexec, calls) @@ -311,7 +311,7 @@ func TestDeletePod(t *testing.T) { podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) podKey := getKey(podObj, t) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ // add pod {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, @@ -363,7 +363,7 @@ func TestDeleteHostNetworkPod(t *testing.T) { podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, HostNetwork, corev1.PodRunning) podKey := getKey(podObj, t) - var calls = []testutils.TestCmd{} + calls := []testutils.TestCmd{} fexec := testutils.GetFakeExecWithScripts(calls) defer testutils.VerifyCalls(t, fexec, calls) @@ -392,7 +392,7 @@ func TestDeletePodWithTombstone(t *testing.T) { } podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{} + calls := []testutils.TestCmd{} fexec := testutils.GetFakeExecWithScripts(calls) defer testutils.VerifyCalls(t, fexec, calls) @@ -421,7 +421,7 @@ func TestDeletePodWithTombstoneAfterAddingPod(t *testing.T) { } podObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ // add pod {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, @@ -468,7 +468,7 @@ func TestLabelUpdatePod(t *testing.T) { } oldPodObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ // add pod {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, @@ -520,7 +520,7 @@ func TestIPAddressUpdatePod(t *testing.T) { } oldPodObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ // add pod {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, @@ -584,7 +584,7 @@ func TestPodStatusUpdatePod(t *testing.T) { oldPodObj := createPod("test-pod", "test-namespace", "0", "1.2.3.4", labels, NonHostNetwork, corev1.PodRunning) podKey := getKey(oldPodObj, t) - var calls = []testutils.TestCmd{ + calls := []testutils.TestCmd{ // add pod {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("ns-test-namespace"), "nethash"}}, {Cmd: []string{"ipset", "-N", "-exist", util.GetHashedName("all-namespaces"), "setlist"}}, diff --git a/npm/translatePolicy_test.go b/npm/translatePolicy_test.go index 245528f4d7..2373a6ab81 100644 --- a/npm/translatePolicy_test.go +++ b/npm/translatePolicy_test.go @@ -377,7 +377,6 @@ func TestCraftPartialIptablesCommentFromSelector(t *testing.T) { t.Errorf("comment:\n%v", comment) t.Errorf("expectedComment:\n%v", expectedComment) } - } func TestGetDefaultDropEntries(t *testing.T) { diff --git a/npm/util/const.go b/npm/util/const.go index ff34c34fd6..5439b02c7c 100644 --- a/npm/util/const.go +++ b/npm/util/const.go @@ -2,7 +2,7 @@ // MIT License package util -//kubernetes related constants. +// kubernetes related constants. const ( KubeSystemFlag string = "kube-system" KubePodTemplateHashFlag string = "pod-template-hash" @@ -19,7 +19,7 @@ const ( k8sMinorVerForNewPolicyDef string = "11" ) -//iptables related constants. +// iptables related constants. const ( Iptables string = "iptables" Ip6tables string = "ip6tables" @@ -103,7 +103,7 @@ const ( IptablesTableFlag string = "-t" ) -//ipset related constants. +// ipset related constants. const ( Ipset string = "ipset" IpsetSaveFlag string = "save" @@ -140,14 +140,14 @@ const ( IpsetNomatch string = "nomatch" - //Prefixes for ipsets + // Prefixes for ipsets NamedPortIPSetPrefix string = "namedport:" NamespacePrefix string = "ns-" NegationPrefix string = "not-" ) -//NPM telemetry constants. +// NPM telemetry constants. const ( AddNamespaceEvent string = "Add Namespace" UpdateNamespaceEvent string = "Update Namespace" diff --git a/npm/util/util.go b/npm/util/util.go index ed80dad8c2..f2b1421acb 100644 --- a/npm/util/util.go +++ b/npm/util/util.go @@ -74,12 +74,9 @@ func SortMap(m *map[string]string) ([]string, []string) { // GetIPSetListFromLabels combine Labels into a single slice func GetIPSetListFromLabels(labels map[string]string) []string { - var ( - ipsetList = []string{} - ) + ipsetList := []string{} for labelKey, labelVal := range labels { ipsetList = append(ipsetList, labelKey, labelKey+IpsetLabelDelimter+labelVal) - } return ipsetList } diff --git a/npm/util/util_test.go b/npm/util/util_test.go index d1b5b51bfb..343e9da03e 100644 --- a/npm/util/util_test.go +++ b/npm/util/util_test.go @@ -237,7 +237,6 @@ func TestCompareResourceVersions(t *testing.T) { if !check { t.Errorf("TestCompareResourceVersions failed @ compare RVs with error returned wrong result ") } - } func TestInValidOldResourceVersions(t *testing.T) { @@ -248,7 +247,6 @@ func TestInValidOldResourceVersions(t *testing.T) { if !check { t.Errorf("TestInValidOldResourceVersions failed @ compare RVs with error returned wrong result ") } - } func TestInValidNewResourceVersions(t *testing.T) { @@ -259,7 +257,6 @@ func TestInValidNewResourceVersions(t *testing.T) { if check { t.Errorf("TestInValidNewResourceVersions failed @ compare RVs with error returned wrong result ") } - } func TestParseResourceVersion(t *testing.T) { diff --git a/platform/os.go b/platform/os.go index 81dc790ea2..8f8300ecbd 100644 --- a/platform/os.go +++ b/platform/os.go @@ -10,9 +10,7 @@ import ( // ReadFileByLines reads file line by line and return array of lines. func ReadFileByLines(filename string) ([]string, error) { - var ( - lineStrArr []string - ) + var lineStrArr []string f, err := os.Open(filename) if err != nil { diff --git a/server/tls/tlscertificate_retriever_linux.go b/server/tls/tlscertificate_retriever_linux.go index 78fabb452b..27d6e2f5c2 100644 --- a/server/tls/tlscertificate_retriever_linux.go +++ b/server/tls/tlscertificate_retriever_linux.go @@ -91,7 +91,6 @@ func NewTlsCertificateRetriever(settings TlsSettings) (TlsCertificateRetriever, settings: settings, } content, err := linuxCertStoreRetriever.readFile() - if err != nil { return nil, fmt.Errorf("Failed to read file with error %+v", err) } diff --git a/server/tls/tlscertificate_retriever_linux_test.go b/server/tls/tlscertificate_retriever_linux_test.go index 02bb887838..80d32a17b9 100644 --- a/server/tls/tlscertificate_retriever_linux_test.go +++ b/server/tls/tlscertificate_retriever_linux_test.go @@ -25,7 +25,7 @@ func TestPemConsumptionLinux(t *testing.T) { currentDirectory, _ := os.Getwd() pemLocation := fmt.Sprintf("%s/%s.Pem", currentDirectory, commonName) - ioutil.WriteFile(pemLocation, pemContent, 0644) + ioutil.WriteFile(pemLocation, pemContent, 0o644) defer os.Remove(pemLocation) config := TlsSettings{ diff --git a/server/tls/tlscertificate_retriever_windows.go b/server/tls/tlscertificate_retriever_windows.go index d97f875d05..2ab172f715 100644 --- a/server/tls/tlscertificate_retriever_windows.go +++ b/server/tls/tlscertificate_retriever_windows.go @@ -7,9 +7,10 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "github.com/billgraziano/dpapi" "io/ioutil" "strings" + + "github.com/billgraziano/dpapi" ) type windowsTlsCertificateRetriever struct { @@ -119,13 +120,11 @@ func NewTlsCertificateRetriever(settings TlsSettings) (TlsCertificateRetriever, } content, err := windowsCertStoreRetriever.readFile() - if err != nil { return nil, fmt.Errorf("Failed to read file with error %+v", err) } decrypted, err := windowsCertStoreRetriever.decrypt(content) - if err != nil { return nil, fmt.Errorf("Failed to decrypt file with error %+v", err) } diff --git a/server/tls/tlscertificate_retriever_windows_test.go b/server/tls/tlscertificate_retriever_windows_test.go index 9ec13fd6c3..37154bea77 100644 --- a/server/tls/tlscertificate_retriever_windows_test.go +++ b/server/tls/tlscertificate_retriever_windows_test.go @@ -9,11 +9,12 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "github.com/billgraziano/dpapi" "io/ioutil" "math/big" "os" "testing" + + "github.com/billgraziano/dpapi" ) const ( @@ -27,7 +28,7 @@ func TestPemConsumptionWindows(t *testing.T) { pemLocation := fmt.Sprintf("%s/%s.Pem", currentDirectory, commonName) encryptedPem, _ := dpapi.Encrypt(string(pemContent)) - ioutil.WriteFile(pemLocation, []byte(encryptedPem), 0644) + ioutil.WriteFile(pemLocation, []byte(encryptedPem), 0o644) defer os.Remove(pemLocation) config := TlsSettings{ diff --git a/store/json.go b/store/json.go index 8cf27affbc..3181f371a9 100644 --- a/store/json.go +++ b/store/json.go @@ -33,11 +33,11 @@ const ( // jsonFileStore is an implementation of KeyValueStore using a local JSON file. type jsonFileStore struct { - fileName string + fileName string lockFileName string - data map[string]*json.RawMessage - inSync bool - locked bool + data map[string]*json.RawMessage + inSync bool + locked bool sync.Mutex } @@ -48,16 +48,16 @@ func NewJsonFileStore(fileName string) (KeyValueStore, error) { } if platform.CNILockPath != "" { - err := os.MkdirAll(platform.CNILockPath, os.FileMode(0664)) + err := os.MkdirAll(platform.CNILockPath, os.FileMode(0o664)) if err != nil { return nil, err } } kvs := &jsonFileStore{ - fileName: fileName, + fileName: fileName, lockFileName: platform.CNILockPath + filepath.Base(fileName) + lockExtension, - data: make(map[string]*json.RawMessage), + data: make(map[string]*json.RawMessage), } return kvs, nil @@ -185,7 +185,7 @@ func (kvs *jsonFileStore) Lock(block bool) error { var lockFile *os.File var err error - lockPerm := os.FileMode(0664) + os.FileMode(os.ModeExclusive) + lockPerm := os.FileMode(0o664) + os.FileMode(os.ModeExclusive) // Try to acquire the lock file. var lockRetryCount uint diff --git a/store/json_test.go b/store/json_test.go index bde3630d6d..6af3851ea5 100644 --- a/store/json_test.go +++ b/store/json_test.go @@ -12,7 +12,7 @@ import ( const ( // File name used for test store. - testFileName = "test.json" + testFileName = "test.json" testLockFileName = "locktest.json" // Keys used during tests. testKey1 = "key1" @@ -27,8 +27,8 @@ type testType1 struct { // Tests that the key value pairs are reinstantiated correctly from a pre-existing JSON encoded file. func TestKeyValuePairsAreReinstantiatedFromJSONFile(t *testing.T) { - var encodedPair = `{"key1":{"Field1":"test","Field2":42}}` - var expectedValue = testType1{"test", 42} + encodedPair := `{"key1":{"Field1":"test","Field2":42}}` + expectedValue := testType1{"test", 42} var actualValue testType1 // Create a JSON file containing the encoded pair. @@ -66,8 +66,8 @@ func TestKeyValuePairsAreReinstantiatedFromJSONFile(t *testing.T) { // Tests that the key value pairs written to the store are persisted correctly in JSON encoded file. func TestKeyValuePairsArePersistedToJSONFile(t *testing.T) { - var writtenValue = testType1{"test", 42} - var expectedPair = `{"key1":{"Field1":"test","Field2":42}}` + writtenValue := testType1{"test", 42} + expectedPair := `{"key1":{"Field1":"test","Field2":42}}` var actualPair string // Create the store. @@ -112,8 +112,8 @@ func TestKeyValuePairsArePersistedToJSONFile(t *testing.T) { // Tests that key value pairs are written and read back correctly. func TestKeyValuePairsAreWrittenAndReadCorrectly(t *testing.T) { - var writtenValue = testType1{"test", 42} - var anotherValue = testType1{"any", 14} + writtenValue := testType1{"test", 42} + anotherValue := testType1{"any", 14} var readValue testType1 // Create the store. @@ -152,7 +152,7 @@ func TestKeyValuePairsAreWrittenAndReadCorrectly(t *testing.T) { // Tests that locking a store gives the caller exclusive access. func TestLockingStoreGivesExclusiveAccess(t *testing.T) { - var anyValue = testType1{"test", 42} + anyValue := testType1{"test", 42} // Create the store. kvs, err := NewJsonFileStore(testFileName) @@ -231,11 +231,11 @@ func TestLockFilePath(t *testing.T) { lockFileName := store.GetLockFileName() if runtime.GOOS == "linux" { - if lockFileName != "/var/run/azure-vnet/" + testLockFileName + ".lock" { + if lockFileName != "/var/run/azure-vnet/"+testLockFileName+".lock" { t.Errorf("Not expected file lock name: %v", lockFileName) } } else { - if lockFileName != testLockFileName + ".lock" { + if lockFileName != testLockFileName+".lock" { t.Errorf("Not expected lockfilename: %v", lockFileName) } } diff --git a/telemetry/telemetry.go b/telemetry/telemetry.go index 5151dd1778..429c2c3bce 100644 --- a/telemetry/telemetry.go +++ b/telemetry/telemetry.go @@ -181,7 +181,7 @@ func (reportMgr *ReportManager) SetReportState(telemetryFile string) error { } // try to open telemetry file - f, err := os.OpenFile(telemetryFile, os.O_RDWR|os.O_CREATE, 0666) + f, err := os.OpenFile(telemetryFile, os.O_RDWR|os.O_CREATE, 0o666) if err != nil { return fmt.Errorf("[Telemetry] Error opening telemetry file %v", err) } diff --git a/telemetry/telemetry_linux.go b/telemetry/telemetry_linux.go index a1710e0a8a..5d0ce9bba0 100644 --- a/telemetry/telemetry_linux.go +++ b/telemetry/telemetry_linux.go @@ -40,7 +40,7 @@ func getMemInfo() (*MemInfo, error) { return nil, fmt.Errorf("Sysinfo failed due to %v", err) } - unit := uint64(info.Unit) * MB //MB + unit := uint64(info.Unit) * MB // MB memInfo := &MemInfo{MemTotal: info.Totalram / unit, MemFree: info.Freeram / unit} return memInfo, nil diff --git a/telemetry/telemetry_test.go b/telemetry/telemetry_test.go index b2508e59ff..e65aea1eee 100644 --- a/telemetry/telemetry_test.go +++ b/telemetry/telemetry_test.go @@ -22,10 +22,12 @@ const ( telemetryConfig = "azure-vnet-telemetry.config" ) -var reportManager *ReportManager -var tb *TelemetryBuffer -var ipamQueryUrl = "localhost:3501" -var hostAgentUrl = "localhost:3500" +var ( + reportManager *ReportManager + tb *TelemetryBuffer + ipamQueryUrl = "localhost:3501" + hostAgentUrl = "localhost:3500" +) var ipamQueryResponse = "" + "" + @@ -130,12 +132,14 @@ func TestGetOSDetails(t *testing.T) { t.Errorf("GetOSDetails failed due to %v", reportManager.Report.(*CNIReport).ErrorMessage) } } + func TestGetSystemDetails(t *testing.T) { reportManager.Report.(*CNIReport).GetSystemDetails() if reportManager.Report.(*CNIReport).ErrorMessage != "" { t.Errorf("GetSystemDetails failed due to %v", reportManager.Report.(*CNIReport).ErrorMessage) } } + func TestGetInterfaceDetails(t *testing.T) { reportManager.Report.(*CNIReport).GetSystemDetails() if reportManager.Report.(*CNIReport).ErrorMessage != "" { diff --git a/telemetry/telemetry_windows.go b/telemetry/telemetry_windows.go index 0136c6a31e..f232f049b3 100644 --- a/telemetry/telemetry_windows.go +++ b/telemetry/telemetry_windows.go @@ -26,12 +26,10 @@ type DiskInfo struct { } func getMemInfo() (*MemInfo, error) { - return nil, nil } func getDiskInfo(path string) (*DiskInfo, error) { - return nil, nil } diff --git a/test/integration/k8s_test.go b/test/integration/k8s_test.go index 226c860492..1d3ca15bcf 100644 --- a/test/integration/k8s_test.go +++ b/test/integration/k8s_test.go @@ -190,11 +190,9 @@ func TestPodScaling(t *testing.T) { } t.Run("all pods can ping each other", func(t *testing.T) { - clusterCheckCtx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() clusterCheckFn := func() error { - pf, err := NewPortForwarder(restConfig) if err != nil { t.Fatal(err) @@ -244,7 +242,6 @@ func TestPodScaling(t *testing.T) { }) }) } - } func updateReplicaCount(t *testing.T, ctx context.Context, deployments v1.DeploymentInterface, name string, replicas int) error { diff --git a/test/integration/retry/retry.go b/test/integration/retry/retry.go index 8d6d2ed0b0..051793aeea 100644 --- a/test/integration/retry/retry.go +++ b/test/integration/retry/retry.go @@ -1,6 +1,6 @@ // +build integration -//todo: there are more robust retry packages out there, discuss with team +// todo: there are more robust retry packages out there, discuss with team package retry import ( diff --git a/test/integration/utils_create_test.go b/test/integration/utils_create_test.go index 007cfc7048..fd89c10d65 100644 --- a/test/integration/utils_create_test.go +++ b/test/integration/utils_create_test.go @@ -6,7 +6,7 @@ import ( "context" "log" - //crd "dnc/requestcontroller/kubernetes" + // crd "dnc/requestcontroller/kubernetes" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" diff --git a/test/integration/utils_test.go b/test/integration/utils_test.go index c6a33505c2..1ab79d5622 100644 --- a/test/integration/utils_test.go +++ b/test/integration/utils_test.go @@ -11,7 +11,7 @@ import ( "strings" "time" - //crd "dnc/requestcontroller/kubernetes" + // crd "dnc/requestcontroller/kubernetes" "os" "testing" @@ -226,7 +226,6 @@ func waitForPodsRunning(ctx context.Context, clientset *kubernetes.Clientset, na return retrier.Do(ctx, checkPodIPsFn) } - func exportLogsByLabelSelector(ctx context.Context, clientset *kubernetes.Clientset, namespace, labelselector, logDir string) error { podsClient := clientset.CoreV1().Pods(namespace) podLogOpts := corev1.PodLogOptions{} @@ -250,7 +249,7 @@ func exportLogsByLabelSelector(ctx context.Context, clientset *kubernetes.Client return err } str := buf.String() - err = writeToFile(logDir, pod.Name + logExtension, str) + err = writeToFile(logDir, pod.Name+logExtension, str) if err != nil { return err } @@ -259,9 +258,9 @@ func exportLogsByLabelSelector(ctx context.Context, clientset *kubernetes.Client } func writeToFile(dir, fileName, str string) error { - if _, err := os.Stat(dir); os.IsNotExist(err) { + if _, err := os.Stat(dir); os.IsNotExist(err) { // your dir does not exist - os.MkdirAll(dir, 0666) + os.MkdirAll(dir, 0o666) } // open output file f, err := os.Create(dir + fileName) diff --git a/test/nnsmockserver/nnsmock/main.go b/test/nnsmockserver/nnsmock/main.go index 2082fd70ba..2a4582d48f 100644 --- a/test/nnsmockserver/nnsmock/main.go +++ b/test/nnsmockserver/nnsmock/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/Azure/azure-container-networking/test/nnsmockserver" ) diff --git a/test/nnsmockserver/nnsmockserver.go b/test/nnsmockserver/nnsmockserver.go index 161b1beedb..ddb95c70e0 100644 --- a/test/nnsmockserver/nnsmockserver.go +++ b/test/nnsmockserver/nnsmockserver.go @@ -3,12 +3,13 @@ package nnsmockserver import ( "context" "fmt" + "net" + "strings" + "github.com/Azure/azure-container-networking/log" nns "github.com/Azure/azure-container-networking/proto/nodenetworkservice/3.302.0.744" "github.com/google/uuid" "google.golang.org/grpc" - "net" - "strings" ) type NnsMockServer struct { @@ -16,8 +17,7 @@ type NnsMockServer struct { } // node network service mock server implementation -type serverApi struct { -} +type serverApi struct{} func (s *serverApi) ConfigureContainerNetworking( ctx context.Context, @@ -68,7 +68,6 @@ func NewNnsMockServer() *NnsMockServer { } func (s *NnsMockServer) StartGrpcServer(port string) { - endpoint := fmt.Sprintf(":%s", port) lis, err := net.Listen("tcp", endpoint) if err != nil { @@ -89,7 +88,6 @@ func (s *NnsMockServer) StopGrpcServer() { } func isValidPodName(podName string) error { - var splits []string splits = strings.Split(podName, "_") podNamelength := len(splits) diff --git a/tools/acncli/api/constants.go b/tools/acncli/api/constants.go index 18a7e64fe7..881733ff6d 100644 --- a/tools/acncli/api/constants.go +++ b/tools/acncli/api/constants.go @@ -11,7 +11,7 @@ const ( EnvPrefix = "AZURE_CNI" - //CNI Install Flags + // CNI Install Flags FlagMode = "mode" FlagTarget = "target" FlagIPAM = "ipam" @@ -22,7 +22,7 @@ const ( FlagConflistDirectory = "conflist-directory" FlagVersion = "version" - //CNI Log Flags + // CNI Log Flags FlagFollow = "follow" FlagLogFilePath = "log-file" diff --git a/tools/acncli/cmd/cni/cni.go b/tools/acncli/cmd/cni/cni.go index dea70662bd..0f5bd7f68f 100644 --- a/tools/acncli/cmd/cni/cni.go +++ b/tools/acncli/cmd/cni/cni.go @@ -8,7 +8,7 @@ import ( // NewRootCmd returns a root func CNICmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cni", Short: "Collection of functions related to Azure CNI", } diff --git a/tools/acncli/cmd/cni/install.go b/tools/acncli/cmd/cni/install.go index 5d9aad334f..46583269a4 100644 --- a/tools/acncli/cmd/cni/install.go +++ b/tools/acncli/cmd/cni/install.go @@ -12,7 +12,7 @@ import ( // install CNI will install CNI to a local machine func InstallCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "install", Short: "Installs an ACN component", } @@ -21,11 +21,10 @@ func InstallCmd() *cobra.Command { } func InstallCNICmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cni", Short: "Installs CNI and conflist ", RunE: func(cmd *cobra.Command, args []string) error { - envs := i.InstallerConfig{ ExemptBins: make(map[string]bool), } diff --git a/tools/acncli/cmd/cni/logs.go b/tools/acncli/cmd/cni/logs.go index 39dc203acb..2f0e05ba4c 100644 --- a/tools/acncli/cmd/cni/logs.go +++ b/tools/acncli/cmd/cni/logs.go @@ -11,7 +11,7 @@ import ( // LogsCmd will write the logs of the Azure CNI logs func LogsCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "logs", Short: "Fetches the logs of an ACN component", Long: "The logs command is used to fetch and/or watch the logs of an ACN component", @@ -21,7 +21,7 @@ func LogsCmd() *cobra.Command { } func LogsCNICmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cni", Short: fmt.Sprintf("Retrieves the logs of %s binary", c.AzureCNIBin), RunE: func(cmd *cobra.Command, args []string) error { @@ -30,7 +30,6 @@ func LogsCNICmd() *cobra.Command { // this loop exists for when the logfile gets rotated, and tail loses the original file for { t, err := tail.TailFile(viper.GetString(c.FlagLogFilePath), tail.Config{Follow: viper.GetBool(c.FlagFollow), ReOpen: true}) - if err != nil { return err } @@ -41,7 +40,8 @@ func LogsCNICmd() *cobra.Command { return nil } } - }} + }, + } cmd.Flags().BoolP(c.FlagFollow, "f", c.DefaultToggles[c.FlagFollow], "Follow the log file, similar to 'tail -f'") cmd.Flags().String(c.FlagLogFilePath, c.Defaults[c.FlagLogFilePath], "Path of the Azure CNI log file") diff --git a/tools/acncli/cmd/cni/manager.go b/tools/acncli/cmd/cni/manager.go index e5161b99b4..9ca58fe54c 100644 --- a/tools/acncli/cmd/cni/manager.go +++ b/tools/acncli/cmd/cni/manager.go @@ -6,7 +6,7 @@ import ( // ManagerCmd starts the manager mode, which installs CNI+Conflists, then watches logs func ManagerCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "manager", Short: "Starts the ACN CNI manager, which installs CNI, sets up conflists, then starts watching logs", RunE: func(cmd *cobra.Command, args []string) error { diff --git a/tools/acncli/cmd/install.go b/tools/acncli/cmd/install.go index cb6c7b667f..a4543a112e 100644 --- a/tools/acncli/cmd/install.go +++ b/tools/acncli/cmd/install.go @@ -12,7 +12,7 @@ import ( // install CNI will install CNI to a local machine func InstallCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "install", Short: "Installs an ACN component", } @@ -21,11 +21,10 @@ func InstallCmd() *cobra.Command { } func InstallCNICmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cni", Short: "Installs CNI and conflist ", RunE: func(cmd *cobra.Command, args []string) error { - envs := i.InstallerConfig{ ExemptBins: make(map[string]bool), } diff --git a/tools/acncli/cmd/logs.go b/tools/acncli/cmd/logs.go index 9b1c6f3dd3..35f0caaa81 100644 --- a/tools/acncli/cmd/logs.go +++ b/tools/acncli/cmd/logs.go @@ -11,7 +11,7 @@ import ( // LogsCmd will write the logs of the Azure CNI logs func LogsCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "logs", Short: "Fetches the logs of an ACN component", Long: "The logs command is used to fetch and/or watch the logs of an ACN component", @@ -21,7 +21,7 @@ func LogsCmd() *cobra.Command { } func LogsCNICmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cni", Short: fmt.Sprintf("Retrieves the logs of %s binary", c.AzureCNIBin), RunE: func(cmd *cobra.Command, args []string) error { @@ -30,7 +30,6 @@ func LogsCNICmd() *cobra.Command { // this loop exists for when the logfile gets rotated, and tail loses the original file for { t, err := tail.TailFile(viper.GetString(c.FlagLogFilePath), tail.Config{Follow: viper.GetBool(c.FlagFollow), ReOpen: true}) - if err != nil { return err } @@ -41,7 +40,8 @@ func LogsCNICmd() *cobra.Command { return nil } } - }} + }, + } cmd.Flags().BoolP(c.FlagFollow, "f", c.DefaultToggles[c.FlagFollow], "Follow the log file, similar to 'tail -f'") cmd.Flags().String(c.FlagLogFilePath, c.Defaults[c.FlagLogFilePath], "Path of the Azure CNI log file") diff --git a/tools/acncli/cmd/manager.go b/tools/acncli/cmd/manager.go index 3d46d31ea5..879b683c02 100644 --- a/tools/acncli/cmd/manager.go +++ b/tools/acncli/cmd/manager.go @@ -6,7 +6,7 @@ import ( // ManagerCmd starts the manager mode, which installs CNI+Conflists, then watches logs func ManagerCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "manager", Short: "Starts the ACN CNI manager, which installs CNI, sets up conflists, then starts watching logs", RunE: func(cmd *cobra.Command, args []string) error { diff --git a/tools/acncli/cmd/npm/get/manager.go b/tools/acncli/cmd/npm/get/manager.go index c19b9854d6..d5dfac10cc 100644 --- a/tools/acncli/cmd/npm/get/manager.go +++ b/tools/acncli/cmd/npm/get/manager.go @@ -8,7 +8,7 @@ import ( ) func GetManagerCmd(npmClient *npm.NPMHttpClient) *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "npmgr", Short: "Get NPM in memory Namespace map", RunE: func(cmd *cobra.Command, args []string) error { diff --git a/tools/acncli/cmd/npm/npm.go b/tools/acncli/cmd/npm/npm.go index 216a0d9c65..ea10ae1c1e 100644 --- a/tools/acncli/cmd/npm/npm.go +++ b/tools/acncli/cmd/npm/npm.go @@ -14,7 +14,7 @@ import ( // NewRootCmd returns a root func NPMRootCmd() *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "npm", Short: "Collection of functions related to Azure NPM", } @@ -31,7 +31,7 @@ func NPMRootCmd() *cobra.Command { } func GetCmd(npmClient *npm.NPMHttpClient) *cobra.Command { - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "get", Short: "Get in-memory maps from Azure NPM", } diff --git a/tools/acncli/cmd/root.go b/tools/acncli/cmd/root.go index ee4e324f03..6b53c531df 100644 --- a/tools/acncli/cmd/root.go +++ b/tools/acncli/cmd/root.go @@ -14,7 +14,7 @@ import ( // NewRootCmd returns a root func NewRootCmd(version string) *cobra.Command { - var rootCmd = &cobra.Command{ + rootCmd := &cobra.Command{ SilenceUsage: true, Version: version, } @@ -23,7 +23,7 @@ func NewRootCmd(version string) *cobra.Command { viper.SetEnvPrefix(c.EnvPrefix) viper.AutomaticEnv() - var versionCmd = &cobra.Command{ + versionCmd := &cobra.Command{ Use: "version", Short: "Print the version for ACN CLI", Run: func(cmd *cobra.Command, args []string) { diff --git a/tools/acncli/installer/conflist.go b/tools/acncli/installer/conflist.go index 3ef15095de..058cb18232 100644 --- a/tools/acncli/installer/conflist.go +++ b/tools/acncli/installer/conflist.go @@ -55,7 +55,7 @@ func LoadConf(conflistpath string) (ccn.NetworkConfig, rawConflist, int, error) } // find the conflist that matches the AzureCNIBin type - for pluginIndex, _ = range conflist.Plugins { + for pluginIndex = range conflist.Plugins { mapbytes, err := json.Marshal(conflist.Plugins[pluginIndex]) if err != nil { return netconfig, conflist, pluginIndex, err