瀏覽代碼

Support networkless containers with new docker run option '-n'

Stefan Praszalowicz 12 年之前
父節點
當前提交
3342bdb331
共有 4 個文件被更改,包括 93 次插入37 次删除
  1. 49 37
      container.go
  2. 38 0
      container_test.go
  3. 1 0
      docs/sources/commandline/command/run.rst
  4. 5 0
      lxc_template.go

+ 49 - 37
container.go

@@ -58,25 +58,26 @@ type Container struct {
 }
 }
 
 
 type Config struct {
 type Config struct {
-	Hostname     string
-	User         string
-	Memory       int64 // Memory limit (in bytes)
-	MemorySwap   int64 // Total memory usage (memory + swap); set `-1' to disable swap
-	CpuShares    int64 // CPU shares (relative weight vs. other containers)
-	AttachStdin  bool
-	AttachStdout bool
-	AttachStderr bool
-	PortSpecs    []string
-	Tty          bool // Attach standard streams to a tty, including stdin if it is not closed.
-	OpenStdin    bool // Open stdin
-	StdinOnce    bool // If true, close stdin after the 1 attached client disconnects.
-	Env          []string
-	Cmd          []string
-	Dns          []string
-	Image        string // Name of the image as it was passed by the operator (eg. could be symbolic)
-	Volumes      map[string]struct{}
-	VolumesFrom  string
-	Entrypoint   []string
+	Hostname       string
+	User           string
+	Memory         int64 // Memory limit (in bytes)
+	MemorySwap     int64 // Total memory usage (memory + swap); set `-1' to disable swap
+	CpuShares      int64 // CPU shares (relative weight vs. other containers)
+	AttachStdin    bool
+	AttachStdout   bool
+	AttachStderr   bool
+	PortSpecs      []string
+	Tty            bool // Attach standard streams to a tty, including stdin if it is not closed.
+	OpenStdin      bool // Open stdin
+	StdinOnce      bool // If true, close stdin after the 1 attached client disconnects.
+	Env            []string
+	Cmd            []string
+	Dns            []string
+	Image          string // Name of the image as it was passed by the operator (eg. could be symbolic)
+	Volumes        map[string]struct{}
+	VolumesFrom    string
+	Entrypoint     []string
+	NetworkEnabled bool
 }
 }
 
 
 type HostConfig struct {
 type HostConfig struct {
@@ -106,6 +107,7 @@ func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig,
 	flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
 	flTty := cmd.Bool("t", false, "Allocate a pseudo-tty")
 	flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
 	flMemory := cmd.Int64("m", 0, "Memory limit (in bytes)")
 	flContainerIDFile := cmd.String("cidfile", "", "Write the container ID to the file")
 	flContainerIDFile := cmd.String("cidfile", "", "Write the container ID to the file")
+	flNetwork := cmd.Bool("n", true, "Enable networking for this container")
 
 
 	if capabilities != nil && *flMemory > 0 && !capabilities.MemoryLimit {
 	if capabilities != nil && *flMemory > 0 && !capabilities.MemoryLimit {
 		//fmt.Fprintf(stdout, "WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
 		//fmt.Fprintf(stdout, "WARNING: Your kernel does not support memory limit capabilities. Limitation discarded.\n")
@@ -174,23 +176,24 @@ func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig,
 	}
 	}
 
 
 	config := &Config{
 	config := &Config{
-		Hostname:     *flHostname,
-		PortSpecs:    flPorts,
-		User:         *flUser,
-		Tty:          *flTty,
-		OpenStdin:    *flStdin,
-		Memory:       *flMemory,
-		CpuShares:    *flCpuShares,
-		AttachStdin:  flAttach.Get("stdin"),
-		AttachStdout: flAttach.Get("stdout"),
-		AttachStderr: flAttach.Get("stderr"),
-		Env:          flEnv,
-		Cmd:          runCmd,
-		Dns:          flDns,
-		Image:        image,
-		Volumes:      flVolumes,
-		VolumesFrom:  *flVolumesFrom,
-		Entrypoint:   entrypoint,
+		Hostname:       *flHostname,
+		PortSpecs:      flPorts,
+		User:           *flUser,
+		Tty:            *flTty,
+		NetworkEnabled: *flNetwork,
+		OpenStdin:      *flStdin,
+		Memory:         *flMemory,
+		CpuShares:      *flCpuShares,
+		AttachStdin:    flAttach.Get("stdin"),
+		AttachStdout:   flAttach.Get("stdout"),
+		AttachStderr:   flAttach.Get("stderr"),
+		Env:            flEnv,
+		Cmd:            runCmd,
+		Dns:            flDns,
+		Image:          image,
+		Volumes:        flVolumes,
+		VolumesFrom:    *flVolumesFrom,
+		Entrypoint:     entrypoint,
 	}
 	}
 	hostConfig := &HostConfig{
 	hostConfig := &HostConfig{
 		Binds:           binds,
 		Binds:           binds,
@@ -626,7 +629,9 @@ func (container *Container) Start(hostConfig *HostConfig) error {
 	}
 	}
 
 
 	// Networking
 	// Networking
-	params = append(params, "-g", container.network.Gateway.String())
+	if container.Config.NetworkEnabled {
+		params = append(params, "-g", container.network.Gateway.String())
+	}
 
 
 	// User
 	// User
 	if container.Config.User != "" {
 	if container.Config.User != "" {
@@ -727,6 +732,10 @@ func (container *Container) StderrPipe() (io.ReadCloser, error) {
 }
 }
 
 
 func (container *Container) allocateNetwork() error {
 func (container *Container) allocateNetwork() error {
+	if !container.Config.NetworkEnabled {
+		return nil
+	}
+
 	iface, err := container.runtime.networkManager.Allocate()
 	iface, err := container.runtime.networkManager.Allocate()
 	if err != nil {
 	if err != nil {
 		return err
 		return err
@@ -753,6 +762,9 @@ func (container *Container) allocateNetwork() error {
 }
 }
 
 
 func (container *Container) releaseNetwork() {
 func (container *Container) releaseNetwork() {
+	if !container.Config.NetworkEnabled {
+		return
+	}
 	container.network.Release()
 	container.network.Release()
 	container.network = nil
 	container.network = nil
 	container.NetworkSettings = &NetworkSettings{}
 	container.NetworkSettings = &NetworkSettings{}

+ 38 - 0
container_test.go

@@ -1251,3 +1251,41 @@ func TestRestartWithVolumes(t *testing.T) {
 		t.Fatalf("Expected volume path: %s Actual path: %s", expected, actual)
 		t.Fatalf("Expected volume path: %s Actual path: %s", expected, actual)
 	}
 	}
 }
 }
+
+func TestOnlyLoopbackExistsWhenUsingDisableNetworkOption(t *testing.T) {
+	runtime := mkRuntime(t)
+	defer nuke(runtime)
+
+	config, hc, _, err := ParseRun([]string{"-n=false", GetTestImage(runtime).ID, "ip", "addr", "show"}, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c, err := NewBuilder(runtime).Create(config)
+	if err != nil {
+		t.Fatal(err)
+	}
+	stdout, err := c.StdoutPipe()
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	defer runtime.Destroy(c)
+	if err := c.Start(hc); err != nil {
+		t.Fatal(err)
+	}
+	c.WaitTimeout(500 * time.Millisecond)
+	c.Wait()
+	output, err := ioutil.ReadAll(stdout)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	interfaces := regexp.MustCompile(`(?m)^[0-9]+: [a-zA-Z0-9]+`).FindAllString(string(output), -1)
+	if len(interfaces) != 1 {
+		t.Fatalf("Wrong interface count in test container: expected [1: lo], got [%s]", interfaces)
+	}
+	if interfaces[0] != "1: lo" {
+		t.Fatalf("Wrong interface in test container: expected [1: lo], got [%s]", interfaces)
+	}
+
+}

+ 1 - 0
docs/sources/commandline/command/run.rst

@@ -20,6 +20,7 @@
       -h="": Container host name
       -h="": Container host name
       -i=false: Keep stdin open even if not attached
       -i=false: Keep stdin open even if not attached
       -m=0: Memory limit (in bytes)
       -m=0: Memory limit (in bytes)
+      -n=true: Enable networking for this container
       -p=[]: Map a network port to the container
       -p=[]: Map a network port to the container
       -t=false: Allocate a pseudo-tty
       -t=false: Allocate a pseudo-tty
       -u="": Username or UID
       -u="": Username or UID

+ 5 - 0
lxc_template.go

@@ -13,6 +13,7 @@ lxc.utsname = {{.Id}}
 {{end}}
 {{end}}
 #lxc.aa_profile = unconfined
 #lxc.aa_profile = unconfined
 
 
+{{if .Config.NetworkEnabled}}
 # network configuration
 # network configuration
 lxc.network.type = veth
 lxc.network.type = veth
 lxc.network.flags = up
 lxc.network.flags = up
@@ -20,6 +21,10 @@ lxc.network.link = {{.NetworkSettings.Bridge}}
 lxc.network.name = eth0
 lxc.network.name = eth0
 lxc.network.mtu = 1500
 lxc.network.mtu = 1500
 lxc.network.ipv4 = {{.NetworkSettings.IPAddress}}/{{.NetworkSettings.IPPrefixLen}}
 lxc.network.ipv4 = {{.NetworkSettings.IPAddress}}/{{.NetworkSettings.IPPrefixLen}}
+{{else}}
+# Network configuration disabled
+lxc.network.type = empty
+{{end}}
 
 
 # root filesystem
 # root filesystem
 {{$ROOTFS := .RootfsPath}}
 {{$ROOTFS := .RootfsPath}}