Merge pull request #2727 from weaveworks/issues/2397-v2-plugin

Create a V2 Docker plugin
This commit is contained in:
Marc Carré authored and GitHub committed 2017-04-12 14:27:34 +01:00
commit 8961041469
33 files changed
+804 -307

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
{
"description": "Weave Net plugin for Docker",
"documentation": "https://weave.works",
"entrypoint": [
"/home/weave/launch.sh"
],
"interface": {
"socket": "weave.sock",
"types": [
"docker.networkdriver/1.0"
]
},
"linux": {
"capabilities": [
"CAP_SYS_ADMIN",
"CAP_NET_ADMIN"
]
},
"mounts": [
{
"destination": "/host/proc/",
"type": "bind",
"source": "/proc/",
"options": ["rbind", "rw"]
},
{
"destination": "/var/run/docker.sock",
"source": "/var/run/docker.sock",
"type": "bind",
"options": ["rbind"]
},
{
"destination": "/host/var/lib/",
"source": "/var/lib/",
"type": "bind",
"options": ["rbind"]
},
{
"destination": "/host/etc/",
"source": "/etc/",
"type": "bind",
"options": ["rbind"]
}
],
"env": [
{
"description": "Extra args to `weaver` and `plugin`",
"name": "EXTRA_ARGS",
"settable": [
"value"
],
"value": ""
},
{
"description": "Encryption password",
"name": "WEAVE_PASSWORD",
"settable": [
"value"
],
"value": ""
},
{
"description": "MTU",
"name": "WEAVE_MTU",
"settable": [
"value"
],
"value": ""
}
],
"network": {
"type": "host"
},
"workdir": ""
}
+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
set -e
# Default if not supplied - same as weave net default
IPALLOC_RANGE=${IPALLOC_RANGE:-10.32.0.0/12}
HTTP_ADDR=${WEAVE_HTTP_ADDR:-127.0.0.1:6784}
STATUS_ADDR=${WEAVE_STATUS_ADDR:-0.0.0.0:6782}
HOST_ROOT=${HOST_ROOT:-/host}
WEAVE_DIR="/host/var/lib/weave"
mkdir $WEAVE_DIR || true
echo "Starting launch.sh"
# Check if the IP range overlaps anything existing on the host
/usr/bin/weaveutil netcheck $IPALLOC_RANGE weave
STATUS=0
/usr/bin/weaveutil is-swarm-manager 2>/dev/null || STATUS=$?
if [ $STATUS -eq 0 ]; then
IS_SWARM_MANAGER=1
elif [ $STATUS -eq 20 ]; then
echo "Host swarm is not \"active\"; exiting." >&2
exit 1
fi
SWARM_MANAGER_PEERS=$(/usr/bin/weaveutil swarm-manager-peers)
# Prevent from restoring from a persisted peers list
rm -f "/restart.sentinel"
/home/weave/weave --local create-bridge \
--proc-path=/host/proc \
--weavedb-dir-path=$WEAVE_DIR \
--force
BRIDGE_OPTIONS="--datapath=datapath"
if [ "$(/home/weave/weave --local bridge-type)" = "bridge" ]; then
# TODO: Call into weave script to do this
if ! ip link show vethwe-pcap >/dev/null 2>&1; then
ip link add name vethwe-bridge type veth peer name vethwe-pcap
ip link set vethwe-bridge up
ip link set vethwe-pcap up
ip link set vethwe-bridge master weave
fi
BRIDGE_OPTIONS="--iface=vethwe-pcap"
fi
if [ -z "$IPALLOC_INIT" ]; then
IPALLOC_INIT="observer"
if [ "$IS_SWARM_MANAGER" == "1" ]; then
IPALLOC_INIT="consensus=$(echo $SWARM_MANAGER_PEERS | wc -l)"
fi
fi
exec /home/weave/weaver $EXTRA_ARGS --port=6783 $BRIDGE_OPTIONS \
--http-addr=$HTTP_ADDR --status-addr=$STATUS_ADDR \
--no-dns \
--ipalloc-range=$IPALLOC_RANGE \
--ipalloc-init $IPALLOC_INIT \
--nickname "$(hostname)" \
--log-level=debug \
--db-prefix="$WEAVE_DIR/weave" \
--plugin-v2 \
--plugin-mesh-socket='' \
$(echo $SWARM_MANAGER_PEERS | tr '\n' ' ')
-3
View File
@@ -1,3 +0,0 @@
FROM DOCKERHUB_USER/weaveARCH_EXT
ADD ./plugin /home/weave/
ENTRYPOINT ["/home/weave/plugin"]
-140
View File
@@ -1,140 +0,0 @@
package main
import (
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"path"
"strings"
"syscall"
"github.com/docker/libnetwork/ipamapi"
weaveapi "github.com/weaveworks/weave/api"
"github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/common/docker"
weavenet "github.com/weaveworks/weave/net"
ipamplugin "github.com/weaveworks/weave/plugin/ipam"
netplugin "github.com/weaveworks/weave/plugin/net"
"github.com/weaveworks/weave/plugin/skel"
)
var version = "unreleased"
var Log = common.Log
func main() {
var (
justVersion bool
address string
meshAddress string
logLevel string
noMulticastRoute bool
)
flag.BoolVar(&justVersion, "version", false, "print version and exit")
flag.StringVar(&logLevel, "log-level", "info", "logging level (debug, info, warning, error)")
flag.StringVar(&address, "socket", "/run/docker/plugins/weave.sock", "socket on which to listen")
flag.StringVar(&meshAddress, "meshsocket", "/run/docker/plugins/weavemesh.sock", "socket on which to listen in mesh mode")
flag.BoolVar(&noMulticastRoute, "no-multicast-route", false, "deprecated (this is now the default)")
flag.Parse()
if justVersion {
fmt.Printf("weave plugin %s\n", version)
os.Exit(0)
}
common.SetLogLevel(logLevel)
weave := weaveapi.NewClient(os.Getenv("WEAVE_HTTP_ADDR"), Log)
// API 1.21 is the first version that supports docker network commands
dockerClient, err := docker.NewVersionedClientFromEnv("1.21")
if err != nil {
Log.Fatalf("unable to connect to docker: %s", err)
}
Log.Println("Weave plugin", version, "Command line options:", os.Args[1:])
if noMulticastRoute {
Log.Warning("--no-multicast-route option has been removed; multicast is off by default")
}
Log.Info(dockerClient.Info())
err = run(dockerClient, weave, address, meshAddress)
if err != nil {
Log.Fatal(err)
}
}
func run(dockerClient *docker.Client, weave *weaveapi.Client, address, meshAddress string) error {
endChan := make(chan error, 1)
if address != "" {
globalListener, err := listenAndServe(dockerClient, weave, address, endChan, "global", false)
if err != nil {
return err
}
defer os.Remove(address)
defer globalListener.Close()
}
if meshAddress != "" {
meshListener, err := listenAndServe(dockerClient, weave, meshAddress, endChan, "local", true)
if err != nil {
return err
}
defer os.Remove(meshAddress)
defer meshListener.Close()
}
statusListener, err := weavenet.ListenUnixSocket("/home/weave/status.sock")
if err != nil {
return err
}
go serveStatus(statusListener)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
select {
case sig := <-sigChan:
Log.Debugf("Caught signal %s; shutting down", sig)
return nil
case err := <-endChan:
return err
}
}
func listenAndServe(dockerClient *docker.Client, weave *weaveapi.Client, address string, endChan chan<- error, scope string, withIpam bool) (net.Listener, error) {
name := strings.TrimSuffix(path.Base(address), ".sock")
d, err := netplugin.New(dockerClient, weave, name, scope)
if err != nil {
return nil, err
}
var i ipamapi.Ipam
if withIpam {
i = ipamplugin.NewIpam(weave)
}
listener, err := weavenet.ListenUnixSocket(address)
if err != nil {
return nil, err
}
Log.Printf("Listening on %s for %s scope", address, scope)
go func() {
endChan <- skel.Listen(listener, d, i)
}()
return listener, nil
}
func serveStatus(listener net.Listener) {
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
})}
if err := server.Serve(listener); err != nil {
Log.Fatalf("ListenAndServeStatus failed: %s", err)
}
}
-12
View File
@@ -1,12 +0,0 @@
package main
import (
"testing"
weavetest "github.com/weaveworks/weave/testing"
)
func TestMain(t *testing.T) {
weavetest.TrimTestArgs()
main()
}
+14
View File
@@ -25,6 +25,7 @@ import (
"github.com/weaveworks/weave/nameserver"
weavenet "github.com/weaveworks/weave/net"
"github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/plugin"
weave "github.com/weaveworks/weave/router"
)
@@ -150,6 +151,10 @@ func main() {
discoveryEndpoint string
token string
advertiseAddress string
pluginSocket string
pluginMeshSocket string
enablePlugin bool
enablePluginV2 bool
defaultDockerHost = "unix:///var/run/docker.sock"
)
@@ -195,6 +200,11 @@ func main() {
mflag.StringVar(&token, []string{"-token"}, "", "token for peer discovery")
mflag.StringVar(&advertiseAddress, []string{"-advertise-address"}, "", "address to advertise for peer discovery")
mflag.BoolVar(&enablePlugin, []string{"-plugin"}, false, "enable Docker plugin (v1)")
mflag.BoolVar(&enablePluginV2, []string{"-plugin-v2"}, false, "enable Docker plugin (v2)")
mflag.StringVar(&pluginSocket, []string{"-plugin-socket"}, "/run/docker/plugins/weave.sock", "plugin socket on which to listen")
mflag.StringVar(&pluginMeshSocket, []string{"-plugin-mesh-socket"}, "/run/docker/plugins/weavemesh.sock", "plugin socket on which to listen in mesh mode")
// crude way of detecting that we probably have been started in a
// container, with `weave launch` --> suppress misleading paths in
// mflags error messages.
@@ -396,6 +406,10 @@ func main() {
go listenAndServeHTTP(statusAddr, statusMux)
}
if enablePlugin || enablePluginV2 {
go plugin.Start(httpAddr, dockerCli, pluginSocket, pluginMeshSocket, !noDNS, enablePluginV2)
}
signals.SignalHandlerLoop(common.Log, router)
}
+26 -23
View File
@@ -14,29 +14,32 @@ var commands map[string]func([]string) error
func init() {
commands = map[string]func([]string) error{
"help": help,
"netcheck": netcheck,
"docker-tls-args": dockerTLSArgs,
"create-datapath": createDatapath,
"delete-datapath": deleteDatapath,
"check-datapath": checkDatapath,
"add-datapath-interface": addDatapathInterface,
"create-plugin-network": createPluginNetwork,
"remove-plugin-network": removePluginNetwork,
"container-addrs": containerAddrs,
"process-addrs": processAddrs,
"attach-container": attach,
"detach-container": detach,
"configure-arp": configureARP,
"check-iface": checkIface,
"del-iface": delIface,
"setup-iface": setupIface,
"list-netdevs": listNetDevs,
"cni-net": cniNet,
"cni-ipam": cniIPAM,
"expose-nat": exposeNAT,
"bridge-ip": bridgeIP,
"unique-id": uniqueID,
"help": help,
"netcheck": netcheck,
"docker-tls-args": dockerTLSArgs,
"create-datapath": createDatapath,
"delete-datapath": deleteDatapath,
"check-datapath": checkDatapath,
"add-datapath-interface": addDatapathInterface,
"create-plugin-network": createPluginNetwork,
"remove-plugin-network": removePluginNetwork,
"container-addrs": containerAddrs,
"process-addrs": processAddrs,
"attach-container": attach,
"detach-container": detach,
"configure-arp": configureARP,
"check-iface": checkIface,
"del-iface": delIface,
"setup-iface": setupIface,
"list-netdevs": listNetDevs,
"cni-net": cniNet,
"cni-ipam": cniIPAM,
"expose-nat": exposeNAT,
"bridge-ip": bridgeIP,
"unique-id": uniqueID,
"swarm-manager-peers": swarmManagerPeers,
"is-swarm-manager": isSwarmManager,
"is-docker-plugin-enabled": isDockerPluginEnabled,
}
}
+34
View File
@@ -2,8 +2,10 @@
package main
import (
"context"
"fmt"
"github.com/docker/docker/client"
docker "github.com/fsouza/go-dockerclient"
"github.com/weaveworks/weave/plugin/net"
@@ -71,6 +73,37 @@ while Weave is not running`, networkName, containers)
return nil
}
// Exits with 0 if the given plugin (v2) is enabled.
//
// Any failure due to missing plugin support is non-harmful as plugin (v2)
// cannot be enabled when Docker does not support it.
func isDockerPluginEnabled(args []string) error {
if len(args) != 1 {
cmdUsage("is-docker-plugin-enabled", "<plugin-name>")
}
pluginName := args[0]
// This is messed up: we are using docker/docker/client instead of
// fsouza/go-dockerclient because the latter does not support plugins.
c, err := client.NewEnvClient()
if err != nil {
return fmt.Errorf("unable to connect to docker: %s", err)
}
ctx := context.Background()
p, _, err := c.PluginInspectWithRaw(ctx, pluginName)
if err != nil {
return err
}
if !p.Enabled {
return fmt.Errorf("plugin %q is disabled", pluginName)
}
return nil
}
func newDockerClient() (*docker.Client, error) {
// API 1.21 is the first version that supports docker network
// commands
@@ -82,5 +115,6 @@ func newDockerClient() (*docker.Client, error) {
if err != nil {
return nil, fmt.Errorf("unable to connect to docker: %s", err)
}
return c, nil
}
+71
View File
@@ -0,0 +1,71 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/docker/docker/api/types/swarm"
"github.com/fsouza/go-dockerclient"
"github.com/pkg/errors"
)
const DOCKER_API_VERSION = "1.26"
func isSwarmManager(args []string) error {
info, err := dockerInfo()
if err != nil {
return err
}
// hack-y way to denote that a node does not belong to any swarm
if info.Swarm.LocalNodeState != swarm.LocalNodeStateActive {
os.Exit(20)
}
if !info.Swarm.ControlAvailable {
return fmt.Errorf("node is not a manager")
}
return nil
}
func swarmManagerPeers(args []string) error {
info, err := dockerInfo()
if err != nil {
return err
}
for _, managerNode := range info.Swarm.RemoteManagers {
ip, err := ipFromAddr(managerNode.Addr)
if err != nil {
return errors.Wrap(err, "ipFromAddr")
}
fmt.Println(ip)
}
return nil
}
func dockerInfo() (*docker.DockerInfo, error) {
client, err := docker.NewVersionedClientFromEnv(DOCKER_API_VERSION)
if err != nil {
return nil, errors.Wrap(err, "docker.NewVersionedClientFromEnv")
}
info, err := client.Info()
if err != nil {
return nil, errors.Wrap(err, "docker.Info")
}
return info, nil
}
func ipFromAddr(addr string) (string, error) {
parts := strings.Split(addr, ":")
if len(parts) != 2 {
return "", fmt.Errorf("invalid address: %q", addr)
}
return parts[0], nil
}