docker_utils.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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 unpauseContainer(container string) error {
  336. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  337. exitCode, err := runCommand(unpauseCmd)
  338. if exitCode != 0 && err == nil {
  339. err = fmt.Errorf("failed to unpause container")
  340. }
  341. return nil
  342. }
  343. func unpauseAllContainers() error {
  344. containers, err := getPausedContainers()
  345. if err != nil {
  346. fmt.Println(containers)
  347. return err
  348. }
  349. containers = strings.Replace(containers, "\n", " ", -1)
  350. containers = strings.Trim(containers, " ")
  351. containerList := strings.Split(containers, " ")
  352. for _, value := range containerList {
  353. if err = unpauseContainer(value); err != nil {
  354. return err
  355. }
  356. }
  357. return nil
  358. }
  359. func deleteImages(images ...string) error {
  360. args := make([]string, 1, 2)
  361. args[0] = "rmi"
  362. args = append(args, images...)
  363. rmiCmd := exec.Command(dockerBinary, args...)
  364. exitCode, err := runCommand(rmiCmd)
  365. // set error manually if not set
  366. if exitCode != 0 && err == nil {
  367. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  368. }
  369. return err
  370. }
  371. func imageExists(image string) error {
  372. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  373. exitCode, err := runCommand(inspectCmd)
  374. if exitCode != 0 && err == nil {
  375. err = fmt.Errorf("couldn't find image %q", image)
  376. }
  377. return err
  378. }
  379. func pullImageIfNotExist(image string) (err error) {
  380. if err := imageExists(image); err != nil {
  381. pullCmd := exec.Command(dockerBinary, "pull", image)
  382. _, exitCode, err := runCommandWithOutput(pullCmd)
  383. if err != nil || exitCode != 0 {
  384. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  385. }
  386. }
  387. return
  388. }
  389. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  390. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  391. if err != nil {
  392. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  393. }
  394. return out, status, err
  395. }
  396. // execute a docker ocmmand with a timeout
  397. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  398. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  399. if err != nil {
  400. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  401. }
  402. return out, status, err
  403. }
  404. // execute a docker command in a directory
  405. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  406. dockerCommand := exec.Command(dockerBinary, args...)
  407. dockerCommand.Dir = path
  408. out, status, err := runCommandWithOutput(dockerCommand)
  409. if err != nil {
  410. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  411. }
  412. return out, status, err
  413. }
  414. // execute a docker command in a directory with a timeout
  415. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  416. dockerCommand := exec.Command(dockerBinary, args...)
  417. dockerCommand.Dir = path
  418. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  419. if err != nil {
  420. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  421. }
  422. return out, status, err
  423. }
  424. func findContainerIP(t *testing.T, id string) string {
  425. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  426. out, _, err := runCommandWithOutput(cmd)
  427. if err != nil {
  428. t.Fatal(err, out)
  429. }
  430. return strings.Trim(out, " \r\n'")
  431. }
  432. func getContainerCount() (int, error) {
  433. const containers = "Containers:"
  434. cmd := exec.Command(dockerBinary, "info")
  435. out, _, err := runCommandWithOutput(cmd)
  436. if err != nil {
  437. return 0, err
  438. }
  439. lines := strings.Split(out, "\n")
  440. for _, line := range lines {
  441. if strings.Contains(line, containers) {
  442. output := stripTrailingCharacters(line)
  443. output = strings.TrimLeft(output, containers)
  444. output = strings.Trim(output, " ")
  445. containerCount, err := strconv.Atoi(output)
  446. if err != nil {
  447. return 0, err
  448. }
  449. return containerCount, nil
  450. }
  451. }
  452. return 0, fmt.Errorf("couldn't find the Container count in the output")
  453. }
  454. type FakeContext struct {
  455. Dir string
  456. }
  457. func (f *FakeContext) Add(file, content string) error {
  458. filepath := path.Join(f.Dir, file)
  459. dirpath := path.Dir(filepath)
  460. if dirpath != "." {
  461. if err := os.MkdirAll(dirpath, 0755); err != nil {
  462. return err
  463. }
  464. }
  465. return ioutil.WriteFile(filepath, []byte(content), 0644)
  466. }
  467. func (f *FakeContext) Delete(file string) error {
  468. filepath := path.Join(f.Dir, file)
  469. return os.RemoveAll(filepath)
  470. }
  471. func (f *FakeContext) Close() error {
  472. return os.RemoveAll(f.Dir)
  473. }
  474. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  475. tmp, err := ioutil.TempDir("", "fake-context")
  476. if err != nil {
  477. return nil, err
  478. }
  479. if err := os.Chmod(tmp, 0755); err != nil {
  480. return nil, err
  481. }
  482. ctx := &FakeContext{tmp}
  483. for file, content := range files {
  484. if err := ctx.Add(file, content); err != nil {
  485. ctx.Close()
  486. return nil, err
  487. }
  488. }
  489. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  490. ctx.Close()
  491. return nil, err
  492. }
  493. return ctx, nil
  494. }
  495. type FakeStorage struct {
  496. *FakeContext
  497. *httptest.Server
  498. }
  499. func (f *FakeStorage) Close() error {
  500. f.Server.Close()
  501. return f.FakeContext.Close()
  502. }
  503. func fakeStorage(files map[string]string) (*FakeStorage, error) {
  504. tmp, err := ioutil.TempDir("", "fake-storage")
  505. if err != nil {
  506. return nil, err
  507. }
  508. ctx := &FakeContext{tmp}
  509. for file, content := range files {
  510. if err := ctx.Add(file, content); err != nil {
  511. ctx.Close()
  512. return nil, err
  513. }
  514. }
  515. handler := http.FileServer(http.Dir(ctx.Dir))
  516. server := httptest.NewServer(handler)
  517. return &FakeStorage{
  518. FakeContext: ctx,
  519. Server: server,
  520. }, nil
  521. }
  522. func inspectField(name, field string) (string, error) {
  523. format := fmt.Sprintf("{{.%s}}", field)
  524. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  525. out, exitCode, err := runCommandWithOutput(inspectCmd)
  526. if err != nil || exitCode != 0 {
  527. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  528. }
  529. return strings.TrimSpace(out), nil
  530. }
  531. func inspectFieldJSON(name, field string) (string, error) {
  532. format := fmt.Sprintf("{{json .%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 inspectFieldMap(name, path, field string) (string, error) {
  541. format := fmt.Sprintf("{{index .%s %q}}", path, 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 getIDByName(name string) (string, error) {
  550. return inspectField(name, "Id")
  551. }
  552. // getContainerState returns the exit code of the container
  553. // and true if it's running
  554. // the exit code should be ignored if it's running
  555. func getContainerState(t *testing.T, id string) (int, bool, error) {
  556. var (
  557. exitStatus int
  558. running bool
  559. )
  560. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  561. if err != nil || exitCode != 0 {
  562. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  563. }
  564. out = strings.Trim(out, "\n")
  565. splitOutput := strings.Split(out, " ")
  566. if len(splitOutput) != 2 {
  567. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  568. }
  569. if splitOutput[0] == "true" {
  570. running = true
  571. }
  572. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  573. exitStatus = n
  574. } else {
  575. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  576. }
  577. return exitStatus, running, nil
  578. }
  579. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  580. args := []string{"build", "-t", name}
  581. if !useCache {
  582. args = append(args, "--no-cache")
  583. }
  584. args = append(args, "-")
  585. buildCmd := exec.Command(dockerBinary, args...)
  586. buildCmd.Stdin = strings.NewReader(dockerfile)
  587. out, exitCode, err := runCommandWithOutput(buildCmd)
  588. if err != nil || exitCode != 0 {
  589. return "", out, fmt.Errorf("failed to build the image: %s", out)
  590. }
  591. id, err := getIDByName(name)
  592. if err != nil {
  593. return "", out, err
  594. }
  595. return id, out, nil
  596. }
  597. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  598. args := []string{"build", "-t", name}
  599. if !useCache {
  600. args = append(args, "--no-cache")
  601. }
  602. args = append(args, "-")
  603. buildCmd := exec.Command(dockerBinary, args...)
  604. buildCmd.Stdin = strings.NewReader(dockerfile)
  605. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  606. if err != nil || exitCode != 0 {
  607. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  608. }
  609. id, err := getIDByName(name)
  610. if err != nil {
  611. return "", stdout, stderr, err
  612. }
  613. return id, stdout, stderr, nil
  614. }
  615. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  616. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  617. return id, err
  618. }
  619. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  620. args := []string{"build", "-t", name}
  621. if !useCache {
  622. args = append(args, "--no-cache")
  623. }
  624. args = append(args, ".")
  625. buildCmd := exec.Command(dockerBinary, args...)
  626. buildCmd.Dir = ctx.Dir
  627. out, exitCode, err := runCommandWithOutput(buildCmd)
  628. if err != nil || exitCode != 0 {
  629. return "", fmt.Errorf("failed to build the image: %s", out)
  630. }
  631. return getIDByName(name)
  632. }
  633. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  634. args := []string{"build", "-t", name}
  635. if !useCache {
  636. args = append(args, "--no-cache")
  637. }
  638. args = append(args, path)
  639. buildCmd := exec.Command(dockerBinary, args...)
  640. out, exitCode, err := runCommandWithOutput(buildCmd)
  641. if err != nil || exitCode != 0 {
  642. return "", fmt.Errorf("failed to build the image: %s", out)
  643. }
  644. return getIDByName(name)
  645. }
  646. type FakeGIT struct {
  647. *httptest.Server
  648. Root string
  649. RepoURL string
  650. }
  651. func (g *FakeGIT) Close() {
  652. g.Server.Close()
  653. os.RemoveAll(g.Root)
  654. }
  655. func fakeGIT(name string, files map[string]string) (*FakeGIT, error) {
  656. tmp, err := ioutil.TempDir("", "fake-git-repo")
  657. if err != nil {
  658. return nil, err
  659. }
  660. ctx := &FakeContext{tmp}
  661. for file, content := range files {
  662. if err := ctx.Add(file, content); err != nil {
  663. ctx.Close()
  664. return nil, err
  665. }
  666. }
  667. defer ctx.Close()
  668. curdir, err := os.Getwd()
  669. if err != nil {
  670. return nil, err
  671. }
  672. defer os.Chdir(curdir)
  673. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  674. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  675. }
  676. err = os.Chdir(ctx.Dir)
  677. if err != nil {
  678. return nil, err
  679. }
  680. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  681. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  682. }
  683. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  684. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  685. }
  686. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  687. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  688. }
  689. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  690. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  691. }
  692. root, err := ioutil.TempDir("", "docker-test-git-repo")
  693. if err != nil {
  694. return nil, err
  695. }
  696. repoPath := filepath.Join(root, name+".git")
  697. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  698. os.RemoveAll(root)
  699. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  700. }
  701. err = os.Chdir(repoPath)
  702. if err != nil {
  703. os.RemoveAll(root)
  704. return nil, err
  705. }
  706. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  707. os.RemoveAll(root)
  708. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  709. }
  710. err = os.Chdir(curdir)
  711. if err != nil {
  712. os.RemoveAll(root)
  713. return nil, err
  714. }
  715. handler := http.FileServer(http.Dir(root))
  716. server := httptest.NewServer(handler)
  717. return &FakeGIT{
  718. Server: server,
  719. Root: root,
  720. RepoURL: fmt.Sprintf("%s/%s.git", server.URL, name),
  721. }, nil
  722. }
  723. // Write `content` to the file at path `dst`, creating it if necessary,
  724. // as well as any missing directories.
  725. // The file is truncated if it already exists.
  726. // Call t.Fatal() at the first error.
  727. func writeFile(dst, content string, t *testing.T) {
  728. // Create subdirectories if necessary
  729. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  730. t.Fatal(err)
  731. }
  732. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  733. if err != nil {
  734. t.Fatal(err)
  735. }
  736. // Write content (truncate if it exists)
  737. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  738. t.Fatal(err)
  739. }
  740. }
  741. // Return the contents of file at path `src`.
  742. // Call t.Fatal() at the first error (including if the file doesn't exist)
  743. func readFile(src string, t *testing.T) (content string) {
  744. f, err := os.Open(src)
  745. if err != nil {
  746. t.Fatal(err)
  747. }
  748. data, err := ioutil.ReadAll(f)
  749. if err != nil {
  750. t.Fatal(err)
  751. }
  752. return string(data)
  753. }
  754. func containerStorageFile(containerId, basename string) string {
  755. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  756. }
  757. // docker commands that use this function must be run with the '-d' switch.
  758. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  759. out, _, err := runCommandWithOutput(cmd)
  760. if err != nil {
  761. return nil, fmt.Errorf("%v: %q", err, out)
  762. }
  763. time.Sleep(1 * time.Second)
  764. contID := strings.TrimSpace(out)
  765. return readContainerFile(contID, filename)
  766. }
  767. func readContainerFile(containerId, filename string) ([]byte, error) {
  768. f, err := os.Open(containerStorageFile(containerId, filename))
  769. if err != nil {
  770. return nil, err
  771. }
  772. defer f.Close()
  773. content, err := ioutil.ReadAll(f)
  774. if err != nil {
  775. return nil, err
  776. }
  777. return content, nil
  778. }
  779. func setupRegistry(t *testing.T) func() {
  780. reg, err := newTestRegistryV2(t)
  781. if err != nil {
  782. t.Fatal(err)
  783. }
  784. // Wait for registry to be ready to serve requests.
  785. for i := 0; i != 5; i++ {
  786. if err = reg.Ping(); err == nil {
  787. break
  788. }
  789. time.Sleep(100 * time.Millisecond)
  790. }
  791. if err != nil {
  792. t.Fatal("Timeout waiting for test registry to become available")
  793. }
  794. return func() { reg.Close() }
  795. }
  796. // appendDockerHostEnv adds given env slice DOCKER_HOST value if set in the
  797. // environment. Useful when environment is cleared but we want to preserve DOCKER_HOST
  798. // to execute tests against a remote daemon.
  799. func appendDockerHostEnv(env []string) []string {
  800. if dockerHost := os.Getenv("DOCKER_HOST"); dockerHost != "" {
  801. env = append(env, fmt.Sprintf("DOCKER_HOST=%s", dockerHost))
  802. }
  803. return env
  804. }