cni

package module
v1.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2023 License: Apache-2.0 Imports: 15 Imported by: 184

README

go-cni

PkgGoDev Build Status codecov Go Report Card

A generic CNI library to provide APIs for CNI plugin interactions. The library provides APIs to:

  • Load CNI network config from different sources
  • Setup networks for container namespace
  • Remove networks from container namespace
  • Query status of CNI network plugin initialization
  • Check verifies the network is still in desired state

go-cni aims to support plugins that implement Container Network Interface

Usage

package main

import (
	"context"
	"fmt"
	"log"

	gocni "github.com/containerd/go-cni"
)

func main() {
	id := "example"
	netns := "/var/run/netns/example-ns-1"

	// CNI allows multiple CNI configurations and the network interface
	// will be named by eth0, eth1, ..., ethN.
	ifPrefixName := "eth"
	defaultIfName := "eth0"

	// Initializes library
	l, err := gocni.New(
		// one for loopback network interface
		gocni.WithMinNetworkCount(2),
		gocni.WithPluginConfDir("/etc/cni/net.d"),
		gocni.WithPluginDir([]string{"/opt/cni/bin"}),
		// Sets the prefix for network interfaces, eth by default
		gocni.WithInterfacePrefix(ifPrefixName))
	if err != nil {
		log.Fatalf("failed to initialize cni library: %v", err)
	}

	// Load the cni configuration
	if err := l.Load(gocni.WithLoNetwork, gocni.WithDefaultConf); err != nil {
		log.Fatalf("failed to load cni configuration: %v", err)
	}

	// Setup network for namespace.
	labels := map[string]string{
		"K8S_POD_NAMESPACE":          "namespace1",
		"K8S_POD_NAME":               "pod1",
		"K8S_POD_INFRA_CONTAINER_ID": id,
		// Plugin tolerates all Args embedded by unknown labels, like
		// K8S_POD_NAMESPACE/NAME/INFRA_CONTAINER_ID...
		"IgnoreUnknown": "1",
	}

	ctx := context.Background()

	// Teardown network
	defer func() {
		if err := l.Remove(ctx, id, netns, gocni.WithLabels(labels)); err != nil {
			log.Fatalf("failed to teardown network: %v", err)
		}
	}()

	// Setup network
	result, err := l.Setup(ctx, id, netns, gocni.WithLabels(labels))
	if err != nil {
		log.Fatalf("failed to setup network for namespace: %v", err)
	}

	// Get IP of the default interface
	IP := result.Interfaces[defaultIfName].IPConfigs[0].IP.String()
	fmt.Printf("IP of the default interface %s:%s", defaultIfName, IP)
}

Project details

The go-cni is a containerd sub-project, licensed under the Apache 2.0 license. As a containerd sub-project, you will find the:

information in our containerd/project repository.

Documentation

Index

Constants

View Source
const (
	CNIPluginName     = "cni"
	DefaultMaxConfNum = 1
	DefaultPrefix     = "eth"
)
View Source
const (
	DefaultNetDir        = "/etc/cni/net.d"
	DefaultCNIDir        = "/opt/cni/bin"
	VendorCNIDirTemplate = "%s/opt/%s/bin"
)

Variables

View Source
var (
	ErrCNINotInitialized = errors.New("cni plugin not initialized")
	ErrInvalidConfig     = errors.New("invalid cni config")
	ErrNotFound          = errors.New("not found")
	ErrRead              = errors.New("failed to read config file")
	ErrInvalidResult     = errors.New("invalid result")
	ErrLoad              = errors.New("failed to load cni config")
)

Functions

func IsCNINotInitialized

func IsCNINotInitialized(err error) bool

IsCNINotInitialized returns true if the error is due to cni config not being initialized

func IsInvalidConfig

func IsInvalidConfig(err error) bool

IsInvalidConfig returns true if the error is invalid cni config

func IsInvalidResult

func IsInvalidResult(err error) bool

