VMware vSphere Integrated Containers provider (#206)

* Add Virtual Kubelet provider for VIC

Initial virtual kubelet provider for VMware VIC.  This provider currently
handles creating and starting of a pod VM via the VIC portlayer and persona
server.  Image store handling via the VIC persona server.  This provider
currently requires the feature/wolfpack branch of VIC.

* Added pod stop and delete.  Also added node capacity.

Added the ability to stop and delete pod VMs via VIC.  Also retrieve
node capacity information from the VCH.

* Cleanup and readme file

Some file clean up and added a Readme.md markdown file for the VIC
provider.

* Cleaned up errors, added function comments, moved operation code

1. Cleaned up error handling.  Set standard for creating errors.
2. Added method prototype comments for all interface functions.
3. Moved PodCreator, PodStarter, PodStopper, and PodDeleter to a new folder.

* Add mocking code and unit tests for podcache, podcreator, and podstarter

Used the unit test framework used in VIC to handle assertions in the provider's
unit test.  Mocking code generated using OSS project mockery, which is compatible
with the testify assertion framework.

* Vendored packages for the VIC provider

Requires feature/wolfpack branch of VIC and a few specific commit sha of
projects used within VIC.

* Implementation of POD Stopper and Deleter unit tests (#4)

* Updated files for initial PR
This commit is contained in:
Loc Nguyen
2018-06-04 15:41:32 -07:00
committed by Ria Bhatia
parent 98a111e8b7
commit 513cebe7b7
6296 changed files with 1123685 additions and 8 deletions

146
vendor/github.com/docker/libnetwork/cmd/dnet/cmd.go generated vendored Normal file
View File

@@ -0,0 +1,146 @@
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/codegangsta/cli"
"github.com/docker/docker/pkg/term"
"github.com/docker/libnetwork/client"
)
var (
containerCreateCommand = cli.Command{
Name: "create",
Usage: "Create a container",
Action: runContainerCreate,
}
containerRmCommand = cli.Command{
Name: "rm",
Usage: "Remove a container",
Action: runContainerRm,
}
containerCommands = []cli.Command{
containerCreateCommand,
containerRmCommand,
}
dnetCommands = []cli.Command{
createDockerCommand("network"),
createDockerCommand("service"),
{
Name: "container",
Usage: "Container management commands",
Subcommands: containerCommands,
},
}
)
func runContainerCreate(c *cli.Context) {
if len(c.Args()) == 0 {
fmt.Printf("Please provide container id argument\n")
os.Exit(1)
}
sc := client.SandboxCreate{ContainerID: c.Args()[0]}
obj, _, err := readBody(epConn.httpCall("POST", "/sandboxes", sc, nil))
if err != nil {
fmt.Printf("POST failed during create container: %v\n", err)
os.Exit(1)
}
var replyID string
err = json.Unmarshal(obj, &replyID)
if err != nil {
fmt.Printf("Unmarshall of response failed during create container: %v\n", err)
os.Exit(1)
}
fmt.Printf("%s\n", replyID)
}
func runContainerRm(c *cli.Context) {
var sbList []*client.SandboxResource
if len(c.Args()) == 0 {
fmt.Printf("Please provide container id argument\n")
os.Exit(1)
}
obj, _, err := readBody(epConn.httpCall("GET", "/sandboxes?partial-container-id="+c.Args()[0], nil, nil))
if err != nil {
fmt.Printf("GET failed during container id lookup: %v\n", err)
os.Exit(1)
}
err = json.Unmarshal(obj, &sbList)
if err != nil {
fmt.Printf("Unmarshall of container id lookup response failed: %v", err)
os.Exit(1)
}
if len(sbList) == 0 {
fmt.Printf("No sandbox for container %s found\n", c.Args()[0])
os.Exit(1)
}
_, _, err = readBody(epConn.httpCall("DELETE", "/sandboxes/"+sbList[0].ID, nil, nil))
if err != nil {
fmt.Printf("DELETE of sandbox id %s failed: %v", sbList[0].ID, err)
os.Exit(1)
}
}
func runDockerCommand(c *cli.Context, cmd string) {
_, stdout, stderr := term.StdStreams()
oldcli := client.NewNetworkCli(stdout, stderr, epConn.httpCall)
var args []string
args = append(args, cmd)
if c.Bool("h") {
args = append(args, "--help")
} else {
args = append(args, c.Args()...)
}
if err := oldcli.Cmd("dnet", args...); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func createDockerCommand(cmd string) cli.Command {
return cli.Command{
Name: cmd,
Usage: fmt.Sprintf("%s management commands", cmd),
SkipFlagParsing: true,
Action: func(c *cli.Context) {
runDockerCommand(c, cmd)
},
Subcommands: []cli.Command{
{
Name: "h, -help",
Usage: fmt.Sprintf("%s help", cmd),
},
},
}
}
func readBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) {
if stream != nil {
defer stream.Close()
}
if err != nil {
return nil, statusCode, err
}
body, err := ioutil.ReadAll(stream)
if err != nil {
return nil, -1, err
}
return body, statusCode, nil
}

441
vendor/github.com/docker/libnetwork/cmd/dnet/dnet.go generated vendored Normal file
View File

@@ -0,0 +1,441 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/codegangsta/cli"
"github.com/docker/docker/opts"
"github.com/docker/docker/pkg/discovery"
"github.com/docker/docker/pkg/reexec"
"github.com/Sirupsen/logrus"
psignal "github.com/docker/docker/pkg/signal"
"github.com/docker/docker/pkg/term"
"github.com/docker/libnetwork"
"github.com/docker/libnetwork/api"
"github.com/docker/libnetwork/config"
"github.com/docker/libnetwork/datastore"
"github.com/docker/libnetwork/driverapi"
"github.com/docker/libnetwork/ipamutils"
"github.com/docker/libnetwork/netlabel"
"github.com/docker/libnetwork/options"
"github.com/docker/libnetwork/types"
"github.com/gorilla/mux"
)
const (
// DefaultHTTPHost is used if only port is provided to -H flag e.g. docker -d -H tcp://:8080
DefaultHTTPHost = "0.0.0.0"
// DefaultHTTPPort is the default http port used by dnet
DefaultHTTPPort = 2385
// DefaultUnixSocket exported
DefaultUnixSocket = "/var/run/dnet.sock"
cfgFileEnv = "LIBNETWORK_CFG"
defaultCfgFile = "/etc/default/libnetwork.toml"
defaultHeartbeat = time.Duration(10) * time.Second
ttlFactor = 2
)
var epConn *dnetConnection
func main() {
if reexec.Init() {
return
}
_, stdout, stderr := term.StdStreams()
logrus.SetOutput(stderr)
err := dnetApp(stdout, stderr)
if err != nil {
os.Exit(1)
}
}
func parseConfig(cfgFile string) (*config.Config, error) {
if strings.Trim(cfgFile, " ") == "" {
cfgFile = os.Getenv(cfgFileEnv)
if strings.Trim(cfgFile, " ") == "" {
cfgFile = defaultCfgFile
}
}
return config.ParseConfig(cfgFile)
}
func processConfig(cfg *config.Config) []config.Option {
options := []config.Option{}
if cfg == nil {
return options
}
dn := "bridge"
if strings.TrimSpace(cfg.Daemon.DefaultNetwork) != "" {
dn = cfg.Daemon.DefaultNetwork
}
options = append(options, config.OptionDefaultNetwork(dn))
dd := "bridge"
if strings.TrimSpace(cfg.Daemon.DefaultDriver) != "" {
dd = cfg.Daemon.DefaultDriver
}
options = append(options, config.OptionDefaultDriver(dd))
if cfg.Daemon.Labels != nil {
options = append(options, config.OptionLabels(cfg.Daemon.Labels))
}
if dcfg, ok := cfg.Scopes[datastore.GlobalScope]; ok && dcfg.IsValid() {
options = append(options, config.OptionKVProvider(dcfg.Client.Provider))
options = append(options, config.OptionKVProviderURL(dcfg.Client.Address))
}
dOptions, err := startDiscovery(&cfg.Cluster)
if err != nil {
logrus.Infof("Skipping discovery : %s", err.Error())
} else {
options = append(options, dOptions...)
}
return options
}
func startDiscovery(cfg *config.ClusterCfg) ([]config.Option, error) {
if cfg == nil {
return nil, fmt.Errorf("discovery requires a valid configuration")
}
hb := time.Duration(cfg.Heartbeat) * time.Second
if hb == 0 {
hb = defaultHeartbeat
}
logrus.Infof("discovery : %s $s", cfg.Discovery, hb.String())
d, err := discovery.New(cfg.Discovery, hb, ttlFactor*hb, map[string]string{})
if err != nil {
return nil, err
}
if cfg.Address == "" {
iface, err := net.InterfaceByName("eth0")
if err != nil {
return nil, err
}
addrs, err := iface.Addrs()
if err != nil || len(addrs) == 0 {
return nil, err
}
ip, _, _ := net.ParseCIDR(addrs[0].String())
cfg.Address = ip.String()
}
if ip := net.ParseIP(cfg.Address); ip == nil {
return nil, errors.New("address config should be either ipv4 or ipv6 address")
}
if err := d.Register(cfg.Address + ":0"); err != nil {
return nil, err
}
options := []config.Option{config.OptionDiscoveryWatcher(d), config.OptionDiscoveryAddress(cfg.Address)}
go func() {
for {
select {
case <-time.After(hb):
if err := d.Register(cfg.Address + ":0"); err != nil {
logrus.Warn(err)
}
}
}
}()
return options, nil
}
func dnetApp(stdout, stderr io.Writer) error {
app := cli.NewApp()
app.Name = "dnet"
app.Usage = "A self-sufficient runtime for container networking."
app.Flags = dnetFlags
app.Before = processFlags
app.Commands = dnetCommands
app.Run(os.Args)
return nil
}
func createDefaultNetwork(c libnetwork.NetworkController) {
nw := c.Config().Daemon.DefaultNetwork
d := c.Config().Daemon.DefaultDriver
createOptions := []libnetwork.NetworkOption{}
genericOption := options.Generic{}
if nw != "" && d != "" {
// Bridge driver is special due to legacy reasons
if d == "bridge" {
genericOption[netlabel.GenericData] = map[string]string{
"BridgeName": "docker0",
"DefaultBridge": "true",
}
createOptions = append(createOptions,
libnetwork.NetworkOptionGeneric(genericOption),
ipamOption(nw))
}
if n, err := c.NetworkByName(nw); err == nil {
logrus.Debugf("Default network %s already present. Deleting it", nw)
if err = n.Delete(); err != nil {
logrus.Debugf("Network could not be deleted: %v", err)
return
}
}
_, err := c.NewNetwork(d, nw, createOptions...)
if err != nil {
logrus.Errorf("Error creating default network : %s : %v", nw, err)
}
}
}
type dnetConnection struct {
// proto holds the client protocol i.e. unix.
proto string
// addr holds the client address.
addr string
}
func (d *dnetConnection) dnetDaemon(cfgFile string) error {
if err := startTestDriver(); err != nil {
return fmt.Errorf("failed to start test driver: %v\n", err)
}
cfg, err := parseConfig(cfgFile)
var cOptions []config.Option
if err == nil {
cOptions = processConfig(cfg)
}
bridgeConfig := options.Generic{
"EnableIPForwarding": true,
"EnableIPTables": true,
}
bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
cOptions = append(cOptions, config.OptionDriverConfig("bridge", bridgeOption))
controller, err := libnetwork.New(cOptions...)
if err != nil {
fmt.Println("Error starting dnetDaemon :", err)
return err
}
createDefaultNetwork(controller)
httpHandler := api.NewHTTPHandler(controller)
r := mux.NewRouter().StrictSlash(false)
post := r.PathPrefix("/{.*}/networks").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
post = r.PathPrefix("/networks").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
post = r.PathPrefix("/{.*}/services").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
post = r.PathPrefix("/services").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
post = r.PathPrefix("/{.*}/sandboxes").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
post = r.PathPrefix("/sandboxes").Subrouter()
post.Methods("GET", "PUT", "POST", "DELETE").HandlerFunc(httpHandler)
handleSignals(controller)
setupDumpStackTrap()
return http.ListenAndServe(d.addr, r)
}
func setupDumpStackTrap() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGUSR1)
go func() {
for range c {
psignal.DumpStacks()
}
}()
}
func handleSignals(controller libnetwork.NetworkController) {
c := make(chan os.Signal, 1)
signals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}
signal.Notify(c, signals...)
go func() {
for _ = range c {
controller.Stop()
os.Exit(0)
}
}()
}
func startTestDriver() error {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
if server == nil {
return fmt.Errorf("Failed to start a HTTP Server")
}
mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
})
mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Scope":"global"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil {
return err
}
if err := ioutil.WriteFile("/etc/docker/plugins/test.spec", []byte(server.URL), 0644); err != nil {
return err
}
return nil
}
func newDnetConnection(val string) (*dnetConnection, error) {
url, err := opts.ParseHost(DefaultHTTPHost, val)
if err != nil {
return nil, err
}
protoAddrParts := strings.SplitN(url, "://", 2)
if len(protoAddrParts) != 2 {
return nil, fmt.Errorf("bad format, expected tcp://ADDR")
}
if strings.ToLower(protoAddrParts[0]) != "tcp" {
return nil, fmt.Errorf("dnet currently only supports tcp transport")
}
return &dnetConnection{protoAddrParts[0], protoAddrParts[1]}, nil
}
func (d *dnetConnection) httpCall(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
var in io.Reader
in, err := encodeData(data)
if err != nil {
return nil, nil, -1, err
}
req, err := http.NewRequest(method, fmt.Sprintf("%s", path), in)
if err != nil {
return nil, nil, -1, err
}
setupRequestHeaders(method, data, req, headers)
req.URL.Host = d.addr
req.URL.Scheme = "http"
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
statusCode := -1
if resp != nil {
statusCode = resp.StatusCode
}
if err != nil {
return nil, nil, statusCode, fmt.Errorf("error when trying to connect: %v", err)
}
if statusCode < 200 || statusCode >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, statusCode, err
}
return nil, nil, statusCode, fmt.Errorf("error : %s", bytes.TrimSpace(body))
}
return resp.Body, resp.Header, statusCode, nil
}
func setupRequestHeaders(method string, data interface{}, req *http.Request, headers map[string][]string) {
if data != nil {
if headers == nil {
headers = make(map[string][]string)
}
headers["Content-Type"] = []string{"application/json"}
}
expectedPayload := (method == "POST" || method == "PUT")
if expectedPayload && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "text/plain")
}
if headers != nil {
for k, v := range headers {
req.Header[k] = v
}
}
}
func encodeData(data interface{}) (*bytes.Buffer, error) {
params := bytes.NewBuffer(nil)
if data != nil {
if err := json.NewEncoder(params).Encode(data); err != nil {
return nil, err
}
}
return params, nil
}
func ipamOption(bridgeName string) libnetwork.NetworkOption {
if nw, _, err := ipamutils.ElectInterfaceAddresses(bridgeName); err == nil {
ipamV4Conf := &libnetwork.IpamConf{PreferredPool: nw.String()}
hip, _ := types.GetHostPartIP(nw.IP, nw.Mask)
if hip.IsGlobalUnicast() {
ipamV4Conf.Gateway = nw.IP.String()
}
return libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil)
}
return nil
}

