* add golint-ci

* add gofmt

* enable linters

* uncap count

* fix linting/fmt issues
This commit is contained in:
Mathew Merrick 2021-06-01 16:58:56 -07:00 коммит произвёл GitHub
Родитель 7f2cfc7b74
Коммит 1fa243e5f5
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
44 изменённых файлов: 525 добавлений и 475 удалений

1
.gitattributes поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
*.go text eol=lf

2
.github/workflows/cyclonus-netpol-test.yaml поставляемый
Просмотреть файл

@ -6,6 +6,8 @@ on:
branches:
- main
pull_request:
paths:
- 'npm/**'
schedule:
# run once a day at midnight
- cron: '0 0 * * *'

34
.github/workflows/repo-hygiene.yaml поставляемый Normal file
Просмотреть файл

@ -0,0 +1,34 @@
name: golangci-lint
on:
workflow_dispatch:
push:
branches:
- main
pull_request:
schedule:
# run once a day at midnight
- cron: '0 0 * * *'
jobs:
golangci:
strategy:
matrix:
go-version: [1.16.x]
os: [ubuntu-latest, windows-latest]
name: Lint
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.40
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
args: --timeout=5m
# Optional: show only new issues if it's a pull request. The default value is `false`.
only-new-issues: true

24
.golangci.yml Normal file
Просмотреть файл

@ -0,0 +1,24 @@
issues:
max-same-issues: 0
max-issues-per-linter: 0
enable:
- bodyclose
- deadcode
- errcheck
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- golint
- gomnd
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- interfacer
- lll
- misspell
- nakedret

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

@ -131,4 +131,4 @@ func GetPoliciesFromNwCfg(kvp []KVPair) []policy.Policy {
func (nwcfg *NetworkConfig) Serialize() []byte {
bytes, _ := json.Marshal(nwcfg)
return bytes
}
}

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

@ -1,20 +1,20 @@
package network
import (
"net"
"github.com/Azure/azure-container-networking/cni"
cniTypesCurr "github.com/containernetworking/cni/pkg/types/current"
)
// IPAMInvoker is used by the azure-vnet CNI plugin to call different sources for IPAM.
// This interface can be used to call into external binaries, like the azure-vnet-ipam binary,
// 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(nwCfg *cni.NetworkConfig, 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(address *net.IPNet, nwCfg *cni.NetworkConfig, options map[string]interface{}) error
}
package network
import (
"net"
"github.com/Azure/azure-container-networking/cni"
cniTypesCurr "github.com/containernetworking/cni/pkg/types/current"
)
// IPAMInvoker is used by the azure-vnet CNI plugin to call different sources for IPAM.
// This interface can be used to call into external binaries, like the azure-vnet-ipam binary,
// 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(nwCfg *cni.NetworkConfig, 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(address *net.IPNet, nwCfg *cni.NetworkConfig, options map[string]interface{}) error
}

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

