docker_utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. rmiCmd := exec.Command(dockerBinary, "rmi", strings.Join(images, " "))
  282. exitCode, err := runCommand(rmiCmd)
  283. // set error manually if not set
  284. if exitCode != 0 && err == nil {
  285. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  286. }
  287. return err
  288. }
  289. func imageExists(image string) error {
  290. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  291. exitCode, err := runCommand(inspectCmd)
  292. if exitCode != 0 && err == nil {
  293. err = fmt.Errorf("couldn't find image %q", image)
  294. }
  295. return err
  296. }
  297. func pullImageIfNotExist(image string) (err error) {
  298. if err := imageExists(image); err != nil {
  299. pullCmd := exec.Command(dockerBinary, "pull", image)
  300. _, exitCode, err := runCommandWithOutput(pullCmd)
  301. if err != nil || exitCode != 0 {
  302. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  303. }
  304. }
  305. return
  306. }
  307. // deprecated, use dockerCmd instead
  308. func cmd(t *testing.T, args ...string) (string, int, error) {
  309. return dockerCmd(t, args...)
  310. }
  311. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  312. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  313. if err != nil {
  314. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  315. }
  316. return out, status, err
  317. }
  318. // execute a docker ocmmand with a timeout
  319. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  320. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  321. if err != nil {
  322. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  323. }
  324. return out, status, err
  325. }
  326. // execute a docker command in a directory
  327. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  328. dockerCommand := exec.Command(dockerBinary, args...)
  329. dockerCommand.Dir = path
  330. out, status, err := runCommandWithOutput(dockerCommand)
  331. if err != nil {
  332. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  333. }
  334. return out, status, err
  335. }
  336. // execute a docker command in a directory with a timeout
  337. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  338. dockerCommand := exec.Command(dockerBinary, args...)
  339. dockerCommand.Dir = path
  340. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  341. if err != nil {
  342. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  343. }
  344. return out, status, err
  345. }
  346. func findContainerIP(t *testing.T, id string) string {
  347. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  348. out, _, err := runCommandWithOutput(cmd)
  349. if err != nil {
  350. t.Fatal(err, out)
  351. }
  352. return strings.Trim(out, " \r\n'")
  353. }
  354. func getContainerCount() (int, error) {
  355. const containers = "Containers:"
  356. cmd := exec.Command(dockerBinary, "info")
  357. out, _, err := runCommandWithOutput(cmd)
  358. if err != nil {
  359. return 0, err
  360. }
  361. lines := strings.Split(out, "\n")
  362. for _, line := range lines {
  363. if strings.Contains(line, containers) {
  364. output := stripTrailingCharacters(line)
  365. output = strings.TrimLeft(output, containers)
  366. output = strings.Trim(output, " ")
  367. containerCount, err := strconv.Atoi(output)
  368. if err != nil {
  369. return 0, err
  370. }
  371. return containerCount, nil
  372. }
  373. }
  374. return 0, fmt.Errorf("couldn't find the Container count in the output")
  375. }
  376. type FakeContext struct {
  377. Dir string
  378. }
  379. func (f *FakeContext) Add(file, content string) error {
  380. filepath := path.Join(f.Dir, file)
  381. dirpath := path.Dir(filepath)
  382. if dirpath != "." {
  383. if err := os.MkdirAll(dirpath, 0755); err != nil {
  384. return err
  385. }
  386. }
  387. return ioutil.WriteFile(filepath, []byte(content), 0644)
  388. }
  389. func (f *FakeContext) Delete(file string) error {
  390. filepath := path.Join(f.Dir, file)
  391. return os.RemoveAll(filepath)
  392. }
  393. func (f *FakeContext) Close() error {
  394. return os.RemoveAll(f.Dir)
  395. }
  396. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  397. tmp, err := ioutil.TempDir("", "fake-context")
  398. if err != nil {
  399. return nil, err
  400. }
  401. if err := os.Chmod(tmp, 0755); err != nil {
  402. return nil, err
  403. }
  404. ctx := &FakeContext{tmp}
  405. for file, content := range files {
  406. if err := ctx.Add(file, content); err != nil {
  407. ctx.Close()
  408. return nil, err
  409. }
  410. }
  411. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  412. ctx.Close()
  413. return nil, err
  414. }
  415. return ctx, nil
  416. }
  417. type FakeStorage struct {
  418. *FakeContext
  419. *httptest.Server
  420. }
  421. func (f *FakeStorage) Close() error {
  422. f.Server.Close()
  423. return f.FakeContext.Close()
  424. }
  425. func fakeStorage(files map[string]string) (*FakeStorage, error) {
  426. tmp, err := ioutil.TempDir("", "fake-storage")
  427. if err != nil {
  428. return nil, err
  429. }
  430. ctx := &FakeContext{tmp}
  431. for file, content := range files {
  432. if err := ctx.Add(file, content); err != nil {
  433. ctx.Close()
  434. return nil, err
  435. }
  436. }
  437. handler := http.FileServer(http.Dir(ctx.Dir))
  438. server := httptest.NewServer(handler)
  439. return &FakeStorage{
  440. FakeContext: ctx,
  441. Server: server,
  442. }, nil
  443. }
  444. func inspectField(name, field string) (string, error) {
  445. format := fmt.Sprintf("{{.%s}}", field)
  446. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  447. out, exitCode, err := runCommandWithOutput(inspectCmd)
  448. if err != nil || exitCode != 0 {
  449. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  450. }
  451. return strings.TrimSpace(out), nil
  452. }
  453. func inspectFieldJSON(name, field string) (string, error) {
  454. format := fmt.Sprintf("{{json .%s}}", field)
  455. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  456. out, exitCode, err := runCommandWithOutput(inspectCmd)
  457. if err != nil || exitCode != 0 {
  458. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  459. }
  460. return strings.TrimSpace(out), nil
  461. }
  462. func inspectFieldMap(name, path, field string) (string, error) {
  463. format := fmt.Sprintf("{{index .%s %q}}", path, field)
  464. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  465. out, exitCode, err := runCommandWithOutput(inspectCmd)
  466. if err != nil || exitCode != 0 {
  467. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  468. }
  469. return strings.TrimSpace(out), nil
  470. }
  471. func getIDByName(name string) (string, error) {
  472. return inspectField(name, "Id")
  473. }
  474. // getContainerState returns the exit code of the container
  475. // and true if it's running
  476. // the exit code should be ignored if it's running
  477. func getContainerState(t *testing.T, id string) (int, bool, error) {
  478. var (
  479. exitStatus int
  480. running bool
  481. )
  482. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  483. if err != nil || exitCode != 0 {
  484. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  485. }
  486. out = strings.Trim(out, "\n")
  487. splitOutput := strings.Split(out, " ")
  488. if len(splitOutput) != 2 {
  489. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  490. }
  491. if splitOutput[0] == "true" {
  492. running = true
  493. }
  494. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  495. exitStatus = n
  496. } else {
  497. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  498. }
  499. return exitStatus, running, nil
  500. }
  501. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  502. args := []string{"build", "-t", name}
  503. if !useCache {
  504. args = append(args, "--no-cache")
  505. }
  506. args = append(args, "-")
  507. buildCmd := exec.Command(dockerBinary, args...)
  508. buildCmd.Stdin = strings.NewReader(dockerfile)
  509. out, exitCode, err := runCommandWithOutput(buildCmd)
  510. if err != nil || exitCode != 0 {
  511. return "", out, fmt.Errorf("failed to build the image: %s", out)
  512. }
  513. id, err := getIDByName(name)
  514. if err != nil {
  515. return "", out, err
  516. }
  517. return id, out, nil
  518. }
  519. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  520. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  521. return id, err
  522. }
  523. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  524. args := []string{"build", "-t", name}
  525. if !useCache {
  526. args = append(args, "--no-cache")
  527. }
  528. args = append(args, ".")
  529. buildCmd := exec.Command(dockerBinary, args...)
  530. buildCmd.Dir = ctx.Dir
  531. out, exitCode, err := runCommandWithOutput(buildCmd)
  532. if err != nil || exitCode != 0 {
  533. return "", fmt.Errorf("failed to build the image: %s", out)
  534. }
  535. return getIDByName(name)
  536. }
  537. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  538. args := []string{"build", "-t", name}
  539. if !useCache {
  540. args = append(args, "--no-cache")
  541. }
  542. args = append(args, path)
  543. buildCmd := exec.Command(dockerBinary, args...)
  544. out, exitCode, err := runCommandWithOutput(buildCmd)
  545. if err != nil || exitCode != 0 {
  546. return "", fmt.Errorf("failed to build the image: %s", out)
  547. }
  548. return getIDByName(name)
  549. }
  550. type FakeGIT struct {
  551. *httptest.Server
  552. Root string
  553. RepoURL string
  554. }
  555. func (g *FakeGIT) Close() {
  556. g.Server.Close()
  557. os.RemoveAll(g.Root)
  558. }
  559. func fakeGIT(name string, files map[string]string) (*FakeGIT, error) {
  560. tmp, err := ioutil.TempDir("", "fake-git-repo")
  561. if err != nil {
  562. return nil, err
  563. }
  564. ctx := &FakeContext{tmp}
  565. for file, content := range files {
  566. if err := ctx.Add(file, content); err != nil {
  567. ctx.Close()
  568. return nil, err
  569. }
  570. }
  571. defer ctx.Close()
  572. curdir, err := os.Getwd()
  573. if err != nil {
  574. return nil, err
  575. }
  576. defer os.Chdir(curdir)
  577. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  578. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  579. }
  580. err = os.Chdir(ctx.Dir)
  581. if err != nil {
  582. return nil, err
  583. }
  584. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  585. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  586. }
  587. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  588. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  589. }
  590. root, err := ioutil.TempDir("", "docker-test-git-repo")
  591. if err != nil {
  592. return nil, err
  593. }
  594. repoPath := filepath.Join(root, name+".git")
  595. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  596. os.RemoveAll(root)
  597. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  598. }
  599. err = os.Chdir(repoPath)
  600. if err != nil {
  601. os.RemoveAll(root)
  602. return nil, err
  603. }
  604. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  605. os.RemoveAll(root)
  606. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  607. }
  608. err = os.Chdir(curdir)
  609. if err != nil {
  610. os.RemoveAll(root)
  611. return nil, err
  612. }
  613. handler := http.FileServer(http.Dir(root))
  614. server := httptest.NewServer(handler)
  615. return &FakeGIT{
  616. Server: server,
  617. Root: root,
  618. RepoURL: fmt.Sprintf("%s/%s.git", server.URL, name),
  619. }, nil
  620. }
  621. // Write `content` to the file at path `dst`, creating it if necessary,
  622. // as well as any missing directories.
  623. // The file is truncated if it already exists.
  624. // Call t.Fatal() at the first error.
  625. func writeFile(dst, content string, t *testing.T) {
  626. // Create subdirectories if necessary
  627. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  628. t.Fatal(err)
  629. }
  630. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. // Write content (truncate if it exists)
  635. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  636. t.Fatal(err)
  637. }
  638. }
  639. // Return the contents of file at path `src`.
  640. // Call t.Fatal() at the first error (including if the file doesn't exist)
  641. func readFile(src string, t *testing.T) (content string) {
  642. f, err := os.Open(src)
  643. if err != nil {
  644. t.Fatal(err)
  645. }
  646. data, err := ioutil.ReadAll(f)
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. return string(data)
  651. }