87
vendor/github.com/docker/libnetwork/cmd/dnet/flags.go generated vendored Normal file
View File

@@ -0,0 +1,87 @@
package main
import (
"fmt"
"os"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
var (
dnetFlags = []cli.Flag{
cli.BoolFlag{
Name: "d, -daemon",
Usage: "Enable daemon mode",
},
cli.StringFlag{
Name: "H, -host",
Value: "",
Usage: "Daemon socket to connect to",
},
cli.StringFlag{
Name: "l, -log-level",
Value: "info",
Usage: "Set the logging level",
},
cli.BoolFlag{
Name: "D, -debug",
Usage: "Enable debug mode",
},
cli.StringFlag{
Name: "c, -cfg-file",
Value: "/etc/default/libnetwork.toml",
Usage: "Configuration file",
},
}
)
func processFlags(c *cli.Context) error {
var err error
if c.String("l") != "" {
lvl, err := logrus.ParseLevel(c.String("l"))
if err != nil {
fmt.Printf("Unable to parse logging level: %s\n", c.String("l"))
os.Exit(1)
}
logrus.SetLevel(lvl)
} else {
logrus.SetLevel(logrus.InfoLevel)
}
if c.Bool("D") {
logrus.SetLevel(logrus.DebugLevel)
}
hostFlag := c.String("H")
if hostFlag == "" {
defaultHost := os.Getenv("DNET_HOST")
if defaultHost == "" {
// TODO : Add UDS support
defaultHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort)
}
hostFlag = defaultHost
}
epConn, err = newDnetConnection(hostFlag)
if err != nil {
if c.Bool("d") {
logrus.Error(err)
} else {
fmt.Println(err)
}
os.Exit(1)
}
if c.Bool("d") {
err = epConn.dnetDaemon(c.String("c"))
if err != nil {
logrus.Errorf("dnet Daemon exited with an error : %v", err)
os.Exit(1)
}
os.Exit(1)
}
return nil
}

