Browse code

libcontainer/network: add netns strategy

Docker-DCO-1.1-Signed-off-by: Johan Euphrosine <proppy@google.com> (github: proppy)

Johan Euphrosine authored on 2014/03/04 07:41:38
Showing 2 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,42 @@
0
+package network
1
+
2
+import (
3
+	"fmt"
4
+	"os"
5
+	"syscall"
6
+
7
+	"github.com/dotcloud/docker/pkg/libcontainer"
8
+	"github.com/dotcloud/docker/pkg/system"
9
+)
10
+
11
+//  crosbymichael: could make a network strategy that instead of returning veth pair names it returns a pid to an existing network namespace
12
+type NetNS struct {
13
+}
14
+
15
+func (v *NetNS) Create(n *libcontainer.Network, nspid int, context libcontainer.Context) error {
16
+	nsname, exists := n.Context["nsname"]
17
+
18
+	if !exists {
19
+		return fmt.Errorf("nspath does not exist in network context")
20
+	}
21
+
22
+	context["nspath"] = fmt.Sprintf("/var/run/netns/%s", nsname)
23
+	return nil
24
+}
25
+
26
+func (v *NetNS) Initialize(config *libcontainer.Network, context libcontainer.Context) error {
27
+	nspath, exists := context["nspath"]
28
+	if !exists {
29
+		return fmt.Errorf("nspath does not exist in network context")
30
+	}
31
+
32
+	f, err := os.OpenFile(nspath, os.O_RDONLY, 0)
33
+	if err != nil {
34
+		return fmt.Errorf("failed get network namespace fd: %v", err)
35
+	}
36
+
37
+	if err := system.Setns(f.Fd(), syscall.CLONE_NEWNET); err != nil {
38
+		return fmt.Errorf("failed to setns current network namespace: %v", err)
39
+	}
40
+	return nil
41
+}
... ...
@@ -2,6 +2,7 @@ package network
2 2
 
3 3
 import (
4 4
 	"errors"
5
+
5 6
 	"github.com/dotcloud/docker/pkg/libcontainer"
6 7
 )
7 8
 
... ...
@@ -12,6 +13,7 @@ var (
12 12
 var strategies = map[string]NetworkStrategy{
13 13
 	"veth":     &Veth{},
14 14
 	"loopback": &Loopback{},
15
+	"netns":    &NetNS{},
15 16
 }
16 17
 
17 18
 // NetworkStrategy represents a specific network configuration for