From ba9b6bc82a8356637a0cfd761a6f5b5c90890947 Mon Sep 17 00:00:00 2001 From: Eugene Yakubovich Date: Thu, 22 Jan 2015 10:07:23 -0800 Subject: [PATCH] net: use env vars for plugin params; use stage1 rootfs for builtins Simplifying the plugin interface. No more HTTP interface and plugin configs. Plugin type maps to executable name in stage1 rootfs or on host in a well known dir. Env vars are used for parameter passing to the plugin. Also, default net conf is kept in stage1 rootfs to make private networking work "out of the box". --- build | 20 ++-- networking/net-plugin.go | 145 +++++++++------------------ networking/net.go | 32 ++++-- networking/networking.go | 49 +++++---- networking/plugins/bridge/bridge.go | 63 ++++++------ networking/plugins/veth/veth.go | 63 ++++++------ stage1/init/init.go | 2 +- stage1/rootfs/Makefile | 2 +- stage1/rootfs/net-plugins/.gitignore | 1 + stage1/rootfs/net-plugins/Makefile | 11 ++ stage1/rootfs/net-plugins/install | 3 + stage1/rootfs/net/99-default.conf | 9 ++ stage1/rootfs/net/Makefile | 9 ++ stage1/rootfs/net/install | 3 + 14 files changed, 220 insertions(+), 192 deletions(-) create mode 100644 stage1/rootfs/net-plugins/.gitignore create mode 100644 stage1/rootfs/net-plugins/Makefile create mode 100644 stage1/rootfs/net-plugins/install create mode 100644 stage1/rootfs/net/99-default.conf create mode 100644 stage1/rootfs/net/Makefile create mode 100644 stage1/rootfs/net/install diff --git a/build b/build index b143a19..f72e4b0 100755 --- a/build +++ b/build @@ -13,10 +13,24 @@ export GOPATH=${GOPATH}:${PWD}/gopath eval $(go env) +echo "Building network plugins" +for d in networking/plugins/*; do + plugin=$(basename $d) + echo " " $plugin + go install ${REPO_PATH}/$d +done + if [[ "$OSTYPE" == "linux-gnu" ]]; then echo "Building init (stage1)..." go build -o $GOBIN/init ${REPO_PATH}/stage1/init + echo "Copying network plugins to stage1" + mkdir -p stage1/rootfs/net-plugins/bin + for d in networking/plugins/*; do + plugin=$(basename $d) + ln -sf ${GOBIN}/$plugin stage1/rootfs/net-plugins/bin + done + S1INIT=${PWD}/stage0/stage1_init if [ $GOBIN/init -nt $S1INIT/bin.go ]; then echo "Packaging init (stage1)..." @@ -37,9 +51,3 @@ go build -o $GOBIN/rkt ${REPO_PATH}/rkt echo "Building metadatasvc..." go build -o $GOBIN/metadatasvc ${REPO_PATH}/metadatasvc -echo "Building network plugins" -for d in networking/plugins/*; do - plugin=$(basename $d) - echo " " $plugin - go build -o $GOBIN/$plugin ${REPO_PATH}/$d -done diff --git a/networking/net-plugin.go b/networking/net-plugin.go index 33f31f4..4931189 100644 --- a/networking/net-plugin.go +++ b/networking/net-plugin.go @@ -16,140 +16,87 @@ package networking import ( "bytes" - "encoding/json" "fmt" - "io/ioutil" - "log" "net" "os" "os/exec" "path/filepath" "strings" - "github.com/appc/spec/schema/types" - "github.com/coreos/rocket/networking/util" + rktpath "github.com/coreos/rocket/path" ) -// NetPlugin encodes a networking plugin. -type NetPlugin struct { - Name string `json:"name,omitempty"` - Endpoint string `json:"endpoint,omitempty"` - Command struct { - Add []string `json:"add,omitempty"` - Del []string `json:"del,omitempty"` - } -} +// TODO(eyakubovich): make this configurable in rkt.conf +const UserNetPluginsPath = "/usr/lib/rkt/plugins/net" +const BuiltinNetPluginsPath = "usr/lib/rkt/plugins/net" -// RktNetPluginsPath is the absolute path of rkt-net-plugins.conf.d. -const RktNetPluginsPath = "/etc/rkt-net-plugins.conf.d" - -// LoadNetPlugin loads a JSON-encoded NetPlugin from the filesystem. -func LoadNetPlugin(path string) (*NetPlugin, error) { - c, err := ioutil.ReadFile(path) +func (e *containerEnv) netPluginAdd(n *Net, netns, args, ifName string) (*net.IPNet, error) { + output, err := e.execNetPlugin("ADD", n, netns, args, ifName) if err != nil { return nil, err } - np := &NetPlugin{} - if err = json.Unmarshal(c, np); err != nil { - return nil, err - } - - return np, nil + return util.ParseCIDR(output) } -// LoadNetPlugins produces a collection of NetPlugins loaded from -// RktNetPluginsPath. -func LoadNetPlugins() (map[string]*NetPlugin, error) { - plugins := make(map[string]*NetPlugin) +func (e *containerEnv) netPluginDel(n *Net, netns, args, ifName string) error { + _, err := e.execNetPlugin("DEL", n, netns, args, ifName) + return err +} - dirents, err := ioutil.ReadDir(RktNetPluginsPath) - switch { - case err == nil: - case os.IsNotExist(err): - return plugins, nil - default: - return nil, err +func (e *containerEnv) findNetPlugin(plugin string) string { + // try 3rd-party path first + paths := []string{ + UserNetPluginsPath, + filepath.Join(rktpath.Stage1RootfsPath(e.rktRoot), BuiltinNetPluginsPath), } - for _, dent := range dirents { - if dent.IsDir() { - continue + for _, p := range paths { + fullname := filepath.Join(p, plugin) + if fi, err := os.Stat(fullname); err == nil && fi.Mode().IsRegular() { + return fullname } - - npPath := filepath.Join(RktNetPluginsPath, dent.Name()) - np, err := LoadNetPlugin(npPath) - if err != nil { - log.Printf("Error loading %v: %v", npPath, err) - continue - } - - plugins[np.Name] = np } - return plugins, nil + return "" } -// Add invokes the plugin's add command, if defined. -func (np *NetPlugin) Add(n *Net, contID types.UUID, netns, args, ifName string) (*net.IPNet, error) { - switch { - case np.Endpoint != "": - return nil, execHTTP(np.Endpoint, "add", n.Name, contID.String(), netns, n.Filename, args, ifName) +func envVars(vars [][2]string) []string { + env := []string{} - default: - if len(np.Command.Add) == 0 { - return nil, fmt.Errorf("plugin does not define command.add") - } - - output, err := execCmd(np.Command.Add, n.Name, contID.String(), netns, n.Filename, args, ifName) - if err != nil { - return nil, err - } - - return util.ParseCIDR(output) + for _, kv := range vars { + env = append(env, strings.Join(kv[:], "=")) } + + return env } -// Del invokes the plugin's del command, if defined. -func (np *NetPlugin) Del(n *Net, contID types.UUID, netns, args, ifName string) error { - switch { - case np.Endpoint != "": - return execHTTP(np.Endpoint, "del", n.Name, contID.String(), netns, n.Filename, args, ifName) - - default: - if len(np.Command.Del) == 0 { - return fmt.Errorf("plugin does not define command.del") - } - - _, err := execCmd(np.Command.Del, n.Name, contID.String(), netns, n.Filename, args, ifName) - return err +func (e *containerEnv) execNetPlugin(cmd string, n *Net, netns, args, ifName string) (string, error) { + pluginPath := e.findNetPlugin(n.Type) + if pluginPath == "" { + return "", fmt.Errorf("Could not find plugin %q", n.Type) } -} -func execHTTP(ep, cmd, netName, contID, netns, confFile, args, ifName string) error { - return fmt.Errorf("not implemented") -} - -func replaceAll(xs []string, what, with string) { - for i, x := range xs { - xs[i] = strings.Replace(x, what, with, -1) + vars := [][2]string{ + { "RKT_NETPLUGIN_COMMAND", cmd }, + { "RKT_NETPLUGIN_CONTID", e.contID.String() }, + { "RKT_NETPLUGIN_NETNS", netns }, + { "RKT_NETPLUGIN_ARGS", args }, + { "RKT_NETPLUGIN_IFNAME", ifName }, + { "RKT_NETPLUGIN_NETNAME", n.Name }, + { "RKT_NETPLUGIN_NETCONF", n.Filename }, } -} - -func execCmd(cmd []string, netName, contID, netns, confFile, args, ifName string) (string, error) { - replaceAll(cmd, "{net-name}", netName) - replaceAll(cmd, "{cont-id}", contID) - replaceAll(cmd, "{netns}", netns) - replaceAll(cmd, "{conf-file}", confFile) - replaceAll(cmd, "{if-name}", ifName) - replaceAll(cmd, "{args}", args) stdout := &bytes.Buffer{} - c := exec.Command(cmd[0], cmd[1:]...) - c.Stdout = stdout - c.Stderr = os.Stderr + c := exec.Cmd{ + Path: pluginPath, + Args: []string{pluginPath}, + Env: envVars(vars), + Stdout: stdout, + Stderr: os.Stderr, + } if err := c.Run(); err != nil { return "", err } diff --git a/networking/net.go b/networking/net.go index 9e52a83..2835f83 100644 --- a/networking/net.go +++ b/networking/net.go @@ -22,6 +22,7 @@ import ( "sort" "github.com/coreos/rocket/networking/util" + rktpath "github.com/coreos/rocket/path" ) // Net encodes a network plugin. @@ -30,11 +31,13 @@ type Net struct { args string } -// RktNetPath is the absolute path of rkt-net.conf.d. -const RktNetPath = "/etc/rkt-net.conf.d" +// Absolute path where users place their net configs +const UserNetPath = "/etc/rkt/net.d" +// Default net path relative to stage1 root +const DefaultNetPath = "etc/rkt/net.d/99-default.conf" func listFiles(dir string) ([]string, error) { - dirents, err := ioutil.ReadDir(RktNetPath) + dirents, err := ioutil.ReadDir(dir) switch { case err == nil: case os.IsNotExist(err): @@ -55,9 +58,8 @@ func listFiles(dir string) ([]string, error) { return files, nil } -// LoadNets produces a collection of NetPlugins loaded from RktNetPluginsPath. -func LoadNets() ([]Net, error) { - files, err := listFiles(RktNetPath) +func loadUserNets() ([]Net, error) { + files, err := listFiles(UserNetPath) if err != nil { return nil, err } @@ -67,7 +69,7 @@ func LoadNets() ([]Net, error) { nets := make([]Net, 0, len(files)) for _, filename := range files { - filepath := path.Join(RktNetPath, filename) + filepath := path.Join(UserNetPath, filename) n := Net{} if err := util.LoadNet(filepath, &n); err != nil { return nil, fmt.Errorf("error loading %v: %v", filepath, err) @@ -78,3 +80,19 @@ func LoadNets() ([]Net, error) { return nets, nil } + +// Loads nets specified by user and default one from stage1 +func (e *containerEnv) loadNets() ([]Net, error) { + nets, err := loadUserNets() + if err != nil { + return nil, err + } + + defPath := path.Join(rktpath.Stage1RootfsPath(e.rktRoot), DefaultNetPath) + defNet := Net{} + if err := util.LoadNet(defPath, &defNet); err != nil { + return nil, fmt.Errorf("error loading net: %v", err) + } + + return append(nets, defNet), nil +} diff --git a/networking/networking.go b/networking/networking.go index bb65d0a..1a95bfa 100644 --- a/networking/networking.go +++ b/networking/networking.go @@ -39,8 +39,18 @@ type activeNet struct { ipn *net.IPNet } +// "base" struct that's populated from the beginning +// describing the environment in which the container +// is running in +type containerEnv struct { + rktRoot string + contID types.UUID +} + // Networking describes the networking details of a container. type Networking struct { + containerEnv + MetadataIP net.IP contID types.UUID @@ -48,13 +58,17 @@ type Networking struct { contNS *os.File contNSPath string nets []activeNet - plugins map[string]*NetPlugin } // Setup produces a Networking object for a given container ID. -func Setup(contID types.UUID) (*Networking, error) { +func Setup(rktRoot string, contID types.UUID) (*Networking, error) { var err error - n := Networking{contID: contID} + n := Networking{ + containerEnv: containerEnv{ + rktRoot: rktRoot, + contID: contID, + }, + } defer func() { // cleanup on error @@ -74,24 +88,27 @@ func Setup(contID types.UUID) (*Networking, error) { } n.contNSPath = filepath.Join(contNSPath, "net") - n.plugins, err = LoadNetPlugins() if err != nil { return nil, fmt.Errorf("error loading plugin definitions: %v", err) } - nets, err := LoadNets() + nets, err := n.loadNets() if err != nil { return nil, fmt.Errorf("error loading network definitions: %v", err) } err = withNetNS(n.contNS, n.hostNS, func() error { - n.nets, err = setupNets(contID, n.contNSPath, n.plugins, nets) + n.nets, err = n.setupNets(n.contNSPath, nets) return err }) if err != nil { return nil, err } + if len(n.nets) == 0 { + return nil, fmt.Errorf("no nets successfully setup") + } + // last net is the default n.MetadataIP = n.nets[len(n.nets)-1].ipn.IP @@ -115,7 +132,7 @@ func (n *Networking) Teardown() { return } - teardownNets(n.contID, n.contNSPath, n.plugins, n.nets) + n.teardownNets(n.contNSPath, n.nets) if n.contNSPath == "" { return @@ -154,18 +171,12 @@ func (n *Networking) EnterContNS() error { return util.SetNS(n.contNS, syscall.CLONE_NEWNET) } -func setupNets(contID types.UUID, netns string, plugins map[string]*NetPlugin, nets []Net) ([]activeNet, error) { +func (e *containerEnv) setupNets(netns string, nets []Net) ([]activeNet, error) { var err error active := []activeNet{} for i, nt := range nets { - plugin, ok := plugins[nt.Type] - if !ok { - err = fmt.Errorf("could not find network plugin %q", nt.Type) - break - } - an := activeNet{ Net: nt, ifName: fmt.Sprintf(ifnamePattern, i), @@ -173,7 +184,7 @@ func setupNets(contID types.UUID, netns string, plugins map[string]*NetPlugin, n log.Printf("Executing net-plugin %v", nt.Type) - an.ipn, err = plugin.Add(&nt, contID, netns, nt.args, an.ifName) + an.ipn, err = e.netPluginAdd(&nt, netns, nt.args, an.ifName) if err != nil { err = fmt.Errorf("error adding network %q: %v", nt.Name, err) break @@ -185,19 +196,17 @@ func setupNets(contID types.UUID, netns string, plugins map[string]*NetPlugin, n log.Print("Done executing net plugins") if err != nil { - teardownNets(contID, netns, plugins, active) + e.teardownNets(netns, active) return nil, err } return active, nil } -func teardownNets(contID types.UUID, netns string, plugins map[string]*NetPlugin, nets []activeNet) { +func (e *containerEnv) teardownNets(netns string, nets []activeNet) { for i := len(nets) - 1; i >= 0; i-- { nt := nets[i] - plugin := plugins[nt.Type] - - err := plugin.Del(&nt.Net, contID, netns, nt.args, nt.ifName) + err := e.netPluginDel(&nt.Net, netns, nt.args, nt.ifName) if err != nil { log.Printf("Error deleting %q: %v", nt.Name, err) } diff --git a/networking/plugins/bridge/bridge.go b/networking/plugins/bridge/bridge.go index 76dc0d2..575e95d 100644 --- a/networking/plugins/bridge/bridge.go +++ b/networking/plugins/bridge/bridge.go @@ -30,35 +30,6 @@ func init() { runtime.LockOSThread() } -func usage() int { - fmt.Fprintln(os.Stderr, "USAGE: add|del CONTAINER-ID NETNS NET-CONF IF-NAME") - return 1 -} - -func main() { - if len(os.Args) != 6 { - os.Exit(usage()) - } - - var err error - - switch os.Args[1] { - case "add": - err = cmdAdd(os.Args[2], os.Args[3], os.Args[4], os.Args[5]) - - case "del": - err = cmdDel(os.Args[2], os.Args[3], os.Args[4], os.Args[5]) - - default: - os.Exit(usage()) - } - - if err != nil { - log.Printf("%v: %v", os.Args[1], err) - os.Exit(1) - } -} - func ensureBridgeAddr(br *netlink.Bridge, ipn *net.IPNet) error { addrs, err := netlink.AddrList(br, syscall.AF_INET) if err != nil && err != syscall.ENOENT { @@ -207,3 +178,37 @@ func cmdDel(contID, netns, netConf, ifName string) error { return util.DelLinkByName(ifName) }) } + +func main() { + var err error + + cmd := os.Getenv("RKT_NETPLUGIN_COMMAND") + contID := os.Getenv("RKT_NETPLUGIN_CONTID") + netns := os.Getenv("RKT_NETPLUGIN_NETNS") + ifName := os.Getenv("RKT_NETPLUGIN_IFNAME") + netConf := os.Getenv("RKT_NETPLUGIN_NETCONF") + + if cmd == "" || contID == "" || netns == "" || ifName == "" || netConf == "" { + log.Printf("Required env variable missing") + log.Print("Env: ", os.Environ()) + os.Exit(1) + } + + switch cmd { + case "ADD": + err = cmdAdd(contID, netns, netConf, ifName) + + case "DEL": + err = cmdDel(contID, netns, netConf, ifName) + + default: + log.Printf("Unknown RKT_NETPLUGIN_COMMAND: %v", cmd) + os.Exit(1) + } + + if err != nil { + log.Printf("%v: %v", os.Args[1], err) + os.Exit(1) + } + +} diff --git a/networking/plugins/veth/veth.go b/networking/plugins/veth/veth.go index bc9f380..1ba68a0 100644 --- a/networking/plugins/veth/veth.go +++ b/networking/plugins/veth/veth.go @@ -35,35 +35,6 @@ func init() { runtime.LockOSThread() } -func usage() int { - fmt.Fprintln(os.Stderr, "USAGE: add|del CONTAINER-ID NETNS NET-CONF IF-NAME ARGS") - return 1 -} - -func main() { - if len(os.Args) != 7 { - os.Exit(usage()) - } - - var err error - - switch os.Args[1] { - case "add": - err = cmdAdd(os.Args[2], os.Args[3], os.Args[4], os.Args[5], os.Args[6]) - - case "del": - err = cmdDel(os.Args[2], os.Args[3], os.Args[4], os.Args[5], os.Args[6]) - - default: - os.Exit(usage()) - } - - if err != nil { - log.Printf("%v: %v", os.Args[1], err) - os.Exit(1) - } -} - func cmdAdd(contID, netns, netConf, ifName, args string) error { var hostVethName, contIPNet string @@ -147,3 +118,37 @@ func cmdDel(contID, netns, netConf, ifName, args string) error { return util.DelLinkByName(ifName) }) } + +func main() { + var err error + + cmd := os.Getenv("RKT_NETPLUGIN_COMMAND") + contID := os.Getenv("RKT_NETPLUGIN_CONTID") + netns := os.Getenv("RKT_NETPLUGIN_NETNS") + args := os.Getenv("RKT_NETPLUGIN_ARGS") + ifName := os.Getenv("RKT_NETPLUGIN_IFNAME") + netConf := os.Getenv("RKT_NETPLUGIN_NETCONF") + + if cmd == "" || contID == "" || netns == "" || ifName == "" || netConf == "" { + log.Printf("Required env variable missing") + log.Print("Env: ", os.Environ()) + os.Exit(1) + } + + switch cmd { + case "ADD": + err = cmdAdd(contID, netns, netConf, ifName, args) + + case "DEL": + err = cmdDel(contID, netns, netConf, ifName, args) + + default: + log.Printf("Unknown RKT_NETPLUGIN_COMMAND: %v", cmd) + os.Exit(1) + } + + if err != nil { + log.Printf("%v: %v", os.Args[1], err) + os.Exit(1) + } +} diff --git a/stage1/init/init.go b/stage1/init/init.go index 8f10fd3..5b2e948 100644 --- a/stage1/init/init.go +++ b/stage1/init/init.go @@ -139,7 +139,7 @@ func stage1() int { // careful not to make another local err variable. // cmd.Run sets the one from parent scope var n *networking.Networking - n, err = networking.Setup(c.Manifest.UUID) + n, err = networking.Setup(root, c.Manifest.UUID) if err != nil { fmt.Fprintf(os.Stderr, "Failed to setup network: %v\n", err) return 6 diff --git a/stage1/rootfs/Makefile b/stage1/rootfs/Makefile index fa2cab2..50181c9 100644 --- a/stage1/rootfs/Makefile +++ b/stage1/rootfs/Makefile @@ -1,4 +1,4 @@ -_SUBDIRS=usr shim diagexec enter +_SUBDIRS=usr shim diagexec enter net-plugins net SUBDIRS=$(_SUBDIRS) aggregate export CFLAGS=-Wall -Os diff --git a/stage1/rootfs/net-plugins/.gitignore b/stage1/rootfs/net-plugins/.gitignore new file mode 100644 index 0000000..ba077a4 --- /dev/null +++ b/stage1/rootfs/net-plugins/.gitignore @@ -0,0 +1 @@ +bin diff --git a/stage1/rootfs/net-plugins/Makefile b/stage1/rootfs/net-plugins/Makefile new file mode 100644 index 0000000..e4db956 --- /dev/null +++ b/stage1/rootfs/net-plugins/Makefile @@ -0,0 +1,11 @@ +PLUGINS=bin/veth bin/bridge + +../aggregate/install.d/30net-plugins: Makefile install $(PLUGINS) + @cp install ../aggregate/install.d/30net-plugins + +.PHONY: clean +clean: + rm -f $(PLUGINS) + +test: + echo TODO diff --git a/stage1/rootfs/net-plugins/install b/stage1/rootfs/net-plugins/install new file mode 100644 index 0000000..ec09180 --- /dev/null +++ b/stage1/rootfs/net-plugins/install @@ -0,0 +1,3 @@ +DST="$ROOT/usr/lib/rkt/plugins/net" +mkdir -p $DST +install -m 0755 ../net-plugins/bin/* $DST diff --git a/stage1/rootfs/net/99-default.conf b/stage1/rootfs/net/99-default.conf new file mode 100644 index 0000000..428a8d2 --- /dev/null +++ b/stage1/rootfs/net/99-default.conf @@ -0,0 +1,9 @@ +{ + "name": "default", + "type": "veth", + "ipAlloc": { + "type": "static", + "subnet": "172.16.28.0/24" + }, + "routes": [ "0.0.0.0/0" ] +} diff --git a/stage1/rootfs/net/Makefile b/stage1/rootfs/net/Makefile new file mode 100644 index 0000000..d3f1de5 --- /dev/null +++ b/stage1/rootfs/net/Makefile @@ -0,0 +1,9 @@ +../aggregate/install.d/30net: Makefile install 99-default.conf + @cp install ../aggregate/install.d/30net + +.PHONY: clean +clean: + echo "nothing to clean" + +test: + echo TODO diff --git a/stage1/rootfs/net/install b/stage1/rootfs/net/install new file mode 100644 index 0000000..a8c3a1f --- /dev/null +++ b/stage1/rootfs/net/install @@ -0,0 +1,3 @@ +DST="$ROOT/etc/rkt/net.d" +mkdir -p $DST +install -m 0755 ../net/*.conf $DST