github.com/a4a881d4/docker@v1.9.0-rc2/integration-cli/docker_utils.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"encoding/json"
     7  	"errors"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"net"
    12  	"net/http"
    13  	"net/http/httptest"
    14  	"net/http/httputil"
    15  	"net/url"
    16  	"os"
    17  	"os/exec"
    18  	"path"
    19  	"path/filepath"
    20  	"strconv"
    21  	"strings"
    22  	"time"
    23  
    24  	"github.com/docker/docker/api/types"
    25  	"github.com/docker/docker/opts"
    26  	"github.com/docker/docker/pkg/httputils"
    27  	"github.com/docker/docker/pkg/integration"
    28  	"github.com/docker/docker/pkg/ioutils"
    29  	"github.com/docker/docker/pkg/sockets"
    30  	"github.com/docker/docker/pkg/stringutils"
    31  	"github.com/docker/docker/pkg/tlsconfig"
    32  	"github.com/go-check/check"
    33  )
    34  
    35  // Daemon represents a Docker daemon for the testing framework.
    36  type Daemon struct {
    37  	// Defaults to "daemon"
    38  	// Useful to set to --daemon or -d for checking backwards compatibility
    39  	Command     string
    40  	GlobalFlags []string
    41  
    42  	id                string
    43  	c                 *check.C
    44  	logFile           *os.File
    45  	folder            string
    46  	root              string
    47  	stdin             io.WriteCloser
    48  	stdout, stderr    io.ReadCloser
    49  	cmd               *exec.Cmd
    50  	storageDriver     string
    51  	execDriver        string
    52  	wait              chan error
    53  	userlandProxy     bool
    54  	useDefaultHost    bool
    55  	useDefaultTLSHost bool
    56  }
    57  
    58  type clientConfig struct {
    59  	transport *http.Transport
    60  	scheme    string
    61  	addr      string
    62  }
    63  
    64  // NewDaemon returns a Daemon instance to be used for testing.
    65  // This will create a directory such as d123456789 in the folder specified by $DEST.
    66  // The daemon will not automatically start.
    67  func NewDaemon(c *check.C) *Daemon {
    68  	dest := os.Getenv("DEST")
    69  	if dest == "" {
    70  		c.Fatal("Please set the DEST environment variable")
    71  	}
    72  
    73  	id := fmt.Sprintf("d%d", time.Now().UnixNano()%100000000)
    74  	dir := filepath.Join(dest, id)
    75  	daemonFolder, err := filepath.Abs(dir)
    76  	if err != nil {
    77  		c.Fatalf("Could not make %q an absolute path: %v", dir, err)
    78  	}
    79  	daemonRoot := filepath.Join(daemonFolder, "root")
    80  
    81  	if err := os.MkdirAll(daemonRoot, 0755); err != nil {
    82  		c.Fatalf("Could not create daemon root %q: %v", dir, err)
    83  	}
    84  
    85  	userlandProxy := true
    86  	if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
    87  		if val, err := strconv.ParseBool(env); err != nil {
    88  			userlandProxy = val
    89  		}
    90  	}
    91  
    92  	return &Daemon{
    93  		Command:       "daemon",
    94  		id:            id,
    95  		c:             c,
    96  		folder:        daemonFolder,
    97  		root:          daemonRoot,
    98  		storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
    99  		execDriver:    os.Getenv("DOCKER_EXECDRIVER"),
   100  		userlandProxy: userlandProxy,
   101  	}
   102  }
   103  
   104  func (d *Daemon) getClientConfig() (*clientConfig, error) {
   105  	var (
   106  		transport *http.Transport
   107  		scheme    string
   108  		addr      string
   109  		proto     string
   110  	)
   111  	if d.useDefaultTLSHost {
   112  		option := &tlsconfig.Options{
   113  			CAFile:   "fixtures/https/ca.pem",
   114  			CertFile: "fixtures/https/client-cert.pem",
   115  			KeyFile:  "fixtures/https/client-key.pem",
   116  		}
   117  		tlsConfig, err := tlsconfig.Client(*option)
   118  		if err != nil {
   119  			return nil, err
   120  		}
   121  		transport = &http.Transport{
   122  			TLSClientConfig: tlsConfig,
   123  		}
   124  		addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
   125  		scheme = "https"
   126  		proto = "tcp"
   127  	} else if d.useDefaultHost {
   128  		addr = opts.DefaultUnixSocket
   129  		proto = "unix"
   130  		scheme = "http"
   131  		transport = &http.Transport{}
   132  	} else {
   133  		addr = filepath.Join(d.folder, "docker.sock")
   134  		proto = "unix"
   135  		scheme = "http"
   136  		transport = &http.Transport{}
   137  	}
   138  
   139  	sockets.ConfigureTCPTransport(transport, proto, addr)
   140  
   141  	return &clientConfig{
   142  		transport: transport,
   143  		scheme:    scheme,
   144  		addr:      addr,
   145  	}, nil
   146  }
   147  
   148  // Start will start the daemon and return once it is ready to receive requests.
   149  // You can specify additional daemon flags.
   150  func (d *Daemon) Start(arg ...string) error {
   151  	dockerBinary, err := exec.LookPath(dockerBinary)
   152  	if err != nil {
   153  		d.c.Fatalf("[%s] could not find docker binary in $PATH: %v", d.id, err)
   154  	}
   155  
   156  	args := append(d.GlobalFlags,
   157  		d.Command,
   158  		"--graph", d.root,
   159  		"--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
   160  		fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
   161  	)
   162  	if !(d.useDefaultHost || d.useDefaultTLSHost) {
   163  		args = append(args, []string{"--host", d.sock()}...)
   164  	}
   165  	if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
   166  		args = append(args, []string{"--userns-remap", root}...)
   167  	}
   168  
   169  	// If we don't explicitly set the log-level or debug flag(-D) then
   170  	// turn on debug mode
   171  	foundIt := false
   172  	for _, a := range arg {
   173  		if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
   174  			foundIt = true
   175  		}
   176  	}
   177  	if !foundIt {
   178  		args = append(args, "--debug")
   179  	}
   180  
   181  	if d.storageDriver != "" {
   182  		args = append(args, "--storage-driver", d.storageDriver)
   183  	}
   184  	if d.execDriver != "" {
   185  		args = append(args, "--exec-driver", d.execDriver)
   186  	}
   187  
   188  	args = append(args, arg...)
   189  	d.cmd = exec.Command(dockerBinary, args...)
   190  
   191  	d.logFile, err = os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
   192  	if err != nil {
   193  		d.c.Fatalf("[%s] Could not create %s/docker.log: %v", d.id, d.folder, err)
   194  	}
   195  
   196  	d.cmd.Stdout = d.logFile
   197  	d.cmd.Stderr = d.logFile
   198  
   199  	if err := d.cmd.Start(); err != nil {
   200  		return fmt.Errorf("[%s] could not start daemon container: %v", d.id, err)
   201  	}
   202  
   203  	wait := make(chan error)
   204  
   205  	go func() {
   206  		wait <- d.cmd.Wait()
   207  		d.c.Logf("[%s] exiting daemon", d.id)
   208  		close(wait)
   209  	}()
   210  
   211  	d.wait = wait
   212  
   213  	tick := time.Tick(500 * time.Millisecond)
   214  	// make sure daemon is ready to receive requests
   215  	startTime := time.Now().Unix()
   216  	for {
   217  		d.c.Logf("[%s] waiting for daemon to start", d.id)
   218  		if time.Now().Unix()-startTime > 5 {
   219  			// After 5 seconds, give up
   220  			return fmt.Errorf("[%s] Daemon exited and never started", d.id)
   221  		}
   222  		select {
   223  		case <-time.After(2 * time.Second):
   224  			return fmt.Errorf("[%s] timeout: daemon does not respond", d.id)
   225  		case <-tick:
   226  			clientConfig, err := d.getClientConfig()
   227  			if err != nil {
   228  				return err
   229  			}
   230  
   231  			client := &http.Client{
   232  				Transport: clientConfig.transport,
   233  			}
   234  
   235  			req, err := http.NewRequest("GET", "/_ping", nil)
   236  			if err != nil {
   237  				d.c.Fatalf("[%s] could not create new request: %v", d.id, err)
   238  			}
   239  			req.URL.Host = clientConfig.addr
   240  			req.URL.Scheme = clientConfig.scheme
   241  			resp, err := client.Do(req)
   242  			if err != nil {
   243  				continue
   244  			}
   245  			if resp.StatusCode != http.StatusOK {
   246  				d.c.Logf("[%s] received status != 200 OK: %s", d.id, resp.Status)
   247  			}
   248  			d.c.Logf("[%s] daemon started", d.id)
   249  			d.root, err = d.queryRootDir()
   250  			if err != nil {
   251  				return fmt.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
   252  			}
   253  			return nil
   254  		}
   255  	}
   256  }
   257  
   258  // StartWithBusybox will first start the daemon with Daemon.Start()
   259  // then save the busybox image from the main daemon and load it into this Daemon instance.
   260  func (d *Daemon) StartWithBusybox(arg ...string) error {
   261  	if err := d.Start(arg...); err != nil {
   262  		return err
   263  	}
   264  	bb := filepath.Join(d.folder, "busybox.tar")
   265  	if _, err := os.Stat(bb); err != nil {
   266  		if !os.IsNotExist(err) {
   267  			return fmt.Errorf("unexpected error on busybox.tar stat: %v", err)
   268  		}
   269  		// saving busybox image from main daemon
   270  		if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil {
   271  			return fmt.Errorf("could not save busybox image: %v", err)
   272  		}
   273  	}
   274  	// loading busybox image to this daemon
   275  	if _, err := d.Cmd("load", "--input", bb); err != nil {
   276  		return fmt.Errorf("could not load busybox image: %v", err)
   277  	}
   278  	if err := os.Remove(bb); err != nil {
   279  		d.c.Logf("Could not remove %s: %v", bb, err)
   280  	}
   281  	return nil
   282  }
   283  
   284  // Stop will send a SIGINT every second and wait for the daemon to stop.
   285  // If it timeouts, a SIGKILL is sent.
   286  // Stop will not delete the daemon directory. If a purged daemon is needed,
   287  // instantiate a new one with NewDaemon.
   288  func (d *Daemon) Stop() error {
   289  	if d.cmd == nil || d.wait == nil {
   290  		return errors.New("daemon not started")
   291  	}
   292  
   293  	defer func() {
   294  		d.logFile.Close()
   295  		d.cmd = nil
   296  	}()
   297  
   298  	i := 1
   299  	tick := time.Tick(time.Second)
   300  
   301  	if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
   302  		return fmt.Errorf("could not send signal: %v", err)
   303  	}
   304  out1:
   305  	for {
   306  		select {
   307  		case err := <-d.wait:
   308  			return err
   309  		case <-time.After(15 * time.Second):
   310  			// time for stopping jobs and run onShutdown hooks
   311  			d.c.Log("timeout")
   312  			break out1
   313  		}
   314  	}
   315  
   316  out2:
   317  	for {
   318  		select {
   319  		case err := <-d.wait:
   320  			return err
   321  		case <-tick:
   322  			i++
   323  			if i > 4 {
   324  				d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
   325  				break out2
   326  			}
   327  			d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
   328  			if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
   329  				return fmt.Errorf("could not send signal: %v", err)
   330  			}
   331  		}
   332  	}
   333  
   334  	if err := d.cmd.Process.Kill(); err != nil {
   335  		d.c.Logf("Could not kill daemon: %v", err)
   336  		return err
   337  	}
   338  
   339  	return nil
   340  }
   341  
   342  // Restart will restart the daemon by first stopping it and then starting it.
   343  func (d *Daemon) Restart(arg ...string) error {
   344  	d.Stop()
   345  	return d.Start(arg...)
   346  }
   347  
   348  func (d *Daemon) queryRootDir() (string, error) {
   349  	// update daemon root by asking /info endpoint (to support user
   350  	// namespaced daemon with root remapped uid.gid directory)
   351  	clientConfig, err := d.getClientConfig()
   352  	if err != nil {
   353  		return "", err
   354  	}
   355  
   356  	client := &http.Client{
   357  		Transport: clientConfig.transport,
   358  	}
   359  
   360  	req, err := http.NewRequest("GET", "/info", nil)
   361  	if err != nil {
   362  		return "", err
   363  	}
   364  	req.Header.Set("Content-Type", "application/json")
   365  	req.URL.Host = clientConfig.addr
   366  	req.URL.Scheme = clientConfig.scheme
   367  
   368  	resp, err := client.Do(req)
   369  	if err != nil {
   370  		return "", err
   371  	}
   372  	body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
   373  		return resp.Body.Close()
   374  	})
   375  
   376  	type Info struct {
   377  		DockerRootDir string
   378  	}
   379  	var b []byte
   380  	var i Info
   381  	b, err = readBody(body)
   382  	if err == nil && resp.StatusCode == 200 {
   383  		// read the docker root dir
   384  		if err = json.Unmarshal(b, &i); err == nil {
   385  			return i.DockerRootDir, nil
   386  		}
   387  	}
   388  	return "", err
   389  }
   390  
   391  func (d *Daemon) sock() string {
   392  	return fmt.Sprintf("unix://%s/docker.sock", d.folder)
   393  }
   394  
   395  // Cmd will execute a docker CLI command against this Daemon.
   396  // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
   397  func (d *Daemon) Cmd(name string, arg ...string) (string, error) {
   398  	args := []string{"--host", d.sock(), name}
   399  	args = append(args, arg...)
   400  	c := exec.Command(dockerBinary, args...)
   401  	b, err := c.CombinedOutput()
   402  	return string(b), err
   403  }
   404  
   405  // CmdWithArgs will execute a docker CLI command against a daemon with the
   406  // given additional arguments
   407  func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) {
   408  	args := append(daemonArgs, name)
   409  	args = append(args, arg...)
   410  	c := exec.Command(dockerBinary, args...)
   411  	b, err := c.CombinedOutput()
   412  	return string(b), err
   413  }
   414  
   415  // LogfileName returns the path the the daemon's log file
   416  func (d *Daemon) LogfileName() string {
   417  	return d.logFile.Name()
   418  }
   419  
   420  func daemonHost() string {
   421  	daemonURLStr := "unix://" + opts.DefaultUnixSocket
   422  	if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
   423  		daemonURLStr = daemonHostVar
   424  	}
   425  	return daemonURLStr
   426  }
   427  
   428  func sockConn(timeout time.Duration) (net.Conn, error) {
   429  	daemon := daemonHost()
   430  	daemonURL, err := url.Parse(daemon)
   431  	if err != nil {
   432  		return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
   433  	}
   434  
   435  	var c net.Conn
   436  	switch daemonURL.Scheme {
   437  	case "unix":
   438  		return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
   439  	case "tcp":
   440  		return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
   441  	default:
   442  		return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
   443  	}
   444  }
   445  
   446  func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
   447  	jsonData := bytes.NewBuffer(nil)
   448  	if err := json.NewEncoder(jsonData).Encode(data); err != nil {
   449  		return -1, nil, err
   450  	}
   451  
   452  	res, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
   453  	if err != nil {
   454  		return -1, nil, err
   455  	}
   456  	b, err := readBody(body)
   457  	return res.StatusCode, b, err
   458  }
   459  
   460  func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
   461  	req, client, err := newRequestClient(method, endpoint, data, ct)
   462  	if err != nil {
   463  		return nil, nil, err
   464  	}
   465  
   466  	resp, err := client.Do(req)
   467  	if err != nil {
   468  		client.Close()
   469  		return nil, nil, err
   470  	}
   471  	body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
   472  		defer resp.Body.Close()
   473  		return client.Close()
   474  	})
   475  
   476  	return resp, body, nil
   477  }
   478  
   479  func sockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {
   480  	req, client, err := newRequestClient(method, endpoint, data, ct)
   481  	if err != nil {
   482  		return nil, nil, err
   483  	}
   484  
   485  	client.Do(req)
   486  	conn, br := client.Hijack()
   487  	return conn, br, nil
   488  }
   489  
   490  func newRequestClient(method, endpoint string, data io.Reader, ct string) (*http.Request, *httputil.ClientConn, error) {
   491  	c, err := sockConn(time.Duration(10 * time.Second))
   492  	if err != nil {
   493  		return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
   494  	}
   495  
   496  	client := httputil.NewClientConn(c, nil)
   497  
   498  	req, err := http.NewRequest(method, endpoint, data)
   499  	if err != nil {
   500  		client.Close()
   501  		return nil, nil, fmt.Errorf("could not create new request: %v", err)
   502  	}
   503  
   504  	if ct != "" {
   505  		req.Header.Set("Content-Type", ct)
   506  	}
   507  	return req, client, nil
   508  }
   509  
   510  func readBody(b io.ReadCloser) ([]byte, error) {
   511  	defer b.Close()
   512  	return ioutil.ReadAll(b)
   513  }
   514  
   515  func deleteContainer(container string) error {
   516  	container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
   517  	rmArgs := strings.Split(fmt.Sprintf("rm -fv %v", container), " ")
   518  	exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
   519  	// set error manually if not set
   520  	if exitCode != 0 && err == nil {
   521  		err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
   522  	}
   523  
   524  	return err
   525  }
   526  
   527  func getAllContainers() (string, error) {
   528  	getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
   529  	out, exitCode, err := runCommandWithOutput(getContainersCmd)
   530  	if exitCode != 0 && err == nil {
   531  		err = fmt.Errorf("failed to get a list of containers: %v\n", out)
   532  	}
   533  
   534  	return out, err
   535  }
   536  
   537  func deleteAllContainers() error {
   538  	containers, err := getAllContainers()
   539  	if err != nil {
   540  		fmt.Println(containers)
   541  		return err
   542  	}
   543  
   544  	if err = deleteContainer(containers); err != nil {
   545  		return err
   546  	}
   547  	return nil
   548  }
   549  
   550  func deleteAllNetworks() error {
   551  	networks, err := getAllNetworks()
   552  	if err != nil {
   553  		return err
   554  	}
   555  	var errors []string
   556  	for _, n := range networks {
   557  		if n.Name != "bridge" {
   558  			status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
   559  			if err != nil {
   560  				errors = append(errors, err.Error())
   561  				continue
   562  			}
   563  			if status != http.StatusNoContent {
   564  				errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
   565  			}
   566  		}
   567  	}
   568  	if len(errors) > 0 {
   569  		return fmt.Errorf(strings.Join(errors, "\n"))
   570  	}
   571  	return nil
   572  }
   573  
   574  func getAllNetworks() ([]types.NetworkResource, error) {
   575  	var networks []types.NetworkResource
   576  	_, b, err := sockRequest("GET", "/networks", nil)
   577  	if err != nil {
   578  		return nil, err
   579  	}
   580  	if err := json.Unmarshal(b, &networks); err != nil {
   581  		return nil, err
   582  	}
   583  	return networks, nil
   584  }
   585  
   586  func deleteAllVolumes() error {
   587  	volumes, err := getAllVolumes()
   588  	if err != nil {
   589  		return err
   590  	}
   591  	var errors []string
   592  	for _, v := range volumes {
   593  		status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
   594  		if err != nil {
   595  			errors = append(errors, err.Error())
   596  			continue
   597  		}
   598  		if status != http.StatusNoContent {
   599  			errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
   600  		}
   601  	}
   602  	if len(errors) > 0 {
   603  		return fmt.Errorf(strings.Join(errors, "\n"))
   604  	}
   605  	return nil
   606  }
   607  
   608  func getAllVolumes() ([]*types.Volume, error) {
   609  	var volumes types.VolumesListResponse
   610  	_, b, err := sockRequest("GET", "/volumes", nil)
   611  	if err != nil {
   612  		return nil, err
   613  	}
   614  	if err := json.Unmarshal(b, &volumes); err != nil {
   615  		return nil, err
   616  	}
   617  	return volumes.Volumes, nil
   618  }
   619  
   620  var protectedImages = map[string]struct{}{}
   621  
   622  func init() {
   623  	out, err := exec.Command(dockerBinary, "images").CombinedOutput()
   624  	if err != nil {
   625  		panic(err)
   626  	}
   627  	lines := strings.Split(string(out), "\n")[1:]
   628  	for _, l := range lines {
   629  		if l == "" {
   630  			continue
   631  		}
   632  		fields := strings.Fields(l)
   633  		imgTag := fields[0] + ":" + fields[1]
   634  		// just for case if we have dangling images in tested daemon
   635  		if imgTag != "<none>:<none>" {
   636  			protectedImages[imgTag] = struct{}{}
   637  		}
   638  	}
   639  
   640  	// Obtain the daemon platform so that it can be used by tests to make
   641  	// intelligent decisions about how to configure themselves, and validate
   642  	// that the target platform is valid.
   643  	res, _, err := sockRequestRaw("GET", "/version", nil, "application/json")
   644  	if err != nil || res == nil || (res != nil && res.StatusCode != http.StatusOK) {
   645  		panic(fmt.Errorf("Init failed to get version: %v. Res=%v", err.Error(), res))
   646  	}
   647  	svrHeader, _ := httputils.ParseServerHeader(res.Header.Get("Server"))
   648  	daemonPlatform = svrHeader.OS
   649  	if daemonPlatform != "linux" && daemonPlatform != "windows" {
   650  		panic("Cannot run tests against platform: " + daemonPlatform)
   651  	}
   652  }
   653  
   654  func deleteAllImages() error {
   655  	out, err := exec.Command(dockerBinary, "images").CombinedOutput()
   656  	if err != nil {
   657  		return err
   658  	}
   659  	lines := strings.Split(string(out), "\n")[1:]
   660  	var imgs []string
   661  	for _, l := range lines {
   662  		if l == "" {
   663  			continue
   664  		}
   665  		fields := strings.Fields(l)
   666  		imgTag := fields[0] + ":" + fields[1]
   667  		if _, ok := protectedImages[imgTag]; !ok {
   668  			if fields[0] == "<none>" {
   669  				imgs = append(imgs, fields[2])
   670  				continue
   671  			}
   672  			imgs = append(imgs, imgTag)
   673  		}
   674  	}
   675  	if len(imgs) == 0 {
   676  		return nil
   677  	}
   678  	args := append([]string{"rmi", "-f"}, imgs...)
   679  	if err := exec.Command(dockerBinary, args...).Run(); err != nil {
   680  		return err
   681  	}
   682  	return nil
   683  }
   684  
   685  func getPausedContainers() (string, error) {
   686  	getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
   687  	out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
   688  	if exitCode != 0 && err == nil {
   689  		err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
   690  	}
   691  
   692  	return out, err
   693  }
   694  
   695  func getSliceOfPausedContainers() ([]string, error) {
   696  	out, err := getPausedContainers()
   697  	if err == nil {
   698  		if len(out) == 0 {
   699  			return nil, err
   700  		}
   701  		slice := strings.Split(strings.TrimSpace(out), "\n")
   702  		return slice, err
   703  	}
   704  	return []string{out}, err
   705  }
   706  
   707  func unpauseContainer(container string) error {
   708  	unpauseCmd := exec.Command(dockerBinary, "unpause", container)
   709  	exitCode, err := runCommand(unpauseCmd)
   710  	if exitCode != 0 && err == nil {
   711  		err = fmt.Errorf("failed to unpause container")
   712  	}
   713  
   714  	return nil
   715  }
   716  
   717  func unpauseAllContainers() error {
   718  	containers, err := getPausedContainers()
   719  	if err != nil {
   720  		fmt.Println(containers)
   721  		return err
   722  	}
   723  
   724  	containers = strings.Replace(containers, "\n", " ", -1)
   725  	containers = strings.Trim(containers, " ")
   726  	containerList := strings.Split(containers, " ")
   727  
   728  	for _, value := range containerList {
   729  		if err = unpauseContainer(value); err != nil {
   730  			return err
   731  		}
   732  	}
   733  
   734  	return nil
   735  }
   736  
   737  func deleteImages(images ...string) error {
   738  	args := []string{"rmi", "-f"}
   739  	args = append(args, images...)
   740  	rmiCmd := exec.Command(dockerBinary, args...)
   741  	exitCode, err := runCommand(rmiCmd)
   742  	// set error manually if not set
   743  	if exitCode != 0 && err == nil {
   744  		err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
   745  	}
   746  	return err
   747  }
   748  
   749  func imageExists(image string) error {
   750  	inspectCmd := exec.Command(dockerBinary, "inspect", image)
   751  	exitCode, err := runCommand(inspectCmd)
   752  	if exitCode != 0 && err == nil {
   753  		err = fmt.Errorf("couldn't find image %q", image)
   754  	}
   755  	return err
   756  }
   757  
   758  func pullImageIfNotExist(image string) error {
   759  	if err := imageExists(image); err != nil {
   760  		pullCmd := exec.Command(dockerBinary, "pull", image)
   761  		_, exitCode, err := runCommandWithOutput(pullCmd)
   762  
   763  		if err != nil || exitCode != 0 {
   764  			return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
   765  		}
   766  	}
   767  	return nil
   768  }
   769  
   770  func dockerCmdWithError(args ...string) (string, int, error) {
   771  	return integration.DockerCmdWithError(dockerBinary, args...)
   772  }
   773  
   774  func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
   775  	return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
   776  }
   777  
   778  func dockerCmd(c *check.C, args ...string) (string, int) {
   779  	return integration.DockerCmd(dockerBinary, c, args...)
   780  }
   781  
   782  // execute a docker command with a timeout
   783  func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
   784  	return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
   785  }
   786  
   787  // execute a docker command in a directory
   788  func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
   789  	return integration.DockerCmdInDir(dockerBinary, path, args...)
   790  }
   791  
   792  // execute a docker command in a directory with a timeout
   793  func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
   794  	return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
   795  }
   796  
   797  func findContainerIP(c *check.C, id string, vargs ...string) string {
   798  	args := append(vargs, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
   799  	cmd := exec.Command(dockerBinary, args...)
   800  	out, _, err := runCommandWithOutput(cmd)
   801  	if err != nil {
   802  		c.Fatal(err, out)
   803  	}
   804  
   805  	return strings.Trim(out, " \r\n'")
   806  }
   807  
   808  func (d *Daemon) findContainerIP(id string) string {
   809  	return findContainerIP(d.c, id, "--host", d.sock())
   810  }
   811  
   812  func getContainerCount() (int, error) {
   813  	const containers = "Containers:"
   814  
   815  	cmd := exec.Command(dockerBinary, "info")
   816  	out, _, err := runCommandWithOutput(cmd)
   817  	if err != nil {
   818  		return 0, err
   819  	}
   820  
   821  	lines := strings.Split(out, "\n")
   822  	for _, line := range lines {
   823  		if strings.Contains(line, containers) {
   824  			output := strings.TrimSpace(line)
   825  			output = strings.TrimLeft(output, containers)
   826  			output = strings.Trim(output, " ")
   827  			containerCount, err := strconv.Atoi(output)
   828  			if err != nil {
   829  				return 0, err
   830  			}
   831  			return containerCount, nil
   832  		}
   833  	}
   834  	return 0, fmt.Errorf("couldn't find the Container count in the output")
   835  }
   836  
   837  // FakeContext creates directories that can be used as a build context
   838  type FakeContext struct {
   839  	Dir string
   840  }
   841  
   842  // Add a file at a path, creating directories where necessary
   843  func (f *FakeContext) Add(file, content string) error {
   844  	return f.addFile(file, []byte(content))
   845  }
   846  
   847  func (f *FakeContext) addFile(file string, content []byte) error {
   848  	filepath := path.Join(f.Dir, file)
   849  	dirpath := path.Dir(filepath)
   850  	if dirpath != "." {
   851  		if err := os.MkdirAll(dirpath, 0755); err != nil {
   852  			return err
   853  		}
   854  	}
   855  	return ioutil.WriteFile(filepath, content, 0644)
   856  
   857  }
   858  
   859  // Delete a file at a path
   860  func (f *FakeContext) Delete(file string) error {
   861  	filepath := path.Join(f.Dir, file)
   862  	return os.RemoveAll(filepath)
   863  }
   864  
   865  // Close deletes the context
   866  func (f *FakeContext) Close() error {
   867  	return os.RemoveAll(f.Dir)
   868  }
   869  
   870  func fakeContextFromNewTempDir() (*FakeContext, error) {
   871  	tmp, err := ioutil.TempDir("", "fake-context")
   872  	if err != nil {
   873  		return nil, err
   874  	}
   875  	if err := os.Chmod(tmp, 0755); err != nil {
   876  		return nil, err
   877  	}
   878  	return fakeContextFromDir(tmp), nil
   879  }
   880  
   881  func fakeContextFromDir(dir string) *FakeContext {
   882  	return &FakeContext{dir}
   883  }
   884  
   885  func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
   886  	ctx, err := fakeContextFromNewTempDir()
   887  	if err != nil {
   888  		return nil, err
   889  	}
   890  	for file, content := range files {
   891  		if err := ctx.Add(file, content); err != nil {
   892  			ctx.Close()
   893  			return nil, err
   894  		}
   895  	}
   896  	return ctx, nil
   897  }
   898  
   899  func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
   900  	if err := ctx.Add("Dockerfile", dockerfile); err != nil {
   901  		ctx.Close()
   902  		return err
   903  	}
   904  	return nil
   905  }
   906  
   907  func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
   908  	ctx, err := fakeContextWithFiles(files)
   909  	if err != nil {
   910  		return nil, err
   911  	}
   912  	if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
   913  		return nil, err
   914  	}
   915  	return ctx, nil
   916  }
   917  
   918  // FakeStorage is a static file server. It might be running locally or remotely
   919  // on test host.
   920  type FakeStorage interface {
   921  	Close() error
   922  	URL() string
   923  	CtxDir() string
   924  }
   925  
   926  func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
   927  	ctx, err := fakeContextFromNewTempDir()
   928  	if err != nil {
   929  		return nil, err
   930  	}
   931  	for name, content := range archives {
   932  		if err := ctx.addFile(name, content.Bytes()); err != nil {
   933  			return nil, err
   934  		}
   935  	}
   936  	return fakeStorageWithContext(ctx)
   937  }
   938  
   939  // fakeStorage returns either a local or remote (at daemon machine) file server
   940  func fakeStorage(files map[string]string) (FakeStorage, error) {
   941  	ctx, err := fakeContextWithFiles(files)
   942  	if err != nil {
   943  		return nil, err
   944  	}
   945  	return fakeStorageWithContext(ctx)
   946  }
   947  
   948  // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
   949  func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
   950  	if isLocalDaemon {
   951  		return newLocalFakeStorage(ctx)
   952  	}
   953  	return newRemoteFileServer(ctx)
   954  }
   955  
   956  // localFileStorage is a file storage on the running machine
   957  type localFileStorage struct {
   958  	*FakeContext
   959  	*httptest.Server
   960  }
   961  
   962  func (s *localFileStorage) URL() string {
   963  	return s.Server.URL
   964  }
   965  
   966  func (s *localFileStorage) CtxDir() string {
   967  	return s.FakeContext.Dir
   968  }
   969  
   970  func (s *localFileStorage) Close() error {
   971  	defer s.Server.Close()
   972  	return s.FakeContext.Close()
   973  }
   974  
   975  func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
   976  	handler := http.FileServer(http.Dir(ctx.Dir))
   977  	server := httptest.NewServer(handler)
   978  	return &localFileStorage{
   979  		FakeContext: ctx,
   980  		Server:      server,
   981  	}, nil
   982  }
   983  
   984  // remoteFileServer is a containerized static file server started on the remote
   985  // testing machine to be used in URL-accepting docker build functionality.
   986  type remoteFileServer struct {
   987  	host      string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
   988  	container string
   989  	image     string
   990  	ctx       *FakeContext
   991  }
   992  
   993  func (f *remoteFileServer) URL() string {
   994  	u := url.URL{
   995  		Scheme: "http",
   996  		Host:   f.host}
   997  	return u.String()
   998  }
   999  
  1000  func (f *remoteFileServer) CtxDir() string {
  1001  	return f.ctx.Dir
  1002  }
  1003  
  1004  func (f *remoteFileServer) Close() error {
  1005  	defer func() {
  1006  		if f.ctx != nil {
  1007  			f.ctx.Close()
  1008  		}
  1009  		if f.image != "" {
  1010  			deleteImages(f.image)
  1011  		}
  1012  	}()
  1013  	if f.container == "" {
  1014  		return nil
  1015  	}
  1016  	return deleteContainer(f.container)
  1017  }
  1018  
  1019  func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  1020  	var (
  1021  		image     = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  1022  		container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  1023  	)
  1024  
  1025  	// Build the image
  1026  	if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  1027  COPY . /static`); err != nil {
  1028  		return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  1029  	}
  1030  	if _, err := buildImageFromContext(image, ctx, false); err != nil {
  1031  		return nil, fmt.Errorf("failed building file storage container image: %v", err)
  1032  	}
  1033  
  1034  	// Start the container
  1035  	runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  1036  	if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1037  		return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  1038  	}
  1039  
  1040  	// Find out the system assigned port
  1041  	out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  1042  	if err != nil {
  1043  		return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  1044  	}
  1045  
  1046  	fileserverHostPort := strings.Trim(out, "\n")
  1047  	_, port, err := net.SplitHostPort(fileserverHostPort)
  1048  	if err != nil {
  1049  		return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  1050  	}
  1051  
  1052  	dockerHostURL, err := url.Parse(daemonHost())
  1053  	if err != nil {
  1054  		return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  1055  	}
  1056  
  1057  	host, _, err := net.SplitHostPort(dockerHostURL.Host)
  1058  	if err != nil {
  1059  		return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  1060  	}
  1061  
  1062  	return &remoteFileServer{
  1063  		container: container,
  1064  		image:     image,
  1065  		host:      fmt.Sprintf("%s:%s", host, port),
  1066  		ctx:       ctx}, nil
  1067  }
  1068  
  1069  func inspectFieldAndMarshall(name, field string, output interface{}) error {
  1070  	str, err := inspectFieldJSON(name, field)
  1071  	if err != nil {
  1072  		return err
  1073  	}
  1074  
  1075  	return json.Unmarshal([]byte(str), output)
  1076  }
  1077  
  1078  func inspectFilter(name, filter string) (string, error) {
  1079  	format := fmt.Sprintf("{{%s}}", filter)
  1080  	inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  1081  	out, exitCode, err := runCommandWithOutput(inspectCmd)
  1082  	if err != nil || exitCode != 0 {
  1083  		return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  1084  	}
  1085  	return strings.TrimSpace(out), nil
  1086  }
  1087  
  1088  func inspectField(name, field string) (string, error) {
  1089  	return inspectFilter(name, fmt.Sprintf(".%s", field))
  1090  }
  1091  
  1092  func inspectFieldJSON(name, field string) (string, error) {
  1093  	return inspectFilter(name, fmt.Sprintf("json .%s", field))
  1094  }
  1095  
  1096  func inspectFieldMap(name, path, field string) (string, error) {
  1097  	return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  1098  }
  1099  
  1100  func inspectMountSourceField(name, destination string) (string, error) {
  1101  	m, err := inspectMountPoint(name, destination)
  1102  	if err != nil {
  1103  		return "", err
  1104  	}
  1105  	return m.Source, nil
  1106  }
  1107  
  1108  func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  1109  	out, err := inspectFieldJSON(name, "Mounts")
  1110  	if err != nil {
  1111  		return types.MountPoint{}, err
  1112  	}
  1113  
  1114  	return inspectMountPointJSON(out, destination)
  1115  }
  1116  
  1117  var errMountNotFound = errors.New("mount point not found")
  1118  
  1119  func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  1120  	var mp []types.MountPoint
  1121  	if err := unmarshalJSON([]byte(j), &mp); err != nil {
  1122  		return types.MountPoint{}, err
  1123  	}
  1124  
  1125  	var m *types.MountPoint
  1126  	for _, c := range mp {
  1127  		if c.Destination == destination {
  1128  			m = &c
  1129  			break
  1130  		}
  1131  	}
  1132  
  1133  	if m == nil {
  1134  		return types.MountPoint{}, errMountNotFound
  1135  	}
  1136  
  1137  	return *m, nil
  1138  }
  1139  
  1140  func getIDByName(name string) (string, error) {
  1141  	return inspectField(name, "Id")
  1142  }
  1143  
  1144  // getContainerState returns the exit code of the container
  1145  // and true if it's running
  1146  // the exit code should be ignored if it's running
  1147  func getContainerState(c *check.C, id string) (int, bool, error) {
  1148  	var (
  1149  		exitStatus int
  1150  		running    bool
  1151  	)
  1152  	out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  1153  	if exitCode != 0 {
  1154  		return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  1155  	}
  1156  
  1157  	out = strings.Trim(out, "\n")
  1158  	splitOutput := strings.Split(out, " ")
  1159  	if len(splitOutput) != 2 {
  1160  		return 0, false, fmt.Errorf("failed to get container state: output is broken")
  1161  	}
  1162  	if splitOutput[0] == "true" {
  1163  		running = true
  1164  	}
  1165  	if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  1166  		exitStatus = n
  1167  	} else {
  1168  		return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  1169  	}
  1170  
  1171  	return exitStatus, running, nil
  1172  }
  1173  
  1174  func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  1175  	args := []string{"-D", "build", "-t", name}
  1176  	if !useCache {
  1177  		args = append(args, "--no-cache")
  1178  	}
  1179  	args = append(args, buildFlags...)
  1180  	args = append(args, "-")
  1181  	buildCmd := exec.Command(dockerBinary, args...)
  1182  	buildCmd.Stdin = strings.NewReader(dockerfile)
  1183  	return buildCmd
  1184  
  1185  }
  1186  
  1187  func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  1188  	buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1189  	out, exitCode, err := runCommandWithOutput(buildCmd)
  1190  	if err != nil || exitCode != 0 {
  1191  		return "", out, fmt.Errorf("failed to build the image: %s", out)
  1192  	}
  1193  	id, err := getIDByName(name)
  1194  	if err != nil {
  1195  		return "", out, err
  1196  	}
  1197  	return id, out, nil
  1198  }
  1199  
  1200  func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  1201  	buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1202  	stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1203  	if err != nil || exitCode != 0 {
  1204  		return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1205  	}
  1206  	id, err := getIDByName(name)
  1207  	if err != nil {
  1208  		return "", stdout, stderr, err
  1209  	}
  1210  	return id, stdout, stderr, nil
  1211  }
  1212  
  1213  func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1214  	id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1215  	return id, err
  1216  }
  1217  
  1218  func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1219  	args := []string{"build", "-t", name}
  1220  	if !useCache {
  1221  		args = append(args, "--no-cache")
  1222  	}
  1223  	args = append(args, buildFlags...)
  1224  	args = append(args, ".")
  1225  	buildCmd := exec.Command(dockerBinary, args...)
  1226  	buildCmd.Dir = ctx.Dir
  1227  	out, exitCode, err := runCommandWithOutput(buildCmd)
  1228  	if err != nil || exitCode != 0 {
  1229  		return "", fmt.Errorf("failed to build the image: %s", out)
  1230  	}
  1231  	return getIDByName(name)
  1232  }
  1233  
  1234  func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1235  	args := []string{"build", "-t", name}
  1236  	if !useCache {
  1237  		args = append(args, "--no-cache")
  1238  	}
  1239  	args = append(args, buildFlags...)
  1240  	args = append(args, path)
  1241  	buildCmd := exec.Command(dockerBinary, args...)
  1242  	out, exitCode, err := runCommandWithOutput(buildCmd)
  1243  	if err != nil || exitCode != 0 {
  1244  		return "", fmt.Errorf("failed to build the image: %s", out)
  1245  	}
  1246  	return getIDByName(name)
  1247  }
  1248  
  1249  type gitServer interface {
  1250  	URL() string
  1251  	Close() error
  1252  }
  1253  
  1254  type localGitServer struct {
  1255  	*httptest.Server
  1256  }
  1257  
  1258  func (r *localGitServer) Close() error {
  1259  	r.Server.Close()
  1260  	return nil
  1261  }
  1262  
  1263  func (r *localGitServer) URL() string {
  1264  	return r.Server.URL
  1265  }
  1266  
  1267  type fakeGit struct {
  1268  	root    string
  1269  	server  gitServer
  1270  	RepoURL string
  1271  }
  1272  
  1273  func (g *fakeGit) Close() {
  1274  	g.server.Close()
  1275  	os.RemoveAll(g.root)
  1276  }
  1277  
  1278  func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1279  	ctx, err := fakeContextWithFiles(files)
  1280  	if err != nil {
  1281  		return nil, err
  1282  	}
  1283  	defer ctx.Close()
  1284  	curdir, err := os.Getwd()
  1285  	if err != nil {
  1286  		return nil, err
  1287  	}
  1288  	defer os.Chdir(curdir)
  1289  
  1290  	if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1291  		return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1292  	}
  1293  	err = os.Chdir(ctx.Dir)
  1294  	if err != nil {
  1295  		return nil, err
  1296  	}
  1297  	if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1298  		return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1299  	}
  1300  	if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1301  		return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1302  	}
  1303  	if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1304  		return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1305  	}
  1306  	if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1307  		return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1308  	}
  1309  
  1310  	root, err := ioutil.TempDir("", "docker-test-git-repo")
  1311  	if err != nil {
  1312  		return nil, err
  1313  	}
  1314  	repoPath := filepath.Join(root, name+".git")
  1315  	if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1316  		os.RemoveAll(root)
  1317  		return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1318  	}
  1319  	err = os.Chdir(repoPath)
  1320  	if err != nil {
  1321  		os.RemoveAll(root)
  1322  		return nil, err
  1323  	}
  1324  	if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1325  		os.RemoveAll(root)
  1326  		return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1327  	}
  1328  	err = os.Chdir(curdir)
  1329  	if err != nil {
  1330  		os.RemoveAll(root)
  1331  		return nil, err
  1332  	}
  1333  
  1334  	var server gitServer
  1335  	if !enforceLocalServer {
  1336  		// use fakeStorage server, which might be local or remote (at test daemon)
  1337  		server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1338  		if err != nil {
  1339  			return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1340  		}
  1341  	} else {
  1342  		// always start a local http server on CLI test machin
  1343  		httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1344  		server = &localGitServer{httpServer}
  1345  	}
  1346  	return &fakeGit{
  1347  		root:    root,
  1348  		server:  server,
  1349  		RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1350  	}, nil
  1351  }
  1352  
  1353  // Write `content` to the file at path `dst`, creating it if necessary,
  1354  // as well as any missing directories.
  1355  // The file is truncated if it already exists.
  1356  // Call c.Fatal() at the first error.
  1357  func writeFile(dst, content string, c *check.C) {
  1358  	// Create subdirectories if necessary
  1359  	if err := os.MkdirAll(path.Dir(dst), 0700); err != nil {
  1360  		c.Fatal(err)
  1361  	}
  1362  	f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1363  	if err != nil {
  1364  		c.Fatal(err)
  1365  	}
  1366  	defer f.Close()
  1367  	// Write content (truncate if it exists)
  1368  	if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  1369  		c.Fatal(err)
  1370  	}
  1371  }
  1372  
  1373  // Return the contents of file at path `src`.
  1374  // Call c.Fatal() at the first error (including if the file doesn't exist)
  1375  func readFile(src string, c *check.C) (content string) {
  1376  	data, err := ioutil.ReadFile(src)
  1377  	if err != nil {
  1378  		c.Fatal(err)
  1379  	}
  1380  
  1381  	return string(data)
  1382  }
  1383  
  1384  func containerStorageFile(containerID, basename string) string {
  1385  	return filepath.Join(containerStoragePath, containerID, basename)
  1386  }
  1387  
  1388  // docker commands that use this function must be run with the '-d' switch.
  1389  func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1390  	out, _, err := runCommandWithOutput(cmd)
  1391  	if err != nil {
  1392  		return nil, fmt.Errorf("%v: %q", err, out)
  1393  	}
  1394  
  1395  	contID := strings.TrimSpace(out)
  1396  
  1397  	if err := waitRun(contID); err != nil {
  1398  		return nil, fmt.Errorf("%v: %q", contID, err)
  1399  	}
  1400  
  1401  	return readContainerFile(contID, filename)
  1402  }
  1403  
  1404  func readContainerFile(containerID, filename string) ([]byte, error) {
  1405  	f, err := os.Open(containerStorageFile(containerID, filename))
  1406  	if err != nil {
  1407  		return nil, err
  1408  	}
  1409  	defer f.Close()
  1410  
  1411  	content, err := ioutil.ReadAll(f)
  1412  	if err != nil {
  1413  		return nil, err
  1414  	}
  1415  
  1416  	return content, nil
  1417  }
  1418  
  1419  func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1420  	out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1421  	return []byte(out), err
  1422  }
  1423  
  1424  // daemonTime provides the current time on the daemon host
  1425  func daemonTime(c *check.C) time.Time {
  1426  	if isLocalDaemon {
  1427  		return time.Now()
  1428  	}
  1429  
  1430  	status, body, err := sockRequest("GET", "/info", nil)
  1431  	c.Assert(status, check.Equals, http.StatusOK)
  1432  	c.Assert(err, check.IsNil)
  1433  
  1434  	type infoJSON struct {
  1435  		SystemTime string
  1436  	}
  1437  	var info infoJSON
  1438  	if err = json.Unmarshal(body, &info); err != nil {
  1439  		c.Fatalf("unable to unmarshal /info response: %v", err)
  1440  	}
  1441  
  1442  	dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1443  	if err != nil {
  1444  		c.Fatal(err)
  1445  	}
  1446  	return dt
  1447  }
  1448  
  1449  func setupRegistry(c *check.C) *testRegistryV2 {
  1450  	testRequires(c, RegistryHosting)
  1451  	reg, err := newTestRegistryV2(c)
  1452  	if err != nil {
  1453  		c.Fatal(err)
  1454  	}
  1455  
  1456  	// Wait for registry to be ready to serve requests.
  1457  	for i := 0; i != 5; i++ {
  1458  		if err = reg.Ping(); err == nil {
  1459  			break
  1460  		}
  1461  		time.Sleep(100 * time.Millisecond)
  1462  	}
  1463  
  1464  	if err != nil {
  1465  		c.Fatal("Timeout waiting for test registry to become available")
  1466  	}
  1467  	return reg
  1468  }
  1469  
  1470  func setupNotary(c *check.C) *testNotary {
  1471  	testRequires(c, NotaryHosting)
  1472  	ts, err := newTestNotary(c)
  1473  	if err != nil {
  1474  		c.Fatal(err)
  1475  	}
  1476  
  1477  	return ts
  1478  }
  1479  
  1480  // appendBaseEnv appends the minimum set of environment variables to exec the
  1481  // docker cli binary for testing with correct configuration to the given env
  1482  // list.
  1483  func appendBaseEnv(env []string) []string {
  1484  	preserveList := []string{
  1485  		// preserve remote test host
  1486  		"DOCKER_HOST",
  1487  
  1488  		// windows: requires preserving SystemRoot, otherwise dial tcp fails
  1489  		// with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1490  		"SystemRoot",
  1491  	}
  1492  
  1493  	for _, key := range preserveList {
  1494  		if val := os.Getenv(key); val != "" {
  1495  			env = append(env, fmt.Sprintf("%s=%s", key, val))
  1496  		}
  1497  	}
  1498  	return env
  1499  }
  1500  
  1501  func createTmpFile(c *check.C, content string) string {
  1502  	f, err := ioutil.TempFile("", "testfile")
  1503  	c.Assert(err, check.IsNil)
  1504  
  1505  	filename := f.Name()
  1506  
  1507  	err = ioutil.WriteFile(filename, []byte(content), 0644)
  1508  	c.Assert(err, check.IsNil)
  1509  
  1510  	return filename
  1511  }
  1512  
  1513  func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1514  	args := []string{"--host", socket}
  1515  	buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1516  	out, exitCode, err := runCommandWithOutput(buildCmd)
  1517  	if err != nil || exitCode != 0 {
  1518  		return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1519  	}
  1520  	return out, nil
  1521  }
  1522  
  1523  func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1524  	args = append(args, []string{"-D", "build", "-t", name}...)
  1525  	if !useCache {
  1526  		args = append(args, "--no-cache")
  1527  	}
  1528  	args = append(args, "-")
  1529  	buildCmd := exec.Command(dockerBinary, args...)
  1530  	buildCmd.Stdin = strings.NewReader(dockerfile)
  1531  	return buildCmd
  1532  
  1533  }
  1534  
  1535  func waitForContainer(contID string, args ...string) error {
  1536  	args = append([]string{"run", "--name", contID}, args...)
  1537  	cmd := exec.Command(dockerBinary, args...)
  1538  	if _, err := runCommand(cmd); err != nil {
  1539  		return err
  1540  	}
  1541  
  1542  	if err := waitRun(contID); err != nil {
  1543  		return err
  1544  	}
  1545  
  1546  	return nil
  1547  }
  1548  
  1549  // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1550  func waitRun(contID string) error {
  1551  	return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1552  }
  1553  
  1554  // waitExited will wait for the specified container to state exit, subject
  1555  // to a maximum time limit in seconds supplied by the caller
  1556  func waitExited(contID string, duration time.Duration) error {
  1557  	return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1558  }
  1559  
  1560  // waitInspect will wait for the specified container to have the specified string
  1561  // in the inspect output. It will wait until the specified timeout (in seconds)
  1562  // is reached.
  1563  func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1564  	after := time.After(timeout)
  1565  
  1566  	for {
  1567  		cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  1568  		out, _, err := runCommandWithOutput(cmd)
  1569  		if err != nil {
  1570  			if !strings.Contains(out, "No such") {
  1571  				return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1572  			}
  1573  			select {
  1574  			case <-after:
  1575  				return err
  1576  			default:
  1577  				time.Sleep(10 * time.Millisecond)
  1578  				continue
  1579  			}
  1580  		}
  1581  
  1582  		out = strings.TrimSpace(out)
  1583  		if out == expected {
  1584  			break
  1585  		}
  1586  
  1587  		select {
  1588  		case <-after:
  1589  			return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1590  		default:
  1591  		}
  1592  
  1593  		time.Sleep(100 * time.Millisecond)
  1594  	}
  1595  	return nil
  1596  }