github.com/docker/docker-ce@v17.12.1-ce-rc2+incompatible/components/engine/integration-cli/docker_cli_daemon_test.go (about)

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