libnetwork: fix lint errors

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
This commit is contained in:
Paul Holzinger 2021-12-17 14:17:32 +01:00
parent 002673d22f
commit 4fcb18dca7
23 changed files with 107 additions and 97 deletions

View File

@ -116,3 +116,11 @@ linters-settings:
- unnecessaryBlock - unnecessaryBlock
gocyclo: gocyclo:
min-complexity: 35 min-complexity: 35
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- dupl

View File

@ -76,7 +76,7 @@ func createNetworkFromCNIConfigList(conf *libcni.NetworkConfigList, confPath str
network.Options["vlan"] = strconv.Itoa(bridge.Vlan) network.Options["vlan"] = strconv.Itoa(bridge.Vlan)
} }
err = convertIPAMConfToNetwork(&network, bridge.IPAM, confPath) err = convertIPAMConfToNetwork(&network, &bridge.IPAM, confPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -98,7 +98,7 @@ func createNetworkFromCNIConfigList(conf *libcni.NetworkConfigList, confPath str
network.Options["mode"] = vlan.Mode network.Options["mode"] = vlan.Mode
} }
err = convertIPAMConfToNetwork(&network, vlan.IPAM, confPath) err = convertIPAMConfToNetwork(&network, &vlan.IPAM, confPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -126,7 +126,7 @@ func findPluginByName(plugins []*libcni.NetworkConfig, name string) bool {
// convertIPAMConfToNetwork converts A cni IPAMConfig to libpod network subnets. // convertIPAMConfToNetwork converts A cni IPAMConfig to libpod network subnets.
// It returns an array of subnets and an extra bool if dhcp is configured. // It returns an array of subnets and an extra bool if dhcp is configured.
func convertIPAMConfToNetwork(network *types.Network, ipam ipamConfig, confPath string) error { func convertIPAMConfToNetwork(network *types.Network, ipam *ipamConfig, confPath string) error {
if ipam.PluginType == types.DHCPIPAMDriver { if ipam.PluginType == types.DHCPIPAMDriver {
network.IPAMOptions["driver"] = types.DHCPIPAMDriver network.IPAMOptions["driver"] = types.DHCPIPAMDriver
return nil return nil
@ -288,7 +288,7 @@ func (n *cniNetwork) createCNIConfigListFromNetwork(network *types.Network, writ
switch network.Driver { switch network.Driver {
case types.BridgeNetworkDriver: case types.BridgeNetworkDriver:
bridge := newHostLocalBridge(network.NetworkInterface, isGateway, ipMasq, mtu, vlan, ipamConf) bridge := newHostLocalBridge(network.NetworkInterface, isGateway, ipMasq, mtu, vlan, &ipamConf)
plugins = append(plugins, bridge, newPortMapPlugin(), newFirewallPlugin(), newTuningPlugin()) plugins = append(plugins, bridge, newPortMapPlugin(), newFirewallPlugin(), newTuningPlugin())
// if we find the dnsname plugin we add configuration for it // if we find the dnsname plugin we add configuration for it
if hasDNSNamePlugin(n.cniPluginDirs) && network.DNSEnabled { if hasDNSNamePlugin(n.cniPluginDirs) && network.DNSEnabled {
@ -297,10 +297,10 @@ func (n *cniNetwork) createCNIConfigListFromNetwork(network *types.Network, writ
} }
case types.MacVLANNetworkDriver: case types.MacVLANNetworkDriver:
plugins = append(plugins, newVLANPlugin(types.MacVLANNetworkDriver, network.NetworkInterface, vlanPluginMode, mtu, ipamConf)) plugins = append(plugins, newVLANPlugin(types.MacVLANNetworkDriver, network.NetworkInterface, vlanPluginMode, mtu, &ipamConf))
case types.IPVLANNetworkDriver: case types.IPVLANNetworkDriver:
plugins = append(plugins, newVLANPlugin(types.IPVLANNetworkDriver, network.NetworkInterface, vlanPluginMode, mtu, ipamConf)) plugins = append(plugins, newVLANPlugin(types.IPVLANNetworkDriver, network.NetworkInterface, vlanPluginMode, mtu, &ipamConf))
default: default:
return nil, "", errors.Errorf("driver %q is not supported by cni", network.Driver) return nil, "", errors.Errorf("driver %q is not supported by cni", network.Driver)

View File

@ -87,7 +87,7 @@ func (e *cniExec) ExecPlugin(ctx context.Context, pluginPath string, stdinData [
} }
// annotatePluginError parses the common cni plugin error json. // annotatePluginError parses the common cni plugin error json.
func annotatePluginError(err error, plugin string, stdout []byte, stderr []byte) error { func annotatePluginError(err error, plugin string, stdout, stderr []byte) error {
pluginName := filepath.Base(plugin) pluginName := filepath.Base(plugin)
emsg := cniPluginError{ emsg := cniPluginError{
plugin: pluginName, plugin: pluginName,

View File

@ -25,11 +25,10 @@ func TestCni(t *testing.T) {
RunSpecs(t, "CNI Suite") RunSpecs(t, "CNI Suite")
} }
func getNetworkInterface(cniConfDir string, machine bool) (types.ContainerNetwork, error) { func getNetworkInterface(cniConfDir string) (types.ContainerNetwork, error) {
return cni.NewCNINetworkInterface(cni.InitConfig{ return cni.NewCNINetworkInterface(&cni.InitConfig{
CNIConfigDir: cniConfDir, CNIConfigDir: cniConfDir,
CNIPluginDirs: cniPluginDirs, CNIPluginDirs: cniPluginDirs,
IsMachine: machine,
LockFile: filepath.Join(cniConfDir, "cni.lock"), LockFile: filepath.Join(cniConfDir, "cni.lock"),
}) })
} }

View File

@ -133,7 +133,7 @@ func newNcList(name, version string, labels, options map[string]string) ncList {
} }
// newHostLocalBridge creates a new LocalBridge for host-local // newHostLocalBridge creates a new LocalBridge for host-local
func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu int, vlan int, ipamConf ipamConfig) *hostLocalBridge { func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu, vlan int, ipamConf *ipamConfig) *hostLocalBridge {
caps := make(map[string]bool) caps := make(map[string]bool)
caps["ips"] = true caps["ips"] = true
bridge := hostLocalBridge{ bridge := hostLocalBridge{
@ -144,7 +144,7 @@ func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu int, vlan int,
MTU: mtu, MTU: mtu,
HairpinMode: true, HairpinMode: true,
Vlan: vlan, Vlan: vlan,
IPAM: ipamConf, IPAM: *ipamConf,
} }
// if we use host-local set the ips cap to ensure we can set static ips via runtime config // if we use host-local set the ips cap to ensure we can set static ips via runtime config
if ipamConf.PluginType == types.HostLocalIPAMDriver { if ipamConf.PluginType == types.HostLocalIPAMDriver {
@ -255,10 +255,10 @@ func hasDNSNamePlugin(paths []string) bool {
} }
// newVLANPlugin creates a macvlanconfig with a given device name // newVLANPlugin creates a macvlanconfig with a given device name
func newVLANPlugin(pluginType, device, mode string, mtu int, ipam ipamConfig) VLANConfig { func newVLANPlugin(pluginType, device, mode string, mtu int, ipam *ipamConfig) VLANConfig {
m := VLANConfig{ m := VLANConfig{
PluginType: pluginType, PluginType: pluginType,
IPAM: ipam, IPAM: *ipam,
} }
if mtu > 0 { if mtu > 0 {
m.MTU = mtu m.MTU = mtu

View File

@ -16,6 +16,7 @@ import (
// NetworkCreate will take a partial filled Network and fill the // NetworkCreate will take a partial filled Network and fill the
// missing fields. It creates the Network and returns the full Network. // missing fields. It creates the Network and returns the full Network.
// nolint:gocritic
func (n *cniNetwork) NetworkCreate(net types.Network) (types.Network, error) { func (n *cniNetwork) NetworkCreate(net types.Network) (types.Network, error) {
n.lock.Lock() n.lock.Lock()
defer n.lock.Unlock() defer n.lock.Unlock()
@ -23,7 +24,7 @@ func (n *cniNetwork) NetworkCreate(net types.Network) (types.Network, error) {
if err != nil { if err != nil {
return types.Network{}, err return types.Network{}, err
} }
network, err := n.networkCreate(net, false) network, err := n.networkCreate(&net, false)
if err != nil { if err != nil {
return types.Network{}, err return types.Network{}, err
} }
@ -34,7 +35,7 @@ func (n *cniNetwork) NetworkCreate(net types.Network) (types.Network, error) {
// networkCreate will fill out the given network struct and return the new network entry. // networkCreate will fill out the given network struct and return the new network entry.
// If defaultNet is true it will not validate against used subnets and it will not write the cni config to disk. // If defaultNet is true it will not validate against used subnets and it will not write the cni config to disk.
func (n *cniNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*network, error) { func (n *cniNetwork) networkCreate(newNetwork *types.Network, defaultNet bool) (*network, error) {
// if no driver is set use the default one // if no driver is set use the default one
if newNetwork.Driver == "" { if newNetwork.Driver == "" {
newNetwork.Driver = types.DefaultNetworkDriver newNetwork.Driver = types.DefaultNetworkDriver
@ -46,7 +47,7 @@ func (n *cniNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*
return nil, errors.Wrap(types.ErrInvalidArg, "ID can not be set for network create") return nil, errors.Wrap(types.ErrInvalidArg, "ID can not be set for network create")
} }
err := internalutil.CommonNetworkCreate(n, &newNetwork) err := internalutil.CommonNetworkCreate(n, newNetwork)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -68,12 +69,12 @@ func (n *cniNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*
switch newNetwork.Driver { switch newNetwork.Driver {
case types.BridgeNetworkDriver: case types.BridgeNetworkDriver:
err = internalutil.CreateBridge(n, &newNetwork, usedNetworks) err = internalutil.CreateBridge(n, newNetwork, usedNetworks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
case types.MacVLANNetworkDriver, types.IPVLANNetworkDriver: case types.MacVLANNetworkDriver, types.IPVLANNetworkDriver:
err = createIPMACVLAN(&newNetwork) err = createIPMACVLAN(newNetwork)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -81,7 +82,7 @@ func (n *cniNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*
return nil, errors.Wrapf(types.ErrInvalidArg, "unsupported driver %s", newNetwork.Driver) return nil, errors.Wrapf(types.ErrInvalidArg, "unsupported driver %s", newNetwork.Driver)
} }
err = internalutil.ValidateSubnets(&newNetwork, usedNetworks) err = internalutil.ValidateSubnets(newNetwork, usedNetworks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -95,11 +96,11 @@ func (n *cniNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*
newNetwork.DNSEnabled = false newNetwork.DNSEnabled = false
} }
cniConf, path, err := n.createCNIConfigListFromNetwork(&newNetwork, !defaultNet) cniConf, path, err := n.createCNIConfigListFromNetwork(newNetwork, !defaultNet)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &network{cniNet: cniConf, libpodNet: &newNetwork, filename: path}, nil return &network{cniNet: cniConf, libpodNet: newNetwork, filename: path}, nil
} }
// NetworkRemove will remove the Network with the given name or ID. // NetworkRemove will remove the Network with the given name or ID.

View File

@ -10,13 +10,12 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
gomegaTypes "github.com/onsi/gomega/types" gomegaTypes "github.com/onsi/gomega/types"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
) )
var _ = Describe("Config", func() { var _ = Describe("Config", func() {
@ -39,7 +38,7 @@ var _ = Describe("Config", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
var err error var err error
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
if err != nil { if err != nil {
Fail("Failed to create NewCNINetworkInterface") Fail("Failed to create NewCNINetworkInterface")
} }
@ -111,7 +110,7 @@ var _ = Describe("Config", func() {
Expect(network2).To(Equal(network1)) Expect(network2).To(Equal(network1))
// create a new interface to force a config load from disk // create a new interface to force a config load from disk
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
network2, err = libpodNet.NetworkInspect(network1.Name) network2, err = libpodNet.NetworkInspect(network1.Name)
@ -351,7 +350,7 @@ var _ = Describe("Config", func() {
grepInFile(path, `"mode": "`+mode+`"`) grepInFile(path, `"mode": "`+mode+`"`)
// reload configs from disk // reload configs from disk
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
network2, err := libpodNet.NetworkInspect(network1.Name) network2, err := libpodNet.NetworkInspect(network1.Name)
@ -417,7 +416,7 @@ var _ = Describe("Config", func() {
Expect(network1.Subnets[0].LeaseRange).To(BeNil()) Expect(network1.Subnets[0].LeaseRange).To(BeNil())
// reload configs from disk // reload configs from disk
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
// check the the networks are identical // check the the networks are identical
network2, err := libpodNet.NetworkInspect(network1.Name) network2, err := libpodNet.NetworkInspect(network1.Name)
@ -667,7 +666,7 @@ var _ = Describe("Config", func() {
Expect(network1.Subnets[0].LeaseRange.EndIP.String()).To(Equal(endIP)) Expect(network1.Subnets[0].LeaseRange.EndIP.String()).To(Equal(endIP))
// create a new interface to force a config load from disk // create a new interface to force a config load from disk
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
network1, err = libpodNet.NetworkInspect(network1.Name) network1, err = libpodNet.NetworkInspect(network1.Name)
@ -1364,7 +1363,7 @@ var _ = Describe("Config", func() {
}) })
func grepInFile(path string, match string) { func grepInFile(path, match string) {
data, err := ioutil.ReadFile(path) data, err := ioutil.ReadFile(path)
ExpectWithOffset(1, err).To(BeNil()) ExpectWithOffset(1, err).To(BeNil())
ExpectWithOffset(1, string(data)).To(ContainSubstring(match)) ExpectWithOffset(1, string(data)).To(ContainSubstring(match))

View File

@ -70,7 +70,7 @@ type InitConfig struct {
// NewCNINetworkInterface creates the ContainerNetwork interface for the CNI backend. // NewCNINetworkInterface creates the ContainerNetwork interface for the CNI backend.
// Note: The networks are not loaded from disk until a method is called. // Note: The networks are not loaded from disk until a method is called.
func NewCNINetworkInterface(conf InitConfig) (types.ContainerNetwork, error) { func NewCNINetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) {
// TODO: consider using a shared memory lock // TODO: consider using a shared memory lock
lock, err := lockfile.GetLockfile(conf.LockFile) lock, err := lockfile.GetLockfile(conf.LockFile)
if err != nil { if err != nil {
@ -203,7 +203,7 @@ func (n *cniNetwork) createDefaultNetwork() (*network, error) {
{Subnet: n.defaultSubnet}, {Subnet: n.defaultSubnet},
}, },
} }
return n.networkCreate(net, true) return n.networkCreate(&net, true)
} }
// getNetwork will lookup a network by name or ID. It returns an // getNetwork will lookup a network by name or ID. It returns an

View File

@ -69,8 +69,9 @@ func (n *cniNetwork) Setup(namespacePath string, options types.SetupOptions) (ma
results := make(map[string]types.StatusBlock, len(options.Networks)) results := make(map[string]types.StatusBlock, len(options.Networks))
for name, netOpts := range options.Networks { for name, netOpts := range options.Networks {
netOpts := netOpts
network := n.networks[name] network := n.networks[name]
rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, netOpts) rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, &netOpts)
// If we have more than one static ip we need parse the ips via runtime config, // If we have more than one static ip we need parse the ips via runtime config,
// make sure to add the ips capability to the first plugin otherwise it doesn't get the ips // make sure to add the ips capability to the first plugin otherwise it doesn't get the ips
@ -157,7 +158,7 @@ func CNIResultToStatus(res cnitypes.Result) (types.StatusBlock, error) {
return result, nil return result, nil
} }
func getRuntimeConfig(netns, conName, conID, networkName string, ports []cniPortMapEntry, opts types.PerNetworkOptions) *libcni.RuntimeConf { func getRuntimeConfig(netns, conName, conID, networkName string, ports []cniPortMapEntry, opts *types.PerNetworkOptions) *libcni.RuntimeConf {
rt := &libcni.RuntimeConf{ rt := &libcni.RuntimeConf{
ContainerID: conID, ContainerID: conID,
NetNS: netns, NetNS: netns,
@ -230,7 +231,8 @@ func (n *cniNetwork) teardown(namespacePath string, options types.TeardownOption
var multiErr *multierror.Error var multiErr *multierror.Error
for name, netOpts := range options.Networks { for name, netOpts := range options.Networks {
rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, netOpts) netOpts := netOpts
rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, &netOpts)
cniConfList, newRt, err := getCachedNetworkConfig(n.cniConf, name, rt) cniConfList, newRt, err := getCachedNetworkConfig(n.cniConf, name, rt)
if err == nil { if err == nil {

View File

@ -24,16 +24,15 @@ import (
"time" "time"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/netns"
"github.com/containers/storage/pkg/stringid"
"github.com/containers/storage/pkg/unshare"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/netns"
"github.com/containers/storage/pkg/stringid"
"github.com/containers/storage/pkg/unshare"
) )
var _ = Describe("run CNI", func() { var _ = Describe("run CNI", func() {
@ -98,7 +97,7 @@ var _ = Describe("run CNI", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
var err error var err error
libpodNet, err = getNetworkInterface(cniConfDir, false) libpodNet, err = getNetworkInterface(cniConfDir)
if err != nil { if err != nil {
Fail("Failed to create NewCNINetworkInterface") Fail("Failed to create NewCNINetworkInterface")
} }
@ -141,7 +140,7 @@ var _ = Describe("run CNI", func() {
Expect(res[defNet].DNSSearchDomains).To(BeEmpty()) Expect(res[defNet].DNSSearchDomains).To(BeEmpty())
// reload the interface so the networks are reload from disk // reload the interface so the networks are reload from disk
libpodNet, err := getNetworkInterface(cniConfDir, false) libpodNet, err := getNetworkInterface(cniConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
err = libpodNet.Teardown(netNSContainer.Path(), types.TeardownOptions(setupOpts)) err = libpodNet.Teardown(netNSContainer.Path(), types.TeardownOptions(setupOpts))
@ -398,7 +397,7 @@ var _ = Describe("run CNI", func() {
i, err := net.InterfaceByName(intName1) i, err := net.InterfaceByName(intName1)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
Expect(i.Name).To(Equal(intName1)) Expect(i.Name).To(Equal(intName1))
Expect(i.HardwareAddr).To(Equal((net.HardwareAddr)(macInt1))) Expect(i.HardwareAddr).To(Equal(net.HardwareAddr(macInt1)))
addrs, err := i.Addrs() addrs, err := i.Addrs()
Expect(err).To(BeNil()) Expect(err).To(BeNil())
subnet := &net.IPNet{ subnet := &net.IPNet{

View File

@ -60,7 +60,7 @@ func getRandomIPv6Subnet() (net.IPNet, error) {
// read 8 random bytes // read 8 random bytes
_, err := rand.Read(ip) _, err := rand.Read(ip)
if err != nil { if err != nil {
return net.IPNet{}, nil return net.IPNet{}, err
} }
// first byte must be FD as per RFC3879 // first byte must be FD as per RFC3879
ip[0] = 0xfd ip[0] = 0xfd

View File

@ -23,24 +23,24 @@ func ValidateSubnet(s *types.Subnet, addGateway bool, usedNetworks []*net.IPNet)
// Reparse to ensure subnet is valid. // Reparse to ensure subnet is valid.
// Do not use types.ParseCIDR() because we want the ip to be // Do not use types.ParseCIDR() because we want the ip to be
// the network address and not a random ip in the subnet. // the network address and not a random ip in the subnet.
_, net, err := net.ParseCIDR(s.Subnet.String()) _, n, err := net.ParseCIDR(s.Subnet.String())
if err != nil { if err != nil {
return errors.Wrap(err, "subnet invalid") return errors.Wrap(err, "subnet invalid")
} }
// check that the new subnet does not conflict with existing ones // check that the new subnet does not conflict with existing ones
if NetworkIntersectsWithNetworks(net, usedNetworks) { if NetworkIntersectsWithNetworks(n, usedNetworks) {
return errors.Errorf("subnet %s is already used on the host or by another config", net.String()) return errors.Errorf("subnet %s is already used on the host or by another config", n.String())
} }
s.Subnet = types.IPNet{IPNet: *net} s.Subnet = types.IPNet{IPNet: *n}
if s.Gateway != nil { if s.Gateway != nil {
if !s.Subnet.Contains(s.Gateway) { if !s.Subnet.Contains(s.Gateway) {
return errors.Errorf("gateway %s not in subnet %s", s.Gateway, &s.Subnet) return errors.Errorf("gateway %s not in subnet %s", s.Gateway, &s.Subnet)
} }
util.NormalizeIP(&s.Gateway) util.NormalizeIP(&s.Gateway)
} else if addGateway { } else if addGateway {
ip, err := util.FirstIPInSubnet(net) ip, err := util.FirstIPInSubnet(n)
if err != nil { if err != nil {
return err return err
} }
@ -91,11 +91,12 @@ func ValidateSetupOptions(n NetUtil, namespacePath string, options types.SetupOp
return errors.New("must specify at least one network") return errors.New("must specify at least one network")
} }
for name, netOpts := range options.Networks { for name, netOpts := range options.Networks {
netOpts := netOpts
network, err := n.Network(name) network, err := n.Network(name)
if err != nil { if err != nil {
return err return err
} }
err = validatePerNetworkOpts(network, netOpts) err = validatePerNetworkOpts(network, &netOpts)
if err != nil { if err != nil {
return err return err
} }
@ -104,7 +105,7 @@ func ValidateSetupOptions(n NetUtil, namespacePath string, options types.SetupOp
} }
// validatePerNetworkOpts checks that all given static ips are in a subnet on this network // validatePerNetworkOpts checks that all given static ips are in a subnet on this network
func validatePerNetworkOpts(network *types.Network, netOpts types.PerNetworkOptions) error { func validatePerNetworkOpts(network *types.Network, netOpts *types.PerNetworkOptions) error {
if netOpts.InterfaceName == "" { if netOpts.InterfaceName == "" {
return errors.Errorf("interface name on network %s is empty", network.Name) return errors.Errorf("interface name on network %s is empty", network.Name)
} }

View File

@ -18,6 +18,7 @@ import (
// NetworkCreate will take a partial filled Network and fill the // NetworkCreate will take a partial filled Network and fill the
// missing fields. It creates the Network and returns the full Network. // missing fields. It creates the Network and returns the full Network.
// nolint:gocritic
func (n *netavarkNetwork) NetworkCreate(net types.Network) (types.Network, error) { func (n *netavarkNetwork) NetworkCreate(net types.Network) (types.Network, error) {
n.lock.Lock() n.lock.Lock()
defer n.lock.Unlock() defer n.lock.Unlock()
@ -25,7 +26,7 @@ func (n *netavarkNetwork) NetworkCreate(net types.Network) (types.Network, error
if err != nil { if err != nil {
return types.Network{}, err return types.Network{}, err
} }
network, err := n.networkCreate(net, false) network, err := n.networkCreate(&net, false)
if err != nil { if err != nil {
return types.Network{}, err return types.Network{}, err
} }
@ -34,7 +35,7 @@ func (n *netavarkNetwork) NetworkCreate(net types.Network) (types.Network, error
return *network, nil return *network, nil
} }
func (n *netavarkNetwork) networkCreate(newNetwork types.Network, defaultNet bool) (*types.Network, error) { func (n *netavarkNetwork) networkCreate(newNetwork *types.Network, defaultNet bool) (*types.Network, error) {
// if no driver is set use the default one // if no driver is set use the default one
if newNetwork.Driver == "" { if newNetwork.Driver == "" {
newNetwork.Driver = types.DefaultNetworkDriver newNetwork.Driver = types.DefaultNetworkDriver
@ -60,7 +61,7 @@ func (n *netavarkNetwork) networkCreate(newNetwork types.Network, defaultNet boo
} }
} }
err := internalutil.CommonNetworkCreate(n, &newNetwork) err := internalutil.CommonNetworkCreate(n, newNetwork)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -82,7 +83,7 @@ func (n *netavarkNetwork) networkCreate(newNetwork types.Network, defaultNet boo
switch newNetwork.Driver { switch newNetwork.Driver {
case types.BridgeNetworkDriver: case types.BridgeNetworkDriver:
err = internalutil.CreateBridge(n, &newNetwork, usedNetworks) err = internalutil.CreateBridge(n, newNetwork, usedNetworks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -139,7 +140,7 @@ func (n *netavarkNetwork) networkCreate(newNetwork types.Network, defaultNet boo
return nil, errors.Wrapf(types.ErrInvalidArg, "unsupported driver %s", newNetwork.Driver) return nil, errors.Wrapf(types.ErrInvalidArg, "unsupported driver %s", newNetwork.Driver)
} }
err = internalutil.ValidateSubnets(&newNetwork, usedNetworks) err = internalutil.ValidateSubnets(newNetwork, usedNetworks)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -165,7 +166,7 @@ func (n *netavarkNetwork) networkCreate(newNetwork types.Network, defaultNet boo
} }
} }
return &newNetwork, nil return newNetwork, nil
} }
// NetworkRemove will remove the Network with the given name or ID. // NetworkRemove will remove the Network with the given name or ID.

View File

@ -10,13 +10,12 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
gomegaTypes "github.com/onsi/gomega/types" gomegaTypes "github.com/onsi/gomega/types"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
) )
var _ = Describe("Config", func() { var _ = Describe("Config", func() {
@ -39,7 +38,7 @@ var _ = Describe("Config", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
var err error var err error
libpodNet, err = getNetworkInterface(networkConfDir, false) libpodNet, err = getNetworkInterface(networkConfDir)
if err != nil { if err != nil {
Fail("Failed to create NewCNINetworkInterface") Fail("Failed to create NewCNINetworkInterface")
} }
@ -112,7 +111,7 @@ var _ = Describe("Config", func() {
EqualNetwork(network2, network1) EqualNetwork(network2, network1)
// create a new interface to force a config load from disk // create a new interface to force a config load from disk
libpodNet, err = getNetworkInterface(networkConfDir, false) libpodNet, err = getNetworkInterface(networkConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
network2, err = libpodNet.NetworkInspect(network1.Name) network2, err = libpodNet.NetworkInspect(network1.Name)
@ -228,7 +227,7 @@ var _ = Describe("Config", func() {
Expect(network1.Subnets[0].LeaseRange).To(BeNil()) Expect(network1.Subnets[0].LeaseRange).To(BeNil())
// reload configs from disk // reload configs from disk
libpodNet, err = getNetworkInterface(networkConfDir, false) libpodNet, err = getNetworkInterface(networkConfDir)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
// check the the networks are identical // check the the networks are identical
network2, err := libpodNet.NetworkInspect(network1.Name) network2, err := libpodNet.NetworkInspect(network1.Name)
@ -1225,7 +1224,7 @@ var _ = Describe("Config", func() {
}) })
func grepInFile(path string, match string) { func grepInFile(path, match string) {
data, err := ioutil.ReadFile(path) data, err := ioutil.ReadFile(path)
ExpectWithOffset(1, err).To(BeNil()) ExpectWithOffset(1, err).To(BeNil())
ExpectWithOffset(1, string(data)).To(ContainSubstring(match)) ExpectWithOffset(1, string(data)).To(ContainSubstring(match))
@ -1239,6 +1238,7 @@ func HaveNetworkName(name string) gomegaTypes.GomegaMatcher {
} }
// EqualNetwork must be used because comparing the time with deep equal does not work // EqualNetwork must be used because comparing the time with deep equal does not work
// nolint:gocritic
func EqualNetwork(net1, net2 types.Network) { func EqualNetwork(net1, net2 types.Network) {
ExpectWithOffset(1, net1.Created.Equal(net2.Created)).To(BeTrue(), "net1 created: %v is not equal net2 created: %v", net1.Created, net2.Created) ExpectWithOffset(1, net1.Created.Equal(net2.Created)).To(BeTrue(), "net1 created: %v is not equal net2 created: %v", net1.Created, net2.Created)
net1.Created = time.Time{} net1.Created = time.Time{}

View File

@ -56,6 +56,8 @@ func newIPAMError(cause error, msg string, args ...interface{}) *ipamError {
// openDB will open the ipam database // openDB will open the ipam database
// Note that the caller has to Close it. // Note that the caller has to Close it.
func (n *netavarkNetwork) openDB() (*bbolt.DB, error) { func (n *netavarkNetwork) openDB() (*bbolt.DB, error) {
// linter complains about the octal value
// nolint:gocritic
db, err := bbolt.Open(n.ipamDBPath, 0600, nil) db, err := bbolt.Open(n.ipamDBPath, 0600, nil)
if err != nil { if err != nil {
return nil, newIPAMError(err, "failed to open database %s", n.ipamDBPath) return nil, newIPAMError(err, "failed to open database %s", n.ipamDBPath)
@ -94,8 +96,8 @@ func (n *netavarkNetwork) allocIPs(opts *types.NetworkOptions) error {
// requestIPs is the list of ips which should be used for this container // requestIPs is the list of ips which should be used for this container
requestIPs := make([]net.IP, 0, len(network.Subnets)) requestIPs := make([]net.IP, 0, len(network.Subnets))
for _, subnet := range network.Subnets { for i := range network.Subnets {
subnetBkt, err := netBkt.CreateBucketIfNotExists([]byte(subnet.Subnet.String())) subnetBkt, err := netBkt.CreateBucketIfNotExists([]byte(network.Subnets[i].Subnet.String()))
if err != nil { if err != nil {
return newIPAMError(err, "failed to create/get subnet bucket for network %s", netName) return newIPAMError(err, "failed to create/get subnet bucket for network %s", netName)
} }
@ -104,7 +106,7 @@ func (n *netavarkNetwork) allocIPs(opts *types.NetworkOptions) error {
// in this case the user wants this one and we should not assign a free one // in this case the user wants this one and we should not assign a free one
var ip net.IP var ip net.IP
for _, staticIP := range netOpts.StaticIPs { for _, staticIP := range netOpts.StaticIPs {
if subnet.Subnet.Contains(staticIP) { if network.Subnets[i].Subnet.Contains(staticIP) {
ip = staticIP ip = staticIP
break break
} }
@ -119,7 +121,7 @@ func (n *netavarkNetwork) allocIPs(opts *types.NetworkOptions) error {
return newIPAMError(nil, "requested ip address %s is already allocated to container ID %s", ip.String(), string(id)) return newIPAMError(nil, "requested ip address %s is already allocated to container ID %s", ip.String(), string(id))
} }
} else { } else {
ip, err = getFreeIPFromBucket(subnetBkt, subnet) ip, err = getFreeIPFromBucket(subnetBkt, &network.Subnets[i])
if err != nil { if err != nil {
return err return err
} }
@ -160,7 +162,7 @@ func (n *netavarkNetwork) allocIPs(opts *types.NetworkOptions) error {
return err return err
} }
func getFreeIPFromBucket(bucket *bbolt.Bucket, subnet types.Subnet) (net.IP, error) { func getFreeIPFromBucket(bucket *bbolt.Bucket, subnet *types.Subnet) (net.IP, error) {
var rangeStart net.IP var rangeStart net.IP
var rangeEnd net.IP var rangeEnd net.IP
if subnet.LeaseRange != nil { if subnet.LeaseRange != nil {

View File

@ -33,7 +33,7 @@ var _ = Describe("IPAM", func() {
}) })
JustBeforeEach(func() { JustBeforeEach(func() {
libpodNet, err := NewNetworkInterface(InitConfig{ libpodNet, err := NewNetworkInterface(&InitConfig{
NetworkConfigDir: networkConfDir, NetworkConfigDir: networkConfDir,
IPAMDBPath: filepath.Join(networkConfDir, "ipam.db"), IPAMDBPath: filepath.Join(networkConfDir, "ipam.db"),
LockFile: filepath.Join(networkConfDir, "netavark.lock"), LockFile: filepath.Join(networkConfDir, "netavark.lock"),

View File

@ -32,10 +32,9 @@ func init() {
} }
} }
func getNetworkInterface(confDir string, machine bool) (types.ContainerNetwork, error) { func getNetworkInterface(confDir string) (types.ContainerNetwork, error) {
return netavark.NewNetworkInterface(netavark.InitConfig{ return netavark.NewNetworkInterface(&netavark.InitConfig{
NetworkConfigDir: confDir, NetworkConfigDir: confDir,
IsMachine: machine,
NetavarkBinary: netavarkBinary, NetavarkBinary: netavarkBinary,
IPAMDBPath: filepath.Join(confDir, "ipam.db"), IPAMDBPath: filepath.Join(confDir, "ipam.db"),
LockFile: filepath.Join(confDir, "netavark.lock"), LockFile: filepath.Join(confDir, "netavark.lock"),

View File

@ -79,7 +79,7 @@ type InitConfig struct {
// NewNetworkInterface creates the ContainerNetwork interface for the netavark backend. // NewNetworkInterface creates the ContainerNetwork interface for the netavark backend.
// Note: The networks are not loaded from disk until a method is called. // Note: The networks are not loaded from disk until a method is called.
func NewNetworkInterface(conf InitConfig) (types.ContainerNetwork, error) { func NewNetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) {
// TODO: consider using a shared memory lock // TODO: consider using a shared memory lock
lock, err := lockfile.GetLockfile(conf.LockFile) lock, err := lockfile.GetLockfile(conf.LockFile)
if err != nil { if err != nil {
@ -251,7 +251,7 @@ func (n *netavarkNetwork) createDefaultNetwork() (*types.Network, error) {
{Subnet: n.defaultSubnet}, {Subnet: n.defaultSubnet},
}, },
} }
return n.networkCreate(net, true) return n.networkCreate(&net, true)
} }
// getNetwork will lookup a network by name or ID. It returns an // getNetwork will lookup a network by name or ID. It returns an

View File

@ -22,16 +22,15 @@ import (
"time" "time"
"github.com/containernetworking/plugins/pkg/ns" "github.com/containernetworking/plugins/pkg/ns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"github.com/containers/common/libnetwork/types" "github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util" "github.com/containers/common/libnetwork/util"
"github.com/containers/common/pkg/netns" "github.com/containers/common/pkg/netns"
"github.com/containers/storage/pkg/stringid" "github.com/containers/storage/pkg/stringid"
"github.com/containers/storage/pkg/unshare" "github.com/containers/storage/pkg/unshare"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
) )
var _ = Describe("run netavark", func() { var _ = Describe("run netavark", func() {
@ -97,7 +96,7 @@ var _ = Describe("run netavark", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
var err error var err error
libpodNet, err = getNetworkInterface(confDir, false) libpodNet, err = getNetworkInterface(confDir)
if err != nil { if err != nil {
Fail("Failed to create NewCNINetworkInterface") Fail("Failed to create NewCNINetworkInterface")
} }

View File

@ -69,7 +69,7 @@ type IPNet struct {
// ParseCIDR parse a string to IPNet // ParseCIDR parse a string to IPNet
func ParseCIDR(cidr string) (IPNet, error) { func ParseCIDR(cidr string) (IPNet, error) {
ip, net, err := net.ParseCIDR(cidr) ip, subnet, err := net.ParseCIDR(cidr)
if err != nil { if err != nil {
return IPNet{}, err return IPNet{}, err
} }
@ -78,8 +78,8 @@ func ParseCIDR(cidr string) (IPNet, error) {
if ipv4 != nil { if ipv4 != nil {
ip = ipv4 ip = ipv4
} }
net.IP = ip subnet.IP = ip
return IPNet{*net}, err return IPNet{*subnet}, err
} }
func (n *IPNet) MarshalText() ([]byte, error) { func (n *IPNet) MarshalText() ([]byte, error) {
@ -87,11 +87,11 @@ func (n *IPNet) MarshalText() ([]byte, error) {
} }
func (n *IPNet) UnmarshalText(text []byte) error { func (n *IPNet) UnmarshalText(text []byte) error {
net, err := ParseCIDR(string(text)) subnet, err := ParseCIDR(string(text))
if err != nil { if err != nil {
return err return err
} }
*n = net *n = subnet
return nil return nil
} }
@ -253,7 +253,7 @@ type PortMapping struct {
} }
// OCICNIPortMapping maps to the standard CNI portmapping Capability. // OCICNIPortMapping maps to the standard CNI portmapping Capability.
// Deprecated, do not use this struct for new fields. This only exists // Deprecated: Do not use this struct for new fields. This only exists
// for backwards compatibility. // for backwards compatibility.
type OCICNIPortMapping struct { type OCICNIPortMapping struct {
// HostPort is the port number on the host. // HostPort is the port number on the host.

View File

@ -9,9 +9,9 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
) )
func GenerateNetworkFilters(filters map[string][]string) ([]types.FilterFunc, error) { func GenerateNetworkFilters(f map[string][]string) ([]types.FilterFunc, error) {
filterFuncs := make([]types.FilterFunc, 0, len(filters)) filterFuncs := make([]types.FilterFunc, 0, len(f))
for key, filterValues := range filters { for key, filterValues := range f {
filterFunc, err := createFilterFuncs(key, filterValues) filterFunc, err := createFilterFuncs(key, filterValues)
if err != nil { if err != nil {
return nil, err return nil, err
@ -46,9 +46,9 @@ func createFilterFuncs(key string, filterValues []string) (types.FilterFunc, err
return createPruneFilterFuncs(key, filterValues) return createPruneFilterFuncs(key, filterValues)
} }
func GenerateNetworkPruneFilters(filters map[string][]string) ([]types.FilterFunc, error) { func GenerateNetworkPruneFilters(f map[string][]string) ([]types.FilterFunc, error) {
filterFuncs := make([]types.FilterFunc, 0, len(filters)) filterFuncs := make([]types.FilterFunc, 0, len(f))
for key, filterValues := range filters { for key, filterValues := range f {
filterFunc, err := createPruneFilterFuncs(key, filterValues) filterFunc, err := createPruneFilterFuncs(key, filterValues)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -27,7 +27,7 @@ func LastIPInSubnet(addr *net.IPNet) (net.IP, error) { //nolint:interfacer
return cidr.IP, nil return cidr.IP, nil
} }
for i := range cidr.IP { for i := range cidr.IP {
cidr.IP[i] = cidr.IP[i] | ^cidr.Mask[i] cidr.IP[i] |= ^cidr.Mask[i]
} }
return cidr.IP, nil return cidr.IP, nil
} }

View File

@ -180,13 +180,13 @@ func NewNSWithName(name string) (ns.NetNS, error) {
} }
// UnmountNS unmounts the NS held by the netns object // UnmountNS unmounts the NS held by the netns object
func UnmountNS(ns ns.NetNS) error { func UnmountNS(netns ns.NetNS) error {
nsRunDir, err := GetNSRunDir() nsRunDir, err := GetNSRunDir()
if err != nil { if err != nil {
return err return err
} }
nsPath := ns.Path() nsPath := netns.Path()
// Only unmount if it's been bind-mounted (don't touch namespaces in /proc...) // Only unmount if it's been bind-mounted (don't touch namespaces in /proc...)
if strings.HasPrefix(nsPath, nsRunDir) { if strings.HasPrefix(nsPath, nsRunDir) {
if err := unix.Unmount(nsPath, unix.MNT_DETACH); err != nil { if err := unix.Unmount(nsPath, unix.MNT_DETACH); err != nil {