chore: appease the linter (3/?), the big gofumpt (#987)

* gofumpt -w -s .

* small addtl cleanups after gofumpt

* rerun after rebase
This commit is contained in:
Evan Baker 2021-09-02 16:33:18 -05:00 коммит произвёл GitHub
Родитель 8a60ff1906
Коммит 96bec09d41
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
122 изменённых файлов: 2909 добавлений и 3019 удалений

Просмотреть файл

@ -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)

Просмотреть файл

@ -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"

Просмотреть файл

@ -104,5 +104,4 @@ func TestGetStateWithEmptyStateFile(t *testing.T) {
state, err := c.GetEndpointState()
require.NoError(t, err)
require.Exactly(t, 0, len(state.ContainerInterfaces))
}

Просмотреть файл

@ -21,18 +21,20 @@ import (
"github.com/Azure/azure-container-networking/common"
)
var ipamQueryUrl = "localhost:42424"
var ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.6\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.7\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
var (
ipamQueryUrl = "localhost:42424"
ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.6\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.7\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
)
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))
}

Просмотреть файл

@ -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"`

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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()))
}

Просмотреть файл

@ -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{

Просмотреть файл

@ -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()

Просмотреть файл

@ -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")

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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 {

Просмотреть файл

@ -20,27 +20,30 @@ import (
"github.com/Azure/azure-container-networking/ipam"
)
var plugin IpamPlugin
var mux *http.ServeMux
var (
plugin IpamPlugin
mux *http.ServeMux
)
var ipamQueryUrl = "localhost:42424"
var ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.6\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.7\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.8\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.9\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
var localAsId string
var poolId1 string
var address1 string
var (
ipamQueryUrl = "localhost:42424"
ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.6\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.7\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.8\" IsPrimary=\"false\"/>" +
" <IPAddress Address=\"10.0.0.9\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
localAsId string
poolId1 string
address1 string
)
// Wraps the test run with plugin setup and teardown.
func TestMain(m *testing.M) {

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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.

Просмотреть файл

@ -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
}

Просмотреть файл

@ -27,7 +27,7 @@ func (plugin *Plugin) getAPIServerURL() string {
urls = defaultAPIServerURL + plugin.Name + ".sock"
}
os.MkdirAll(pluginSocketPath, 0755)
os.MkdirAll(pluginSocketPath, 0o755)
return urls
}

Просмотреть файл

@ -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

Просмотреть файл

@ -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))
}

Просмотреть файл

@ -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)

Просмотреть файл

@ -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

Просмотреть файл

@ -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

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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
}
}

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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.

Просмотреть файл

@ -2,10 +2,10 @@
package logger
const (
//Metrics
// Metrics
HeartBeatMetricStr = "HeartBeat"
//Dimensions
// Dimensions
OrchestratorTypeStr = "OrchestratorType"
NodeIDStr = "NodeID"
// CNS Snspshot properties

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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)

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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()

Просмотреть файл

@ -5,8 +5,6 @@
package routes
const ()
func getRoutes() ([]Route, error) {
return nil, nil
}

Просмотреть файл

@ -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...)

Просмотреть файл

@ -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...)

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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",
})
}

Просмотреть файл

@ -30,8 +30,7 @@ type NetApi interface {
}
// IPAM internal interface.
type IpamApi interface {
}
type IpamApi interface{}
// Plugin common configuration.
type PluginConfig struct {

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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

Просмотреть файл

@ -17,19 +17,21 @@ import (
"github.com/Azure/azure-container-networking/common"
)
var ipamQueryUrl = "localhost:42424"
var ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" <IPSubnet Prefix=\"10.1.0.0/16\">" +
" <IPAddress Address=\"10.1.0.4\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
var (
ipamQueryUrl = "localhost:42424"
ipamQueryResponse = "" +
"<Interfaces>" +
" <Interface MacAddress=\"*\" IsPrimary=\"true\">" +
" <IPSubnet Prefix=\"10.0.0.0/16\">" +
" <IPAddress Address=\"10.0.0.4\" IsPrimary=\"true\"/>" +
" <IPAddress Address=\"10.0.0.5\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" <IPSubnet Prefix=\"10.1.0.0/16\">" +
" <IPAddress Address=\"10.1.0.4\" IsPrimary=\"false\"/>" +
" </IPSubnet>" +
" </Interface>" +
"</Interfaces>"
)
// 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 _ = Describe("Test azure source", func() {
var (
testAgent *common.Listener
source *azureSource
err error
)
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))
})
})
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 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 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 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 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())
amImpl := am.(*addressManager)
err = amImpl.source.refresh()
Expect(err).ToNot(HaveOccurred())
as, ok := amImpl.AddrSpaces["local"]
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.5"]
Expect(ok).To(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())
_, ok = pool.Addresses["10.1.0.4"]
Expect(ok).To(BeTrue())
})
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))
})
})
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 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
am, err := createAddressManager(options)
Expect(err).ToNot(HaveOccurred())
amImpl := am.(*addressManager)
err = amImpl.source.refresh()
Expect(err).ToNot(HaveOccurred())
as, ok := amImpl.AddrSpaces["local"]
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.5"]
Expect(ok).To(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())
_, ok = pool.Addresses["10.1.0.4"]
Expect(ok).To(BeTrue())
})
})
})
})

Просмотреть файл

@ -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 := ""

Просмотреть файл

