docker_utils.go 22 KB

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