docker_utils.go 44 KB

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