enable revive linter

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
Matthieu MOREL 2023-03-12 11:25:53 +01:00
parent 79f524689c
commit a02bf4b463
19 changed files with 68 additions and 60 deletions

View File

@ -1,3 +1,12 @@
issues:
exclude-rules:
- linters:
- revive
text: "don't use ALL_CAPS in Go names; use CamelCase"
- linters:
- revive
text: " and that stutters;"
linters: linters:
enable: enable:
- contextcheck - contextcheck
@ -8,6 +17,7 @@ linters:
- ineffassign - ineffassign
- misspell - misspell
- nonamedreturns - nonamedreturns
- revive
- staticcheck - staticcheck
disable: disable:
- errcheck - errcheck

View File

@ -176,12 +176,12 @@ var _ = Describe("Basic PTP using cnitool", func() {
By(fmt.Sprintf("sending tcp traffic to the chained, bridged, traffic shaped container on ip address '%s:%d'\n\n", chainedBridgeIP, chainedBridgeBandwidthPort)) By(fmt.Sprintf("sending tcp traffic to the chained, bridged, traffic shaped container on ip address '%s:%d'\n\n", chainedBridgeIP, chainedBridgeBandwidthPort))
runtimeWithLimit := b.Time("with chained bridge and bandwidth plugins", func() { runtimeWithLimit := b.Time("with chained bridge and bandwidth plugins", func() {
makeTcpClientInNS(hostNS.ShortName(), chainedBridgeIP, chainedBridgeBandwidthPort, packetInBytes) makeTCPClientInNS(hostNS.ShortName(), chainedBridgeIP, chainedBridgeBandwidthPort, packetInBytes)
}) })
By(fmt.Sprintf("sending tcp traffic to the basic bridged container on ip address '%s:%d'\n\n", basicBridgeIP, basicBridgePort)) By(fmt.Sprintf("sending tcp traffic to the basic bridged container on ip address '%s:%d'\n\n", basicBridgeIP, basicBridgePort))
runtimeWithoutLimit := b.Time("with basic bridged plugin", func() { runtimeWithoutLimit := b.Time("with basic bridged plugin", func() {
makeTcpClientInNS(hostNS.ShortName(), basicBridgeIP, basicBridgePort, packetInBytes) makeTCPClientInNS(hostNS.ShortName(), basicBridgeIP, basicBridgePort, packetInBytes)
}) })
Expect(runtimeWithLimit).To(BeNumerically(">", runtimeWithoutLimit+1000*time.Millisecond)) Expect(runtimeWithLimit).To(BeNumerically(">", runtimeWithoutLimit+1000*time.Millisecond))
@ -223,7 +223,7 @@ func (n Namespace) Del() {
(TestEnv{}).run("ip", "netns", "del", string(n)) (TestEnv{}).run("ip", "netns", "del", string(n))
} }
func makeTcpClientInNS(netns string, address string, port int, numBytes int) { func makeTCPClientInNS(netns string, address string, port int, numBytes int) {
payload := bytes.Repeat([]byte{'a'}, numBytes) payload := bytes.Repeat([]byte{'a'}, numBytes)
message := string(payload) message := string(payload)

View File

@ -47,13 +47,12 @@ func ParseIP(s string) *IP {
return nil return nil
} }
return newIP(ip, ipNet.Mask) 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. // ToIP will return a net.IP in standard form from this IP.

View File

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

View File

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

View File

@ -116,10 +116,10 @@ var _ = Describe("spoofcheck", func() {
}) })
func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub) { func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub) {
deleteRegularChainRulesJsonConfig, err := action.applyConfig[1].ToJSON() deleteRegularChainRulesJSONConfig, err := action.applyConfig[1].ToJSON()
ExpectWithOffset(1, err).NotTo(HaveOccurred()) ExpectWithOffset(1, err).NotTo(HaveOccurred())
expectedDeleteRegularChainRulesJsonConfig := ` expectedDeleteRegularChainRulesJSONConfig := `
{"nftables": [ {"nftables": [
{"delete": {"chain": { {"delete": {"chain": {
"family": "bridge", "family": "bridge",
@ -133,14 +133,14 @@ func assertExpectedRegularChainsDeletionInTeardownConfig(action configurerStub)
}}} }}}
]}` ]}`
ExpectWithOffset(1, string(deleteRegularChainRulesJsonConfig)).To(MatchJSON(expectedDeleteRegularChainRulesJsonConfig)) ExpectWithOffset(1, string(deleteRegularChainRulesJSONConfig)).To(MatchJSON(expectedDeleteRegularChainRulesJSONConfig))
} }
func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub) { func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub) {
deleteBaseChainRuleJsonConfig, err := action.applyConfig[0].ToJSON() deleteBaseChainRuleJSONConfig, err := action.applyConfig[0].ToJSON()
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
expectedDeleteIfaceMatchRuleJsonConfig := ` expectedDeleteIfaceMatchRuleJSONConfig := `
{"nftables": [ {"nftables": [
{"delete": {"rule": { {"delete": {"rule": {
"family": "bridge", "family": "bridge",
@ -157,7 +157,7 @@ func assertExpectedBaseChainRuleDeletionInTeardownConfig(action configurerStub)
"comment": "macspoofchk-container99-net1" "comment": "macspoofchk-container99-net1"
}}} }}}
]}` ]}`
Expect(string(deleteBaseChainRuleJsonConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJsonConfig)) Expect(string(deleteBaseChainRuleJSONConfig)).To(MatchJSON(expectedDeleteIfaceMatchRuleJSONConfig))
} }
func rowConfigWithRulesOnly() string { func rowConfigWithRulesOnly() string {

View File

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

View File

@ -209,7 +209,7 @@ func (l *DHCPLease) Check() {
l.check <- struct{}{} l.check <- struct{}{}
} }
func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options { func (l *DHCPLease) getOptionsWithClientID() dhcp4.Options {
opts := make(dhcp4.Options) opts := make(dhcp4.Options)
opts[dhcp4.OptionClientIdentifier] = []byte(l.clientID) opts[dhcp4.OptionClientIdentifier] = []byte(l.clientID)
// client identifier's first byte is "type" // client identifier's first byte is "type"
@ -220,7 +220,7 @@ func (l *DHCPLease) getOptionsWithClientId() dhcp4.Options {
} }
func (l *DHCPLease) getAllOptions() dhcp4.Options { func (l *DHCPLease) getAllOptions() dhcp4.Options {
opts := l.getOptionsWithClientId() opts := l.getOptionsWithClientID()
for k, v := range l.optsProviding { for k, v := range l.optsProviding {
opts[k] = v opts[k] = v
@ -397,7 +397,7 @@ func (l *DHCPLease) release() error {
} }
defer c.Close() defer c.Close()
opts := l.getOptionsWithClientId() opts := l.getOptionsWithClientID()
if err = DhcpRelease(c, *l.ack, opts); err != nil { if err = DhcpRelease(c, *l.ack, opts); err != nil {
return fmt.Errorf("failed to send DHCPRELEASE") return fmt.Errorf("failed to send DHCPRELEASE")
@ -427,9 +427,9 @@ func (l *DHCPLease) Routes() []*types.Route {
// RFC 3442 states that if Classless Static Routes (option 121) // RFC 3442 states that if Classless Static Routes (option 121)
// exist, we ignore Static Routes (option 33) and the Router/Gateway. // exist, we ignore Static Routes (option 33) and the Router/Gateway.
opt121_routes := parseCIDRRoutes(l.opts) opt121Routes := parseCIDRRoutes(l.opts)
if len(opt121_routes) > 0 { if len(opt121Routes) > 0 {
return append(routes, opt121_routes...) return append(routes, opt121Routes...)
} }
// Append Static Routes // Append Static Routes
@ -451,7 +451,7 @@ func jitter(span time.Duration) time.Duration {
} }
func backoffRetry(resendMax time.Duration, f func() (*dhcp4.Packet, error)) (*dhcp4.Packet, error) { func backoffRetry(resendMax time.Duration, f func() (*dhcp4.Packet, error)) (*dhcp4.Packet, error) {
var baseDelay time.Duration = resendDelay0 baseDelay := resendDelay0
var sleepTime time.Duration var sleepTime time.Duration
fastRetryLimit := resendFastMax fastRetryLimit := resendFastMax
for { for {

View File

@ -196,7 +196,7 @@ func (i *RangeIter) Next() (*net.IPNet, net.IP) {
// If we've reached the end of this range, we need to advance the range // If we've reached the end of this range, we need to advance the range
// RangeEnd is inclusive as well // RangeEnd is inclusive as well
if i.cur.Equal(r.RangeEnd) { if i.cur.Equal(r.RangeEnd) {
i.rangeIdx += 1 i.rangeIdx++
i.rangeIdx %= len(*i.rangeset) i.rangeIdx %= len(*i.rangeset)
r = (*i.rangeset)[i.rangeIdx] r = (*i.rangeset)[i.rangeIdx]

View File

@ -46,8 +46,8 @@ func cmdCheck(args *skel.CmdArgs) error {
} }
defer store.Close() defer store.Close()
containerIpFound := store.FindByID(args.ContainerID, args.IfName) containerIPFound := store.FindByID(args.ContainerID, args.IfName)
if !containerIpFound { if !containerIPFound {
return fmt.Errorf("host-local: Failed to find address added by container %v", args.ContainerID) return fmt.Errorf("host-local: Failed to find address added by container %v", args.ContainerID)
} }

View File

@ -299,8 +299,8 @@ func ensureBridge(brName string, mtu int, promiscMode, vlanFiltering bool) (*net
return br, nil return br, nil
} }
func ensureVlanInterface(br *netlink.Bridge, vlanId int) (netlink.Link, error) { func ensureVlanInterface(br *netlink.Bridge, vlanID int) (netlink.Link, error) {
name := fmt.Sprintf("%s.%d", br.Name, vlanId) name := fmt.Sprintf("%s.%d", br.Name, vlanID)
brGatewayVeth, err := netlink.LinkByName(name) brGatewayVeth, err := netlink.LinkByName(name)
if err != nil { if err != nil {
@ -313,7 +313,7 @@ func ensureVlanInterface(br *netlink.Bridge, vlanId int) (netlink.Link, error) {
return nil, fmt.Errorf("faild to find host namespace: %v", err) return nil, fmt.Errorf("faild to find host namespace: %v", err)
} }
_, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanId, "") _, brGatewayIface, err := setupVeth(hostNS, br, name, br.MTU, false, vlanID, "")
if err != nil { if err != nil {
return nil, fmt.Errorf("faild to create vlan gateway %q: %v", name, err) return nil, fmt.Errorf("faild to create vlan gateway %q: %v", name, err)
} }
@ -406,7 +406,7 @@ func enableIPForward(family int) error {
} }
func cmdAdd(args *skel.CmdArgs) error { func cmdAdd(args *skel.CmdArgs) error {
var success bool = false success := false
n, cniVersion, err := loadNetConf(args.StdinData, args.Args) n, cniVersion, err := loadNetConf(args.StdinData, args.Args)
if err != nil { if err != nil {
@ -420,7 +420,7 @@ func cmdAdd(args *skel.CmdArgs) error {
} }
if n.HairpinMode && n.PromiscMode { if n.HairpinMode && n.PromiscMode {
return fmt.Errorf("cannot set hairpin mode and promiscuous mode at the same time.") return fmt.Errorf("cannot set hairpin mode and promiscuous mode at the same time")
} }
br, brInterface, err := setupBridge(n) br, brInterface, err := setupBridge(n)

View File

@ -410,9 +410,9 @@ func countIPAMIPs(path string) (int, error) {
return count, nil return count, nil
} }
func checkVlan(vlanId int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool { func checkVlan(vlanID int, bridgeVlanInfo []*nl.BridgeVlanInfo) bool {
for _, vlan := range bridgeVlanInfo { for _, vlan := range bridgeVlanInfo {
if vlan.Vid == uint16(vlanId) { if vlan.Vid == uint16(vlanID) {
return true return true
} }
} }

View File

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

View File

@ -46,7 +46,7 @@ type Net struct {
CNIVersion string `json:"cniVersion"` CNIVersion string `json:"cniVersion"`
Type string `json:"type,omitempty"` Type string `json:"type,omitempty"`
Master string `json:"master"` Master string `json:"master"`
VlanId int `json:"vlanId"` VlanID int `json:"vlanId"`
MTU int `json:"mtu"` MTU int `json:"mtu"`
IPAM *allocator.IPAMConfig `json:"ipam"` IPAM *allocator.IPAMConfig `json:"ipam"`
DNS types.DNS `json:"dns"` DNS types.DNS `json:"dns"`
@ -249,7 +249,7 @@ var _ = Describe("vlan Operations", func() {
Type: "vlan", Type: "vlan",
}, },
Master: masterInterface, Master: masterInterface,
VlanId: 33, VlanID: 33,
MTU: 1500, MTU: 1500,
LinkContNs: isInContainer, LinkContNs: isInContainer,
} }
@ -285,7 +285,7 @@ var _ = Describe("vlan Operations", func() {
Type: "vlan", Type: "vlan",
}, },
Master: masterInterface, Master: masterInterface,
VlanId: 33, VlanID: 33,
LinkContNs: isInContainer, LinkContNs: isInContainer,
} }

View File

@ -1027,7 +1027,7 @@ var _ = Describe("bandwidth test", func() {
result, err := types100.GetResult(containerWithTbfRes) result, err := types100.GetResult(containerWithTbfRes)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
makeTcpClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithTbf, packetInBytes) makeTCPClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithTbf, packetInBytes)
}) })
}) })
@ -1036,7 +1036,7 @@ var _ = Describe("bandwidth test", func() {
result, err := types100.GetResult(containerWithoutTbfRes) result, err := types100.GetResult(containerWithoutTbfRes)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
makeTcpClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithoutTbf, packetInBytes) makeTCPClientInNS(hostNs.Path(), result.IPs[0].Address.IP.String(), portServerWithoutTbf, packetInBytes)
}) })
}) })

View File

@ -86,7 +86,7 @@ func startEchoServerInNamespace(netNS ns.NetNS) (int, *gexec.Session, error) {
return port, session, nil return port, session, nil
} }
func makeTcpClientInNS(netns string, address string, port int, numBytes int) { func makeTCPClientInNS(netns string, address string, port int, numBytes int) {
payload := bytes.Repeat([]byte{'a'}, numBytes) payload := bytes.Repeat([]byte{'a'}, numBytes)
message := string(payload) message := string(payload)

View File

@ -115,8 +115,8 @@ func validateRateAndBurst(rate, burst uint64) error {
return nil return nil
} }
func getIfbDeviceName(networkName string, containerId string) string { func getIfbDeviceName(networkName string, containerID string) string {
return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerId) return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerID)
} }
func getMTU(deviceName string) (int, error) { func getMTU(deviceName string) (int, error) {

View File

@ -293,7 +293,7 @@ func fillDnatRules(c *chain, config *PortMapConf, containerNet net.IPNet) {
copy(dnatRule, ruleBase) copy(dnatRule, ruleBase)
dnatRule = append(dnatRule, dnatRule = append(dnatRule,
"-j", "DNAT", "-j", "DNAT",
"--to-destination", fmtIpPort(containerNet.IP, entry.ContainerPort), "--to-destination", fmtIPPort(containerNet.IP, entry.ContainerPort),
) )
c.rules = append(c.rules, dnatRule) c.rules = append(c.rules, dnatRule)
} }

View File

@ -25,7 +25,7 @@ import (
// fmtIpPort correctly formats ip:port literals for iptables and ip6tables - // fmtIpPort correctly formats ip:port literals for iptables and ip6tables -
// need to wrap v6 literals in a [] // need to wrap v6 literals in a []
func fmtIpPort(ip net.IP, port int) string { func fmtIPPort(ip net.IP, port int) string {
if ip.To4() == nil { if ip.To4() == nil {
return fmt.Sprintf("[%s]:%d", ip.String(), port) return fmt.Sprintf("[%s]:%d", ip.String(), port)
} }