docker_utils.go 20 KB

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