@ -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"
const (
validFileName = "testfiles/masInterfaceConfig.json"
invalidFileName = "mas_test.go"
nonexistentFileName = "bad"
)
var (
_ = Describe("Test MAS", func() {
var _ = Describe("Test MAS", func() {
var (
mas *fileIpamSource
err error
)
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("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 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("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 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))
}
})
})
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())
})
})
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("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
})
})
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())
Expect(len(local.Pools)).To(Equal(1))
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))
_, ok = pool.Addresses["1.1.1.6"]
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",
},
},
},
{
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())
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.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.1.0.0/24"]
Expect(ok).To(BeTrue())
Expect(pool.IfName).To(Equal("eth1"))
Expect(pool.Priority).To(Equal(1))
})
Context("When fileLoaded", func() {
It("refresh return with nil", func() {
mas.fileLoaded = true
err = mas.refresh()
Expect(err).To(BeNil())
mas.fileLoaded = false
})
})
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 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 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 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("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},
},
},
},
},
},
}
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 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},
},
},
},
},
},
}
err := populateAddressSpace(local, sdnInterfaces, localInterfaces)
Expect(err).ToNot(HaveOccurred())
Expect(len(local.Pools)).To(Equal(1))
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))
_, ok = pool.Addresses["1.1.1.6"]
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",
},
},
},
{
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())
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.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.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())
})
})
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())
})
})
})
})

Просмотреть файл

@ -45,104 +45,99 @@ func TestIpv6Ipam(t *testing.T) {
RunSpecs(t, "Ipv6Ipam Suite")
}
var (
_ = Describe("Test ipv6Ipam", func() {
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 newIPv6IpamSource", func() {
Describe("Test start and stop", func() {
source := &ipv6IpamSource{}
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))
})
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())
})
})
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("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
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{})
client := newKubernetesTestClient()
node, _ := client.CoreV1().Nodes().Get(context.TODO(), testNodeName, metav1.GetOptions{})
testInterfaces, err := retrieveKubernetesPodIPs(node, testSubnetSize)
Expect(err).NotTo(HaveOccurred())
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},
},
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
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"},
},
}
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())
})
_, err := retrieveKubernetesPodIPs(testnode, testSubnetSize)
Expect(err).To(HaveOccurred())
})
})
})
)
})

Просмотреть файл

@ -48,74 +48,69 @@ func createTestIpv6AddressManager() (AddressManager, error) {
return am, nil
}
var (
_ = Describe("Test manager ipv6Ipam", func() {
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
)
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("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())
})
})
})
)
})

Просмотреть файл

@ -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())
})
})
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 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())
})
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())
})
})
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("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 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())
})
})
Describe("Test save", func() {
Context("When store is nill", func() {
It("Should return nil", func() {
am := &addressManager{}
err := am.save()
Expect(err).NotTo(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())
})
})
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 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] = "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())
})
})
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 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())
})
})
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())
})
})
})
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())
})
})
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 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())
})
})
})
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"))
})
})
})
})

Просмотреть файл

@ -34,7 +34,6 @@ func (s *nullSource) stop() {
// Refreshes configuration.
func (s *nullSource) refresh() error {
// Initialize once.
if s.initialized {
return nil

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -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,

Просмотреть файл

@ -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

Просмотреть файл

@ -18,6 +18,7 @@ const (
RT_SCOPE_HOST = 254
RT_SCOPE_NOWHERE = 255
)
const (
RTPROT_KERNEL = 2
)

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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())
})
})
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))
})
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())
})
})
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 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())
})
})
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))
})
})
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))
})
})
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 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))
}
})
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())
})
})
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))
})
})
})
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())
})
})
})
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))
})
})
})
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())
})
})
})
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))
}
})
})
})
})

Просмотреть файл

@ -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

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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())
})
})
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())
})
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())
})
})
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 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))
})
})
})
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{}))
})
})
})
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 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 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 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 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())
})
})
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 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{}))
})
})
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))
})
})
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 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 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": {},
"ep2": {},
"ep3": {},
},
}
num := nm.GetNumberOfEndpoints("", nwId)
Expect(num).To(Equal(3))
})
})
})
})

Просмотреть файл

@ -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"))
})
})
})
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 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))
})
})
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 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 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())
})
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 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 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 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())
})
})
})
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())
})
})
})
})

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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

Просмотреть файл

@ -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"
)

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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()

Просмотреть файл

@ -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)
}
}

Просмотреть файл

@ -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(

Просмотреть файл

@ -8,8 +8,6 @@ const (
NPMMgrPath = "/npm/v1/debug/manager"
)
type DescribeIPSetRequest struct {
}
type DescribeIPSetRequest struct{}
type DescribeIPSetResponse struct {
}
type DescribeIPSetResponse struct{}

Просмотреть файл

@ -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))

Просмотреть файл

@ -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"}},

Просмотреть файл

@ -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

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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

Просмотреть файл

@ -3,8 +3,9 @@
package iptm
import (
"golang.org/x/sys/unix"
"os"
"golang.org/x/sys/unix"
)
func grabIptablesFileLock(f *os.File) error {

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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,

Просмотреть файл

@ -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

Просмотреть файл

@ -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))
}

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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)

Просмотреть файл

@ -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

Просмотреть файл

@ -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,

Просмотреть файл

@ -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,
},
},

Просмотреть файл

@ -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

Просмотреть файл

@ -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{

Просмотреть файл

@ -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

Просмотреть файл

@ -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

Просмотреть файл

@ -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"}},

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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"

Просмотреть файл

@ -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
}

Просмотреть файл

@ -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) {

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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{

Просмотреть файл

@ -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)
}

Просмотреть файл

@ -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{

Просмотреть файл

@ -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

Просмотреть файл

@ -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)
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше