Support the IPAM for host-device plugin

- Change variable name to camel style to fix golint warning
- Execute the IPAM to assign the IP address if it's inside in the config
- Test the IPAM module with static plugin
This commit is contained in:
hwchiu
2018-10-20 09:44:20 +00:00
parent b93d284d18
commit d3284f7c5e
2 changed files with 169 additions and 6 deletions

View File

@ -17,6 +17,7 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
@ -28,10 +29,12 @@ import (
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/ipam"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/vishvananda/netlink"
)
//NetConf for host-device config, look the README to learn how to use those parameters
type NetConf struct {
types.NetConf
Device string `json:"device"` // Device-Name, something like eth0 or can0 etc.
@ -77,11 +80,57 @@ func cmdAdd(args *skel.CmdArgs) error {
if err != nil {
return fmt.Errorf("failed to move link %v", err)
}
// run the IPAM plugin and get back the config to apply
if cfg.IPAM.Type != "" {
r, err := ipam.ExecAdd(cfg.IPAM.Type, args.StdinData)
if err != nil {
return err
}
// Invoke ipam del if err to avoid ip leak
defer func() {
if err != nil {
ipam.ExecDel(cfg.IPAM.Type, args.StdinData)
}
}()
// Convert whatever the IPAM result was into the current Result type
result, err := current.NewResultFromResult(r)
if err != nil {
return err
}
if len(result.IPs) == 0 {
return errors.New("IPAM plugin returned missing IP config")
}
result.Interfaces = []*current.Interface{{
Name: contDev.Attrs().Name,
Mac: contDev.Attrs().HardwareAddr.String(),
Sandbox: containerNs.Path(),
}}
for _, ipc := range result.IPs {
// All addresses apply to the container interface (move from host)
ipc.Interface = current.Int(0)
}
err = containerNs.Do(func(_ ns.NetNS) error {
if err := ipam.ConfigureIface(args.IfName, result); err != nil {
return err
}
return nil
})
if err != nil {
return err
}
}
return printLink(contDev, cfg.CNIVersion, containerNs)
}
func cmdDel(args *skel.CmdArgs) error {
_, err := loadConf(args.StdinData)
cfg, err := loadConf(args.StdinData)
if err != nil {
return err
}
@ -98,6 +147,12 @@ func cmdDel(args *skel.CmdArgs) error {
return err
}
if cfg.IPAM.Type != "" {
if err := ipam.ExecDel(cfg.IPAM.Type, args.StdinData); err != nil {
return err
}
}
return nil
}