@ -1,180 +1,182 @@
package network
import (
"encoding/json"
"fmt"
"net"
"strconv"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cns"
"github.com/Azure/azure-container-networking/cns/cnsclient"
"github.com/Azure/azure-container-networking/iptables"
"github.com/Azure/azure-container-networking/log"
"github.com/Azure/azure-container-networking/network"
cniTypes "github.com/containernetworking/cni/pkg/types"
cniTypesCurr "github.com/containernetworking/cni/pkg/types/current"
)
const (
cnsPort = 10090
)
type CNSIPAMInvoker struct {
podName string
podNamespace string
primaryInterfaceName string
cnsClient *cnsclient.CNSClient
}
type IPv4ResultInfo struct {
podIPAddress string
ncSubnetPrefix uint8
ncPrimaryIP string
ncGatewayIPAddress string
hostSubnet string
hostPrimaryIP string
hostGateway string
}
func NewCNSInvoker(podName, namespace string) (*CNSIPAMInvoker, error) {
cnsURL := "http://localhost:" + strconv.Itoa(cnsPort)
cnsClient, err := cnsclient.InitCnsClient(cnsURL, defaultRequestTimeout)
return &CNSIPAMInvoker{
podName: podName,
podNamespace: namespace,
cnsClient: cnsClient,
}, err
}
//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, hostSubnetPrefix *net.IPNet, options map[string]interface{}) (*cniTypesCurr.Result, *cniTypesCurr.Result, error) {
// Parse Pod arguments.
podInfo := cns.KubernetesPodInfo{PodName: invoker.podName, PodNamespace: invoker.podNamespace}
orchestratorContext, err := json.Marshal(podInfo)
log.Printf("Requesting IP for pod %v", podInfo)
response, err := invoker.cnsClient.RequestIPAddress(orchestratorContext)
if err != nil {
log.Printf("Failed to get IP address from CNS with error %v, response: %v", err, response)
return nil, nil, err
}
info := IPv4ResultInfo{
podIPAddress: response.PodIpInfo.PodIPConfig.IPAddress,
ncSubnetPrefix: response.PodIpInfo.NetworkContainerPrimaryIPConfig.IPSubnet.PrefixLength,
ncPrimaryIP: response.PodIpInfo.NetworkContainerPrimaryIPConfig.IPSubnet.IPAddress,
ncGatewayIPAddress: response.PodIpInfo.NetworkContainerPrimaryIPConfig.GatewayIPAddress,
hostSubnet: response.PodIpInfo.HostPrimaryIPInfo.Subnet,
hostPrimaryIP: response.PodIpInfo.HostPrimaryIPInfo.PrimaryIP,
hostGateway: response.PodIpInfo.HostPrimaryIPInfo.Gateway,
}
// set the NC Primary IP in options
options[network.SNATIPKey] = info.ncPrimaryIP
log.Printf("[cni-invoker-cns] Received info %v for pod %v", info, podInfo)
ncgw := net.ParseIP(info.ncGatewayIPAddress)
if ncgw == nil {
return nil, nil, fmt.Errorf("Gateway address %v from response is invalid", info.ncGatewayIPAddress)
}
// set result ipconfig from CNS Response Body
ip, ncipnet, err := net.ParseCIDR(info.podIPAddress + "/" + fmt.Sprint(info.ncSubnetPrefix))
if ip == nil {
return nil, nil, fmt.Errorf("Unable to parse IP from response: %v with err %v", info.podIPAddress, err)
}
// construct ipnet for result
resultIPnet := net.IPNet{
IP: ip,
Mask: ncipnet.Mask,
}
result := &cniTypesCurr.Result{
IPs: []*cniTypesCurr.IPConfig{
{
Version: "4",
Address: resultIPnet,
Gateway: ncgw,
},
},
Routes: []*cniTypes.Route{
{
Dst: network.Ipv4DefaultRouteDstPrefix,
GW: ncgw,
},
},
}
// set subnet prefix for host vm
err = setHostOptions(nwCfg, hostSubnetPrefix, ncipnet, options, info)
if err != nil {
return nil, nil, err
}
// first result is ipv4, second is ipv6, SWIFT doesn't currently support IPv6
return result, nil, nil
}
func setHostOptions(nwCfg *cni.NetworkConfig, hostSubnetPrefix *net.IPNet, ncSubnetPrefix *net.IPNet, options map[string]interface{}, info IPv4ResultInfo) error {
// get the name of the primary IP address
_, hostIPNet, err := net.ParseCIDR(info.hostSubnet)
if err != nil {
return err
}
*hostSubnetPrefix = *hostIPNet
// get the host ip
hostIP := net.ParseIP(info.hostPrimaryIP)
if hostIP == nil {
return fmt.Errorf("Host IP address %v from response is invalid", info.hostPrimaryIP)
}
// get host gateway
hostGateway := net.ParseIP(info.hostGateway)
if hostGateway == nil {
return fmt.Errorf("Host Gateway %v from response is invalid", info.hostGateway)
}
// this route is needed when the vm on subnet A needs to send traffic to a pod in subnet B on a different vm
options[network.RoutesKey] = []network.RouteInfo{
{
Dst: *ncSubnetPrefix,
Gw: hostGateway,
},
}
azureDNSMatch := fmt.Sprintf(" -m addrtype ! --dst-type local -s %s -d %s -p %s --dport %d", ncSubnetPrefix.String(), iptables.AzureDNS, iptables.UDP, iptables.DNSPort)
// TODO remove this rule once we remove adding MASQUEARDE from AgentBaker, check below PR
// https://github.com/Azure/AgentBaker/pull/367/files
podTrafficAccept := fmt.Sprintf(" -m iprange ! --dst-range 168.63.129.16-168.63.129.16 -s %s ", ncSubnetPrefix.String())
snatPrimaryIPJump := fmt.Sprintf("%s --to %s", iptables.Snat, info.ncPrimaryIP)
options[network.IPTablesKey] = []iptables.IPTableEntry{
iptables.GetCreateChainCmd(iptables.V4, iptables.Nat, iptables.Swift),
iptables.GetInsertIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Postrouting, podTrafficAccept, iptables.Accept),
iptables.GetAppendIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Postrouting, "", iptables.Swift),
iptables.GetInsertIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Swift, azureDNSMatch, snatPrimaryIPJump),
}
return nil
}
// Delete calls into the releaseipconfiguration API in CNS
func (invoker *CNSIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkConfig, options map[string]interface{}) error {
// Parse Pod arguments.
podInfo := cns.KubernetesPodInfo{PodName: invoker.podName, PodNamespace: invoker.podNamespace}
orchestratorContext, err := json.Marshal(podInfo)
if err != nil {
return err
}
return invoker.cnsClient.ReleaseIPAddress(orchestratorContext)
}
package network
import (
"encoding/json"
"fmt"
"net"
"strconv"
"github.com/Azure/azure-container-networking/cni"
"github.com/Azure/azure-container-networking/cns"
"github.com/Azure/azure-container-networking/cns/cnsclient"
"github.com/Azure/azure-container-networking/iptables"
"github.com/Azure/azure-container-networking/log"
"github.com/Azure/azure-container-networking/network"
cniTypes "github.com/containernetworking/cni/pkg/types"
cniTypesCurr "github.com/containernetworking/cni/pkg/types/current"
)
const (
cnsPort = 10090
)
type CNSIPAMInvoker struct {
podName string
podNamespace string
cnsClient *cnsclient.CNSClient
}
type IPv4ResultInfo struct {
podIPAddress string
ncSubnetPrefix uint8
ncPrimaryIP string
ncGatewayIPAddress string
hostSubnet string
hostPrimaryIP string
hostGateway string
}
func NewCNSInvoker(podName, namespace string) (*CNSIPAMInvoker, error) {
cnsURL := "http://localhost:" + strconv.Itoa(cnsPort)
cnsClient, err := cnsclient.InitCnsClient(cnsURL, defaultRequestTimeout)
return &CNSIPAMInvoker{
podName: podName,
podNamespace: namespace,
cnsClient: cnsClient,
}, err
}
//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, hostSubnetPrefix *net.IPNet, options map[string]interface{}) (*cniTypesCurr.Result, *cniTypesCurr.Result, error) {
// Parse Pod arguments.
podInfo := cns.KubernetesPodInfo{PodName: invoker.podName, PodNamespace: invoker.podNamespace}
orchestratorContext, err := json.Marshal(podInfo)
if err != nil {
return nil, nil, err
}
log.Printf("Requesting IP for pod %v", podInfo)
response, err := invoker.cnsClient.RequestIPAddress(orchestratorContext)
if err != nil {
log.Printf("Failed to get IP address from CNS with error %v, response: %v", err, response)
return nil, nil, err
}
info := IPv4ResultInfo{
podIPAddress: response.PodIpInfo.PodIPConfig.IPAddress,
ncSubnetPrefix: response.PodIpInfo.NetworkContainerPrimaryIPConfig.IPSubnet.PrefixLength,
ncPrimaryIP: response.PodIpInfo.NetworkContainerPrimaryIPConfig.IPSubnet.IPAddress,
ncGatewayIPAddress: response.PodIpInfo.NetworkContainerPrimaryIPConfig.GatewayIPAddress,
hostSubnet: response.PodIpInfo.HostPrimaryIPInfo.Subnet,
hostPrimaryIP: response.PodIpInfo.HostPrimaryIPInfo.PrimaryIP,
hostGateway: response.PodIpInfo.HostPrimaryIPInfo.Gateway,
}
// set the NC Primary IP in options
options[network.SNATIPKey] = info.ncPrimaryIP
log.Printf("[cni-invoker-cns] Received info %v for pod %v", info, podInfo)
ncgw := net.ParseIP(info.ncGatewayIPAddress)
if ncgw == nil {
return nil, nil, fmt.Errorf("Gateway address %v from response is invalid", info.ncGatewayIPAddress)
}
// set result ipconfig from CNS Response Body
ip, ncipnet, err := net.ParseCIDR(info.podIPAddress + "/" + fmt.Sprint(info.ncSubnetPrefix))
if ip == nil {
return nil, nil, fmt.Errorf("Unable to parse IP from response: %v with err %v", info.podIPAddress, err)
}
// construct ipnet for result
resultIPnet := net.IPNet{
IP: ip,
Mask: ncipnet.Mask,
}
result := &cniTypesCurr.Result{
IPs: []*cniTypesCurr.IPConfig{
{
Version: "4",
Address: resultIPnet,
Gateway: ncgw,
},
},
Routes: []*cniTypes.Route{
{
Dst: network.Ipv4DefaultRouteDstPrefix,
GW: ncgw,
},
},
}
// set subnet prefix for host vm
err = setHostOptions(nwCfg, hostSubnetPrefix, ncipnet, options, info)
if err != nil {
return nil, nil, err
}
// first result is ipv4, second is ipv6, SWIFT doesn't currently support IPv6
return result, nil, nil
}
func setHostOptions(nwCfg *cni.NetworkConfig, hostSubnetPrefix *net.IPNet, ncSubnetPrefix *net.IPNet, options map[string]interface{}, info IPv4ResultInfo) error {
// get the name of the primary IP address
_, hostIPNet, err := net.ParseCIDR(info.hostSubnet)
if err != nil {
return err
}
*hostSubnetPrefix = *hostIPNet
// get the host ip
hostIP := net.ParseIP(info.hostPrimaryIP)
if hostIP == nil {
return fmt.Errorf("Host IP address %v from response is invalid", info.hostPrimaryIP)
}
// get host gateway
hostGateway := net.ParseIP(info.hostGateway)
if hostGateway == nil {
return fmt.Errorf("Host Gateway %v from response is invalid", info.hostGateway)
}
// this route is needed when the vm on subnet A needs to send traffic to a pod in subnet B on a different vm
options[network.RoutesKey] = []network.RouteInfo{
{
Dst: *ncSubnetPrefix,
Gw: hostGateway,
},
}
azureDNSMatch := fmt.Sprintf(" -m addrtype ! --dst-type local -s %s -d %s -p %s --dport %d", ncSubnetPrefix.String(), iptables.AzureDNS, iptables.UDP, iptables.DNSPort)
// TODO remove this rule once we remove adding MASQUEARDE from AgentBaker, check below PR
// https://github.com/Azure/AgentBaker/pull/367/files
podTrafficAccept := fmt.Sprintf(" -m iprange ! --dst-range 168.63.129.16-168.63.129.16 -s %s ", ncSubnetPrefix.String())
snatPrimaryIPJump := fmt.Sprintf("%s --to %s", iptables.Snat, info.ncPrimaryIP)
options[network.IPTablesKey] = []iptables.IPTableEntry{
iptables.GetCreateChainCmd(iptables.V4, iptables.Nat, iptables.Swift),
iptables.GetInsertIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Postrouting, podTrafficAccept, iptables.Accept),
iptables.GetAppendIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Postrouting, "", iptables.Swift),
iptables.GetInsertIptableRuleCmd(iptables.V4, iptables.Nat, iptables.Swift, azureDNSMatch, snatPrimaryIPJump),
}
return nil
}
// Delete calls into the releaseipconfiguration API in CNS
func (invoker *CNSIPAMInvoker) Delete(address *net.IPNet, nwCfg *cni.NetworkConfig, options map[string]interface{}) error {
// Parse Pod arguments.
podInfo := cns.KubernetesPodInfo{PodName: invoker.podName, PodNamespace: invoker.podNamespace}
orchestratorContext, err := json.Marshal(podInfo)
if err != nil {
return err
}
return invoker.cnsClient.ReleaseIPAddress(orchestratorContext)
}

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

