Skip to content

Commit

Permalink
Merge pull request #58 from fuweid/update-readme-usage
Browse files Browse the repository at this point in the history
README.md: update Usage case
  • Loading branch information
mikebrow authored Jun 15, 2020
2 parents 0553354 + 8ffba88 commit 1582593
Showing 1 changed file with 49 additions and 17 deletions.
66 changes: 49 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,67 @@ go-cni aims to support plugins that implement [Container Network Interface](http

## Usage
```go
package main

import (
"context"
"fmt"
"log"

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

func main() {
id := "123456"
netns := "/proc/9999/ns/net"
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"
// Initialize library
l = gocni.New(gocni.WithMinNetworkCount(2),
gocni.WithPluginConfDir("/etc/mycni/net.d"),
gocni.WithPluginDir([]string{"/opt/mycni/bin", "/opt/cni/bin"}),
gocni.WithDefaultIfName(defaultIfName))


// 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
err:= l.Load(gocni.WithLoNetwork, gocni.WithDefaultConf)
if err != nil{
log.Errorf("failed to load cni configuration: %v", err)
return
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",
}
result, err := l.Setup(id, netns, gocni.WithLabels(labels))

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.Errorf("failed to setup network for namespace %q: %v",id, err)
return
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)
Expand Down

0 comments on commit 1582593

Please sign in to comment.