13
vendor/github.com/docker/libnetwork/cmd/dnet/libnetwork.toml generated vendored Executable file
View File

@@ -0,0 +1,13 @@
title = "LibNetwork Configuration file"
[daemon]
debug = false
[cluster]
discovery = "consul://localhost:8500"
Address = "1.1.1.1"
Heartbeat = 20
[datastore]
embedded = false
[datastore.client]
provider = "consul"
Address = "localhost:8500"

View File

@@ -0,0 +1,165 @@
package main
import (
"fmt"
"net"
"os"
"os/signal"
"github.com/docker/docker/pkg/reexec"
"github.com/docker/libnetwork/driverapi"
"github.com/docker/libnetwork/drivers/overlay"
"github.com/docker/libnetwork/netlabel"
"github.com/docker/libnetwork/types"
"github.com/vishvananda/netlink"
)
type router struct {
d driverapi.Driver
}
type endpoint struct {
addr *net.IPNet
mac net.HardwareAddr
name string
}
func (r *router) RegisterDriver(name string, driver driverapi.Driver, c driverapi.Capability) error {
r.d = driver
return nil
}
func (ep *endpoint) Interface() driverapi.InterfaceInfo {
return nil
}
func (ep *endpoint) SetMacAddress(mac net.HardwareAddr) error {
if ep.mac != nil {
return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", ep.mac, mac)
}
if mac == nil {
return types.BadRequestErrorf("tried to set nil MAC address to endpoint interface")
}
ep.mac = types.GetMacCopy(mac)
return nil
}
func (ep *endpoint) SetIPAddress(address *net.IPNet) error {
if address.IP == nil {
return types.BadRequestErrorf("tried to set nil IP address to endpoint interface")
}
if address.IP.To4() == nil {
return types.NotImplementedErrorf("do not support ipv6 yet")
}
if ep.addr != nil {
return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with %s.", ep.addr, address)
}
ep.addr = types.GetIPNetCopy(address)
return nil
}
func (ep *endpoint) MacAddress() net.HardwareAddr {
return types.GetMacCopy(ep.mac)
}
func (ep *endpoint) Address() *net.IPNet {
return types.GetIPNetCopy(ep.addr)
}
func (ep *endpoint) AddressIPv6() *net.IPNet {
return nil
}
func (ep *endpoint) InterfaceName() driverapi.InterfaceNameInfo {
return ep
}
func (ep *endpoint) SetNames(srcName, dstPrefix string) error {
ep.name = srcName
return nil
}
func (ep *endpoint) SetGateway(net.IP) error {
return nil
}
func (ep *endpoint) SetGatewayIPv6(net.IP) error {
return nil
}
func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int,
nextHop net.IP) error {
return nil
}
func (ep *endpoint) DisableGatewayService() {}
func main() {
if reexec.Init() {
return
}
opt := make(map[string]interface{})
if len(os.Args) > 1 {
opt[netlabel.OverlayBindInterface] = os.Args[1]
}
if len(os.Args) > 2 {
opt[netlabel.OverlayNeighborIP] = os.Args[2]
}
if len(os.Args) > 3 {
opt[netlabel.GlobalKVProvider] = os.Args[3]
}
if len(os.Args) > 4 {
opt[netlabel.GlobalKVProviderURL] = os.Args[4]
}
r := &router{}
if err := overlay.Init(r, opt); err != nil {
fmt.Printf("Failed to initialize overlay driver: %v\n", err)
os.Exit(1)
}
if err := r.d.CreateNetwork("testnetwork",
map[string]interface{}{}, nil, nil); err != nil {
fmt.Printf("Failed to create network in the driver: %v\n", err)
os.Exit(1)
}
ep := &endpoint{}
if err := r.d.CreateEndpoint("testnetwork", "testep",
ep, map[string]interface{}{}); err != nil {
fmt.Printf("Failed to create endpoint in the driver: %v\n", err)
os.Exit(1)
}
if err := r.d.Join("testnetwork", "testep",
"", ep, map[string]interface{}{}); err != nil {
fmt.Printf("Failed to join an endpoint in the driver: %v\n", err)
os.Exit(1)
}
link, err := netlink.LinkByName(ep.name)
if err != nil {
fmt.Printf("Failed to find the container interface with name %s: %v\n",
ep.name, err)
os.Exit(1)
}
ipAddr := &netlink.Addr{IPNet: ep.addr, Label: ""}
if err := netlink.AddrAdd(link, ipAddr); err != nil {
fmt.Printf("Failed to add address to the interface: %v\n", err)
os.Exit(1)
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, os.Kill)
for {
select {
case <-sigCh:
r.d.Leave("testnetwork", "testep")
overlay.Fini(r.d)
os.Exit(0)
}
}
}

