docker_utils.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/http/httputil"
  13. "net/url"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. "time"
  22. "github.com/docker/docker/api"
  23. )
  24. // Daemon represents a Docker daemon for the testing framework.
  25. type Daemon struct {
  26. t *testing.T
  27. logFile *os.File
  28. folder string
  29. stdin io.WriteCloser
  30. stdout, stderr io.ReadCloser
  31. cmd *exec.Cmd
  32. storageDriver string
  33. execDriver string
  34. wait chan error
  35. }
  36. // NewDaemon returns a Daemon instance to be used for testing.
  37. // This will create a directory such as daemon123456789 in the folder specified by $DEST.
  38. // The daemon will not automatically start.
  39. func NewDaemon(t *testing.T) *Daemon {
  40. dest := os.Getenv("DEST")
  41. if dest == "" {
  42. t.Fatal("Please set the DEST environment variable")
  43. }
  44. dir := filepath.Join(dest, fmt.Sprintf("daemon%d", time.Now().UnixNano()%100000000))
  45. daemonFolder, err := filepath.Abs(dir)
  46. if err != nil {
  47. t.Fatalf("Could not make %q an absolute path: %v", dir, err)
  48. }
  49. if err := os.MkdirAll(filepath.Join(daemonFolder, "graph"), 0600); err != nil {
  50. t.Fatalf("Could not create %s/graph directory", daemonFolder)
  51. }
  52. return &Daemon{
  53. t: t,
  54. folder: daemonFolder,
  55. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  56. execDriver: os.Getenv("DOCKER_EXECDRIVER"),
  57. }
  58. }
  59. // Start will start the daemon and return once it is ready to receive requests.
  60. // You can specify additional daemon flags.
  61. func (d *Daemon) Start(arg ...string) error {
  62. dockerBinary, err := exec.LookPath(dockerBinary)
  63. if err != nil {
  64. d.t.Fatalf("could not find docker binary in $PATH: %v", err)
  65. }
  66. args := []string{
  67. "--host", d.sock(),
  68. "--daemon",
  69. "--graph", fmt.Sprintf("%s/graph", d.folder),
  70. "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
  71. }
  72. // If we don't explicitly set the log-level or debug flag(-D) then
  73. // turn on debug mode
  74. foundIt := false
  75. for _, a := range arg {
  76. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") {
  77. foundIt = true
  78. }
  79. }
  80. if !foundIt {
  81. args = append(args, "--debug")
  82. }
  83. if d.storageDriver != "" {
  84. args = append(args, "--storage-driver", d.storageDriver)
  85. }
  86. if d.execDriver != "" {
  87. args = append(args, "--exec-driver", d.execDriver)
  88. }
  89. args = append(args, arg...)
  90. d.cmd = exec.Command(dockerBinary, args...)
  91. d.logFile, err = os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  92. if err != nil {
  93. d.t.Fatalf("Could not create %s/docker.log: %v", d.folder, err)
  94. }
  95. d.cmd.Stdout = d.logFile
  96. d.cmd.Stderr = d.logFile
  97. if err := d.cmd.Start(); err != nil {
  98. return fmt.Errorf("could not start daemon container: %v", err)
  99. }
  100. wait := make(chan error)
  101. go func() {
  102. wait <- d.cmd.Wait()
  103. d.t.Log("exiting daemon")
  104. close(wait)
  105. }()
  106. d.wait = wait
  107. tick := time.Tick(500 * time.Millisecond)
  108. // make sure daemon is ready to receive requests
  109. startTime := time.Now().Unix()
  110. for {
  111. d.t.Log("waiting for daemon to start")
  112. if time.Now().Unix()-startTime > 5 {
  113. // After 5 seconds, give up
  114. return errors.New("Daemon exited and never started")
  115. }
  116. select {
  117. case <-time.After(2 * time.Second):
  118. return errors.New("timeout: daemon does not respond")
  119. case <-tick:
  120. c, err := net.Dial("unix", filepath.Join(d.folder, "docker.sock"))
  121. if err != nil {
  122. continue
  123. }
  124. client := httputil.NewClientConn(c, nil)
  125. defer client.Close()
  126. req, err := http.NewRequest("GET", "/_ping", nil)
  127. if err != nil {
  128. d.t.Fatalf("could not create new request: %v", err)
  129. }
  130. resp, err := client.Do(req)
  131. if err != nil {
  132. continue
  133. }
  134. if resp.StatusCode != http.StatusOK {
  135. d.t.Logf("received status != 200 OK: %s", resp.Status)
  136. }
  137. d.t.Log("daemon started")
  138. return nil
  139. }
  140. }
  141. }
  142. // StartWithBusybox will first start the daemon with Daemon.Start()
  143. // then save the busybox image from the main daemon and load it into this Daemon instance.
  144. func (d *Daemon) StartWithBusybox(arg ...string) error {
  145. if err := d.Start(arg...); err != nil {
  146. return err
  147. }
  148. bb := filepath.Join(d.folder, "busybox.tar")
  149. if _, err := os.Stat(bb); err != nil {
  150. if !os.IsNotExist(err) {
  151. return fmt.Errorf("unexpected error on busybox.tar stat: %v", err)
  152. }
  153. // saving busybox image from main daemon
  154. if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil {
  155. return fmt.Errorf("could not save busybox image: %v", err)
  156. }
  157. }
  158. // loading busybox image to this daemon
  159. if _, err := d.Cmd("load", "--input", bb); err != nil {
  160. return fmt.Errorf("could not load busybox image: %v", err)
  161. }
  162. if err := os.Remove(bb); err != nil {
  163. d.t.Logf("Could not remove %s: %v", bb, err)
  164. }
  165. return nil
  166. }
  167. // Stop will send a SIGINT every second and wait for the daemon to stop.
  168. // If it timeouts, a SIGKILL is sent.
  169. // Stop will not delete the daemon directory. If a purged daemon is needed,
  170. // instantiate a new one with NewDaemon.
  171. func (d *Daemon) Stop() error {
  172. if d.cmd == nil || d.wait == nil {
  173. return errors.New("daemon not started")
  174. }
  175. defer func() {
  176. d.logFile.Close()
  177. d.cmd = nil
  178. }()
  179. i := 1
  180. tick := time.Tick(time.Second)
  181. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  182. return fmt.Errorf("could not send signal: %v", err)
  183. }
  184. out1:
  185. for {
  186. select {
  187. case err := <-d.wait:
  188. return err
  189. case <-time.After(15 * time.Second):
  190. // time for stopping jobs and run onShutdown hooks
  191. d.t.Log("timeout")
  192. break out1
  193. }
  194. }
  195. out2:
  196. for {
  197. select {
  198. case err := <-d.wait:
  199. return err
  200. case <-tick:
  201. i++
  202. if i > 4 {
  203. d.t.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  204. break out2
  205. }
  206. d.t.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  207. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  208. return fmt.Errorf("could not send signal: %v", err)
  209. }
  210. }
  211. }
  212. if err := d.cmd.Process.Kill(); err != nil {
  213. d.t.Logf("Could not kill daemon: %v", err)
  214. return err
  215. }
  216. return nil
  217. }
  218. // Restart will restart the daemon by first stopping it and then starting it.
  219. func (d *Daemon) Restart(arg ...string) error {
  220. d.Stop()
  221. return d.Start(arg...)
  222. }
  223. func (d *Daemon) sock() string {
  224. return fmt.Sprintf("unix://%s/docker.sock", d.folder)
  225. }
  226. // Cmd will execute a docker CLI command against this Daemon.
  227. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  228. func (d *Daemon) Cmd(name string, arg ...string) (string, error) {
  229. args := []string{"--host", d.sock(), name}
  230. args = append(args, arg...)
  231. c := exec.Command(dockerBinary, args...)
  232. b, err := c.CombinedOutput()
  233. return string(b), err
  234. }
  235. func daemonHost() string {
  236. daemonUrlStr := "unix://" + api.DEFAULTUNIXSOCKET
  237. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  238. daemonUrlStr = daemonHostVar
  239. }
  240. return daemonUrlStr
  241. }
  242. func sockConn(timeout time.Duration) (net.Conn, error) {
  243. daemon := daemonHost()
  244. daemonUrl, err := url.Parse(daemon)
  245. if err != nil {
  246. return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
  247. }
  248. var c net.Conn
  249. switch daemonUrl.Scheme {
  250. case "unix":
  251. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Path, timeout)
  252. case "tcp":
  253. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Host, timeout)
  254. default:
  255. return c, fmt.Errorf("unknown scheme %v (%s)", daemonUrl.Scheme, daemon)
  256. }
  257. }
  258. func sockRequest(method, endpoint string, data interface{}) ([]byte, error) {
  259. jsonData := bytes.NewBuffer(nil)
  260. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  261. return nil, err
  262. }
  263. return sockRequestRaw(method, endpoint, jsonData, "application/json")
  264. }
  265. func sockRequestRaw(method, endpoint string, data io.Reader, ct string) ([]byte, error) {
  266. c, err := sockConn(time.Duration(10 * time.Second))
  267. if err != nil {
  268. return nil, fmt.Errorf("could not dial docker daemon: %v", err)
  269. }
  270. client := httputil.NewClientConn(c, nil)
  271. defer client.Close()
  272. req, err := http.NewRequest(method, endpoint, data)
  273. if err != nil {
  274. return nil, fmt.Errorf("could not create new request: %v", err)
  275. }
  276. if ct == "" {
  277. ct = "application/json"
  278. }
  279. req.Header.Set("Content-Type", ct)
  280. resp, err := client.Do(req)
  281. if err != nil {
  282. return nil, fmt.Errorf("could not perform request: %v", err)
  283. }
  284. defer resp.Body.Close()
  285. if resp.StatusCode != http.StatusOK {
  286. body, _ := ioutil.ReadAll(resp.Body)
  287. return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
  288. }
  289. return ioutil.ReadAll(resp.Body)
  290. }
  291. func deleteContainer(container string) error {
  292. container = strings.Replace(container, "\n", " ", -1)
  293. container = strings.Trim(container, " ")
  294. killArgs := fmt.Sprintf("kill %v", container)
  295. killSplitArgs := strings.Split(killArgs, " ")
  296. killCmd := exec.Command(dockerBinary, killSplitArgs...)
  297. runCommand(killCmd)
  298. rmArgs := fmt.Sprintf("rm -v %v", container)
  299. rmSplitArgs := strings.Split(rmArgs, " ")
  300. rmCmd := exec.Command(dockerBinary, rmSplitArgs...)
  301. exitCode, err := runCommand(rmCmd)
  302. // set error manually if not set
  303. if exitCode != 0 && err == nil {
  304. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  305. }
  306. return err
  307. }
  308. func getAllContainers() (string, error) {
  309. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  310. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  311. if exitCode != 0 && err == nil {
  312. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  313. }
  314. return out, err
  315. }
  316. func deleteAllContainers() error {
  317. containers, err := getAllContainers()
  318. if err != nil {
  319. fmt.Println(containers)
  320. return err
  321. }
  322. if err = deleteContainer(containers); err != nil {
  323. return err
  324. }
  325. return nil
  326. }
  327. func getPausedContainers() (string, error) {
  328. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  329. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  330. if exitCode != 0 && err == nil {
  331. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  332. }
  333. return out, err
  334. }
  335. func getSliceOfPausedContainers() ([]string, error) {
  336. out, err := getPausedContainers()
  337. if err == nil {
  338. slice := strings.Split(strings.TrimSpace(out), "\n")
  339. return slice, err
  340. } else {
  341. return []string{out}, err
  342. }
  343. }
  344. func unpauseContainer(container string) error {
  345. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  346. exitCode, err := runCommand(unpauseCmd)
  347. if exitCode != 0 && err == nil {
  348. err = fmt.Errorf("failed to unpause container")
  349. }
  350. return nil
  351. }
  352. func unpauseAllContainers() error {
  353. containers, err := getPausedContainers()
  354. if err != nil {
  355. fmt.Println(containers)
  356. return err
  357. }
  358. containers = strings.Replace(containers, "\n", " ", -1)
  359. containers = strings.Trim(containers, " ")
  360. containerList := strings.Split(containers, " ")
  361. for _, value := range containerList {
  362. if err = unpauseContainer(value); err != nil {
  363. return err
  364. }
  365. }
  366. return nil
  367. }
  368. func deleteImages(images ...string) error {
  369. args := make([]string, 1, 2)
  370. args[0] = "rmi"
  371. args = append(args, images...)
  372. rmiCmd := exec.Command(dockerBinary, args...)
  373. exitCode, err := runCommand(rmiCmd)
  374. // set error manually if not set
  375. if exitCode != 0 && err == nil {
  376. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  377. }
  378. return err
  379. }
  380. func imageExists(image string) error {
  381. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  382. exitCode, err := runCommand(inspectCmd)
  383. if exitCode != 0 && err == nil {
  384. err = fmt.Errorf("couldn't find image %q", image)
  385. }
  386. return err
  387. }
  388. func pullImageIfNotExist(image string) (err error) {
  389. if err := imageExists(image); err != nil {
  390. pullCmd := exec.Command(dockerBinary, "pull", image)
  391. _, exitCode, err := runCommandWithOutput(pullCmd)
  392. if err != nil || exitCode != 0 {
  393. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  394. }
  395. }
  396. return
  397. }
  398. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  399. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  400. if err != nil {
  401. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  402. }
  403. return out, status, err
  404. }
  405. // execute a docker ocmmand with a timeout
  406. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  407. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  408. if err != nil {
  409. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  410. }
  411. return out, status, err
  412. }
  413. // execute a docker command in a directory
  414. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  415. dockerCommand := exec.Command(dockerBinary, args...)
  416. dockerCommand.Dir = path
  417. out, status, err := runCommandWithOutput(dockerCommand)
  418. if err != nil {
  419. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  420. }
  421. return out, status, err
  422. }
  423. // execute a docker command in a directory with a timeout
  424. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  425. dockerCommand := exec.Command(dockerBinary, args...)
  426. dockerCommand.Dir = path
  427. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  428. if err != nil {
  429. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  430. }
  431. return out, status, err
  432. }
  433. func findContainerIP(t *testing.T, id string) string {
  434. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  435. out, _, err := runCommandWithOutput(cmd)
  436. if err != nil {
  437. t.Fatal(err, out)
  438. }
  439. return strings.Trim(out, " \r\n'")
  440. }
  441. func getContainerCount() (int, error) {
  442. const containers = "Containers:"
  443. cmd := exec.Command(dockerBinary, "info")
  444. out, _, err := runCommandWithOutput(cmd)
  445. if err != nil {
  446. return 0, err
  447. }
  448. lines := strings.Split(out, "\n")
  449. for _, line := range lines {
  450. if strings.Contains(line, containers) {
  451. output := stripTrailingCharacters(line)
  452. output = strings.TrimLeft(output, containers)
  453. output = strings.Trim(output, " ")
  454. containerCount, err := strconv.Atoi(output)
  455. if err != nil {
  456. return 0, err
  457. }
  458. return containerCount, nil
  459. }
  460. }
  461. return 0, fmt.Errorf("couldn't find the Container count in the output")
  462. }
  463. type FakeContext struct {
  464. Dir string
  465. }
  466. func (f *FakeContext) Add(file, content string) error {
  467. filepath := path.Join(f.Dir, file)
  468. dirpath := path.Dir(filepath)
  469. if dirpath != "." {
  470. if err := os.MkdirAll(dirpath, 0755); err != nil {
  471. return err
  472. }
  473. }
  474. return ioutil.WriteFile(filepath, []byte(content), 0644)
  475. }
  476. func (f *FakeContext) Delete(file string) error {
  477. filepath := path.Join(f.Dir, file)
  478. return os.RemoveAll(filepath)
  479. }
  480. func (f *FakeContext) Close() error {
  481. return os.RemoveAll(f.Dir)
  482. }
  483. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  484. tmp, err := ioutil.TempDir("", "fake-context")
  485. if err != nil {
  486. return nil, err
  487. }
  488. if err := os.Chmod(tmp, 0755); err != nil {
  489. return nil, err
  490. }
  491. ctx := &FakeContext{tmp}
  492. for file, content := range files {
  493. if err := ctx.Add(file, content); err != nil {
  494. ctx.Close()
  495. return nil, err
  496. }
  497. }
  498. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  499. ctx.Close()
  500. return nil, err
  501. }
  502. return ctx, nil
  503. }
  504. type FakeStorage struct {
  505. *FakeContext
  506. *httptest.Server
  507. }
  508. func (f *FakeStorage) Close() error {
  509. f.Server.Close()
  510. return f.FakeContext.Close()
  511. }
  512. func fakeStorage(files map[string]string) (*FakeStorage, error) {
  513. tmp, err := ioutil.TempDir("", "fake-storage")
  514. if err != nil {
  515. return nil, err
  516. }
  517. ctx := &FakeContext{tmp}
  518. for file, content := range files {
  519. if err := ctx.Add(file, content); err != nil {
  520. ctx.Close()
  521. return nil, err
  522. }
  523. }
  524. handler := http.FileServer(http.Dir(ctx.Dir))
  525. server := httptest.NewServer(handler)
  526. return &FakeStorage{
  527. FakeContext: ctx,
  528. Server: server,
  529. }, nil
  530. }
  531. func inspectField(name, field string) (string, error) {
  532. format := fmt.Sprintf("{{.%s}}", field)
  533. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  534. out, exitCode, err := runCommandWithOutput(inspectCmd)
  535. if err != nil || exitCode != 0 {
  536. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  537. }
  538. return strings.TrimSpace(out), nil
  539. }
  540. func inspectFieldJSON(name, field string) (string, error) {
  541. format := fmt.Sprintf("{{json .%s}}", field)
  542. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  543. out, exitCode, err := runCommandWithOutput(inspectCmd)
  544. if err != nil || exitCode != 0 {
  545. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  546. }
  547. return strings.TrimSpace(out), nil
  548. }
  549. func inspectFieldMap(name, path, field string) (string, error) {
  550. format := fmt.Sprintf("{{index .%s %q}}", path, field)
  551. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  552. out, exitCode, err := runCommandWithOutput(inspectCmd)
  553. if err != nil || exitCode != 0 {
  554. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  555. }
  556. return strings.TrimSpace(out), nil
  557. }
  558. func getIDByName(name string) (string, error) {
  559. return inspectField(name, "Id")
  560. }
  561. // getContainerState returns the exit code of the container
  562. // and true if it's running
  563. // the exit code should be ignored if it's running
  564. func getContainerState(t *testing.T, id string) (int, bool, error) {
  565. var (
  566. exitStatus int
  567. running bool
  568. )
  569. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  570. if err != nil || exitCode != 0 {
  571. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  572. }
  573. out = strings.Trim(out, "\n")
  574. splitOutput := strings.Split(out, " ")
  575. if len(splitOutput) != 2 {
  576. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  577. }
  578. if splitOutput[0] == "true" {
  579. running = true
  580. }
  581. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  582. exitStatus = n
  583. } else {
  584. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  585. }
  586. return exitStatus, running, nil
  587. }
  588. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  589. args := []string{"build", "-t", name}
  590. if !useCache {
  591. args = append(args, "--no-cache")
  592. }
  593. args = append(args, "-")
  594. buildCmd := exec.Command(dockerBinary, args...)
  595. buildCmd.Stdin = strings.NewReader(dockerfile)
  596. out, exitCode, err := runCommandWithOutput(buildCmd)
  597. if err != nil || exitCode != 0 {
  598. return "", out, fmt.Errorf("failed to build the image: %s", out)
  599. }
  600. id, err := getIDByName(name)
  601. if err != nil {
  602. return "", out, err
  603. }
  604. return id, out, nil
  605. }
  606. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  607. args := []string{"build", "-t", name}
  608. if !useCache {
  609. args = append(args, "--no-cache")
  610. }
  611. args = append(args, "-")
  612. buildCmd := exec.Command(dockerBinary, args...)
  613. buildCmd.Stdin = strings.NewReader(dockerfile)
  614. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  615. if err != nil || exitCode != 0 {
  616. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  617. }
  618. id, err := getIDByName(name)
  619. if err != nil {
  620. return "", stdout, stderr, err
  621. }
  622. return id, stdout, stderr, nil
  623. }
  624. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  625. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  626. return id, err
  627. }
  628. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  629. args := []string{"build", "-t", name}
  630. if !useCache {
  631. args = append(args, "--no-cache")
  632. }
  633. args = append(args, ".")
  634. buildCmd := exec.Command(dockerBinary, args...)
  635. buildCmd.Dir = ctx.Dir
  636. out, exitCode, err := runCommandWithOutput(buildCmd)
  637. if err != nil || exitCode != 0 {
  638. return "", fmt.Errorf("failed to build the image: %s", out)
  639. }
  640. return getIDByName(name)
  641. }
  642. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  643. args := []string{"build", "-t", name}
  644. if !useCache {
  645. args = append(args, "--no-cache")
  646. }
  647. args = append(args, path)
  648. buildCmd := exec.Command(dockerBinary, args...)
  649. out, exitCode, err := runCommandWithOutput(buildCmd)
  650. if err != nil || exitCode != 0 {
  651. return "", fmt.Errorf("failed to build the image: %s", out)
  652. }
  653. return getIDByName(name)
  654. }
  655. type FakeGIT struct {
  656. *httptest.Server
  657. Root string
  658. RepoURL string
  659. }
  660. func (g *FakeGIT) Close() {
  661. g.Server.Close()
  662. os.RemoveAll(g.Root)
  663. }
  664. func fakeGIT(name string, files map[string]string) (*FakeGIT, error) {
  665. tmp, err := ioutil.TempDir("", "fake-git-repo")
  666. if err != nil {
  667. return nil, err
  668. }
  669. ctx := &FakeContext{tmp}
  670. for file, content := range files {
  671. if err := ctx.Add(file, content); err != nil {
  672. ctx.Close()
  673. return nil, err
  674. }
  675. }
  676. defer ctx.Close()
  677. curdir, err := os.Getwd()
  678. if err != nil {
  679. return nil, err
  680. }
  681. defer os.Chdir(curdir)
  682. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  683. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  684. }
  685. err = os.Chdir(ctx.Dir)
  686. if err != nil {
  687. return nil, err
  688. }
  689. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  690. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  691. }
  692. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  693. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  694. }
  695. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  696. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  697. }
  698. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  699. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  700. }
  701. root, err := ioutil.TempDir("", "docker-test-git-repo")
  702. if err != nil {
  703. return nil, err
  704. }
  705. repoPath := filepath.Join(root, name+".git")
  706. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  707. os.RemoveAll(root)
  708. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  709. }
  710. err = os.Chdir(repoPath)
  711. if err != nil {
  712. os.RemoveAll(root)
  713. return nil, err
  714. }
  715. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  716. os.RemoveAll(root)
  717. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  718. }
  719. err = os.Chdir(curdir)
  720. if err != nil {
  721. os.RemoveAll(root)
  722. return nil, err
  723. }
  724. handler := http.FileServer(http.Dir(root))
  725. server := httptest.NewServer(handler)
  726. return &FakeGIT{
  727. Server: server,
  728. Root: root,
  729. RepoURL: fmt.Sprintf("%s/%s.git", server.URL, name),
  730. }, nil
  731. }
  732. // Write `content` to the file at path `dst`, creating it if necessary,
  733. // as well as any missing directories.
  734. // The file is truncated if it already exists.
  735. // Call t.Fatal() at the first error.
  736. func writeFile(dst, content string, t *testing.T) {
  737. // Create subdirectories if necessary
  738. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  739. t.Fatal(err)
  740. }
  741. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  742. if err != nil {
  743. t.Fatal(err)
  744. }
  745. // Write content (truncate if it exists)
  746. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  747. t.Fatal(err)
  748. }
  749. }
  750. // Return the contents of file at path `src`.
  751. // Call t.Fatal() at the first error (including if the file doesn't exist)
  752. func readFile(src string, t *testing.T) (content string) {
  753. data, err := ioutil.ReadFile(src)
  754. if err != nil {
  755. t.Fatal(err)
  756. }
  757. return string(data)
  758. }
  759. func containerStorageFile(containerId, basename string) string {
  760. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  761. }
  762. // docker commands that use this function must be run with the '-d' switch.
  763. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  764. out, _, err := runCommandWithOutput(cmd)
  765. if err != nil {
  766. return nil, fmt.Errorf("%v: %q", err, out)
  767. }
  768. time.Sleep(1 * time.Second)
  769. contID := strings.TrimSpace(out)
  770. return readContainerFile(contID, filename)
  771. }
  772. func readContainerFile(containerId, filename string) ([]byte, error) {
  773. f, err := os.Open(containerStorageFile(containerId, filename))
  774. if err != nil {
  775. return nil, err
  776. }
  777. defer f.Close()
  778. content, err := ioutil.ReadAll(f)
  779. if err != nil {
  780. return nil, err
  781. }
  782. return content, nil
  783. }
  784. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  785. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  786. return []byte(out), err
  787. }
  788. func setupRegistry(t *testing.T) func() {
  789. testRequires(t, RegistryHosting)
  790. reg, err := newTestRegistryV2(t)
  791. if err != nil {
  792. t.Fatal(err)
  793. }
  794. // Wait for registry to be ready to serve requests.
  795. for i := 0; i != 5; i++ {
  796. if err = reg.Ping(); err == nil {
  797. break
  798. }
  799. time.Sleep(100 * time.Millisecond)
  800. }
  801. if err != nil {
  802. t.Fatal("Timeout waiting for test registry to become available")
  803. }
  804. return func() { reg.Close() }
  805. }
  806. // appendBaseEnv appends the minimum set of environment variables to exec the
  807. // docker cli binary for testing with correct configuration to the given env
  808. // list.
  809. func appendBaseEnv(env []string) []string {
  810. preserveList := []string{
  811. // preserve remote test host
  812. "DOCKER_HOST",
  813. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  814. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  815. "SystemRoot",
  816. }
  817. for _, key := range preserveList {
  818. if val := os.Getenv(key); val != "" {
  819. env = append(env, fmt.Sprintf("%s=%s", key, val))
  820. }
  821. }
  822. return env
  823. }