diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index ab9d5d9c..2eb30815 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -20,6 +20,9 @@ jobs: - uses: ibiqlik/action-yamllint@v3 with: format: auto + - uses: golangci/golangci-lint-action@v3 + with: + args: -v build: name: Build all linux architectures needs: lint diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..5ba27b11 --- /dev/null +++ b/.golangci.yml @@ -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 diff --git a/integration/integration_linux_test.go b/integration/integration_linux_test.go index 98a967af..fc673384 100644 --- a/integration/integration_linux_test.go +++ b/integration/integration_linux_test.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,15 +14,14 @@ package integration_test import ( + "bytes" "fmt" + "io" "math/rand" + "net" "os" "os/exec" "path/filepath" - - "bytes" - "io" - "net" "regexp" "strconv" "strings" @@ -148,8 +147,8 @@ var _ = Describe("Basic PTP using cnitool", func() { basicBridgeEnv.runInNS(hostNS, cnitoolBin, "del", "network-chain-test", contNS2.LongName()) }) - Measure("limits traffic only on the restricted bandwith veth device", func(b Benchmarker) { - ipRegexp := regexp.MustCompile("10\\.1[12]\\.2\\.\\d{1,3}") + Measure("limits traffic only on the restricted bandwidth veth device", func(b Benchmarker) { + ipRegexp := regexp.MustCompile(`10\.1[12]\.2\.\d{1,3}`) By(fmt.Sprintf("adding %s to %s\n\n", "chained-bridge-bandwidth", contNS1.ShortName())) 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)) 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)) 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)) @@ -224,7 +223,7 @@ func (n Namespace) Del() { (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) message := string(payload) diff --git a/integration/integration_suite_test.go b/integration/integration_suite_test.go index 595915e7..48e7a0b5 100644 --- a/integration/integration_suite_test.go +++ b/integration/integration_suite_test.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/pkg/ip/ip.go b/pkg/ip/ip.go index 4469e1b5..c5a34fa3 100644 --- a/pkg/ip/ip.go +++ b/pkg/ip/ip.go @@ -47,13 +47,12 @@ func ParseIP(s string) *IP { return nil } return newIP(ip, ipNet.Mask) - } else { - ip := net.ParseIP(s) - if ip == nil { - return nil - } - return newIP(ip, nil) } + ip := net.ParseIP(s) + if ip == nil { + return nil + } + return newIP(ip, nil) } // ToIP will return a net.IP in standard form from this IP. diff --git a/pkg/ip/ip_suite_test.go b/pkg/ip/ip_suite_test.go index da97ba9a..53177c4c 100644 --- a/pkg/ip/ip_suite_test.go +++ b/pkg/ip/ip_suite_test.go @@ -15,10 +15,10 @@ package ip_test import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestIp(t *testing.T) { diff --git a/pkg/ip/ip_test.go b/pkg/ip/ip_test.go index 6e8545ab..0ec74ff9 100644 --- a/pkg/ip/ip_test.go +++ b/pkg/ip/ip_test.go @@ -205,7 +205,6 @@ var _ = Describe("IP Operations", func() { Expect(err).NotTo(HaveOccurred()) Expect(ip).To(Equal(test.expected)) } - }) It("empty text", func() { diff --git a/pkg/ip/ipforward_linux.go b/pkg/ip/ipforward_linux.go index 0e8b6b69..7c901141 100644 --- a/pkg/ip/ipforward_linux.go +++ b/pkg/ip/ipforward_linux.go @@ -58,5 +58,5 @@ func echo1(f string) error { return nil } } - return os.WriteFile(f, []byte("1"), 0644) + return os.WriteFile(f, []byte("1"), 0o644) } diff --git a/pkg/ip/ipmasq_linux.go b/pkg/ip/ipmasq_linux.go index cc640a60..aa59a8db 100644 --- a/pkg/ip/ipmasq_linux.go +++ b/pkg/ip/ipmasq_linux.go @@ -104,7 +104,6 @@ func TeardownIPMasq(ipn *net.IPNet, chain string, comment string) error { err = ipt.ClearChain("nat", chain) if err != nil && !isNotExist(err) { return err - } err = ipt.DeleteChain("nat", chain) diff --git a/pkg/ip/link_linux.go b/pkg/ip/link_linux.go index 91f931b5..4fe83fda 100644 --- a/pkg/ip/link_linux.go +++ b/pkg/ip/link_linux.go @@ -28,9 +28,7 @@ import ( "github.com/containernetworking/plugins/pkg/utils/sysctl" ) -var ( - ErrLinkNotFound = errors.New("link not found") -) +var ErrLinkNotFound = errors.New("link not found") // 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) { @@ -69,38 +67,37 @@ func peerExists(name string) bool { 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++ { if vethPeerName != "" { peerName = vethPeerName } else { peerName, err = RandomVethName() if err != nil { - return + return peerName, nil, err } } veth, err = makeVethPair(name, peerName, mtu, mac, hostNS) switch { case err == nil: - return + return peerName, veth, err case os.IsExist(err): if peerExists(peerName) && vethPeerName == "" { continue } - err = fmt.Errorf("container veth name provided (%v) already exists", name) - return - + return peerName, veth, fmt.Errorf("container veth name provided (%v) already exists", name) default: - err = fmt.Errorf("failed to make veth pair: %v", err) - return + return peerName, veth, fmt.Errorf("failed to make veth pair: %v", err) } } // should really never be hit - err = fmt.Errorf("failed to find a unique veth name") - return + return peerName, nil, fmt.Errorf("failed to find a unique veth name") } // RandomVethName returns string "veth" with random prefix (hashed from entropy) diff --git a/pkg/ip/link_linux_test.go b/pkg/ip/link_linux_test.go index d10ff240..67976a99 100644 --- a/pkg/ip/link_linux_test.go +++ b/pkg/ip/link_linux_test.go @@ -22,20 +22,13 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/vishvananda/netlink" "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ns" "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() { const ( ifaceFormatString string = "i%d" @@ -64,7 +57,7 @@ var _ = Describe("Link", func() { Expect(err).NotTo(HaveOccurred()) fakeBytes := make([]byte, 20) - //to be reset in AfterEach block + // to be reset in AfterEach block rand.Reader = bytes.NewReader(fakeBytes) _ = containerNetNS.Do(func(ns.NetNS) error { @@ -181,7 +174,7 @@ var _ = Describe("Link", func() { Context("when there is no name available for the host-side", func() { BeforeEach(func() { - //adding different interface to container ns + // adding different interface to container ns containerVethName += "0" }) It("returns useful error", func() { @@ -197,7 +190,7 @@ var _ = Describe("Link", func() { Context("when there is no name conflict for the host or container interfaces", func() { BeforeEach(func() { - //adding different interface to container and host ns + // adding different interface to container and host ns containerVethName += "0" rand.Reader = originalRandReader }) @@ -211,7 +204,7 @@ var _ = Describe("Link", func() { return nil }) - //verify veths are in different namespaces + // verify veths are in different namespaces _ = containerNetNS.Do(func(ns.NetNS) error { defer GinkgoRecover() diff --git a/pkg/ip/utils_linux.go b/pkg/ip/utils_linux.go index 943117e1..567cd885 100644 --- a/pkg/ip/utils_linux.go +++ b/pkg/ip/utils_linux.go @@ -21,13 +21,13 @@ import ( "fmt" "net" + "github.com/vishvananda/netlink" + "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" - "github.com/vishvananda/netlink" ) func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig) error { - // Ensure ips for _, ips := range resultIPs { ourAddr := netlink.Addr{IPNet: &ips.Address} @@ -49,12 +49,15 @@ func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig) break } } - if match == false { + if !match { return fmt.Errorf("Failed to match addr %v on interface %v", ourAddr, ifName) } // Convert the host/prefixlen to just prefix for route lookup. _, ourPrefix, err := net.ParseCIDR(ourAddr.String()) + if err != nil { + return err + } findGwy := &netlink.Route{Dst: ourPrefix} routeFilter := netlink.RT_FILTER_DST @@ -77,7 +80,6 @@ func ValidateExpectedInterfaceIPs(ifName string, resultIPs []*current.IPConfig) } func ValidateExpectedRoute(resultRoutes []*types.Route) error { - // Ensure that each static route in prevResults is found in the routing table for _, route := range resultRoutes { find := &netlink.Route{Dst: &route.Dst, Gw: route.GW} diff --git a/pkg/ipam/ipam.go b/pkg/ipam/ipam.go index 4463035d..e39d36b0 100644 --- a/pkg/ipam/ipam.go +++ b/pkg/ipam/ipam.go @@ -16,6 +16,7 @@ package ipam import ( "context" + "github.com/containernetworking/cni/pkg/invoke" "github.com/containernetworking/cni/pkg/types" ) diff --git a/pkg/ipam/ipam_linux.go b/pkg/ipam/ipam_linux.go index 60694cc9..6c2bfe72 100644 --- a/pkg/ipam/ipam_linux.go +++ b/pkg/ipam/ipam_linux.go @@ -19,11 +19,11 @@ import ( "net" "os" + "github.com/vishvananda/netlink" + current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/utils/sysctl" - - "github.com/vishvananda/netlink" ) const ( @@ -44,7 +44,7 @@ func ConfigureIface(ifName string, res *current.Result) error { } var v4gw, v6gw net.IP - var has_enabled_ipv6 bool = false + hasEnabledIpv6 := false for _, ipc := range res.IPs { if ipc.Interface == nil { 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 // 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 // being configured 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) } } - has_enabled_ipv6 = true + hasEnabledIpv6 = true } addr := &netlink.Addr{IPNet: &ipc.Address, Label: ""} diff --git a/pkg/ipam/ipam_linux_test.go b/pkg/ipam/ipam_linux_test.go index d6a3d839..2ead7d9a 100644 --- a/pkg/ipam/ipam_linux_test.go +++ b/pkg/ipam/ipam_linux_test.go @@ -18,15 +18,14 @@ import ( "net" "syscall" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/vishvananda/netlink" + "github.com/containernetworking/cni/pkg/types" current "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/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) const LINK_NAME = "eth0" diff --git a/pkg/ipam/ipam_suite_test.go b/pkg/ipam/ipam_suite_test.go index ce27653b..b4370337 100644 --- a/pkg/ipam/ipam_suite_test.go +++ b/pkg/ipam/ipam_suite_test.go @@ -15,10 +15,10 @@ package ipam_test import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestIpam(t *testing.T) { diff --git a/pkg/link/spoofcheck.go b/pkg/link/spoofcheck.go index 361af965..7ff4ad3c 100644 --- a/pkg/link/spoofcheck.go +++ b/pkg/link/spoofcheck.go @@ -41,11 +41,11 @@ type SpoofChecker struct { type defaultNftConfigurer struct{} -func (_ defaultNftConfigurer) Apply(cfg *nft.Config) error { +func (dnc defaultNftConfigurer) Apply(cfg *nft.Config) error { return nft.ApplyConfig(cfg) } -func (_ defaultNftConfigurer) Read() (*nft.Config, error) { +func (dnc defaultNftConfigurer) Read() (*nft.Config, error) { 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 return &schema.Chain{ 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" return &schema.Chain{ Family: schema.FamilyBridge, diff --git a/pkg/link/spoofcheck_test.go b/pkg/link/spoofcheck_test.go index ff9ebdaf..a7ed7ee5 100644 --- a/pkg/link/spoofcheck_test.go +++ b/pkg/link/spoofcheck_test.go @@ -16,8 +16,8 @@ package link_test import ( "fmt" - "github.com/networkplumbing/go-nft/nft" + "github.com/networkplumbing/go-nft/nft" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -116,10 +116,10 @@ var _ = Describe("spoofcheck", func() { }) func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub) { - deleteRegularChainRulesJsonConfig, err := action.applyConfig[1].ToJSON() + deleteRegularChainRulesJSONConfig, err := action.applyConfig[1].ToJSON() ExpectWithOffset(1, err).NotTo(HaveOccurred()) - expectedDeleteRegularChainRulesJsonConfig := ` + expectedDeleteRegularChainRulesJSONConfig := ` {"nftables": [ {"delete": {"chain": { "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) { - deleteBaseChainRuleJsonConfig, err := action.applyConfig[0].ToJSON() + deleteBaseChainRuleJSONConfig, err := action.applyConfig[0].ToJSON() Expect(err).NotTo(HaveOccurred()) - expectedDeleteIfaceMatchRuleJsonConfig := ` + expectedDeleteIfaceMatchRuleJSONConfig := ` {"nftables": [ {"delete": {"rule": { "family": "bridge", @@ -157,7 +157,7 @@ func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub) "comment": "macspoofchk-container99-net1" }}} ]}` - Expect(string(deleteBaseChainRuleJsonConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJsonConfig)) + Expect(string(deleteBaseChainRuleJSONConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJSONConfig)) } func rowConfigWithRulesOnly() string { diff --git a/pkg/ns/ns_linux_test.go b/pkg/ns/ns_linux_test.go index 82d07b4b..82f56eda 100644 --- a/pkg/ns/ns_linux_test.go +++ b/pkg/ns/ns_linux_test.go @@ -21,11 +21,12 @@ import ( "path/filepath" "sync" - "github.com/containernetworking/plugins/pkg/ns" - "github.com/containernetworking/plugins/pkg/testutils" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "golang.org/x/sys/unix" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" ) func getInodeCurNetNS() (uint64, error) { diff --git a/pkg/ns/ns_suite_test.go b/pkg/ns/ns_suite_test.go index f5ea1d00..ecc5e34e 100644 --- a/pkg/ns/ns_suite_test.go +++ b/pkg/ns/ns_suite_test.go @@ -17,11 +17,10 @@ package ns_test import ( "math/rand" "runtime" + "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestNs(t *testing.T) { diff --git a/pkg/testutils/echo/init_test.go b/pkg/testutils/echo/init_test.go index 8160dc35..ca8e464d 100644 --- a/pkg/testutils/echo/init_test.go +++ b/pkg/testutils/echo/init_test.go @@ -1,10 +1,10 @@ package main_test import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestEchosvr(t *testing.T) { diff --git a/pkg/testutils/echo/server/main.go b/pkg/testutils/echo/server/main.go index 2db49847..2fe4f563 100644 --- a/pkg/testutils/echo/server/main.go +++ b/pkg/testutils/echo/server/main.go @@ -1,9 +1,10 @@ // Echosvr is a simple TCP echo server // // It prints its listen address on stdout -// 127.0.0.1:xxxxx -// A test should wait for this line, parse it -// and may then attempt to connect. +// +// 127.0.0.1:xxxxx +// A test should wait for this line, parse it +// and may then attempt to connect. package main import ( @@ -43,11 +44,13 @@ func main() { // Start UDP server addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%s", port)) 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) if err != nil { - log.Fatalf("Error from ListenUDP(): %s", err) + log.Printf("Error from ListenUDP(): %s", err) + return } defer sock.Close() @@ -55,10 +58,11 @@ func main() { for { n, addr, err := sock.ReadFrom(buffer) 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)) - n, err = sock.WriteTo(buffer[0:n], addr) + _, err = sock.WriteTo(buffer[0:n], addr) if err != nil { return } diff --git a/pkg/testutils/netns_linux.go b/pkg/testutils/netns_linux.go index b9683a3a..b467eb3c 100644 --- a/pkg/testutils/netns_linux.go +++ b/pkg/testutils/netns_linux.go @@ -24,8 +24,9 @@ import ( "sync" "syscall" - "github.com/containernetworking/plugins/pkg/ns" "golang.org/x/sys/unix" + + "github.com/containernetworking/plugins/pkg/ns" ) func getNsRunDir() string { @@ -49,7 +50,6 @@ func getNsRunDir() string { // Creates a new persistent (bind-mounted) network namespace and returns an object // representing that namespace, without switching to it. func NewNS() (ns.NetNS, error) { - nsRunDir := getNsRunDir() b := make([]byte, 16) @@ -61,7 +61,7 @@ func NewNS() (ns.NetNS, error) { // Create the directory for mounting network namespaces // This needs to be a shared mountpoint in case it is mounted in to // other namespaces (containers) - err = os.MkdirAll(nsRunDir, 0755) + err = os.MkdirAll(nsRunDir, 0o755) if err != nil { return nil, err } diff --git a/pkg/utils/iptables.go b/pkg/utils/iptables.go index d0172626..6aec8bca 100644 --- a/pkg/utils/iptables.go +++ b/pkg/utils/iptables.go @@ -133,7 +133,6 @@ func InsertUnique(ipt *iptables.IPTables, table, chain string, prepend bool, rul if prepend { return ipt.Insert(table, chain, 1, rule...) - } else { - return ipt.Append(table, chain, rule...) } + return ipt.Append(table, chain, rule...) } diff --git a/pkg/utils/iptables_test.go b/pkg/utils/iptables_test.go index fec5a813..103d3797 100644 --- a/pkg/utils/iptables_test.go +++ b/pkg/utils/iptables_test.go @@ -19,11 +19,12 @@ import ( "math/rand" "runtime" - "github.com/containernetworking/plugins/pkg/ns" - "github.com/containernetworking/plugins/pkg/testutils" "github.com/coreos/go-iptables/iptables" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" ) const TABLE = "filter" // We'll monkey around here @@ -34,7 +35,6 @@ var _ = Describe("chain tests", func() { var cleanup func() BeforeEach(func() { - // Save a reference to the original namespace, // Add a new NS currNs, err := ns.GetCurrentNS() @@ -60,7 +60,6 @@ var _ = Describe("chain tests", func() { ipt.DeleteChain(TABLE, testChain) currNs.Set() } - }) AfterEach(func() { @@ -93,5 +92,4 @@ var _ = Describe("chain tests", func() { Expect(err).NotTo(HaveOccurred()) }) }) - }) diff --git a/pkg/utils/sysctl/sysctl_linux.go b/pkg/utils/sysctl/sysctl_linux.go index 469e9be9..e700f19b 100644 --- a/pkg/utils/sysctl/sysctl_linux.go +++ b/pkg/utils/sysctl/sysctl_linux.go @@ -46,7 +46,7 @@ func getSysctl(name string) (string, error) { func setSysctl(name, value string) (string, error) { 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 } diff --git a/pkg/utils/sysctl/sysctl_linux_test.go b/pkg/utils/sysctl/sysctl_linux_test.go index 9450759d..917b1532 100644 --- a/pkg/utils/sysctl/sysctl_linux_test.go +++ b/pkg/utils/sysctl/sysctl_linux_test.go @@ -20,12 +20,13 @@ import ( "runtime" "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/gomega" "github.com/vishvananda/netlink" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" + "github.com/containernetworking/plugins/pkg/utils/sysctl" ) const ( @@ -38,7 +39,6 @@ var _ = Describe("Sysctl tests", func() { var cleanup func() beforeEach := func() { - // Save a reference to the original namespace, // Add a new NS currNs, err := ns.GetCurrentNS() @@ -66,7 +66,6 @@ var _ = Describe("Sysctl tests", func() { netlink.LinkDel(testIface) currNs.Set() } - } AfterEach(func() { @@ -76,7 +75,7 @@ var _ = Describe("Sysctl tests", func() { Describe("Sysctl", func() { It("reads keys with dot separators", func() { beforeEach() - sysctlIfaceName := strings.Replace(testIfaceName, ".", "/", -1) + sysctlIfaceName := strings.ReplaceAll(testIfaceName, ".", "/") sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName) _, err := sysctl.Sysctl(sysctlKey) @@ -97,7 +96,7 @@ var _ = Describe("Sysctl tests", func() { Describe("Sysctl", func() { It("writes keys with dot separators", func() { beforeEach() - sysctlIfaceName := strings.Replace(testIfaceName, ".", "/", -1) + sysctlIfaceName := strings.ReplaceAll(testIfaceName, ".", "/") sysctlKey := fmt.Sprintf(sysctlDotKeyTemplate, sysctlIfaceName) _, err := sysctl.Sysctl(sysctlKey, "1") @@ -114,5 +113,4 @@ var _ = Describe("Sysctl tests", func() { Expect(err).NotTo(HaveOccurred()) }) }) - }) diff --git a/pkg/utils/utils_suite_test.go b/pkg/utils/utils_suite_test.go index 775d61d2..b93723eb 100644 --- a/pkg/utils/utils_suite_test.go +++ b/pkg/utils/utils_suite_test.go @@ -15,10 +15,10 @@ package utils_test import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestUtils(t *testing.T) { diff --git a/pkg/utils/utils_test.go b/pkg/utils/utils_test.go index dda4d659..7868d927 100644 --- a/pkg/utils/utils_test.go +++ b/pkg/utils/utils_test.go @@ -161,5 +161,4 @@ var _ = Describe("Utils", func() { ) }) }) - }) diff --git a/plugins/ipam/dhcp/client.go b/plugins/ipam/dhcp/client.go index 911ae326..d39ad7fb 100644 --- a/plugins/ipam/dhcp/client.go +++ b/plugins/ipam/dhcp/client.go @@ -23,7 +23,7 @@ const ( MaxDHCPLen = 576 ) -//Send the Discovery Packet to the Broadcast Channel +// Send the Discovery Packet to the Broadcast Channel func DhcpSendDiscoverPacket(c *dhcp4client.Client, options dhcp4.Options) (dhcp4.Packet, error) { discoveryPacket := c.DiscoverPacket() @@ -35,7 +35,7 @@ func DhcpSendDiscoverPacket(c *dhcp4client.Client, options dhcp4.Options) (dhcp4 return discoveryPacket, c.SendPacket(discoveryPacket) } -//Send Request Based On the offer Received. +// Send Request Based On the offer Received. func DhcpSendRequest(c *dhcp4client.Client, options dhcp4.Options, offerPacket *dhcp4.Packet) (dhcp4.Packet, error) { requestPacket := c.RequestPacket(offerPacket) @@ -48,7 +48,7 @@ func DhcpSendRequest(c *dhcp4client.Client, options dhcp4.Options, offerPacket * return requestPacket, c.SendPacket(requestPacket) } -//Send Decline to the received acknowledgement. +// Send Decline to the received acknowledgement. func DhcpSendDecline(c *dhcp4client.Client, acknowledgementPacket *dhcp4.Packet, options dhcp4.Options) (dhcp4.Packet, error) { declinePacket := c.DeclinePacket(acknowledgementPacket) @@ -61,7 +61,7 @@ func DhcpSendDecline(c *dhcp4client.Client, acknowledgementPacket *dhcp4.Packet, return declinePacket, c.SendPacket(declinePacket) } -//Lets do a Full DHCP Request. +// Lets do a Full DHCP Request. func DhcpRequest(c *dhcp4client.Client, options dhcp4.Options) (bool, dhcp4.Packet, error) { discoveryPacket, err := DhcpSendDiscoverPacket(c, options) if err != nil { @@ -91,8 +91,8 @@ func DhcpRequest(c *dhcp4client.Client, options dhcp4.Options) (bool, dhcp4.Pack return true, acknowledgement, nil } -//Renew a lease backed on the Acknowledgement Packet. -//Returns Successful, The AcknoledgementPacket, Any Errors +// Renew a lease backed on the Acknowledgement Packet. +// Returns Successful, The AcknoledgementPacket, Any Errors func DhcpRenew(c *dhcp4client.Client, acknowledgement dhcp4.Packet, options dhcp4.Options) (bool, dhcp4.Packet, error) { renewRequest := c.RenewalRequestPacket(&acknowledgement) @@ -120,8 +120,8 @@ func DhcpRenew(c *dhcp4client.Client, acknowledgement dhcp4.Packet, options dhcp return true, newAcknowledgement, nil } -//Release a lease backed on the Acknowledgement Packet. -//Returns Any Errors +// Release a lease backed on the Acknowledgement Packet. +// Returns Any Errors func DhcpRelease(c *dhcp4client.Client, acknowledgement dhcp4.Packet, options dhcp4.Options) error { release := c.ReleasePacket(&acknowledgement) diff --git a/plugins/ipam/dhcp/daemon.go b/plugins/ipam/dhcp/daemon.go index 4949a8c6..087e8e9c 100644 --- a/plugins/ipam/dhcp/daemon.go +++ b/plugins/ipam/dhcp/daemon.go @@ -30,9 +30,10 @@ import ( "syscall" "time" + "github.com/coreos/go-systemd/v22/activation" + "github.com/containernetworking/cni/pkg/skel" current "github.com/containernetworking/cni/pkg/types/100" - "github.com/coreos/go-systemd/v22/activation" ) 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. -// 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 { 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. @@ -166,7 +167,7 @@ func getListener(socketPath string) (net.Listener, error) { switch { 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 net.Listen("unix", socketPath) @@ -195,7 +196,7 @@ func runDaemon( if !filepath.IsAbs(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) } } diff --git a/plugins/ipam/dhcp/dhcp2_test.go b/plugins/ipam/dhcp/dhcp2_test.go index a7efe6ac..d14ac789 100644 --- a/plugins/ipam/dhcp/dhcp2_test.go +++ b/plugins/ipam/dhcp/dhcp2_test.go @@ -22,15 +22,14 @@ import ( "sync" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/vishvananda/netlink" + "github.com/containernetworking/cni/pkg/skel" current "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/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("DHCP Multiple Lease Operations", func() { diff --git a/plugins/ipam/dhcp/dhcp_suite_test.go b/plugins/ipam/dhcp/dhcp_suite_test.go index ac2b27c4..3ba23303 100644 --- a/plugins/ipam/dhcp/dhcp_suite_test.go +++ b/plugins/ipam/dhcp/dhcp_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestDHCP(t *testing.T) { diff --git a/plugins/ipam/dhcp/dhcp_test.go b/plugins/ipam/dhcp/dhcp_test.go index 8913093c..5fa43ed0 100644 --- a/plugins/ipam/dhcp/dhcp_test.go +++ b/plugins/ipam/dhcp/dhcp_test.go @@ -25,20 +25,18 @@ import ( "sync" "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/dhcp4server" "github.com/d2g/dhcp4server/leasepool" "github.com/d2g/dhcp4server/leasepool/memorypool" - . "github.com/onsi/ginkgo/v2" . "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) { @@ -120,7 +118,7 @@ const ( ) var _ = BeforeSuite(func() { - err := os.MkdirAll(cniDirPrefix, 0700) + err := os.MkdirAll(cniDirPrefix, 0o700) Expect(err).NotTo(HaveOccurred()) }) diff --git a/plugins/ipam/dhcp/lease.go b/plugins/ipam/dhcp/lease.go index 5d7ec91a..d1fc40e4 100644 --- a/plugins/ipam/dhcp/lease.go +++ b/plugins/ipam/dhcp/lease.go @@ -34,13 +34,17 @@ import ( // RFC 2131 suggests using exponential backoff, starting with 4sec // and randomized to +/- 1sec -const resendDelay0 = 4 * time.Second -const resendDelayMax = 62 * time.Second +const ( + resendDelay0 = 4 * time.Second + resendDelayMax = 62 * time.Second +) // To speed up the retry for first few failures, we retry without // backoff for a few times -const resendFastDelay = 2 * time.Second -const resendFastMax = 4 +const ( + resendFastDelay = 2 * time.Second + resendFastMax = 4 +) const ( leaseStateBound = iota @@ -79,9 +83,12 @@ var requestOptionsDefault = map[dhcp4.OptionCode]bool{ dhcp4.OptionSubnetMask: true, } -func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptions []RequestOption) ( - optsRequesting map[dhcp4.OptionCode]bool, optsProviding map[dhcp4.OptionCode][]byte, err error) { - +func prepareOptions(cniArgs string, provideOptions []ProvideOption, requestOptions []RequestOption) ( + 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 cniArgsParsed := map[string]string{} for _, argPair := range strings.Split(cniArgs, ";") { @@ -94,23 +101,20 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio // parse providing options map var optParsed dhcp4.OptionCode optsProviding = make(map[dhcp4.OptionCode][]byte) - for _, opt := range ProvideOptions { + for _, opt := range provideOptions { optParsed, err = parseOptionName(string(opt.Option)) if err != nil { - err = fmt.Errorf("Can not parse option %q: %w", opt.Option, err) - return + return nil, nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err) } if len(opt.Value) > 0 { if len(opt.Value) > 255 { - err = fmt.Errorf("value too long for option %q: %q", opt.Option, opt.Value) - return + return nil, nil, fmt.Errorf("value too long for option %q: %q", opt.Option, opt.Value) } optsProviding[optParsed] = []byte(opt.Value) } if value, ok := cniArgsParsed[opt.ValueFromCNIArg]; ok { 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 + return nil, nil, fmt.Errorf("value too long for option %q from CNI_ARGS %q: %q", opt.Option, opt.ValueFromCNIArg, opt.Value) } optsProviding[optParsed] = []byte(value) } @@ -119,14 +123,13 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio // parse necessary options map optsRequesting = make(map[dhcp4.OptionCode]bool) skipRequireDefault := false - for _, opt := range RequestOptions { + for _, opt := range requestOptions { if opt.SkipDefault { skipRequireDefault = true } optParsed, err = parseOptionName(string(opt.Option)) if err != nil { - err = fmt.Errorf("Can not parse option %q: %w", opt.Option, err) - return + return nil, nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err) } optsRequesting[optParsed] = true } @@ -136,7 +139,7 @@ func prepareOptions(cniArgs string, ProvideOptions []ProvideOption, RequestOptio optsRequesting[k] = v } } - return + return optsRequesting, optsProviding, err } // AcquireLease gets an DHCP lease and then maintains it in the background @@ -206,7 +209,7 @@ func (l *DHCPLease) Check() { l.check <- struct{}{} } -func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options { +func (l *DHCPLease) getOptionsWithClientID() dhcp4.Options { opts := make(dhcp4.Options) opts[dhcp4.OptionClientIdentifier] = []byte(l.clientID) // client identifier's first byte is "type" @@ -217,7 +220,7 @@ func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options { } func (l *DHCPLease) getAllOptions() dhcp4.Options { - opts := l.getOptionsWithClientId() + opts := l.getOptionsWithClientID() for k, v := range l.optsProviding { opts[k] = v @@ -302,7 +305,7 @@ func (l *DHCPLease) maintain() { switch state { case leaseStateBound: - sleepDur = l.renewalTime.Sub(time.Now()) + sleepDur = time.Until(l.renewalTime) if sleepDur <= 0 { log.Printf("%v: renewing lease", l.clientID) state = leaseStateRenewing @@ -394,7 +397,7 @@ func (l *DHCPLease) release() error { } defer c.Close() - opts := l.getOptionsWithClientId() + opts := l.getOptionsWithClientID() if err = DhcpRelease(c, *l.ack, opts); err != nil { 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) // exist, we ignore Static Routes (option 33) and the Router/Gateway. - opt121_routes := parseCIDRRoutes(l.opts) - if len(opt121_routes) > 0 { - return append(routes, opt121_routes...) + opt121Routes := parseCIDRRoutes(l.opts) + if len(opt121Routes) > 0 { + return append(routes, opt121Routes...) } // 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) { - var baseDelay time.Duration = resendDelay0 + baseDelay := resendDelay0 var sleepTime time.Duration - var fastRetryLimit = resendFastMax + fastRetryLimit := resendFastMax for { pkt, err := f() if err == nil { diff --git a/plugins/ipam/dhcp/main.go b/plugins/ipam/dhcp/main.go index be18aff4..144d4f77 100644 --- a/plugins/ipam/dhcp/main.go +++ b/plugins/ipam/dhcp/main.go @@ -127,7 +127,7 @@ func cmdDel(args *skel.CmdArgs) error { func cmdCheck(args *skel.CmdArgs) error { // Plugin must return result in same version as specified in netconf versionDecoder := &version.ConfigDecoder{} - //confVersion, err := versionDecoder.Decode(args.StdinData) + // confVersion, err := versionDecoder.Decode(args.StdinData) _, err := versionDecoder.Decode(args.StdinData) if err != nil { return err diff --git a/plugins/ipam/dhcp/options.go b/plugins/ipam/dhcp/options.go index 0adbc655..f9fd472d 100644 --- a/plugins/ipam/dhcp/options.go +++ b/plugins/ipam/dhcp/options.go @@ -21,8 +21,9 @@ import ( "strconv" "time" - "github.com/containernetworking/cni/pkg/types" "github.com/d2g/dhcp4" + + "github.com/containernetworking/cni/pkg/types" ) var optionNameToID = map[string]dhcp4.OptionCode{ diff --git a/plugins/ipam/dhcp/options_test.go b/plugins/ipam/dhcp/options_test.go index ee18b881..d5ba4cb1 100644 --- a/plugins/ipam/dhcp/options_test.go +++ b/plugins/ipam/dhcp/options_test.go @@ -19,8 +19,9 @@ import ( "reflect" "testing" - "github.com/containernetworking/cni/pkg/types" "github.com/d2g/dhcp4" + + "github.com/containernetworking/cni/pkg/types" ) func validateRoutes(t *testing.T, routes []*types.Route) { diff --git a/plugins/ipam/host-local/backend/allocator/allocator.go b/plugins/ipam/host-local/backend/allocator/allocator.go index 5e2d52bb..c060ed74 100644 --- a/plugins/ipam/host-local/backend/allocator/allocator.go +++ b/plugins/ipam/host-local/backend/allocator/allocator.go @@ -22,7 +22,6 @@ import ( "strconv" current "github.com/containernetworking/cni/pkg/types/100" - "github.com/containernetworking/plugins/pkg/ip" "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 // RangeEnd is inclusive as well if i.cur.Equal(r.RangeEnd) { - i.rangeIdx += 1 + i.rangeIdx++ i.rangeIdx %= len(*i.rangeset) r = (*i.rangeset)[i.rangeIdx] diff --git a/plugins/ipam/host-local/backend/allocator/allocator_suite_test.go b/plugins/ipam/host-local/backend/allocator/allocator_suite_test.go index a486bf89..1d52355f 100644 --- a/plugins/ipam/host-local/backend/allocator/allocator_suite_test.go +++ b/plugins/ipam/host-local/backend/allocator/allocator_suite_test.go @@ -15,10 +15,10 @@ package allocator_test import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestAllocator(t *testing.T) { diff --git a/plugins/ipam/host-local/backend/allocator/allocator_test.go b/plugins/ipam/host-local/backend/allocator/allocator_test.go index ccedca7c..7e62b3e8 100644 --- a/plugins/ipam/host-local/backend/allocator/allocator_test.go +++ b/plugins/ipam/host-local/backend/allocator/allocator_test.go @@ -18,12 +18,12 @@ import ( "fmt" "net" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" fakestore "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) type AllocatorTestCase struct { @@ -262,7 +262,6 @@ var _ = Describe("host-local ip allocator", func() { res, err = alloc.Get("ID", "eth0", nil) Expect(err).ToNot(HaveOccurred()) Expect(res.Address.String()).To(Equal("192.168.1.3/29")) - }) Context("when requesting a specific IP", func() { @@ -301,7 +300,6 @@ var _ = Describe("host-local ip allocator", func() { Expect(err).To(HaveOccurred()) }) }) - }) Context("when out of ips", func() { It("returns a meaningful error", func() { diff --git a/plugins/ipam/host-local/backend/allocator/config.go b/plugins/ipam/host-local/backend/allocator/config.go index ec8bf639..f62aa551 100644 --- a/plugins/ipam/host-local/backend/allocator/config.go +++ b/plugins/ipam/host-local/backend/allocator/config.go @@ -21,7 +21,6 @@ import ( "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" ) @@ -43,7 +42,7 @@ type Net struct { // IPAMConfig represents the IP related network configuration. // 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 { *Range Name string diff --git a/plugins/ipam/host-local/backend/allocator/config_test.go b/plugins/ipam/host-local/backend/allocator/config_test.go index 5d452bb2..432b3ccb 100644 --- a/plugins/ipam/host-local/backend/allocator/config_test.go +++ b/plugins/ipam/host-local/backend/allocator/config_test.go @@ -17,9 +17,10 @@ package allocator import ( "net" - "github.com/containernetworking/cni/pkg/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/cni/pkg/types" ) var _ = Describe("IPAM config", func() { @@ -415,7 +416,6 @@ var _ = Describe("IPAM config", func() { }` _, _, err := LoadIPAMConfig([]byte(input), "") Expect(err).To(MatchError("invalid range set 0: mixed address families")) - }) It("Should should error on too many ranges", func() { diff --git a/plugins/ipam/host-local/backend/allocator/range.go b/plugins/ipam/host-local/backend/allocator/range.go index 9bf389e8..6ce8b0dc 100644 --- a/plugins/ipam/host-local/backend/allocator/range.go +++ b/plugins/ipam/host-local/backend/allocator/range.go @@ -125,7 +125,7 @@ func (r *Range) Contains(addr net.IP) bool { // Overlaps returns true if there is any overlap between ranges func (r *Range) Overlaps(r1 *Range) bool { - // different familes + // different families if len(r.RangeStart) != len(r1.RangeStart) { return false } diff --git a/plugins/ipam/host-local/backend/allocator/range_set.go b/plugins/ipam/host-local/backend/allocator/range_set.go index da957f53..40d6b2be 100644 --- a/plugins/ipam/host-local/backend/allocator/range_set.go +++ b/plugins/ipam/host-local/backend/allocator/range_set.go @@ -67,10 +67,8 @@ func (s *RangeSet) Canonicalize() error { } if i == 0 { fam = len((*s)[i].RangeStart) - } else { - if fam != len((*s)[i].RangeStart) { - return fmt.Errorf("mixed address families") - } + } else if fam != len((*s)[i].RangeStart) { + return fmt.Errorf("mixed address families") } } diff --git a/plugins/ipam/host-local/backend/allocator/range_set_test.go b/plugins/ipam/host-local/backend/allocator/range_set_test.go index cc18877b..707f1ae9 100644 --- a/plugins/ipam/host-local/backend/allocator/range_set_test.go +++ b/plugins/ipam/host-local/backend/allocator/range_set_test.go @@ -40,7 +40,6 @@ var _ = Describe("range sets", func() { r, err = p.RangeFor(net.IP{192, 168, 99, 99}) 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")) - }) It("should discover overlaps within a set", func() { diff --git a/plugins/ipam/host-local/backend/allocator/range_test.go b/plugins/ipam/host-local/backend/allocator/range_test.go index f9edfcce..2af3f2e6 100644 --- a/plugins/ipam/host-local/backend/allocator/range_test.go +++ b/plugins/ipam/host-local/backend/allocator/range_test.go @@ -17,10 +17,10 @@ package allocator import ( "net" - "github.com/containernetworking/cni/pkg/types" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/cni/pkg/types" ) var _ = Describe("IP ranges", func() { diff --git a/plugins/ipam/host-local/backend/disk/backend.go b/plugins/ipam/host-local/backend/disk/backend.go index 2aeee69e..40c7863b 100644 --- a/plugins/ipam/host-local/backend/disk/backend.go +++ b/plugins/ipam/host-local/backend/disk/backend.go @@ -24,8 +24,10 @@ import ( "github.com/containernetworking/plugins/plugins/ipam/host-local/backend" ) -const lastIPFilePrefix = "last_reserved_ip." -const LineBreak = "\r\n" +const ( + lastIPFilePrefix = "last_reserved_ip." + LineBreak = "\r\n" +) var defaultDataDir = "/var/lib/cni/networks" @@ -44,7 +46,7 @@ func New(network, dataDir string) (*Store, error) { dataDir = defaultDataDir } dir := filepath.Join(dataDir, network) - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { 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) { 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) { 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 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 { return false, err } @@ -110,7 +112,6 @@ func (s *Store) FindByKey(id string, ifname string, match string) (bool, error) return nil }) return found, err - } 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 if !found && err == nil { match := strings.TrimSpace(id) - found, err = s.FindByKey(id, ifname, match) + found, _ = s.FindByKey(id, ifname, match) } return found @@ -149,7 +150,6 @@ func (s *Store) ReleaseByKey(id string, ifname string, match string) (bool, erro return nil }) return found, err - } // 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 if !found && err == nil { match := strings.TrimSpace(id) - found, err = s.ReleaseByKey(id, ifname, match) + _, err = s.ReleaseByKey(id, ifname, match) } return err } @@ -198,7 +198,7 @@ func (s *Store) GetByID(id string, ifname string) []net.IP { func GetEscapedPath(dataDir string, fname string) string { if runtime.GOOS == "windows" { - fname = strings.Replace(fname, ":", "_", -1) + fname = strings.ReplaceAll(fname, ":", "_") } return filepath.Join(dataDir, fname) } diff --git a/plugins/ipam/host-local/backend/disk/disk_suite_test.go b/plugins/ipam/host-local/backend/disk/disk_suite_test.go index 4f9b36e4..d039f541 100644 --- a/plugins/ipam/host-local/backend/disk/disk_suite_test.go +++ b/plugins/ipam/host-local/backend/disk/disk_suite_test.go @@ -15,10 +15,10 @@ package disk import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestLock(t *testing.T) { diff --git a/plugins/ipam/host-local/backend/disk/lock.go b/plugins/ipam/host-local/backend/disk/lock.go index fe7b4803..d42ebc3c 100644 --- a/plugins/ipam/host-local/backend/disk/lock.go +++ b/plugins/ipam/host-local/backend/disk/lock.go @@ -15,9 +15,10 @@ package disk import ( - "github.com/alexflint/go-filemutex" "os" "path" + + "github.com/alexflint/go-filemutex" ) // FileLock wraps os.File to be used as a lock using flock diff --git a/plugins/ipam/host-local/backend/disk/lock_test.go b/plugins/ipam/host-local/backend/disk/lock_test.go index 4591e103..3e0804e6 100644 --- a/plugins/ipam/host-local/backend/disk/lock_test.go +++ b/plugins/ipam/host-local/backend/disk/lock_test.go @@ -30,7 +30,7 @@ var _ = Describe("Lock Operations", func() { // create a dummy file to lock 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()) err = f.Close() Expect(err).ToNot(HaveOccurred()) diff --git a/plugins/ipam/host-local/dns_test.go b/plugins/ipam/host-local/dns_test.go index 0b04cba9..6ad89f9d 100644 --- a/plugins/ipam/host-local/dns_test.go +++ b/plugins/ipam/host-local/dns_test.go @@ -17,9 +17,10 @@ package main import ( "os" - "github.com/containernetworking/cni/pkg/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/cni/pkg/types" ) var _ = Describe("parsing resolv.conf", func() { diff --git a/plugins/ipam/host-local/host_local_suite_test.go b/plugins/ipam/host-local/host_local_suite_test.go index 10f0d5ec..d65e089b 100644 --- a/plugins/ipam/host-local/host_local_suite_test.go +++ b/plugins/ipam/host-local/host_local_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestHostLocal(t *testing.T) { diff --git a/plugins/ipam/host-local/host_local_test.go b/plugins/ipam/host-local/host_local_test.go index 213c36be..7ae11b73 100644 --- a/plugins/ipam/host-local/host_local_test.go +++ b/plugins/ipam/host-local/host_local_test.go @@ -21,14 +21,14 @@ import ( "path/filepath" "strings" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" types100 "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/testutils" - "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) const LineBreak = "\r\n" @@ -57,7 +57,7 @@ var _ = Describe("host-local Operations", func() { ver := ver 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()) 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() { 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()) 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() { - 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()) conf := fmt.Sprintf(`{ @@ -397,7 +397,7 @@ var _ = Describe("host-local Operations", func() { contents, err := os.ReadFile(ipFilePath) Expect(err).NotTo(HaveOccurred()) 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()) err = testutils.CmdDelWithArgs(args, func() error { @@ -504,7 +504,7 @@ var _ = Describe("host-local Operations", func() { return cmdAdd(args) }) 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() { @@ -546,7 +546,7 @@ var _ = Describe("host-local Operations", 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()) 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() { - 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()) conf := fmt.Sprintf(`{ diff --git a/plugins/ipam/host-local/main.go b/plugins/ipam/host-local/main.go index 9983c83f..0f53574e 100644 --- a/plugins/ipam/host-local/main.go +++ b/plugins/ipam/host-local/main.go @@ -19,14 +19,13 @@ import ( "net" "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/types" current "github.com/containernetworking/cni/pkg/types/100" "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() { @@ -34,7 +33,6 @@ func main() { } func cmdCheck(args *skel.CmdArgs) error { - ipamConf, _, err := allocator.LoadIPAMConfig(args.StdinData, args.Args) if err != nil { return err @@ -48,8 +46,8 @@ func cmdCheck(args *skel.CmdArgs) error { } defer store.Close() - containerIpFound := store.FindByID(args.ContainerID, args.IfName) - if containerIpFound == false { + containerIPFound := store.FindByID(args.ContainerID, args.IfName) + if !containerIPFound { return fmt.Errorf("host-local: Failed to find address added by container %v", args.ContainerID) } @@ -84,7 +82,7 @@ func cmdAdd(args *skel.CmdArgs) error { // Store all requested IPs in a map, so we can easily remove ones we use // and error if some remain - requestedIPs := map[string]net.IP{} //net.IP cannot be a key + requestedIPs := map[string]net.IP{} // net.IP cannot be a key for _, ip := range ipamConf.IPArgs { requestedIPs[ip.String()] = ip diff --git a/plugins/ipam/static/static_test.go b/plugins/ipam/static/static_test.go index a7f9e231..ac2a6719 100644 --- a/plugins/ipam/static/static_test.go +++ b/plugins/ipam/static/static_test.go @@ -19,13 +19,13 @@ import ( "net" "strings" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" types100 "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/testutils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("static Operations", func() { diff --git a/plugins/main/bridge/bridge.go b/plugins/main/bridge/bridge.go index dce8568b..b8ffb5bb 100644 --- a/plugins/main/bridge/bridge.go +++ b/plugins/main/bridge/bridge.go @@ -129,7 +129,6 @@ func loadNetConf(bytes []byte, envArgs string) (*NetConf, string, error) { // - Calculates and compiles a list of gateway addresses // - Adds a default route if needed func calcGateways(result *current.Result, n *NetConf) (*gwInfo, *gwInfo, error) { - gwsV4 := &gwInfo{} gwsV6 := &gwInfo{} @@ -300,8 +299,8 @@ func ensureBridge(brName string, mtu int, promiscMode, vlanFiltering bool) (*net return br, nil } -func ensureVlanInterface(br *netlink.Bridge, vlanId int) (netlink.Link, error) { - name := fmt.Sprintf("%s.%d", br.Name, vlanId) +func ensureVlanInterface(br *netlink.Bridge, vlanID int) (netlink.Link, error) { + name := fmt.Sprintf("%s.%d", br.Name, vlanID) brGatewayVeth, err := netlink.LinkByName(name) 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) } - _, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanId, "") + _, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanID, "") if err != nil { 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 { - var success bool = false + success := false n, cniVersion, err := loadNetConf(args.StdinData, args.Args) if err != nil { @@ -421,7 +420,7 @@ func cmdAdd(args *skel.CmdArgs) error { } 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) @@ -533,8 +532,10 @@ func cmdAdd(args *skel.CmdArgs) error { } if vlanInterface == nil { - vlanInterface = ¤t.Interface{Name: vlanIface.Attrs().Name, - Mac: vlanIface.Attrs().HardwareAddr.String()} + vlanInterface = ¤t.Interface{ + Name: vlanIface.Attrs().Name, + Mac: vlanIface.Attrs().HardwareAddr.String(), + } result.Interfaces = append(result.Interfaces, vlanInterface) } @@ -720,7 +721,6 @@ type cniBridgeIf struct { } func validateInterface(intf current.Interface, expectInSb bool) (cniBridgeIf, netlink.Link, error) { - ifFound := cniBridgeIf{found: false} if intf.Name == "" { 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) { - brFound, link, err := validateInterface(intf, false) if err != nil { 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) { - vethFound, link, err := validateInterface(*intf, false) if err != nil { return vethFound, err @@ -821,7 +819,6 @@ func validateCniVethInterface(intf *current.Interface, brIf cniBridgeIf, contIf } func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error) { - vethFound, link, err := validateInterface(intf, true) if err != nil { return vethFound, err @@ -850,7 +847,6 @@ func validateCniContainerInterface(intf current.Interface) (cniBridgeIf, error) } func cmdCheck(args *skel.CmdArgs) error { - n, _, err := loadNetConf(args.StdinData, args.Args) if err != nil { return err diff --git a/plugins/main/bridge/bridge_suite_test.go b/plugins/main/bridge/bridge_suite_test.go index 1e882852..1ec199cf 100644 --- a/plugins/main/bridge/bridge_suite_test.go +++ b/plugins/main/bridge/bridge_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) var ( diff --git a/plugins/main/bridge/bridge_test.go b/plugins/main/bridge/bridge_test.go index da393e8f..d39557e2 100644 --- a/plugins/main/bridge/bridge_test.go +++ b/plugins/main/bridge/bridge_test.go @@ -23,6 +23,9 @@ import ( "github.com/coreos/go-iptables/iptables" "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/containernetworking/cni/pkg/skel" @@ -32,12 +35,7 @@ import ( "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" - - "github.com/vishvananda/netlink" - "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) const ( @@ -53,10 +51,11 @@ type Net struct { Type string `json:"type,omitempty"` BrName string `json:"bridge"` IPAM *allocator.IPAMConfig `json:"ipam"` - //RuntimeConfig struct { // The capability arg + // RuntimeConfig struct { // The capability arg // IPRanges []RangeSet `json:"ipRanges,omitempty"` - //} `json:"runtimeConfig,omitempty"` - //Args *struct { + // Args *struct { + // } `json:"runtimeConfig,omitempty"` + // A *IPAMArgs `json:"cni"` DNS types.DNS `json:"dns"` RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` @@ -285,7 +284,7 @@ var counter uint // arguments for a test case. func (tc testCase) createCmdArgs(targetNS ns.NetNS, dataDir string) *skel.CmdArgs { conf := tc.netConfJSON(dataDir) - //defer func() { counter += 1 }() + // defer func() { counter += 1 }() return &skel.CmdArgs{ ContainerID: fmt.Sprintf("dummy-%d", counter), Netns: targetNS.Path(), @@ -298,12 +297,11 @@ func (tc testCase) createCmdArgs(targetNS ns.NetNS, dataDir string) *skel.CmdArg // createCheckCmdArgs generates network configuration and creates command // arguments for a Check test case. func (tc testCase) createCheckCmdArgs(targetNS ns.NetNS, config *Net, dataDir string) *skel.CmdArgs { - conf, err := json.Marshal(config) Expect(err).NotTo(HaveOccurred()) // TODO Don't we need to use the same counter as before? - //defer func() { counter += 1 }() + // defer func() { counter += 1 }() return &skel.CmdArgs{ ContainerID: fmt.Sprintf("dummy-%d", counter), Netns: targetNS.Path(), @@ -412,9 +410,9 @@ func countIPAMIPs(path string) (int, error) { return count, nil } -func checkVlan(vlanId int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool { +func checkVlan(vlanID int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool { for _, vlan := range bridgeVlanInfo { - if vlan.Vid == uint16(vlanId) { + if vlan.Vid == uint16(vlanID) { return true } } @@ -435,10 +433,12 @@ type testerBase struct { vethName string } -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string, testNS, targetNS ns.NetNS) cmdAddDelTester { switch { @@ -615,7 +615,7 @@ func (tester *testerV10x) cmdAddTest(tc testCase, dataDir string) (types.Result, Expect(err).NotTo(HaveOccurred()) Expect(len(addrs)).To(Equal(len(expCIDRsV4))) addrs, err = netlink.AddrList(link, netlink.FAMILY_V6) - Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) //add one for the link-local + Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) // add one for the link-local Expect(err).NotTo(HaveOccurred()) // Ignore link local address which may or may not be // ready when we read addresses. @@ -691,7 +691,7 @@ func (tester *testerV10x) cmdCheckTest(tc testCase, conf *Net, dataDir string) { Expect(err).NotTo(HaveOccurred()) Expect(len(addrs)).To(Equal(len(expCIDRsV4))) addrs, err = netlink.AddrList(link, netlink.FAMILY_V6) - Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) //add one for the link-local + Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) // add one for the link-local Expect(err).NotTo(HaveOccurred()) // Ignore link local address which may or may not be // ready when we read addresses. @@ -915,7 +915,7 @@ func (tester *testerV04x) cmdAddTest(tc testCase, dataDir string) (types.Result, Expect(err).NotTo(HaveOccurred()) Expect(len(addrs)).To(Equal(len(expCIDRsV4))) addrs, err = netlink.AddrList(link, netlink.FAMILY_V6) - Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) //add one for the link-local + Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) // add one for the link-local Expect(err).NotTo(HaveOccurred()) // Ignore link local address which may or may not be // ready when we read addresses. @@ -991,7 +991,7 @@ func (tester *testerV04x) cmdCheckTest(tc testCase, conf *Net, dataDir string) { Expect(err).NotTo(HaveOccurred()) Expect(len(addrs)).To(Equal(len(expCIDRsV4))) addrs, err = netlink.AddrList(link, netlink.FAMILY_V6) - Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) //add one for the link-local + Expect(len(addrs)).To(Equal(len(expCIDRsV6) + 1)) // add one for the link-local Expect(err).NotTo(HaveOccurred()) // Ignore link local address which may or may not be // ready when we read addresses. @@ -1259,7 +1259,6 @@ func (tester *testerV03x) cmdAddTest(tc testCase, dataDir string) (types.Result, } func (tester *testerV03x) cmdCheckTest(tc testCase, conf *Net, dataDir string) { - return } 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) { - return } 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 { return cmdDel(tester.args) }) - if expect020DelError(tc) { + switch { + case expect020DelError(tc): Expect(err).To(MatchError(tc.DelErr020)) - } else if expect010DelError(tc) { + case expect010DelError(tc): Expect(err).To(MatchError(tc.DelErr010)) - } else { + default: Expect(err).NotTo(HaveOccurred()) } return nil @@ -1577,7 +1576,6 @@ func buildOneConfig(name, cniVersion string, orig *Net, prevResult types.Result) } return conf, nil - } 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() { const IFNAME = "bridge0" - const EXPECTED_IP = "10.0.0.0/8" - const CHANGED_EXPECTED_IP = "10.1.2.3/16" conf := &NetConf{ NetConf: types.NetConf{ @@ -2014,7 +2010,7 @@ var _ = Describe("bridge Operations", func() { // Check if ForceAddress has default value Expect(conf.ForceAddress).To(Equal(false)) - //Check if promiscuous mode is set correctly + // Check if promiscuous mode is set correctly link, err := netlink.LinkByName("bridge0") Expect(err).NotTo(HaveOccurred()) diff --git a/plugins/main/dummy/dummy.go b/plugins/main/dummy/dummy.go index 22edeafb..60202a64 100644 --- a/plugins/main/dummy/dummy.go +++ b/plugins/main/dummy/dummy.go @@ -26,7 +26,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "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) { - dummy := ¤t.Interface{} 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 if err := netns.Do(func(_ ns.NetNS) error { - // Check interface against values found in the container err := validateCniContainerInterface(contMap) if err != nil { @@ -262,11 +259,9 @@ func cmdCheck(args *skel.CmdArgs) error { } return nil - } func validateCniContainerInterface(intf current.Interface) error { - var link netlink.Link var err error diff --git a/plugins/main/dummy/dummy_suite_test.go b/plugins/main/dummy/dummy_suite_test.go index c1157975..26c79bc0 100644 --- a/plugins/main/dummy/dummy_suite_test.go +++ b/plugins/main/dummy/dummy_suite_test.go @@ -15,12 +15,11 @@ package main_test import ( - "github.com/onsi/gomega/gexec" + "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" + "github.com/onsi/gomega/gexec" ) var pathToLoPlugin string diff --git a/plugins/main/dummy/dummy_test.go b/plugins/main/dummy/dummy_test.go index 185dd2b3..3b5f00d6 100644 --- a/plugins/main/dummy/dummy_test.go +++ b/plugins/main/dummy/dummy_test.go @@ -23,6 +23,10 @@ import ( "strings" "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/types" types020 "github.com/containernetworking/cni/pkg/types/020" @@ -31,11 +35,6 @@ import ( "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" "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" @@ -89,7 +88,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ } return conf, nil - } type tester interface { @@ -99,10 +97,12 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string) tester { switch { diff --git a/plugins/main/host-device/host-device.go b/plugins/main/host-device/host-device.go index 0cdeb943..cd31c6ad 100644 --- a/plugins/main/host-device/host-device.go +++ b/plugins/main/host-device/host-device.go @@ -31,16 +31,13 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) -var ( - sysBusPCI = "/sys/bus/pci/devices" -) +var sysBusPCI = "/sys/bus/pci/devices" // Array of different linux drivers bound to network device needed for DPDK 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 { return nil, fmt.Errorf("failed to list node links: %v", err) } + switch { - if len(devname) > 0 { + case len(devname) > 0: return netlink.LinkByName(devname) - } else if len(hwaddr) > 0 { + case len(hwaddr) > 0: hwAddr, err := net.ParseMAC(hwaddr) if err != nil { 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 } } - } else if len(kernelpath) > 0 { + case len(kernelpath) > 0: 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) } @@ -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") if _, err := os.Lstat(netDir); err != nil { virtioNetDir := filepath.Join(sysBusPCI, pciaddr, "virtio*", "net") @@ -386,7 +384,6 @@ func main() { } func cmdCheck(args *skel.CmdArgs) error { - cfg, err := loadConf(args.StdinData) if err != nil { 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 if err := netns.Do(func(_ ns.NetNS) error { - // Check interface against values found in the container err := validateCniContainerInterface(contMap) if err != nil { @@ -469,7 +465,6 @@ func cmdCheck(args *skel.CmdArgs) error { } func validateCniContainerInterface(intf current.Interface) error { - var link netlink.Link var err error diff --git a/plugins/main/host-device/host-device_suite_test.go b/plugins/main/host-device/host-device_suite_test.go index aca9fd35..51144ceb 100644 --- a/plugins/main/host-device/host-device_suite_test.go +++ b/plugins/main/host-device/host-device_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestVlan(t *testing.T) { diff --git a/plugins/main/host-device/host-device_test.go b/plugins/main/host-device/host-device_test.go index 2320fc81..bc5a6f43 100644 --- a/plugins/main/host-device/host-device_test.go +++ b/plugins/main/host-device/host-device_test.go @@ -23,6 +23,10 @@ import ( "path" "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/types" types040 "github.com/containernetworking/cni/pkg/types/040" @@ -30,10 +34,6 @@ import ( "github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - "github.com/vishvananda/netlink" ) type Net struct { @@ -214,7 +214,6 @@ func buildOneConfig(name, cniVersion string, orig *Net, prevResult types.Result) } return conf, nil - } type tester interface { @@ -224,9 +223,11 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase +) func newTesterByVersion(version string) tester { switch { @@ -664,11 +665,11 @@ var _ = Describe("base functionality", func() { Expect(link.Attrs().HardwareAddr).To(Equal(origLink.Attrs().HardwareAddr)) Expect(link.Attrs().Flags & net.FlagUp).To(Equal(net.FlagUp)) - //get the IP address of the interface in the target namespace + // get the IP address of the interface in the target namespace addrs, err := netlink.AddrList(link, netlink.FAMILY_V4) Expect(err).NotTo(HaveOccurred()) addr := addrs[0].IPNet.String() - //assert that IP address is what we set + // assert that IP address is what we set Expect(addr).To(Equal(targetIP)) return nil @@ -711,7 +712,6 @@ var _ = Describe("base functionality", func() { } _, _, err := testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) }) Expect(err).To(MatchError(`specify either "device", "hwaddr", "kernelpath" or "pciBusID"`)) - }) It(fmt.Sprintf("[%s] works with a valid config without IPAM", ver), func() { @@ -961,11 +961,11 @@ var _ = Describe("base functionality", func() { Expect(link.Attrs().HardwareAddr).To(Equal(origLink.Attrs().HardwareAddr)) Expect(link.Attrs().Flags & net.FlagUp).To(Equal(net.FlagUp)) - //get the IP address of the interface in the target namespace + // get the IP address of the interface in the target namespace addrs, err := netlink.AddrList(link, netlink.FAMILY_V4) Expect(err).NotTo(HaveOccurred()) addr := addrs[0].IPNet.String() - //assert that IP address is what we set + // assert that IP address is what we set Expect(addr).To(Equal(targetIP)) return nil @@ -1167,7 +1167,7 @@ func (fs *fakeFilesystem) use() func() { fs.rootDir = tmpDir 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 { panic(fmt.Errorf("error creating fake directory: %s", err.Error())) } diff --git a/plugins/main/ipvlan/ipvlan.go b/plugins/main/ipvlan/ipvlan.go index 20506561..2fbfd746 100644 --- a/plugins/main/ipvlan/ipvlan.go +++ b/plugins/main/ipvlan/ipvlan.go @@ -26,7 +26,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" @@ -357,7 +356,6 @@ func main() { } func cmdCheck(args *skel.CmdArgs) error { - n, _, err := loadConf(args, true) if err != nil { 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 if err := netns.Do(func(_ ns.NetNS) error { - // Check interface against values found in the container err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode) if err != nil { @@ -448,7 +445,6 @@ func cmdCheck(args *skel.CmdArgs) error { } func validateCniContainerInterface(intf current.Interface, masterIndex int, modeExpected string) error { - var link netlink.Link var err error @@ -469,6 +465,9 @@ func validateCniContainerInterface(intf current.Interface, masterIndex int, mode } mode, err := modeFromString(modeExpected) + if err != nil { + return err + } if ipv.Mode != mode { currString, err := modeToString(ipv.Mode) if err != nil { diff --git a/plugins/main/ipvlan/ipvlan_suite_test.go b/plugins/main/ipvlan/ipvlan_suite_test.go index 83f73cb9..2cdaaff6 100644 --- a/plugins/main/ipvlan/ipvlan_suite_test.go +++ b/plugins/main/ipvlan/ipvlan_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestIpvlan(t *testing.T) { diff --git a/plugins/main/ipvlan/ipvlan_test.go b/plugins/main/ipvlan/ipvlan_test.go index 7f81ed4e..9ba4db8a 100644 --- a/plugins/main/ipvlan/ipvlan_test.go +++ b/plugins/main/ipvlan/ipvlan_test.go @@ -22,6 +22,10 @@ import ( "strings" "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/types" types020 "github.com/containernetworking/cni/pkg/types/020" @@ -29,16 +33,13 @@ import ( 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/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) -const MASTER_NAME = "eth0" -const MASTER_NAME_INCONTAINER = "eth1" +const ( + MASTER_NAME = "eth0" + MASTER_NAME_INCONTAINER = "eth1" +) type Net struct { Name string `json:"name"` @@ -92,7 +93,6 @@ func buildOneConfig(cniVersion string, master string, orig *Net, prevResult type } return conf, nil - } func ipvlanAddCheckDelTest(conf, masterName string, originalNS, targetNS ns.NetNS) { @@ -206,9 +206,11 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV02x testerBase +) func newTesterByVersion(version string) tester { switch { @@ -324,7 +326,7 @@ var _ = Describe("ipvlan Operations", func() { if inContainer { masterInterface = MASTER_NAME_INCONTAINER } - //for _, ver := range testutils.AllSpecVersions { + // for _, ver := range testutils.AllSpecVersions { for _, ver := range [...]string{"1.0.0"} { // Redefine ver inside for scope so real value is picked up by each dynamically defined It() // See Gingkgo's "Patterns for dynamically generating tests" documentation. @@ -471,8 +473,8 @@ var _ = Describe("ipvlan Operations", func() { err = netlink.LinkSetUp(link) Expect(err).NotTo(HaveOccurred()) - var address = &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} - var addr = &netlink.Addr{IPNet: address} + address := &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} + addr := &netlink.Addr{IPNet: address} err = netlink.AddrAdd(link, addr) Expect(err).NotTo(HaveOccurred()) diff --git a/plugins/main/loopback/loopback.go b/plugins/main/loopback/loopback.go index cae4aa4c..640b6dd0 100644 --- a/plugins/main/loopback/loopback.go +++ b/plugins/main/loopback/loopback.go @@ -26,7 +26,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ns" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) @@ -112,7 +111,7 @@ func cmdAdd(args *skel.CmdArgs) error { r := ¤t.Result{ CNIVersion: conf.CNIVersion, Interfaces: []*current.Interface{ - ¤t.Interface{ + { Name: args.IfName, Mac: "00:00:00:00:00:00", Sandbox: args.Netns, diff --git a/plugins/main/loopback/loopback_suite_test.go b/plugins/main/loopback/loopback_suite_test.go index 1180a81d..27829ae1 100644 --- a/plugins/main/loopback/loopback_suite_test.go +++ b/plugins/main/loopback/loopback_suite_test.go @@ -15,12 +15,11 @@ package main_test import ( - "github.com/onsi/gomega/gexec" + "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" + "github.com/onsi/gomega/gexec" ) var pathToLoPlugin string diff --git a/plugins/main/loopback/loopback_test.go b/plugins/main/loopback/loopback_test.go index b3f0e779..0697b80a 100644 --- a/plugins/main/loopback/loopback_test.go +++ b/plugins/main/loopback/loopback_test.go @@ -20,12 +20,13 @@ import ( "os/exec" "strings" - "github.com/containernetworking/plugins/pkg/ns" - "github.com/containernetworking/plugins/pkg/testutils" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" ) func generateConfig(cniVersion string) *strings.Reader { diff --git a/plugins/main/macvlan/macvlan.go b/plugins/main/macvlan/macvlan.go index af24971c..c6700139 100644 --- a/plugins/main/macvlan/macvlan.go +++ b/plugins/main/macvlan/macvlan.go @@ -27,7 +27,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" @@ -434,7 +433,6 @@ func main() { } func cmdCheck(args *skel.CmdArgs) error { - n, _, err := loadConf(args, args.Args) if err != nil { return err @@ -457,7 +455,7 @@ func cmdCheck(args *skel.CmdArgs) error { // Parse previous result. 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 { @@ -482,7 +480,7 @@ func cmdCheck(args *skel.CmdArgs) error { // The namespace must be the same as what was configured 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) } @@ -501,7 +499,6 @@ func cmdCheck(args *skel.CmdArgs) error { // Check prevResults for ips, routes and dns against values found in the container if err := netns.Do(func(_ ns.NetNS) error { - // Check interface against values found in the container err := validateCniContainerInterface(contMap, m.Attrs().Index, n.Mode) if err != nil { @@ -526,27 +523,29 @@ func cmdCheck(args *skel.CmdArgs) error { } func validateCniContainerInterface(intf current.Interface, parentIndex int, modeExpected string) error { - var link netlink.Link var err error 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) 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 == "" { - 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) 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) + if err != nil { + return err + } if macv.Mode != mode { currString, err := modeToString(macv.Mode) if err != nil { @@ -556,12 +555,12 @@ func validateCniContainerInterface(intf current.Interface, parentIndex int, mode if err != nil { 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 != 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) } } diff --git a/plugins/main/macvlan/macvlan_suite_test.go b/plugins/main/macvlan/macvlan_suite_test.go index e70a0f52..0a24b796 100644 --- a/plugins/main/macvlan/macvlan_suite_test.go +++ b/plugins/main/macvlan/macvlan_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestMacvlan(t *testing.T) { diff --git a/plugins/main/macvlan/macvlan_test.go b/plugins/main/macvlan/macvlan_test.go index 650e6229..968bd8e1 100644 --- a/plugins/main/macvlan/macvlan_test.go +++ b/plugins/main/macvlan/macvlan_test.go @@ -22,6 +22,10 @@ import ( "strings" "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/types" types020 "github.com/containernetworking/cni/pkg/types/020" @@ -29,16 +33,13 @@ import ( 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/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) -const MASTER_NAME = "eth0" -const MASTER_NAME_INCONTAINER = "eth1" +const ( + MASTER_NAME = "eth0" + MASTER_NAME_INCONTAINER = "eth1" +) type Net struct { Name string `json:"name"` @@ -47,10 +48,10 @@ type Net struct { Master string `json:"master"` Mode string `json:"mode"` IPAM *allocator.IPAMConfig `json:"ipam"` - //RuntimeConfig struct { // The capability arg + // RuntimeConfig struct { // The capability arg // IPRanges []RangeSet `json:"ipRanges,omitempty"` - //} `json:"runtimeConfig,omitempty"` - //Args *struct { + // Args *struct { + // } `json:"runtimeConfig,omitempty"` // A *IPAMArgs `json:"cni"` DNS types.DNS `json:"dns"` RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` @@ -98,7 +99,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ } return conf, nil - } type tester interface { @@ -108,10 +108,12 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string) tester { switch { @@ -407,7 +409,6 @@ var _ = Describe("macvlan Operations", func() { return nil }) Expect(err).NotTo(HaveOccurred()) - }) 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) Expect(err).NotTo(HaveOccurred()) - var address = &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} - var addr = &netlink.Addr{IPNet: address} + address := &net.IPNet{IP: net.IPv4(192, 0, 0, 1), Mask: net.CIDRMask(24, 32)} + addr := &netlink.Addr{IPNet: address} err = netlink.AddrAdd(link, addr) Expect(err).NotTo(HaveOccurred()) diff --git a/plugins/main/ptp/ptp.go b/plugins/main/ptp/ptp.go index 80107832..841e57d1 100644 --- a/plugins/main/ptp/ptp.go +++ b/plugins/main/ptp/ptp.go @@ -28,7 +28,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" @@ -282,7 +281,6 @@ func cmdDel(args *skel.CmdArgs) error { } return err }) - if err != nil { // 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. @@ -358,7 +356,6 @@ func cmdCheck(args *skel.CmdArgs) error { // // Check prevResults for ips, routes and dns against values found in the container if err := netns.Do(func(_ ns.NetNS) error { - // Check interface against values found in the container err := validateCniContainerInterface(contMap) if err != nil { @@ -383,7 +380,6 @@ func cmdCheck(args *skel.CmdArgs) error { } func validateCniContainerInterface(intf current.Interface) error { - var link netlink.Link var err error diff --git a/plugins/main/ptp/ptp_suite_test.go b/plugins/main/ptp/ptp_suite_test.go index b8bd30bd..038a680b 100644 --- a/plugins/main/ptp/ptp_suite_test.go +++ b/plugins/main/ptp/ptp_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestPtp(t *testing.T) { diff --git a/plugins/main/ptp/ptp_test.go b/plugins/main/ptp/ptp_test.go index adb016d1..869a02f2 100644 --- a/plugins/main/ptp/ptp_test.go +++ b/plugins/main/ptp/ptp_test.go @@ -20,6 +20,10 @@ import ( "os" "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/types" types020 "github.com/containernetworking/cni/pkg/types/020" @@ -27,12 +31,7 @@ import ( 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/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) type Net struct { @@ -87,7 +86,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ } return conf, nil - } type tester interface { @@ -97,10 +95,12 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string) tester { switch { diff --git a/plugins/main/tap/tap.go b/plugins/main/tap/tap.go index e51b4194..c8a6c9f8 100644 --- a/plugins/main/tap/tap.go +++ b/plugins/main/tap/tap.go @@ -25,15 +25,13 @@ import ( "syscall" "github.com/opencontainers/selinux/go-selinux" - + "github.com/vishvananda/netlink" "golang.org/x/sys/unix" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/vishvananda/netlink" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" @@ -43,15 +41,14 @@ import ( type NetConf struct { types.NetConf - MultiQueue bool `json:"multiQueue"` - MTU int `json:"mtu"` - Mac string `json:"mac,omitempty"` - Owner *uint32 `json:"owner,omitempty"` - Group *uint32 `json:"group,omitempty"` - SelinuxContext string `json:"selinuxContext,omitempty"` - Args *struct { - } `json:"args,omitempty"` - RuntimeConfig struct { + MultiQueue bool `json:"multiQueue"` + MTU int `json:"mtu"` + Mac string `json:"mac,omitempty"` + Owner *uint32 `json:"owner,omitempty"` + Group *uint32 `json:"group,omitempty"` + SelinuxContext string `json:"selinuxContext,omitempty"` + Args *struct{} `json:"args,omitempty"` + RuntimeConfig struct { Mac string `json:"mac,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 { - if conf.SelinuxContext != "" { + switch { + case conf.SelinuxContext != "": if err := selinux.SetExecLabel(conf.SelinuxContext); err != nil { return fmt.Errorf("failed set socket label: %v", err) } 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) - } else { + default: return createLinkWithNetlink(tmpName, conf.MTU, int(netns.Fd()), conf.MultiQueue, conf.Mac, conf.Owner, conf.Group) } } diff --git a/plugins/main/tap/tap_test.go b/plugins/main/tap/tap_test.go index a744730e..08615139 100644 --- a/plugins/main/tap/tap_test.go +++ b/plugins/main/tap/tap_test.go @@ -25,7 +25,6 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "github.com/vishvananda/netlink" "github.com/containernetworking/cni/pkg/skel" @@ -92,7 +91,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ } return conf, nil - } type tester interface { @@ -102,10 +100,12 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string) tester { switch { diff --git a/plugins/main/vlan/vlan.go b/plugins/main/vlan/vlan.go index a6bceeef..f8ff48b9 100644 --- a/plugins/main/vlan/vlan.go +++ b/plugins/main/vlan/vlan.go @@ -20,12 +20,12 @@ import ( "fmt" "runtime" + "github.com/vishvananda/netlink" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/vishvananda/netlink" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ipam" "github.com/containernetworking/plugins/pkg/ns" @@ -35,7 +35,7 @@ import ( type NetConf struct { types.NetConf Master string `json:"master"` - VlanId int `json:"vlanId"` + VlanID int `json:"vlanId"` MTU int `json:"mtu,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) } 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 { - return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4095 inclusive)", n.VlanId) + if n.VlanID < 0 || n.VlanID > 4094 { + return nil, "", fmt.Errorf("invalid VLAN ID %d (must be between 0 and 4095 inclusive)", n.VlanID) } // check existing and MTU of master interface masterMTU, err := getMTUByName(n.Master, args.Netns, n.LinkContNs) - if err != nil { return nil, "", err } @@ -127,7 +126,7 @@ func createVlan(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interfac ParentIndex: m.Attrs().Index, Namespace: netlink.NsFd(int(netns.Fd())), }, - VlanId: conf.VlanId, + VlanId: conf.VlanID, } 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 if err := netns.Do(func(_ ns.NetNS) error { - // 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 { return err } @@ -350,8 +348,7 @@ func cmdCheck(args *skel.CmdArgs) error { 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 err error @@ -372,7 +369,7 @@ func validateCniContainerInterface(intf current.Interface, masterIndex int, vlan } // TODO This works when unit testing via cnitool; fails with ./test.sh - //if masterIndex != vlan.Attrs().ParentIndex { + // if masterIndex != vlan.Attrs().ParentIndex { // return fmt.Errorf("Container vlan Master %d does not match expected value: %d", vlan.Attrs().ParentIndex, masterIndex) //} @@ -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", - intf.Name, vlanId, vlan.VlanId) + intf.Name, vlanID, vlan.VlanId) } if mtu != 0 { diff --git a/plugins/main/vlan/vlan_suite_test.go b/plugins/main/vlan/vlan_suite_test.go index 28a7c83d..c18e025b 100644 --- a/plugins/main/vlan/vlan_suite_test.go +++ b/plugins/main/vlan/vlan_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestVlan(t *testing.T) { diff --git a/plugins/main/vlan/vlan_test.go b/plugins/main/vlan/vlan_test.go index 4b54bb0b..d3b9bfde 100644 --- a/plugins/main/vlan/vlan_test.go +++ b/plugins/main/vlan/vlan_test.go @@ -22,6 +22,10 @@ import ( "strings" "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/types" types020 "github.com/containernetworking/cni/pkg/types/020" @@ -29,23 +33,20 @@ import ( 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/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) -const MASTER_NAME = "eth0" -const MASTER_NAME_INCONTAINER = "eth1" +const ( + MASTER_NAME = "eth0" + MASTER_NAME_INCONTAINER = "eth1" +) type Net struct { Name string `json:"name"` CNIVersion string `json:"cniVersion"` Type string `json:"type,omitempty"` Master string `json:"master"` - VlanId int `json:"vlanId"` + VlanID int `json:"vlanId"` MTU int `json:"mtu"` IPAM *allocator.IPAMConfig `json:"ipam"` DNS types.DNS `json:"dns"` @@ -94,7 +95,6 @@ func buildOneConfig(netName string, cniVersion string, orig *Net, prevResult typ } return conf, nil - } type tester interface { @@ -104,10 +104,12 @@ type tester interface { type testerBase struct{} -type testerV10x testerBase -type testerV04x testerBase -type testerV03x testerBase -type testerV01xOr02x testerBase +type ( + testerV10x testerBase + testerV04x testerBase + testerV03x testerBase + testerV01xOr02x testerBase +) func newTesterByVersion(version string) tester { switch { @@ -247,7 +249,7 @@ var _ = Describe("vlan Operations", func() { Type: "vlan", }, Master: masterInterface, - VlanId: 33, + VlanID: 33, MTU: 1500, LinkContNs: isInContainer, } @@ -283,7 +285,7 @@ var _ = Describe("vlan Operations", func() { Type: "vlan", }, Master: masterInterface, - VlanId: 33, + VlanID: 33, LinkContNs: isInContainer, } diff --git a/plugins/meta/bandwidth/bandwidth_linux_test.go b/plugins/meta/bandwidth/bandwidth_linux_test.go index 755a0274..d08f36a6 100644 --- a/plugins/meta/bandwidth/bandwidth_linux_test.go +++ b/plugins/meta/bandwidth/bandwidth_linux_test.go @@ -22,6 +22,9 @@ import ( "os" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/onsi/gomega/gexec" "github.com/vishvananda/netlink" "github.com/containernetworking/cni/pkg/invoke" @@ -30,10 +33,6 @@ import ( types100 "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ns" "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) { @@ -78,7 +77,6 @@ func buildOneConfig(name, cniVersion string, orig *PluginConf, prevResult types. } return conf, newBytes, nil - } var _ = Describe("bandwidth test", func() { @@ -221,7 +219,6 @@ var _ = Describe("bandwidth test", func() { Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1))) return nil })).To(Succeed()) - }) It(fmt.Sprintf("[%s] does not apply ingress when disabled", ver), func() { @@ -289,7 +286,6 @@ var _ = Describe("bandwidth test", func() { return nil })).To(Succeed()) - }) 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))) return nil })).To(Succeed()) - }) 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))) return nil })).To(Succeed()) - }) 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 })).To(Succeed()) - }) }) @@ -730,7 +723,6 @@ var _ = Describe("bandwidth test", func() { Expect(qdiscs[0].(*netlink.Tbf).Limit).To(Equal(uint32(1))) return nil })).To(Succeed()) - }) 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) 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) 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) }) }) diff --git a/plugins/meta/bandwidth/bandwidth_suite_test.go b/plugins/meta/bandwidth/bandwidth_suite_test.go index 65593fb0..75ce7417 100644 --- a/plugins/meta/bandwidth/bandwidth_suite_test.go +++ b/plugins/meta/bandwidth/bandwidth_suite_test.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -24,14 +24,13 @@ import ( "strings" "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/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) { @@ -87,7 +86,7 @@ func startEchoServerInNamespace(netNS ns.NetNS) (int, *gexec.Session, error) { 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) message := string(payload) diff --git a/plugins/meta/bandwidth/ifb_creator.go b/plugins/meta/bandwidth/ifb_creator.go index 205b40a0..0037700e 100644 --- a/plugins/meta/bandwidth/ifb_creator.go +++ b/plugins/meta/bandwidth/ifb_creator.go @@ -19,9 +19,9 @@ import ( "net" "syscall" - "github.com/containernetworking/plugins/pkg/ip" - "github.com/vishvananda/netlink" + + "github.com/containernetworking/plugins/pkg/ip" ) const latencyInMillis = 25 @@ -34,7 +34,6 @@ func CreateIfb(ifbDeviceName string, mtu int) error { MTU: mtu, }, }) - if err != nil { return fmt.Errorf("adding link: %s", err) } @@ -147,10 +146,6 @@ func createTBF(rateInBits, burstInBits uint64, linkIndex int) error { return nil } -func tick2Time(tick uint32) uint32 { - return uint32(float64(tick) / float64(netlink.TickInUsec())) -} - func time2Tick(time uint32) uint32 { return uint32(float64(time) * float64(netlink.TickInUsec())) } diff --git a/plugins/meta/bandwidth/main.go b/plugins/meta/bandwidth/main.go index 2e926055..518f3624 100644 --- a/plugins/meta/bandwidth/main.go +++ b/plugins/meta/bandwidth/main.go @@ -25,24 +25,25 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/utils" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) -const maxIfbDeviceLength = 15 -const ifbDevicePrefix = "bwp" +const ( + maxIfbDeviceLength = 15 + ifbDevicePrefix = "bwp" +) // BandwidthEntry corresponds to a single entry in the bandwidth argument, // see CONVENTIONS.md type BandwidthEntry struct { - IngressRate uint64 `json:"ingressRate"` //Bandwidth rate in bps for traffic through container. 0 for no limit. If ingressRate is set, ingressBurst must also be set - IngressBurst uint64 `json:"ingressBurst"` //Bandwidth burst in bits for traffic through container. 0 for no limit. If ingressBurst is set, ingressRate must also be set + IngressRate uint64 `json:"ingressRate"` // Bandwidth rate in bps for traffic through container. 0 for no limit. If ingressRate is set, ingressBurst must also be set + IngressBurst uint64 `json:"ingressBurst"` // Bandwidth burst in bits for traffic through container. 0 for no limit. If ingressBurst is set, ingressRate must also be set - EgressRate uint64 `json:"egressRate"` //Bandwidth rate in bps for traffic through container. 0 for no limit. If egressRate is set, egressBurst must also be set - EgressBurst uint64 `json:"egressBurst"` //Bandwidth burst in bits for traffic through container. 0 for no limit. If egressBurst is set, egressRate must also be set + EgressRate uint64 `json:"egressRate"` // Bandwidth rate in bps for traffic through container. 0 for no limit. If egressRate is set, egressBurst must also be set + EgressBurst uint64 `json:"egressBurst"` // Bandwidth burst in bits for traffic through container. 0 for no limit. If egressBurst is set, egressRate must also be set } func (bw *BandwidthEntry) isZero() bool { @@ -92,7 +93,6 @@ func parseConfig(stdin []byte) (*PluginConf, error) { } return &conf, nil - } func getBandwidth(conf *PluginConf) *BandwidthEntry { @@ -104,8 +104,6 @@ func getBandwidth(conf *PluginConf) *BandwidthEntry { func validateRateAndBurst(rate, burst uint64) error { switch { - case burst < 0 || rate < 0: - return fmt.Errorf("rate and burst must be a positive integer") case burst == 0 && rate != 0: return fmt.Errorf("if rate is set, burst must also be set") case rate == 0 && burst != 0: @@ -117,8 +115,8 @@ func validateRateAndBurst(rate, burst uint64) error { return nil } -func getIfbDeviceName(networkName string, containerId string) string { - return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerId) +func getIfbDeviceName(networkName string, containerID string) string { + return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerID) } func getMTU(deviceName string) (int, error) { diff --git a/plugins/meta/firewall/firewall.go b/plugins/meta/firewall/firewall.go index 35743f45..77c39416 100644 --- a/plugins/meta/firewall/firewall.go +++ b/plugins/meta/firewall/firewall.go @@ -26,7 +26,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) diff --git a/plugins/meta/firewall/firewall_firewalld_test.go b/plugins/meta/firewall/firewall_firewalld_test.go index fea8ae87..5083d572 100644 --- a/plugins/meta/firewall/firewall_firewalld_test.go +++ b/plugins/meta/firewall/firewall_firewalld_test.go @@ -22,16 +22,15 @@ import ( "sync" "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/skel" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" - - "github.com/godbus/dbus/v5" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) const ifname = "eth0" diff --git a/plugins/meta/firewall/firewall_integ_test.go b/plugins/meta/firewall/firewall_integ_test.go index 7000f37c..ab67db2f 100644 --- a/plugins/meta/firewall/firewall_integ_test.go +++ b/plugins/meta/firewall/firewall_integ_test.go @@ -22,12 +22,13 @@ import ( "path/filepath" "strings" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/containernetworking/cni/libcni" types100 "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ns" "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. diff --git a/plugins/meta/firewall/firewall_iptables_test.go b/plugins/meta/firewall/firewall_iptables_test.go index d9d16815..9407e2f0 100644 --- a/plugins/meta/firewall/firewall_iptables_test.go +++ b/plugins/meta/firewall/firewall_iptables_test.go @@ -19,6 +19,11 @@ import ( "fmt" "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/types" "github.com/containernetworking/cni/pkg/types/040" @@ -26,13 +31,6 @@ import ( "github.com/containernetworking/cni/pkg/version" "github.com/containernetworking/plugins/pkg/ns" "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) { diff --git a/plugins/meta/firewall/firewall_suite_test.go b/plugins/meta/firewall/firewall_suite_test.go index 760bebb7..9b125b01 100644 --- a/plugins/meta/firewall/firewall_suite_test.go +++ b/plugins/meta/firewall/firewall_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestFirewall(t *testing.T) { diff --git a/plugins/meta/firewall/firewalld.go b/plugins/meta/firewall/firewalld.go index ba0c47b8..6e4b575d 100644 --- a/plugins/meta/firewall/firewalld.go +++ b/plugins/meta/firewall/firewalld.go @@ -18,8 +18,9 @@ import ( "fmt" "strings" - current "github.com/containernetworking/cni/pkg/types/100" "github.com/godbus/dbus/v5" + + current "github.com/containernetworking/cni/pkg/types/100" ) const ( diff --git a/plugins/meta/firewall/ingresspolicy.go b/plugins/meta/firewall/ingresspolicy.go index ded87732..8c27af04 100644 --- a/plugins/meta/firewall/ingresspolicy.go +++ b/plugins/meta/firewall/ingresspolicy.go @@ -19,9 +19,10 @@ package main import ( "fmt" + "github.com/coreos/go-iptables/iptables" + types100 "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/utils" - "github.com/coreos/go-iptables/iptables" ) func setupIngressPolicy(conf *FirewallNetConf, prevResult *types100.Result) error { @@ -166,7 +167,7 @@ func isolationStage2BridgeRule(bridgeName 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) } diff --git a/plugins/meta/firewall/iptables.go b/plugins/meta/firewall/iptables.go index dd5fdb38..8221d01d 100644 --- a/plugins/meta/firewall/iptables.go +++ b/plugins/meta/firewall/iptables.go @@ -21,9 +21,10 @@ import ( "fmt" "net" + "github.com/coreos/go-iptables/iptables" + current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/utils" - "github.com/coreos/go-iptables/iptables" ) 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 } @@ -211,7 +212,6 @@ type iptablesBackend struct { protos map[iptables.Protocol]*iptables.IPTables privChainName string adminChainName string - ifName string } // iptablesBackend implements the FirewallBackend interface diff --git a/plugins/meta/portmap/chain.go b/plugins/meta/portmap/chain.go index adad1e70..d7b10d5a 100644 --- a/plugins/meta/portmap/chain.go +++ b/plugins/meta/portmap/chain.go @@ -18,9 +18,10 @@ import ( "fmt" "strings" - "github.com/containernetworking/plugins/pkg/utils" "github.com/coreos/go-iptables/iptables" "github.com/mattn/go-shellwords" + + "github.com/containernetworking/plugins/pkg/utils" ) type chain struct { @@ -36,7 +37,6 @@ type chain struct { // setup idempotently creates the chain. It will not error if the chain exists. func (c *chain) setup(ipt *iptables.IPTables) error { - err := utils.EnsureChain(ipt, c.table, c.name) if err != nil { return err @@ -103,7 +103,6 @@ func (c *chain) teardown(ipt *iptables.IPTables) error { // check the chain. func (c *chain) check(ipt *iptables.IPTables) error { - exists, err := utils.ChainExists(ipt, c.table, c.name) if err != nil { return err diff --git a/plugins/meta/portmap/chain_test.go b/plugins/meta/portmap/chain_test.go index 84f49219..c693f3ff 100644 --- a/plugins/meta/portmap/chain_test.go +++ b/plugins/meta/portmap/chain_test.go @@ -20,11 +20,12 @@ import ( "runtime" "sync" - "github.com/containernetworking/plugins/pkg/ns" - "github.com/containernetworking/plugins/pkg/testutils" "github.com/coreos/go-iptables/iptables" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" ) const TABLE = "filter" // We'll monkey around here @@ -37,7 +38,6 @@ var _ = Describe("chain tests", func() { var cleanup func() beforeEach := func() { - // Save a reference to the original namespace, // Add a new NS currNs, err := ns.GetCurrentNS() @@ -83,7 +83,6 @@ var _ = Describe("chain tests", func() { ipt.DeleteChain(TABLE, tlChainName) currNs.Set() } - } It("creates and destroys a chain", func() { @@ -169,7 +168,6 @@ var _ = Describe("chain tests", func() { Expect(err).NotTo(HaveOccurred()) Expect(len(rules)).To(Equal(3)) - }) It("deletes chains idempotently", func() { @@ -233,6 +231,5 @@ var _ = Describe("chain tests", func() { Fail("Chain was not deleted") } } - }) }) diff --git a/plugins/meta/portmap/main.go b/plugins/meta/portmap/main.go index 1e6bdd11..1b5ea228 100644 --- a/plugins/meta/portmap/main.go +++ b/plugins/meta/portmap/main.go @@ -31,12 +31,12 @@ import ( "log" "net" + "golang.org/x/sys/unix" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "golang.org/x/sys/unix" - bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) diff --git a/plugins/meta/portmap/portmap.go b/plugins/meta/portmap/portmap.go index f8ca92f1..e380da93 100644 --- a/plugins/meta/portmap/portmap.go +++ b/plugins/meta/portmap/portmap.go @@ -21,10 +21,11 @@ import ( "strconv" "strings" - "github.com/containernetworking/plugins/pkg/utils" - "github.com/containernetworking/plugins/pkg/utils/sysctl" "github.com/coreos/go-iptables/iptables" "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 @@ -292,7 +293,7 @@ func fillDnatRules(c *chain, config *PortMapConf, containerNet net.IPNet) { copy(dnatRule, ruleBase) dnatRule = append(dnatRule, "-j", "DNAT", - "--to-destination", fmtIpPort(containerNet.IP, entry.ContainerPort), + "--to-destination", fmtIPPort(containerNet.IP, entry.ContainerPort), ) c.rules = append(c.rules, dnatRule) } diff --git a/plugins/meta/portmap/portmap_integ_test.go b/plugins/meta/portmap/portmap_integ_test.go index 3e544a99..f25f6f4b 100644 --- a/plugins/meta/portmap/portmap_integ_test.go +++ b/plugins/meta/portmap/portmap_integ_test.go @@ -24,15 +24,16 @@ import ( "os/exec" "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/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" "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 { diff --git a/plugins/meta/portmap/portmap_suite_test.go b/plugins/meta/portmap/portmap_suite_test.go index c9f4528f..a376f293 100644 --- a/plugins/meta/portmap/portmap_suite_test.go +++ b/plugins/meta/portmap/portmap_suite_test.go @@ -21,15 +21,14 @@ import ( "path/filepath" "strconv" "strings" - - "github.com/containernetworking/plugins/pkg/ns" + "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" - "testing" + "github.com/containernetworking/plugins/pkg/ns" ) func TestPortmap(t *testing.T) { diff --git a/plugins/meta/portmap/portmap_test.go b/plugins/meta/portmap/portmap_test.go index dcd202aa..4897fe63 100644 --- a/plugins/meta/portmap/portmap_test.go +++ b/plugins/meta/portmap/portmap_test.go @@ -17,10 +17,10 @@ package main import ( "fmt" - "github.com/containernetworking/cni/pkg/types" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + + "github.com/containernetworking/cni/pkg/types" ) var _ = Describe("portmapping configuration", func() { @@ -84,8 +84,10 @@ var _ = Describe("portmapping configuration", func() { Expect(c.Name).To(Equal("test")) n, err := types.ParseCIDR("10.0.0.2/24") + Expect(err).NotTo(HaveOccurred()) Expect(c.ContIPv4).To(Equal(*n)) n, err = types.ParseCIDR("2001:db8:1::2/64") + Expect(err).NotTo(HaveOccurred()) Expect(c.ContIPv6).To(Equal(*n)) }) @@ -199,21 +201,26 @@ var _ = Describe("portmapping configuration", func() { })) n, err := types.ParseCIDR("10.0.0.2/24") + Expect(err).NotTo(HaveOccurred()) fillDnatRules(&ch, conf, *n) Expect(ch.entryRules).To(Equal([][]string{ - {"-m", "comment", "--comment", + { + "-m", "comment", "--comment", fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID), "-m", "multiport", "-p", "tcp", "--destination-ports", "8080,8081,8083,8084,8085,8086", - "a", "b"}, - {"-m", "comment", "--comment", + "a", "b", + }, + { + "-m", "comment", "--comment", fmt.Sprintf("dnat name: \"test\" id: \"%s\"", containerID), "-m", "multiport", "-p", "udp", "--destination-ports", "8080,8082", - "a", "b"}, + "a", "b", + }, })) Expect(ch.rules).To(Equal([][]string{ @@ -245,6 +252,7 @@ var _ = Describe("portmapping configuration", func() { ch.entryRules = nil n, err = types.ParseCIDR("2001:db8::2/64") + Expect(err).NotTo(HaveOccurred()) fillDnatRules(&ch, conf, *n) Expect(ch.rules).To(Equal([][]string{ @@ -273,6 +281,7 @@ var _ = Describe("portmapping configuration", func() { conf.SNAT = &fvar n, err = types.ParseCIDR("10.0.0.2/24") + Expect(err).NotTo(HaveOccurred()) fillDnatRules(&ch, conf, *n) Expect(ch.rules).To(Equal([][]string{ {"-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) n, err := types.ParseCIDR("10.0.0.2/24") + Expect(err).NotTo(HaveOccurred()) fillDnatRules(&ch, conf, *n) Expect(ch.rules).To(Equal([][]string{ {"-p", "tcp", "--dport", "8080", "-s", "10.0.0.2/24", "-j", "PLZ-SET-MARK"}, diff --git a/plugins/meta/portmap/utils.go b/plugins/meta/portmap/utils.go index a733fdaa..e6709089 100644 --- a/plugins/meta/portmap/utils.go +++ b/plugins/meta/portmap/utils.go @@ -25,20 +25,13 @@ import ( // fmtIpPort correctly formats ip:port literals for iptables and ip6tables - // 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 { 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 // traffic. This is the one on which we disable martian filtering. func getRoutableHostIF(containerIP net.IP) string { diff --git a/plugins/meta/sbr/main.go b/plugins/meta/sbr/main.go index 7929952a..54a57d62 100644 --- a/plugins/meta/sbr/main.go +++ b/plugins/meta/sbr/main.go @@ -28,7 +28,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ns" 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 func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, error) { - if len(prevResult.IPs) == 0 { // No IP addresses; that makes no sense. Pack it in. 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, Gw: ipCfg.Gateway, Table: table, - LinkIndex: linkIndex} + LinkIndex: linkIndex, + } err = netlink.RouteAdd(&route) if err != nil { @@ -350,7 +349,6 @@ func cmdDel(args *skel.CmdArgs) error { // Tidy up the rules for the deleted interface func tidyRules(iface string) error { - // We keep on going on rule deletion error, but return the last failure. var errReturn error diff --git a/plugins/meta/sbr/sbr_linux_test.go b/plugins/meta/sbr/sbr_linux_test.go index a34aa9ff..ea428320 100644 --- a/plugins/meta/sbr/sbr_linux_test.go +++ b/plugins/meta/sbr/sbr_linux_test.go @@ -19,15 +19,14 @@ import ( "log" "net" - "github.com/containernetworking/cni/pkg/skel" - "github.com/containernetworking/plugins/pkg/ns" - "github.com/containernetworking/plugins/pkg/testutils" - + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" + "github.com/containernetworking/cni/pkg/skel" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" ) // Structures specifying state at start. @@ -114,7 +113,6 @@ func readback(targetNs ns.NetNS, devNames []string) (netStatus, error) { routes, err := netlink.RouteListFiltered(netlink.FAMILY_ALL, routeFilter, netlink.RT_FILTER_OIF|netlink.RT_FILTER_TABLE) - if err != nil { return err } @@ -218,7 +216,8 @@ func createDefaultStatus() netStatus { return netStatus{ Devices: devs, - Rules: rules} + Rules: rules, + } } var _ = Describe("sbr test", func() { @@ -293,7 +292,8 @@ var _ = Describe("sbr test", func() { netlink.Route{ Gw: net.IPv4(192, 168, 1, 1), Table: 100, - LinkIndex: expNet1.Routes[0].LinkIndex}) + LinkIndex: expNet1.Routes[0].LinkIndex, + }) Expect(len(newStatus.Rules)).To(Equal(1)) Expect(newStatus.Rules[0].Table).To(Equal(100)) @@ -367,7 +367,8 @@ var _ = Describe("sbr test", func() { preStatus.Devices[1].Routes = append(preStatus.Devices[1].Routes, netlink.Route{ Gw: net.IPv4(192, 168, 1, 1), - LinkIndex: routes[0].LinkIndex}) + LinkIndex: routes[0].LinkIndex, + }) err := setup(targetNs, preStatus) Expect(err).NotTo(HaveOccurred()) @@ -480,7 +481,8 @@ var _ = Describe("sbr test", func() { netlink.Route{ Dst: expNet1.Routes[i].Dst, Table: 101, - LinkIndex: expNet1.Routes[i].LinkIndex}) + LinkIndex: expNet1.Routes[i].LinkIndex, + }) } else { // All 192.168.1.x routes expected in table 100 expNet1.Routes[i].Table = 100 @@ -491,13 +493,15 @@ var _ = Describe("sbr test", func() { netlink.Route{ Gw: net.IPv4(192, 168, 1, 1), Table: 100, - LinkIndex: expNet1.Routes[0].LinkIndex}) + LinkIndex: expNet1.Routes[0].LinkIndex, + }) expNet1.Routes = append(expNet1.Routes, netlink.Route{ Gw: net.IPv4(192, 168, 101, 1), Table: 101, - LinkIndex: expNet1.Routes[0].LinkIndex}) + LinkIndex: expNet1.Routes[0].LinkIndex, + }) // 2 Rules will be created for each IP address. (100, 101) Expect(len(newStatus.Rules)).To(Equal(2)) @@ -514,7 +518,6 @@ var _ = Describe("sbr test", func() { devEth0 := newStatus.Devices[1] Expect(equalRoutes(expNet1.Routes, devNet1.Routes)).To(BeTrue()) Expect(equalRoutes(expEth0.Routes, devEth0.Routes)).To(BeTrue()) - }) It("fails with CNI spec versions that don't support plugin chaining", func() { @@ -537,5 +540,4 @@ var _ = Describe("sbr test", func() { _, _, err = testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) }) Expect(err).To(MatchError("This plugin must be called as chained plugin")) }) - }) diff --git a/plugins/meta/sbr/sbr_suite_test.go b/plugins/meta/sbr/sbr_suite_test.go index d8ce98b3..11e8c0cb 100644 --- a/plugins/meta/sbr/sbr_suite_test.go +++ b/plugins/meta/sbr/sbr_suite_test.go @@ -3,10 +3,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestSample(t *testing.T) { diff --git a/plugins/meta/tuning/tuning.go b/plugins/meta/tuning/tuning.go index f40543c2..e23b84f1 100644 --- a/plugins/meta/tuning/tuning.go +++ b/plugins/meta/tuning/tuning.go @@ -35,14 +35,15 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ns" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) -const defaultDataDir = "/run/cni/tuning" -const defaultAllowlistDir = "/etc/cni/tuning/" -const defaultAllowlistFile = "allowlist.conf" +const ( + defaultDataDir = "/run/cni/tuning" + defaultAllowlistDir = "/etc/cni/tuning/" + defaultAllowlistFile = "allowlist.conf" +) // TuningConf represents the network tuning configuration. type TuningConf struct { @@ -225,7 +226,7 @@ func createBackup(ifName, containerID, backupPath string, tuningConf *TuningConf } if _, err := os.Stat(backupPath); os.IsNotExist(err) { - if err = os.MkdirAll(backupPath, 0600); err != nil { + if err = os.MkdirAll(backupPath, 0o600); err != nil { return fmt.Errorf("failed to create backup directory: %v", err) } } @@ -234,7 +235,7 @@ func createBackup(ifName, containerID, backupPath string, tuningConf *TuningConf if err != nil { return fmt.Errorf("failed to marshall data for %q: %v", ifName, err) } - if err = os.WriteFile(path.Join(backupPath, containerID+"_"+ifName+".json"), data, 0600); err != nil { + if err = os.WriteFile(path.Join(backupPath, containerID+"_"+ifName+".json"), data, 0o600); err != nil { return fmt.Errorf("failed to save file %s.json: %v", ifName, err) } @@ -333,7 +334,7 @@ func cmdAdd(args *skel.CmdArgs) error { err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { for key, value := range tuningConf.SysCtl { - key = strings.Replace(key, ".", string(os.PathSeparator), -1) + key = strings.ReplaceAll(key, ".", string(os.PathSeparator)) // If the key contains `IFNAME` - substitute it with args.IfName // to allow setting sysctls on a particular interface, on which @@ -348,7 +349,7 @@ func cmdAdd(args *skel.CmdArgs) error { return fmt.Errorf("invalid net sysctl key: %q", key) } content := []byte(value) - err := os.WriteFile(fileName, content, 0644) + err := os.WriteFile(fileName, content, 0o644) if err != nil { return err } @@ -368,7 +369,7 @@ func cmdAdd(args *skel.CmdArgs) error { updateResultsMacAddr(tuningConf, args.IfName, tuningConf.Mac) } - if tuningConf.Promisc != false { + if tuningConf.Promisc { if err = changePromisc(args.IfName, true); err != nil { return err } @@ -438,7 +439,7 @@ func cmdCheck(args *skel.CmdArgs) error { err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { // Check each configured value vs what's currently in the container for key, confValue := range tuningConf.SysCtl { - fileName := filepath.Join("/proc/sys", strings.Replace(key, ".", "/", -1)) + fileName := filepath.Join("/proc/sys", strings.ReplaceAll(key, ".", "/")) contents, err := os.ReadFile(fileName) if err != nil { @@ -507,13 +508,13 @@ func validateSysctlConf(tuningConf *TuningConf) error { if !isPresent { return nil } - for sysctl, _ := range tuningConf.SysCtl { + for sysctl := range tuningConf.SysCtl { match, err := contains(sysctl, allowlist) if err != nil { return err } if !match { - return errors.New(fmt.Sprintf("Sysctl %s is not allowed. Only the following sysctls are allowed: %+v", sysctl, allowlist)) + return fmt.Errorf("Sysctl %s is not allowed. Only the following sysctls are allowed: %+v", sysctl, allowlist) } } return nil @@ -578,7 +579,7 @@ func validateSysctlConflictingKeys(data []byte) error { func validateArgs(args *skel.CmdArgs) error { if strings.Contains(args.IfName, string(os.PathSeparator)) { - return errors.New(fmt.Sprintf("Interface name (%s) contains an invalid character %s", args.IfName, string(os.PathSeparator))) + return fmt.Errorf("Interface name (%s) contains an invalid character %s", args.IfName, string(os.PathSeparator)) } return nil } diff --git a/plugins/meta/tuning/tuning_suite_test.go b/plugins/meta/tuning/tuning_suite_test.go index 654900d7..479bd970 100644 --- a/plugins/meta/tuning/tuning_suite_test.go +++ b/plugins/meta/tuning/tuning_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestTuning(t *testing.T) { diff --git a/plugins/meta/tuning/tuning_test.go b/plugins/meta/tuning/tuning_test.go index 2bad674f..ec81ee55 100644 --- a/plugins/meta/tuning/tuning_test.go +++ b/plugins/meta/tuning/tuning_test.go @@ -21,17 +21,16 @@ import ( "os" "path/filepath" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" - "golang.org/x/sys/unix" - - "github.com/vishvananda/netlink" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) func buildOneConfig(name, cniVersion string, orig *TuningConf, prevResult types.Result) (*TuningConf, []byte, error) { @@ -74,11 +73,10 @@ func buildOneConfig(name, cniVersion string, orig *TuningConf, prevResult types. } return conf, newBytes, nil - } func createSysctlAllowFile(sysctls []string) error { - err := os.MkdirAll(defaultAllowlistDir, 0755) + err := os.MkdirAll(defaultAllowlistDir, 0o755) if err != nil { return err } diff --git a/plugins/meta/vrf/main.go b/plugins/meta/vrf/main.go index e69abac7..8729bf9e 100644 --- a/plugins/meta/vrf/main.go +++ b/plugins/meta/vrf/main.go @@ -24,7 +24,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - "github.com/containernetworking/plugins/pkg/ns" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) @@ -157,6 +156,9 @@ func cmdCheck(args *skel.CmdArgs) error { return err } vrfInterfaces, err := assignedInterfaces(vrf) + if err != nil { + return err + } found := false for _, intf := range vrfInterfaces { @@ -166,10 +168,13 @@ func cmdCheck(args *skel.CmdArgs) error { } } if !found { - return fmt.Errorf("Failed to find %s associated to vrf %s", args.IfName, conf.VRFName) + return fmt.Errorf("failed to find %s associated to vrf %s", args.IfName, conf.VRFName) } return nil }) + if err != nil { + return err + } return nil } diff --git a/plugins/meta/vrf/vrf_suite_test.go b/plugins/meta/vrf/vrf_suite_test.go index 9b80fc30..bd02eb5e 100644 --- a/plugins/meta/vrf/vrf_suite_test.go +++ b/plugins/meta/vrf/vrf_suite_test.go @@ -15,10 +15,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestVRF(t *testing.T) { diff --git a/plugins/meta/vrf/vrf_test.go b/plugins/meta/vrf/vrf_test.go index 2442c328..55e94b04 100644 --- a/plugins/meta/vrf/vrf_test.go +++ b/plugins/meta/vrf/vrf_test.go @@ -18,16 +18,15 @@ import ( "encoding/json" "fmt" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/vishvananda/netlink" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" current "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/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) func buildOneConfig(name, cniVersion string, orig *VRFNetConf, prevResult types.Result) (*VRFNetConf, []byte, error) { @@ -70,7 +69,6 @@ func buildOneConfig(name, cniVersion string, orig *VRFNetConf, prevResult types. } return conf, newBytes, nil - } var _ = Describe("vrf plugin", func() { @@ -169,6 +167,7 @@ var _ = Describe("vrf plugin", func() { Expect(err).NotTo(HaveOccurred()) return nil }) + Expect(err).NotTo(HaveOccurred()) err = targetNS.Do(func(ns.NetNS) error { defer GinkgoRecover() @@ -298,6 +297,7 @@ var _ = Describe("vrf plugin", func() { link, err := netlink.LinkByName(IF0Name) Expect(err).NotTo(HaveOccurred()) addresses, err := netlink.AddrList(link, netlink.FAMILY_ALL) + Expect(err).NotTo(HaveOccurred()) Expect(len(addresses)).To(Equal(1)) Expect(addresses[0].IP.Equal(addr0.IP)).To(BeTrue()) Expect(addresses[0].Mask).To(Equal(addr0.Mask)) @@ -315,6 +315,7 @@ var _ = Describe("vrf plugin", func() { Expect(err).NotTo(HaveOccurred()) addresses, err := netlink.AddrList(link, netlink.FAMILY_ALL) + Expect(err).NotTo(HaveOccurred()) Expect(len(addresses)).To(Equal(1)) Expect(addresses[0].IP.Equal(addr1.IP)).To(BeTrue()) Expect(addresses[0].Mask).To(Equal(addr1.Mask)) @@ -343,7 +344,6 @@ var _ = Describe("vrf plugin", func() { }) Expect(err).NotTo(HaveOccurred()) }) - }, Entry("added to the same vrf", VRF0Name, VRF0Name, "10.0.0.2/24", "10.0.0.3/24"), Entry("added to different vrfs", VRF0Name, VRF1Name, "10.0.0.2/24", "10.0.0.3/24"), @@ -606,7 +606,6 @@ var _ = Describe("vrf plugin", func() { }) Expect(err).NotTo(HaveOccurred()) }) - }) var _ = Describe("unit tests", func() { @@ -703,10 +702,3 @@ func checkInterfaceOnVRF(vrfName, intfName string) { Expect(err).NotTo(HaveOccurred()) Expect(master.Attrs().Name).To(Equal(vrfName)) } - -func checkLinkHasNoMaster(intfName string) { - link, err := netlink.LinkByName(intfName) - Expect(err).NotTo(HaveOccurred()) - masterIndx := link.Attrs().MasterIndex - Expect(masterIndx).To(Equal(0)) -} diff --git a/plugins/sample/main.go b/plugins/sample/main.go index 67b03217..2cd365eb 100644 --- a/plugins/sample/main.go +++ b/plugins/sample/main.go @@ -24,7 +24,6 @@ import ( "github.com/containernetworking/cni/pkg/types" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/cni/pkg/version" - bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) diff --git a/plugins/sample/sample_linux_test.go b/plugins/sample/sample_linux_test.go index c7c038da..22066fdb 100644 --- a/plugins/sample/sample_linux_test.go +++ b/plugins/sample/sample_linux_test.go @@ -17,11 +17,12 @@ package main import ( "fmt" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/testutils" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("sample test", func() { @@ -125,5 +126,4 @@ var _ = Describe("sample test", func() { _, _, err := testutils.CmdAddWithArgs(args, func() error { return cmdAdd(args) }) Expect(err).To(MatchError("must be called as chained plugin")) }) - }) diff --git a/plugins/sample/sample_suite_test.go b/plugins/sample/sample_suite_test.go index de7b9e32..d2506fc5 100644 --- a/plugins/sample/sample_suite_test.go +++ b/plugins/sample/sample_suite_test.go @@ -3,10 +3,10 @@ package main import ( + "testing" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - "testing" ) func TestSample(t *testing.T) {