docker_utils.go 24 KB

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