docker_utils.go 21 KB

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