docker_utils.go 16 KB

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