View File

@@ -0,0 +1,74 @@
package main
import (
"fmt"
"log"
"github.com/docker/docker/pkg/reexec"
"github.com/docker/libnetwork"
"github.com/docker/libnetwork/config"
"github.com/docker/libnetwork/netlabel"
"github.com/docker/libnetwork/options"
)
func main() {
if reexec.Init() {
return
}
// Select and configure the network driver
networkType := "bridge"
// Create a new controller instance
driverOptions := options.Generic{}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = driverOptions
controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
if err != nil {
log.Fatalf("libnetwork.New: %s", err)
}
// Create a network for containers to join.
// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
network, err := controller.NewNetwork(networkType, "network1")
if err != nil {
log.Fatalf("controller.NewNetwork: %s", err)
}
// For each new container: allocate IP and interfaces. The returned network
// settings will be used for container infos (inspect and such), as well as
// iptables rules for port publishing. This info is contained or accessible
// from the returned endpoint.
ep, err := network.CreateEndpoint("Endpoint1")
if err != nil {
log.Fatalf("network.CreateEndpoint: %s", err)
}
// Create the sandbox for the container.
// NewSandbox accepts Variadic optional arguments which libnetwork can use.
sbx, err := controller.NewSandbox("container1",
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("docker.io"))
if err != nil {
log.Fatalf("controller.NewSandbox: %s", err)
}
// A sandbox can join the endpoint via the join api.
err = ep.Join(sbx)
if err != nil {
log.Fatalf("ep.Join: %s", err)
}
// libnetwork client can check the endpoint's operational data via the Info() API
epInfo, err := ep.DriverInfo()
if err != nil {
log.Fatalf("ep.DriverInfo: %s", err)
}
macAddress, ok := epInfo[netlabel.MacAddress]
if !ok {
log.Fatalf("failed to get mac address from endpoint info")
}
fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key())
}