Merge pull request #843 from mmorel-35/golangci-lint

ci(lint): setup golangci-lint
This commit is contained in:
Casey Callendrello 2023-03-13 22:26:32 +01:00 committed by GitHub
commit d3ee71f240
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
114 changed files with 582 additions and 611 deletions

View File

@ -20,6 +20,9 @@ jobs:
- uses: ibiqlik/action-yamllint@v3 - uses: ibiqlik/action-yamllint@v3
with: with:
format: auto format: auto
- uses: golangci/golangci-lint-action@v3
with:
args: -v
build: build:
name: Build all linux architectures name: Build all linux architectures
needs: lint needs: lint

34
.golangci.yml Normal file
View File

@ -0,0 +1,34 @@
issues:
exclude-rules:
- linters:
- revive
text: "don't use ALL_CAPS in Go names; use CamelCase"
- linters:
- revive
text: " and that stutters;"
linters:
enable:
- contextcheck
- gci
- gocritic
- gofumpt
- gosimple
- ineffassign
- misspell
- nonamedreturns
- revive
- staticcheck
disable:
- errcheck
linters-settings:
gci:
sections:
- standard
- default
- prefix(github.com/containernetworking)
run:
skip-dirs:
- vendor

View File

@ -14,15 +14,14 @@
package integration_test package integration_test
import ( import (
"bytes"
"fmt" "fmt"
"io"
"math/rand" "math/rand"
"net"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"bytes"
"io"
"net"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -148,8 +147,8 @@ var _ = Describe("Basic PTP using cnitool", func() {
basicBridgeEnv.runInNS(hostNS, cnitoolBin, "del", "network-chain-test", contNS2.LongName()) basicBridgeEnv.runInNS(hostNS, cnitoolBin, "del", "network-chain-test", contNS2.LongName())
}) })
Measure("limits traffic only on the restricted bandwith veth device", func(b Benchmarker) { Measure("limits traffic only on the restricted bandwidth veth device", func(b Benchmarker) {
ipRegexp := regexp.MustCompile("10\\.1[12]\\.2\\.\\d{1,3}") ipRegexp := regexp.MustCompile(`10\.1[12]\.2\.\d{1,3}`)
By(fmt.Sprintf("adding %s to %s\n\n", "chained-bridge-bandwidth", contNS1.ShortName())) By(fmt.Sprintf("adding %s to %s\n\n", "chained-bridge-bandwidth", contNS1.ShortName()))
chainedBridgeBandwidthEnv.runInNS(hostNS, cnitoolBin, "add", "network-chain-test", contNS1.LongName()) chainedBridgeBandwidthEnv.runInNS(hostNS, cnitoolBin, "add", "network-chain-test", contNS1.LongName())
@ -177,12 +176,12 @@ var _ = Describe("Basic PTP using cnitool", func() {
By(fmt.Sprintf("sending tcp traffic to the chained, bridged, traffic shaped container on ip address '%s:%d'\n\n", chainedBridgeIP, chainedBridgeBandwidthPort)) By(fmt.Sprintf("sending tcp traffic to the chained, bridged, traffic shaped container on ip address '%s:%d'\n\n", chainedBridgeIP, chainedBridgeBandwidthPort))
runtimeWithLimit := b.Time("with chained bridge and bandwidth plugins", func() { runtimeWithLimit := b.Time("with chained bridge and bandwidth plugins", func() {
makeTcpClientInNS(hostNS.ShortName(), chainedBridgeIP, chainedBridgeBandwidthPort, packetInBytes) makeTCPClientInNS(hostNS.ShortName(), chainedBridgeIP, chainedBridgeBandwidthPort, packetInBytes)
}) })
By(fmt.Sprintf("sending tcp traffic to the basic bridged container on ip address '%s:%d'\n\n", basicBridgeIP, basicBridgePort)) By(fmt.Sprintf("sending tcp traffic to the basic bridged container on ip address '%s:%d'\n\n", basicBridgeIP, basicBridgePort))
runtimeWithoutLimit := b.Time("with basic bridged plugin", func() { runtimeWithoutLimit := b.Time("with basic bridged plugin", func() {
makeTcpClientInNS(hostNS.ShortName(), basicBridgeIP, basicBridgePort, packetInBytes) makeTCPClientInNS(hostNS.ShortName(), basicBridgeIP, basicBridgePort, packetInBytes)
}) })
Expect(runtimeWithLimit).To(BeNumerically(">", runtimeWithoutLimit+1000*time.Millisecond)) Expect(runtimeWithLimit).To(BeNumerically(">", runtimeWithoutLimit+1000*time.Millisecond))
@ -224,7 +223,7 @@ func (n Namespace) Del() {
(TestEnv{}).run("ip", "netns", "del", string(n)) (TestEnv{}).run("ip", "netns", "del", string(n))
} }
func makeTcpClientInNS(netns string, address string, port int, numBytes int) { func makeTCPClientInNS(netns string, address string, port int, numBytes int) {
payload := bytes.Repeat([]byte{'a'}, numBytes) payload := bytes.Repeat([]byte{'a'}, numBytes)
message := string(payload) message := string(payload)

View File

@ -47,14 +47,13 @@ func ParseIP(s string) *IP {
return nil return nil
} }
return newIP(ip, ipNet.Mask) return newIP(ip, ipNet.Mask)
} else { }
ip := net.ParseIP(s) ip := net.ParseIP(s)
if ip == nil { if ip == nil {
return nil return nil
} }
return newIP(ip, nil) return newIP(ip, nil)
} }
}
// ToIP will return a net.IP in standard form from this IP. // ToIP will return a net.IP in standard form from this IP.
// If this IP can not be converted to a valid net.IP, will return nil. // If this IP can not be converted to a valid net.IP, will return nil.

View File

@ -15,10 +15,10 @@
package ip_test package ip_test
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestIp(t *testing.T) { func TestIp(t *testing.T) {

View File

@ -205,7 +205,6 @@ var _ = Describe("IP Operations", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(ip).To(Equal(test.expected)) Expect(ip).To(Equal(test.expected))
} }
}) })
It("empty text", func() { It("empty text", func() {

View File

@ -58,5 +58,5 @@ func echo1(f string) error {
return nil return nil
} }
} }
return os.WriteFile(f, []byte("1"), 0644) return os.WriteFile(f, []byte("1"), 0o644)
} }

View File

@ -104,7 +104,6 @@ func TeardownIPMasq(ipn *net.IPNet, chain string, comment string) error {
err = ipt.ClearChain("nat", chain) err = ipt.ClearChain("nat", chain)
if err != nil && !isNotExist(err) { if err != nil && !isNotExist(err) {
return err return err
} }
err = ipt.DeleteChain("nat", chain) err = ipt.DeleteChain("nat", chain)

View File

@ -28,9 +28,7 @@ import (
"github.com/containernetworking/plugins/pkg/utils/sysctl" "github.com/containernetworking/plugins/pkg/utils/sysctl"
) )
var ( var ErrLinkNotFound = errors.New("link not found")
ErrLinkNotFound = errors.New("link not found")
)
// makeVethPair is called from within the container's network namespace // makeVethPair is called from within the container's network namespace
func makeVethPair(name, peer string, mtu int, mac string, hostNS ns.NetNS) (netlink.Link, error) { func makeVethPair(name, peer string, mtu int, mac string, hostNS ns.NetNS) (netlink.Link, error) {
@ -69,38 +67,37 @@ func peerExists(name string) bool {
return true return true
} }
func makeVeth(name, vethPeerName string, mtu int, mac string, hostNS ns.NetNS) (peerName string, veth netlink.Link, err error) { func makeVeth(name, vethPeerName string, mtu int, mac string, hostNS ns.NetNS) (string, netlink.Link, error) {
var peerName string
var veth netlink.Link
var err error
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
if vethPeerName != "" { if vethPeerName != "" {
peerName = vethPeerName peerName = vethPeerName
} else { } else {
peerName, err = RandomVethName() peerName, err = RandomVethName()
if err != nil { if err != nil {
return return peerName, nil, err
} }
} }
veth, err = makeVethPair(name, peerName, mtu, mac, hostNS) veth, err = makeVethPair(name, peerName, mtu, mac, hostNS)
switch { switch {
case err == nil: case err == nil:
return return peerName, veth, err
case os.IsExist(err): case os.IsExist(err):
if peerExists(peerName) && vethPeerName == "" { if peerExists(peerName) && vethPeerName == "" {
continue continue
} }
err = fmt.Errorf("container veth name provided (%v) already exists", name) return peerName, veth, fmt.Errorf("container veth name provided (%v) already exists", name)
return
default: default:
err = fmt.Errorf("failed to make veth pair: %v", err) return peerName, veth, fmt.Errorf("failed to make veth pair: %v", err)
return
} }
} }
// should really never be hit // should really never be hit
err = fmt.Errorf("failed to find a unique veth name") return peerName, nil, fmt.Errorf("failed to find a unique veth name")
return
} }
// RandomVethName returns string "veth" with random prefix (hashed from entropy) // RandomVethName returns string "veth" with random prefix (hashed from entropy)

View File

