@@ -13,35 +13,67 @@ go-cni aims to support plugins that implement [Container Network Interface](http
1313
1414## Usage
1515``` go
16+ package main
17+
18+ import (
19+ " context"
20+ " fmt"
21+ " log"
22+
23+ gocni " github.com/containerd/go-cni"
24+ )
25+
1626func main () {
17- id := " 123456"
18- netns := " /proc/9999/ns/net"
27+ id := " example"
28+ netns := " /var/run/netns/example-ns-1"
29+
30+ // CNI allows multiple CNI configurations and the network interface
31+ // will be named by eth0, eth1, ..., ethN.
32+ ifPrefixName := " eth"
1933 defaultIfName := " eth0"
20- // Initialize library
21- l = gocni.New (gocni.WithMinNetworkCount (2 ),
22- gocni.WithPluginConfDir (" /etc/mycni/net.d" ),
23- gocni.WithPluginDir ([]string {" /opt/mycni/bin" , " /opt/cni/bin" }),
24- gocni.WithDefaultIfName (defaultIfName))
25-
34+
35+ // Initializes library
36+ l , err := gocni.New (
37+ // one for loopback network interface
38+ gocni.WithMinNetworkCount (2 ),
39+ gocni.WithPluginConfDir (" /etc/cni/net.d" ),
40+ gocni.WithPluginDir ([]string {" /opt/cni/bin" }),
41+ // Sets the prefix for network interfaces, eth by default
42+ gocni.WithInterfacePrefix (ifPrefixName))
43+ if err != nil {
44+ log.Fatalf (" failed to initialize cni library: %v " , err)
45+ }
46+
2647 // Load the cni configuration
27- err := l.Load (gocni.WithLoNetwork , gocni.WithDefaultConf )
28- if err != nil {
29- log.Errorf (" failed to load cni configuration: %v " , err)
30- return
48+ if err := l.Load (gocni.WithLoNetwork , gocni.WithDefaultConf ); err != nil {
49+ log.Fatalf (" failed to load cni configuration: %v " , err)
3150 }
32-
51+
3352 // Setup network for namespace.
3453 labels := map [string ]string {
3554 " K8S_POD_NAMESPACE" : " namespace1" ,
3655 " K8S_POD_NAME" : " pod1" ,
3756 " K8S_POD_INFRA_CONTAINER_ID" : id,
57+ // Plugin tolerates all Args embedded by unknown labels, like
58+ // K8S_POD_NAMESPACE/NAME/INFRA_CONTAINER_ID...
59+ " IgnoreUnknown" : " 1" ,
3860 }
39- result , err := l.Setup (id, netns, gocni.WithLabels (labels))
61+
62+ ctx := context.Background ()
63+
64+ // Teardown network
65+ defer func () {
66+ if err := l.Remove (ctx, id, netns, gocni.WithLabels (labels)); err != nil {
67+ log.Fatalf (" failed to teardown network: %v " , err)
68+ }
69+ }()
70+
71+ // Setup network
72+ result , err := l.Setup (ctx, id, netns, gocni.WithLabels (labels))
4073 if err != nil {
41- log.Errorf (" failed to setup network for namespace %q : %v " ,id, err)
42- return
74+ log.Fatalf (" failed to setup network for namespace: %v " , err)
4375 }
44-
76+
4577 // Get IP of the default interface
4678 IP := result.Interfaces [defaultIfName].IPConfigs [0 ].IP .String ()
4779 fmt.Printf (" IP of the default interface %s :%s " , defaultIfName, IP)
0 commit comments