github.com/noxiouz/docker@v0.7.3-0.20160629055221-3d231c78e8c5/integration-cli/docker_cli_daemon_test.go (about)

     1  // +build linux
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/json"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"net"
    12  	"os"
    13  	"os/exec"
    14  	"path"
    15  	"path/filepath"
    16  	"regexp"
    17  	"strconv"
    18  	"strings"
    19  	"sync"
    20  	"syscall"
    21  	"time"
    22  
    23  	"github.com/docker/docker/pkg/integration/checker"
    24  	"github.com/docker/docker/pkg/mount"
    25  	"github.com/docker/go-units"
    26  	"github.com/docker/libnetwork/iptables"
    27  	"github.com/docker/libtrust"
    28  	"github.com/go-check/check"
    29  	"github.com/kr/pty"
    30  )
    31  
    32  // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon
    33  // command. Remove this test when we remove this.
    34  func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) {
    35  	cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug")
    36  	err := cmd.Start()
    37  	c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'"))
    38  
    39  	c.Assert(cmd.Process.Kill(), checker.IsNil)
    40  }
    41  
    42  func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) {
    43  	if err := s.d.StartWithBusybox(); err != nil {
    44  		c.Fatalf("Could not start daemon with busybox: %v", err)
    45  	}
    46  
    47  	if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil {
    48  		c.Fatalf("Could not run top1: err=%v\n%s", err, out)
    49  	}
    50  	// --restart=no by default
    51  	if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil {
    52  		c.Fatalf("Could not run top2: err=%v\n%s", err, out)
    53  	}
    54  
    55  	testRun := func(m map[string]bool, prefix string) {
    56  		var format string
    57  		for cont, shouldRun := range m {
    58  			out, err := s.d.Cmd("ps")
    59  			if err != nil {
    60  				c.Fatalf("Could not run ps: err=%v\n%q", err, out)
    61  			}
    62  			if shouldRun {
    63  				format = "%scontainer %q is not running"
    64  			} else {
    65  				format = "%scontainer %q is running"
    66  			}
    67  			if shouldRun != strings.Contains(out, cont) {
    68  				c.Fatalf(format, prefix, cont)
    69  			}
    70  		}
    71  	}
    72  
    73  	testRun(map[string]bool{"top1": true, "top2": true}, "")
    74  
    75  	if err := s.d.Restart(); err != nil {
    76  		c.Fatalf("Could not restart daemon: %v", err)
    77  	}
    78  	testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
    79  }
    80  
    81  func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) {
    82  	if err := s.d.StartWithBusybox(); err != nil {
    83  		c.Fatal(err)
    84  	}
    85  
    86  	if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
    87  		c.Fatal(err, out)
    88  	}
    89  
    90  	if err := s.d.Restart(); err != nil {
    91  		c.Fatal(err)
    92  	}
    93  
    94  	if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil {
    95  		c.Fatal(err)
    96  	}
    97  
    98  	if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
    99  		c.Fatal(err, out)
   100  	}
   101  
   102  	out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1")
   103  	c.Assert(err, check.IsNil)
   104  
   105  	if _, err := inspectMountPointJSON(out, "/foo"); err != nil {
   106  		c.Fatalf("Expected volume to exist: /foo, error: %v\n", err)
   107  	}
   108  }
   109  
   110  // #11008
   111  func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) {
   112  	err := s.d.StartWithBusybox()
   113  	c.Assert(err, check.IsNil)
   114  
   115  	out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top")
   116  	c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
   117  
   118  	out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top")
   119  	c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out))
   120  
   121  	testRun := func(m map[string]bool, prefix string) {
   122  		var format string
   123  		for name, shouldRun := range m {
   124  			out, err := s.d.Cmd("ps")
   125  			c.Assert(err, check.IsNil, check.Commentf("run ps: %v", out))
   126  			if shouldRun {
   127  				format = "%scontainer %q is not running"
   128  			} else {
   129  				format = "%scontainer %q is running"
   130  			}
   131  			c.Assert(strings.Contains(out, name), check.Equals, shouldRun, check.Commentf(format, prefix, name))
   132  		}
   133  	}
   134  
   135  	// both running
   136  	testRun(map[string]bool{"top1": true, "top2": true}, "")
   137  
   138  	out, err = s.d.Cmd("stop", "top1")
   139  	c.Assert(err, check.IsNil, check.Commentf(out))
   140  
   141  	out, err = s.d.Cmd("stop", "top2")
   142  	c.Assert(err, check.IsNil, check.Commentf(out))
   143  
   144  	// both stopped
   145  	testRun(map[string]bool{"top1": false, "top2": false}, "")
   146  
   147  	err = s.d.Restart()
   148  	c.Assert(err, check.IsNil)
   149  
   150  	// restart=always running
   151  	testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
   152  
   153  	out, err = s.d.Cmd("start", "top2")
   154  	c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out))
   155  
   156  	err = s.d.Restart()
   157  	c.Assert(err, check.IsNil)
   158  
   159  	// both running
   160  	testRun(map[string]bool{"top1": true, "top2": true}, "After second daemon restart: ")
   161  
   162  }
   163  
   164  func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) {
   165  	err := s.d.StartWithBusybox()
   166  	c.Assert(err, check.IsNil)
   167  
   168  	out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false")
   169  	c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
   170  
   171  	// wait test1 to stop
   172  	hostArgs := []string{"--host", s.d.sock()}
   173  	err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...)
   174  	c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
   175  
   176  	// record last start time
   177  	out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
   178  	c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
   179  	lastStartTime := out
   180  
   181  	err = s.d.Restart()
   182  	c.Assert(err, check.IsNil)
   183  
   184  	// test1 shouldn't restart at all
   185  	err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...)
   186  	c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
   187  
   188  	// make sure test1 isn't restarted when daemon restart
   189  	// if "StartAt" time updates, means test1 was once restarted.
   190  	out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
   191  	c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
   192  	c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts"))
   193  }
   194  
   195  func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) {
   196  	if err := s.d.Start("--iptables=false"); err != nil {
   197  		c.Fatalf("we should have been able to start the daemon with passing iptables=false: %v", err)
   198  	}
   199  }
   200  
   201  // Make sure we cannot shrink base device at daemon restart.
   202  func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *check.C) {
   203  	testRequires(c, Devicemapper)
   204  	c.Assert(s.d.Start(), check.IsNil)
   205  
   206  	oldBasesizeBytes := s.d.getBaseDeviceSize(c)
   207  	var newBasesizeBytes int64 = 1073741824 //1GB in bytes
   208  
   209  	if newBasesizeBytes < oldBasesizeBytes {
   210  		err := s.d.Restart("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
   211  		c.Assert(err, check.IsNil, check.Commentf("daemon should not have started as new base device size is less than existing base device size: %v", err))
   212  	}
   213  	c.Assert(s.d.Stop(), check.IsNil)
   214  }
   215  
   216  // Make sure we can grow base device at daemon restart.
   217  func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *check.C) {
   218  	testRequires(c, Devicemapper)
   219  	c.Assert(s.d.Start(), check.IsNil)
   220  
   221  	oldBasesizeBytes := s.d.getBaseDeviceSize(c)
   222  
   223  	var newBasesizeBytes int64 = 53687091200 //50GB in bytes
   224  
   225  	if newBasesizeBytes < oldBasesizeBytes {
   226  		c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes))))
   227  	}
   228  
   229  	err := s.d.Restart("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
   230  	c.Assert(err, check.IsNil, check.Commentf("we should have been able to start the daemon with increased base device size: %v", err))
   231  
   232  	basesizeAfterRestart := s.d.getBaseDeviceSize(c)
   233  	newBasesize, err := convertBasesize(newBasesizeBytes)
   234  	c.Assert(err, check.IsNil, check.Commentf("Error in converting base device size: %v", err))
   235  	c.Assert(newBasesize, check.Equals, basesizeAfterRestart, check.Commentf("Basesize passed is not equal to Basesize set"))
   236  	c.Assert(s.d.Stop(), check.IsNil)
   237  }
   238  
   239  // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and
   240  // no longer has an IP associated, we should gracefully handle that case and associate
   241  // an IP with it rather than fail daemon start
   242  func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) {
   243  	// rather than depending on brctl commands to verify docker0 is created and up
   244  	// let's start the daemon and stop it, and then make a modification to run the
   245  	// actual test
   246  	if err := s.d.Start(); err != nil {
   247  		c.Fatalf("Could not start daemon: %v", err)
   248  	}
   249  	if err := s.d.Stop(); err != nil {
   250  		c.Fatalf("Could not stop daemon: %v", err)
   251  	}
   252  
   253  	// now we will remove the ip from docker0 and then try starting the daemon
   254  	ipCmd := exec.Command("ip", "addr", "flush", "dev", "docker0")
   255  	stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd)
   256  	if err != nil {
   257  		c.Fatalf("failed to remove docker0 IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr)
   258  	}
   259  
   260  	if err := s.d.Start(); err != nil {
   261  		warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix"
   262  		c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning)
   263  	}
   264  }
   265  
   266  func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) {
   267  	if err := s.d.StartWithBusybox(); err != nil {
   268  		c.Fatalf("Could not start daemon with busybox: %v", err)
   269  	}
   270  
   271  	if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
   272  		c.Fatalf("Could not run top: %s, %v", out, err)
   273  	}
   274  
   275  	// get output from iptables with container running
   276  	ipTablesSearchString := "tcp dpt:80"
   277  	ipTablesCmd := exec.Command("iptables", "-nvL")
   278  	out, _, err := runCommandWithOutput(ipTablesCmd)
   279  	if err != nil {
   280  		c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
   281  	}
   282  
   283  	if !strings.Contains(out, ipTablesSearchString) {
   284  		c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
   285  	}
   286  
   287  	if err := s.d.Stop(); err != nil {
   288  		c.Fatalf("Could not stop daemon: %v", err)
   289  	}
   290  
   291  	// get output from iptables after restart
   292  	ipTablesCmd = exec.Command("iptables", "-nvL")
   293  	out, _, err = runCommandWithOutput(ipTablesCmd)
   294  	if err != nil {
   295  		c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
   296  	}
   297  
   298  	if strings.Contains(out, ipTablesSearchString) {
   299  		c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, out)
   300  	}
   301  }
   302  
   303  func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) {
   304  	if err := s.d.StartWithBusybox(); err != nil {
   305  		c.Fatalf("Could not start daemon with busybox: %v", err)
   306  	}
   307  
   308  	if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil {
   309  		c.Fatalf("Could not run top: %s, %v", out, err)
   310  	}
   311  
   312  	// get output from iptables with container running
   313  	ipTablesSearchString := "tcp dpt:80"
   314  	ipTablesCmd := exec.Command("iptables", "-nvL")
   315  	out, _, err := runCommandWithOutput(ipTablesCmd)
   316  	if err != nil {
   317  		c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
   318  	}
   319  
   320  	if !strings.Contains(out, ipTablesSearchString) {
   321  		c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
   322  	}
   323  
   324  	if err := s.d.Restart(); err != nil {
   325  		c.Fatalf("Could not restart daemon: %v", err)
   326  	}
   327  
   328  	// make sure the container is not running
   329  	runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", "top")
   330  	if err != nil {
   331  		c.Fatalf("Could not inspect on container: %s, %v", out, err)
   332  	}
   333  	if strings.TrimSpace(runningOut) != "true" {
   334  		c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut))
   335  	}
   336  
   337  	// get output from iptables after restart
   338  	ipTablesCmd = exec.Command("iptables", "-nvL")
   339  	out, _, err = runCommandWithOutput(ipTablesCmd)
   340  	if err != nil {
   341  		c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
   342  	}
   343  
   344  	if !strings.Contains(out, ipTablesSearchString) {
   345  		c.Fatalf("iptables output after restart should have contained %q, but was %q", ipTablesSearchString, out)
   346  	}
   347  }
   348  
   349  // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge
   350  // has the fe80::1 address and that a container is assigned a link-local address
   351  func (s *DockerSuite) TestDaemonIPv6Enabled(c *check.C) {
   352  	testRequires(c, IPv6)
   353  
   354  	if err := setupV6(); err != nil {
   355  		c.Fatal("Could not set up host for IPv6 tests")
   356  	}
   357  
   358  	d := NewDaemon(c)
   359  
   360  	if err := d.StartWithBusybox("--ipv6"); err != nil {
   361  		c.Fatal(err)
   362  	}
   363  	defer d.Stop()
   364  
   365  	iface, err := net.InterfaceByName("docker0")
   366  	if err != nil {
   367  		c.Fatalf("Error getting docker0 interface: %v", err)
   368  	}
   369  
   370  	addrs, err := iface.Addrs()
   371  	if err != nil {
   372  		c.Fatalf("Error getting addresses for docker0 interface: %v", err)
   373  	}
   374  
   375  	var found bool
   376  	expected := "fe80::1/64"
   377  
   378  	for i := range addrs {
   379  		if addrs[i].String() == expected {
   380  			found = true
   381  		}
   382  	}
   383  
   384  	if !found {
   385  		c.Fatalf("Bridge does not have an IPv6 Address")
   386  	}
   387  
   388  	if out, err := d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil {
   389  		c.Fatalf("Could not run container: %s, %v", out, err)
   390  	}
   391  
   392  	out, err := d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test")
   393  	out = strings.Trim(out, " \r\n'")
   394  
   395  	if err != nil {
   396  		c.Fatalf("Error inspecting container: %s, %v", out, err)
   397  	}
   398  
   399  	if ip := net.ParseIP(out); ip == nil {
   400  		c.Fatalf("Container should have a link-local IPv6 address")
   401  	}
   402  
   403  	out, err = d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test")
   404  	out = strings.Trim(out, " \r\n'")
   405  
   406  	if err != nil {
   407  		c.Fatalf("Error inspecting container: %s, %v", out, err)
   408  	}
   409  
   410  	if ip := net.ParseIP(out); ip != nil {
   411  		c.Fatalf("Container should not have a global IPv6 address: %v", out)
   412  	}
   413  
   414  	if err := teardownV6(); err != nil {
   415  		c.Fatal("Could not perform teardown for IPv6 tests")
   416  	}
   417  
   418  }
   419  
   420  // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR
   421  // that running containers are given a link-local and global IPv6 address
   422  func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) {
   423  	// IPv6 setup is messing with local bridge address.
   424  	testRequires(c, SameHostDaemon)
   425  	err := setupV6()
   426  	c.Assert(err, checker.IsNil, check.Commentf("Could not set up host for IPv6 tests"))
   427  
   428  	err = s.d.StartWithBusybox("--ipv6", "--fixed-cidr-v6='2001:db8:2::/64'", "--default-gateway-v6='2001:db8:2::100'")
   429  	c.Assert(err, checker.IsNil, check.Commentf("Could not start daemon with busybox: %v", err))
   430  
   431  	out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest")
   432  	c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err))
   433  
   434  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test")
   435  	out = strings.Trim(out, " \r\n'")
   436  
   437  	c.Assert(err, checker.IsNil, check.Commentf(out))
   438  
   439  	ip := net.ParseIP(out)
   440  	c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address"))
   441  
   442  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.IPv6Gateway}}'", "ipv6test")
   443  	c.Assert(err, checker.IsNil, check.Commentf(out))
   444  
   445  	c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway"))
   446  
   447  	err = teardownV6()
   448  	c.Assert(err, checker.IsNil, check.Commentf("Could not perform teardown for IPv6 tests"))
   449  }
   450  
   451  // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR
   452  // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR
   453  func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) {
   454  	// IPv6 setup is messing with local bridge address.
   455  	testRequires(c, SameHostDaemon)
   456  	err := setupV6()
   457  	c.Assert(err, checker.IsNil)
   458  
   459  	err = s.d.StartWithBusybox("--ipv6", "--fixed-cidr-v6='2001:db8:1::/64'")
   460  	c.Assert(err, checker.IsNil)
   461  
   462  	out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox")
   463  	c.Assert(err, checker.IsNil)
   464  
   465  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test")
   466  	c.Assert(err, checker.IsNil)
   467  	c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff")
   468  
   469  	err = teardownV6()
   470  	c.Assert(err, checker.IsNil)
   471  }
   472  
   473  func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) {
   474  	c.Assert(s.d.Start("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level"))
   475  }
   476  
   477  func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) {
   478  	if err := s.d.Start("--log-level=debug"); err != nil {
   479  		c.Fatal(err)
   480  	}
   481  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
   482  	if !strings.Contains(string(content), `level=debug`) {
   483  		c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content))
   484  	}
   485  }
   486  
   487  func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) {
   488  	// we creating new daemons to create new logFile
   489  	if err := s.d.Start("--log-level=fatal"); err != nil {
   490  		c.Fatal(err)
   491  	}
   492  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
   493  	if strings.Contains(string(content), `level=debug`) {
   494  		c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content))
   495  	}
   496  }
   497  
   498  func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) {
   499  	if err := s.d.Start("-D"); err != nil {
   500  		c.Fatal(err)
   501  	}
   502  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
   503  	if !strings.Contains(string(content), `level=debug`) {
   504  		c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content))
   505  	}
   506  }
   507  
   508  func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) {
   509  	if err := s.d.Start("--debug"); err != nil {
   510  		c.Fatal(err)
   511  	}
   512  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
   513  	if !strings.Contains(string(content), `level=debug`) {
   514  		c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content))
   515  	}
   516  }
   517  
   518  func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) {
   519  	if err := s.d.Start("--debug", "--log-level=fatal"); err != nil {
   520  		c.Fatal(err)
   521  	}
   522  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
   523  	if !strings.Contains(string(content), `level=debug`) {
   524  		c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content))
   525  	}
   526  }
   527  
   528  func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) {
   529  	listeningPorts := [][]string{
   530  		{"0.0.0.0", "0.0.0.0", "5678"},
   531  		{"127.0.0.1", "127.0.0.1", "1234"},
   532  		{"localhost", "127.0.0.1", "1235"},
   533  	}
   534  
   535  	cmdArgs := make([]string, 0, len(listeningPorts)*2)
   536  	for _, hostDirective := range listeningPorts {
   537  		cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2]))
   538  	}
   539  
   540  	if err := s.d.StartWithBusybox(cmdArgs...); err != nil {
   541  		c.Fatalf("Could not start daemon with busybox: %v", err)
   542  	}
   543  
   544  	for _, hostDirective := range listeningPorts {
   545  		output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true")
   546  		if err == nil {
   547  			c.Fatalf("Container should not start, expected port already allocated error: %q", output)
   548  		} else if !strings.Contains(output, "port is already allocated") {
   549  			c.Fatalf("Expected port is already allocated error: %q", output)
   550  		}
   551  	}
   552  }
   553  
   554  func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) {
   555  	// TODO: skip or update for Windows daemon
   556  	os.Remove("/etc/docker/key.json")
   557  	if err := s.d.Start(); err != nil {
   558  		c.Fatalf("Could not start daemon: %v", err)
   559  	}
   560  	s.d.Stop()
   561  
   562  	k, err := libtrust.LoadKeyFile("/etc/docker/key.json")
   563  	if err != nil {
   564  		c.Fatalf("Error opening key file")
   565  	}
   566  	kid := k.KeyID()
   567  	// Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF)
   568  	if len(kid) != 59 {
   569  		c.Fatalf("Bad key ID: %s", kid)
   570  	}
   571  }
   572  
   573  func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) {
   574  	// TODO: skip or update for Windows daemon
   575  	os.Remove("/etc/docker/key.json")
   576  	k1, err := libtrust.GenerateECP256PrivateKey()
   577  	if err != nil {
   578  		c.Fatalf("Error generating private key: %s", err)
   579  	}
   580  	if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil {
   581  		c.Fatalf("Error creating .docker directory: %s", err)
   582  	}
   583  	if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil {
   584  		c.Fatalf("Error saving private key: %s", err)
   585  	}
   586  
   587  	if err := s.d.Start(); err != nil {
   588  		c.Fatalf("Could not start daemon: %v", err)
   589  	}
   590  	s.d.Stop()
   591  
   592  	k2, err := libtrust.LoadKeyFile("/etc/docker/key.json")
   593  	if err != nil {
   594  		c.Fatalf("Error opening key file")
   595  	}
   596  	if k1.KeyID() != k2.KeyID() {
   597  		c.Fatalf("Key not migrated")
   598  	}
   599  }
   600  
   601  // GH#11320 - verify that the daemon exits on failure properly
   602  // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means
   603  // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required
   604  func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) {
   605  	//attempt to start daemon with incorrect flags (we know -b and --bip conflict)
   606  	if err := s.d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil {
   607  		//verify we got the right error
   608  		if !strings.Contains(err.Error(), "Daemon exited") {
   609  			c.Fatalf("Expected daemon not to start, got %v", err)
   610  		}
   611  		// look in the log and make sure we got the message that daemon is shutting down
   612  		runCmd := exec.Command("grep", "Error starting daemon", s.d.LogFileName())
   613  		if out, _, err := runCommandWithOutput(runCmd); err != nil {
   614  			c.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err)
   615  		}
   616  	} else {
   617  		//if we didn't get an error and the daemon is running, this is a failure
   618  		c.Fatal("Conflicting options should cause the daemon to error out with a failure")
   619  	}
   620  }
   621  
   622  func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) {
   623  	d := s.d
   624  	err := d.Start("--bridge", "nosuchbridge")
   625  	c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail"))
   626  	defer d.Restart()
   627  
   628  	bridgeName := "external-bridge"
   629  	bridgeIP := "192.169.1.1/24"
   630  	_, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
   631  
   632  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
   633  	c.Assert(err, check.IsNil, check.Commentf(out))
   634  	defer deleteInterface(c, bridgeName)
   635  
   636  	err = d.StartWithBusybox("--bridge", bridgeName)
   637  	c.Assert(err, check.IsNil)
   638  
   639  	ipTablesSearchString := bridgeIPNet.String()
   640  	ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
   641  	out, _, err = runCommandWithOutput(ipTablesCmd)
   642  	c.Assert(err, check.IsNil)
   643  
   644  	c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
   645  		check.Commentf("iptables output should have contained %q, but was %q",
   646  			ipTablesSearchString, out))
   647  
   648  	_, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top")
   649  	c.Assert(err, check.IsNil)
   650  
   651  	containerIP := d.findContainerIP("ExtContainer")
   652  	ip := net.ParseIP(containerIP)
   653  	c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
   654  		check.Commentf("Container IP-Address must be in the same subnet range : %s",
   655  			containerIP))
   656  }
   657  
   658  func createInterface(c *check.C, ifType string, ifName string, ipNet string) (string, error) {
   659  	args := []string{"link", "add", "name", ifName, "type", ifType}
   660  	ipLinkCmd := exec.Command("ip", args...)
   661  	out, _, err := runCommandWithOutput(ipLinkCmd)
   662  	if err != nil {
   663  		return out, err
   664  	}
   665  
   666  	ifCfgCmd := exec.Command("ifconfig", ifName, ipNet, "up")
   667  	out, _, err = runCommandWithOutput(ifCfgCmd)
   668  	return out, err
   669  }
   670  
   671  func deleteInterface(c *check.C, ifName string) {
   672  	ifCmd := exec.Command("ip", "link", "delete", ifName)
   673  	out, _, err := runCommandWithOutput(ifCmd)
   674  	c.Assert(err, check.IsNil, check.Commentf(out))
   675  
   676  	flushCmd := exec.Command("iptables", "-t", "nat", "--flush")
   677  	out, _, err = runCommandWithOutput(flushCmd)
   678  	c.Assert(err, check.IsNil, check.Commentf(out))
   679  
   680  	flushCmd = exec.Command("iptables", "--flush")
   681  	out, _, err = runCommandWithOutput(flushCmd)
   682  	c.Assert(err, check.IsNil, check.Commentf(out))
   683  }
   684  
   685  func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) {
   686  	// TestDaemonBridgeIP Steps
   687  	// 1. Delete the existing docker0 Bridge
   688  	// 2. Set --bip daemon configuration and start the new Docker Daemon
   689  	// 3. Check if the bip config has taken effect using ifconfig and iptables commands
   690  	// 4. Launch a Container and make sure the IP-Address is in the expected subnet
   691  	// 5. Delete the docker0 Bridge
   692  	// 6. Restart the Docker Daemon (via deferred action)
   693  	//    This Restart takes care of bringing docker0 interface back to auto-assigned IP
   694  
   695  	defaultNetworkBridge := "docker0"
   696  	deleteInterface(c, defaultNetworkBridge)
   697  
   698  	d := s.d
   699  
   700  	bridgeIP := "192.169.1.1/24"
   701  	ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
   702  
   703  	err := d.StartWithBusybox("--bip", bridgeIP)
   704  	c.Assert(err, check.IsNil)
   705  	defer d.Restart()
   706  
   707  	ifconfigSearchString := ip.String()
   708  	ifconfigCmd := exec.Command("ifconfig", defaultNetworkBridge)
   709  	out, _, _, err := runCommandWithStdoutStderr(ifconfigCmd)
   710  	c.Assert(err, check.IsNil)
   711  
   712  	c.Assert(strings.Contains(out, ifconfigSearchString), check.Equals, true,
   713  		check.Commentf("ifconfig output should have contained %q, but was %q",
   714  			ifconfigSearchString, out))
   715  
   716  	ipTablesSearchString := bridgeIPNet.String()
   717  	ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
   718  	out, _, err = runCommandWithOutput(ipTablesCmd)
   719  	c.Assert(err, check.IsNil)
   720  
   721  	c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
   722  		check.Commentf("iptables output should have contained %q, but was %q",
   723  			ipTablesSearchString, out))
   724  
   725  	out, err = d.Cmd("run", "-d", "--name", "test", "busybox", "top")
   726  	c.Assert(err, check.IsNil)
   727  
   728  	containerIP := d.findContainerIP("test")
   729  	ip = net.ParseIP(containerIP)
   730  	c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
   731  		check.Commentf("Container IP-Address must be in the same subnet range : %s",
   732  			containerIP))
   733  	deleteInterface(c, defaultNetworkBridge)
   734  }
   735  
   736  func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) {
   737  	if err := s.d.Start(); err != nil {
   738  		c.Fatalf("Could not start daemon: %v", err)
   739  	}
   740  	defer s.d.Restart()
   741  	if err := s.d.Stop(); err != nil {
   742  		c.Fatalf("Could not stop daemon: %v", err)
   743  	}
   744  
   745  	// now we will change the docker0's IP and then try starting the daemon
   746  	bridgeIP := "192.169.100.1/24"
   747  	_, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
   748  
   749  	ipCmd := exec.Command("ifconfig", "docker0", bridgeIP)
   750  	stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd)
   751  	if err != nil {
   752  		c.Fatalf("failed to change docker0's IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr)
   753  	}
   754  
   755  	if err := s.d.Start("--bip", bridgeIP); err != nil {
   756  		c.Fatalf("Could not start daemon: %v", err)
   757  	}
   758  
   759  	//check if the iptables contains new bridgeIP MASQUERADE rule
   760  	ipTablesSearchString := bridgeIPNet.String()
   761  	ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
   762  	out, _, err := runCommandWithOutput(ipTablesCmd)
   763  	if err != nil {
   764  		c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
   765  	}
   766  	if !strings.Contains(out, ipTablesSearchString) {
   767  		c.Fatalf("iptables output should have contained new MASQUERADE rule with IP %q, but was %q", ipTablesSearchString, out)
   768  	}
   769  }
   770  
   771  func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) {
   772  	d := s.d
   773  
   774  	bridgeName := "external-bridge"
   775  	bridgeIP := "192.169.1.1/24"
   776  
   777  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
   778  	c.Assert(err, check.IsNil, check.Commentf(out))
   779  	defer deleteInterface(c, bridgeName)
   780  
   781  	args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"}
   782  	err = d.StartWithBusybox(args...)
   783  	c.Assert(err, check.IsNil)
   784  	defer d.Restart()
   785  
   786  	for i := 0; i < 4; i++ {
   787  		cName := "Container" + strconv.Itoa(i)
   788  		out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
   789  		if err != nil {
   790  			c.Assert(strings.Contains(out, "no available IPv4 addresses"), check.Equals, true,
   791  				check.Commentf("Could not run a Container : %s %s", err.Error(), out))
   792  		}
   793  	}
   794  }
   795  
   796  func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) {
   797  	d := s.d
   798  
   799  	bridgeName := "external-bridge"
   800  	bridgeIP := "10.2.2.1/16"
   801  
   802  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
   803  	c.Assert(err, check.IsNil, check.Commentf(out))
   804  	defer deleteInterface(c, bridgeName)
   805  
   806  	err = d.StartWithBusybox("--bip", bridgeIP, "--fixed-cidr", "10.2.2.0/24")
   807  	c.Assert(err, check.IsNil)
   808  	defer s.d.Restart()
   809  
   810  	out, err = d.Cmd("run", "-d", "--name", "bb", "busybox", "top")
   811  	c.Assert(err, checker.IsNil, check.Commentf(out))
   812  	defer d.Cmd("stop", "bb")
   813  
   814  	out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
   815  	c.Assert(out, checker.Equals, "10.2.2.0\n")
   816  
   817  	out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
   818  	c.Assert(err, checker.IsNil, check.Commentf(out))
   819  	c.Assert(out, checker.Equals, "10.2.2.2\n")
   820  }
   821  
   822  func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check.C) {
   823  	d := s.d
   824  
   825  	bridgeName := "external-bridge"
   826  	bridgeIP := "172.27.42.1/16"
   827  
   828  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
   829  	c.Assert(err, check.IsNil, check.Commentf(out))
   830  	defer deleteInterface(c, bridgeName)
   831  
   832  	err = d.StartWithBusybox("--bridge", bridgeName, "--fixed-cidr", bridgeIP)
   833  	c.Assert(err, check.IsNil)
   834  	defer s.d.Restart()
   835  
   836  	out, err = d.Cmd("run", "-d", "busybox", "top")
   837  	c.Assert(err, check.IsNil, check.Commentf(out))
   838  	cid1 := strings.TrimSpace(out)
   839  	defer d.Cmd("stop", cid1)
   840  }
   841  
   842  func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) {
   843  	defaultNetworkBridge := "docker0"
   844  	deleteInterface(c, defaultNetworkBridge)
   845  
   846  	d := s.d
   847  
   848  	bridgeIP := "192.169.1.1"
   849  	bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP)
   850  
   851  	err := d.StartWithBusybox("--bip", bridgeIPNet)
   852  	c.Assert(err, check.IsNil)
   853  	defer d.Restart()
   854  
   855  	expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP)
   856  	out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
   857  	c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
   858  		check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'",
   859  			bridgeIP, strings.TrimSpace(out)))
   860  	deleteInterface(c, defaultNetworkBridge)
   861  }
   862  
   863  func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) {
   864  	defaultNetworkBridge := "docker0"
   865  	deleteInterface(c, defaultNetworkBridge)
   866  
   867  	d := s.d
   868  
   869  	bridgeIP := "192.169.1.1"
   870  	bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP)
   871  	gatewayIP := "192.169.1.254"
   872  
   873  	err := d.StartWithBusybox("--bip", bridgeIPNet, "--default-gateway", gatewayIP)
   874  	c.Assert(err, check.IsNil)
   875  	defer d.Restart()
   876  
   877  	expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP)
   878  	out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
   879  	c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
   880  		check.Commentf("Explicit default gateway should be %s, but default route was '%s'",
   881  			gatewayIP, strings.TrimSpace(out)))
   882  	deleteInterface(c, defaultNetworkBridge)
   883  }
   884  
   885  func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainerSubnet(c *check.C) {
   886  	defaultNetworkBridge := "docker0"
   887  	deleteInterface(c, defaultNetworkBridge)
   888  
   889  	// Program a custom default gateway outside of the container subnet, daemon should accept it and start
   890  	err := s.d.StartWithBusybox("--bip", "172.16.0.10/16", "--fixed-cidr", "172.16.1.0/24", "--default-gateway", "172.16.0.254")
   891  	c.Assert(err, check.IsNil)
   892  
   893  	deleteInterface(c, defaultNetworkBridge)
   894  	s.d.Restart()
   895  }
   896  
   897  func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *check.C) {
   898  	testRequires(c, DaemonIsLinux, SameHostDaemon)
   899  
   900  	// Start daemon without docker0 bridge
   901  	defaultNetworkBridge := "docker0"
   902  	deleteInterface(c, defaultNetworkBridge)
   903  
   904  	d := NewDaemon(c)
   905  	discoveryBackend := "consul://consuladdr:consulport/some/path"
   906  	err := d.Start(fmt.Sprintf("--cluster-store=%s", discoveryBackend))
   907  	c.Assert(err, checker.IsNil)
   908  
   909  	// Start daemon with docker0 bridge
   910  	ifconfigCmd := exec.Command("ifconfig", defaultNetworkBridge)
   911  	_, err = runCommand(ifconfigCmd)
   912  	c.Assert(err, check.IsNil)
   913  
   914  	err = d.Restart(fmt.Sprintf("--cluster-store=%s", discoveryBackend))
   915  	c.Assert(err, checker.IsNil)
   916  
   917  	d.Stop()
   918  }
   919  
   920  func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) {
   921  	d := s.d
   922  
   923  	ipStr := "192.170.1.1/24"
   924  	ip, _, _ := net.ParseCIDR(ipStr)
   925  	args := []string{"--ip", ip.String()}
   926  	err := d.StartWithBusybox(args...)
   927  	c.Assert(err, check.IsNil)
   928  	defer d.Restart()
   929  
   930  	out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
   931  	c.Assert(err, check.NotNil,
   932  		check.Commentf("Running a container must fail with an invalid --ip option"))
   933  	c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true)
   934  
   935  	ifName := "dummy"
   936  	out, err = createInterface(c, "dummy", ifName, ipStr)
   937  	c.Assert(err, check.IsNil, check.Commentf(out))
   938  	defer deleteInterface(c, ifName)
   939  
   940  	_, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
   941  	c.Assert(err, check.IsNil)
   942  
   943  	ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
   944  	out, _, err = runCommandWithOutput(ipTablesCmd)
   945  	c.Assert(err, check.IsNil)
   946  
   947  	regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String())
   948  	matched, _ := regexp.MatchString(regex, out)
   949  	c.Assert(matched, check.Equals, true,
   950  		check.Commentf("iptables output should have contained %q, but was %q", regex, out))
   951  }
   952  
   953  func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) {
   954  	testRequires(c, bridgeNfIptables)
   955  	d := s.d
   956  
   957  	bridgeName := "external-bridge"
   958  	bridgeIP := "192.169.1.1/24"
   959  
   960  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
   961  	c.Assert(err, check.IsNil, check.Commentf(out))
   962  	defer deleteInterface(c, bridgeName)
   963  
   964  	args := []string{"--bridge", bridgeName, "--icc=false"}
   965  	err = d.StartWithBusybox(args...)
   966  	c.Assert(err, check.IsNil)
   967  	defer d.Restart()
   968  
   969  	ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD")
   970  	out, _, err = runCommandWithOutput(ipTablesCmd)
   971  	c.Assert(err, check.IsNil)
   972  
   973  	regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
   974  	matched, _ := regexp.MatchString(regex, out)
   975  	c.Assert(matched, check.Equals, true,
   976  		check.Commentf("iptables output should have contained %q, but was %q", regex, out))
   977  
   978  	// Pinging another container must fail with --icc=false
   979  	pingContainers(c, d, true)
   980  
   981  	ipStr := "192.171.1.1/24"
   982  	ip, _, _ := net.ParseCIDR(ipStr)
   983  	ifName := "icc-dummy"
   984  
   985  	createInterface(c, "dummy", ifName, ipStr)
   986  
   987  	// But, Pinging external or a Host interface must succeed
   988  	pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String())
   989  	runArgs := []string{"--rm", "busybox", "sh", "-c", pingCmd}
   990  	_, err = d.Cmd("run", runArgs...)
   991  	c.Assert(err, check.IsNil)
   992  }
   993  
   994  func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) {
   995  	d := s.d
   996  
   997  	bridgeName := "external-bridge"
   998  	bridgeIP := "192.169.1.1/24"
   999  
  1000  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  1001  	c.Assert(err, check.IsNil, check.Commentf(out))
  1002  	defer deleteInterface(c, bridgeName)
  1003  
  1004  	args := []string{"--bridge", bridgeName, "--icc=false"}
  1005  	err = d.StartWithBusybox(args...)
  1006  	c.Assert(err, check.IsNil)
  1007  	defer d.Restart()
  1008  
  1009  	ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD")
  1010  	out, _, err = runCommandWithOutput(ipTablesCmd)
  1011  	c.Assert(err, check.IsNil)
  1012  
  1013  	regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
  1014  	matched, _ := regexp.MatchString(regex, out)
  1015  	c.Assert(matched, check.Equals, true,
  1016  		check.Commentf("iptables output should have contained %q, but was %q", regex, out))
  1017  
  1018  	out, err = d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567")
  1019  	c.Assert(err, check.IsNil, check.Commentf(out))
  1020  
  1021  	out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567")
  1022  	c.Assert(err, check.IsNil, check.Commentf(out))
  1023  }
  1024  
  1025  func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) {
  1026  	bridgeName := "external-bridge"
  1027  	bridgeIP := "192.169.1.1/24"
  1028  
  1029  	out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
  1030  	c.Assert(err, check.IsNil, check.Commentf(out))
  1031  	defer deleteInterface(c, bridgeName)
  1032  
  1033  	err = s.d.StartWithBusybox("--bridge", bridgeName, "--icc=false")
  1034  	c.Assert(err, check.IsNil)
  1035  	defer s.d.Restart()
  1036  
  1037  	_, err = s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top")
  1038  	c.Assert(err, check.IsNil)
  1039  	_, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top")
  1040  	c.Assert(err, check.IsNil)
  1041  
  1042  	childIP := s.d.findContainerIP("child")
  1043  	parentIP := s.d.findContainerIP("parent")
  1044  
  1045  	sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
  1046  	destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
  1047  	if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) {
  1048  		c.Fatal("Iptables rules not found")
  1049  	}
  1050  
  1051  	s.d.Cmd("rm", "--link", "parent/http")
  1052  	if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) {
  1053  		c.Fatal("Iptables rules should be removed when unlink")
  1054  	}
  1055  
  1056  	s.d.Cmd("kill", "child")
  1057  	s.d.Cmd("kill", "parent")
  1058  }
  1059  
  1060  func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) {
  1061  	testRequires(c, DaemonIsLinux)
  1062  
  1063  	if err := s.d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil {
  1064  		c.Fatal(err)
  1065  	}
  1066  
  1067  	out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)")
  1068  	if err != nil {
  1069  		c.Fatal(out, err)
  1070  	}
  1071  
  1072  	outArr := strings.Split(out, "\n")
  1073  	if len(outArr) < 2 {
  1074  		c.Fatalf("got unexpected output: %s", out)
  1075  	}
  1076  	nofile := strings.TrimSpace(outArr[0])
  1077  	nproc := strings.TrimSpace(outArr[1])
  1078  
  1079  	if nofile != "42" {
  1080  		c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile)
  1081  	}
  1082  	if nproc != "2048" {
  1083  		c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  1084  	}
  1085  
  1086  	// Now restart daemon with a new default
  1087  	if err := s.d.Restart("--default-ulimit", "nofile=43"); err != nil {
  1088  		c.Fatal(err)
  1089  	}
  1090  
  1091  	out, err = s.d.Cmd("start", "-a", "test")
  1092  	if err != nil {
  1093  		c.Fatal(err)
  1094  	}
  1095  
  1096  	outArr = strings.Split(out, "\n")
  1097  	if len(outArr) < 2 {
  1098  		c.Fatalf("got unexpected output: %s", out)
  1099  	}
  1100  	nofile = strings.TrimSpace(outArr[0])
  1101  	nproc = strings.TrimSpace(outArr[1])
  1102  
  1103  	if nofile != "43" {
  1104  		c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile)
  1105  	}
  1106  	if nproc != "2048" {
  1107  		c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  1108  	}
  1109  }
  1110  
  1111  // #11315
  1112  func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) {
  1113  	if err := s.d.StartWithBusybox(); err != nil {
  1114  		c.Fatal(err)
  1115  	}
  1116  
  1117  	if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil {
  1118  		c.Fatal(err, out)
  1119  	}
  1120  
  1121  	if out, err := s.d.Cmd("rename", "test", "test2"); err != nil {
  1122  		c.Fatal(err, out)
  1123  	}
  1124  
  1125  	if err := s.d.Restart(); err != nil {
  1126  		c.Fatal(err)
  1127  	}
  1128  
  1129  	if out, err := s.d.Cmd("start", "test2"); err != nil {
  1130  		c.Fatal(err, out)
  1131  	}
  1132  }
  1133  
  1134  func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) {
  1135  	if err := s.d.StartWithBusybox(); err != nil {
  1136  		c.Fatal(err)
  1137  	}
  1138  
  1139  	out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  1140  	c.Assert(err, check.IsNil, check.Commentf(out))
  1141  	id, err := s.d.getIDByName("test")
  1142  	c.Assert(err, check.IsNil)
  1143  
  1144  	logPath := filepath.Join(s.d.root, "containers", id, id+"-json.log")
  1145  
  1146  	if _, err := os.Stat(logPath); err != nil {
  1147  		c.Fatal(err)
  1148  	}
  1149  	f, err := os.Open(logPath)
  1150  	if err != nil {
  1151  		c.Fatal(err)
  1152  	}
  1153  	var res struct {
  1154  		Log    string    `json:"log"`
  1155  		Stream string    `json:"stream"`
  1156  		Time   time.Time `json:"time"`
  1157  	}
  1158  	if err := json.NewDecoder(f).Decode(&res); err != nil {
  1159  		c.Fatal(err)
  1160  	}
  1161  	if res.Log != "testline\n" {
  1162  		c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  1163  	}
  1164  	if res.Stream != "stdout" {
  1165  		c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  1166  	}
  1167  	if !time.Now().After(res.Time) {
  1168  		c.Fatalf("Log time %v in future", res.Time)
  1169  	}
  1170  }
  1171  
  1172  func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) {
  1173  	if err := s.d.StartWithBusybox(); err != nil {
  1174  		c.Fatal(err)
  1175  	}
  1176  
  1177  	out, err := s.d.Cmd("run", "--name=test", "--log-driver=none", "busybox", "echo", "testline")
  1178  	if err != nil {
  1179  		c.Fatal(out, err)
  1180  	}
  1181  	id, err := s.d.getIDByName("test")
  1182  	c.Assert(err, check.IsNil)
  1183  
  1184  	logPath := filepath.Join(s.d.root, "containers", id, id+"-json.log")
  1185  
  1186  	if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  1187  		c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  1188  	}
  1189  }
  1190  
  1191  func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) {
  1192  	if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  1193  		c.Fatal(err)
  1194  	}
  1195  
  1196  	out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  1197  	if err != nil {
  1198  		c.Fatal(out, err)
  1199  	}
  1200  	id, err := s.d.getIDByName("test")
  1201  	c.Assert(err, check.IsNil)
  1202  
  1203  	logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  1204  
  1205  	if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  1206  		c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  1207  	}
  1208  }
  1209  
  1210  func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) {
  1211  	if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  1212  		c.Fatal(err)
  1213  	}
  1214  
  1215  	out, err := s.d.Cmd("run", "--name=test", "--log-driver=json-file", "busybox", "echo", "testline")
  1216  	if err != nil {
  1217  		c.Fatal(out, err)
  1218  	}
  1219  	id, err := s.d.getIDByName("test")
  1220  	c.Assert(err, check.IsNil)
  1221  
  1222  	logPath := filepath.Join(s.d.root, "containers", id, id+"-json.log")
  1223  
  1224  	if _, err := os.Stat(logPath); err != nil {
  1225  		c.Fatal(err)
  1226  	}
  1227  	f, err := os.Open(logPath)
  1228  	if err != nil {
  1229  		c.Fatal(err)
  1230  	}
  1231  	var res struct {
  1232  		Log    string    `json:"log"`
  1233  		Stream string    `json:"stream"`
  1234  		Time   time.Time `json:"time"`
  1235  	}
  1236  	if err := json.NewDecoder(f).Decode(&res); err != nil {
  1237  		c.Fatal(err)
  1238  	}
  1239  	if res.Log != "testline\n" {
  1240  		c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  1241  	}
  1242  	if res.Stream != "stdout" {
  1243  		c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  1244  	}
  1245  	if !time.Now().After(res.Time) {
  1246  		c.Fatalf("Log time %v in future", res.Time)
  1247  	}
  1248  }
  1249  
  1250  func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) {
  1251  	c.Assert(s.d.StartWithBusybox("--log-driver=none"), checker.IsNil)
  1252  
  1253  	out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  1254  	c.Assert(err, checker.IsNil, check.Commentf(out))
  1255  
  1256  	out, err = s.d.Cmd("logs", "test")
  1257  	c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver"))
  1258  	expected := `"logs" command is supported only for "json-file" and "journald" logging drivers (got: none)`
  1259  	c.Assert(out, checker.Contains, expected)
  1260  }
  1261  
  1262  func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) {
  1263  	if err := s.d.StartWithBusybox(); err != nil {
  1264  		c.Fatal(err)
  1265  	}
  1266  
  1267  	// Now create 4 containers
  1268  	if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1269  		c.Fatalf("Error creating container: %q", err)
  1270  	}
  1271  	if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1272  		c.Fatalf("Error creating container: %q", err)
  1273  	}
  1274  	if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1275  		c.Fatalf("Error creating container: %q", err)
  1276  	}
  1277  	if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1278  		c.Fatalf("Error creating container: %q", err)
  1279  	}
  1280  
  1281  	s.d.Stop()
  1282  
  1283  	s.d.Start("--log-level=debug")
  1284  	s.d.Stop()
  1285  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1286  	if strings.Contains(string(content), "....") {
  1287  		c.Fatalf("Debug level should not have ....\n%s", string(content))
  1288  	}
  1289  
  1290  	s.d.Start("--log-level=error")
  1291  	s.d.Stop()
  1292  	content, _ = ioutil.ReadFile(s.d.logFile.Name())
  1293  	if strings.Contains(string(content), "....") {
  1294  		c.Fatalf("Error level should not have ....\n%s", string(content))
  1295  	}
  1296  
  1297  	s.d.Start("--log-level=info")
  1298  	s.d.Stop()
  1299  	content, _ = ioutil.ReadFile(s.d.logFile.Name())
  1300  	if !strings.Contains(string(content), "....") {
  1301  		c.Fatalf("Info level should have ....\n%s", string(content))
  1302  	}
  1303  }
  1304  
  1305  func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) {
  1306  	dir, err := ioutil.TempDir("", "socket-cleanup-test")
  1307  	if err != nil {
  1308  		c.Fatal(err)
  1309  	}
  1310  	defer os.RemoveAll(dir)
  1311  
  1312  	sockPath := filepath.Join(dir, "docker.sock")
  1313  	if err := s.d.Start("--host", "unix://"+sockPath); err != nil {
  1314  		c.Fatal(err)
  1315  	}
  1316  
  1317  	if _, err := os.Stat(sockPath); err != nil {
  1318  		c.Fatal("socket does not exist")
  1319  	}
  1320  
  1321  	if err := s.d.Stop(); err != nil {
  1322  		c.Fatal(err)
  1323  	}
  1324  
  1325  	if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) {
  1326  		c.Fatal("unix socket is not cleaned up")
  1327  	}
  1328  }
  1329  
  1330  func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) {
  1331  	type Config struct {
  1332  		Crv string `json:"crv"`
  1333  		D   string `json:"d"`
  1334  		Kid string `json:"kid"`
  1335  		Kty string `json:"kty"`
  1336  		X   string `json:"x"`
  1337  		Y   string `json:"y"`
  1338  	}
  1339  
  1340  	os.Remove("/etc/docker/key.json")
  1341  	if err := s.d.Start(); err != nil {
  1342  		c.Fatalf("Failed to start daemon: %v", err)
  1343  	}
  1344  
  1345  	if err := s.d.Stop(); err != nil {
  1346  		c.Fatalf("Could not stop daemon: %v", err)
  1347  	}
  1348  
  1349  	config := &Config{}
  1350  	bytes, err := ioutil.ReadFile("/etc/docker/key.json")
  1351  	if err != nil {
  1352  		c.Fatalf("Error reading key.json file: %s", err)
  1353  	}
  1354  
  1355  	// byte[] to Data-Struct
  1356  	if err := json.Unmarshal(bytes, &config); err != nil {
  1357  		c.Fatalf("Error Unmarshal: %s", err)
  1358  	}
  1359  
  1360  	//replace config.Kid with the fake value
  1361  	config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
  1362  
  1363  	// NEW Data-Struct to byte[]
  1364  	newBytes, err := json.Marshal(&config)
  1365  	if err != nil {
  1366  		c.Fatalf("Error Marshal: %s", err)
  1367  	}
  1368  
  1369  	// write back
  1370  	if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
  1371  		c.Fatalf("Error ioutil.WriteFile: %s", err)
  1372  	}
  1373  
  1374  	defer os.Remove("/etc/docker/key.json")
  1375  
  1376  	if err := s.d.Start(); err == nil {
  1377  		c.Fatalf("It should not be successful to start daemon with wrong key: %v", err)
  1378  	}
  1379  
  1380  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1381  
  1382  	if !strings.Contains(string(content), "Public Key ID does not match") {
  1383  		c.Fatal("Missing KeyID message from daemon logs")
  1384  	}
  1385  }
  1386  
  1387  func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) {
  1388  	if err := s.d.StartWithBusybox(); err != nil {
  1389  		c.Fatalf("Could not start daemon with busybox: %v", err)
  1390  	}
  1391  
  1392  	out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat")
  1393  	if err != nil {
  1394  		c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out)
  1395  	}
  1396  	containerID := strings.TrimSpace(out)
  1397  
  1398  	if out, err := s.d.Cmd("kill", containerID); err != nil {
  1399  		c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out)
  1400  	}
  1401  
  1402  	if err := s.d.Restart(); err != nil {
  1403  		c.Fatalf("Could not restart daemon: %v", err)
  1404  	}
  1405  
  1406  	errchan := make(chan error)
  1407  	go func() {
  1408  		if out, err := s.d.Cmd("wait", containerID); err != nil {
  1409  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  1410  		}
  1411  		close(errchan)
  1412  	}()
  1413  
  1414  	select {
  1415  	case <-time.After(5 * time.Second):
  1416  		c.Fatal("Waiting on a stopped (killed) container timed out")
  1417  	case err := <-errchan:
  1418  		if err != nil {
  1419  			c.Fatal(err)
  1420  		}
  1421  	}
  1422  }
  1423  
  1424  // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint
  1425  func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) {
  1426  	const (
  1427  		testDaemonHTTPSAddr = "tcp://localhost:4271"
  1428  	)
  1429  
  1430  	if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1431  		"--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1432  		c.Fatalf("Could not start daemon with busybox: %v", err)
  1433  	}
  1434  
  1435  	daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1436  	out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1437  	if err != nil {
  1438  		c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1439  	}
  1440  }
  1441  
  1442  // TestHttpsRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints.
  1443  // https://github.com/docker/docker/issues/19280
  1444  func (s *DockerDaemonSuite) TestHttpsRun(c *check.C) {
  1445  	const (
  1446  		testDaemonHTTPSAddr = "tcp://localhost:4271"
  1447  	)
  1448  
  1449  	if err := s.d.StartWithBusybox("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1450  		"--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1451  		c.Fatalf("Could not start daemon with busybox: %v", err)
  1452  	}
  1453  
  1454  	daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1455  	out, err := s.d.CmdWithArgs(daemonArgs, "run", "busybox", "echo", "TLS response")
  1456  	if err != nil {
  1457  		c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1458  	}
  1459  
  1460  	if !strings.Contains(out, "TLS response") {
  1461  		c.Fatalf("expected output to include `TLS response`, got %v", out)
  1462  	}
  1463  }
  1464  
  1465  // TestTlsVerify verifies that --tlsverify=false turns on tls
  1466  func (s *DockerDaemonSuite) TestTlsVerify(c *check.C) {
  1467  	out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput()
  1468  	if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") {
  1469  		c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out))
  1470  	}
  1471  }
  1472  
  1473  // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  1474  // by using a rogue client certificate and checks that it fails with the expected error.
  1475  func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
  1476  	const (
  1477  		errBadCertificate   = "bad certificate"
  1478  		testDaemonHTTPSAddr = "tcp://localhost:4271"
  1479  	)
  1480  
  1481  	if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1482  		"--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1483  		c.Fatalf("Could not start daemon with busybox: %v", err)
  1484  	}
  1485  
  1486  	daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1487  	out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1488  	if err == nil || !strings.Contains(out, errBadCertificate) {
  1489  		c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  1490  	}
  1491  }
  1492  
  1493  // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  1494  // which provides a rogue server certificate and checks that it fails with the expected error
  1495  func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) {
  1496  	const (
  1497  		errCaUnknown             = "x509: certificate signed by unknown authority"
  1498  		testDaemonRogueHTTPSAddr = "tcp://localhost:4272"
  1499  	)
  1500  	if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem",
  1501  		"--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHTTPSAddr); err != nil {
  1502  		c.Fatalf("Could not start daemon with busybox: %v", err)
  1503  	}
  1504  
  1505  	daemonArgs := []string{"--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1506  	out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1507  	if err == nil || !strings.Contains(out, errCaUnknown) {
  1508  		c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  1509  	}
  1510  }
  1511  
  1512  func pingContainers(c *check.C, d *Daemon, expectFailure bool) {
  1513  	var dargs []string
  1514  	if d != nil {
  1515  		dargs = []string{"--host", d.sock()}
  1516  	}
  1517  
  1518  	args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top")
  1519  	dockerCmd(c, args...)
  1520  
  1521  	args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c")
  1522  	pingCmd := "ping -c 1 %s -W 1"
  1523  	args = append(args, fmt.Sprintf(pingCmd, "alias1"))
  1524  	_, _, err := dockerCmdWithError(args...)
  1525  
  1526  	if expectFailure {
  1527  		c.Assert(err, check.NotNil)
  1528  	} else {
  1529  		c.Assert(err, check.IsNil)
  1530  	}
  1531  
  1532  	args = append(dargs, "rm", "-f", "container1")
  1533  	dockerCmd(c, args...)
  1534  }
  1535  
  1536  func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) {
  1537  	c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1538  
  1539  	socket := filepath.Join(s.d.folder, "docker.sock")
  1540  
  1541  	out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox")
  1542  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1543  	c.Assert(s.d.Restart(), check.IsNil)
  1544  }
  1545  
  1546  // os.Kill should kill daemon ungracefully, leaving behind container mounts.
  1547  // A subsequent daemon restart shoud clean up said mounts.
  1548  func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *check.C) {
  1549  	c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1550  
  1551  	out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1552  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1553  	id := strings.TrimSpace(out)
  1554  	c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1555  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1556  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1557  
  1558  	// container mounts should exist even after daemon has crashed.
  1559  	comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1560  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment)
  1561  
  1562  	// kill the container
  1563  	runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", id)
  1564  	if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1565  		c.Fatalf("Failed to run ctr, ExitCode: %d, err: %v output: %s id: %s\n", ec, err, out, id)
  1566  	}
  1567  
  1568  	// restart daemon.
  1569  	if err := s.d.Restart(); err != nil {
  1570  		c.Fatal(err)
  1571  	}
  1572  
  1573  	// Now, container mounts should be gone.
  1574  	mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1575  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1576  	comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1577  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1578  }
  1579  
  1580  // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts.
  1581  func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) {
  1582  	c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1583  
  1584  	out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1585  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1586  	id := strings.TrimSpace(out)
  1587  
  1588  	// Send SIGINT and daemon should clean up
  1589  	c.Assert(s.d.cmd.Process.Signal(os.Interrupt), check.IsNil)
  1590  	// Wait for the daemon to stop.
  1591  	c.Assert(<-s.d.wait, checker.IsNil)
  1592  
  1593  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1594  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1595  
  1596  	comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1597  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1598  }
  1599  
  1600  func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1601  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1602  	c.Assert(s.d.StartWithBusybox("-b", "none"), check.IsNil)
  1603  
  1604  	out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1605  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1606  	c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1607  		check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1608  
  1609  	out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1610  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1611  	c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1612  		check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1613  	// the extra grep and awk clean up the output of `ip` to only list the number and name of
  1614  	// interfaces, allowing for different versions of ip (e.g. inside and outside the container) to
  1615  	// be used while still verifying that the interface list is the exact same
  1616  	cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1617  	stdout := bytes.NewBuffer(nil)
  1618  	cmd.Stdout = stdout
  1619  	if err := cmd.Run(); err != nil {
  1620  		c.Fatal("Failed to get host network interface")
  1621  	}
  1622  	out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1623  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1624  	c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout),
  1625  		check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out))
  1626  }
  1627  
  1628  func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1629  	if err := s.d.StartWithBusybox(); err != nil {
  1630  		t.Fatal(err)
  1631  	}
  1632  	if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1633  		t.Fatal(out, err)
  1634  	}
  1635  
  1636  	if err := s.d.Restart(); err != nil {
  1637  		t.Fatal(err)
  1638  	}
  1639  	// Container 'test' should be removed without error
  1640  	if out, err := s.d.Cmd("rm", "test"); err != nil {
  1641  		t.Fatal(out, err)
  1642  	}
  1643  }
  1644  
  1645  func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1646  	if err := s.d.StartWithBusybox(); err != nil {
  1647  		c.Fatal(err)
  1648  	}
  1649  	out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1650  	if err != nil {
  1651  		c.Fatal(out, err)
  1652  	}
  1653  
  1654  	// Get sandbox key via inspect
  1655  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1656  	if err != nil {
  1657  		c.Fatalf("Error inspecting container: %s, %v", out, err)
  1658  	}
  1659  	fileName := strings.Trim(out, " \r\n'")
  1660  
  1661  	if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1662  		c.Fatal(out, err)
  1663  	}
  1664  
  1665  	// Test if the file still exists
  1666  	out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1667  	out = strings.TrimSpace(out)
  1668  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1669  	c.Assert(out, check.Equals, fileName, check.Commentf("Output: %s", out))
  1670  
  1671  	// Remove the container and restart the daemon
  1672  	if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1673  		c.Fatal(out, err)
  1674  	}
  1675  
  1676  	if err := s.d.Restart(); err != nil {
  1677  		c.Fatal(err)
  1678  	}
  1679  
  1680  	// Test again and see now the netns file does not exist
  1681  	out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1682  	out = strings.TrimSpace(out)
  1683  	c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out))
  1684  }
  1685  
  1686  // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1687  func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) {
  1688  	host := "tcp://localhost:4271"
  1689  	c.Assert(s.d.Start("-H", host), check.IsNil)
  1690  	cmd := exec.Command(dockerBinary, "-H", host, "info")
  1691  	cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}
  1692  	out, _, err := runCommandWithOutput(cmd)
  1693  	c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out))
  1694  	c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true)
  1695  
  1696  }
  1697  
  1698  func setupV6() error {
  1699  	// Hack to get the right IPv6 address on docker0, which has already been created
  1700  	return exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run()
  1701  }
  1702  
  1703  func teardownV6() error {
  1704  	return exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run()
  1705  }
  1706  
  1707  func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1708  	c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1709  
  1710  	out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1711  	c.Assert(err, check.IsNil)
  1712  	id := strings.TrimSpace(out)
  1713  
  1714  	_, err = s.d.Cmd("stop", id)
  1715  	c.Assert(err, check.IsNil)
  1716  	_, err = s.d.Cmd("wait", id)
  1717  	c.Assert(err, check.IsNil)
  1718  
  1719  	out, err = s.d.Cmd("ps", "-q")
  1720  	c.Assert(err, check.IsNil)
  1721  	c.Assert(out, check.Equals, "")
  1722  
  1723  	c.Assert(s.d.Restart(), check.IsNil)
  1724  
  1725  	out, err = s.d.Cmd("ps", "-q")
  1726  	c.Assert(err, check.IsNil)
  1727  	c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1728  }
  1729  
  1730  func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1731  	if err := s.d.StartWithBusybox("--log-opt=max-size=1k"); err != nil {
  1732  		c.Fatal(err)
  1733  	}
  1734  	name := "logtest"
  1735  	out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top")
  1736  	c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1737  
  1738  	out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name)
  1739  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1740  	c.Assert(out, checker.Contains, "max-size:1k")
  1741  	c.Assert(out, checker.Contains, "max-file:5")
  1742  
  1743  	out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name)
  1744  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1745  	c.Assert(strings.TrimSpace(out), checker.Equals, "json-file")
  1746  }
  1747  
  1748  func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1749  	if err := s.d.StartWithBusybox(); err != nil {
  1750  		c.Fatal(err)
  1751  	}
  1752  	if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1753  		c.Fatal(err, out)
  1754  	}
  1755  	if out, err := s.d.Cmd("pause", "test"); err != nil {
  1756  		c.Fatal(err, out)
  1757  	}
  1758  	if err := s.d.Restart(); err != nil {
  1759  		c.Fatal(err)
  1760  	}
  1761  
  1762  	errchan := make(chan error)
  1763  	go func() {
  1764  		out, err := s.d.Cmd("start", "test")
  1765  		if err != nil {
  1766  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  1767  		}
  1768  		name := strings.TrimSpace(out)
  1769  		if name != "test" {
  1770  			errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1771  		}
  1772  		close(errchan)
  1773  	}()
  1774  
  1775  	select {
  1776  	case <-time.After(5 * time.Second):
  1777  		c.Fatal("Waiting on start a container timed out")
  1778  	case err := <-errchan:
  1779  		if err != nil {
  1780  			c.Fatal(err)
  1781  		}
  1782  	}
  1783  }
  1784  
  1785  func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1786  	c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1787  
  1788  	out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1789  	c.Assert(err, check.IsNil, check.Commentf(out))
  1790  
  1791  	c.Assert(s.d.Restart(), check.IsNil)
  1792  
  1793  	out, err = s.d.Cmd("volume", "rm", "test")
  1794  	c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1795  	c.Assert(out, checker.Contains, "in use")
  1796  }
  1797  
  1798  func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1799  	c.Assert(s.d.Start(), check.IsNil)
  1800  
  1801  	_, err := s.d.Cmd("volume", "create", "--name", "test")
  1802  	c.Assert(err, check.IsNil)
  1803  	c.Assert(s.d.Restart(), check.IsNil)
  1804  
  1805  	_, err = s.d.Cmd("volume", "inspect", "test")
  1806  	c.Assert(err, check.IsNil)
  1807  }
  1808  
  1809  func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1810  	c.Assert(s.d.Start("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1811  	expected := "Failed to set log opts: syslog-address should be in form proto://address"
  1812  	runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1813  	if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1814  		c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1815  	}
  1816  }
  1817  
  1818  func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) {
  1819  	c.Assert(s.d.Start("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1820  	expected := "Failed to set log opts: invalid fluentd-address corrupted:c: "
  1821  	runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1822  	if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1823  		c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1824  	}
  1825  }
  1826  
  1827  func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) {
  1828  	s.d.useDefaultHost = true
  1829  	defer func() {
  1830  		s.d.useDefaultHost = false
  1831  	}()
  1832  	c.Assert(s.d.Start(), check.IsNil)
  1833  }
  1834  
  1835  func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTlsHost(c *check.C) {
  1836  	s.d.useDefaultTLSHost = true
  1837  	defer func() {
  1838  		s.d.useDefaultTLSHost = false
  1839  	}()
  1840  	if err := s.d.Start(
  1841  		"--tlsverify",
  1842  		"--tlscacert", "fixtures/https/ca.pem",
  1843  		"--tlscert", "fixtures/https/server-cert.pem",
  1844  		"--tlskey", "fixtures/https/server-key.pem"); err != nil {
  1845  		c.Fatalf("Could not start daemon: %v", err)
  1846  	}
  1847  
  1848  	// The client with --tlsverify should also use default host localhost:2376
  1849  	tmpHost := os.Getenv("DOCKER_HOST")
  1850  	defer func() {
  1851  		os.Setenv("DOCKER_HOST", tmpHost)
  1852  	}()
  1853  
  1854  	os.Setenv("DOCKER_HOST", "")
  1855  
  1856  	out, _ := dockerCmd(
  1857  		c,
  1858  		"--tlsverify",
  1859  		"--tlscacert", "fixtures/https/ca.pem",
  1860  		"--tlscert", "fixtures/https/client-cert.pem",
  1861  		"--tlskey", "fixtures/https/client-key.pem",
  1862  		"version",
  1863  	)
  1864  	if !strings.Contains(out, "Server") {
  1865  		c.Fatalf("docker version should return information of server side")
  1866  	}
  1867  }
  1868  
  1869  func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1870  	defaultNetworkBridge := "docker0"
  1871  	deleteInterface(c, defaultNetworkBridge)
  1872  
  1873  	bridgeIP := "192.169.1.1"
  1874  	bridgeRange := bridgeIP + "/30"
  1875  
  1876  	err := s.d.StartWithBusybox("--bip", bridgeRange)
  1877  	c.Assert(err, check.IsNil)
  1878  	defer s.d.Restart()
  1879  
  1880  	var cont int
  1881  	for {
  1882  		contName := fmt.Sprintf("container%d", cont)
  1883  		_, err = s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1884  		if err != nil {
  1885  			// pool exhausted
  1886  			break
  1887  		}
  1888  		ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1889  		c.Assert(err, check.IsNil)
  1890  
  1891  		c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1892  		cont++
  1893  	}
  1894  }
  1895  
  1896  // Test daemon for no space left on device error
  1897  func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) {
  1898  	testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1899  
  1900  	testDir, err := ioutil.TempDir("", "no-space-left-on-device-test")
  1901  	c.Assert(err, checker.IsNil)
  1902  	defer os.RemoveAll(testDir)
  1903  	c.Assert(mount.MakeRShared(testDir), checker.IsNil)
  1904  	defer mount.Unmount(testDir)
  1905  
  1906  	// create a 2MiB image and mount it as graph root
  1907  	// Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:jessie (which is what the test suite runs under if run from the Makefile)
  1908  	dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=2 count=0")
  1909  	out, _, err := runCommandWithOutput(exec.Command("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img"))) // `mkfs.ext4` is not in busybox
  1910  	c.Assert(err, checker.IsNil, check.Commentf(out))
  1911  
  1912  	cmd := exec.Command("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img"))
  1913  	loout, err := cmd.CombinedOutput()
  1914  	c.Assert(err, checker.IsNil)
  1915  	loopname := strings.TrimSpace(string(loout))
  1916  	defer exec.Command("losetup", "-d", loopname).Run()
  1917  
  1918  	dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", fmt.Sprintf("mkdir -p /test/test-mount && mount -t ext4 -no loop,rw %v /test/test-mount", loopname))
  1919  	defer mount.Unmount(filepath.Join(testDir, "test-mount"))
  1920  
  1921  	err = s.d.Start("--graph", filepath.Join(testDir, "test-mount"))
  1922  	defer s.d.Stop()
  1923  	c.Assert(err, check.IsNil)
  1924  
  1925  	// pull a repository large enough to fill the mount point
  1926  	pullOut, err := s.d.Cmd("pull", "registry:2")
  1927  	c.Assert(err, checker.NotNil, check.Commentf(pullOut))
  1928  	c.Assert(pullOut, checker.Contains, "no space left on device")
  1929  }
  1930  
  1931  // Test daemon restart with container links + auto restart
  1932  func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1933  	d := NewDaemon(c)
  1934  	defer d.Stop()
  1935  	err := d.StartWithBusybox()
  1936  	c.Assert(err, checker.IsNil)
  1937  
  1938  	parent1Args := []string{}
  1939  	parent2Args := []string{}
  1940  	wg := sync.WaitGroup{}
  1941  	maxChildren := 10
  1942  	chErr := make(chan error, maxChildren)
  1943  
  1944  	for i := 0; i < maxChildren; i++ {
  1945  		wg.Add(1)
  1946  		name := fmt.Sprintf("test%d", i)
  1947  
  1948  		if i < maxChildren/2 {
  1949  			parent1Args = append(parent1Args, []string{"--link", name}...)
  1950  		} else {
  1951  			parent2Args = append(parent2Args, []string{"--link", name}...)
  1952  		}
  1953  
  1954  		go func() {
  1955  			_, err = d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1956  			chErr <- err
  1957  			wg.Done()
  1958  		}()
  1959  	}
  1960  
  1961  	wg.Wait()
  1962  	close(chErr)
  1963  	for err := range chErr {
  1964  		c.Assert(err, check.IsNil)
  1965  	}
  1966  
  1967  	parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1968  	parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1969  	parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1970  	parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1971  
  1972  	_, err = d.Cmd(parent1Args[0], parent1Args[1:]...)
  1973  	c.Assert(err, check.IsNil)
  1974  	_, err = d.Cmd(parent2Args[0], parent2Args[1:]...)
  1975  	c.Assert(err, check.IsNil)
  1976  
  1977  	err = d.Stop()
  1978  	c.Assert(err, check.IsNil)
  1979  	// clear the log file -- we don't need any of it but may for the next part
  1980  	// can ignore the error here, this is just a cleanup
  1981  	os.Truncate(d.LogFileName(), 0)
  1982  	err = d.Start()
  1983  	c.Assert(err, check.IsNil)
  1984  
  1985  	for _, num := range []string{"1", "2"} {
  1986  		out, err := d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1987  		c.Assert(err, check.IsNil)
  1988  		if strings.TrimSpace(out) != "true" {
  1989  			log, _ := ioutil.ReadFile(d.LogFileName())
  1990  			c.Fatalf("parent container is not running\n%s", string(log))
  1991  		}
  1992  	}
  1993  }
  1994  
  1995  func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1996  	testRequires(c, DaemonIsLinux)
  1997  
  1998  	cgroupParent := "test"
  1999  	name := "cgroup-test"
  2000  
  2001  	err := s.d.StartWithBusybox("--cgroup-parent", cgroupParent)
  2002  	c.Assert(err, check.IsNil)
  2003  	defer s.d.Restart()
  2004  
  2005  	out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  2006  	c.Assert(err, checker.IsNil)
  2007  	cgroupPaths := parseCgroupPaths(string(out))
  2008  	c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  2009  	out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  2010  	c.Assert(err, checker.IsNil)
  2011  	id := strings.TrimSpace(string(out))
  2012  	expectedCgroup := path.Join(cgroupParent, id)
  2013  	found := false
  2014  	for _, path := range cgroupPaths {
  2015  		if strings.HasSuffix(path, expectedCgroup) {
  2016  			found = true
  2017  			break
  2018  		}
  2019  	}
  2020  	c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  2021  }
  2022  
  2023  func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  2024  	testRequires(c, DaemonIsLinux) // Windows does not support links
  2025  	err := s.d.StartWithBusybox()
  2026  	c.Assert(err, check.IsNil)
  2027  
  2028  	out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  2029  	c.Assert(err, check.IsNil, check.Commentf(out))
  2030  
  2031  	out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  2032  	c.Assert(err, check.IsNil, check.Commentf(out))
  2033  
  2034  	c.Assert(s.d.Restart(), check.IsNil)
  2035  
  2036  	// should fail since test is not running yet
  2037  	out, err = s.d.Cmd("start", "test2")
  2038  	c.Assert(err, check.NotNil, check.Commentf(out))
  2039  
  2040  	out, err = s.d.Cmd("start", "test")
  2041  	c.Assert(err, check.IsNil, check.Commentf(out))
  2042  	out, err = s.d.Cmd("start", "-a", "test2")
  2043  	c.Assert(err, check.IsNil, check.Commentf(out))
  2044  	c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  2045  }
  2046  
  2047  func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  2048  	testRequires(c, DaemonIsLinux) // Windows does not support links
  2049  	err := s.d.StartWithBusybox()
  2050  	c.Assert(err, check.IsNil)
  2051  
  2052  	out, err := s.d.Cmd("create", "--name=test", "busybox")
  2053  	c.Assert(err, check.IsNil, check.Commentf(out))
  2054  
  2055  	out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  2056  	c.Assert(err, check.IsNil, check.Commentf(out))
  2057  	test2ID := strings.TrimSpace(out)
  2058  
  2059  	out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  2060  	test3ID := strings.TrimSpace(out)
  2061  
  2062  	c.Assert(s.d.Restart(), check.IsNil)
  2063  
  2064  	out, err = s.d.Cmd("create", "--name=test", "busybox")
  2065  	c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  2066  	// this one is no longer needed, removing simplifies the remainder of the test
  2067  	out, err = s.d.Cmd("rm", "-f", "test")
  2068  	c.Assert(err, check.IsNil, check.Commentf(out))
  2069  
  2070  	out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  2071  	c.Assert(err, check.IsNil, check.Commentf(out))
  2072  
  2073  	lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  2074  
  2075  	test2validated := false
  2076  	test3validated := false
  2077  	for _, line := range lines {
  2078  		fields := strings.Fields(line)
  2079  		names := fields[len(fields)-1]
  2080  		switch fields[0] {
  2081  		case test2ID:
  2082  			c.Assert(names, check.Equals, "test2,test3/abc")
  2083  			test2validated = true
  2084  		case test3ID:
  2085  			c.Assert(names, check.Equals, "test3")
  2086  			test3validated = true
  2087  		}
  2088  	}
  2089  
  2090  	c.Assert(test2validated, check.Equals, true)
  2091  	c.Assert(test3validated, check.Equals, true)
  2092  }
  2093  
  2094  // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers
  2095  func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) {
  2096  	// TODO(mlaventure): Not sure what would the exit code be on windows
  2097  	testRequires(t, DaemonIsLinux)
  2098  	if err := s.d.StartWithBusybox(); err != nil {
  2099  		t.Fatal(err)
  2100  	}
  2101  
  2102  	cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  2103  	defer s.d.Stop()
  2104  	if err != nil {
  2105  		t.Fatal(cid, err)
  2106  	}
  2107  	cid = strings.TrimSpace(cid)
  2108  
  2109  	pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  2110  	t.Assert(err, check.IsNil)
  2111  	pid = strings.TrimSpace(pid)
  2112  
  2113  	// Kill the daemon
  2114  	if err := s.d.Kill(); err != nil {
  2115  		t.Fatal(err)
  2116  	}
  2117  
  2118  	// kill the container
  2119  	runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", cid)
  2120  	if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  2121  		t.Fatalf("Failed to run ctr, ExitCode: %d, err: '%v' output: '%s' cid: '%s'\n", ec, err, out, cid)
  2122  	}
  2123  
  2124  	// Give time to containerd to process the command if we don't
  2125  	// the exit event might be received after we do the inspect
  2126  	pidCmd := exec.Command("kill", "-0", pid)
  2127  	_, ec, _ := runCommandWithOutput(pidCmd)
  2128  	for ec == 0 {
  2129  		time.Sleep(1 * time.Second)
  2130  		_, ec, _ = runCommandWithOutput(pidCmd)
  2131  	}
  2132  
  2133  	// restart the daemon
  2134  	if err := s.d.Start(); err != nil {
  2135  		t.Fatal(err)
  2136  	}
  2137  
  2138  	// Check that we've got the correct exit code
  2139  	out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid)
  2140  	t.Assert(err, check.IsNil)
  2141  
  2142  	out = strings.TrimSpace(out)
  2143  	if out != "143" {
  2144  		t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid)
  2145  	}
  2146  
  2147  }
  2148  
  2149  // os.Kill should kill daemon ungracefully, leaving behind live containers.
  2150  // The live containers should be known to the restarted daemon. Stopping
  2151  // them now, should remove the mounts.
  2152  func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) {
  2153  	testRequires(c, DaemonIsLinux)
  2154  	c.Assert(s.d.StartWithBusybox("--live-restore"), check.IsNil)
  2155  
  2156  	out, err := s.d.Cmd("run", "-d", "busybox", "top")
  2157  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2158  	id := strings.TrimSpace(out)
  2159  
  2160  	c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  2161  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  2162  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  2163  
  2164  	// container mounts should exist even after daemon has crashed.
  2165  	comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  2166  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment)
  2167  
  2168  	// restart daemon.
  2169  	if err := s.d.Restart("--live-restore"); err != nil {
  2170  		c.Fatal(err)
  2171  	}
  2172  
  2173  	// container should be running.
  2174  	out, err = s.d.Cmd("inspect", "--format='{{.State.Running}}'", id)
  2175  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2176  	out = strings.TrimSpace(out)
  2177  	if out != "true" {
  2178  		c.Fatalf("Container %s expected to stay alive after daemon restart", id)
  2179  	}
  2180  
  2181  	// 'docker stop' should work.
  2182  	out, err = s.d.Cmd("stop", id)
  2183  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2184  
  2185  	// Now, container mounts should be gone.
  2186  	mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  2187  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  2188  	comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  2189  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  2190  }
  2191  
  2192  // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers.
  2193  func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) {
  2194  	// TODO(mlaventure): Not sure what would the exit code be on windows
  2195  	testRequires(t, DaemonIsLinux)
  2196  	if err := s.d.StartWithBusybox("--live-restore"); err != nil {
  2197  		t.Fatal(err)
  2198  	}
  2199  
  2200  	cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  2201  	defer s.d.Stop()
  2202  	if err != nil {
  2203  		t.Fatal(cid, err)
  2204  	}
  2205  	cid = strings.TrimSpace(cid)
  2206  
  2207  	pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  2208  	t.Assert(err, check.IsNil)
  2209  	pid = strings.TrimSpace(pid)
  2210  
  2211  	// pause the container
  2212  	if _, err := s.d.Cmd("pause", cid); err != nil {
  2213  		t.Fatal(cid, err)
  2214  	}
  2215  
  2216  	// Kill the daemon
  2217  	if err := s.d.Kill(); err != nil {
  2218  		t.Fatal(err)
  2219  	}
  2220  
  2221  	// resume the container
  2222  	runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "resume", cid)
  2223  	if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  2224  		t.Fatalf("Failed to run ctr, ExitCode: %d, err: '%v' output: '%s' cid: '%s'\n", ec, err, out, cid)
  2225  	}
  2226  
  2227  	// Give time to containerd to process the command if we don't
  2228  	// the resume event might be received after we do the inspect
  2229  	pidCmd := exec.Command("kill", "-0", pid)
  2230  	_, ec, _ := runCommandWithOutput(pidCmd)
  2231  	for ec == 0 {
  2232  		time.Sleep(1 * time.Second)
  2233  		_, ec, _ = runCommandWithOutput(pidCmd)
  2234  	}
  2235  
  2236  	// restart the daemon
  2237  	if err := s.d.Start("--live-restore"); err != nil {
  2238  		t.Fatal(err)
  2239  	}
  2240  
  2241  	// Check that we've got the correct status
  2242  	out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid)
  2243  	t.Assert(err, check.IsNil)
  2244  
  2245  	out = strings.TrimSpace(out)
  2246  	if out != "running" {
  2247  		t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid)
  2248  	}
  2249  	if _, err := s.d.Cmd("kill", cid); err != nil {
  2250  		t.Fatal(err)
  2251  	}
  2252  }
  2253  
  2254  // TestRunLinksChanged checks that creating a new container with the same name does not update links
  2255  // this ensures that the old, pre gh#16032 functionality continues on
  2256  func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  2257  	testRequires(c, DaemonIsLinux) // Windows does not support links
  2258  	err := s.d.StartWithBusybox()
  2259  	c.Assert(err, check.IsNil)
  2260  
  2261  	out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  2262  	c.Assert(err, check.IsNil, check.Commentf(out))
  2263  
  2264  	out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  2265  	c.Assert(err, check.IsNil, check.Commentf(out))
  2266  	c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  2267  
  2268  	out, err = s.d.Cmd("rm", "-f", "test")
  2269  	c.Assert(err, check.IsNil, check.Commentf(out))
  2270  
  2271  	out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  2272  	c.Assert(err, check.IsNil, check.Commentf(out))
  2273  	out, err = s.d.Cmd("start", "-a", "test2")
  2274  	c.Assert(err, check.NotNil, check.Commentf(out))
  2275  	c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  2276  
  2277  	err = s.d.Restart()
  2278  	c.Assert(err, check.IsNil)
  2279  	out, err = s.d.Cmd("start", "-a", "test2")
  2280  	c.Assert(err, check.NotNil, check.Commentf(out))
  2281  	c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  2282  }
  2283  
  2284  func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  2285  	testRequires(c, DaemonIsLinux, NotPpc64le)
  2286  	newD := NewDaemon(c)
  2287  
  2288  	infoLog := "\x1b[34mINFO\x1b"
  2289  
  2290  	p, tty, err := pty.Open()
  2291  	c.Assert(err, checker.IsNil)
  2292  	defer func() {
  2293  		tty.Close()
  2294  		p.Close()
  2295  	}()
  2296  
  2297  	b := bytes.NewBuffer(nil)
  2298  	go io.Copy(b, p)
  2299  
  2300  	// Enable coloring explicitly
  2301  	newD.StartWithLogFile(tty, "--raw-logs=false")
  2302  	newD.Stop()
  2303  	c.Assert(b.String(), checker.Contains, infoLog)
  2304  
  2305  	b.Reset()
  2306  
  2307  	// Disable coloring explicitly
  2308  	newD.StartWithLogFile(tty, "--raw-logs=true")
  2309  	newD.Stop()
  2310  	c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  2311  }
  2312  
  2313  func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  2314  	testRequires(c, DaemonIsLinux, NotPpc64le)
  2315  	newD := NewDaemon(c)
  2316  
  2317  	debugLog := "\x1b[37mDEBU\x1b"
  2318  
  2319  	p, tty, err := pty.Open()
  2320  	c.Assert(err, checker.IsNil)
  2321  	defer func() {
  2322  		tty.Close()
  2323  		p.Close()
  2324  	}()
  2325  
  2326  	b := bytes.NewBuffer(nil)
  2327  	go io.Copy(b, p)
  2328  
  2329  	newD.StartWithLogFile(tty, "--debug")
  2330  	newD.Stop()
  2331  	c.Assert(b.String(), checker.Contains, debugLog)
  2332  }
  2333  
  2334  func (s *DockerSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  2335  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2336  
  2337  	// daemon config file
  2338  	daemonConfig := `{ "debug" : false }`
  2339  	configFilePath := "test.json"
  2340  
  2341  	configFile, err := os.Create(configFilePath)
  2342  	c.Assert(err, checker.IsNil)
  2343  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2344  
  2345  	d := NewDaemon(c)
  2346  	err = d.Start(fmt.Sprintf("--config-file=%s", configFilePath))
  2347  	c.Assert(err, checker.IsNil)
  2348  	defer d.Stop()
  2349  
  2350  	// daemon config file
  2351  	daemonConfig = `{
  2352  	      "cluster-store": "consul://consuladdr:consulport/some/path",
  2353  	      "cluster-advertise": "192.168.56.100:0",
  2354  	      "debug" : false
  2355  	}`
  2356  
  2357  	configFile.Close()
  2358  	os.Remove(configFilePath)
  2359  
  2360  	configFile, err = os.Create(configFilePath)
  2361  	c.Assert(err, checker.IsNil)
  2362  	defer os.Remove(configFilePath)
  2363  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2364  	configFile.Close()
  2365  
  2366  	syscall.Kill(d.cmd.Process.Pid, syscall.SIGHUP)
  2367  
  2368  	time.Sleep(3 * time.Second)
  2369  
  2370  	out, err := d.Cmd("info")
  2371  	c.Assert(err, checker.IsNil)
  2372  	c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path"))
  2373  	c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0"))
  2374  }
  2375  
  2376  // Test for #21956
  2377  func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) {
  2378  	err := s.d.StartWithBusybox("--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514")
  2379  	c.Assert(err, check.IsNil)
  2380  
  2381  	out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top")
  2382  	c.Assert(err, check.IsNil, check.Commentf(out))
  2383  	id := strings.TrimSpace(out)
  2384  
  2385  	out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id)
  2386  	c.Assert(err, check.IsNil, check.Commentf(out))
  2387  	c.Assert(out, checker.Contains, "{json-file map[]}")
  2388  }
  2389  
  2390  // Test case for #20936, #22443
  2391  func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) {
  2392  	c.Assert(s.d.Start("--max-concurrent-uploads=6", "--max-concurrent-downloads=8"), check.IsNil)
  2393  
  2394  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"`
  2395  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  2396  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2397  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2398  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2399  }
  2400  
  2401  // Test case for #20936, #22443
  2402  func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) {
  2403  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2404  
  2405  	// daemon config file
  2406  	configFilePath := "test.json"
  2407  	configFile, err := os.Create(configFilePath)
  2408  	c.Assert(err, checker.IsNil)
  2409  	defer os.Remove(configFilePath)
  2410  
  2411  	daemonConfig := `{ "max-concurrent-downloads" : 8 }`
  2412  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2413  	configFile.Close()
  2414  	c.Assert(s.d.Start(fmt.Sprintf("--config-file=%s", configFilePath)), check.IsNil)
  2415  
  2416  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  2417  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  2418  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2419  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2420  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2421  
  2422  	configFile, err = os.Create(configFilePath)
  2423  	c.Assert(err, checker.IsNil)
  2424  	daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }`
  2425  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2426  	configFile.Close()
  2427  
  2428  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2429  
  2430  	time.Sleep(3 * time.Second)
  2431  
  2432  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"`
  2433  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"`
  2434  	content, _ = ioutil.ReadFile(s.d.logFile.Name())
  2435  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2436  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2437  }
  2438  
  2439  // Test case for #20936, #22443
  2440  func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) {
  2441  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2442  
  2443  	// daemon config file
  2444  	configFilePath := "test.json"
  2445  	configFile, err := os.Create(configFilePath)
  2446  	c.Assert(err, checker.IsNil)
  2447  	defer os.Remove(configFilePath)
  2448  
  2449  	daemonConfig := `{ "max-concurrent-uploads" : null }`
  2450  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2451  	configFile.Close()
  2452  	c.Assert(s.d.Start(fmt.Sprintf("--config-file=%s", configFilePath)), check.IsNil)
  2453  
  2454  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  2455  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"`
  2456  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2457  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2458  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2459  
  2460  	configFile, err = os.Create(configFilePath)
  2461  	c.Assert(err, checker.IsNil)
  2462  	daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }`
  2463  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2464  	configFile.Close()
  2465  
  2466  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2467  
  2468  	time.Sleep(3 * time.Second)
  2469  
  2470  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"`
  2471  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  2472  	content, _ = ioutil.ReadFile(s.d.logFile.Name())
  2473  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2474  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2475  
  2476  	configFile, err = os.Create(configFilePath)
  2477  	c.Assert(err, checker.IsNil)
  2478  	daemonConfig = `{ "labels":["foo=bar"] }`
  2479  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2480  	configFile.Close()
  2481  
  2482  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2483  
  2484  	time.Sleep(3 * time.Second)
  2485  
  2486  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"`
  2487  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  2488  	content, _ = ioutil.ReadFile(s.d.logFile.Name())
  2489  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2490  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2491  }
  2492  
  2493  func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) {
  2494  	err := s.d.StartWithBusybox("-b=none", "--iptables=false")
  2495  	c.Assert(err, check.IsNil)
  2496  	s.d.c.Logf("dockerBinary %s", dockerBinary)
  2497  	out, code, err := s.d.buildImageWithOut("busyboxs",
  2498  		`FROM busybox
  2499                  RUN cat /etc/hosts`, false)
  2500  	comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err)
  2501  	c.Assert(err, check.IsNil, comment)
  2502  	c.Assert(code, check.Equals, 0, comment)
  2503  }
  2504  
  2505  // Test case for #21976
  2506  func (s *DockerDaemonSuite) TestDaemonDNSInHostMode(c *check.C) {
  2507  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2508  
  2509  	err := s.d.StartWithBusybox("--dns", "1.2.3.4")
  2510  	c.Assert(err, checker.IsNil)
  2511  
  2512  	expectedOutput := "nameserver 1.2.3.4"
  2513  	out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2514  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2515  }
  2516  
  2517  // Test case for #21976
  2518  func (s *DockerDaemonSuite) TestDaemonDNSSearchInHostMode(c *check.C) {
  2519  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2520  
  2521  	err := s.d.StartWithBusybox("--dns-search", "example.com")
  2522  	c.Assert(err, checker.IsNil)
  2523  
  2524  	expectedOutput := "search example.com"
  2525  	out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2526  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2527  }
  2528  
  2529  // Test case for #21976
  2530  func (s *DockerDaemonSuite) TestDaemonDNSOptionsInHostMode(c *check.C) {
  2531  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2532  
  2533  	err := s.d.StartWithBusybox("--dns-opt", "timeout:3")
  2534  	c.Assert(err, checker.IsNil)
  2535  
  2536  	expectedOutput := "options timeout:3"
  2537  	out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2538  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2539  }
  2540  
  2541  func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
  2542  	conf, err := ioutil.TempFile("", "config-file-")
  2543  	c.Assert(err, check.IsNil)
  2544  	configName := conf.Name()
  2545  	conf.Close()
  2546  	defer os.Remove(configName)
  2547  
  2548  	config := `
  2549  {
  2550      "runtimes": {
  2551          "oci": {
  2552              "path": "docker-runc"
  2553          },
  2554          "vm": {
  2555              "path": "/usr/local/bin/vm-manager",
  2556              "runtimeArgs": [
  2557                  "--debug"
  2558              ]
  2559          }
  2560      }
  2561  }
  2562  `
  2563  	ioutil.WriteFile(configName, []byte(config), 0644)
  2564  	err = s.d.StartWithBusybox("--config-file", configName)
  2565  	c.Assert(err, check.IsNil)
  2566  
  2567  	// Run with default runtime
  2568  	out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2569  	c.Assert(err, check.IsNil, check.Commentf(out))
  2570  
  2571  	// Run with default runtime explicitly
  2572  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2573  	c.Assert(err, check.IsNil, check.Commentf(out))
  2574  
  2575  	// Run with oci (same path as default) but keep it around
  2576  	out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2577  	c.Assert(err, check.IsNil, check.Commentf(out))
  2578  
  2579  	// Run with "vm"
  2580  	out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2581  	c.Assert(err, check.NotNil, check.Commentf(out))
  2582  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2583  
  2584  	// Reset config to only have the default
  2585  	config = `
  2586  {
  2587      "runtimes": {
  2588      }
  2589  }
  2590  `
  2591  	ioutil.WriteFile(configName, []byte(config), 0644)
  2592  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2593  	// Give daemon time to reload config
  2594  	<-time.After(1 * time.Second)
  2595  
  2596  	// Run with default runtime
  2597  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2598  	c.Assert(err, check.IsNil, check.Commentf(out))
  2599  
  2600  	// Run with "oci"
  2601  	out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2602  	c.Assert(err, check.NotNil, check.Commentf(out))
  2603  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2604  
  2605  	// Start previously created container with oci
  2606  	out, err = s.d.Cmd("start", "oci-runtime-ls")
  2607  	c.Assert(err, check.NotNil, check.Commentf(out))
  2608  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2609  
  2610  	// Check that we can't override the default runtime
  2611  	config = `
  2612  {
  2613      "runtimes": {
  2614          "runc": {
  2615              "path": "my-runc"
  2616          }
  2617      }
  2618  }
  2619  `
  2620  	ioutil.WriteFile(configName, []byte(config), 0644)
  2621  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2622  	// Give daemon time to reload config
  2623  	<-time.After(1 * time.Second)
  2624  
  2625  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2626  	c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`)
  2627  
  2628  	// Check that we can select a default runtime
  2629  	config = `
  2630  {
  2631      "default-runtime": "vm",
  2632      "runtimes": {
  2633          "oci": {
  2634              "path": "docker-runc"
  2635          },
  2636          "vm": {
  2637              "path": "/usr/local/bin/vm-manager",
  2638              "runtimeArgs": [
  2639                  "--debug"
  2640              ]
  2641          }
  2642      }
  2643  }
  2644  `
  2645  	ioutil.WriteFile(configName, []byte(config), 0644)
  2646  	syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2647  	// Give daemon time to reload config
  2648  	<-time.After(1 * time.Second)
  2649  
  2650  	out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2651  	c.Assert(err, check.NotNil, check.Commentf(out))
  2652  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2653  
  2654  	// Run with default runtime explicitly
  2655  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2656  	c.Assert(err, check.IsNil, check.Commentf(out))
  2657  }
  2658  
  2659  func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
  2660  	err := s.d.StartWithBusybox("--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2661  	c.Assert(err, check.IsNil)
  2662  
  2663  	// Run with default runtime
  2664  	out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2665  	c.Assert(err, check.IsNil, check.Commentf(out))
  2666  
  2667  	// Run with default runtime explicitly
  2668  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2669  	c.Assert(err, check.IsNil, check.Commentf(out))
  2670  
  2671  	// Run with oci (same path as default) but keep it around
  2672  	out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2673  	c.Assert(err, check.IsNil, check.Commentf(out))
  2674  
  2675  	// Run with "vm"
  2676  	out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2677  	c.Assert(err, check.NotNil, check.Commentf(out))
  2678  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2679  
  2680  	// Start a daemon without any extra runtimes
  2681  	s.d.Stop()
  2682  	err = s.d.StartWithBusybox()
  2683  	c.Assert(err, check.IsNil)
  2684  
  2685  	// Run with default runtime
  2686  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2687  	c.Assert(err, check.IsNil, check.Commentf(out))
  2688  
  2689  	// Run with "oci"
  2690  	out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2691  	c.Assert(err, check.NotNil, check.Commentf(out))
  2692  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2693  
  2694  	// Start previously created container with oci
  2695  	out, err = s.d.Cmd("start", "oci-runtime-ls")
  2696  	c.Assert(err, check.NotNil, check.Commentf(out))
  2697  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2698  
  2699  	// Check that we can't override the default runtime
  2700  	s.d.Stop()
  2701  	err = s.d.Start("--add-runtime", "runc=my-runc")
  2702  	c.Assert(err, check.NotNil)
  2703  
  2704  	content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2705  	c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`)
  2706  
  2707  	// Check that we can select a default runtime
  2708  	s.d.Stop()
  2709  	err = s.d.StartWithBusybox("--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2710  	c.Assert(err, check.IsNil)
  2711  
  2712  	out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2713  	c.Assert(err, check.NotNil, check.Commentf(out))
  2714  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2715  
  2716  	// Run with default runtime explicitly
  2717  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2718  	c.Assert(err, check.IsNil, check.Commentf(out))
  2719  }