@ -22,20 +22,13 @@ import (
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
) )
func getHwAddr(linkname string) string {
veth, err := netlink.LinkByName(linkname)
Expect(err).NotTo(HaveOccurred())
return fmt.Sprintf("%s", veth.Attrs().HardwareAddr)
}
var _ = Describe("Link", func() { var _ = Describe("Link", func() {
const ( const (
ifaceFormatString string = "i%d" ifaceFormatString string = "i%d"

View File

@ -21,13 +21,13 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/vishvananda/netlink"
) )
func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig) error { func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig) error {
// Ensure ips // Ensure ips
for _, ips := range resultIPs { for _, ips := range resultIPs {
ourAddr := netlink.Addr{IPNet: &ips.Address} ourAddr := netlink.Addr{IPNet: &ips.Address}
@ -49,12 +49,15 @@ func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig)
break break
} }
} }
if match == false { if !match {
return fmt.Errorf("Failed to match addr %v on interface %v", ourAddr, ifName) return fmt.Errorf("Failed to match addr %v on interface %v", ourAddr, ifName)
} }
// Convert the host/prefixlen to just prefix for route lookup. // Convert the host/prefixlen to just prefix for route lookup.
_, ourPrefix, err := net.ParseCIDR(ourAddr.String()) _, ourPrefix, err := net.ParseCIDR(ourAddr.String())
if err != nil {
return err
}
findGwy := &netlink.Route{Dst: ourPrefix} findGwy := &netlink.Route{Dst: ourPrefix}
routeFilter := netlink.RT_FILTER_DST routeFilter := netlink.RT_FILTER_DST
@ -77,7 +80,6 @@ func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig)
} }
func ValidateExpectedRoute(resultRoutes []*types.Route) error { func ValidateExpectedRoute(resultRoutes []*types.Route) error {
// Ensure that each static route in prevResults is found in the routing table // Ensure that each static route in prevResults is found in the routing table
for _, route := range resultRoutes { for _, route := range resultRoutes {
find := &netlink.Route{Dst: &route.Dst, Gw: route.GW} find := &netlink.Route{Dst: &route.Dst, Gw: route.GW}

View File

@ -16,6 +16,7 @@ package ipam
import ( import (
"context" "context"
"github.com/containernetworking/cni/pkg/invoke" "github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
) )

View File

@ -19,11 +19,11 @@ import (
"net" "net"
"os" "os"
"github.com/vishvananda/netlink"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/utils/sysctl" "github.com/containernetworking/plugins/pkg/utils/sysctl"
"github.com/vishvananda/netlink"
) )
const ( const (
@ -44,7 +44,7 @@ func ConfigureIface(ifName string, res *current.Result) error {
} }
var v4gw, v6gw net.IP var v4gw, v6gw net.IP
var has_enabled_ipv6 bool = false hasEnabledIpv6 := false
for _, ipc := range res.IPs { for _, ipc := range res.IPs {
if ipc.Interface == nil { if ipc.Interface == nil {
continue continue
@ -57,7 +57,7 @@ func ConfigureIface(ifName string, res *current.Result) error {
// Make sure sysctl "disable_ipv6" is 0 if we are about to add // Make sure sysctl "disable_ipv6" is 0 if we are about to add
// an IPv6 address to the interface // an IPv6 address to the interface
if !has_enabled_ipv6 && ipc.Address.IP.To4() == nil { if !hasEnabledIpv6 && ipc.Address.IP.To4() == nil {
// Enabled IPv6 for loopback "lo" and the interface // Enabled IPv6 for loopback "lo" and the interface
// being configured // being configured
for _, iface := range [2]string{"lo", ifName} { for _, iface := range [2]string{"lo", ifName} {
@ -79,7 +79,7 @@ func ConfigureIface(ifName string, res *current.Result) error {
return fmt.Errorf("failed to enable IPv6 for interface %q (%s=%s): %v", iface, ipv6SysctlValueName, value, err) return fmt.Errorf("failed to enable IPv6 for interface %q (%s=%s): %v", iface, ipv6SysctlValueName, value, err)
} }
} }
has_enabled_ipv6 = true hasEnabledIpv6 = true
} }
addr := &netlink.Addr{IPNet: &ipc.Address, Label: ""} addr := &netlink.Addr{IPNet: &ipc.Address, Label: ""}

View File

@ -18,15 +18,14 @@ import (
"net" "net"
"syscall" "syscall"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const LINK_NAME = "eth0" const LINK_NAME = "eth0"

View File

@ -15,10 +15,10 @@
package ipam_test package ipam_test
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestIpam(t *testing.T) { func TestIpam(t *testing.T) {

View File

@ -41,11 +41,11 @@ type SpoofChecker struct {
type defaultNftConfigurer struct{} type defaultNftConfigurer struct{}
func (_ defaultNftConfigurer) Apply(cfg *nft.Config) error { func (dnc defaultNftConfigurer) Apply(cfg *nft.Config) error {
return nft.ApplyConfig(cfg) return nft.ApplyConfig(cfg)
} }
func (_ defaultNftConfigurer) Read() (*nft.Config, error) { func (dnc defaultNftConfigurer) Read() (*nft.Config, error) {
return nft.ReadConfig() return nft.ReadConfig()
} }
@ -208,7 +208,7 @@ func (sc *SpoofChecker) dropRule(chain string) *schema.Rule {
} }
} }
func (_ *SpoofChecker) baseChain() *schema.Chain { func (sc *SpoofChecker) baseChain() *schema.Chain {
chainPriority := -300 chainPriority := -300
return &schema.Chain{ return &schema.Chain{
Family: schema.FamilyBridge, Family: schema.FamilyBridge,
@ -230,7 +230,7 @@ func (sc *SpoofChecker) ifaceChain() *schema.Chain {
} }
} }
func (_ *SpoofChecker) macChain(ifaceChainName string) *schema.Chain { func (sc *SpoofChecker) macChain(ifaceChainName string) *schema.Chain {
macChainName := ifaceChainName + "-mac" macChainName := ifaceChainName + "-mac"
return &schema.Chain{ return &schema.Chain{
Family: schema.FamilyBridge, Family: schema.FamilyBridge,

View File

@ -16,8 +16,8 @@ package link_test
import ( import (
"fmt" "fmt"
"github.com/networkplumbing/go-nft/nft"
"github.com/networkplumbing/go-nft/nft"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -116,10 +116,10 @@ var _ = Describe("spoofcheck", func() {
}) })
func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub) { func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub) {
deleteRegularChainRulesJsonConfig, err := action.applyConfig[1].ToJSON() deleteRegularChainRulesJSONConfig, err := action.applyConfig[1].ToJSON()
ExpectWithOffset(1, err).NotTo(HaveOccurred()) ExpectWithOffset(1, err).NotTo(HaveOccurred())
expectedDeleteRegularChainRulesJsonConfig := ` expectedDeleteRegularChainRulesJSONConfig := `
{"nftables": [ {"nftables": [
{"delete": {"chain": { {"delete": {"chain": {
"family": "bridge", "family": "bridge",
@ -133,14 +133,14 @@ func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub)
}}} }}}
]}` ]}`
ExpectWithOffset(1, string(deleteRegularChainRulesJsonConfig)).To(MatchJSON(expectedDeleteRegularChainRulesJsonConfig)) ExpectWithOffset(1, string(deleteRegularChainRulesJSONConfig)).To(MatchJSON(expectedDeleteRegularChainRulesJSONConfig))
} }
func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub) { func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub) {
deleteBaseChainRuleJsonConfig, err := action.applyConfig[0].ToJSON() deleteBaseChainRuleJSONConfig, err := action.applyConfig[0].ToJSON()
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
expectedDeleteIfaceMatchRuleJsonConfig := ` expectedDeleteIfaceMatchRuleJSONConfig := `
{"nftables": [ {"nftables": [
{"delete": {"rule": { {"delete": {"rule": {
"family": "bridge", "family": "bridge",
@ -157,7 +157,7 @@ func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub)
"comment": "macspoofchk-container99-net1" "comment": "macspoofchk-container99-net1"
}}} }}}
]}` ]}`
Expect(string(deleteBaseChainRuleJsonConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJsonConfig)) Expect(string(deleteBaseChainRuleJSONConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJSONConfig))
} }
func rowConfigWithRulesOnly() string { func rowConfigWithRulesOnly() string {

View File

@ -21,11 +21,12 @@ import (
"path/filepath" "path/filepath"
"sync" "sync"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
func getInodeCurNetNS() (uint64, error) { func getInodeCurNetNS() (uint64, error) {

View File

@ -17,11 +17,10 @@ package ns_test
import ( import (
"math/rand" "math/rand"
"runtime" "runtime"
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestNs(t *testing.T) { func TestNs(t *testing.T) {

View File

@ -1,10 +1,10 @@
package main_test package main_test
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestEchosvr(t *testing.T) { func TestEchosvr(t *testing.T) {

View File

@ -1,6 +1,7 @@
// Echosvr is a simple TCP echo server // Echosvr is a simple TCP echo server
// //
// It prints its listen address on stdout // It prints its listen address on stdout
//
// 127.0.0.1:xxxxx // 127.0.0.1:xxxxx
// A test should wait for this line, parse it // A test should wait for this line, parse it
// and may then attempt to connect. // and may then attempt to connect.
@ -43,11 +44,13 @@ func main() {
// Start UDP server // Start UDP server
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%s", port)) addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%s", port))
if err != nil { if err != nil {
log.Fatalf("Error from net.ResolveUDPAddr(): %s", err) log.Printf("Error from net.ResolveUDPAddr(): %s", err)
return
} }
sock, err := net.ListenUDP("udp", addr) sock, err := net.ListenUDP("udp", addr)
if err != nil { if err != nil {
log.Fatalf("Error from ListenUDP(): %s", err) log.Printf("Error from ListenUDP(): %s", err)
return
} }
defer sock.Close() defer sock.Close()
@ -55,10 +58,11 @@ func main() {
for { for {
n, addr, err := sock.ReadFrom(buffer) n, addr, err := sock.ReadFrom(buffer)
if err != nil { if err != nil {
log.Fatalf("Error from ReadFrom(): %s", err) log.Printf("Error from ReadFrom(): %s", err)
return
} }
sock.SetWriteDeadline(time.Now().Add(1 * time.Minute)) sock.SetWriteDeadline(time.Now().Add(1 * time.Minute))
n, err = sock.WriteTo(buffer[0:n], addr) _, err = sock.WriteTo(buffer[0:n], addr)
if err != nil { if err != nil {
return return
} }

View File

@ -24,8 +24,9 @@ import (
"sync" "sync"
"syscall" "syscall"
"github.com/containernetworking/plugins/pkg/ns"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"github.com/containernetworking/plugins/pkg/ns"
) )
func getNsRunDir() string { func getNsRunDir() string {
@ -49,7 +50,6 @@ func getNsRunDir() string {
// Creates a new persistent (bind-mounted) network namespace and returns an object // Creates a new persistent (bind-mounted) network namespace and returns an object
// representing that namespace, without switching to it. // representing that namespace, without switching to it.
func NewNS() (ns.NetNS, error) { func NewNS() (ns.NetNS, error) {
nsRunDir := getNsRunDir() nsRunDir := getNsRunDir()
b := make([]byte, 16) b := make([]byte, 16)
@ -61,7 +61,7 @@ func NewNS() (ns.NetNS, error) {
// Create the directory for mounting network namespaces // Create the directory for mounting network namespaces
// This needs to be a shared mountpoint in case it is mounted in to // This needs to be a shared mountpoint in case it is mounted in to
// other namespaces (containers) // other namespaces (containers)
err = os.MkdirAll(nsRunDir, 0755) err = os.MkdirAll(nsRunDir, 0o755)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -133,7 +133,6 @@ func InsertUnique(ipt *iptables.IPTables, table, chain string, prepend bool, rul
if prepend { if prepend {
return ipt.Insert(table, chain, 1, rule...) return ipt.Insert(table, chain, 1, rule...)
} else { }
return ipt.Append(table, chain, rule...) return ipt.Append(table, chain, rule...)
} }
}

View File

@ -19,11 +19,12 @@ import (
"math/rand" "math/rand"
"runtime" "runtime"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
const TABLE = "filter" // We'll monkey around here const TABLE = "filter" // We'll monkey around here
@ -34,7 +35,6 @@ var _ = Describe("chain tests", func() {
var cleanup func() var cleanup func()
BeforeEach(func() { BeforeEach(func() {
// Save a reference to the original namespace, // Save a reference to the original namespace,
// Add a new NS // Add a new NS
currNs, err := ns.GetCurrentNS() currNs, err := ns.GetCurrentNS()
@ -60,7 +60,6 @@ var _ = Describe("chain tests", func() {
ipt.DeleteChain(TABLE, testChain) ipt.DeleteChain(TABLE, testChain)
currNs.Set() currNs.Set()
} }
}) })
AfterEach(func() { AfterEach(func() {
@ -93,5 +92,4 @@ var _ = Describe("chain tests", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
}) })
}) })

View File

@ -46,7 +46,7 @@ func getSysctl(name string) (string, error) {
func setSysctl(name, value string) (string, error) { func setSysctl(name, value string) (string, error) {
fullName := filepath.Join("/proc/sys", toNormalName(name)) fullName := filepath.Join("/proc/sys", toNormalName(name))
if err := os.WriteFile(fullName, []byte(value), 0644); err != nil { if err := os.WriteFile(fullName, []byte(value), 0o644); err != nil {
return "", err return "", err
} }

View File

@ -20,12 +20,13 @@ import (
"runtime" "runtime"
"strings" "strings"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/containernetworking/plugins/pkg/utils/sysctl"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/containernetworking/plugins/pkg/utils/sysctl"
) )
const ( const (
@ -38,7 +39,6 @@ var _ = Describe("Sysctl tests", func() {
var cleanup func() var cleanup func()
beforeEach := func() { beforeEach := func() {
// Save a reference to the original namespace, // Save a reference to the original namespace,
// Add a new NS // Add a new NS
currNs, err := ns.GetCurrentNS() currNs, err := ns.GetCurrentNS()
@ -66,7 +66,6 @@ var _ = Describe("Sysctl tests", func() {
netlink.LinkDel(testIface) netlink.LinkDel(testIface)
currNs.Set() currNs.Set()
} }
} }
AfterEach(func() { AfterEach(func() {
@ -76,7 +75,7 @@ var _ = Describe("Sysctl tests", func() {
Describe("Sysctl", func() { Describe("Sysctl", func() {
It("reads keys with dot separators", func() { It("reads keys with dot separators", func() {
beforeEach() beforeEach()
sysctlIfaceName := strings.Replace(testIfaceName, ".", "/", -1) sysctlIfaceName := strings.ReplaceAll(testIfaceName, ".", "/")
sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName) sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName)
_, err := sysctl.Sysctl(sysctlKey) _, err := sysctl.Sysctl(sysctlKey)
@ -97,7 +96,7 @@ var _ = Describe("Sysctl tests", func() {
Describe("Sysctl", func() { Describe("Sysctl", func() {
It("writes keys with dot separators", func() { It("writes keys with dot separators", func() {
beforeEach() beforeEach()
sysctlIfaceName := strings.Replace(testIfaceName, ".", "/", -1) sysctlIfaceName := strings.ReplaceAll(testIfaceName, ".", "/")
sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName) sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName)
_, err := sysctl.Sysctl(sysctlKey, "1") _, err := sysctl.Sysctl(sysctlKey, "1")
@ -114,5 +113,4 @@ var _ = Describe("Sysctl tests", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
}) })
}) })

View File

@ -15,10 +15,10 @@
package utils_test package utils_test
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestUtils(t *testing.T) { func TestUtils(t *testing.T) {

View File

@ -161,5 +161,4 @@ var _ = Describe("Utils", func() {
) )
}) })
}) })
}) })

View File

@ -30,9 +30,10 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/coreos/go-systemd/v22/activation"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/coreos/go-systemd/v22/activation"
) )
var errNoMoreTries = errors.New("no more tries") var errNoMoreTries = errors.New("no more tries")
@ -55,7 +56,7 @@ func newDHCP(clientTimeout, clientResendMax time.Duration) *DHCP {
} }
// TODO: current client ID is too long. At least the container ID should not be used directly. // TODO: current client ID is too long. At least the container ID should not be used directly.
// A seperate issue is necessary to ensure no breaking change is affecting other users. // A separate issue is necessary to ensure no breaking change is affecting other users.
func generateClientID(containerID string, netName string, ifName string) string { func generateClientID(containerID string, netName string, ifName string) string {
clientID := containerID + "/" + netName + "/" + ifName clientID := containerID + "/" + netName + "/" + ifName
// defined in RFC 2132, length size can not be larger than 1 octet. So we truncate 254 to make everyone happy. // defined in RFC 2132, length size can not be larger than 1 octet. So we truncate 254 to make everyone happy.
@ -166,7 +167,7 @@ func getListener(socketPath string) (net.Listener, error) {
switch { switch {
case len(l) == 0: case len(l) == 0:
if err := os.MkdirAll(filepath.Dir(socketPath), 0700); err != nil { if err := os.MkdirAll(filepath.Dir(socketPath), 0o700); err != nil {
return nil, err return nil, err
} }
return net.Listen("unix", socketPath) return net.Listen("unix", socketPath)
@ -195,7 +196,7 @@ func runDaemon(
if !filepath.IsAbs(pidfilePath) { if !filepath.IsAbs(pidfilePath) {
return fmt.Errorf("Error writing pidfile %q: path not absolute", pidfilePath) return fmt.Errorf("Error writing pidfile %q: path not absolute", pidfilePath)
} }
if err := os.WriteFile(pidfilePath, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil { if err := os.WriteFile(pidfilePath, []byte(fmt.Sprintf("%d", os.Getpid())), 0o644); err != nil {
return fmt.Errorf("Error writing pidfile %q: %v", pidfilePath, err) return fmt.Errorf("Error writing pidfile %q: %v", pidfilePath, err)
} }
} }

View File

@ -22,15 +22,14 @@ import (
"sync" "sync"
"time" "time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
var _ = Describe("DHCP Multiple Lease Operations", func() { var _ = Describe("DHCP Multiple Lease Operations", func() {

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestDHCP(t *testing.T) { func TestDHCP(t *testing.T) {

View File

@ -25,20 +25,18 @@ import (
"sync" "sync"
"time" "time"
"github.com/containernetworking/cni/pkg/skel"
types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/d2g/dhcp4" "github.com/d2g/dhcp4"
"github.com/d2g/dhcp4server" "github.com/d2g/dhcp4server"
"github.com/d2g/dhcp4server/leasepool" "github.com/d2g/dhcp4server/leasepool"
"github.com/d2g/dhcp4server/leasepool/memorypool" "github.com/d2g/dhcp4server/leasepool/memorypool"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel"
types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
func getTmpDir() (string, error) { func getTmpDir() (string, error) {
@ -120,7 +118,7 @@ const (
) )
var _ = BeforeSuite(func() { var _ = BeforeSuite(func() {
err := os.MkdirAll(cniDirPrefix, 0700) err := os.MkdirAll(cniDirPrefix, 0o700)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })

View File

@ -34,13 +34,17 @@ import (
// RFC 2131 suggests using exponential backoff, starting with 4sec // RFC 2131 suggests using exponential backoff, starting with 4sec
// and randomized to +/- 1sec // and randomized to +/- 1sec
const resendDelay0 = 4 * time.Second const (
const resendDelayMax = 62 * time.Second resendDelay0 = 4 * time.Second
resendDelayMax = 62 * time.Second
)
// To speed up the retry for first few failures, we retry without // To speed up the retry for first few failures, we retry without
// backoff for a few times // backoff for a few times
const resendFastDelay = 2 * time.Second const (
const resendFastMax = 4 resendFastDelay = 2 * time.Second
resendFastMax = 4
)
const ( const (
leaseStateBound = iota leaseStateBound = iota
@ -79,9 +83,12 @@ var requestOptionsDefault = map[dhcp4.OptionCode]bool{
dhcp4.OptionSubnetMask: true, dhcp4.OptionSubnetMask: true,
} }
func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptions []RequestOption) ( func prepareOptions(cniArgs string, provideOptions []ProvideOption, requestOptions []RequestOption) (
optsRequesting map[dhcp4.OptionCode]bool, optsProviding map[dhcp4.OptionCode][]byte, err error) { map[dhcp4.OptionCode]bool, map[dhcp4.OptionCode][]byte, error,
) {
var optsRequesting map[dhcp4.OptionCode]bool
var optsProviding map[dhcp4.OptionCode][]byte
var err error
// parse CNI args // parse CNI args
cniArgsParsed := map[string]string{} cniArgsParsed := map[string]string{}
for _, argPair := range strings.Split(cniArgs, ";") { for _, argPair := range strings.Split(cniArgs, ";") {
@ -94,23 +101,20 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio
// parse providing options map // parse providing options map
var optParsed dhcp4.OptionCode var optParsed dhcp4.OptionCode
optsProviding = make(map[dhcp4.OptionCode][]byte) optsProviding = make(map[dhcp4.OptionCode][]byte)
for _, opt := range ProvideOptions { for _, opt := range provideOptions {
optParsed, err = parseOptionName(string(opt.Option)) optParsed, err = parseOptionName(string(opt.Option))
if err != nil { if err != nil {
err = fmt.Errorf("Can not parse option %q: %w", opt.Option, err) return nil, nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err)
return
} }
if len(opt.Value) > 0 { if len(opt.Value) > 0 {
if len(opt.Value) > 255 { if len(opt.Value) > 255 {
err = fmt.Errorf("value too long for option %q: %q", opt.Option, opt.Value) return nil, nil, fmt.Errorf("value too long for option %q: %q", opt.Option, opt.Value)
return
} }
optsProviding[optParsed] = []byte(opt.Value) optsProviding[optParsed] = []byte(opt.Value)
} }
if value, ok := cniArgsParsed[opt.ValueFromCNIArg]; ok { if value, ok := cniArgsParsed[opt.ValueFromCNIArg]; ok {
if len(value) > 255 { if len(value) > 255 {
err = fmt.Errorf("value too long for option %q from CNI_ARGS %q: %q", opt.Option, opt.ValueFromCNIArg, opt.Value) return nil, nil, fmt.Errorf("value too long for option %q from CNI_ARGS %q: %q", opt.Option, opt.ValueFromCNIArg, opt.Value)
return
} }
optsProviding[optParsed] = []byte(value) optsProviding[optParsed] = []byte(value)
} }
@ -119,14 +123,13 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio
// parse necessary options map // parse necessary options map
optsRequesting = make(map[dhcp4.OptionCode]bool) optsRequesting = make(map[dhcp4.OptionCode]bool)
skipRequireDefault := false skipRequireDefault := false
for _, opt := range RequestOptions { for _, opt := range requestOptions {
if opt.SkipDefault { if opt.SkipDefault {
skipRequireDefault = true skipRequireDefault = true
} }
optParsed, err = parseOptionName(string(opt.Option)) optParsed, err = parseOptionName(string(opt.Option))
if err != nil { if err != nil {
err = fmt.Errorf("Can not parse option %q: %w", opt.Option, err) return nil, nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err)
return
} }
optsRequesting[optParsed] = true optsRequesting[optParsed] = true
} }
@ -136,7 +139,7 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio
optsRequesting[k] = v optsRequesting[k] = v
} }
} }
return return optsRequesting, optsProviding, err
} }
// AcquireLease gets an DHCP lease and then maintains it in the background // AcquireLease gets an DHCP lease and then maintains it in the background
@ -206,7 +209,7 @@ func (l *DHCPLease) Check() {
l.check <- struct{}{} l.check <- struct{}{}
} }
func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options { func (l *DHCPLease) getOptionsWithClientID() dhcp4.Options {
opts := make(dhcp4.Options) opts := make(dhcp4.Options)
opts[dhcp4.OptionClientIdentifier] = []byte(l.clientID) opts[dhcp4.OptionClientIdentifier] = []byte(l.clientID)
// client identifier's first byte is "type" // client identifier's first byte is "type"
@ -217,7 +220,7 @@ func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options {
} }
func (l *DHCPLease) getAllOptions() dhcp4.Options { func (l *DHCPLease) getAllOptions() dhcp4.Options {
opts := l.getOptionsWithClientId() opts := l.getOptionsWithClientID()
for k, v := range l.optsProviding { for k, v := range l.optsProviding {
opts[k] = v opts[k] = v
@ -302,7 +305,7 @@ func (l *DHCPLease) maintain() {
switch state { switch state {
case leaseStateBound: case leaseStateBound:
sleepDur = l.renewalTime.Sub(time.Now()) sleepDur = time.Until(l.renewalTime)
if sleepDur <= 0 { if sleepDur <= 0 {
log.Printf("%v: renewing lease", l.clientID) log.Printf("%v: renewing lease", l.clientID)
state = leaseStateRenewing state = leaseStateRenewing
@ -394,7 +397,7 @@ func (l *DHCPLease) release() error {
} }
defer c.Close() defer c.Close()
opts := l.getOptionsWithClientId() opts := l.getOptionsWithClientID()
if err = DhcpRelease(c, *l.ack, opts); err != nil { if err = DhcpRelease(c, *l.ack, opts); err != nil {
return fmt.Errorf("failed to send DHCPRELEASE") return fmt.Errorf("failed to send DHCPRELEASE")
@ -424,9 +427,9 @@ func (l *DHCPLease) Routes() []*types.Route {
// RFC 3442 states that if Classless Static Routes (option 121) // RFC 3442 states that if Classless Static Routes (option 121)
// exist, we ignore Static Routes (option 33) and the Router/Gateway. // exist, we ignore Static Routes (option 33) and the Router/Gateway.
opt121_routes := parseCIDRRoutes(l.opts) opt121Routes := parseCIDRRoutes(l.opts)
if len(opt121_routes) > 0 { if len(opt121Routes) > 0 {
return append(routes, opt121_routes...) return append(routes, opt121Routes...)
} }
// Append Static Routes // Append Static Routes
@ -448,9 +451,9 @@ func jitter(span time.Duration) time.Duration {
} }
func backoffRetry(resendMax time.Duration, f func() (*dhcp4.Packet, error)) (*dhcp4.Packet, error) { func backoffRetry(resendMax time.Duration, f func() (*dhcp4.Packet, error)) (*dhcp4.Packet, error) {
var baseDelay time.Duration = resendDelay0 baseDelay := resendDelay0
var sleepTime time.Duration var sleepTime time.Duration
var fastRetryLimit = resendFastMax fastRetryLimit := resendFastMax
for { for {
pkt, err := f() pkt, err := f()
if err == nil { if err == nil {

View File

@ -21,8 +21,9 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/containernetworking/cni/pkg/types"
"github.com/d2g/dhcp4" "github.com/d2g/dhcp4"
"github.com/containernetworking/cni/pkg/types"
) )
var optionNameToID = map[string]dhcp4.OptionCode{ var optionNameToID = map[string]dhcp4.OptionCode{

View File

@ -19,8 +19,9 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/containernetworking/cni/pkg/types"
"github.com/d2g/dhcp4" "github.com/d2g/dhcp4"
"github.com/containernetworking/cni/pkg/types"
) )
func validateRoutes(t *testing.T, routes []*types.Route) { func validateRoutes(t *testing.T, routes []*types.Route) {

View File

@ -22,7 +22,6 @@ import (
"strconv" "strconv"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend"
) )
@ -197,7 +196,7 @@ func (i *RangeIter) Next() (*net.IPNet, net.IP) {
// If we've reached the end of this range, we need to advance the range // If we've reached the end of this range, we need to advance the range
// RangeEnd is inclusive as well // RangeEnd is inclusive as well
if i.cur.Equal(r.RangeEnd) { if i.cur.Equal(r.RangeEnd) {
i.rangeIdx += 1 i.rangeIdx++
i.rangeIdx %= len(*i.rangeset) i.rangeIdx %= len(*i.rangeset)
r = (*i.rangeset)[i.rangeIdx] r = (*i.rangeset)[i.rangeIdx]

View File

@ -15,10 +15,10 @@
package allocator_test package allocator_test
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestAllocator(t *testing.T) { func TestAllocator(t *testing.T) {

View File

@ -18,12 +18,12 @@ import (
"fmt" "fmt"
"net" "net"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
fakestore "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/testing" fakestore "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
type AllocatorTestCase struct { type AllocatorTestCase struct {
@ -262,7 +262,6 @@ var _ = Describe("host-local ip allocator", func() {
res, err = alloc.Get("ID", "eth0", nil) res, err = alloc.Get("ID", "eth0", nil)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(res.Address.String()).To(Equal("192.168.1.3/29")) Expect(res.Address.String()).To(Equal("192.168.1.3/29"))
}) })
Context("when requesting a specific IP", func() { Context("when requesting a specific IP", func() {
@ -301,7 +300,6 @@ var _ = Describe("host-local ip allocator", func() {
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
}) })
}) })
}) })
Context("when out of ips", func() { Context("when out of ips", func() {
It("returns a meaningful error", func() { It("returns a meaningful error", func() {

View File

@ -21,7 +21,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
) )
@ -43,7 +42,7 @@ type Net struct {
// IPAMConfig represents the IP related network configuration. // IPAMConfig represents the IP related network configuration.
// This nests Range because we initially only supported a single // This nests Range because we initially only supported a single
// range directly, and wish to preserve backwards compatability // range directly, and wish to preserve backwards compatibility
type IPAMConfig struct { type IPAMConfig struct {
*Range *Range
Name string Name string

View File

@ -17,9 +17,10 @@ package allocator
import ( import (
"net" "net"
"github.com/containernetworking/cni/pkg/types"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/types"
) )
var _ = Describe("IPAM config", func() { var _ = Describe("IPAM config", func() {
@ -415,7 +416,6 @@ var _ = Describe("IPAM config", func() {
}` }`
_, _, err := LoadIPAMConfig([]byte(input), "") _, _, err := LoadIPAMConfig([]byte(input), "")
Expect(err).To(MatchError("invalid range set 0: mixed address families")) Expect(err).To(MatchError("invalid range set 0: mixed address families"))
}) })
It("Should should error on too many ranges", func() { It("Should should error on too many ranges", func() {

View File

@ -125,7 +125,7 @@ func (r *Range) Contains(addr net.IP) bool {
// Overlaps returns true if there is any overlap between ranges // Overlaps returns true if there is any overlap between ranges
func (r *Range) Overlaps(r1 *Range) bool { func (r *Range) Overlaps(r1 *Range) bool {
// different familes // different families
if len(r.RangeStart) != len(r1.RangeStart) { if len(r.RangeStart) != len(r1.RangeStart) {
return false return false
} }

View File

@ -67,12 +67,10 @@ func (s *RangeSet) Canonicalize() error {
} }
if i == 0 { if i == 0 {
fam = len((*s)[i].RangeStart) fam = len((*s)[i].RangeStart)
} else { } else if fam != len((*s)[i].RangeStart) {
if fam != len((*s)[i].RangeStart) {
return fmt.Errorf("mixed address families") return fmt.Errorf("mixed address families")
} }
} }
}
// Make sure none of the ranges in the set overlap // Make sure none of the ranges in the set overlap
l := len(*s) l := len(*s)

View File

@ -40,7 +40,6 @@ var _ = Describe("range sets", func() {
r, err = p.RangeFor(net.IP{192, 168, 99, 99}) r, err = p.RangeFor(net.IP{192, 168, 99, 99})
Expect(r).To(BeNil()) Expect(r).To(BeNil())
Expect(err).To(MatchError("192.168.99.99 not in range set 192.168.0.1-192.168.0.254,172.16.1.1-172.16.1.254")) Expect(err).To(MatchError("192.168.99.99 not in range set 192.168.0.1-192.168.0.254,172.16.1.1-172.16.1.254"))
}) })
It("should discover overlaps within a set", func() { It("should discover overlaps within a set", func() {

View File

@ -17,10 +17,10 @@ package allocator
import ( import (
"net" "net"
"github.com/containernetworking/cni/pkg/types"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/types"
) )
var _ = Describe("IP ranges", func() { var _ = Describe("IP ranges", func() {

View File

@ -24,8 +24,10 @@ import (
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend"
) )
const lastIPFilePrefix = "last_reserved_ip." const (
const LineBreak = "\r\n" lastIPFilePrefix = "last_reserved_ip."
LineBreak = "\r\n"
)
var defaultDataDir = "/var/lib/cni/networks" var defaultDataDir = "/var/lib/cni/networks"
@ -44,7 +46,7 @@ func New(network, dataDir string) (*Store, error) {
dataDir = defaultDataDir dataDir = defaultDataDir
} }
dir := filepath.Join(dataDir, network) dir := filepath.Join(dataDir, network)
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err return nil, err
} }
@ -58,7 +60,7 @@ func New(network, dataDir string) (*Store, error) {
func (s *Store) Reserve(id string, ifname string, ip net.IP, rangeID string) (bool, error) { func (s *Store) Reserve(id string, ifname string, ip net.IP, rangeID string) (bool, error) {
fname := GetEscapedPath(s.dataDir, ip.String()) fname := GetEscapedPath(s.dataDir, ip.String())
f, err := os.OpenFile(fname, os.O_RDWR|os.O_EXCL|os.O_CREATE, 0644) f, err := os.OpenFile(fname, os.O_RDWR|os.O_EXCL|os.O_CREATE, 0o644)
if os.IsExist(err) { if os.IsExist(err) {
return false, nil return false, nil
} }
@ -76,7 +78,7 @@ func (s *Store) Reserve(id string, ifname string, ip net.IP, rangeID string) (bo
} }
// store the reserved ip in lastIPFile // store the reserved ip in lastIPFile
ipfile := GetEscapedPath(s.dataDir, lastIPFilePrefix+rangeID) ipfile := GetEscapedPath(s.dataDir, lastIPFilePrefix+rangeID)
err = os.WriteFile(ipfile, []byte(ip.String()), 0644) err = os.WriteFile(ipfile, []byte(ip.String()), 0o644)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -110,7 +112,6 @@ func (s *Store) FindByKey(id string, ifname string, match string) (bool, error)
return nil return nil
}) })
return found, err return found, err
} }
func (s *Store) FindByID(id string, ifname string) bool { func (s *Store) FindByID(id string, ifname string) bool {
@ -124,7 +125,7 @@ func (s *Store) FindByID(id string, ifname string) bool {
// Match anything created by this id // Match anything created by this id
if !found && err == nil { if !found && err == nil {
match := strings.TrimSpace(id) match := strings.TrimSpace(id)
found, err = s.FindByKey(id, ifname, match) found, _ = s.FindByKey(id, ifname, match)
} }
return found return found
@ -149,7 +150,6 @@ func (s *Store) ReleaseByKey(id string, ifname string, match string) (bool, erro
return nil return nil
}) })
return found, err return found, err
} }
// N.B. This function eats errors to be tolerant and // N.B. This function eats errors to be tolerant and
@ -162,7 +162,7 @@ func (s *Store) ReleaseByID(id string, ifname string) error {
// For backwards compatibility, look for files written by a previous version // For backwards compatibility, look for files written by a previous version
if !found && err == nil { if !found && err == nil {
match := strings.TrimSpace(id) match := strings.TrimSpace(id)
found, err = s.ReleaseByKey(id, ifname, match) _, err = s.ReleaseByKey(id, ifname, match)
} }
return err return err
} }
@ -198,7 +198,7 @@ func (s *Store) GetByID(id string, ifname string) []net.IP {
func GetEscapedPath(dataDir string, fname string) string { func GetEscapedPath(dataDir string, fname string) string {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
fname = strings.Replace(fname, ":", "_", -1) fname = strings.ReplaceAll(fname, ":", "_")
} }
return filepath.Join(dataDir, fname) return filepath.Join(dataDir, fname)
} }

View File

@ -15,10 +15,10 @@
package disk package disk
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestLock(t *testing.T) { func TestLock(t *testing.T) {

View File

@ -15,9 +15,10 @@
package disk package disk
import ( import (
"github.com/alexflint/go-filemutex"
"os" "os"
"path" "path"
"github.com/alexflint/go-filemutex"
) )
// FileLock wraps os.File to be used as a lock using flock // FileLock wraps os.File to be used as a lock using flock

View File

@ -30,7 +30,7 @@ var _ = Describe("Lock Operations", func() {
// create a dummy file to lock // create a dummy file to lock
path := filepath.Join(dir, "x") path := filepath.Join(dir, "x")
f, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0666) f, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0o666)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
err = f.Close() err = f.Close()
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())

View File

@ -17,9 +17,10 @@ package main
import ( import (
"os" "os"
"github.com/containernetworking/cni/pkg/types"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/types"
) )
var _ = Describe("parsing resolv.conf", func() { var _ = Describe("parsing resolv.conf", func() {

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestHostLocal(t *testing.T) { func TestHostLocal(t *testing.T) {

View File

@ -21,14 +21,14 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const LineBreak = "\r\n" const LineBreak = "\r\n"
@ -57,7 +57,7 @@ var _ = Describe("host-local Operations", func() {
ver := ver ver := ver
It(fmt.Sprintf("[%s] allocates and releases addresses with ADD/DEL", ver), func() { It(fmt.Sprintf("[%s] allocates and releases addresses with ADD/DEL", ver), func() {
err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0644) err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
conf := fmt.Sprintf(`{ conf := fmt.Sprintf(`{
@ -166,7 +166,7 @@ var _ = Describe("host-local Operations", func() {
It(fmt.Sprintf("[%s] allocates and releases addresses on specific interface with ADD/DEL", ver), func() { It(fmt.Sprintf("[%s] allocates and releases addresses on specific interface with ADD/DEL", ver), func() {
const ifname1 string = "eth1" const ifname1 string = "eth1"
err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0644) err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
conf0 := fmt.Sprintf(`{ conf0 := fmt.Sprintf(`{
@ -356,7 +356,7 @@ var _ = Describe("host-local Operations", func() {
}) })
It(fmt.Sprintf("[%s] verify DEL works on backwards compatible allocate", ver), func() { It(fmt.Sprintf("[%s] verify DEL works on backwards compatible allocate", ver), func() {
err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0644) err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
conf := fmt.Sprintf(`{ conf := fmt.Sprintf(`{
@ -397,7 +397,7 @@ var _ = Describe("host-local Operations", func() {
contents, err := os.ReadFile(ipFilePath) contents, err := os.ReadFile(ipFilePath)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(string(contents)).To(Equal(args.ContainerID + LineBreak + ifname)) Expect(string(contents)).To(Equal(args.ContainerID + LineBreak + ifname))
err = os.WriteFile(ipFilePath, []byte(strings.TrimSpace(args.ContainerID)), 0644) err = os.WriteFile(ipFilePath, []byte(strings.TrimSpace(args.ContainerID)), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
err = testutils.CmdDelWithArgs(args, func() error { err = testutils.CmdDelWithArgs(args, func() error {
@ -504,7 +504,7 @@ var _ = Describe("host-local Operations", func() {
return cmdAdd(args) return cmdAdd(args)
}) })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(strings.Index(string(out), "Error retriving last reserved ip")).To(Equal(-1)) Expect(strings.Index(string(out), "Error retrieving last reserved ip")).To(Equal(-1))
}) })
It(fmt.Sprintf("[%s] allocates a custom IP when requested by config args", ver), func() { It(fmt.Sprintf("[%s] allocates a custom IP when requested by config args", ver), func() {
@ -546,7 +546,7 @@ var _ = Describe("host-local Operations", func() {
}) })
It(fmt.Sprintf("[%s] allocates custom IPs from multiple ranges", ver), func() { It(fmt.Sprintf("[%s] allocates custom IPs from multiple ranges", ver), func() {
err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0644) err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
conf := fmt.Sprintf(`{ conf := fmt.Sprintf(`{
@ -594,7 +594,7 @@ var _ = Describe("host-local Operations", func() {
}) })
It(fmt.Sprintf("[%s] allocates custom IPs from multiple protocols", ver), func() { It(fmt.Sprintf("[%s] allocates custom IPs from multiple protocols", ver), func() {
err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0644) err := os.WriteFile(filepath.Join(tmpDir, "resolv.conf"), []byte("nameserver 192.0.2.3"), 0o644)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
conf := fmt.Sprintf(`{ conf := fmt.Sprintf(`{

View File

@ -19,14 +19,13 @@ import (
"net" "net"
"strings" "strings"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk"
) )
func main() { func main() {
@ -34,7 +33,6 @@ func main() {
} }
func cmdCheck(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error {
ipamConf, _, err := allocator.LoadIPAMConfig(args.StdinData, args.Args) ipamConf, _, err := allocator.LoadIPAMConfig(args.StdinData, args.Args)
if err != nil { if err != nil {
return err return err
@ -48,8 +46,8 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
defer store.Close() defer store.Close()
containerIpFound := store.FindByID(args.ContainerID, args.IfName) containerIPFound := store.FindByID(args.ContainerID, args.IfName)
if containerIpFound == false { if !containerIPFound {
return fmt.Errorf("host-local: Failed to find address added by container %v", args.ContainerID) return fmt.Errorf("host-local: Failed to find address added by container %v", args.ContainerID)
} }

View File

@ -19,13 +19,13 @@ import (
"net" "net"
"strings" "strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
var _ = Describe("static Operations", func() { var _ = Describe("static Operations", func() {

View File

@ -129,7 +129,6 @@ func loadNetConf(bytes []byte, envArgs string) (*NetConf, string, error) {
// - Calculates and compiles a list of gateway addresses // - Calculates and compiles a list of gateway addresses
// - Adds a default route if needed // - Adds a default route if needed
func calcGateways(result *current.Result, n *NetConf) (*gwInfo, *gwInfo, error) { func calcGateways(result *current.Result, n *NetConf) (*gwInfo, *gwInfo, error) {
gwsV4 := &gwInfo{} gwsV4 := &gwInfo{}
gwsV6 := &gwInfo{} gwsV6 := &gwInfo{}
@ -300,8 +299,8 @@ func ensureBridge(brName string, mtu int, promiscMode, vlanFiltering bool) (*net
return br, nil return br, nil
} }
func ensureVlanInterface(br *netlink.Bridge, vlanId int) (netlink.Link, error) { func ensureVlanInterface(br *netlink.Bridge, vlanID int) (netlink.Link, error) {
name := fmt.Sprintf("%s.%d", br.Name, vlanId) name := fmt.Sprintf("%s.%d", br.Name, vlanID)
brGatewayVeth, err := netlink.LinkByName(name) brGatewayVeth, err := netlink.LinkByName(name)
if err != nil { if err != nil {
@ -314,7 +313,7 @@ func ensureVlanInterface(br *netlink.Bridge, vlanId int) (netlink.Link, error) {
return nil, fmt.Errorf("faild to find host namespace: %v", err) return nil, fmt.Errorf("faild to find host namespace: %v", err)
} }
_, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanId, "") _, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanID, "")
if err != nil { if err != nil {
return nil, fmt.Errorf("faild to create vlan gateway %q: %v", name, err) return nil, fmt.Errorf("faild to create vlan gateway %q: %v", name, err)
} }
@ -407,7 +406,7 @@ func enableIPForward(family int) error {
} }
func cmdAdd(args *skel.CmdArgs) error { func cmdAdd(args *skel.CmdArgs) error {
var success bool = false success := false
n, cniVersion, err := loadNetConf(args.StdinData, args.Args) n, cniVersion, err := loadNetConf(args.StdinData, args.Args)
if err != nil { if err != nil {
@ -421,7 +420,7 @@ func cmdAdd(args *skel.CmdArgs) error {
} }
if n.HairpinMode && n.PromiscMode { if n.HairpinMode && n.PromiscMode {
return fmt.Errorf("cannot set hairpin mode and promiscuous mode at the same time.") return fmt.Errorf("cannot set hairpin mode and promiscuous mode at the same time")
} }
br, brInterface, err := setupBridge(n) br, brInterface, err := setupBridge(n)
@ -533,8 +532,10 @@ func cmdAdd(args *skel.CmdArgs) error {
} }
if vlanInterface == nil { if vlanInterface == nil {
vlanInterface = &current.Interface{Name: vlanIface.Attrs().Name, vlanInterface = &current.Interface{
Mac: vlanIface.Attrs().HardwareAddr.String()} Name: vlanIface.Attrs().Name,
Mac: vlanIface.Attrs().HardwareAddr.String(),
}
result.Interfaces = append(result.Interfaces, vlanInterface) result.Interfaces = append(result.Interfaces, vlanInterface)
} }
@ -720,7 +721,6 @@ type cniBridgeIf struct {
} }
func validateInterface(intf current.Interface, expectInSb bool) (cniBridgeIf, netlink.Link, error) { func validateInterface(intf current.Interface, expectInSb bool) (cniBridgeIf, netlink.Link, error) {
ifFound := cniBridgeIf{found: false} ifFound := cniBridgeIf{found: false}
if intf.Name == "" { if intf.Name == "" {
return ifFound, nil, fmt.Errorf("Interface name missing ") return ifFound, nil, fmt.Errorf("Interface name missing ")
@ -745,7 +745,6 @@ func validateInterface(intf current.Interface, expectInSb bool) (cniBridgeIf, ne
} }
func validateCniBrInterface(intf current.Interface, n *NetConf) (cniBridgeIf, error) { func validateCniBrInterface(intf current.Interface, n *NetConf) (cniBridgeIf, error) {
brFound, link, err := validateInterface(intf, false) brFound, link, err := validateInterface(intf, false)
if err != nil { if err != nil {
return brFound, err return brFound, err
@ -777,7 +776,6 @@ func validateCniBrInterface(intf current.Interface, n *NetConf) (cniBridgeIf, er
} }
func validateCniVethInterface(intf *current.Interface, brIf cniBridgeIf, contIf cniBridgeIf) (cniBridgeIf, error) { func validateCniVethInterface(intf *current.Interface, brIf cniBridgeIf, contIf cniBridgeIf) (cniBridgeIf, error) {
vethFound, link, err := validateInterface(*intf, false) vethFound, link, err := validateInterface(*intf, false)
if err != nil { if err != nil {
return vethFound, err return vethFound, err
@ -821,7 +819,6 @@ func validateCniVethInterface(intf *current.Interface, brIf cniBridgeIf, contIf
} }
func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error) { func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error) {
vethFound, link, err := validateInterface(intf, true) vethFound, link, err := validateInterface(intf, true)
if err != nil { if err != nil {
return vethFound, err return vethFound, err
@ -850,7 +847,6 @@ func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error)
} }
func cmdCheck(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error {
n, _, err := loadNetConf(args.StdinData, args.Args) n, _, err := loadNetConf(args.StdinData, args.Args)
if err != nil { if err != nil {
return err return err

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
var ( var (

View File

@ -23,6 +23,9 @@ import (
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
"github.com/networkplumbing/go-nft/nft" "github.com/networkplumbing/go-nft/nft"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/vishvananda/netlink/nl" "github.com/vishvananda/netlink/nl"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
@ -32,12 +35,7 @@ import (
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const ( const (
@ -55,8 +53,9 @@ type Net struct {
IPAM *allocator.IPAMConfig `json:"ipam"` IPAM *allocator.IPAMConfig `json:"ipam"`
// RuntimeConfig struct { // The capability arg // RuntimeConfig struct { // The capability arg
// IPRanges []RangeSet `json:"ipRanges,omitempty"` // IPRanges []RangeSet `json:"ipRanges,omitempty"`
//} `json:"runtimeConfig,omitempty"`
// Args *struct { // Args *struct {
// } `json:"runtimeConfig,omitempty"`
// A *IPAMArgs `json:"cni"` // A *IPAMArgs `json:"cni"`
DNS types.DNS `json:"dns"` DNS types.DNS `json:"dns"`
RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` RawPrevResult map[string]interface{} `json:"prevResult,omitempty"`
@ -298,7 +297,6 @@ func (tc testCase) createCmdArgs(targetNS ns.NetNS, dataDir string) *skel.CmdArg
// createCheckCmdArgs generates network configuration and creates command // createCheckCmdArgs generates network configuration and creates command
// arguments for a Check test case. // arguments for a Check test case.
func (tc testCase) createCheckCmdArgs(targetNS ns.NetNS, config *Net, dataDir string) *skel.CmdArgs { func (tc testCase) createCheckCmdArgs(targetNS ns.NetNS, config *Net, dataDir string) *skel.CmdArgs {
conf, err := json.Marshal(config) conf, err := json.Marshal(config)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
@ -412,9 +410,9 @@ func countIPAMIPs(path string) (int, error) {
return count, nil return count, nil
} }
func checkVlan(vlanId int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool { func checkVlan(vlanID int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool {
for _, vlan := range bridgeVlanInfo { for _, vlan := range bridgeVlanInfo {
if vlan.Vid == uint16(vlanId) { if vlan.Vid == uint16(vlanID) {
return true return true
} }
} }
@ -435,10 +433,12 @@ type testerBase struct {
vethName string vethName string
} }
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string, testNS, targetNS ns.NetNS) cmdAddDelTester { func newTesterByVersion(version string, testNS, targetNS ns.NetNS) cmdAddDelTester {
switch { switch {
@ -1259,7 +1259,6 @@ func (tester *testerV03x) cmdAddTest(tc testCase, dataDir string) (types.Result,
} }
func (tester *testerV03x) cmdCheckTest(tc testCase, conf *Net, dataDir string) { func (tester *testerV03x) cmdCheckTest(tc testCase, conf *Net, dataDir string) {
return
} }
func (tester *testerV03x) cmdDelTest(tc testCase, dataDir string) { func (tester *testerV03x) cmdDelTest(tc testCase, dataDir string) {
@ -1490,7 +1489,6 @@ func (tester *testerV01xOr02x) cmdAddTest(tc testCase, dataDir string) (types.Re
} }
func (tester *testerV01xOr02x) cmdCheckTest(tc testCase, conf *Net, dataDir string) { func (tester *testerV01xOr02x) cmdCheckTest(tc testCase, conf *Net, dataDir string) {
return
} }
func (tester *testerV01xOr02x) cmdDelTest(tc testCase, dataDir string) { func (tester *testerV01xOr02x) cmdDelTest(tc testCase, dataDir string) {
@ -1500,11 +1498,12 @@ func (tester *testerV01xOr02x) cmdDelTest(tc testCase, dataDir string) {
err := testutils.CmdDelWithArgs(tester.args, func() error { err := testutils.CmdDelWithArgs(tester.args, func() error {
return cmdDel(tester.args) return cmdDel(tester.args)
}) })
if expect020DelError(tc) { switch {
case expect020DelError(tc):
Expect(err).To(MatchError(tc.DelErr020)) Expect(err).To(MatchError(tc.DelErr020))
} else if expect010DelError(tc) { case expect010DelError(tc):
Expect(err).To(MatchError(tc.DelErr010)) Expect(err).To(MatchError(tc.DelErr010))
} else { default:
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
} }
return nil return nil
@ -1577,7 +1576,6 @@ func buildOneConfig(name, cniVersion string, orig *Net, prevResult types.Result)
} }
return conf, nil return conf, nil
} }
func cmdAddDelCheckTest(origNS, targetNS ns.NetNS, tc testCase, dataDir string) { func cmdAddDelCheckTest(origNS, targetNS ns.NetNS, tc testCase, dataDir string) {
@ -1989,8 +1987,6 @@ var _ = Describe("bridge Operations", func() {
It(fmt.Sprintf("[%s] ensure promiscuous mode on bridge", ver), func() { It(fmt.Sprintf("[%s] ensure promiscuous mode on bridge", ver), func() {
const IFNAME = "bridge0" const IFNAME = "bridge0"
const EXPECTED_IP = "10.0.0.0/8"
const CHANGED_EXPECTED_IP = "10.1.2.3/16"
conf := &NetConf{ conf := &NetConf{
NetConf: types.NetConf{ NetConf: types.NetConf{

View File

@ -26,7 +26,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -42,7 +41,6 @@ func parseNetConf(bytes []byte) (*types.NetConf, error) {
} }
func createDummy(conf *types.NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) { func createDummy(conf *types.NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) {
dummy := &current.Interface{} dummy := &current.Interface{}
dm := &netlink.Dummy{ dm := &netlink.Dummy{
@ -245,7 +243,6 @@ func cmdCheck(args *skel.CmdArgs) error {
// //
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap) err := validateCniContainerInterface(contMap)
if err != nil { if err != nil {
@ -262,11 +259,9 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
return nil return nil
} }
func validateCniContainerInterface(intf current.Interface) error { func validateCniContainerInterface(intf current.Interface) error {
var link netlink.Link var link netlink.Link
var err error var err error

View File

@ -15,12 +15,11 @@
package main_test package main_test
import ( import (
"github.com/onsi/gomega/gexec" "testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"testing"
) )
var pathToLoPlugin string var pathToLoPlugin string

View File

@ -23,6 +23,10 @@ import (
"strings" "strings"
"syscall" "syscall"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
@ -31,11 +35,6 @@ import (
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const MASTER_NAME = "eth0" const MASTER_NAME = "eth0"
@ -89,7 +88,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -99,10 +97,12 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {

View File

@ -31,16 +31,13 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )
var ( var sysBusPCI = "/sys/bus/pci/devices"
sysBusPCI = "/sys/bus/pci/devices"
)
// Array of different linux drivers bound to network device needed for DPDK // Array of different linux drivers bound to network device needed for DPDK
var userspaceDrivers = []string{"vfio-pci", "uio_pci_generic", "igb_uio"} var userspaceDrivers = []string{"vfio-pci", "uio_pci_generic", "igb_uio"}
@ -325,10 +322,11 @@ func getLink(devname, hwaddr, kernelpath, pciaddr string) (netlink.Link, error)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to list node links: %v", err) return nil, fmt.Errorf("failed to list node links: %v", err)
} }
switch {
if len(devname) > 0 { case len(devname) > 0:
return netlink.LinkByName(devname) return netlink.LinkByName(devname)
} else if len(hwaddr) > 0 { case len(hwaddr) > 0:
hwAddr, err := net.ParseMAC(hwaddr) hwAddr, err := net.ParseMAC(hwaddr)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to parse MAC address %q: %v", hwaddr, err) return nil, fmt.Errorf("failed to parse MAC address %q: %v", hwaddr, err)
@ -339,7 +337,7 @@ func getLink(devname, hwaddr, kernelpath, pciaddr string) (netlink.Link, error)
return link, nil return link, nil
} }
} }
} else if len(kernelpath) > 0 { case len(kernelpath) > 0:
if !filepath.IsAbs(kernelpath) || !strings.HasPrefix(kernelpath, "/sys/devices/") { if !filepath.IsAbs(kernelpath) || !strings.HasPrefix(kernelpath, "/sys/devices/") {
return nil, fmt.Errorf("kernel device path %q must be absolute and begin with /sys/devices/", kernelpath) return nil, fmt.Errorf("kernel device path %q must be absolute and begin with /sys/devices/", kernelpath)
} }
@ -358,7 +356,7 @@ func getLink(devname, hwaddr, kernelpath, pciaddr string) (netlink.Link, error)
} }
} }
} }
} else if len(pciaddr) > 0 { case len(pciaddr) > 0:
netDir := filepath.Join(sysBusPCI, pciaddr, "net") netDir := filepath.Join(sysBusPCI, pciaddr, "net")
if _, err := os.Lstat(netDir); err != nil { if _, err := os.Lstat(netDir); err != nil {
virtioNetDir := filepath.Join(sysBusPCI, pciaddr, "virtio*", "net") virtioNetDir := filepath.Join(sysBusPCI, pciaddr, "virtio*", "net")
@ -386,7 +384,6 @@ func main() {
} }
func cmdCheck(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error {
cfg, err := loadConf(args.StdinData) cfg, err := loadConf(args.StdinData)
if err != nil { if err != nil {
return err return err
@ -443,7 +440,6 @@ func cmdCheck(args *skel.CmdArgs) error {
// //
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap) err := validateCniContainerInterface(contMap)
if err != nil { if err != nil {
@ -469,7 +465,6 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
func validateCniContainerInterface(intf current.Interface) error { func validateCniContainerInterface(intf current.Interface) error {
var link netlink.Link var link netlink.Link
var err error var err error

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestVlan(t *testing.T) { func TestVlan(t *testing.T) {

View File

@ -23,6 +23,10 @@ import (
"path" "path"
"strings" "strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types040 "github.com/containernetworking/cni/pkg/types/040" types040 "github.com/containernetworking/cni/pkg/types/040"
@ -30,10 +34,6 @@ import (
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
) )
type Net struct { type Net struct {
@ -214,7 +214,6 @@ func buildOneConfig(name, cniVersion string, orig *Net, prevResult types.Result)
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -224,9 +223,11 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
testerV03x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {
@ -711,7 +712,6 @@ var _ = Describe("base functionality", func() {
} }
_, _, err := testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) }) _, _, err := testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) })
Expect(err).To(MatchError(`specify either "device", "hwaddr", "kernelpath" or "pciBusID"`)) Expect(err).To(MatchError(`specify either "device", "hwaddr", "kernelpath" or "pciBusID"`))
}) })
It(fmt.Sprintf("[%s] works with a valid config without IPAM", ver), func() { It(fmt.Sprintf("[%s] works with a valid config without IPAM", ver), func() {
@ -1167,7 +1167,7 @@ func (fs *fakeFilesystem) use() func() {
fs.rootDir = tmpDir fs.rootDir = tmpDir
for _, dir := range fs.dirs { for _, dir := range fs.dirs {
err := os.MkdirAll(path.Join(fs.rootDir, dir), 0755) err := os.MkdirAll(path.Join(fs.rootDir, dir), 0o755)
if err != nil { if err != nil {
panic(fmt.Errorf("error creating fake directory: %s", err.Error())) panic(fmt.Errorf("error creating fake directory: %s", err.Error()))
} }

View File

@ -26,7 +26,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -357,7 +356,6 @@ func main() {
} }
func cmdCheck(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error {
n, _, err := loadConf(args, true) n, _, err := loadConf(args, true)
if err != nil { if err != nil {
return err return err
@ -423,7 +421,6 @@ func cmdCheck(args *skel.CmdArgs) error {
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode) err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode)
if err != nil { if err != nil {
@ -448,7 +445,6 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
func validateCniContainerInterface(intf current.Interface, masterIndex int, modeExpected string) error { func validateCniContainerInterface(intf current.Interface, masterIndex int, modeExpected string) error {
var link netlink.Link var link netlink.Link
var err error var err error
@ -469,6 +465,9 @@ func validateCniContainerInterface(intf current.Interface, masterIndex int, mode
} }
mode, err := modeFromString(modeExpected) mode, err := modeFromString(modeExpected)
if err != nil {
return err
}
if ipv.Mode != mode { if ipv.Mode != mode {
currString, err := modeToString(ipv.Mode) currString, err := modeToString(ipv.Mode)
if err != nil { if err != nil {

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestIpvlan(t *testing.T) { func TestIpvlan(t *testing.T) {

View File

@ -22,6 +22,10 @@ import (
"strings" "strings"
"syscall" "syscall"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
@ -29,16 +33,13 @@ import (
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const MASTER_NAME = "eth0" const (
const MASTER_NAME_INCONTAINER = "eth1" MASTER_NAME = "eth0"
MASTER_NAME_INCONTAINER = "eth1"
)
type Net struct { type Net struct {
Name string `json:"name"` Name string `json:"name"`
@ -92,7 +93,6 @@ func buildOneConfig(cniVersion string, master string, orig *Net, prevResult type
} }
return conf, nil return conf, nil
} }
func ipvlanAddCheckDelTest(conf, masterName string, originalNS, targetNS ns.NetNS) { func ipvlanAddCheckDelTest(conf, masterName string, originalNS, targetNS ns.NetNS) {
@ -206,9 +206,11 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV02x testerBase testerV04x testerBase
testerV02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {
@ -471,8 +473,8 @@ var _ = Describe("ipvlan Operations", func() {
err = netlink.LinkSetUp(link) err = netlink.LinkSetUp(link)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
var address = &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} address := &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)}
var addr = &netlink.Addr{IPNet: address} addr := &netlink.Addr{IPNet: address}
err = netlink.AddrAdd(link, addr) err = netlink.AddrAdd(link, addr)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())

View File

@ -26,7 +26,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )
@ -112,7 +111,7 @@ func cmdAdd(args *skel.CmdArgs) error {
r := &current.Result{ r := &current.Result{
CNIVersion: conf.CNIVersion, CNIVersion: conf.CNIVersion,
Interfaces: []*current.Interface{ Interfaces: []*current.Interface{
&current.Interface{ {
Name: args.IfName, Name: args.IfName,
Mac: "00:00:00:00:00:00", Mac: "00:00:00:00:00:00",
Sandbox: args.Netns, Sandbox: args.Netns,

View File

@ -15,12 +15,11 @@
package main_test package main_test
import ( import (
"github.com/onsi/gomega/gexec" "testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"testing"
) )
var pathToLoPlugin string var pathToLoPlugin string

View File

@ -20,12 +20,13 @@ import (
"os/exec" "os/exec"
"strings" "strings"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec" "github.com/onsi/gomega/gexec"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
func generateConfig(cniVersion string) *strings.Reader { func generateConfig(cniVersion string) *strings.Reader {

View File

@ -27,7 +27,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -434,7 +433,6 @@ func main() {
} }
func cmdCheck(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error {
n, _, err := loadConf(args, args.Args) n, _, err := loadConf(args, args.Args)
if err != nil { if err != nil {
return err return err
@ -457,7 +455,7 @@ func cmdCheck(args *skel.CmdArgs) error {
// Parse previous result. // Parse previous result.
if n.NetConf.RawPrevResult == nil { if n.NetConf.RawPrevResult == nil {
return fmt.Errorf("Required prevResult missing") return fmt.Errorf("required prevResult missing")
} }
if err := version.ParsePrevResult(&n.NetConf); err != nil { if err := version.ParsePrevResult(&n.NetConf); err != nil {
@ -482,7 +480,7 @@ func cmdCheck(args *skel.CmdArgs) error {
// The namespace must be the same as what was configured // The namespace must be the same as what was configured
if args.Netns != contMap.Sandbox { if args.Netns != contMap.Sandbox {
return fmt.Errorf("Sandbox in prevResult %s doesn't match configured netns: %s", return fmt.Errorf("sandbox in prevResult %s doesn't match configured netns: %s",
contMap.Sandbox, args.Netns) contMap.Sandbox, args.Netns)
} }
@ -501,7 +499,6 @@ func cmdCheck(args *skel.CmdArgs) error {
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode) err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode)
if err != nil { if err != nil {
@ -526,27 +523,29 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
func validateCniContainerInterface(intf current.Interface, parentIndex int, modeExpected string) error { func validateCniContainerInterface(intf current.Interface, parentIndex int, modeExpected string) error {
var link netlink.Link var link netlink.Link
var err error var err error
if intf.Name == "" { if intf.Name == "" {
return fmt.Errorf("Container interface name missing in prevResult: %v", intf.Name) return fmt.Errorf("container interface name missing in prevResult: %v", intf.Name)
} }
link, err = netlink.LinkByName(intf.Name) link, err = netlink.LinkByName(intf.Name)
if err != nil { if err != nil {
return fmt.Errorf("Container Interface name in prevResult: %s not found", intf.Name) return fmt.Errorf("container Interface name in prevResult: %s not found", intf.Name)
} }
if intf.Sandbox == "" { if intf.Sandbox == "" {
return fmt.Errorf("Error: Container interface %s should not be in host namespace", link.Attrs().Name) return fmt.Errorf("error: Container interface %s should not be in host namespace", link.Attrs().Name)
} }
macv, isMacvlan := link.(*netlink.Macvlan) macv, isMacvlan := link.(*netlink.Macvlan)
if !isMacvlan { if !isMacvlan {
return fmt.Errorf("Error: Container interface %s not of type macvlan", link.Attrs().Name) return fmt.Errorf("error: Container interface %s not of type macvlan", link.Attrs().Name)
} }
mode, err := modeFromString(modeExpected) mode, err := modeFromString(modeExpected)
if err != nil {
return err
}
if macv.Mode != mode { if macv.Mode != mode {
currString, err := modeToString(macv.Mode) currString, err := modeToString(macv.Mode)
if err != nil { if err != nil {
@ -556,12 +555,12 @@ func validateCniContainerInterface(intf current.Interface, parentIndex int, mode
if err != nil { if err != nil {
return err return err
} }
return fmt.Errorf("Container macvlan mode %s does not match expected value: %s", currString, confString) return fmt.Errorf("container macvlan mode %s does not match expected value: %s", currString, confString)
} }
if intf.Mac != "" { if intf.Mac != "" {
if intf.Mac != link.Attrs().HardwareAddr.String() { if intf.Mac != link.Attrs().HardwareAddr.String() {
return fmt.Errorf("Interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr) return fmt.Errorf("interface %s Mac %s doesn't match container Mac: %s", intf.Name, intf.Mac, link.Attrs().HardwareAddr)
} }
} }

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestMacvlan(t *testing.T) { func TestMacvlan(t *testing.T) {

View File

@ -22,6 +22,10 @@ import (
"strings" "strings"
"syscall" "syscall"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
@ -29,16 +33,13 @@ import (
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const MASTER_NAME = "eth0" const (
const MASTER_NAME_INCONTAINER = "eth1" MASTER_NAME = "eth0"
MASTER_NAME_INCONTAINER = "eth1"
)
type Net struct { type Net struct {
Name string `json:"name"` Name string `json:"name"`
@ -49,8 +50,8 @@ type Net struct {
IPAM *allocator.IPAMConfig `json:"ipam"` IPAM *allocator.IPAMConfig `json:"ipam"`
// RuntimeConfig struct { // The capability arg // RuntimeConfig struct { // The capability arg
// IPRanges []RangeSet `json:"ipRanges,omitempty"` // IPRanges []RangeSet `json:"ipRanges,omitempty"`
//} `json:"runtimeConfig,omitempty"`
// Args *struct { // Args *struct {
// } `json:"runtimeConfig,omitempty"`
// A *IPAMArgs `json:"cni"` // A *IPAMArgs `json:"cni"`
DNS types.DNS `json:"dns"` DNS types.DNS `json:"dns"`
RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` RawPrevResult map[string]interface{} `json:"prevResult,omitempty"`
@ -98,7 +99,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -108,10 +108,12 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {
@ -407,7 +409,6 @@ var _ = Describe("macvlan Operations", func() {
return nil return nil
}) })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
It(fmt.Sprintf("[%s] configures and deconfigures a l2 macvlan link with ADD/DEL", ver), func() { It(fmt.Sprintf("[%s] configures and deconfigures a l2 macvlan link with ADD/DEL", ver), func() {
@ -637,8 +638,8 @@ var _ = Describe("macvlan Operations", func() {
err = netlink.LinkSetUp(link) err = netlink.LinkSetUp(link)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
var address = &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} address := &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)}
var addr = &netlink.Addr{IPNet: address} addr := &netlink.Addr{IPNet: address}
err = netlink.AddrAdd(link, addr) err = netlink.AddrAdd(link, addr)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())

View File

@ -28,7 +28,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -282,7 +281,6 @@ func cmdDel(args *skel.CmdArgs) error {
} }
return err return err
}) })
if err != nil { if err != nil {
// if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times // if NetNs is passed down by the Cloud Orchestration Engine, or if it called multiple times
// so don't return an error if the device is already removed. // so don't return an error if the device is already removed.
@ -358,7 +356,6 @@ func cmdCheck(args *skel.CmdArgs) error {
// //
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap) err := validateCniContainerInterface(contMap)
if err != nil { if err != nil {
@ -383,7 +380,6 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
func validateCniContainerInterface(intf current.Interface) error { func validateCniContainerInterface(intf current.Interface) error {
var link netlink.Link var link netlink.Link
var err error var err error

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestPtp(t *testing.T) { func TestPtp(t *testing.T) {

View File

@ -20,6 +20,10 @@ import (
"os" "os"
"strings" "strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
@ -27,12 +31,7 @@ import (
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
type Net struct { type Net struct {
@ -87,7 +86,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -97,10 +95,12 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {

View File

@ -25,15 +25,13 @@ import (
"syscall" "syscall"
"github.com/opencontainers/selinux/go-selinux" "github.com/opencontainers/selinux/go-selinux"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -49,8 +47,7 @@ type NetConf struct {
Owner *uint32 `json:"owner,omitempty"` Owner *uint32 `json:"owner,omitempty"`
Group *uint32 `json:"group,omitempty"` Group *uint32 `json:"group,omitempty"`
SelinuxContext string `json:"selinuxContext,omitempty"` SelinuxContext string `json:"selinuxContext,omitempty"`
Args *struct { Args *struct{} `json:"args,omitempty"`
} `json:"args,omitempty"`
RuntimeConfig struct { RuntimeConfig struct {
Mac string `json:"mac,omitempty"` Mac string `json:"mac,omitempty"`
} `json:"runtimeConfig,omitempty"` } `json:"runtimeConfig,omitempty"`
@ -176,14 +173,15 @@ func createLinkWithNetlink(tmpName string, mtu int, nsFd int, multiqueue bool, m
} }
func createLink(tmpName string, conf *NetConf, netns ns.NetNS) error { func createLink(tmpName string, conf *NetConf, netns ns.NetNS) error {
if conf.SelinuxContext != "" { switch {
case conf.SelinuxContext != "":
if err := selinux.SetExecLabel(conf.SelinuxContext); err != nil { if err := selinux.SetExecLabel(conf.SelinuxContext); err != nil {
return fmt.Errorf("failed set socket label: %v", err) return fmt.Errorf("failed set socket label: %v", err)
} }
return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group)
} else if conf.Owner == nil || conf.Group == nil { case conf.Owner == nil || conf.Group == nil:
return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) return createTapWithIptool(tmpName, conf.MTU, conf.MultiQueue, conf.Mac, conf.Owner, conf.Group)
} else { default:
return createLinkWithNetlink(tmpName, conf.MTU, int(netns.Fd()), conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) return createLinkWithNetlink(tmpName, conf.MTU, int(netns.Fd()), conf.MultiQueue, conf.Mac, conf.Owner, conf.Group)
} }
} }

View File

@ -25,7 +25,6 @@ import (
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
@ -92,7 +91,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -102,10 +100,12 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {

View File

@ -20,12 +20,12 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
@ -35,7 +35,7 @@ import (
type NetConf struct { type NetConf struct {
types.NetConf types.NetConf
Master string `json:"master"` Master string `json:"master"`
VlanId int `json:"vlanId"` VlanID int `json:"vlanId"`
MTU int `json:"mtu,omitempty"` MTU int `json:"mtu,omitempty"`
LinkContNs bool `json:"linkInContainer,omitempty"` LinkContNs bool `json:"linkInContainer,omitempty"`
} }
@ -53,15 +53,14 @@ func loadConf(args *skel.CmdArgs) (*NetConf, string, error) {
return nil, "", fmt.Errorf("failed to load netconf: %v", err) return nil, "", fmt.Errorf("failed to load netconf: %v", err)
} }
if n.Master == "" { if n.Master == "" {
return nil, "", fmt.Errorf("\"master\" field is required. It specifies the host interface name to create the VLAN for.") return nil, "", fmt.Errorf("\"master\" field is required. It specifies the host interface name to create the VLAN for")
} }
if n.VlanId < 0 || n.VlanId > 4094 { if n.VlanID < 0 || n.VlanID > 4094 {
return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4095 inclusive)", n.VlanId) return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4095 inclusive)", n.VlanID)
} }
// check existing and MTU of master interface // check existing and MTU of master interface
masterMTU, err := getMTUByName(n.Master, args.Netns, n.LinkContNs) masterMTU, err := getMTUByName(n.Master, args.Netns, n.LinkContNs)
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }
@ -127,7 +126,7 @@ func createVlan(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interfac
ParentIndex: m.Attrs().Index, ParentIndex: m.Attrs().Index,
Namespace: netlink.NsFd(int(netns.Fd())), Namespace: netlink.NsFd(int(netns.Fd())),
}, },
VlanId: conf.VlanId, VlanId: conf.VlanID,
} }
if conf.LinkContNs { if conf.LinkContNs {
@ -326,9 +325,8 @@ func cmdCheck(args *skel.CmdArgs) error {
// //
// Check prevResults for ips, routes and dns against values found in the container // Check prevResults for ips, routes and dns against values found in the container
if err := netns.Do(func(_ ns.NetNS) error { if err := netns.Do(func(_ ns.NetNS) error {
// Check interface against values found in the container // Check interface against values found in the container
err := validateCniContainerInterface(contMap, m.Attrs().Index, conf.VlanId, conf.MTU) err := validateCniContainerInterface(contMap, m.Attrs().Index, conf.VlanID, conf.MTU)
if err != nil { if err != nil {
return err return err
} }
@ -350,8 +348,7 @@ func cmdCheck(args *skel.CmdArgs) error {
return nil return nil
} }
func validateCniContainerInterface(intf current.Interface, masterIndex int, vlanId int, mtu int) error { func validateCniContainerInterface(intf current.Interface, masterIndex int, vlanID int, mtu int) error {
var link netlink.Link var link netlink.Link
var err error var err error
@ -382,9 +379,9 @@ func validateCniContainerInterface(intf current.Interface, masterIndex int, vlan
} }
} }
if vlanId != vlan.VlanId { if vlanID != vlan.VlanId {
return fmt.Errorf("Error: Tuning link %s configured promisc is %v, current value is %d", return fmt.Errorf("Error: Tuning link %s configured promisc is %v, current value is %d",
intf.Name, vlanId, vlan.VlanId) intf.Name, vlanID, vlan.VlanId)
} }
if mtu != 0 { if mtu != 0 {

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestVlan(t *testing.T) { func TestVlan(t *testing.T) {

View File

@ -22,6 +22,10 @@ import (
"strings" "strings"
"syscall" "syscall"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020" types020 "github.com/containernetworking/cni/pkg/types/020"
@ -29,23 +33,20 @@ import (
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const MASTER_NAME = "eth0" const (
const MASTER_NAME_INCONTAINER = "eth1" MASTER_NAME = "eth0"
MASTER_NAME_INCONTAINER = "eth1"
)
type Net struct { type Net struct {
Name string `json:"name"` Name string `json:"name"`
CNIVersion string `json:"cniVersion"` CNIVersion string `json:"cniVersion"`
Type string `json:"type,omitempty"` Type string `json:"type,omitempty"`
Master string `json:"master"` Master string `json:"master"`
VlanId int `json:"vlanId"` VlanID int `json:"vlanId"`
MTU int `json:"mtu"` MTU int `json:"mtu"`
IPAM *allocator.IPAMConfig `json:"ipam"` IPAM *allocator.IPAMConfig `json:"ipam"`
DNS types.DNS `json:"dns"` DNS types.DNS `json:"dns"`
@ -94,7 +95,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ
} }
return conf, nil return conf, nil
} }
type tester interface { type tester interface {
@ -104,10 +104,12 @@ type tester interface {
type testerBase struct{} type testerBase struct{}
type testerV10x testerBase type (
type testerV04x testerBase testerV10x testerBase
type testerV03x testerBase testerV04x testerBase
type testerV01xOr02x testerBase testerV03x testerBase
testerV01xOr02x testerBase
)
func newTesterByVersion(version string) tester { func newTesterByVersion(version string) tester {
switch { switch {
@ -247,7 +249,7 @@ var _ = Describe("vlan Operations", func() {
Type: "vlan", Type: "vlan",
}, },
Master: masterInterface, Master: masterInterface,
VlanId: 33, VlanID: 33,
MTU: 1500, MTU: 1500,
LinkContNs: isInContainer, LinkContNs: isInContainer,
} }
@ -283,7 +285,7 @@ var _ = Describe("vlan Operations", func() {
Type: "vlan", Type: "vlan",
}, },
Master: masterInterface, Master: masterInterface,
VlanId: 33, VlanID: 33,
LinkContNs: isInContainer, LinkContNs: isInContainer,
} }

View File

@ -22,6 +22,9 @@ import (
"os" "os"
"time" "time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/invoke" "github.com/containernetworking/cni/pkg/invoke"
@ -30,10 +33,6 @@ import (
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
) )
func buildOneConfig(name, cniVersion string, orig *PluginConf, prevResult types.Result) (*PluginConf, []byte, error) { func buildOneConfig(name, cniVersion string, orig *PluginConf, prevResult types.Result) (*PluginConf, []byte, error) {
@ -78,7 +77,6 @@ func buildOneConfig(name, cniVersion string, orig *PluginConf, prevResult types.
} }
return conf, newBytes, nil return conf, newBytes, nil
} }
var _ = Describe("bandwidth test", func() { var _ = Describe("bandwidth test", func() {
@ -221,7 +219,6 @@ var _ = Describe("bandwidth test", func() {
Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1))) Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1)))
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
It(fmt.Sprintf("[%s] does not apply ingress when disabled", ver), func() { It(fmt.Sprintf("[%s] does not apply ingress when disabled", ver), func() {
@ -289,7 +286,6 @@ var _ = Describe("bandwidth test", func() {
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
It(fmt.Sprintf("[%s] does not apply egress when disabled", ver), func() { It(fmt.Sprintf("[%s] does not apply egress when disabled", ver), func() {
@ -359,7 +355,6 @@ var _ = Describe("bandwidth test", func() {
Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(35))) Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(35)))
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
It(fmt.Sprintf("[%s] fails an invalid ingress config", ver), func() { It(fmt.Sprintf("[%s] fails an invalid ingress config", ver), func() {
@ -507,7 +502,6 @@ var _ = Describe("bandwidth test", func() {
Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1))) Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1)))
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
It(fmt.Sprintf("[%s] should apply static config when both static config and runtime config exist", ver), func() { It(fmt.Sprintf("[%s] should apply static config when both static config and runtime config exist", ver), func() {
@ -620,7 +614,6 @@ var _ = Describe("bandwidth test", func() {
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
}) })
@ -730,7 +723,6 @@ var _ = Describe("bandwidth test", func() {
Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1))) Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1)))
return nil return nil
})).To(Succeed()) })).To(Succeed())
}) })
It(fmt.Sprintf("[%s] should fail when container interface has no veth peer", ver), func() { It(fmt.Sprintf("[%s] should fail when container interface has no veth peer", ver), func() {
@ -1035,7 +1027,7 @@ var _ = Describe("bandwidth test", func() {
result, err := types100.GetResult(containerWithTbfRes) result, err := types100.GetResult(containerWithTbfRes)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
makeTcpClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithTbf, packetInBytes) makeTCPClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithTbf, packetInBytes)
}) })
}) })
@ -1044,7 +1036,7 @@ var _ = Describe("bandwidth test", func() {
result, err := types100.GetResult(containerWithoutTbfRes) result, err := types100.GetResult(containerWithoutTbfRes)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
makeTcpClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithoutTbf, packetInBytes) makeTCPClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithoutTbf, packetInBytes)
}) })
}) })

View File

@ -24,14 +24,13 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
"github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ns"
) )
func TestTBF(t *testing.T) { func TestTBF(t *testing.T) {
@ -87,7 +86,7 @@ func startEchoServerInNamespace(netNS ns.NetNS) (int, *gexec.Session, error) {
return port, session, nil return port, session, nil
} }
func makeTcpClientInNS(netns string, address string, port int, numBytes int) { func makeTCPClientInNS(netns string, address string, port int, numBytes int) {
payload := bytes.Repeat([]byte{'a'}, numBytes) payload := bytes.Repeat([]byte{'a'}, numBytes)
message := string(payload) message := string(payload)

View File

@ -19,9 +19,9 @@ import (
"net" "net"
"syscall" "syscall"
"github.com/containernetworking/plugins/pkg/ip"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/ip"
) )
const latencyInMillis = 25 const latencyInMillis = 25
@ -34,7 +34,6 @@ func CreateIfb(ifbDeviceName string, mtu int) error {
MTU: mtu, MTU: mtu,
}, },
}) })
if err != nil { if err != nil {
return fmt.Errorf("adding link: %s", err) return fmt.Errorf("adding link: %s", err)
} }
@ -147,10 +146,6 @@ func createTBF(rateInBits, burstInBits uint64, linkIndex int) error {
return nil return nil
} }
func tick2Time(tick uint32) uint32 {
return uint32(float64(tick) / float64(netlink.TickInUsec()))
}
func time2Tick(time uint32) uint32 { func time2Tick(time uint32) uint32 {
return uint32(float64(time) * float64(netlink.TickInUsec())) return uint32(float64(time) * float64(netlink.TickInUsec()))
} }

View File

@ -25,15 +25,16 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ip"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/utils" "github.com/containernetworking/plugins/pkg/utils"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )
const maxIfbDeviceLength = 15 const (
const ifbDevicePrefix = "bwp" maxIfbDeviceLength = 15
ifbDevicePrefix = "bwp"
)
// BandwidthEntry corresponds to a single entry in the bandwidth argument, // BandwidthEntry corresponds to a single entry in the bandwidth argument,
// see CONVENTIONS.md // see CONVENTIONS.md
@ -92,7 +93,6 @@ func parseConfig(stdin []byte) (*PluginConf, error) {
} }
return &conf, nil return &conf, nil
} }
func getBandwidth(conf *PluginConf) *BandwidthEntry { func getBandwidth(conf *PluginConf) *BandwidthEntry {
@ -104,8 +104,6 @@ func getBandwidth(conf *PluginConf) *BandwidthEntry {
func validateRateAndBurst(rate, burst uint64) error { func validateRateAndBurst(rate, burst uint64) error {
switch { switch {
case burst < 0 || rate < 0:
return fmt.Errorf("rate and burst must be a positive integer")
case burst == 0 && rate != 0: case burst == 0 && rate != 0:
return fmt.Errorf("if rate is set, burst must also be set") return fmt.Errorf("if rate is set, burst must also be set")
case rate == 0 && burst != 0: case rate == 0 && burst != 0:
@ -117,8 +115,8 @@ func validateRateAndBurst(rate, burst uint64) error {
return nil return nil
} }
func getIfbDeviceName(networkName string, containerId string) string { func getIfbDeviceName(networkName string, containerID string) string {
return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerId) return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerID)
} }
func getMTU(deviceName string) (int, error) { func getMTU(deviceName string) (int, error) {

View File

@ -26,7 +26,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )

View File

@ -22,16 +22,15 @@ import (
"sync" "sync"
"syscall" "syscall"
"github.com/godbus/dbus/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/invoke" "github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/godbus/dbus/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
const ifname = "eth0" const ifname = "eth0"

View File

@ -22,12 +22,13 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/containernetworking/cni/libcni" "github.com/containernetworking/cni/libcni"
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
// The integration tests expect the "firewall" binary to be present in $PATH. // The integration tests expect the "firewall" binary to be present in $PATH.

View File

@ -19,6 +19,11 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/coreos/go-iptables/iptables"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/vishvananda/netlink"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/040" "github.com/containernetworking/cni/pkg/types/040"
@ -26,13 +31,6 @@ import (
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils" "github.com/containernetworking/plugins/pkg/testutils"
"github.com/vishvananda/netlink"
"github.com/coreos/go-iptables/iptables"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
func findChains(chains []string) (bool, bool) { func findChains(chains []string) (bool, bool) {

View File

@ -15,10 +15,10 @@
package main package main
import ( import (
"testing"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"testing"
) )
func TestFirewall(t *testing.T) { func TestFirewall(t *testing.T) {

View File

@ -18,8 +18,9 @@ import (
"fmt" "fmt"
"strings" "strings"
current "github.com/containernetworking/cni/pkg/types/100"
"github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5"
current "github.com/containernetworking/cni/pkg/types/100"
) )
const ( const (

View File

@ -19,9 +19,10 @@ package main
import ( import (
"fmt" "fmt"
"github.com/coreos/go-iptables/iptables"
types100 "github.com/containernetworking/cni/pkg/types/100" types100 "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/utils" "github.com/containernetworking/plugins/pkg/utils"
"github.com/coreos/go-iptables/iptables"
) )
func setupIngressPolicy(conf *FirewallNetConf, prevResult *types100.Result) error { func setupIngressPolicy(conf *FirewallNetConf, prevResult *types100.Result) error {
@ -166,7 +167,7 @@ func isolationStage2BridgeRule(bridgeName string) []string {
} }
func withDefaultComment(rule []string) []string { func withDefaultComment(rule []string) []string {
defaultComment := fmt.Sprintf("CNI firewall plugin rules (ingressPolicy: same-bridge)") defaultComment := "CNI firewall plugin rules (ingressPolicy: same-bridge)"
return withComment(rule, defaultComment) return withComment(rule, defaultComment)
} }

View File

@ -21,9 +21,10 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/coreos/go-iptables/iptables"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/utils" "github.com/containernetworking/plugins/pkg/utils"
"github.com/coreos/go-iptables/iptables"
) )
func getPrivChainRules(ip string) [][]string { func getPrivChainRules(ip string) [][]string {
@ -142,7 +143,7 @@ func (ib *iptablesBackend) checkRules(conf *FirewallNetConf, result *current.Res
} }
} }
if len(rules) <= 0 { if len(rules) == 0 {
return nil return nil
} }
@ -211,7 +212,6 @@ type iptablesBackend struct {
protos map[iptables.Protocol]*iptables.IPTables protos map[iptables.Protocol]*iptables.IPTables
privChainName string privChainName string
adminChainName string adminChainName string
ifName string
} }
// iptablesBackend implements the FirewallBackend interface // iptablesBackend implements the FirewallBackend interface

View File

@ -18,9 +18,10 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/containernetworking/plugins/pkg/utils"
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
"github.com/mattn/go-shellwords" "github.com/mattn/go-shellwords"
"github.com/containernetworking/plugins/pkg/utils"
) )
type chain struct { type chain struct {
@ -36,7 +37,6 @@ type chain struct {
// setup idempotently creates the chain. It will not error if the chain exists. // setup idempotently creates the chain. It will not error if the chain exists.
func (c *chain) setup(ipt *iptables.IPTables) error { func (c *chain) setup(ipt *iptables.IPTables) error {
err := utils.EnsureChain(ipt, c.table, c.name) err := utils.EnsureChain(ipt, c.table, c.name)
if err != nil { if err != nil {
return err return err
@ -103,7 +103,6 @@ func (c *chain) teardown(ipt *iptables.IPTables) error {
// check the chain. // check the chain.
func (c *chain) check(ipt *iptables.IPTables) error { func (c *chain) check(ipt *iptables.IPTables) error {
exists, err := utils.ChainExists(ipt, c.table, c.name) exists, err := utils.ChainExists(ipt, c.table, c.name)
if err != nil { if err != nil {
return err return err

View File

@ -20,11 +20,12 @@ import (
"runtime" "runtime"
"sync" "sync"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
const TABLE = "filter" // We'll monkey around here const TABLE = "filter" // We'll monkey around here
@ -37,7 +38,6 @@ var _ = Describe("chain tests", func() {
var cleanup func() var cleanup func()
beforeEach := func() { beforeEach := func() {
// Save a reference to the original namespace, // Save a reference to the original namespace,
// Add a new NS // Add a new NS
currNs, err := ns.GetCurrentNS() currNs, err := ns.GetCurrentNS()
@ -83,7 +83,6 @@ var _ = Describe("chain tests", func() {
ipt.DeleteChain(TABLE, tlChainName) ipt.DeleteChain(TABLE, tlChainName)
currNs.Set() currNs.Set()
} }
} }
It("creates and destroys a chain", func() { It("creates and destroys a chain", func() {
@ -169,7 +168,6 @@ var _ = Describe("chain tests", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(len(rules)).To(Equal(3)) Expect(len(rules)).To(Equal(3))
}) })
It("deletes chains idempotently", func() { It("deletes chains idempotently", func() {
@ -233,6 +231,5 @@ var _ = Describe("chain tests", func() {
Fail("Chain was not deleted") Fail("Chain was not deleted")
} }
} }
}) })
}) })

View File

@ -31,12 +31,12 @@ import (
"log" "log"
"net" "net"
"golang.org/x/sys/unix"
"github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"golang.org/x/sys/unix"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )

View File

@ -21,10 +21,11 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/containernetworking/plugins/pkg/utils"
"github.com/containernetworking/plugins/pkg/utils/sysctl"
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/plugins/pkg/utils"
"github.com/containernetworking/plugins/pkg/utils/sysctl"
) )
// This creates the chains to be added to iptables. The basic structure is // This creates the chains to be added to iptables. The basic structure is
@ -292,7 +293,7 @@ func fillDnatRules(c *chain, config *PortMapConf, containerNet net.IPNet) {
copy(dnatRule, ruleBase) copy(dnatRule, ruleBase)
dnatRule = append(dnatRule, dnatRule = append(dnatRule,
"-j", "DNAT", "-j", "DNAT",
"--to-destination", fmtIpPort(containerNet.IP, entry.ContainerPort), "--to-destination", fmtIPPort(containerNet.IP, entry.ContainerPort),
) )
c.rules = append(c.rules, dnatRule) c.rules = append(c.rules, dnatRule)
} }

View File

@ -24,15 +24,16 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"github.com/containernetworking/cni/libcni"
"github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
"github.com/coreos/go-iptables/iptables" "github.com/coreos/go-iptables/iptables"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec" "github.com/onsi/gomega/gexec"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/containernetworking/cni/libcni"
"github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/containernetworking/plugins/pkg/testutils"
) )
func makeConfig(ver string) *libcni.NetworkConfigList { func makeConfig(ver string) *libcni.NetworkConfigList {

View File

@ -21,15 +21,14 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"testing"
"github.com/containernetworking/plugins/pkg/ns"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec" "github.com/onsi/gomega/gexec"
"testing" "github.com/containernetworking/plugins/pkg/ns"
) )
func TestPortmap(t *testing.T) { func TestPortmap(t *testing.T) {

View File

@ -17,10 +17,10 @@ package main
import ( import (
"fmt" "fmt"
"github.com/containernetworking/cni/pkg/types"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/containernetworking/cni/pkg/types"
) )
var _ = Describe("portmapping configuration", func() { var _ = Describe("portmapping configuration", func() {
@ -84,8 +84,10 @@ var _ = Describe("portmapping configuration", func() {
Expect(c.Name).To(Equal("test")) Expect(c.Name).To(Equal("test"))
n, err := types.ParseCIDR("10.0.0.2/24") n, err := types.ParseCIDR("10.0.0.2/24")
Expect(err).NotTo(HaveOccurred())
Expect(c.ContIPv4).To(Equal(*n)) Expect(c.ContIPv4).To(Equal(*n))
n, err = types.ParseCIDR("2001:db8:1::2/64") n, err = types.ParseCIDR("2001:db8:1::2/64")
Expect(err).NotTo(HaveOccurred())
Expect(c.ContIPv6).To(Equal(*n)) Expect(c.ContIPv6).To(Equal(*n))
}) })
@ -199,21 +201,26 @@ var _ = Describe("portmapping configuration", func() {
})) }))
n, err := types.ParseCIDR("10.0.0.2/24") n, err := types.ParseCIDR("10.0.0.2/24")
Expect(err).NotTo(HaveOccurred())
fillDnatRules(&ch, conf, *n) fillDnatRules(&ch, conf, *n)
Expect(ch.entryRules).To(Equal([][]string{ Expect(ch.entryRules).To(Equal([][]string{
{"-m", "comment", "--comment", {
"-m", "comment", "--comment",
fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID), fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID),
"-m", "multiport", "-m", "multiport",
"-p", "tcp", "-p", "tcp",
"--destination-ports", "8080,8081,8083,8084,8085,8086", "--destination-ports", "8080,8081,8083,8084,8085,8086",
"a", "b"}, "a", "b",
{"-m", "comment", "--comment", },
{
"-m", "comment", "--comment",
fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID), fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID),
"-m", "multiport", "-m", "multiport",
"-p", "udp", "-p", "udp",
"--destination-ports", "8080,8082", "--destination-ports", "8080,8082",
"a", "b"}, "a", "b",
},
})) }))
Expect(ch.rules).To(Equal([][]string{ Expect(ch.rules).To(Equal([][]string{
@ -245,6 +252,7 @@ var _ = Describe("portmapping configuration", func() {
ch.entryRules = nil ch.entryRules = nil
n, err = types.ParseCIDR("2001:db8::2/64") n, err = types.ParseCIDR("2001:db8::2/64")
Expect(err).NotTo(HaveOccurred())
fillDnatRules(&ch, conf, *n) fillDnatRules(&ch, conf, *n)
Expect(ch.rules).To(Equal([][]string{ Expect(ch.rules).To(Equal([][]string{
@ -273,6 +281,7 @@ var _ = Describe("portmapping configuration", func() {
conf.SNAT = &fvar conf.SNAT = &fvar
n, err = types.ParseCIDR("10.0.0.2/24") n, err = types.ParseCIDR("10.0.0.2/24")
Expect(err).NotTo(HaveOccurred())
fillDnatRules(&ch, conf, *n) fillDnatRules(&ch, conf, *n)
Expect(ch.rules).To(Equal([][]string{ Expect(ch.rules).To(Equal([][]string{
{"-p", "tcp", "--dport", "8080", "-j", "DNAT", "--to-destination", "10.0.0.2:80"}, {"-p", "tcp", "--dport", "8080", "-j", "DNAT", "--to-destination", "10.0.0.2:80"},
@ -312,6 +321,7 @@ var _ = Describe("portmapping configuration", func() {
ch = genDnatChain(conf.Name, containerID) ch = genDnatChain(conf.Name, containerID)
n, err := types.ParseCIDR("10.0.0.2/24") n, err := types.ParseCIDR("10.0.0.2/24")
Expect(err).NotTo(HaveOccurred())
fillDnatRules(&ch, conf, *n) fillDnatRules(&ch, conf, *n)
Expect(ch.rules).To(Equal([][]string{ Expect(ch.rules).To(Equal([][]string{
{"-p", "tcp", "--dport", "8080", "-s", "10.0.0.2/24", "-j", "PLZ-SET-MARK"}, {"-p", "tcp", "--dport", "8080", "-s", "10.0.0.2/24", "-j", "PLZ-SET-MARK"},

View File

@ -25,20 +25,13 @@ import (
// fmtIpPort correctly formats ip:port literals for iptables and ip6tables - // fmtIpPort correctly formats ip:port literals for iptables and ip6tables -
// need to wrap v6 literals in a [] // need to wrap v6 literals in a []
func fmtIpPort(ip net.IP, port int) string { func fmtIPPort(ip net.IP, port int) string {
if ip.To4() == nil { if ip.To4() == nil {
return fmt.Sprintf("[%s]:%d", ip.String(), port) return fmt.Sprintf("[%s]:%d", ip.String(), port)
} }
return fmt.Sprintf("%s:%d", ip.String(), port) return fmt.Sprintf("%s:%d", ip.String(), port)
} }
func localhostIP(isV6 bool) string {
if isV6 {
return "::1"
}
return "127.0.0.1"
}
// getRoutableHostIF will try and determine which interface routes the container's // getRoutableHostIF will try and determine which interface routes the container's
// traffic. This is the one on which we disable martian filtering. // traffic. This is the one on which we disable martian filtering.
func getRoutableHostIF(containerIP net.IP) string { func getRoutableHostIF(containerIP net.IP) string {

View File

@ -28,7 +28,6 @@ import (
"github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100" current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion" bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
) )
@ -109,7 +108,6 @@ func parseConfig(stdin []byte) (*PluginConf, error) {
// getIPCfgs finds the IPs on the supplied interface, returning as IPConfig structures // getIPCfgs finds the IPs on the supplied interface, returning as IPConfig structures
func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, error) { func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, error) {
if len(prevResult.IPs) == 0 { if len(prevResult.IPs) == 0 {
// No IP addresses; that makes no sense. Pack it in. // No IP addresses; that makes no sense. Pack it in.
return nil, fmt.Errorf("No IP addresses supplied on interface: %s", iface) return nil, fmt.Errorf("No IP addresses supplied on interface: %s", iface)
@ -276,7 +274,8 @@ func doRoutes(ipCfgs []*current.IPConfig, origRoutes []*types.Route, iface strin
Dst: &dest, Dst: &dest,
Gw: ipCfg.Gateway, Gw: ipCfg.Gateway,
Table: table, Table: table,
LinkIndex: linkIndex} LinkIndex: linkIndex,
}
err = netlink.RouteAdd(&route) err = netlink.RouteAdd(&route)
if err != nil { if err != nil {
@ -350,7 +349,6 @@ func cmdDel(args *skel.CmdArgs) error {
// Tidy up the rules for the deleted interface // Tidy up the rules for the deleted interface
func tidyRules(iface string) error { func tidyRules(iface string) error {
// We keep on going on rule deletion error, but return the last failure. // We keep on going on rule deletion error, but return the last failure.
var errReturn error var errReturn error

Some files were not shown because too many files have changed in this diff Show More