github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/testutil/daemon/daemon.go (about)

     1  package daemon // import "github.com/docker/docker/testutil/daemon"
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"os"
     9  	"os/exec"
    10  	"os/user"
    11  	"path/filepath"
    12  	"strconv"
    13  	"strings"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/docker/docker/api/types"
    18  	"github.com/docker/docker/api/types/events"
    19  	"github.com/docker/docker/client"
    20  	"github.com/docker/docker/pkg/ioutils"
    21  	"github.com/docker/docker/pkg/stringid"
    22  	"github.com/docker/docker/testutil/request"
    23  	"github.com/docker/go-connections/sockets"
    24  	"github.com/docker/go-connections/tlsconfig"
    25  	"github.com/pkg/errors"
    26  	"gotest.tools/v3/assert"
    27  )
    28  
    29  // LogT is the subset of the testing.TB interface used by the daemon.
    30  type LogT interface {
    31  	Logf(string, ...interface{})
    32  }
    33  
    34  // nopLog is a no-op implementation of LogT that is used in daemons created by
    35  // NewDaemon (where no testing.TB is available).
    36  type nopLog struct{}
    37  
    38  func (nopLog) Logf(string, ...interface{}) {}
    39  
    40  const (
    41  	defaultDockerdBinary         = "dockerd"
    42  	defaultContainerdSocket      = "/var/run/docker/containerd/containerd.sock"
    43  	defaultDockerdRootlessBinary = "dockerd-rootless.sh"
    44  	defaultUnixSocket            = "/var/run/docker.sock"
    45  	defaultTLSHost               = "localhost:2376"
    46  )
    47  
    48  var errDaemonNotStarted = errors.New("daemon not started")
    49  
    50  // SockRoot holds the path of the default docker integration daemon socket
    51  var SockRoot = filepath.Join(os.TempDir(), "docker-integration")
    52  
    53  type clientConfig struct {
    54  	transport *http.Transport
    55  	scheme    string
    56  	addr      string
    57  }
    58  
    59  // Daemon represents a Docker daemon for the testing framework
    60  type Daemon struct {
    61  	Root              string
    62  	Folder            string
    63  	Wait              chan error
    64  	UseDefaultHost    bool
    65  	UseDefaultTLSHost bool
    66  
    67  	id                         string
    68  	logFile                    *os.File
    69  	cmd                        *exec.Cmd
    70  	storageDriver              string
    71  	userlandProxy              bool
    72  	defaultCgroupNamespaceMode string
    73  	execRoot                   string
    74  	experimental               bool
    75  	init                       bool
    76  	dockerdBinary              string
    77  	log                        LogT
    78  	pidFile                    string
    79  	args                       []string
    80  	containerdSocket           string
    81  	rootlessUser               *user.User
    82  	rootlessXDGRuntimeDir      string
    83  
    84  	// swarm related field
    85  	swarmListenAddr string
    86  	SwarmPort       int // FIXME(vdemeester) should probably not be exported
    87  	DefaultAddrPool []string
    88  	SubnetSize      uint32
    89  	DataPathPort    uint32
    90  	OOMScoreAdjust  int
    91  	// cached information
    92  	CachedInfo types.Info
    93  }
    94  
    95  // NewDaemon returns a Daemon instance to be used for testing.
    96  // The daemon will not automatically start.
    97  // The daemon will modify and create files under workingDir.
    98  func NewDaemon(workingDir string, ops ...Option) (*Daemon, error) {
    99  	storageDriver := os.Getenv("DOCKER_GRAPHDRIVER")
   100  
   101  	if err := os.MkdirAll(SockRoot, 0700); err != nil {
   102  		return nil, errors.Wrapf(err, "failed to create daemon socket root %q", SockRoot)
   103  	}
   104  
   105  	id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
   106  	dir := filepath.Join(workingDir, id)
   107  	daemonFolder, err := filepath.Abs(dir)
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  	daemonRoot := filepath.Join(daemonFolder, "root")
   112  	if err := os.MkdirAll(daemonRoot, 0755); err != nil {
   113  		return nil, errors.Wrapf(err, "failed to create daemon root %q", daemonRoot)
   114  	}
   115  
   116  	userlandProxy := true
   117  	if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
   118  		if val, err := strconv.ParseBool(env); err != nil {
   119  			userlandProxy = val
   120  		}
   121  	}
   122  	d := &Daemon{
   123  		id:            id,
   124  		Folder:        daemonFolder,
   125  		Root:          daemonRoot,
   126  		storageDriver: storageDriver,
   127  		userlandProxy: userlandProxy,
   128  		// dxr stands for docker-execroot (shortened for avoiding unix(7) path length limitation)
   129  		execRoot:         filepath.Join(os.TempDir(), "dxr", id),
   130  		dockerdBinary:    defaultDockerdBinary,
   131  		swarmListenAddr:  defaultSwarmListenAddr,
   132  		SwarmPort:        DefaultSwarmPort,
   133  		log:              nopLog{},
   134  		containerdSocket: defaultContainerdSocket,
   135  	}
   136  
   137  	for _, op := range ops {
   138  		op(d)
   139  	}
   140  
   141  	if d.rootlessUser != nil {
   142  		if err := os.Chmod(SockRoot, 0777); err != nil {
   143  			return nil, err
   144  		}
   145  		uid, err := strconv.Atoi(d.rootlessUser.Uid)
   146  		if err != nil {
   147  			return nil, err
   148  		}
   149  		gid, err := strconv.Atoi(d.rootlessUser.Gid)
   150  		if err != nil {
   151  			return nil, err
   152  		}
   153  		if err := os.Chown(d.Folder, uid, gid); err != nil {
   154  			return nil, err
   155  		}
   156  		if err := os.Chown(d.Root, uid, gid); err != nil {
   157  			return nil, err
   158  		}
   159  		if err := os.MkdirAll(filepath.Dir(d.execRoot), 0700); err != nil {
   160  			return nil, err
   161  		}
   162  		if err := os.Chown(filepath.Dir(d.execRoot), uid, gid); err != nil {
   163  			return nil, err
   164  		}
   165  		if err := os.MkdirAll(d.execRoot, 0700); err != nil {
   166  			return nil, err
   167  		}
   168  		if err := os.Chown(d.execRoot, uid, gid); err != nil {
   169  			return nil, err
   170  		}
   171  		d.rootlessXDGRuntimeDir = filepath.Join(d.Folder, "xdgrun")
   172  		if err := os.MkdirAll(d.rootlessXDGRuntimeDir, 0700); err != nil {
   173  			return nil, err
   174  		}
   175  		if err := os.Chown(d.rootlessXDGRuntimeDir, uid, gid); err != nil {
   176  			return nil, err
   177  		}
   178  		d.containerdSocket = ""
   179  	}
   180  
   181  	return d, nil
   182  }
   183  
   184  // New returns a Daemon instance to be used for testing.
   185  // This will create a directory such as d123456789 in the folder specified by
   186  // $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
   187  // The daemon will not automatically start.
   188  func New(t testing.TB, ops ...Option) *Daemon {
   189  	t.Helper()
   190  	dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
   191  	if dest == "" {
   192  		dest = os.Getenv("DEST")
   193  	}
   194  	dest = filepath.Join(dest, t.Name())
   195  
   196  	assert.Check(t, dest != "", "Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
   197  
   198  	if os.Getenv("DOCKER_ROOTLESS") != "" {
   199  		if os.Getenv("DOCKER_REMAP_ROOT") != "" {
   200  			t.Skip("DOCKER_ROOTLESS doesn't support DOCKER_REMAP_ROOT currently")
   201  		}
   202  		if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
   203  			if val, err := strconv.ParseBool(env); err == nil && !val {
   204  				t.Skip("DOCKER_ROOTLESS doesn't support DOCKER_USERLANDPROXY=false")
   205  			}
   206  		}
   207  		ops = append(ops, WithRootlessUser("unprivilegeduser"))
   208  	}
   209  	ops = append(ops, WithOOMScoreAdjust(-500))
   210  
   211  	d, err := NewDaemon(dest, ops...)
   212  	assert.NilError(t, err, "could not create daemon at %q", dest)
   213  	if d.rootlessUser != nil && d.dockerdBinary != defaultDockerdBinary {
   214  		t.Skipf("DOCKER_ROOTLESS doesn't support specifying non-default dockerd binary path %q", d.dockerdBinary)
   215  	}
   216  
   217  	return d
   218  }
   219  
   220  // BinaryPath returns the binary and its arguments.
   221  func (d *Daemon) BinaryPath() (string, error) {
   222  	dockerdBinary, err := exec.LookPath(d.dockerdBinary)
   223  	if err != nil {
   224  		return "", errors.Wrapf(err, "[%s] could not find docker binary in $PATH", d.id)
   225  	}
   226  	return dockerdBinary, nil
   227  }
   228  
   229  // ContainersNamespace returns the containerd namespace used for containers.
   230  func (d *Daemon) ContainersNamespace() string {
   231  	return d.id
   232  }
   233  
   234  // RootDir returns the root directory of the daemon.
   235  func (d *Daemon) RootDir() string {
   236  	return d.Root
   237  }
   238  
   239  // ID returns the generated id of the daemon
   240  func (d *Daemon) ID() string {
   241  	return d.id
   242  }
   243  
   244  // StorageDriver returns the configured storage driver of the daemon
   245  func (d *Daemon) StorageDriver() string {
   246  	return d.storageDriver
   247  }
   248  
   249  // Sock returns the socket path of the daemon
   250  func (d *Daemon) Sock() string {
   251  	return fmt.Sprintf("unix://" + d.sockPath())
   252  }
   253  
   254  func (d *Daemon) sockPath() string {
   255  	return filepath.Join(SockRoot, d.id+".sock")
   256  }
   257  
   258  // LogFileName returns the path the daemon's log file
   259  func (d *Daemon) LogFileName() string {
   260  	return d.logFile.Name()
   261  }
   262  
   263  // ReadLogFile returns the content of the daemon log file
   264  func (d *Daemon) ReadLogFile() ([]byte, error) {
   265  	_ = d.logFile.Sync()
   266  	return os.ReadFile(d.logFile.Name())
   267  }
   268  
   269  // NewClientT creates new client based on daemon's socket path
   270  func (d *Daemon) NewClientT(t testing.TB, extraOpts ...client.Opt) *client.Client {
   271  	t.Helper()
   272  
   273  	c, err := d.NewClient(extraOpts...)
   274  	assert.NilError(t, err, "[%s] could not create daemon client", d.id)
   275  	return c
   276  }
   277  
   278  // NewClient creates new client based on daemon's socket path
   279  func (d *Daemon) NewClient(extraOpts ...client.Opt) (*client.Client, error) {
   280  	clientOpts := []client.Opt{
   281  		client.FromEnv,
   282  		client.WithHost(d.Sock()),
   283  	}
   284  	clientOpts = append(clientOpts, extraOpts...)
   285  
   286  	return client.NewClientWithOpts(clientOpts...)
   287  }
   288  
   289  // Cleanup cleans the daemon files : exec root (network namespaces, ...), swarmkit files
   290  func (d *Daemon) Cleanup(t testing.TB) {
   291  	t.Helper()
   292  	cleanupMount(t, d)
   293  	cleanupRaftDir(t, d)
   294  	cleanupDaemonStorage(t, d)
   295  	cleanupNetworkNamespace(t, d)
   296  }
   297  
   298  // Start starts the daemon and return once it is ready to receive requests.
   299  func (d *Daemon) Start(t testing.TB, args ...string) {
   300  	t.Helper()
   301  	if err := d.StartWithError(args...); err != nil {
   302  		d.DumpStackAndQuit() // in case the daemon is stuck
   303  		t.Fatalf("[%s] failed to start daemon with arguments %v : %v", d.id, d.args, err)
   304  	}
   305  }
   306  
   307  // StartWithError starts the daemon and return once it is ready to receive requests.
   308  // It returns an error in case it couldn't start.
   309  func (d *Daemon) StartWithError(args ...string) error {
   310  	logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
   311  	if err != nil {
   312  		return errors.Wrapf(err, "[%s] failed to create logfile", d.id)
   313  	}
   314  
   315  	return d.StartWithLogFile(logFile, args...)
   316  }
   317  
   318  // StartWithLogFile will start the daemon and attach its streams to a given file.
   319  func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
   320  	d.handleUserns()
   321  	dockerdBinary, err := d.BinaryPath()
   322  	if err != nil {
   323  		return err
   324  	}
   325  
   326  	if d.pidFile == "" {
   327  		d.pidFile = filepath.Join(d.Folder, "docker.pid")
   328  	}
   329  
   330  	d.args = []string{}
   331  	if d.rootlessUser != nil {
   332  		if d.dockerdBinary != defaultDockerdBinary {
   333  			return errors.Errorf("[%s] DOCKER_ROOTLESS doesn't support non-default dockerd binary path %q", d.id, d.dockerdBinary)
   334  		}
   335  		dockerdBinary = "sudo"
   336  		d.args = append(d.args,
   337  			"-u", d.rootlessUser.Username,
   338  			"-E", "XDG_RUNTIME_DIR="+d.rootlessXDGRuntimeDir,
   339  			"-E", "HOME="+d.rootlessUser.HomeDir,
   340  			"-E", "PATH="+os.Getenv("PATH"),
   341  			"--",
   342  			defaultDockerdRootlessBinary,
   343  		)
   344  	}
   345  
   346  	d.args = append(d.args,
   347  		"--data-root", d.Root,
   348  		"--exec-root", d.execRoot,
   349  		"--pidfile", d.pidFile,
   350  		fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
   351  		"--containerd-namespace", d.id,
   352  		"--containerd-plugins-namespace", d.id+"p",
   353  	)
   354  	if d.containerdSocket != "" {
   355  		d.args = append(d.args, "--containerd", d.containerdSocket)
   356  	}
   357  
   358  	if d.defaultCgroupNamespaceMode != "" {
   359  		d.args = append(d.args, "--default-cgroupns-mode", d.defaultCgroupNamespaceMode)
   360  	}
   361  	if d.experimental {
   362  		d.args = append(d.args, "--experimental")
   363  	}
   364  	if d.init {
   365  		d.args = append(d.args, "--init")
   366  	}
   367  	if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
   368  		d.args = append(d.args, "--host", d.Sock())
   369  	}
   370  	if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
   371  		d.args = append(d.args, "--userns-remap", root)
   372  	}
   373  
   374  	// If we don't explicitly set the log-level or debug flag(-D) then
   375  	// turn on debug mode
   376  	foundLog := false
   377  	foundSd := false
   378  	for _, a := range providedArgs {
   379  		if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
   380  			foundLog = true
   381  		}
   382  		if strings.Contains(a, "--storage-driver") {
   383  			foundSd = true
   384  		}
   385  	}
   386  	if !foundLog {
   387  		d.args = append(d.args, "--debug")
   388  	}
   389  	if d.storageDriver != "" && !foundSd {
   390  		d.args = append(d.args, "--storage-driver", d.storageDriver)
   391  	}
   392  
   393  	d.args = append(d.args, providedArgs...)
   394  	d.cmd = exec.Command(dockerdBinary, d.args...)
   395  	d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
   396  	d.cmd.Stdout = out
   397  	d.cmd.Stderr = out
   398  	d.logFile = out
   399  	if d.rootlessUser != nil {
   400  		// sudo requires this for propagating signals
   401  		setsid(d.cmd)
   402  	}
   403  
   404  	if err := d.cmd.Start(); err != nil {
   405  		return errors.Wrapf(err, "[%s] could not start daemon container", d.id)
   406  	}
   407  
   408  	wait := make(chan error, 1)
   409  
   410  	go func() {
   411  		ret := d.cmd.Wait()
   412  		d.log.Logf("[%s] exiting daemon", d.id)
   413  		// If we send before logging, we might accidentally log _after_ the test is done.
   414  		// As of Go 1.12, this incurs a panic instead of silently being dropped.
   415  		wait <- ret
   416  		close(wait)
   417  	}()
   418  
   419  	d.Wait = wait
   420  
   421  	clientConfig, err := d.getClientConfig()
   422  	if err != nil {
   423  		return err
   424  	}
   425  	client := &http.Client{
   426  		Transport: clientConfig.transport,
   427  	}
   428  
   429  	req, err := http.NewRequest(http.MethodGet, "/_ping", nil)
   430  	if err != nil {
   431  		return errors.Wrapf(err, "[%s] could not create new request", d.id)
   432  	}
   433  	req.URL.Host = clientConfig.addr
   434  	req.URL.Scheme = clientConfig.scheme
   435  
   436  	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
   437  	defer cancel()
   438  
   439  	// make sure daemon is ready to receive requests
   440  	for i := 0; ; i++ {
   441  		d.log.Logf("[%s] waiting for daemon to start", d.id)
   442  
   443  		select {
   444  		case <-ctx.Done():
   445  			return errors.Wrapf(ctx.Err(), "[%s] daemon exited and never started", d.id)
   446  		case err := <-d.Wait:
   447  			return errors.Wrapf(err, "[%s] daemon exited during startup", d.id)
   448  		default:
   449  			rctx, rcancel := context.WithTimeout(context.TODO(), 2*time.Second)
   450  			defer rcancel()
   451  
   452  			resp, err := client.Do(req.WithContext(rctx))
   453  			if err != nil {
   454  				if i > 2 { // don't log the first couple, this ends up just being noise
   455  					d.log.Logf("[%s] error pinging daemon on start: %v", d.id, err)
   456  				}
   457  
   458  				select {
   459  				case <-ctx.Done():
   460  				case <-time.After(500 * time.Millisecond):
   461  				}
   462  				continue
   463  			}
   464  
   465  			resp.Body.Close()
   466  			if resp.StatusCode != http.StatusOK {
   467  				d.log.Logf("[%s] received status != 200 OK: %s\n", d.id, resp.Status)
   468  			}
   469  			d.log.Logf("[%s] daemon started\n", d.id)
   470  			d.Root, err = d.queryRootDir()
   471  			if err != nil {
   472  				return errors.Wrapf(err, "[%s] error querying daemon for root directory", d.id)
   473  			}
   474  			return nil
   475  		}
   476  	}
   477  }
   478  
   479  // StartWithBusybox will first start the daemon with Daemon.Start()
   480  // then save the busybox image from the main daemon and load it into this Daemon instance.
   481  func (d *Daemon) StartWithBusybox(t testing.TB, arg ...string) {
   482  	t.Helper()
   483  	d.Start(t, arg...)
   484  	d.LoadBusybox(t)
   485  }
   486  
   487  // Kill will send a SIGKILL to the daemon
   488  func (d *Daemon) Kill() error {
   489  	if d.cmd == nil || d.Wait == nil {
   490  		return errDaemonNotStarted
   491  	}
   492  
   493  	defer func() {
   494  		d.logFile.Close()
   495  		d.cmd = nil
   496  	}()
   497  
   498  	if err := d.cmd.Process.Kill(); err != nil {
   499  		return err
   500  	}
   501  
   502  	if d.pidFile != "" {
   503  		_ = os.Remove(d.pidFile)
   504  	}
   505  	return nil
   506  }
   507  
   508  // Pid returns the pid of the daemon
   509  func (d *Daemon) Pid() int {
   510  	return d.cmd.Process.Pid
   511  }
   512  
   513  // Interrupt stops the daemon by sending it an Interrupt signal
   514  func (d *Daemon) Interrupt() error {
   515  	return d.Signal(os.Interrupt)
   516  }
   517  
   518  // Signal sends the specified signal to the daemon if running
   519  func (d *Daemon) Signal(signal os.Signal) error {
   520  	if d.cmd == nil || d.Wait == nil {
   521  		return errDaemonNotStarted
   522  	}
   523  	return d.cmd.Process.Signal(signal)
   524  }
   525  
   526  // DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
   527  // stack to its log file and exit
   528  // This is used primarily for gathering debug information on test timeout
   529  func (d *Daemon) DumpStackAndQuit() {
   530  	if d.cmd == nil || d.cmd.Process == nil {
   531  		return
   532  	}
   533  	SignalDaemonDump(d.cmd.Process.Pid)
   534  }
   535  
   536  // Stop will send a SIGINT every second and wait for the daemon to stop.
   537  // If it times out, a SIGKILL is sent.
   538  // Stop will not delete the daemon directory. If a purged daemon is needed,
   539  // instantiate a new one with NewDaemon.
   540  // If an error occurs while starting the daemon, the test will fail.
   541  func (d *Daemon) Stop(t testing.TB) {
   542  	t.Helper()
   543  	err := d.StopWithError()
   544  	if err != nil {
   545  		if err != errDaemonNotStarted {
   546  			t.Fatalf("[%s] error while stopping the daemon: %v", d.id, err)
   547  		} else {
   548  			t.Logf("[%s] daemon is not started", d.id)
   549  		}
   550  	}
   551  }
   552  
   553  // StopWithError will send a SIGINT every second and wait for the daemon to stop.
   554  // If it timeouts, a SIGKILL is sent.
   555  // Stop will not delete the daemon directory. If a purged daemon is needed,
   556  // instantiate a new one with NewDaemon.
   557  func (d *Daemon) StopWithError() (err error) {
   558  	if d.cmd == nil || d.Wait == nil {
   559  		return errDaemonNotStarted
   560  	}
   561  	defer func() {
   562  		if err != nil {
   563  			d.log.Logf("[%s] error while stopping daemon: %v", d.id, err)
   564  		} else {
   565  			d.log.Logf("[%s] daemon stopped", d.id)
   566  			if d.pidFile != "" {
   567  				_ = os.Remove(d.pidFile)
   568  			}
   569  		}
   570  		if err := d.logFile.Close(); err != nil {
   571  			d.log.Logf("[%s] failed to close daemon logfile: %v", d.id, err)
   572  		}
   573  		d.cmd = nil
   574  	}()
   575  
   576  	i := 1
   577  	ticker := time.NewTicker(time.Second)
   578  	defer ticker.Stop()
   579  	tick := ticker.C
   580  
   581  	d.log.Logf("[%s] stopping daemon", d.id)
   582  
   583  	if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
   584  		if strings.Contains(err.Error(), "os: process already finished") {
   585  			return errDaemonNotStarted
   586  		}
   587  		return errors.Wrapf(err, "[%s] could not send signal", d.id)
   588  	}
   589  
   590  out1:
   591  	for {
   592  		select {
   593  		case err := <-d.Wait:
   594  			return err
   595  		case <-time.After(20 * time.Second):
   596  			// time for stopping jobs and run onShutdown hooks
   597  			d.log.Logf("[%s] daemon stop timed out after 20 seconds", d.id)
   598  			break out1
   599  		}
   600  	}
   601  
   602  out2:
   603  	for {
   604  		select {
   605  		case err := <-d.Wait:
   606  			return err
   607  		case <-tick:
   608  			i++
   609  			if i > 5 {
   610  				d.log.Logf("[%s] tried to interrupt daemon for %d times, now try to kill it", d.id, i)
   611  				break out2
   612  			}
   613  			d.log.Logf("[%d] attempt #%d/5: daemon is still running with pid %d", i, d.cmd.Process.Pid)
   614  			if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
   615  				return errors.Wrapf(err, "[%s] attempt #%d/5 could not send signal", d.id, i)
   616  			}
   617  		}
   618  	}
   619  
   620  	if err := d.cmd.Process.Kill(); err != nil {
   621  		d.log.Logf("[%s] failed to kill daemon: %v", d.id, err)
   622  		return err
   623  	}
   624  
   625  	return nil
   626  }
   627  
   628  // Restart will restart the daemon by first stopping it and the starting it.
   629  // If an error occurs while starting the daemon, the test will fail.
   630  func (d *Daemon) Restart(t testing.TB, args ...string) {
   631  	t.Helper()
   632  	d.Stop(t)
   633  	d.Start(t, args...)
   634  }
   635  
   636  // RestartWithError will restart the daemon by first stopping it and then starting it.
   637  func (d *Daemon) RestartWithError(arg ...string) error {
   638  	if err := d.StopWithError(); err != nil {
   639  		return err
   640  	}
   641  	return d.StartWithError(arg...)
   642  }
   643  
   644  func (d *Daemon) handleUserns() {
   645  	// in the case of tests running a user namespace-enabled daemon, we have resolved
   646  	// d.Root to be the actual final path of the graph dir after the "uid.gid" of
   647  	// remapped root is added--we need to subtract it from the path before calling
   648  	// start or else we will continue making subdirectories rather than truly restarting
   649  	// with the same location/root:
   650  	if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
   651  		d.Root = filepath.Dir(d.Root)
   652  	}
   653  }
   654  
   655  // ReloadConfig asks the daemon to reload its configuration
   656  func (d *Daemon) ReloadConfig() error {
   657  	if d.cmd == nil || d.cmd.Process == nil {
   658  		return errors.New("daemon is not running")
   659  	}
   660  
   661  	errCh := make(chan error, 1)
   662  	started := make(chan struct{})
   663  	go func() {
   664  		_, body, err := request.Get("/events", request.Host(d.Sock()))
   665  		close(started)
   666  		if err != nil {
   667  			errCh <- err
   668  			return
   669  		}
   670  		defer body.Close()
   671  		dec := json.NewDecoder(body)
   672  		for {
   673  			var e events.Message
   674  			if err := dec.Decode(&e); err != nil {
   675  				errCh <- err
   676  				return
   677  			}
   678  			if e.Type != events.DaemonEventType {
   679  				continue
   680  			}
   681  			if e.Action != "reload" {
   682  				continue
   683  			}
   684  			close(errCh) // notify that we are done
   685  			return
   686  		}
   687  	}()
   688  
   689  	<-started
   690  	if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
   691  		return errors.Wrapf(err, "[%s] error signaling daemon reload", d.id)
   692  	}
   693  	select {
   694  	case err := <-errCh:
   695  		if err != nil {
   696  			return errors.Wrapf(err, "[%s] error waiting for daemon reload event", d.id)
   697  		}
   698  	case <-time.After(30 * time.Second):
   699  		return errors.Errorf("[%s] daemon reload event timed out after 30 seconds", d.id)
   700  	}
   701  	return nil
   702  }
   703  
   704  // LoadBusybox image into the daemon
   705  func (d *Daemon) LoadBusybox(t testing.TB) {
   706  	t.Helper()
   707  	clientHost, err := client.NewClientWithOpts(client.FromEnv)
   708  	assert.NilError(t, err, "[%s] failed to create client", d.id)
   709  	defer clientHost.Close()
   710  
   711  	ctx := context.Background()
   712  	reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
   713  	assert.NilError(t, err, "[%s] failed to download busybox", d.id)
   714  	defer reader.Close()
   715  
   716  	c := d.NewClientT(t)
   717  	defer c.Close()
   718  
   719  	resp, err := c.ImageLoad(ctx, reader, true)
   720  	assert.NilError(t, err, "[%s] failed to load busybox", d.id)
   721  	defer resp.Body.Close()
   722  }
   723  
   724  func (d *Daemon) getClientConfig() (*clientConfig, error) {
   725  	var (
   726  		transport *http.Transport
   727  		scheme    string
   728  		addr      string
   729  		proto     string
   730  	)
   731  	if d.UseDefaultTLSHost {
   732  		option := &tlsconfig.Options{
   733  			CAFile:   "fixtures/https/ca.pem",
   734  			CertFile: "fixtures/https/client-cert.pem",
   735  			KeyFile:  "fixtures/https/client-key.pem",
   736  		}
   737  		tlsConfig, err := tlsconfig.Client(*option)
   738  		if err != nil {
   739  			return nil, err
   740  		}
   741  		transport = &http.Transport{
   742  			TLSClientConfig: tlsConfig,
   743  		}
   744  		addr = defaultTLSHost
   745  		scheme = "https"
   746  		proto = "tcp"
   747  	} else if d.UseDefaultHost {
   748  		addr = defaultUnixSocket
   749  		proto = "unix"
   750  		scheme = "http"
   751  		transport = &http.Transport{}
   752  	} else {
   753  		addr = d.sockPath()
   754  		proto = "unix"
   755  		scheme = "http"
   756  		transport = &http.Transport{}
   757  	}
   758  
   759  	if err := sockets.ConfigureTransport(transport, proto, addr); err != nil {
   760  		return nil, err
   761  	}
   762  	transport.DisableKeepAlives = true
   763  	if proto == "unix" {
   764  		addr = filepath.Base(addr)
   765  	}
   766  	return &clientConfig{
   767  		transport: transport,
   768  		scheme:    scheme,
   769  		addr:      addr,
   770  	}, nil
   771  }
   772  
   773  func (d *Daemon) queryRootDir() (string, error) {
   774  	// update daemon root by asking /info endpoint (to support user
   775  	// namespaced daemon with root remapped uid.gid directory)
   776  	clientConfig, err := d.getClientConfig()
   777  	if err != nil {
   778  		return "", err
   779  	}
   780  
   781  	c := &http.Client{
   782  		Transport: clientConfig.transport,
   783  	}
   784  
   785  	req, err := http.NewRequest(http.MethodGet, "/info", nil)
   786  	if err != nil {
   787  		return "", err
   788  	}
   789  	req.Header.Set("Content-Type", "application/json")
   790  	req.URL.Host = clientConfig.addr
   791  	req.URL.Scheme = clientConfig.scheme
   792  
   793  	resp, err := c.Do(req)
   794  	if err != nil {
   795  		return "", err
   796  	}
   797  	body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
   798  		return resp.Body.Close()
   799  	})
   800  
   801  	type Info struct {
   802  		DockerRootDir string
   803  	}
   804  	var b []byte
   805  	var i Info
   806  	b, err = request.ReadBody(body)
   807  	if err == nil && resp.StatusCode == http.StatusOK {
   808  		// read the docker root dir
   809  		if err = json.Unmarshal(b, &i); err == nil {
   810  			return i.DockerRootDir, nil
   811  		}
   812  	}
   813  	return "", err
   814  }
   815  
   816  // Info returns the info struct for this daemon
   817  func (d *Daemon) Info(t testing.TB) types.Info {
   818  	t.Helper()
   819  	c := d.NewClientT(t)
   820  	info, err := c.Info(context.Background())
   821  	assert.NilError(t, err)
   822  	assert.NilError(t, c.Close())
   823  	return info
   824  }
   825  
   826  // cleanupRaftDir removes swarmkit wal files if present
   827  func cleanupRaftDir(t testing.TB, d *Daemon) {
   828  	t.Helper()
   829  	for _, p := range []string{"wal", "wal-v3-encrypted", "snap-v3-encrypted"} {
   830  		dir := filepath.Join(d.Root, "swarm/raft", p)
   831  		if err := os.RemoveAll(dir); err != nil {
   832  			t.Logf("[%s] error removing %v: %v", d.id, dir, err)
   833  		}
   834  	}
   835  }
   836  
   837  // cleanupDaemonStorage removes the daemon's storage directory.
   838  //
   839  // Note that we don't delete the whole directory, as some files (e.g. daemon
   840  // logs) are collected for inclusion in the "bundles" that are stored as Jenkins
   841  // artifacts.
   842  //
   843  // We currently do not include container logs in the bundles, so this also
   844  // removes the "containers" sub-directory.
   845  func cleanupDaemonStorage(t testing.TB, d *Daemon) {
   846  	t.Helper()
   847  	dirs := []string{
   848  		"builder",
   849  		"buildkit",
   850  		"containers",
   851  		"image",
   852  		"network",
   853  		"plugins",
   854  		"tmp",
   855  		"trust",
   856  		"volumes",
   857  		// note: this assumes storage-driver name matches the subdirectory,
   858  		// which is currently true, but not guaranteed.
   859  		d.storageDriver,
   860  	}
   861  
   862  	for _, p := range dirs {
   863  		dir := filepath.Join(d.Root, p)
   864  		if err := os.RemoveAll(dir); err != nil {
   865  			t.Logf("[%s] error removing %v: %v", d.id, dir, err)
   866  		}
   867  	}
   868  }