IsInvalidResult return true if the error is due to invalid cni result

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error is due to a missing config or result

func IsReadFailure

func IsReadFailure(err error) bool

IsReadFailure return true if the error is a config read failure

func WithAllConf

func WithAllConf(c *libcni) error

WithAllConf can be used to detect all network config files from the configured cni config directory and load them.

func WithDefaultConf

func WithDefaultConf(c *libcni) error

WithDefaultConf can be used to detect the default network config file from the configured cni config directory and load it. Since the CNI spec does not specify a way to detect default networks, the convention chosen is - the first network configuration in the sorted list of network conf files as the default network.

func WithLoNetwork

func WithLoNetwork(c *libcni) error

WithLoNetwork can be used to load the loopback network config.

Types

type BandWidth

type BandWidth struct {
	IngressRate  uint64
	IngressBurst uint64
	EgressRate   uint64
	EgressBurst  uint64
}

BandWidth defines the ingress/egress rate and burst limits

type CNI

type CNI interface {
	// Setup setup the network for the namespace
	Setup(ctx context.Context, id string, path string, opts ...NamespaceOpts) (*Result, error)
	// SetupSerially sets up each of the network interfaces for the namespace in serial
	SetupSerially(ctx context.Context, id string, path string, opts ...NamespaceOpts) (*Result, error)
	// Remove tears down the network of the namespace.
	Remove(ctx context.Context, id string, path string, opts ...NamespaceOpts) error
	// Check checks if the network is still in desired state
	Check(ctx context.Context, id string, path string, opts ...NamespaceOpts) error
	// Load loads the cni network config
	Load(opts ...Opt) error
	// Status checks the status of the cni initialization
	Status() error
	// GetConfig returns a copy of the CNI plugin configurations as parsed by CNI
	GetConfig() *ConfigResult
}

func New

func New(config ...Opt) (CNI, error)

New creates a new libcni instance.

type CNIOpt deprecated

type CNIOpt = Opt //revive:disable // type name will be used as cni.CNIOpt by other packages, and that stutters

Deprecated: use cni.Opt instead

type CNIResult deprecated

type CNIResult = Result //revive:disable // type name will be used as cni.CNIResult by other packages, and that stutters

Deprecated: use cni.Result instead

type ConfNetwork

type ConfNetwork struct {
	Config *NetworkConfList
	IFName string
}

type Config

type Config struct {
	IPConfigs []*IPConfig
	Mac       string
	Sandbox   string
}

type ConfigResult

type ConfigResult struct {
	PluginDirs       []string
	PluginConfDir    string
	PluginMaxConfNum int
	Prefix           string
	Networks         []*ConfNetwork
}

type DNS

type DNS struct {
	// List of DNS servers of the cluster.
	Servers []string
	// List of DNS search domains of the cluster.
	Searches []string
	// List of DNS options.
	Options []string
}

DNS defines the dns config

type IPConfig

type IPConfig struct {
	IP      net.IP
	Gateway net.IP
}

type IPRanges

type IPRanges struct {
	Subnet     string
	RangeStart string
	RangeEnd   string
	Gateway    string
}

type Namespace

type Namespace struct {
	// contains filtered or unexported fields
}

type NamespaceOpts

type NamespaceOpts func(s *Namespace) error

func WithArgs

func WithArgs(k, v string) NamespaceOpts

func WithCapability

func WithCapability(name string, capability interface{}) NamespaceOpts

WithCapability support well-known capabilities https://www.cni.dev/docs/conventions/#well-known-capabilities

func WithCapabilityBandWidth

func WithCapabilityBandWidth(bandWidth BandWidth) NamespaceOpts

WithCapabilityBandWitdh adds support for bandwidth limits

func WithCapabilityCgroupPath added in v1.1.9

func WithCapabilityCgroupPath(cgroupPath string) NamespaceOpts

WithCapabilityCgroupPath passes in the cgroup path capability.

func WithCapabilityDNS

