github.com/rita33cool1/iot-system-gateway@v0.0.0-20200911033302-e65bde238cc5/docker-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  	testdaemon "github.com/docker/docker/internal/test/daemon"
    36  	"github.com/docker/docker/opts"
    37  	"github.com/docker/docker/pkg/mount"
    38  	"github.com/docker/docker/pkg/stringid"
    39  	units "github.com/docker/go-units"
    40  	"github.com/docker/libnetwork/iptables"
    41  	"github.com/docker/libtrust"
    42  	"github.com/go-check/check"
    43  	"github.com/gotestyourself/gotestyourself/icmd"
    44  	"github.com/kr/pty"
    45  	"golang.org/x/sys/unix"
    46  )
    47  
    48  // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon
    49  // command. Remove this test when we remove this.
    50  func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) {
    51  	cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug")
    52  	err := cmd.Start()
    53  	go cmd.Wait()
    54  	c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'"))
    55  
    56  	c.Assert(cmd.Process.Kill(), checker.IsNil)
    57  }
    58  
    59  func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) {
    60  	s.d.StartWithBusybox(c)
    61  
    62  	cli.Docker(
    63  		cli.Args("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"),
    64  		cli.Daemon(s.d),
    65  	).Assert(c, icmd.Success)
    66  
    67  	cli.Docker(
    68  		cli.Args("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"),
    69  		cli.Daemon(s.d),
    70  	).Assert(c, icmd.Success)
    71  
    72  	testRun := func(m map[string]bool, prefix string) {
    73  		var format string
    74  		for cont, shouldRun := range m {
    75  			out := cli.Docker(cli.Args("ps"), cli.Daemon(s.d)).Assert(c, icmd.Success).Combined()
    76  			if shouldRun {
    77  				format = "%scontainer %q is not running"
    78  			} else {
    79  				format = "%scontainer %q is running"
    80  			}
    81  			if shouldRun != strings.Contains(out, cont) {
    82  				c.Fatalf(format, prefix, cont)
    83  			}
    84  		}
    85  	}
    86  
    87  	testRun(map[string]bool{"top1": true, "top2": true}, "")
    88  
    89  	s.d.Restart(c)
    90  	testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
    91  }
    92  
    93  func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) {
    94  	s.d.StartWithBusybox(c)
    95  
    96  	if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
    97  		c.Fatal(err, out)
    98  	}
    99  
   100  	s.d.Restart(c)
   101  
   102  	if out, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil {
   103  		c.Fatal(err, out)
   104  	}
   105  
   106  	if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
   107  		c.Fatal(err, out)
   108  	}
   109  
   110  	out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1")
   111  	c.Assert(err, check.IsNil)
   112  
   113  	if _, err := inspectMountPointJSON(out, "/foo"); err != nil {
   114  		c.Fatalf("Expected volume to exist: /foo, error: %v\n", err)
   115  	}
   116  }
   117  
   118  // #11008
   119  func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) {
   120  	s.d.StartWithBusybox(c)
   121  
   122  	out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top")
   123  	c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
   124  
   125  	out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top")
   126  	c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out))
   127  
   128  	testRun := func(m map[string]bool, prefix string) {
   129  		var format string
   130  		for name, shouldRun := range m {
   131  			out, err := s.d.Cmd("ps")
   132  			c.Assert(err, check.IsNil, check.Commentf("run ps: %v", out))
   133  			if shouldRun {
   134  				format = "%scontainer %q is not running"
   135  			} else {
   136  				format = "%scontainer %q is running"
   137  			}
   138  			c.Assert(strings.Contains(out, name), check.Equals, shouldRun, check.Commentf(format, prefix, name))
   139  		}
   140  	}
   141  
   142  	// both running
   143  	testRun(map[string]bool{"top1": true, "top2": true}, "")
   144  
   145  	out, err = s.d.Cmd("stop", "top1")
   146  	c.Assert(err, check.IsNil, check.Commentf(out))
   147  
   148  	out, err = s.d.Cmd("stop", "top2")
   149  	c.Assert(err, check.IsNil, check.Commentf(out))
   150  
   151  	// both stopped
   152  	testRun(map[string]bool{"top1": false, "top2": false}, "")
   153  
   154  	s.d.Restart(c)
   155  
   156  	// restart=always running
   157  	testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
   158  
   159  	out, err = s.d.Cmd("start", "top2")
   160  	c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out))
   161  
   162  	s.d.Restart(c)
   163  
   164  	// both running
   165  	testRun(map[string]bool{"top1": true, "top2": true}, "After second daemon restart: ")
   166  
   167  }
   168  
   169  func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) {
   170  	s.d.StartWithBusybox(c)
   171  
   172  	out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false")
   173  	c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
   174  
   175  	// wait test1 to stop
   176  	hostArgs := []string{"--host", s.d.Sock()}
   177  	err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...)
   178  	c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
   179  
   180  	// record last start time
   181  	out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
   182  	c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
   183  	lastStartTime := out
   184  
   185  	s.d.Restart(c)
   186  
   187  	// test1 shouldn't restart at all
   188  	err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...)
   189  	c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
   190  
   191  	// make sure test1 isn't restarted when daemon restart
   192  	// if "StartAt" time updates, means test1 was once restarted.
   193  	out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
   194  	c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
   195  	c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts"))
   196  }
   197  
   198  func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) {
   199  	s.d.Start(c, "--iptables=false")
   200  }
   201  
   202  // Make sure we cannot shrink base device at daemon restart.
   203  func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *check.C) {
   204  	testRequires(c, Devicemapper)
   205  	s.d.Start(c)
   206  
   207  	oldBasesizeBytes := getBaseDeviceSize(c, s.d)
   208  	var newBasesizeBytes int64 = 1073741824 //1GB in bytes
   209  
   210  	if newBasesizeBytes < oldBasesizeBytes {
   211  		err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
   212  		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))
   213  		// 'err != nil' is expected behaviour, no new daemon started,
   214  		// so no need to stop daemon.
   215  		if err != nil {
   216  			return
   217  		}
   218  	}
   219  	s.d.Stop(c)
   220  }
   221  
   222  // Make sure we can grow base device at daemon restart.
   223  func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *check.C) {
   224  	testRequires(c, Devicemapper)
   225  	s.d.Start(c)
   226  
   227  	oldBasesizeBytes := getBaseDeviceSize(c, s.d)
   228  
   229  	var newBasesizeBytes int64 = 53687091200 //50GB in bytes
   230  
   231  	if newBasesizeBytes < oldBasesizeBytes {
   232  		c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes))))
   233  	}
   234  
   235  	err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
   236  	c.Assert(err, check.IsNil, check.Commentf("we should have been able to start the daemon with increased base device size: %v", err))
   237  
   238  	basesizeAfterRestart := getBaseDeviceSize(c, s.d)
   239  	newBasesize, err := convertBasesize(newBasesizeBytes)
   240  	c.Assert(err, check.IsNil, check.Commentf("Error in converting base device size: %v", err))
   241  	c.Assert(newBasesize, check.Equals, basesizeAfterRestart, check.Commentf("Basesize passed is not equal to Basesize set"))
   242  	s.d.Stop(c)
   243  }
   244  
   245  func getBaseDeviceSize(c *check.C, d *daemon.Daemon) int64 {
   246  	info := d.Info(c)
   247  	for _, statusLine := range info.DriverStatus {
   248  		key, value := statusLine[0], statusLine[1]
   249  		if key == "Base Device Size" {
   250  			return parseDeviceSize(c, value)
   251  		}
   252  	}
   253  	c.Fatal("failed to parse Base Device Size from info")
   254  	return int64(0)
   255  }
   256  
   257  func parseDeviceSize(c *check.C, raw string) int64 {
   258  	size, err := units.RAMInBytes(strings.TrimSpace(raw))
   259  	c.Assert(err, check.IsNil)
   260  	return size
   261  }
   262  
   263  func convertBasesize(basesizeBytes int64) (int64, error) {
   264  	basesize := units.HumanSize(float64(basesizeBytes))
   265  	basesize = strings.Trim(basesize, " ")[:len(basesize)-3]
   266  	basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
   267  	if err != nil {
   268  		return 0, err
   269  	}
   270  	return int64(basesizeFloat) * 1024 * 1024 * 1024, nil
   271  }
   272  
   273  // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and
   274  // no longer has an IP associated, we should gracefully handle that case and associate
   275  // an IP with it rather than fail daemon start
   276  func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) {
   277  	// rather than depending on brctl commands to verify docker0 is created and up
   278  	// let's start the daemon and stop it, and then make a modification to run the
   279  	// actual test
   280  	s.d.Start(c)
   281  	s.d.Stop(c)
   282  
   283  	// now we will remove the ip from docker0 and then try starting the daemon
   284  	icmd.RunCommand("ip", "addr", "flush", "dev", "docker0").Assert(c, icmd.Success)
   285  
   286  	if err := s.d.StartWithError(); err != nil {
   287  		warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix"
   288  		c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning)
   289  	}
   290  }
   291  
   292  func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) {
   293  	s.d.StartWithBusybox(c)
   294  
   295  	if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
   296  		c.Fatalf("Could not run top: %s, %v", out, err)
   297  	}
   298  
   299  	ipTablesSearchString := "tcp dpt:80"
   300  
   301  	// get output from iptables with container running
   302  	verifyIPTablesContains(c, ipTablesSearchString)
   303  
   304  	s.d.Stop(c)
   305  
   306  	// get output from iptables after restart
   307  	verifyIPTablesDoesNotContains(c, ipTablesSearchString)
   308  }
   309  
   310  func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) {
   311  	s.d.StartWithBusybox(c)
   312  
   313  	if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil {
   314  		c.Fatalf("Could not run top: %s, %v", out, err)
   315  	}
   316  
   317  	// get output from iptables with container running
   318  	ipTablesSearchString := "tcp dpt:80"
   319  	verifyIPTablesContains(c, ipTablesSearchString)
   320  
   321  	s.d.Restart(c)
   322  
   323  	// make sure the container is not running
   324  	runningOut, err := s.d.Cmd("inspect", "--format={{.State.Running}}", "top")
   325  	if err != nil {
   326  		c.Fatalf("Could not inspect on container: %s, %v", runningOut, err)
   327  	}
   328  	if strings.TrimSpace(runningOut) != "true" {
   329  		c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut))
   330  	}
   331  
   332  	// get output from iptables after restart
   333  	verifyIPTablesContains(c, ipTablesSearchString)
   334  }
   335  
   336  func verifyIPTablesContains(c *check.C, ipTablesSearchString string) {
   337  	result := icmd.RunCommand("iptables", "-nvL")
   338  	result.Assert(c, icmd.Success)
   339  	if !strings.Contains(result.Combined(), ipTablesSearchString) {
   340  		c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, result.Combined())
   341  	}
   342  }
   343  
   344  func verifyIPTablesDoesNotContains(c *check.C, ipTablesSearchString string) {
   345  	result := icmd.RunCommand("iptables", "-nvL")
   346  	result.Assert(c, icmd.Success)
   347  	if strings.Contains(result.Combined(), ipTablesSearchString) {
   348  		c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, result.Combined())
   349  	}
   350  }
   351  
   352  // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge
   353  // has the fe80::1 address and that a container is assigned a link-local address
   354  func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *check.C) {
   355  	testRequires(c, IPv6)
   356  
   357  	setupV6(c)
   358  	defer teardownV6(c)
   359  
   360  	s.d.StartWithBusybox(c, "--ipv6")
   361  
   362  	iface, err := net.InterfaceByName("docker0")
   363  	if err != nil {
   364  		c.Fatalf("Error getting docker0 interface: %v", err)
   365  	}
   366  
   367  	addrs, err := iface.Addrs()
   368  	if err != nil {
   369  		c.Fatalf("Error getting addresses for docker0 interface: %v", err)
   370  	}
   371  
   372  	var found bool
   373  	expected := "fe80::1/64"
   374  
   375  	for i := range addrs {
   376  		if addrs[i].String() == expected {
   377  			found = true
   378  			break
   379  		}
   380  	}
   381  
   382  	if !found {
   383  		c.Fatalf("Bridge does not have an IPv6 Address")
   384  	}
   385  
   386  	if out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil {
   387  		c.Fatalf("Could not run container: %s, %v", out, err)
   388  	}
   389  
   390  	out, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test")
   391  	out = strings.Trim(out, " \r\n'")
   392  
   393  	if err != nil {
   394  		c.Fatalf("Error inspecting container: %s, %v", out, err)
   395  	}
   396  
   397  	if ip := net.ParseIP(out); ip == nil {
   398  		c.Fatalf("Container should have a link-local IPv6 address")
   399  	}
   400  
   401  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test")
   402  	out = strings.Trim(out, " \r\n'")
   403  
   404  	if err != nil {
   405  		c.Fatalf("Error inspecting container: %s, %v", out, err)
   406  	}
   407  
   408  	if ip := net.ParseIP(out); ip != nil {
   409  		c.Fatalf("Container should not have a global IPv6 address: %v", out)
   410  	}
   411  }
   412  
   413  // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR
   414  // that running containers are given a link-local and global IPv6 address
   415  func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) {
   416  	// IPv6 setup is messing with local bridge address.
   417  	testRequires(c, SameHostDaemon)
   418  	// Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with
   419  	// ipv6 enabled
   420  	deleteInterface(c, "docker0")
   421  
   422  	s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100")
   423  
   424  	out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest")
   425  	c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err))
   426  
   427  	out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
   428  	out = strings.Trim(out, " \r\n'")
   429  
   430  	c.Assert(err, checker.IsNil, check.Commentf(out))
   431  
   432  	ip := net.ParseIP(out)
   433  	c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address"))
   434  
   435  	out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test")
   436  	c.Assert(err, checker.IsNil, check.Commentf(out))
   437  
   438  	c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway"))
   439  }
   440  
   441  // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR
   442  // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR
   443  func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) {
   444  	// IPv6 setup is messing with local bridge address.
   445  	testRequires(c, SameHostDaemon)
   446  	// Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with
   447  	// ipv6 enabled
   448  	deleteInterface(c, "docker0")
   449  
   450  	s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64")
   451  
   452  	out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox")
   453  	c.Assert(err, checker.IsNil)
   454  
   455  	out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
   456  	c.Assert(err, checker.IsNil)
   457  	c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff")
   458  }
   459  
   460  // TestDaemonIPv6HostMode checks that when the running a container with
   461  // network=host the host ipv6 addresses are not removed
   462  func (s *DockerDaemonSuite) TestDaemonIPv6HostMode(c *check.C) {
   463  	testRequires(c, SameHostDaemon)
   464  	deleteInterface(c, "docker0")
   465  
   466  	s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64")
   467  	out, err := s.d.Cmd("run", "-itd", "--name=hostcnt", "--network=host", "busybox:latest")
   468  	c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err))
   469  
   470  	out, err = s.d.Cmd("exec", "hostcnt", "ip", "-6", "addr", "show", "docker0")
   471  	c.Assert(err, checker.IsNil)
   472  	c.Assert(strings.Trim(out, " \r\n'"), 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, testdaemon.WithEnvironment(testEnv.Execution))
  1437  	d.StartWithBusybox(c)
  1438  
  1439  	out, err := d.Cmd("run", "-d", "busybox", "top")
  1440  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1441  	id := strings.TrimSpace(out)
  1442  
  1443  	// If there are no mounts with container id visible from the host
  1444  	// (as those are in container's own mount ns), there is nothing
  1445  	// to check here and the test should be skipped.
  1446  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1447  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1448  	if !strings.Contains(string(mountOut), id) {
  1449  		d.Stop(c)
  1450  		c.Skip("no container mounts visible in host ns")
  1451  	}
  1452  
  1453  	// kill the daemon
  1454  	c.Assert(d.Kill(), check.IsNil)
  1455  
  1456  	// kill the container
  1457  	icmd.RunCommand(ctrBinary, "--address", "/var/run/docker/containerd/docker-containerd.sock",
  1458  		"--namespace", moby_daemon.ContainersNamespace, "tasks", "kill", id).Assert(c, icmd.Success)
  1459  
  1460  	// restart daemon.
  1461  	d.Restart(c)
  1462  
  1463  	// Now, container mounts should be gone.
  1464  	mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1465  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1466  	comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut)
  1467  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1468  
  1469  	d.Stop(c)
  1470  }
  1471  
  1472  // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts.
  1473  func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) {
  1474  	d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1475  	d.StartWithBusybox(c)
  1476  
  1477  	out, err := d.Cmd("run", "-d", "busybox", "top")
  1478  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1479  	id := strings.TrimSpace(out)
  1480  
  1481  	// Send SIGINT and daemon should clean up
  1482  	c.Assert(d.Signal(os.Interrupt), check.IsNil)
  1483  	// Wait for the daemon to stop.
  1484  	c.Assert(<-d.Wait, checker.IsNil)
  1485  
  1486  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1487  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1488  
  1489  	comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut)
  1490  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1491  }
  1492  
  1493  func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1494  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1495  	s.d.StartWithBusybox(c, "-b", "none")
  1496  
  1497  	out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1498  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1499  	c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1500  		check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1501  
  1502  	out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1503  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1504  	c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1505  		check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1506  	// the extra grep and awk clean up the output of `ip` to only list the number and name of
  1507  	// interfaces, allowing for different versions of ip (e.g. inside and outside the container) to
  1508  	// be used while still verifying that the interface list is the exact same
  1509  	cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1510  	stdout := bytes.NewBuffer(nil)
  1511  	cmd.Stdout = stdout
  1512  	if err := cmd.Run(); err != nil {
  1513  		c.Fatal("Failed to get host network interface")
  1514  	}
  1515  	out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1516  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1517  	c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout),
  1518  		check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out))
  1519  }
  1520  
  1521  func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1522  	s.d.StartWithBusybox(t)
  1523  	if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1524  		t.Fatal(out, err)
  1525  	}
  1526  
  1527  	s.d.Restart(t)
  1528  	// Container 'test' should be removed without error
  1529  	if out, err := s.d.Cmd("rm", "test"); err != nil {
  1530  		t.Fatal(out, err)
  1531  	}
  1532  }
  1533  
  1534  func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1535  	s.d.StartWithBusybox(c)
  1536  	out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1537  	if err != nil {
  1538  		c.Fatal(out, err)
  1539  	}
  1540  
  1541  	// Get sandbox key via inspect
  1542  	out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1543  	if err != nil {
  1544  		c.Fatalf("Error inspecting container: %s, %v", out, err)
  1545  	}
  1546  	fileName := strings.Trim(out, " \r\n'")
  1547  
  1548  	if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1549  		c.Fatal(out, err)
  1550  	}
  1551  
  1552  	// Test if the file still exists
  1553  	icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{
  1554  		Out: fileName,
  1555  	})
  1556  
  1557  	// Remove the container and restart the daemon
  1558  	if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1559  		c.Fatal(out, err)
  1560  	}
  1561  
  1562  	s.d.Restart(c)
  1563  
  1564  	// Test again and see now the netns file does not exist
  1565  	icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{
  1566  		Err:      "No such file or directory",
  1567  		ExitCode: 1,
  1568  	})
  1569  }
  1570  
  1571  // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1572  func (s *DockerDaemonSuite) TestDaemonTLSVerifyIssue13964(c *check.C) {
  1573  	host := "tcp://localhost:4271"
  1574  	s.d.Start(c, "-H", host)
  1575  	icmd.RunCmd(icmd.Cmd{
  1576  		Command: []string{dockerBinary, "-H", host, "info"},
  1577  		Env:     []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"},
  1578  	}).Assert(c, icmd.Expected{
  1579  		ExitCode: 1,
  1580  		Err:      "error during connect",
  1581  	})
  1582  }
  1583  
  1584  func setupV6(c *check.C) {
  1585  	// Hack to get the right IPv6 address on docker0, which has already been created
  1586  	result := icmd.RunCommand("ip", "addr", "add", "fe80::1/64", "dev", "docker0")
  1587  	result.Assert(c, icmd.Success)
  1588  }
  1589  
  1590  func teardownV6(c *check.C) {
  1591  	result := icmd.RunCommand("ip", "addr", "del", "fe80::1/64", "dev", "docker0")
  1592  	result.Assert(c, icmd.Success)
  1593  }
  1594  
  1595  func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1596  	s.d.StartWithBusybox(c)
  1597  
  1598  	out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1599  	c.Assert(err, check.IsNil)
  1600  	id := strings.TrimSpace(out)
  1601  
  1602  	_, err = s.d.Cmd("stop", id)
  1603  	c.Assert(err, check.IsNil)
  1604  	_, err = s.d.Cmd("wait", id)
  1605  	c.Assert(err, check.IsNil)
  1606  
  1607  	out, err = s.d.Cmd("ps", "-q")
  1608  	c.Assert(err, check.IsNil)
  1609  	c.Assert(out, check.Equals, "")
  1610  
  1611  	s.d.Restart(c)
  1612  
  1613  	out, err = s.d.Cmd("ps", "-q")
  1614  	c.Assert(err, check.IsNil)
  1615  	c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1616  }
  1617  
  1618  func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1619  	s.d.StartWithBusybox(c, "--log-opt=max-size=1k")
  1620  	name := "logtest"
  1621  	out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top")
  1622  	c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1623  
  1624  	out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name)
  1625  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1626  	c.Assert(out, checker.Contains, "max-size:1k")
  1627  	c.Assert(out, checker.Contains, "max-file:5")
  1628  
  1629  	out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name)
  1630  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1631  	c.Assert(strings.TrimSpace(out), checker.Equals, "json-file")
  1632  }
  1633  
  1634  func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1635  	s.d.StartWithBusybox(c)
  1636  	if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1637  		c.Fatal(err, out)
  1638  	}
  1639  	if out, err := s.d.Cmd("pause", "test"); err != nil {
  1640  		c.Fatal(err, out)
  1641  	}
  1642  	s.d.Restart(c)
  1643  
  1644  	errchan := make(chan error)
  1645  	go func() {
  1646  		out, err := s.d.Cmd("start", "test")
  1647  		if err != nil {
  1648  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  1649  		}
  1650  		name := strings.TrimSpace(out)
  1651  		if name != "test" {
  1652  			errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1653  		}
  1654  		close(errchan)
  1655  	}()
  1656  
  1657  	select {
  1658  	case <-time.After(5 * time.Second):
  1659  		c.Fatal("Waiting on start a container timed out")
  1660  	case err := <-errchan:
  1661  		if err != nil {
  1662  			c.Fatal(err)
  1663  		}
  1664  	}
  1665  }
  1666  
  1667  func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1668  	s.d.StartWithBusybox(c)
  1669  
  1670  	out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1671  	c.Assert(err, check.IsNil, check.Commentf(out))
  1672  
  1673  	s.d.Restart(c)
  1674  
  1675  	out, err = s.d.Cmd("volume", "rm", "test")
  1676  	c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1677  	c.Assert(out, checker.Contains, "in use")
  1678  }
  1679  
  1680  func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1681  	s.d.Start(c)
  1682  
  1683  	_, err := s.d.Cmd("volume", "create", "test")
  1684  	c.Assert(err, check.IsNil)
  1685  	s.d.Restart(c)
  1686  
  1687  	_, err = s.d.Cmd("volume", "inspect", "test")
  1688  	c.Assert(err, check.IsNil)
  1689  }
  1690  
  1691  // FIXME(vdemeester) should be a unit test
  1692  func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1693  	d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1694  	c.Assert(d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1695  	expected := "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, testdaemon.WithEnvironment(testEnv.Execution))
  1702  	c.Assert(d.StartWithError("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1703  	expected := "invalid fluentd-address corrupted:c: "
  1704  	icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success)
  1705  }
  1706  
  1707  // FIXME(vdemeester) Use a new daemon instance instead of the Suite one
  1708  func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) {
  1709  	s.d.UseDefaultHost = true
  1710  	defer func() {
  1711  		s.d.UseDefaultHost = false
  1712  	}()
  1713  	s.d.Start(c)
  1714  }
  1715  
  1716  // FIXME(vdemeester) Use a new daemon instance instead of the Suite one
  1717  func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *check.C) {
  1718  	s.d.UseDefaultTLSHost = true
  1719  	defer func() {
  1720  		s.d.UseDefaultTLSHost = false
  1721  	}()
  1722  	s.d.Start(c,
  1723  		"--tlsverify",
  1724  		"--tlscacert", "fixtures/https/ca.pem",
  1725  		"--tlscert", "fixtures/https/server-cert.pem",
  1726  		"--tlskey", "fixtures/https/server-key.pem")
  1727  
  1728  	// The client with --tlsverify should also use default host localhost:2376
  1729  	tmpHost := os.Getenv("DOCKER_HOST")
  1730  	defer func() {
  1731  		os.Setenv("DOCKER_HOST", tmpHost)
  1732  	}()
  1733  
  1734  	os.Setenv("DOCKER_HOST", "")
  1735  
  1736  	out, _ := dockerCmd(
  1737  		c,
  1738  		"--tlsverify",
  1739  		"--tlscacert", "fixtures/https/ca.pem",
  1740  		"--tlscert", "fixtures/https/client-cert.pem",
  1741  		"--tlskey", "fixtures/https/client-key.pem",
  1742  		"version",
  1743  	)
  1744  	if !strings.Contains(out, "Server") {
  1745  		c.Fatalf("docker version should return information of server side")
  1746  	}
  1747  
  1748  	// ensure when connecting to the server that only a single acceptable CA is requested
  1749  	contents, err := ioutil.ReadFile("fixtures/https/ca.pem")
  1750  	c.Assert(err, checker.IsNil)
  1751  	rootCert, err := helpers.ParseCertificatePEM(contents)
  1752  	c.Assert(err, checker.IsNil)
  1753  	rootPool := x509.NewCertPool()
  1754  	rootPool.AddCert(rootCert)
  1755  
  1756  	var certRequestInfo *tls.CertificateRequestInfo
  1757  	conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort), &tls.Config{
  1758  		RootCAs: rootPool,
  1759  		GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
  1760  			certRequestInfo = cri
  1761  			cert, err := tls.LoadX509KeyPair("fixtures/https/client-cert.pem", "fixtures/https/client-key.pem")
  1762  			if err != nil {
  1763  				return nil, err
  1764  			}
  1765  			return &cert, nil
  1766  		},
  1767  	})
  1768  	c.Assert(err, checker.IsNil)
  1769  	conn.Close()
  1770  
  1771  	c.Assert(certRequestInfo, checker.NotNil)
  1772  	c.Assert(certRequestInfo.AcceptableCAs, checker.HasLen, 1)
  1773  	c.Assert(certRequestInfo.AcceptableCAs[0], checker.DeepEquals, rootCert.RawSubject)
  1774  }
  1775  
  1776  func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1777  	defaultNetworkBridge := "docker0"
  1778  	deleteInterface(c, defaultNetworkBridge)
  1779  
  1780  	bridgeIP := "192.169.1.1"
  1781  	bridgeRange := bridgeIP + "/30"
  1782  
  1783  	s.d.StartWithBusybox(c, "--bip", bridgeRange)
  1784  	defer s.d.Restart(c)
  1785  
  1786  	var cont int
  1787  	for {
  1788  		contName := fmt.Sprintf("container%d", cont)
  1789  		_, err := s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1790  		if err != nil {
  1791  			// pool exhausted
  1792  			break
  1793  		}
  1794  		ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1795  		c.Assert(err, check.IsNil)
  1796  
  1797  		c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1798  		cont++
  1799  	}
  1800  }
  1801  
  1802  // Test daemon for no space left on device error
  1803  func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) {
  1804  	testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1805  
  1806  	testDir, err := ioutil.TempDir("", "no-space-left-on-device-test")
  1807  	c.Assert(err, checker.IsNil)
  1808  	defer os.RemoveAll(testDir)
  1809  	c.Assert(mount.MakeRShared(testDir), checker.IsNil)
  1810  	defer mount.Unmount(testDir)
  1811  
  1812  	// create a 2MiB image and mount it as graph root
  1813  	// 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)
  1814  	dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=3 count=0")
  1815  	icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success)
  1816  
  1817  	result := icmd.RunCommand("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img"))
  1818  	result.Assert(c, icmd.Success)
  1819  	loopname := strings.TrimSpace(string(result.Combined()))
  1820  	defer exec.Command("losetup", "-d", loopname).Run()
  1821  
  1822  	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))
  1823  	defer mount.Unmount(filepath.Join(testDir, "test-mount"))
  1824  
  1825  	s.d.Start(c, "--data-root", filepath.Join(testDir, "test-mount"))
  1826  	defer s.d.Stop(c)
  1827  
  1828  	// pull a repository large enough to fill the mount point
  1829  	pullOut, err := s.d.Cmd("pull", "debian:stretch")
  1830  	c.Assert(err, checker.NotNil, check.Commentf(pullOut))
  1831  	c.Assert(pullOut, checker.Contains, "no space left on device")
  1832  }
  1833  
  1834  // Test daemon restart with container links + auto restart
  1835  func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1836  	s.d.StartWithBusybox(c)
  1837  
  1838  	parent1Args := []string{}
  1839  	parent2Args := []string{}
  1840  	wg := sync.WaitGroup{}
  1841  	maxChildren := 10
  1842  	chErr := make(chan error, maxChildren)
  1843  
  1844  	for i := 0; i < maxChildren; i++ {
  1845  		wg.Add(1)
  1846  		name := fmt.Sprintf("test%d", i)
  1847  
  1848  		if i < maxChildren/2 {
  1849  			parent1Args = append(parent1Args, []string{"--link", name}...)
  1850  		} else {
  1851  			parent2Args = append(parent2Args, []string{"--link", name}...)
  1852  		}
  1853  
  1854  		go func() {
  1855  			_, err := s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1856  			chErr <- err
  1857  			wg.Done()
  1858  		}()
  1859  	}
  1860  
  1861  	wg.Wait()
  1862  	close(chErr)
  1863  	for err := range chErr {
  1864  		c.Assert(err, check.IsNil)
  1865  	}
  1866  
  1867  	parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1868  	parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1869  	parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1870  	parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1871  
  1872  	_, err := s.d.Cmd(parent1Args...)
  1873  	c.Assert(err, check.IsNil)
  1874  	_, err = s.d.Cmd(parent2Args...)
  1875  	c.Assert(err, check.IsNil)
  1876  
  1877  	s.d.Stop(c)
  1878  	// clear the log file -- we don't need any of it but may for the next part
  1879  	// can ignore the error here, this is just a cleanup
  1880  	os.Truncate(s.d.LogFileName(), 0)
  1881  	s.d.Start(c)
  1882  
  1883  	for _, num := range []string{"1", "2"} {
  1884  		out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1885  		c.Assert(err, check.IsNil)
  1886  		if strings.TrimSpace(out) != "true" {
  1887  			log, _ := ioutil.ReadFile(s.d.LogFileName())
  1888  			c.Fatalf("parent container is not running\n%s", string(log))
  1889  		}
  1890  	}
  1891  }
  1892  
  1893  func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1894  	testRequires(c, DaemonIsLinux)
  1895  
  1896  	cgroupParent := "test"
  1897  	name := "cgroup-test"
  1898  
  1899  	s.d.StartWithBusybox(c, "--cgroup-parent", cgroupParent)
  1900  	defer s.d.Restart(c)
  1901  
  1902  	out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  1903  	c.Assert(err, checker.IsNil)
  1904  	cgroupPaths := ParseCgroupPaths(string(out))
  1905  	c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  1906  	out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  1907  	c.Assert(err, checker.IsNil)
  1908  	id := strings.TrimSpace(string(out))
  1909  	expectedCgroup := path.Join(cgroupParent, id)
  1910  	found := false
  1911  	for _, path := range cgroupPaths {
  1912  		if strings.HasSuffix(path, expectedCgroup) {
  1913  			found = true
  1914  			break
  1915  		}
  1916  	}
  1917  	c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  1918  }
  1919  
  1920  func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  1921  	testRequires(c, DaemonIsLinux) // Windows does not support links
  1922  	s.d.StartWithBusybox(c)
  1923  
  1924  	out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1925  	c.Assert(err, check.IsNil, check.Commentf(out))
  1926  
  1927  	out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  1928  	c.Assert(err, check.IsNil, check.Commentf(out))
  1929  
  1930  	s.d.Restart(c)
  1931  
  1932  	// should fail since test is not running yet
  1933  	out, err = s.d.Cmd("start", "test2")
  1934  	c.Assert(err, check.NotNil, check.Commentf(out))
  1935  
  1936  	out, err = s.d.Cmd("start", "test")
  1937  	c.Assert(err, check.IsNil, check.Commentf(out))
  1938  	out, err = s.d.Cmd("start", "-a", "test2")
  1939  	c.Assert(err, check.IsNil, check.Commentf(out))
  1940  	c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  1941  }
  1942  
  1943  func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  1944  	testRequires(c, DaemonIsLinux) // Windows does not support links
  1945  	s.d.StartWithBusybox(c)
  1946  
  1947  	out, err := s.d.Cmd("create", "--name=test", "busybox")
  1948  	c.Assert(err, check.IsNil, check.Commentf(out))
  1949  
  1950  	out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  1951  	c.Assert(err, check.IsNil, check.Commentf(out))
  1952  	test2ID := strings.TrimSpace(out)
  1953  
  1954  	out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  1955  	test3ID := strings.TrimSpace(out)
  1956  
  1957  	s.d.Restart(c)
  1958  
  1959  	out, err = s.d.Cmd("create", "--name=test", "busybox")
  1960  	c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  1961  	// this one is no longer needed, removing simplifies the remainder of the test
  1962  	out, err = s.d.Cmd("rm", "-f", "test")
  1963  	c.Assert(err, check.IsNil, check.Commentf(out))
  1964  
  1965  	out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  1966  	c.Assert(err, check.IsNil, check.Commentf(out))
  1967  
  1968  	lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  1969  
  1970  	test2validated := false
  1971  	test3validated := false
  1972  	for _, line := range lines {
  1973  		fields := strings.Fields(line)
  1974  		names := fields[len(fields)-1]
  1975  		switch fields[0] {
  1976  		case test2ID:
  1977  			c.Assert(names, check.Equals, "test2,test3/abc")
  1978  			test2validated = true
  1979  		case test3ID:
  1980  			c.Assert(names, check.Equals, "test3")
  1981  			test3validated = true
  1982  		}
  1983  	}
  1984  
  1985  	c.Assert(test2validated, check.Equals, true)
  1986  	c.Assert(test3validated, check.Equals, true)
  1987  }
  1988  
  1989  // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers
  1990  func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) {
  1991  	testRequires(t, DaemonIsLinux)
  1992  	s.d.StartWithBusybox(t)
  1993  
  1994  	cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  1995  	defer s.d.Stop(t)
  1996  	if err != nil {
  1997  		t.Fatal(cid, err)
  1998  	}
  1999  	cid = strings.TrimSpace(cid)
  2000  
  2001  	pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  2002  	t.Assert(err, check.IsNil)
  2003  	pid = strings.TrimSpace(pid)
  2004  
  2005  	// Kill the daemon
  2006  	if err := s.d.Kill(); err != nil {
  2007  		t.Fatal(err)
  2008  	}
  2009  
  2010  	// kill the container
  2011  	icmd.RunCommand(ctrBinary, "--address", "/var/run/docker/containerd/docker-containerd.sock",
  2012  		"--namespace", moby_daemon.ContainersNamespace, "tasks", "kill", cid).Assert(t, icmd.Success)
  2013  
  2014  	// Give time to containerd to process the command if we don't
  2015  	// the exit event might be received after we do the inspect
  2016  	result := icmd.RunCommand("kill", "-0", pid)
  2017  	for result.ExitCode == 0 {
  2018  		time.Sleep(1 * time.Second)
  2019  		// FIXME(vdemeester) should we check it doesn't error out ?
  2020  		result = icmd.RunCommand("kill", "-0", pid)
  2021  	}
  2022  
  2023  	// restart the daemon
  2024  	s.d.Start(t)
  2025  
  2026  	// Check that we've got the correct exit code
  2027  	out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid)
  2028  	t.Assert(err, check.IsNil)
  2029  
  2030  	out = strings.TrimSpace(out)
  2031  	if out != "143" {
  2032  		t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid)
  2033  	}
  2034  
  2035  }
  2036  
  2037  // os.Kill should kill daemon ungracefully, leaving behind live containers.
  2038  // The live containers should be known to the restarted daemon. Stopping
  2039  // them now, should remove the mounts.
  2040  func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) {
  2041  	testRequires(c, DaemonIsLinux)
  2042  	s.d.StartWithBusybox(c, "--live-restore")
  2043  
  2044  	out, err := s.d.Cmd("run", "-d", "busybox", "top")
  2045  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2046  	id := strings.TrimSpace(out)
  2047  
  2048  	// kill the daemon
  2049  	c.Assert(s.d.Kill(), check.IsNil)
  2050  
  2051  	// Check if there are mounts with container id visible from the host.
  2052  	// If not, those mounts exist in container's own mount ns, and so
  2053  	// the following check for mounts being cleared is pointless.
  2054  	skipMountCheck := false
  2055  	mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  2056  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  2057  	if !strings.Contains(string(mountOut), id) {
  2058  		skipMountCheck = true
  2059  	}
  2060  
  2061  	// restart daemon.
  2062  	s.d.Start(c, "--live-restore")
  2063  
  2064  	// container should be running.
  2065  	out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id)
  2066  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2067  	out = strings.TrimSpace(out)
  2068  	if out != "true" {
  2069  		c.Fatalf("Container %s expected to stay alive after daemon restart", id)
  2070  	}
  2071  
  2072  	// 'docker stop' should work.
  2073  	out, err = s.d.Cmd("stop", id)
  2074  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2075  
  2076  	if skipMountCheck {
  2077  		return
  2078  	}
  2079  	// Now, container mounts should be gone.
  2080  	mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  2081  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  2082  	comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut)
  2083  	c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  2084  }
  2085  
  2086  // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers.
  2087  func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) {
  2088  	testRequires(t, DaemonIsLinux)
  2089  	s.d.StartWithBusybox(t, "--live-restore")
  2090  
  2091  	cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  2092  	defer s.d.Stop(t)
  2093  	if err != nil {
  2094  		t.Fatal(cid, err)
  2095  	}
  2096  	cid = strings.TrimSpace(cid)
  2097  
  2098  	pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  2099  	t.Assert(err, check.IsNil)
  2100  
  2101  	// pause the container
  2102  	if _, err := s.d.Cmd("pause", cid); err != nil {
  2103  		t.Fatal(cid, err)
  2104  	}
  2105  
  2106  	// Kill the daemon
  2107  	if err := s.d.Kill(); err != nil {
  2108  		t.Fatal(err)
  2109  	}
  2110  
  2111  	// resume the container
  2112  	result := icmd.RunCommand(
  2113  		ctrBinary,
  2114  		"--address", "/var/run/docker/containerd/docker-containerd.sock",
  2115  		"--namespace", moby_daemon.ContainersNamespace,
  2116  		"tasks", "resume", cid)
  2117  	result.Assert(t, icmd.Success)
  2118  
  2119  	// Give time to containerd to process the command if we don't
  2120  	// the resume event might be received after we do the inspect
  2121  	waitAndAssert(t, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) {
  2122  		result := icmd.RunCommand("kill", "-0", strings.TrimSpace(pid))
  2123  		return result.ExitCode, nil
  2124  	}, checker.Equals, 0)
  2125  
  2126  	// restart the daemon
  2127  	s.d.Start(t, "--live-restore")
  2128  
  2129  	// Check that we've got the correct status
  2130  	out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid)
  2131  	t.Assert(err, check.IsNil)
  2132  
  2133  	out = strings.TrimSpace(out)
  2134  	if out != "running" {
  2135  		t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid)
  2136  	}
  2137  	if _, err := s.d.Cmd("kill", cid); err != nil {
  2138  		t.Fatal(err)
  2139  	}
  2140  }
  2141  
  2142  // TestRunLinksChanged checks that creating a new container with the same name does not update links
  2143  // this ensures that the old, pre gh#16032 functionality continues on
  2144  func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  2145  	testRequires(c, DaemonIsLinux) // Windows does not support links
  2146  	s.d.StartWithBusybox(c)
  2147  
  2148  	out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  2149  	c.Assert(err, check.IsNil, check.Commentf(out))
  2150  
  2151  	out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  2152  	c.Assert(err, check.IsNil, check.Commentf(out))
  2153  	c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  2154  
  2155  	out, err = s.d.Cmd("rm", "-f", "test")
  2156  	c.Assert(err, check.IsNil, check.Commentf(out))
  2157  
  2158  	out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  2159  	c.Assert(err, check.IsNil, check.Commentf(out))
  2160  	out, err = s.d.Cmd("start", "-a", "test2")
  2161  	c.Assert(err, check.NotNil, check.Commentf(out))
  2162  	c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  2163  
  2164  	s.d.Restart(c)
  2165  	out, err = s.d.Cmd("start", "-a", "test2")
  2166  	c.Assert(err, check.NotNil, check.Commentf(out))
  2167  	c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  2168  }
  2169  
  2170  func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  2171  	testRequires(c, DaemonIsLinux)
  2172  
  2173  	infoLog := "\x1b[36mINFO\x1b"
  2174  
  2175  	b := bytes.NewBuffer(nil)
  2176  	done := make(chan bool)
  2177  
  2178  	p, tty, err := pty.Open()
  2179  	c.Assert(err, checker.IsNil)
  2180  	defer func() {
  2181  		tty.Close()
  2182  		p.Close()
  2183  	}()
  2184  
  2185  	go func() {
  2186  		io.Copy(b, p)
  2187  		done <- true
  2188  	}()
  2189  
  2190  	// Enable coloring explicitly
  2191  	s.d.StartWithLogFile(tty, "--raw-logs=false")
  2192  	s.d.Stop(c)
  2193  	// Wait for io.Copy() before checking output
  2194  	<-done
  2195  	c.Assert(b.String(), checker.Contains, infoLog)
  2196  
  2197  	b.Reset()
  2198  
  2199  	// "tty" is already closed in prev s.d.Stop(),
  2200  	// we have to close the other side "p" and open another pair of
  2201  	// pty for the next test.
  2202  	p.Close()
  2203  	p, tty, err = pty.Open()
  2204  	c.Assert(err, checker.IsNil)
  2205  
  2206  	go func() {
  2207  		io.Copy(b, p)
  2208  		done <- true
  2209  	}()
  2210  
  2211  	// Disable coloring explicitly
  2212  	s.d.StartWithLogFile(tty, "--raw-logs=true")
  2213  	s.d.Stop(c)
  2214  	// Wait for io.Copy() before checking output
  2215  	<-done
  2216  	c.Assert(b.String(), check.Not(check.Equals), "")
  2217  	c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  2218  }
  2219  
  2220  func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  2221  	testRequires(c, DaemonIsLinux)
  2222  
  2223  	debugLog := "\x1b[37mDEBU\x1b"
  2224  
  2225  	p, tty, err := pty.Open()
  2226  	c.Assert(err, checker.IsNil)
  2227  	defer func() {
  2228  		tty.Close()
  2229  		p.Close()
  2230  	}()
  2231  
  2232  	b := bytes.NewBuffer(nil)
  2233  	go io.Copy(b, p)
  2234  
  2235  	s.d.StartWithLogFile(tty, "--debug")
  2236  	s.d.Stop(c)
  2237  	c.Assert(b.String(), checker.Contains, debugLog)
  2238  }
  2239  
  2240  func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  2241  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2242  
  2243  	// daemon config file
  2244  	daemonConfig := `{ "debug" : false }`
  2245  	configFile, err := ioutil.TempFile("", "test-daemon-discovery-backend-config-reload-config")
  2246  	c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload"))
  2247  	configFilePath := configFile.Name()
  2248  	defer func() {
  2249  		configFile.Close()
  2250  		os.RemoveAll(configFile.Name())
  2251  	}()
  2252  
  2253  	_, err = configFile.Write([]byte(daemonConfig))
  2254  	c.Assert(err, checker.IsNil)
  2255  
  2256  	// --log-level needs to be set so that d.Start() doesn't add --debug causing
  2257  	// a conflict with the config
  2258  	s.d.Start(c, "--config-file", configFilePath, "--log-level=info")
  2259  
  2260  	// daemon config file
  2261  	daemonConfig = `{
  2262  	      "cluster-store": "consul://consuladdr:consulport/some/path",
  2263  	      "cluster-advertise": "192.168.56.100:0",
  2264  	      "debug" : false
  2265  	}`
  2266  
  2267  	err = configFile.Truncate(0)
  2268  	c.Assert(err, checker.IsNil)
  2269  	_, err = configFile.Seek(0, os.SEEK_SET)
  2270  	c.Assert(err, checker.IsNil)
  2271  
  2272  	_, err = configFile.Write([]byte(daemonConfig))
  2273  	c.Assert(err, checker.IsNil)
  2274  
  2275  	err = s.d.ReloadConfig()
  2276  	c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config"))
  2277  
  2278  	out, err := s.d.Cmd("info")
  2279  	c.Assert(err, checker.IsNil)
  2280  
  2281  	c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path"))
  2282  	c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0"))
  2283  }
  2284  
  2285  // Test for #21956
  2286  func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) {
  2287  	s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514")
  2288  
  2289  	out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top")
  2290  	c.Assert(err, check.IsNil, check.Commentf(out))
  2291  	id := strings.TrimSpace(out)
  2292  
  2293  	out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id)
  2294  	c.Assert(err, check.IsNil, check.Commentf(out))
  2295  	c.Assert(out, checker.Contains, "{json-file map[]}")
  2296  }
  2297  
  2298  // Test case for #20936, #22443
  2299  func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) {
  2300  	s.d.Start(c, "--max-concurrent-uploads=6", "--max-concurrent-downloads=8")
  2301  
  2302  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"`
  2303  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  2304  	content, err := s.d.ReadLogFile()
  2305  	c.Assert(err, checker.IsNil)
  2306  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2307  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2308  }
  2309  
  2310  // Test case for #20936, #22443
  2311  func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) {
  2312  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2313  
  2314  	// daemon config file
  2315  	configFilePath := "test.json"
  2316  	configFile, err := os.Create(configFilePath)
  2317  	c.Assert(err, checker.IsNil)
  2318  	defer os.Remove(configFilePath)
  2319  
  2320  	daemonConfig := `{ "max-concurrent-downloads" : 8 }`
  2321  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2322  	configFile.Close()
  2323  	s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  2324  
  2325  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  2326  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  2327  	content, err := s.d.ReadLogFile()
  2328  	c.Assert(err, checker.IsNil)
  2329  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2330  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2331  
  2332  	configFile, err = os.Create(configFilePath)
  2333  	c.Assert(err, checker.IsNil)
  2334  	daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }`
  2335  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2336  	configFile.Close()
  2337  
  2338  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2339  	// unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP)
  2340  
  2341  	time.Sleep(3 * time.Second)
  2342  
  2343  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"`
  2344  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"`
  2345  	content, err = s.d.ReadLogFile()
  2346  	c.Assert(err, checker.IsNil)
  2347  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2348  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2349  }
  2350  
  2351  // Test case for #20936, #22443
  2352  func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) {
  2353  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2354  
  2355  	// daemon config file
  2356  	configFilePath := "test.json"
  2357  	configFile, err := os.Create(configFilePath)
  2358  	c.Assert(err, checker.IsNil)
  2359  	defer os.Remove(configFilePath)
  2360  
  2361  	daemonConfig := `{ "max-concurrent-uploads" : null }`
  2362  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2363  	configFile.Close()
  2364  	s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  2365  
  2366  	expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  2367  	expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"`
  2368  	content, err := s.d.ReadLogFile()
  2369  	c.Assert(err, checker.IsNil)
  2370  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2371  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2372  
  2373  	configFile, err = os.Create(configFilePath)
  2374  	c.Assert(err, checker.IsNil)
  2375  	daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }`
  2376  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2377  	configFile.Close()
  2378  
  2379  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2380  	// unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP)
  2381  
  2382  	time.Sleep(3 * time.Second)
  2383  
  2384  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"`
  2385  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  2386  	content, err = s.d.ReadLogFile()
  2387  	c.Assert(err, checker.IsNil)
  2388  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2389  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2390  
  2391  	configFile, err = os.Create(configFilePath)
  2392  	c.Assert(err, checker.IsNil)
  2393  	daemonConfig = `{ "labels":["foo=bar"] }`
  2394  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2395  	configFile.Close()
  2396  
  2397  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2398  
  2399  	time.Sleep(3 * time.Second)
  2400  
  2401  	expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"`
  2402  	expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  2403  	content, err = s.d.ReadLogFile()
  2404  	c.Assert(err, checker.IsNil)
  2405  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2406  	c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2407  }
  2408  
  2409  func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) {
  2410  	s.d.StartWithBusybox(c, "-b=none", "--iptables=false")
  2411  	out, code, err := s.d.BuildImageWithOut("busyboxs",
  2412  		`FROM busybox
  2413                  RUN cat /etc/hosts`, false)
  2414  	comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err)
  2415  	c.Assert(err, check.IsNil, comment)
  2416  	c.Assert(code, check.Equals, 0, comment)
  2417  }
  2418  
  2419  // Test case for #21976
  2420  func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) {
  2421  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2422  
  2423  	s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3")
  2424  
  2425  	expectedOutput := "nameserver 1.2.3.4"
  2426  	out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2427  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2428  	expectedOutput = "search example.com"
  2429  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2430  	expectedOutput = "options timeout:3"
  2431  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2432  }
  2433  
  2434  func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
  2435  	conf, err := ioutil.TempFile("", "config-file-")
  2436  	c.Assert(err, check.IsNil)
  2437  	configName := conf.Name()
  2438  	conf.Close()
  2439  	defer os.Remove(configName)
  2440  
  2441  	config := `
  2442  {
  2443      "runtimes": {
  2444          "oci": {
  2445              "path": "docker-runc"
  2446          },
  2447          "vm": {
  2448              "path": "/usr/local/bin/vm-manager",
  2449              "runtimeArgs": [
  2450                  "--debug"
  2451              ]
  2452          }
  2453      }
  2454  }
  2455  `
  2456  	ioutil.WriteFile(configName, []byte(config), 0644)
  2457  	s.d.StartWithBusybox(c, "--config-file", configName)
  2458  
  2459  	// Run with default runtime
  2460  	out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2461  	c.Assert(err, check.IsNil, check.Commentf(out))
  2462  
  2463  	// Run with default runtime explicitly
  2464  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2465  	c.Assert(err, check.IsNil, check.Commentf(out))
  2466  
  2467  	// Run with oci (same path as default) but keep it around
  2468  	out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2469  	c.Assert(err, check.IsNil, check.Commentf(out))
  2470  
  2471  	// Run with "vm"
  2472  	out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2473  	c.Assert(err, check.NotNil, check.Commentf(out))
  2474  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2475  
  2476  	// Reset config to only have the default
  2477  	config = `
  2478  {
  2479      "runtimes": {
  2480      }
  2481  }
  2482  `
  2483  	ioutil.WriteFile(configName, []byte(config), 0644)
  2484  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2485  	// Give daemon time to reload config
  2486  	<-time.After(1 * time.Second)
  2487  
  2488  	// Run with default runtime
  2489  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2490  	c.Assert(err, check.IsNil, check.Commentf(out))
  2491  
  2492  	// Run with "oci"
  2493  	out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2494  	c.Assert(err, check.NotNil, check.Commentf(out))
  2495  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2496  
  2497  	// Start previously created container with oci
  2498  	out, err = s.d.Cmd("start", "oci-runtime-ls")
  2499  	c.Assert(err, check.NotNil, check.Commentf(out))
  2500  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2501  
  2502  	// Check that we can't override the default runtime
  2503  	config = `
  2504  {
  2505      "runtimes": {
  2506          "runc": {
  2507              "path": "my-runc"
  2508          }
  2509      }
  2510  }
  2511  `
  2512  	ioutil.WriteFile(configName, []byte(config), 0644)
  2513  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2514  	// Give daemon time to reload config
  2515  	<-time.After(1 * time.Second)
  2516  
  2517  	content, err := s.d.ReadLogFile()
  2518  	c.Assert(err, checker.IsNil)
  2519  	c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`)
  2520  
  2521  	// Check that we can select a default runtime
  2522  	config = `
  2523  {
  2524      "default-runtime": "vm",
  2525      "runtimes": {
  2526          "oci": {
  2527              "path": "docker-runc"
  2528          },
  2529          "vm": {
  2530              "path": "/usr/local/bin/vm-manager",
  2531              "runtimeArgs": [
  2532                  "--debug"
  2533              ]
  2534          }
  2535      }
  2536  }
  2537  `
  2538  	ioutil.WriteFile(configName, []byte(config), 0644)
  2539  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2540  	// Give daemon time to reload config
  2541  	<-time.After(1 * time.Second)
  2542  
  2543  	out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2544  	c.Assert(err, check.NotNil, check.Commentf(out))
  2545  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2546  
  2547  	// Run with default runtime explicitly
  2548  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2549  	c.Assert(err, check.IsNil, check.Commentf(out))
  2550  }
  2551  
  2552  func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
  2553  	s.d.StartWithBusybox(c, "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2554  
  2555  	// Run with default runtime
  2556  	out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2557  	c.Assert(err, check.IsNil, check.Commentf(out))
  2558  
  2559  	// Run with default runtime explicitly
  2560  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2561  	c.Assert(err, check.IsNil, check.Commentf(out))
  2562  
  2563  	// Run with oci (same path as default) but keep it around
  2564  	out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2565  	c.Assert(err, check.IsNil, check.Commentf(out))
  2566  
  2567  	// Run with "vm"
  2568  	out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2569  	c.Assert(err, check.NotNil, check.Commentf(out))
  2570  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2571  
  2572  	// Start a daemon without any extra runtimes
  2573  	s.d.Stop(c)
  2574  	s.d.StartWithBusybox(c)
  2575  
  2576  	// Run with default runtime
  2577  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2578  	c.Assert(err, check.IsNil, check.Commentf(out))
  2579  
  2580  	// Run with "oci"
  2581  	out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2582  	c.Assert(err, check.NotNil, check.Commentf(out))
  2583  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2584  
  2585  	// Start previously created container with oci
  2586  	out, err = s.d.Cmd("start", "oci-runtime-ls")
  2587  	c.Assert(err, check.NotNil, check.Commentf(out))
  2588  	c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2589  
  2590  	// Check that we can't override the default runtime
  2591  	s.d.Stop(c)
  2592  	c.Assert(s.d.StartWithError("--add-runtime", "runc=my-runc"), checker.NotNil)
  2593  
  2594  	content, err := s.d.ReadLogFile()
  2595  	c.Assert(err, checker.IsNil)
  2596  	c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`)
  2597  
  2598  	// Check that we can select a default runtime
  2599  	s.d.Stop(c)
  2600  	s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2601  
  2602  	out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2603  	c.Assert(err, check.NotNil, check.Commentf(out))
  2604  	c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2605  
  2606  	// Run with default runtime explicitly
  2607  	out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2608  	c.Assert(err, check.IsNil, check.Commentf(out))
  2609  }
  2610  
  2611  func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) {
  2612  	s.d.StartWithBusybox(c)
  2613  
  2614  	// top1 will exist after daemon restarts
  2615  	out, err := s.d.Cmd("run", "-d", "--name", "top1", "busybox:latest", "top")
  2616  	c.Assert(err, checker.IsNil, check.Commentf("run top1: %v", out))
  2617  	// top2 will be removed after daemon restarts
  2618  	out, err = s.d.Cmd("run", "-d", "--rm", "--name", "top2", "busybox:latest", "top")
  2619  	c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out))
  2620  
  2621  	out, err = s.d.Cmd("ps")
  2622  	c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running"))
  2623  	c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running"))
  2624  
  2625  	// now restart daemon gracefully
  2626  	s.d.Restart(c)
  2627  
  2628  	out, err = s.d.Cmd("ps", "-a")
  2629  	c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  2630  	c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should exist after daemon restarts"))
  2631  	c.Assert(out, checker.Not(checker.Contains), "top2", check.Commentf("top2 should be removed after daemon restarts"))
  2632  }
  2633  
  2634  func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) {
  2635  	s.d.StartWithBusybox(c)
  2636  
  2637  	containerName := "error-values"
  2638  	// Make a container with both a non 0 exit code and an error message
  2639  	// We explicitly disable `--init` for this test, because `--init` is enabled by default
  2640  	// on "experimental". Enabling `--init` results in a different behavior; because the "init"
  2641  	// process itself is PID1, the container does not fail on _startup_ (i.e., `docker-init` starting),
  2642  	// but directly after. The exit code of the container is still 127, but the Error Message is not
  2643  	// captured, so `.State.Error` is empty.
  2644  	// See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426,
  2645  	// and https://github.com/docker/docker/pull/26061#r78054578 for more information.
  2646  	out, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto")
  2647  	c.Assert(err, checker.NotNil)
  2648  
  2649  	// Check that those values were saved on disk
  2650  	out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
  2651  	out = strings.TrimSpace(out)
  2652  	c.Assert(err, checker.IsNil)
  2653  	c.Assert(out, checker.Equals, "127")
  2654  
  2655  	errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName)
  2656  	errMsg1 = strings.TrimSpace(errMsg1)
  2657  	c.Assert(err, checker.IsNil)
  2658  	c.Assert(errMsg1, checker.Contains, "executable file not found")
  2659  
  2660  	// now restart daemon
  2661  	s.d.Restart(c)
  2662  
  2663  	// Check that those values are still around
  2664  	out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
  2665  	out = strings.TrimSpace(out)
  2666  	c.Assert(err, checker.IsNil)
  2667  	c.Assert(out, checker.Equals, "127")
  2668  
  2669  	out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName)
  2670  	out = strings.TrimSpace(out)
  2671  	c.Assert(err, checker.IsNil)
  2672  	c.Assert(out, checker.Equals, errMsg1)
  2673  }
  2674  
  2675  func (s *DockerDaemonSuite) TestDaemonBackcompatPre17Volumes(c *check.C) {
  2676  	testRequires(c, SameHostDaemon)
  2677  	d := s.d
  2678  	d.StartWithBusybox(c)
  2679  
  2680  	// hack to be able to side-load a container config
  2681  	out, err := d.Cmd("create", "busybox:latest")
  2682  	c.Assert(err, checker.IsNil, check.Commentf(out))
  2683  	id := strings.TrimSpace(out)
  2684  
  2685  	out, err = d.Cmd("inspect", "--type=image", "--format={{.ID}}", "busybox:latest")
  2686  	c.Assert(err, checker.IsNil, check.Commentf(out))
  2687  	d.Stop(c)
  2688  	<-d.Wait
  2689  
  2690  	imageID := strings.TrimSpace(out)
  2691  	volumeID := stringid.GenerateNonCryptoID()
  2692  	vfsPath := filepath.Join(d.Root, "vfs", "dir", volumeID)
  2693  	c.Assert(os.MkdirAll(vfsPath, 0755), checker.IsNil)
  2694  
  2695  	config := []byte(`
  2696  		{
  2697  			"ID": "` + id + `",
  2698  			"Name": "hello",
  2699  			"Driver": "` + d.StorageDriver() + `",
  2700  			"Image": "` + imageID + `",
  2701  			"Config": {"Image": "busybox:latest"},
  2702  			"NetworkSettings": {},
  2703  			"Volumes": {
  2704  				"/bar":"/foo",
  2705  				"/foo": "` + vfsPath + `",
  2706  				"/quux":"/quux"
  2707  			},
  2708  			"VolumesRW": {
  2709  				"/bar": true,
  2710  				"/foo": true,
  2711  				"/quux": false
  2712  			}
  2713  		}
  2714  	`)
  2715  
  2716  	configPath := filepath.Join(d.Root, "containers", id, "config.v2.json")
  2717  	c.Assert(ioutil.WriteFile(configPath, config, 600), checker.IsNil)
  2718  	d.Start(c)
  2719  
  2720  	out, err = d.Cmd("inspect", "--type=container", "--format={{ json .Mounts }}", id)
  2721  	c.Assert(err, checker.IsNil, check.Commentf(out))
  2722  	type mount struct {
  2723  		Name        string
  2724  		Source      string
  2725  		Destination string
  2726  		Driver      string
  2727  		RW          bool
  2728  	}
  2729  
  2730  	ls := []mount{}
  2731  	err = json.NewDecoder(strings.NewReader(out)).Decode(&ls)
  2732  	c.Assert(err, checker.IsNil)
  2733  
  2734  	expected := []mount{
  2735  		{Source: "/foo", Destination: "/bar", RW: true},
  2736  		{Name: volumeID, Destination: "/foo", RW: true},
  2737  		{Source: "/quux", Destination: "/quux", RW: false},
  2738  	}
  2739  	c.Assert(ls, checker.HasLen, len(expected))
  2740  
  2741  	for _, m := range ls {
  2742  		var matched bool
  2743  		for _, x := range expected {
  2744  			if m.Source == x.Source && m.Destination == x.Destination && m.RW == x.RW || m.Name != x.Name {
  2745  				matched = true
  2746  				break
  2747  			}
  2748  		}
  2749  		c.Assert(matched, checker.True, check.Commentf("did find match for %+v", m))
  2750  	}
  2751  }
  2752  
  2753  func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) {
  2754  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2755  
  2756  	dockerProxyPath, err := exec.LookPath("docker-proxy")
  2757  	c.Assert(err, checker.IsNil)
  2758  	tmpDir, err := ioutil.TempDir("", "test-docker-proxy")
  2759  	c.Assert(err, checker.IsNil)
  2760  
  2761  	newProxyPath := filepath.Join(tmpDir, "docker-proxy")
  2762  	cmd := exec.Command("cp", dockerProxyPath, newProxyPath)
  2763  	c.Assert(cmd.Run(), checker.IsNil)
  2764  
  2765  	// custom one
  2766  	s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath)
  2767  	out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2768  	c.Assert(err, checker.IsNil, check.Commentf(out))
  2769  
  2770  	// try with the original one
  2771  	s.d.Restart(c, "--userland-proxy-path", dockerProxyPath)
  2772  	out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2773  	c.Assert(err, checker.IsNil, check.Commentf(out))
  2774  
  2775  	// not exist
  2776  	s.d.Restart(c, "--userland-proxy-path", "/does/not/exist")
  2777  	out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2778  	c.Assert(err, checker.NotNil, check.Commentf(out))
  2779  	c.Assert(out, checker.Contains, "driver failed programming external connectivity on endpoint")
  2780  	c.Assert(out, checker.Contains, "/does/not/exist: no such file or directory")
  2781  }
  2782  
  2783  // Test case for #22471
  2784  func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) {
  2785  	testRequires(c, SameHostDaemon)
  2786  	s.d.StartWithBusybox(c, "--shutdown-timeout=3")
  2787  
  2788  	_, err := s.d.Cmd("run", "-d", "busybox", "top")
  2789  	c.Assert(err, check.IsNil)
  2790  
  2791  	c.Assert(s.d.Signal(unix.SIGINT), checker.IsNil)
  2792  
  2793  	select {
  2794  	case <-s.d.Wait:
  2795  	case <-time.After(5 * time.Second):
  2796  	}
  2797  
  2798  	expectedMessage := `level=debug msg="daemon configured with a 3 seconds minimum shutdown timeout"`
  2799  	content, err := s.d.ReadLogFile()
  2800  	c.Assert(err, checker.IsNil)
  2801  	c.Assert(string(content), checker.Contains, expectedMessage)
  2802  }
  2803  
  2804  // Test case for #22471
  2805  func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) {
  2806  	testRequires(c, SameHostDaemon)
  2807  
  2808  	// daemon config file
  2809  	configFilePath := "test.json"
  2810  	configFile, err := os.Create(configFilePath)
  2811  	c.Assert(err, checker.IsNil)
  2812  	defer os.Remove(configFilePath)
  2813  
  2814  	daemonConfig := `{ "shutdown-timeout" : 8 }`
  2815  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2816  	configFile.Close()
  2817  	s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  2818  
  2819  	configFile, err = os.Create(configFilePath)
  2820  	c.Assert(err, checker.IsNil)
  2821  	daemonConfig = `{ "shutdown-timeout" : 5 }`
  2822  	fmt.Fprintf(configFile, "%s", daemonConfig)
  2823  	configFile.Close()
  2824  
  2825  	c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2826  
  2827  	select {
  2828  	case <-s.d.Wait:
  2829  	case <-time.After(3 * time.Second):
  2830  	}
  2831  
  2832  	expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"`
  2833  	content, err := s.d.ReadLogFile()
  2834  	c.Assert(err, checker.IsNil)
  2835  	c.Assert(string(content), checker.Contains, expectedMessage)
  2836  }
  2837  
  2838  // Test case for 29342
  2839  func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) {
  2840  	testRequires(c, DaemonIsLinux)
  2841  	s.d.StartWithBusybox(c, "--live-restore")
  2842  
  2843  	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")
  2844  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2845  
  2846  	s.d.WaitRun("top")
  2847  
  2848  	// Wait for shell command to be completed
  2849  	_, 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`)
  2850  	c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for shell command to be completed"))
  2851  
  2852  	out1, err := s.d.Cmd("exec", "-u", "test", "top", "id")
  2853  	// uid=100(test) gid=101(test) groups=101(test)
  2854  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out1))
  2855  
  2856  	// restart daemon.
  2857  	s.d.Restart(c, "--live-restore")
  2858  
  2859  	out2, err := s.d.Cmd("exec", "-u", "test", "top", "id")
  2860  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out2))
  2861  	c.Assert(out2, check.Equals, out1, check.Commentf("Output: before restart '%s', after restart '%s'", out1, out2))
  2862  
  2863  	out, err = s.d.Cmd("stop", "top")
  2864  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2865  }
  2866  
  2867  func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) {
  2868  	testRequires(c, DaemonIsLinux, overlayFSSupported, SameHostDaemon)
  2869  	s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay")
  2870  	out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top")
  2871  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2872  
  2873  	s.d.WaitRun("top")
  2874  
  2875  	// restart daemon.
  2876  	s.d.Restart(c, "--live-restore", "--storage-driver", "overlay")
  2877  
  2878  	out, err = s.d.Cmd("stop", "top")
  2879  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2880  
  2881  	// test if the rootfs mountpoint still exist
  2882  	mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir")
  2883  	c.Assert(err, check.IsNil)
  2884  	f, err := os.Open("/proc/self/mountinfo")
  2885  	c.Assert(err, check.IsNil)
  2886  	defer f.Close()
  2887  	sc := bufio.NewScanner(f)
  2888  	for sc.Scan() {
  2889  		line := sc.Text()
  2890  		if strings.Contains(line, mountpoint) {
  2891  			c.Fatalf("mountinfo should not include the mountpoint of stop container")
  2892  		}
  2893  	}
  2894  
  2895  	out, err = s.d.Cmd("rm", "top")
  2896  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2897  }
  2898  
  2899  // #29598
  2900  func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) {
  2901  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  2902  	s.d.StartWithBusybox(c, "--live-restore")
  2903  
  2904  	out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  2905  	c.Assert(err, check.IsNil, check.Commentf("output: %s", out))
  2906  	id := strings.TrimSpace(out)
  2907  
  2908  	type state struct {
  2909  		Running   bool
  2910  		StartedAt time.Time
  2911  	}
  2912  	out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id)
  2913  	c.Assert(err, checker.IsNil, check.Commentf("output: %s", out))
  2914  
  2915  	var origState state
  2916  	err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState)
  2917  	c.Assert(err, checker.IsNil)
  2918  
  2919  	s.d.Restart(c, "--live-restore")
  2920  
  2921  	pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id)
  2922  	c.Assert(err, check.IsNil)
  2923  	pidint, err := strconv.Atoi(strings.TrimSpace(pid))
  2924  	c.Assert(err, check.IsNil)
  2925  	c.Assert(pidint, checker.GreaterThan, 0)
  2926  	c.Assert(unix.Kill(pidint, unix.SIGKILL), check.IsNil)
  2927  
  2928  	ticker := time.NewTicker(50 * time.Millisecond)
  2929  	timeout := time.After(10 * time.Second)
  2930  
  2931  	for range ticker.C {
  2932  		select {
  2933  		case <-timeout:
  2934  			c.Fatal("timeout waiting for container restart")
  2935  		default:
  2936  		}
  2937  
  2938  		out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id)
  2939  		c.Assert(err, checker.IsNil, check.Commentf("output: %s", out))
  2940  
  2941  		var newState state
  2942  		err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState)
  2943  		c.Assert(err, checker.IsNil)
  2944  
  2945  		if !newState.Running {
  2946  			continue
  2947  		}
  2948  		if newState.StartedAt.After(origState.StartedAt) {
  2949  			break
  2950  		}
  2951  	}
  2952  
  2953  	out, err = s.d.Cmd("stop", id)
  2954  	c.Assert(err, check.IsNil, check.Commentf("output: %s", out))
  2955  }
  2956  
  2957  func (s *DockerDaemonSuite) TestShmSize(c *check.C) {
  2958  	testRequires(c, DaemonIsLinux)
  2959  
  2960  	size := 67108864 * 2
  2961  	pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  2962  
  2963  	s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size))
  2964  
  2965  	name := "shm1"
  2966  	out, err := s.d.Cmd("run", "--name", name, "busybox", "mount")
  2967  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2968  	c.Assert(pattern.MatchString(out), checker.True)
  2969  	out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  2970  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2971  	c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  2972  }
  2973  
  2974  func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) {
  2975  	testRequires(c, DaemonIsLinux)
  2976  
  2977  	configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config")
  2978  	c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload"))
  2979  	defer os.RemoveAll(configPath) // clean up
  2980  	configFile := filepath.Join(configPath, "config.json")
  2981  
  2982  	size := 67108864 * 2
  2983  	configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024))
  2984  	c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload"))
  2985  	pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  2986  
  2987  	s.d.StartWithBusybox(c, "--config-file", configFile)
  2988  
  2989  	name := "shm1"
  2990  	out, err := s.d.Cmd("run", "--name", name, "busybox", "mount")
  2991  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2992  	c.Assert(pattern.MatchString(out), checker.True)
  2993  	out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  2994  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2995  	c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  2996  
  2997  	size = 67108864 * 3
  2998  	configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024))
  2999  	c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload"))
  3000  	pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  3001  
  3002  	err = s.d.ReloadConfig()
  3003  	c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config"))
  3004  
  3005  	name = "shm2"
  3006  	out, err = s.d.Cmd("run", "--name", name, "busybox", "mount")
  3007  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  3008  	c.Assert(pattern.MatchString(out), checker.True)
  3009  	out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  3010  	c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  3011  	c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  3012  }
  3013  
  3014  // this is used to test both "private" and "shareable" daemon default ipc modes
  3015  func testDaemonIpcPrivateShareable(d *daemon.Daemon, c *check.C, mustExist bool) {
  3016  	name := "test-ipcmode"
  3017  	_, err := d.Cmd("run", "-d", "--name", name, "busybox", "top")
  3018  	c.Assert(err, checker.IsNil)
  3019  
  3020  	// get major:minor pair for /dev/shm from container's /proc/self/mountinfo
  3021  	cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo"
  3022  	mm, err := d.Cmd("exec", "-i", name, "sh", "-c", cmd)
  3023  	c.Assert(err, checker.IsNil)
  3024  	c.Assert(mm, checker.Matches, "^[0-9]+:[0-9]+$")
  3025  
  3026  	exists, err := testIpcCheckDevExists(mm)
  3027  	c.Assert(err, checker.IsNil)
  3028  	c.Logf("[testDaemonIpcPrivateShareable] ipcdev: %v, exists: %v, mustExist: %v\n", mm, exists, mustExist)
  3029  	c.Assert(exists, checker.Equals, mustExist)
  3030  }
  3031  
  3032  // TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended.
  3033  func (s *DockerDaemonSuite) TestDaemonIpcModeShareable(c *check.C) {
  3034  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3035  
  3036  	s.d.StartWithBusybox(c, "--default-ipc-mode", "shareable")
  3037  	testDaemonIpcPrivateShareable(s.d, c, true)
  3038  }
  3039  
  3040  // TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended.
  3041  func (s *DockerDaemonSuite) TestDaemonIpcModePrivate(c *check.C) {
  3042  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3043  
  3044  	s.d.StartWithBusybox(c, "--default-ipc-mode", "private")
  3045  	testDaemonIpcPrivateShareable(s.d, c, false)
  3046  }
  3047  
  3048  // used to check if an IpcMode given in config works as intended
  3049  func testDaemonIpcFromConfig(s *DockerDaemonSuite, c *check.C, mode string, mustExist bool) {
  3050  	f, err := ioutil.TempFile("", "test-daemon-ipc-config")
  3051  	c.Assert(err, checker.IsNil)
  3052  	defer os.Remove(f.Name())
  3053  
  3054  	config := `{"default-ipc-mode": "` + mode + `"}`
  3055  	_, err = f.WriteString(config)
  3056  	c.Assert(f.Close(), checker.IsNil)
  3057  	c.Assert(err, checker.IsNil)
  3058  
  3059  	s.d.StartWithBusybox(c, "--config-file", f.Name())
  3060  	testDaemonIpcPrivateShareable(s.d, c, mustExist)
  3061  }
  3062  
  3063  // TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended.
  3064  func (s *DockerDaemonSuite) TestDaemonIpcModePrivateFromConfig(c *check.C) {
  3065  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3066  	testDaemonIpcFromConfig(s, c, "private", false)
  3067  }
  3068  
  3069  // TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended.
  3070  func (s *DockerDaemonSuite) TestDaemonIpcModeShareableFromConfig(c *check.C) {
  3071  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3072  	testDaemonIpcFromConfig(s, c, "shareable", true)
  3073  }
  3074  
  3075  func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) {
  3076  	d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  3077  	c.Logf("Checking IpcMode %s set from %s\n", mode, from)
  3078  	var serr error
  3079  	switch from {
  3080  	case "config":
  3081  		f, err := ioutil.TempFile("", "test-daemon-ipc-config")
  3082  		c.Assert(err, checker.IsNil)
  3083  		defer os.Remove(f.Name())
  3084  		config := `{"default-ipc-mode": "` + mode + `"}`
  3085  		_, err = f.WriteString(config)
  3086  		c.Assert(f.Close(), checker.IsNil)
  3087  		c.Assert(err, checker.IsNil)
  3088  
  3089  		serr = d.StartWithError("--config-file", f.Name())
  3090  	case "cli":
  3091  		serr = d.StartWithError("--default-ipc-mode", mode)
  3092  	default:
  3093  		c.Fatalf("testDaemonStartIpcMode: invalid 'from' argument")
  3094  	}
  3095  	if serr == nil {
  3096  		d.Stop(c)
  3097  	}
  3098  
  3099  	if valid {
  3100  		c.Assert(serr, check.IsNil)
  3101  	} else {
  3102  		c.Assert(serr, check.NotNil)
  3103  		icmd.RunCommand("grep", "-E", "IPC .* is (invalid|not supported)", d.LogFileName()).Assert(c, icmd.Success)
  3104  	}
  3105  }
  3106  
  3107  // TestDaemonStartWithIpcModes checks that daemon starts fine given correct
  3108  // arguments for default IPC mode, and bails out with incorrect ones.
  3109  // Both CLI option (--default-ipc-mode) and config parameter are tested.
  3110  func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *check.C) {
  3111  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3112  
  3113  	ipcModes := []struct {
  3114  		mode  string
  3115  		valid bool
  3116  	}{
  3117  		{"private", true},
  3118  		{"shareable", true},
  3119  
  3120  		{"host", false},
  3121  		{"container:123", false},
  3122  		{"nosuchmode", false},
  3123  	}
  3124  
  3125  	for _, from := range []string{"config", "cli"} {
  3126  		for _, m := range ipcModes {
  3127  			testDaemonStartIpcMode(c, from, m.mode, m.valid)
  3128  		}
  3129  	}
  3130  }
  3131  
  3132  // TestDaemonRestartIpcMode makes sure a container keeps its ipc mode
  3133  // (derived from daemon default) even after the daemon is restarted
  3134  // with a different default ipc mode.
  3135  func (s *DockerDaemonSuite) TestDaemonRestartIpcMode(c *check.C) {
  3136  	f, err := ioutil.TempFile("", "test-daemon-ipc-config-restart")
  3137  	c.Assert(err, checker.IsNil)
  3138  	file := f.Name()
  3139  	defer os.Remove(file)
  3140  	c.Assert(f.Close(), checker.IsNil)
  3141  
  3142  	config := []byte(`{"default-ipc-mode": "private"}`)
  3143  	c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil)
  3144  	s.d.StartWithBusybox(c, "--config-file", file)
  3145  
  3146  	// check the container is created with private ipc mode as per daemon default
  3147  	name := "ipc1"
  3148  	_, err = s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  3149  	c.Assert(err, checker.IsNil)
  3150  	m, err := s.d.InspectField(name, ".HostConfig.IpcMode")
  3151  	c.Assert(err, check.IsNil)
  3152  	c.Assert(m, checker.Equals, "private")
  3153  
  3154  	// restart the daemon with shareable default ipc mode
  3155  	config = []byte(`{"default-ipc-mode": "shareable"}`)
  3156  	c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil)
  3157  	s.d.Restart(c, "--config-file", file)
  3158  
  3159  	// check the container is still having private ipc mode
  3160  	m, err = s.d.InspectField(name, ".HostConfig.IpcMode")
  3161  	c.Assert(err, check.IsNil)
  3162  	c.Assert(m, checker.Equals, "private")
  3163  
  3164  	// check a new container is created with shareable ipc mode as per new daemon default
  3165  	name = "ipc2"
  3166  	_, err = s.d.Cmd("run", "-d", "--name", name, "busybox", "top")
  3167  	c.Assert(err, checker.IsNil)
  3168  	m, err = s.d.InspectField(name, ".HostConfig.IpcMode")
  3169  	c.Assert(err, check.IsNil)
  3170  	c.Assert(m, checker.Equals, "shareable")
  3171  }
  3172  
  3173  // TestFailedPluginRemove makes sure that a failed plugin remove does not block
  3174  // the daemon from starting
  3175  func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) {
  3176  	testRequires(c, DaemonIsLinux, IsAmd64, SameHostDaemon)
  3177  	d := daemon.New(c, dockerBinary, dockerdBinary)
  3178  	d.Start(c)
  3179  	cli, err := client.NewClient(d.Sock(), api.DefaultVersion, nil, nil)
  3180  	c.Assert(err, checker.IsNil)
  3181  
  3182  	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
  3183  	defer cancel()
  3184  
  3185  	name := "test-plugin-rm-fail"
  3186  	out, err := cli.PluginInstall(ctx, name, types.PluginInstallOptions{
  3187  		Disabled:             true,
  3188  		AcceptAllPermissions: true,
  3189  		RemoteRef:            "cpuguy83/docker-logdriver-test",
  3190  	})
  3191  	c.Assert(err, checker.IsNil)
  3192  	defer out.Close()
  3193  	io.Copy(ioutil.Discard, out)
  3194  
  3195  	ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
  3196  	defer cancel()
  3197  	p, _, err := cli.PluginInspectWithRaw(ctx, name)
  3198  	c.Assert(err, checker.IsNil)
  3199  
  3200  	// simulate a bad/partial removal by removing the plugin config.
  3201  	configPath := filepath.Join(d.Root, "plugins", p.ID, "config.json")
  3202  	c.Assert(os.Remove(configPath), checker.IsNil)
  3203  
  3204  	d.Restart(c)
  3205  	ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
  3206  	defer cancel()
  3207  	_, err = cli.Ping(ctx)
  3208  	c.Assert(err, checker.IsNil)
  3209  
  3210  	_, _, err = cli.PluginInspectWithRaw(ctx, name)
  3211  	// plugin should be gone since the config.json is gone
  3212  	c.Assert(err, checker.NotNil)
  3213  }