@ -262,4 +262,4 @@ func main() {
log.Printf("Sending report succeeded")
}
}
}
}

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

@ -306,7 +306,6 @@ func (fake *HTTPServiceFake) Start(*common.ServiceConfig) error {
return nil
}
func (fake *HTTPServiceFake) Init(*common.ServiceConfig) error {
return nil
}

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

@ -10,8 +10,8 @@ import (
"os"
"testing"
"github.com/Azure/azure-container-networking/common"
"github.com/Azure/azure-container-networking/cnm/ipam"
"github.com/Azure/azure-container-networking/common"
)
var mux *http.ServeMux

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

@ -78,7 +78,6 @@ func (pm *CNSIPAMPoolMonitor) Reconcile() error {
batchSize := pm.getBatchSize() //Use getters in case customer changes batchsize manually
maxIPCount := pm.getMaxIPCount()
msg := fmt.Sprintf("[ipam-pool-monitor] Pool Size: %v, Goal Size: %v, BatchSize: %v, MaxIPCount: %v, MinFree: %v, MaxFree:%v, Allocated: %v, Available: %v, Pending Release: %v, Free: %v, Pending Program: %v",
cnsPodIPConfigCount, pm.cachedNNC.Spec.RequestedIPCount, batchSize, maxIPCount, pm.MinimumFreeIps, pm.MaximumFreeIps, allocatedPodIPCount, availableIPConfigCount, pendingReleaseIPCount, freeIPConfigCount, pendingProgramCount)
@ -181,13 +180,13 @@ func (pm *CNSIPAMPoolMonitor) decreasePoolSize(existingPendingReleaseIPCount int
// Don't want that, so make requestedIPCount 20 (25 - (25 % 10)) so that it is a multiple of the batchsize (10)
updatedRequestedIPCount = previouslyRequestedIPCount - modResult
} else {
// Example: previouscount = 30, batchsize = 10, 30 - 10 = 20 which is multiple of batchsize (10) so all good
// Example: previouscount = 30, batchsize = 10, 30 - 10 = 20 which is multiple of batchsize (10) so all good
updatedRequestedIPCount = previouslyRequestedIPCount - batchSize
}
decreaseIPCountBy = previouslyRequestedIPCount - updatedRequestedIPCount
decreaseIPCountBy = previouslyRequestedIPCount - updatedRequestedIPCount
logger.Printf("[ipam-pool-monitor] updatedRequestedIPCount %v", updatedRequestedIPCount)
logger.Printf("[ipam-pool-monitor] updatedRequestedIPCount %v", updatedRequestedIPCount)
if pm.updatingIpsNotInUseCount == 0 ||
pm.updatingIpsNotInUseCount < existingPendingReleaseIPCount {

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

@ -38,7 +38,7 @@ func TestPoolSizeIncrease(t *testing.T) {
initialIPConfigCount = 10
requestThresholdPercent = 30
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, fakerc, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -92,7 +92,7 @@ func TestPoolIncreaseDoesntChangeWhenIncreaseIsAlreadyInProgress(t *testing.T) {
initialIPConfigCount = 10
requestThresholdPercent = 30
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, fakerc, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -158,7 +158,7 @@ func TestPoolSizeIncreaseIdempotency(t *testing.T) {
initialIPConfigCount = 10
requestThresholdPercent = 30
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -197,11 +197,11 @@ func TestPoolSizeIncreaseIdempotency(t *testing.T) {
func TestPoolIncreasePastNodeLimit(t *testing.T) {
var (
batchSize = 16
initialIPConfigCount = 16
batchSize = 16
initialIPConfigCount = 16
requestThresholdPercent = 50
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -229,11 +229,11 @@ func TestPoolIncreasePastNodeLimit(t *testing.T) {
func TestPoolIncreaseBatchSizeGreaterThanMaxPodIPCount(t *testing.T) {
var (
batchSize = 50
initialIPConfigCount = 16
batchSize = 50
initialIPConfigCount = 16
requestThresholdPercent = 50
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -261,12 +261,12 @@ func TestPoolIncreaseBatchSizeGreaterThanMaxPodIPCount(t *testing.T) {
func TestPoolIncreaseMaxIPCountSetToZero(t *testing.T) {
var (
batchSize = 16
initialIPConfigCount = 16
batchSize = 16
initialIPConfigCount = 16
requestThresholdPercent = 50
releaseThresholdPercent = 150
initialMaxPodIPCount = int64(0)
expectedMaxPodIPCount = defaultMaxIPCount
initialMaxPodIPCount = int64(0)
expectedMaxPodIPCount = defaultMaxIPCount
)
_, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, initialMaxPodIPCount)
@ -282,7 +282,7 @@ func TestPoolDecrease(t *testing.T) {
initialIPConfigCount = 20
requestThresholdPercent = 30
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, fakerc, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -339,7 +339,7 @@ func TestPoolSizeDecreaseWhenDecreaseHasAlreadyBeenRequested(t *testing.T) {
initialIPConfigCount = 20
requestThresholdPercent = 30
releaseThresholdPercent = 100
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, fakerc, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -407,7 +407,7 @@ func TestPoolSizeDecreaseToReallyLow(t *testing.T) {
initialIPConfigCount = 30
requestThresholdPercent = 30
releaseThresholdPercent = 100
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, fakerc, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -486,13 +486,13 @@ func TestPoolSizeDecreaseToReallyLow(t *testing.T) {
func TestDecreaseAfterNodeLimitReached(t *testing.T) {
var (
batchSize = 16
initialIPConfigCount = 30
batchSize = 16
initialIPConfigCount = 30
requestThresholdPercent = 50
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
expectedRequestedIP = 16
expectedDecreaseIP = int(maxPodIPCount) % batchSize
maxPodIPCount = int64(30)
expectedRequestedIP = 16
expectedDecreaseIP = int(maxPodIPCount) % batchSize
)
fakecns, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -534,11 +534,11 @@ func TestDecreaseAfterNodeLimitReached(t *testing.T) {
func TestPoolDecreaseBatchSizeGreaterThanMaxPodIPCount(t *testing.T) {
var (
batchSize = 31
initialIPConfigCount = 30
batchSize = 31
initialIPConfigCount = 30
requestThresholdPercent = 50
releaseThresholdPercent = 150
maxPodIPCount = int64(30)
maxPodIPCount = int64(30)
)
fakecns, _, poolmonitor := initFakes(batchSize, initialIPConfigCount, requestThresholdPercent, releaseThresholdPercent, maxPodIPCount)
@ -573,4 +573,4 @@ func TestPoolDecreaseBatchSizeGreaterThanMaxPodIPCount(t *testing.T) {
if poolmonitor.cachedNNC.Spec.RequestedIPCount != maxPodIPCount {
t.Fatalf("Pool monitor target IP count (%v) should be the node limit (%v) when the max has been reached", poolmonitor.cachedNNC.Spec.RequestedIPCount, maxPodIPCount)
}
}
}

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

@ -42,7 +42,6 @@ func (r *CrdReconciler) Reconcile(request reconcile.Request) (reconcile.Result,
logger.Printf("[cns-rc] CRD Spec: %v", nodeNetConfig.Spec)
// If there are no network containers, don't hand it off to CNS
if len(nodeNetConfig.Status.NetworkContainers) == 0 {
logger.Errorf("[cns-rc] Empty NetworkContainers")
@ -50,7 +49,7 @@ func (r *CrdReconciler) Reconcile(request reconcile.Request) (reconcile.Result,
}
networkContainer := nodeNetConfig.Status.NetworkContainers[0]
logger.Printf("[cns-rc] CRD Status: NcId: [%s], Version: [%d], podSubnet: [%s], Subnet CIDR: [%s], " +
logger.Printf("[cns-rc] CRD Status: NcId: [%s], Version: [%d], podSubnet: [%s], Subnet CIDR: [%s], "+
"Gateway Addr: [%s], Primary IP: [%s], SecondaryIpsCount: [%d]",
networkContainer.ID,
networkContainer.Version,

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

@ -271,7 +271,7 @@ func (crdRC *crdRequestController) initCNS() error {
}
// UpdateCRDSpec updates the CRD spec
func (crdRC *crdRequestController) UpdateCRDSpec(cntxt context.Context, crdSpec nnc.NodeNetworkConfigSpec) error {
func (crdRC *crdRequestController) UpdateCRDSpec(cntxt context.Context, crdSpec nnc.NodeNetworkConfigSpec) error {
nodeNetworkConfig, err := crdRC.getNodeNetConfig(cntxt, crdRC.nodeName, k8sNamespace)
if err != nil {
logger.Errorf("[cns-rc] Error getting CRD when updating spec %v", err)

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

@ -512,7 +512,7 @@ func main() {
}
logger.Printf("[Azure CNS] Start HTTP listener")
if (httpRestService != nil) {
if httpRestService != nil {
err = httpRestService.Start(&config)
if err != nil {
logger.Errorf("Failed to start CNS, err:%v.\n", err)
@ -686,7 +686,7 @@ func IniitalizeCRDState(httpRestService cns.HTTPService, cnsconfig configuration
httpRestServiceImplementation, ok := httpRestService.(*restserver.HTTPRestService)
if !ok {
logger.Errorf("[Azure CNS] Failed to convert interface httpRestService to implementation: %v", httpRestService)
return fmt.Errorf("[Azure CNS] Failed to convert interface httpRestService to implementation: %v",
return fmt.Errorf("[Azure CNS] Failed to convert interface httpRestService to implementation: %v",
httpRestService)
}
@ -703,7 +703,7 @@ func IniitalizeCRDState(httpRestService cns.HTTPService, cnsconfig configuration
return err
}
// initialize the ipam pool monitor
// initialize the ipam pool monitor
httpRestServiceImplementation.IPAMPoolMonitor = ipampoolmonitor.NewCNSIPAMPoolMonitor(httpRestServiceImplementation, requestController)
err = requestController.InitRequestController()

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

@ -5,13 +5,13 @@ 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"
)
func TestFileIpam(t *testing.T) {
@ -276,11 +276,11 @@ var (
IsPrimary: true,
IPSubnets: []IPSubnet{
{
Prefix: "0.0.0.0/24",
Prefix: "0.0.0.0/24",
IPAddresses: []IPAddress{},
},
{
Prefix: "0.1.0.0/24",
Prefix: "0.1.0.0/24",
IPAddresses: []IPAddress{},
},
{
@ -293,22 +293,22 @@ var (
},
{
MacAddress: "111111111111",
IsPrimary: false,
IsPrimary: false,
IPSubnets: []IPSubnet{
{
Prefix: "1.0.0.0/24",
Prefix: "1.0.0.0/24",
IPAddresses: []IPAddress{},
},
{
Prefix: "1.1.0.0/24",
Prefix: "1.1.0.0/24",
IPAddresses: []IPAddress{},
},
},
},
{
MacAddress: "222222222222",
IsPrimary: false,
IPSubnets: []IPSubnet{},
IsPrimary: false,
IPSubnets: []IPSubnet{},
},
},
}

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

@ -9,12 +9,12 @@ import (
"runtime"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
testclient "k8s.io/client-go/kubernetes/fake"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/Azure/azure-container-networking/common"
)
@ -146,4 +146,3 @@ var (
})
})
)

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

@ -24,7 +24,6 @@ func TestManagerIpv6Ipam(t *testing.T) {
RunSpecs(t, "Manager ipv6ipam Suite")
}
func createTestIpv6AddressManager() (AddressManager, error) {
var config common.PluginConfig
var options map[string]interface{}
@ -57,10 +56,10 @@ var (
Describe("Test IPv6 get address pool and address", func() {
var (
am AddressManager
err error
poolID1 string
subnet1 string
am AddressManager
err error
poolID1 string
subnet1 string
address2 string
address3 string
)
@ -92,7 +91,7 @@ var (
It("Should request address successfully", func() {
address2, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, ipv6addr2, nil)
Expect(err).NotTo(HaveOccurred())
Expect(address2).To(Equal(ipv6addr2+testSubnetSize))
Expect(address2).To(Equal(ipv6addr2 + testSubnetSize))
})
})
@ -100,7 +99,7 @@ var (
It("Should request address successfully", func() {
address3, err := am.RequestAddress(LocalDefaultAddressSpaceId, poolID1, "", nil)
Expect(err).NotTo(HaveOccurred())
Expect(address3).To(Equal(ipv6addr3+testSubnetSize))
Expect(address3).To(Equal(ipv6addr3 + testSubnetSize))
})
})

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

@ -564,8 +564,8 @@ var (
}
poolId := "10.0.0.0/16"
as.Pools[poolId] = &addressPool{
Id: poolId,
RefCount: 1,
Id: poolId,
RefCount: 1,
Addresses: map[string]*addressRecord{},
}
as.Pools[poolId].Addresses["10.0.0.2"] = &addressRecord{
@ -579,7 +579,6 @@ var (
})
})
Context("When pool is in use and it has ips allocated", func() {
It("Should raise an error", func() {
as := &addressSpace{
@ -587,8 +586,8 @@ var (
}
poolId := "10.0.0.0/16"
as.Pools[poolId] = &addressPool{
Id: poolId,
RefCount: 1,
Id: poolId,
RefCount: 1,
Addresses: map[string]*addressRecord{},
}
as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{
@ -613,8 +612,8 @@ var (
}
poolId := "10.0.0.0/16"
as.Pools[poolId] = &addressPool{
Id: poolId,
RefCount: 1,
Id: poolId,
RefCount: 1,
Addresses: map[string]*addressRecord{},
}
as.Pools[poolId].Addresses["10.0.0.1"] = &addressRecord{

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

@ -1,54 +1,54 @@
// Copyright 2017 Microsoft. All rights reserved.
// MIT License
package log
import (
"fmt"
"io"
"log"
"log/syslog"
"os"
)
const (
// LogPath is the path where log files are stored.
LogPath = "/var/log/"
)
// SetTarget sets the log target.
func (logger *Logger) SetTarget(target int) error {
var err error
switch target {
case TargetStdout:
logger.out = os.Stdout
case TargetStderr:
logger.out = os.Stderr
case TargetSyslog:
logger.out, err = syslog.New(log.LstdFlags, logger.name)
case TargetLogfile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
case TargetStdOutAndLogFile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
if err == nil {
logger.l.SetOutput(io.MultiWriter(os.Stdout, logger.out))
logger.target = target
return nil
}
default:
err = fmt.Errorf("Invalid log target %d", target)
}
if err == nil {
logger.l.SetOutput(logger.out)
logger.target = target
}
return err
}
// Copyright 2017 Microsoft. All rights reserved.
// MIT License
package log
import (
"fmt"
"io"
"log"
"log/syslog"
"os"
)
const (
// LogPath is the path where log files are stored.
LogPath = "/var/log/"
)
// SetTarget sets the log target.
func (logger *Logger) SetTarget(target int) error {
var err error
switch target {
case TargetStdout:
logger.out = os.Stdout
case TargetStderr:
logger.out = os.Stderr
case TargetSyslog:
logger.out, err = syslog.New(log.LstdFlags, logger.name)
case TargetLogfile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
case TargetStdOutAndLogFile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
if err == nil {
logger.l.SetOutput(io.MultiWriter(os.Stdout, logger.out))
logger.target = target
return nil
}
default:
err = fmt.Errorf("Invalid log target %d", target)
}
if err == nil {
logger.l.SetOutput(logger.out)
logger.target = target
}
return err
}

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

@ -1,46 +1,46 @@
// Copyright 2017 Microsoft. All rights reserved.
// MIT License
package log
import (
"fmt"
"io"
"os"
)
const (
// LogPath is the path where log files are stored.
LogPath = ""
)
// SetTarget sets the log target.
func (logger *Logger) SetTarget(target int) error {
var err error
switch target {
case TargetStderr:
logger.out = os.Stderr
case TargetLogfile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
case TargetStdOutAndLogFile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
if err == nil {
logger.l.SetOutput(io.MultiWriter(os.Stdout, logger.out))
logger.target = target
return nil
}
default:
err = fmt.Errorf("Invalid log target %d", target)
}
if err == nil {
logger.l.SetOutput(logger.out)
logger.target = target
}
return err
}
// Copyright 2017 Microsoft. All rights reserved.
// MIT License
package log
import (
"fmt"
"io"
"os"
)
const (
// LogPath is the path where log files are stored.
LogPath = ""
)
// SetTarget sets the log target.
func (logger *Logger) SetTarget(target int) error {
var err error
switch target {
case TargetStderr:
logger.out = os.Stderr
case TargetLogfile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
case TargetStdOutAndLogFile:
logger.out, err = os.OpenFile(logger.getLogFileName(), os.O_CREATE|os.O_APPEND|os.O_RDWR, logFilePerm)
if err == nil {
logger.l.SetOutput(io.MultiWriter(os.Stdout, logger.out))
logger.target = target
return nil
}
default:
err = fmt.Errorf("Invalid log target %d", target)
}
if err == nil {
logger.l.SetOutput(logger.out)
logger.target = target
}
return err
}

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

@ -210,12 +210,12 @@ func (ep *endpoint) getInfo() *EndpointInfo {
EnableMultiTenancy: ep.EnableMultitenancy,
AllowInboundFromHostToNC: ep.AllowInboundFromHostToNC,
AllowInboundFromNCToHost: ep.AllowInboundFromNCToHost,
IfName: ep.IfName,
ContainerID: ep.ContainerID,
NetNsPath: ep.NetworkNameSpace,
PODName: ep.PODName,
PODNameSpace: ep.PODNameSpace,
NetworkContainerID: ep.NetworkContainerID,
IfName: ep.IfName,
ContainerID: ep.ContainerID,
NetNsPath: ep.NetworkNameSpace,
PODName: ep.PODName,
PODNameSpace: ep.PODNameSpace,
NetworkContainerID: ep.NetworkContainerID,
}
for _, route := range ep.Routes {

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

@ -57,11 +57,11 @@ var (
Endpoints: map[string]*endpoint{},
}
nw.Endpoints["pod1"] = &endpoint{
PODName: podName,
PODName: podName,
PODNameSpace: podNS,
}
nw.Endpoints["pod2"] = &endpoint{
PODName: podName,
PODName: podName,
PODNameSpace: podNS,
}
ep, err := nw.getEndpointByPOD(podName, podNS, true)
@ -89,7 +89,7 @@ var (
Endpoints: map[string]*endpoint{},
}
nw.Endpoints["pod"] = &endpoint{
PODName: podName,
PODName: podName,
PODNameSpace: podNS,
}
ep, err := nw.getEndpointByPOD(podName, podNS, true)
@ -187,9 +187,9 @@ var (
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",
"nginx-deployment-5c689d88bb": "nginx",
"nginx-deployment-5c689d88bb-qwq47": "nginx-deployment",
"nginx": "nginx",
}
for testValue, expectedPodName := range testData {
podName := GetPodNameWithoutSuffix(testValue)

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

@ -373,16 +373,16 @@ func (nw *network) newEndpointImplHnsV2(epInfo *EndpointInfo) (*endpoint, error)
// Create the endpoint object.
ep := &endpoint{
Id: hcnEndpoint.Name,
HnsId: hnsResponse.Id,
SandboxKey: epInfo.ContainerID,
IfName: epInfo.IfName,
IPAddresses: epInfo.IPAddresses,
Gateways: []net.IP{gateway},
DNS: epInfo.DNS,
VlanID: vlanid,
EnableSnatOnHost: epInfo.EnableSnatOnHost,
NetNs: epInfo.NetNsPath,
Id: hcnEndpoint.Name,
HnsId: hnsResponse.Id,
SandboxKey: epInfo.ContainerID,
IfName: epInfo.IfName,
IPAddresses: epInfo.IPAddresses,
Gateways: []net.IP{gateway},
DNS: epInfo.DNS,
VlanID: vlanid,
EnableSnatOnHost: epInfo.EnableSnatOnHost,
NetNs: epInfo.NetNsPath,
AllowInboundFromNCToHost: epInfo.AllowInboundFromNCToHost,
AllowInboundFromHostToNC: epInfo.AllowInboundFromHostToNC,
NetworkContainerID: epInfo.NetworkContainerID,

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

@ -24,8 +24,8 @@ var (
ExternalInterfaces: map[string]*externalInterface{},
}
nm.ExternalInterfaces[ifName] = &externalInterface{
Name: ifName,
Subnets: []string{"10.0.0.0/16"},
Name: ifName,
Subnets: []string{"10.0.0.0/16"},
}
err := nm.newExternalInterface(ifName, "10.1.0.0/16")
Expect(err).To(BeNil())
@ -43,8 +43,8 @@ var (
ExternalInterfaces: map[string]*externalInterface{},
}
nm.ExternalInterfaces[ifName] = &externalInterface{
Name: ifName,
Subnets: []string{"10.0.0.0/16", "10.1.0.0/16"},
Name: ifName,
Subnets: []string{"10.0.0.0/16", "10.1.0.0/16"},
}
err := nm.deleteExternalInterface(ifName)
Expect(err).NotTo(HaveOccurred())
@ -60,12 +60,12 @@ var (
ExternalInterfaces: map[string]*externalInterface{},
}
nm.ExternalInterfaces["eth0"] = &externalInterface{
Name: "eth0",
Subnets: []string{"subnet1", "subnet2"},
Name: "eth0",
Subnets: []string{"subnet1", "subnet2"},
}
nm.ExternalInterfaces["en0"] = &externalInterface{
Name: "en0",
Subnets: []string{"subnet3", "subnet4"},
Name: "en0",
Subnets: []string{"subnet3", "subnet4"},
}
exInterface := nm.findExternalInterfaceBySubnet("subnet4")
Expect(exInterface.Name).To(Equal("en0"))
@ -82,7 +82,7 @@ var (
ExternalInterfaces: map[string]*externalInterface{},
}
nm.ExternalInterfaces["eth0"] = &externalInterface{
Name: "eth0",
Name: "eth0",
}
nm.ExternalInterfaces["en0"] = nil
exInterface := nm.findExternalInterfaceByName("eth0")
@ -131,8 +131,8 @@ var (
nwInfo := &NetworkInfo{
Subnets: []SubnetInfo{{
Prefix: net.IPNet{
IP: net.IPv4(10,0,0,1),
Mask: net.IPv4Mask(255,255,0,0),
IP: net.IPv4(10, 0, 0, 1),
Mask: net.IPv4Mask(255, 255, 0, 0),
},
}},
}
@ -152,7 +152,7 @@ var (
}
nm.ExternalInterfaces["eth0"].Networks["nw"] = &network{}
nwInfo := &NetworkInfo{
Id: "nw",
Id: "nw",
MasterIfName: "eth0",
}
nw, err := nm.newNetwork(nwInfo)
@ -179,8 +179,8 @@ var (
ExternalInterfaces: map[string]*externalInterface{},
}
nm.ExternalInterfaces["eth0"] = &externalInterface{
Name: "eth0",
Networks: map[string]*network{},
Name: "eth0",
Networks: map[string]*network{},
}
nm.ExternalInterfaces["eth0"].Networks["nw1"] = &network{}
nw, err := nm.getNetwork("nw1")

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

@ -10,7 +10,7 @@ import (
)
const (
nnsPort = "6668" // port where node network service listens at
nnsPort = "6668" // port where node network service listens at
apiTimeout = 5 * time.Minute // recommended timeout from node service
connectionTimeout = 2 * time.Minute
)
@ -93,4 +93,4 @@ func newGrpcClient(ctx context.Context) (contracts.NodeNetworkServiceClient, *gr
}
return contracts.NewNodeNetworkServiceClient(conn), conn, nil
}
}

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

@ -80,7 +80,7 @@ func TestDeleteContainerNetworkingFailure(t *testing.T) {
}
if !strings.Contains(err.Error(), "Teardown") {
t.Fatalf("TestDeleteContainerNetworkingFailure failed. Error should have contained Teardown. %v" , err)
t.Fatalf("TestDeleteContainerNetworkingFailure failed. Error should have contained Teardown. %v", err)
}
}
@ -104,4 +104,4 @@ func TestAddContainerNetworkingGrpcServerDown(t *testing.T) {
t.Fatalf("TestAddContainerNetworkingGrpcServerDown failed. %s", err)
}
}
}

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

@ -3,11 +3,10 @@
package iptm
import (
"os"
"golang.org/x/sys/unix"
"os"
)
func grabIptablesFileLock(f *os.File) error {
return unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
}

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

@ -1,9 +1,9 @@
package npm
import (
"container/heap"
"fmt"
"sort"
"container/heap"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -14,18 +14,18 @@ import (
// An ReqHeap is a min-heap of labelSelectorRequirements.
type ReqHeap []metav1.LabelSelectorRequirement
func (h ReqHeap) Len() int {
func (h ReqHeap) Len() int {
return len(h)
}
func (h ReqHeap) Less(i, j int) bool {
sort.Strings(h[i].Values)
sort.Strings(h[j].Values)
if int(h[i].Key[0]) < int(h[j].Key[0]) {
return true
}
if int(h[i].Key[0]) > int(h[j].Key[0]) {
return false
}
@ -37,7 +37,7 @@ func (h ReqHeap) Less(i, j int) bool {
if len(h[j].Values) == 0 {
return false
}
if len(h[i].Values[0]) == 0 {
return true
}
@ -61,8 +61,8 @@ func (h *ReqHeap) Push(x interface{}) {
func (h *ReqHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n -1]
*h = old[0 : n - 1]
x := old[n-1]
*h = old[0 : n-1]
return x
}

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

@ -1,9 +1,9 @@
package npm
import (
"container/heap"
"reflect"
"testing"
"container/heap"
"github.com/Azure/azure-container-networking/npm/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -89,7 +89,6 @@ func TestGetOperatorAndLabel(t *testing.T) {
t.Errorf("TestGetOperatorAndLabel failed @ operator comparison")
}
if !reflect.DeepEqual(resultLabels, expectedLabels) {
t.Errorf("TestGetOperatorAndLabel failed @ label comparison")
}
@ -136,7 +135,7 @@ func TestReqHeap(t *testing.T) {
metav1.LabelSelectorRequirement{
Key: "a",
Operator: metav1.LabelSelectorOpIn,
Values: []string{},
Values: []string{},
},
metav1.LabelSelectorRequirement{
Key: "testIn",
@ -164,7 +163,7 @@ func TestReqHeap(t *testing.T) {
metav1.LabelSelectorRequirement{
Key: "a",
Operator: metav1.LabelSelectorOpIn,
Values: []string{},
Values: []string{},
},
metav1.LabelSelectorRequirement{
Key: "testIn",
@ -272,7 +271,7 @@ func TestHashSelector(t *testing.T) {
"c": "d",
},
}
secondSelector := &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
metav1.LabelSelectorRequirement{

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

@ -70,4 +70,4 @@ func CreateDirectory(dirPath string) error {
}
return err
}
}

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

@ -160,4 +160,4 @@ func PrintDependencyPackageDetails() {
func ReplaceFile(source, destination string) error {
return os.Rename(source, destination)
}
}

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

@ -74,7 +74,6 @@ func TestReadFileByLines(t *testing.T) {
}
}
func TestFileExists(t *testing.T) {
isExist, err := CheckIfFileExists("testfiles/test1")
if err != nil || !isExist {
@ -85,4 +84,4 @@ func TestFileExists(t *testing.T) {
if err != nil || isExist {
t.Errorf("Returned file found")
}
}
}

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

@ -6,12 +6,12 @@ package platform
import (
"bytes"
"fmt"
"golang.org/x/sys/windows"
"os"
"os/exec"
"strings"
"syscall"
"time"
"golang.org/x/sys/windows"
"github.com/Azure/azure-container-networking/log"
)
@ -245,4 +245,4 @@ func ReplaceFile(source, destination string) error {
}
return windows.MoveFileEx(src, dest, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
}
}

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

@ -12,4 +12,4 @@ import (
type TlsCertificateRetriever interface {
GetCertificate() (*x509.Certificate, error)
GetPrivateKey() (crypto.PrivateKey, error)
}
}

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

@ -7,7 +7,7 @@ type TlsSettings struct {
TLSSubjectName string
TLSCertificatePath string
TLSEndpoint string
TLSPort string
TLSPort string
}
func GetTlsCertificateRetriever(settings TlsSettings) (TlsCertificateRetriever, error) {

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

@ -51,7 +51,7 @@ func (fcert *linuxTlsCertificateRetriever) GetPrivateKey() (crypto.PrivateKey, e
}
// ReadFile reads a from disk
func (fcert *linuxTlsCertificateRetriever) readFile() ([]byte,error) {
func (fcert *linuxTlsCertificateRetriever) readFile() ([]byte, error) {
content, err := ioutil.ReadFile(fcert.settings.TLSCertificatePath)
if err != nil {
return nil, fmt.Errorf("Error reading file from path %s with error: %+v ", fcert.settings.TLSCertificatePath, err)
@ -60,7 +60,7 @@ func (fcert *linuxTlsCertificateRetriever) readFile() ([]byte,error) {
}
// Parses a file to PEM format
func (fcert *linuxTlsCertificateRetriever) parsePEMFile(content []byte) (error) {
func (fcert *linuxTlsCertificateRetriever) parsePEMFile(content []byte) error {
pemBlocks := make([]*pem.Block, 0)
var pemBlock *pem.Block
@ -96,9 +96,9 @@ func NewTlsCertificateRetriever(settings TlsSettings) (TlsCertificateRetriever,
return nil, fmt.Errorf("Failed to read file with error %+v", err)
}
if err:= linuxCertStoreRetriever.parsePEMFile(content); err != nil{
if err := linuxCertStoreRetriever.parsePEMFile(content); err != nil {
return nil, fmt.Errorf("Failed to parse PEM file with error %+v", err)
}
return linuxCertStoreRetriever, nil
}
}

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

@ -29,8 +29,8 @@ func TestPemConsumptionLinux(t *testing.T) {
defer os.Remove(pemLocation)
config := TlsSettings{
TLSCertificatePath: pemLocation,
TLSSubjectName: commonName,
TLSCertificatePath: pemLocation,
TLSSubjectName: commonName,
}
fileCertRetriever, err := NewTlsCertificateRetriever(config)
@ -77,11 +77,10 @@ func createPemCertificate(t *testing.T) []byte {
t.Fatalf("Could not encode certificate to Pem %+v", err)
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: CertLabel, Bytes: derBytes})
pemKey:= pem.EncodeToMemory(&pem.Block{Type: PrivateKeyLabel, Bytes: privateKeyBytes})
pemKey := pem.EncodeToMemory(&pem.Block{Type: PrivateKeyLabel, Bytes: privateKeyBytes})
pemBundle := fmt.Sprintf("%s%s",pemCert,pemKey)
pemBundle := fmt.Sprintf("%s%s", pemCert, pemKey)
return []byte(pemBundle)
}

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

@ -14,7 +14,7 @@ import (
type windowsTlsCertificateRetriever struct {
pemBlock []*pem.Block
settings TlsSettings
settings TlsSettings
}
const (
@ -53,7 +53,7 @@ func (wtls *windowsTlsCertificateRetriever) GetPrivateKey() (crypto.PrivateKey,
}
// ReadFile reads a from disk
func (wtls *windowsTlsCertificateRetriever) readFile() ([]byte,error) {
func (wtls *windowsTlsCertificateRetriever) readFile() ([]byte, error) {
content, err := ioutil.ReadFile(wtls.settings.TLSCertificatePath)
if err != nil {
return nil, fmt.Errorf("Error reading file from path %s with error: %+v ", wtls.settings.TLSCertificatePath, err)
@ -62,7 +62,7 @@ func (wtls *windowsTlsCertificateRetriever) readFile() ([]byte,error) {
}
// ParsePEMFile Parses a file to PEM format
func (fcert *windowsTlsCertificateRetriever) parsePEMFile(content []byte) (error) {
func (fcert *windowsTlsCertificateRetriever) parsePEMFile(content []byte) error {
pemBlocks := make([]*pem.Block, 0)
var pemBlock *pem.Block
@ -89,7 +89,7 @@ func (fcert *windowsTlsCertificateRetriever) parsePEMFile(content []byte) (error
func (wtls *windowsTlsCertificateRetriever) decrypt(content []byte) (string, error) {
decrypted, err := dpapi.Decrypt(string(content))
if err != nil {
return "",fmt.Errorf("Error decrypting file from path %s with error: %+v ", wtls.settings.TLSCertificatePath, err)
return "", fmt.Errorf("Error decrypting file from path %s with error: %+v ", wtls.settings.TLSCertificatePath, err)
}
decrypted = formatDecryptedPemString(decrypted)
@ -130,9 +130,9 @@ func NewTlsCertificateRetriever(settings TlsSettings) (TlsCertificateRetriever,
return nil, fmt.Errorf("Failed to decrypt file with error %+v", err)
}
if err:= windowsCertStoreRetriever.parsePEMFile([]byte(decrypted)); err != nil{
if err := windowsCertStoreRetriever.parsePEMFile([]byte(decrypted)); err != nil {
return nil, fmt.Errorf("Failed to parse PEM file with error %+v", err)
}
return windowsCertStoreRetriever, nil
}
}

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

@ -26,13 +26,13 @@ func TestPemConsumptionWindows(t *testing.T) {
currentDirectory, _ := os.Getwd()
pemLocation := fmt.Sprintf("%s/%s.Pem", currentDirectory, commonName)
encryptedPem, _:= dpapi.Encrypt(string(pemContent))
encryptedPem, _ := dpapi.Encrypt(string(pemContent))
ioutil.WriteFile(pemLocation, []byte(encryptedPem), 0644)
defer os.Remove(pemLocation)
config := TlsSettings{
TLSCertificatePath: pemLocation,
TLSSubjectName: commonName,
TLSCertificatePath: pemLocation,
TLSSubjectName: commonName,
}
fileCertRetriever, err := NewTlsCertificateRetriever(config)
@ -79,11 +79,10 @@ func createPemCertificate(t *testing.T) []byte {
t.Fatalf("Could not encode certificate to Pem %+v", err)
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: CertLabel, Bytes: derBytes})
pemKey:= pem.EncodeToMemory(&pem.Block{Type: PrivateKeyLabel, Bytes: privateKeyBytes})
pemKey := pem.EncodeToMemory(&pem.Block{Type: PrivateKeyLabel, Bytes: privateKeyBytes})
pemBundle := fmt.Sprintf("%s%s",pemCert,pemKey)
pemBundle := fmt.Sprintf("%s%s", pemCert, pemKey)
return []byte(pemBundle)
}

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

@ -130,7 +130,7 @@ func (kvs *jsonFileStore) flush() error {
tmpFileName := f.Name()
defer func(){
defer func() {
if err != nil {
// remove temp file after job is done
_ = os.Remove(tmpFileName)
@ -139,7 +139,6 @@ func (kvs *jsonFileStore) flush() error {
}
}()
if _, err = f.Write(buf); err != nil {
return fmt.Errorf("Temp file write failed with: %v", err)
}

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

@ -6,12 +6,12 @@ import (
)
const (
port = "6668"
port = "6668"
)
func main () {
func main() {
fmt.Printf("starting mock nns server ....\n")
mockserver := nnsmockserver.NewNnsMockServer()
mockserver := nnsmockserver.NewNnsMockServer()
mockserver.StartGrpcServer(port)
}
}

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

@ -28,25 +28,25 @@ func (s *serverApi) ConfigureContainerNetworking(
return nil, fmt.Errorf("NnsMockServer: RequestType:%s failed with error: %v", req.RequestType, err)
}
ipaddress := &nns.ContainerIPAddress {
Ip: "10.91.149.1",
DefaultGateway: "10.91.148.1",
PrefixLength: "24",
Version: "4",
ipaddress := &nns.ContainerIPAddress{
Ip: "10.91.149.1",
DefaultGateway: "10.91.148.1",
PrefixLength: "24",
Version: "4",
}
contTnterface := & nns.ContainerNetworkInterface{
Name: "azurevnet_45830dd4-1778-4735-9173-bba59b74cc8b_4ab80fb9-147e-4461-a213-56f4d44e806f",
NetworkNamespaceId: req.NetworkNamespaceId,
Ipaddresses: []*nns.ContainerIPAddress {ipaddress},
MacAddress: "0036578BB0F1",
contTnterface := &nns.ContainerNetworkInterface{
Name: "azurevnet_45830dd4-1778-4735-9173-bba59b74cc8b_4ab80fb9-147e-4461-a213-56f4d44e806f",
NetworkNamespaceId: req.NetworkNamespaceId,
Ipaddresses: []*nns.ContainerIPAddress{ipaddress},
MacAddress: "0036578BB0F1",
}
res := nns.ConfigureContainerNetworkingResponse{
Interfaces: []*nns.ContainerNetworkInterface {contTnterface},
Interfaces: []*nns.ContainerNetworkInterface{contTnterface},
}
return &res, nil
return &res, nil
}
func (s *serverApi) ConfigureNetworking(
@ -67,7 +67,7 @@ func NewNnsMockServer() *NnsMockServer {
}
}
func (s *NnsMockServer)StartGrpcServer(port string) {
func (s *NnsMockServer) StartGrpcServer(port string) {
endpoint := fmt.Sprintf(":%s", port)
lis, err := net.Listen("tcp", endpoint)
@ -81,7 +81,7 @@ func (s *NnsMockServer)StartGrpcServer(port string) {
}
}
func (s *NnsMockServer)StopGrpcServer() {
func (s *NnsMockServer) StopGrpcServer() {
if s.srv == nil {
fmt.Printf("s.srv is nil \n")
}
@ -104,4 +104,4 @@ func isValidPodName(podName string) error {
}
return nil
}
}

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

@ -5,12 +5,12 @@ import (
)
type KeyValueStoreMock struct {
ReadError error
WriteError error
FlushError error
LockError error
UnlockError error
ModificationTime time.Time
ReadError error
WriteError error
FlushError error
LockError error
UnlockError error
ModificationTime time.Time
GetModificationTimeError error
}
@ -50,4 +50,3 @@ func (store *KeyValueStoreMock) GetLockFileName() string {
func (store *KeyValueStoreMock) Remove() {
return
}