func WithCapabilityDNS(dns DNS) NamespaceOpts

WithCapabilityDNS adds support for dns

func WithCapabilityIPRanges

func WithCapabilityIPRanges(ipRanges []IPRanges) NamespaceOpts

WithCapabilityIPRanges adds support for ip ranges

func WithCapabilityPortMap

func WithCapabilityPortMap(portMapping []PortMapping) NamespaceOpts

WithCapabilityPortMap adds support for port mappings

func WithLabels

func WithLabels(labels map[string]string) NamespaceOpts

Args

type Network

type Network struct {
	// contains filtered or unexported fields
}

func (*Network) Attach

func (n *Network) Attach(ctx context.Context, ns *Namespace) (*types100.Result, error)

func (*Network) Check added in v1.1.2

func (n *Network) Check(ctx context.Context, ns *Namespace) error

func (*Network) Remove

func (n *Network) Remove(ctx context.Context, ns *Namespace) error

type NetworkConf

type NetworkConf struct {
	Network *types.NetConf
	Source  string
}

NetworkConf is a source bytes to string conversion of cnilibrary.NetworkConfig

type NetworkConfList

type NetworkConfList struct {
	Name       string
	CNIVersion string
	Plugins    []*NetworkConf
	Source     string
}

NetworkConfList is a source bytes to string version of cnilibrary.NetworkConfigList

type Opt added in v1.0.2

type Opt func(c *libcni) error

Opt sets options for a CNI instance

func WithConf

func WithConf(bytes []byte) Opt

WithConf can be used to load config directly from byte.

func WithConfFile

func WithConfFile(fileName string) Opt

WithConfFile can be used to load network config from an .conf file. Supported with absolute fileName with path only.

func WithConfIndex

func WithConfIndex(bytes []byte, index int) Opt

WithConfIndex can be used to load config directly from byte and set the interface name's index.

func WithConfListBytes

func WithConfListBytes(bytes []byte) Opt

WithConfListBytes can be used to load network config list directly from byte

func WithConfListFile

func WithConfListFile(fileName string) Opt

WithConfListFile can be used to load network config from an .conflist file. Supported with absolute fileName with path only.

func WithInterfacePrefix

func WithInterfacePrefix(prefix string) Opt

WithInterfacePrefix sets the prefix for network interfaces e.g. eth or wlan

func WithMinNetworkCount

func WithMinNetworkCount(count int) Opt

WithMinNetworkCount can be used to configure the minimum networks to be configured and initialized for the status to report success. By default its 1.

func WithPluginConfDir

func WithPluginConfDir(dir string) Opt

WithPluginConfDir can be used to configure the cni configuration directory.

func WithPluginDir

func WithPluginDir(dirs []string) Opt

WithPluginDir can be used to set the locations of the cni plugin binaries

func WithPluginMaxConfNum

func WithPluginMaxConfNum(max int) Opt

WithPluginMaxConfNum can be used to configure the max cni plugin config file num.

type PortMapping

type PortMapping struct {
	HostPort      int32
	ContainerPort int32
	Protocol      string
	HostIP        string
}

type Result added in v1.0.2

type Result struct {
	Interfaces map[string]*Config
	DNS        []types.DNS
	Routes     []*types.Route
	// contains filtered or unexported fields
}

Result contains the network information returned by CNI.Setup

a) Interfaces list. Depending on the plugin, this can include the sandbox

(eg, container or hypervisor) interface name and/or the host interface
name, the hardware addresses of each interface, and details about the
sandbox (if any) the interface is in.

b) IP configuration assigned to each interface. The IPv4 and/or IPv6 addresses,

gateways, and routes assigned to sandbox and/or host interfaces.

c) DNS information. Dictionary that includes DNS information for nameservers,

domain, search domains and options.

func (*Result) Raw added in v1.1.0

func (r *Result) Raw() []*types100.Result

Raw returns the raw CNI results of multiple networks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL