docker_utils.go 21 KB

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