docker_utils.go 20 KB

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