docker_utils.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. out1:
  183. for {
  184. select {
  185. case err := <-d.wait:
  186. return err
  187. case <-time.After(15 * time.Second):
  188. // time for stopping jobs and run onShutdown hooks
  189. d.t.Log("timeout")
  190. break out1
  191. }
  192. }
  193. out2:
  194. for {
  195. select {
  196. case err := <-d.wait:
  197. return err
  198. case <-tick:
  199. i++
  200. if i > 4 {
  201. d.t.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  202. break out2
  203. }
  204. d.t.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  205. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  206. return fmt.Errorf("could not send signal: %v", err)
  207. }
  208. }
  209. }
  210. if err := d.cmd.Process.Kill(); err != nil {
  211. d.t.Logf("Could not kill daemon: %v", err)
  212. return err
  213. }
  214. return nil
  215. }
  216. // Restart will restart the daemon by first stopping it and then starting it.
  217. func (d *Daemon) Restart(arg ...string) error {
  218. d.Stop()
  219. return d.Start(arg...)
  220. }
  221. func (d *Daemon) sock() string {
  222. return fmt.Sprintf("unix://%s/docker.sock", d.folder)
  223. }
  224. // Cmd will execute a docker CLI command against this Daemon.
  225. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  226. func (d *Daemon) Cmd(name string, arg ...string) (string, error) {
  227. args := []string{"--host", d.sock(), name}
  228. args = append(args, arg...)
  229. c := exec.Command(dockerBinary, args...)
  230. b, err := c.CombinedOutput()
  231. return string(b), err
  232. }
  233. func sockRequest(method, endpoint string, data interface{}) ([]byte, error) {
  234. // FIX: the path to sock should not be hardcoded
  235. sock := filepath.Join("/", "var", "run", "docker.sock")
  236. c, err := net.DialTimeout("unix", sock, time.Duration(10*time.Second))
  237. if err != nil {
  238. return nil, fmt.Errorf("could not dial docker sock at %s: %v", sock, err)
  239. }
  240. client := httputil.NewClientConn(c, nil)
  241. defer client.Close()
  242. jsonData := bytes.NewBuffer(nil)
  243. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  244. return nil, err
  245. }
  246. req, err := http.NewRequest(method, endpoint, jsonData)
  247. req.Header.Set("Content-Type", "application/json")
  248. if err != nil {
  249. return nil, fmt.Errorf("could not create new request: %v", err)
  250. }
  251. resp, err := client.Do(req)
  252. if err != nil {
  253. return nil, fmt.Errorf("could not perform request: %v", err)
  254. }
  255. defer resp.Body.Close()
  256. if resp.StatusCode != http.StatusOK {
  257. body, _ := ioutil.ReadAll(resp.Body)
  258. return body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
  259. }
  260. return ioutil.ReadAll(resp.Body)
  261. }
  262. func deleteContainer(container string) error {
  263. container = strings.Replace(container, "\n", " ", -1)
  264. container = strings.Trim(container, " ")
  265. killArgs := fmt.Sprintf("kill %v", container)
  266. killSplitArgs := strings.Split(killArgs, " ")
  267. killCmd := exec.Command(dockerBinary, killSplitArgs...)
  268. runCommand(killCmd)
  269. rmArgs := fmt.Sprintf("rm -v %v", container)
  270. rmSplitArgs := strings.Split(rmArgs, " ")
  271. rmCmd := exec.Command(dockerBinary, rmSplitArgs...)
  272. exitCode, err := runCommand(rmCmd)
  273. // set error manually if not set
  274. if exitCode != 0 && err == nil {
  275. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  276. }
  277. return err
  278. }
  279. func getAllContainers() (string, error) {
  280. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  281. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  282. if exitCode != 0 && err == nil {
  283. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  284. }
  285. return out, err
  286. }
  287. func deleteAllContainers() error {
  288. containers, err := getAllContainers()
  289. if err != nil {
  290. fmt.Println(containers)
  291. return err
  292. }
  293. if err = deleteContainer(containers); err != nil {
  294. return err
  295. }
  296. return nil
  297. }
  298. func getPausedContainers() (string, error) {
  299. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  300. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  301. if exitCode != 0 && err == nil {
  302. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  303. }
  304. return out, err
  305. }
  306. func unpauseContainer(container string) error {
  307. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  308. exitCode, err := runCommand(unpauseCmd)
  309. if exitCode != 0 && err == nil {
  310. err = fmt.Errorf("failed to unpause container")
  311. }
  312. return nil
  313. }
  314. func unpauseAllContainers() error {
  315. containers, err := getPausedContainers()
  316. if err != nil {
  317. fmt.Println(containers)
  318. return err
  319. }
  320. containers = strings.Replace(containers, "\n", " ", -1)
  321. containers = strings.Trim(containers, " ")
  322. containerList := strings.Split(containers, " ")
  323. for _, value := range containerList {
  324. if err = unpauseContainer(value); err != nil {
  325. return err
  326. }
  327. }
  328. return nil
  329. }
  330. func deleteImages(images ...string) error {
  331. args := make([]string, 1, 2)
  332. args[0] = "rmi"
  333. args = append(args, images...)
  334. rmiCmd := exec.Command(dockerBinary, args...)
  335. exitCode, err := runCommand(rmiCmd)
  336. // set error manually if not set
  337. if exitCode != 0 && err == nil {
  338. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  339. }
  340. return err
  341. }
  342. func imageExists(image string) error {
  343. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  344. exitCode, err := runCommand(inspectCmd)
  345. if exitCode != 0 && err == nil {
  346. err = fmt.Errorf("couldn't find image %q", image)
  347. }
  348. return err
  349. }
  350. func pullImageIfNotExist(image string) (err error) {
  351. if err := imageExists(image); err != nil {
  352. pullCmd := exec.Command(dockerBinary, "pull", image)
  353. _, exitCode, err := runCommandWithOutput(pullCmd)
  354. if err != nil || exitCode != 0 {
  355. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  356. }
  357. }
  358. return
  359. }
  360. func dockerCmd(t *testing.T, args ...string) (string, int, error) {
  361. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  362. if err != nil {
  363. t.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  364. }
  365. return out, status, err
  366. }
  367. // execute a docker ocmmand with a timeout
  368. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  369. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  370. if err != nil {
  371. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  372. }
  373. return out, status, err
  374. }
  375. // execute a docker command in a directory
  376. func dockerCmdInDir(t *testing.T, path string, args ...string) (string, int, error) {
  377. dockerCommand := exec.Command(dockerBinary, args...)
  378. dockerCommand.Dir = path
  379. out, status, err := runCommandWithOutput(dockerCommand)
  380. if err != nil {
  381. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  382. }
  383. return out, status, err
  384. }
  385. // execute a docker command in a directory with a timeout
  386. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  387. dockerCommand := exec.Command(dockerBinary, args...)
  388. dockerCommand.Dir = path
  389. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  390. if err != nil {
  391. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  392. }
  393. return out, status, err
  394. }
  395. func findContainerIP(t *testing.T, id string) string {
  396. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  397. out, _, err := runCommandWithOutput(cmd)
  398. if err != nil {
  399. t.Fatal(err, out)
  400. }
  401. return strings.Trim(out, " \r\n'")
  402. }
  403. func getContainerCount() (int, error) {
  404. const containers = "Containers:"
  405. cmd := exec.Command(dockerBinary, "info")
  406. out, _, err := runCommandWithOutput(cmd)
  407. if err != nil {
  408. return 0, err
  409. }
  410. lines := strings.Split(out, "\n")
  411. for _, line := range lines {
  412. if strings.Contains(line, containers) {
  413. output := stripTrailingCharacters(line)
  414. output = strings.TrimLeft(output, containers)
  415. output = strings.Trim(output, " ")
  416. containerCount, err := strconv.Atoi(output)
  417. if err != nil {
  418. return 0, err
  419. }
  420. return containerCount, nil
  421. }
  422. }
  423. return 0, fmt.Errorf("couldn't find the Container count in the output")
  424. }
  425. type FakeContext struct {
  426. Dir string
  427. }
  428. func (f *FakeContext) Add(file, content string) error {
  429. filepath := path.Join(f.Dir, file)
  430. dirpath := path.Dir(filepath)
  431. if dirpath != "." {
  432. if err := os.MkdirAll(dirpath, 0755); err != nil {
  433. return err
  434. }
  435. }
  436. return ioutil.WriteFile(filepath, []byte(content), 0644)
  437. }
  438. func (f *FakeContext) Delete(file string) error {
  439. filepath := path.Join(f.Dir, file)
  440. return os.RemoveAll(filepath)
  441. }
  442. func (f *FakeContext) Close() error {
  443. return os.RemoveAll(f.Dir)
  444. }
  445. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  446. tmp, err := ioutil.TempDir("", "fake-context")
  447. if err != nil {
  448. return nil, err
  449. }
  450. if err := os.Chmod(tmp, 0755); err != nil {
  451. return nil, err
  452. }
  453. ctx := &FakeContext{tmp}
  454. for file, content := range files {
  455. if err := ctx.Add(file, content); err != nil {
  456. ctx.Close()
  457. return nil, err
  458. }
  459. }
  460. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  461. ctx.Close()
  462. return nil, err
  463. }
  464. return ctx, nil
  465. }
  466. type FakeStorage struct {
  467. *FakeContext
  468. *httptest.Server
  469. }
  470. func (f *FakeStorage) Close() error {
  471. f.Server.Close()
  472. return f.FakeContext.Close()
  473. }
  474. func fakeStorage(files map[string]string) (*FakeStorage, error) {
  475. tmp, err := ioutil.TempDir("", "fake-storage")
  476. if err != nil {
  477. return nil, err
  478. }
  479. ctx := &FakeContext{tmp}
  480. for file, content := range files {
  481. if err := ctx.Add(file, content); err != nil {
  482. ctx.Close()
  483. return nil, err
  484. }
  485. }
  486. handler := http.FileServer(http.Dir(ctx.Dir))
  487. server := httptest.NewServer(handler)
  488. return &FakeStorage{
  489. FakeContext: ctx,
  490. Server: server,
  491. }, nil
  492. }
  493. func inspectField(name, field string) (string, error) {
  494. format := fmt.Sprintf("{{.%s}}", field)
  495. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  496. out, exitCode, err := runCommandWithOutput(inspectCmd)
  497. if err != nil || exitCode != 0 {
  498. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  499. }
  500. return strings.TrimSpace(out), nil
  501. }
  502. func inspectFieldJSON(name, field string) (string, error) {
  503. format := fmt.Sprintf("{{json .%s}}", field)
  504. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  505. out, exitCode, err := runCommandWithOutput(inspectCmd)
  506. if err != nil || exitCode != 0 {
  507. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  508. }
  509. return strings.TrimSpace(out), nil
  510. }
  511. func inspectFieldMap(name, path, field string) (string, error) {
  512. format := fmt.Sprintf("{{index .%s %q}}", path, field)
  513. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  514. out, exitCode, err := runCommandWithOutput(inspectCmd)
  515. if err != nil || exitCode != 0 {
  516. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  517. }
  518. return strings.TrimSpace(out), nil
  519. }
  520. func getIDByName(name string) (string, error) {
  521. return inspectField(name, "Id")
  522. }
  523. // getContainerState returns the exit code of the container
  524. // and true if it's running
  525. // the exit code should be ignored if it's running
  526. func getContainerState(t *testing.T, id string) (int, bool, error) {
  527. var (
  528. exitStatus int
  529. running bool
  530. )
  531. out, exitCode, err := dockerCmd(t, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  532. if err != nil || exitCode != 0 {
  533. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, err)
  534. }
  535. out = strings.Trim(out, "\n")
  536. splitOutput := strings.Split(out, " ")
  537. if len(splitOutput) != 2 {
  538. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  539. }
  540. if splitOutput[0] == "true" {
  541. running = true
  542. }
  543. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  544. exitStatus = n
  545. } else {
  546. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  547. }
  548. return exitStatus, running, nil
  549. }
  550. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  551. args := []string{"build", "-t", name}
  552. if !useCache {
  553. args = append(args, "--no-cache")
  554. }
  555. args = append(args, "-")
  556. buildCmd := exec.Command(dockerBinary, args...)
  557. buildCmd.Stdin = strings.NewReader(dockerfile)
  558. out, exitCode, err := runCommandWithOutput(buildCmd)
  559. if err != nil || exitCode != 0 {
  560. return "", out, fmt.Errorf("failed to build the image: %s", out)
  561. }
  562. id, err := getIDByName(name)
  563. if err != nil {
  564. return "", out, err
  565. }
  566. return id, out, nil
  567. }
  568. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  569. args := []string{"build", "-t", name}
  570. if !useCache {
  571. args = append(args, "--no-cache")
  572. }
  573. args = append(args, "-")
  574. buildCmd := exec.Command(dockerBinary, args...)
  575. buildCmd.Stdin = strings.NewReader(dockerfile)
  576. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  577. if err != nil || exitCode != 0 {
  578. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  579. }
  580. id, err := getIDByName(name)
  581. if err != nil {
  582. return "", stdout, stderr, err
  583. }
  584. return id, stdout, stderr, nil
  585. }
  586. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  587. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  588. return id, err
  589. }
  590. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  591. args := []string{"build", "-t", name}
  592. if !useCache {
  593. args = append(args, "--no-cache")
  594. }
  595. args = append(args, ".")
  596. buildCmd := exec.Command(dockerBinary, args...)
  597. buildCmd.Dir = ctx.Dir
  598. out, exitCode, err := runCommandWithOutput(buildCmd)
  599. if err != nil || exitCode != 0 {
  600. return "", fmt.Errorf("failed to build the image: %s", out)
  601. }
  602. return getIDByName(name)
  603. }
  604. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  605. args := []string{"build", "-t", name}
  606. if !useCache {
  607. args = append(args, "--no-cache")
  608. }
  609. args = append(args, path)
  610. buildCmd := exec.Command(dockerBinary, args...)
  611. out, exitCode, err := runCommandWithOutput(buildCmd)
  612. if err != nil || exitCode != 0 {
  613. return "", fmt.Errorf("failed to build the image: %s", out)
  614. }
  615. return getIDByName(name)
  616. }
  617. type FakeGIT struct {
  618. *httptest.Server
  619. Root string
  620. RepoURL string
  621. }
  622. func (g *FakeGIT) Close() {
  623. g.Server.Close()
  624. os.RemoveAll(g.Root)
  625. }
  626. func fakeGIT(name string, files map[string]string) (*FakeGIT, error) {
  627. tmp, err := ioutil.TempDir("", "fake-git-repo")
  628. if err != nil {
  629. return nil, err
  630. }
  631. ctx := &FakeContext{tmp}
  632. for file, content := range files {
  633. if err := ctx.Add(file, content); err != nil {
  634. ctx.Close()
  635. return nil, err
  636. }
  637. }
  638. defer ctx.Close()
  639. curdir, err := os.Getwd()
  640. if err != nil {
  641. return nil, err
  642. }
  643. defer os.Chdir(curdir)
  644. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  645. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  646. }
  647. err = os.Chdir(ctx.Dir)
  648. if err != nil {
  649. return nil, err
  650. }
  651. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  652. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  653. }
  654. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  655. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  656. }
  657. root, err := ioutil.TempDir("", "docker-test-git-repo")
  658. if err != nil {
  659. return nil, err
  660. }
  661. repoPath := filepath.Join(root, name+".git")
  662. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  663. os.RemoveAll(root)
  664. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  665. }
  666. err = os.Chdir(repoPath)
  667. if err != nil {
  668. os.RemoveAll(root)
  669. return nil, err
  670. }
  671. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  672. os.RemoveAll(root)
  673. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  674. }
  675. err = os.Chdir(curdir)
  676. if err != nil {
  677. os.RemoveAll(root)
  678. return nil, err
  679. }
  680. handler := http.FileServer(http.Dir(root))
  681. server := httptest.NewServer(handler)
  682. return &FakeGIT{
  683. Server: server,
  684. Root: root,
  685. RepoURL: fmt.Sprintf("%s/%s.git", server.URL, name),
  686. }, nil
  687. }
  688. // Write `content` to the file at path `dst`, creating it if necessary,
  689. // as well as any missing directories.
  690. // The file is truncated if it already exists.
  691. // Call t.Fatal() at the first error.
  692. func writeFile(dst, content string, t *testing.T) {
  693. // Create subdirectories if necessary
  694. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  695. t.Fatal(err)
  696. }
  697. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  698. if err != nil {
  699. t.Fatal(err)
  700. }
  701. // Write content (truncate if it exists)
  702. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  703. t.Fatal(err)
  704. }
  705. }
  706. // Return the contents of file at path `src`.
  707. // Call t.Fatal() at the first error (including if the file doesn't exist)
  708. func readFile(src string, t *testing.T) (content string) {
  709. f, err := os.Open(src)
  710. if err != nil {
  711. t.Fatal(err)
  712. }
  713. data, err := ioutil.ReadAll(f)
  714. if err != nil {
  715. t.Fatal(err)
  716. }
  717. return string(data)
  718. }
  719. func containerStorageFile(containerId, basename string) string {
  720. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  721. }
  722. // docker commands that use this function must be run with the '-d' switch.
  723. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  724. out, _, err := runCommandWithOutput(cmd)
  725. if err != nil {
  726. return nil, fmt.Errorf("%v: %q", err, out)
  727. }
  728. time.Sleep(1 * time.Second)
  729. contID := strings.TrimSpace(out)
  730. return readContainerFile(contID, filename)
  731. }
  732. func readContainerFile(containerId, filename string) ([]byte, error) {
  733. f, err := os.Open(containerStorageFile(containerId, filename))
  734. if err != nil {
  735. return nil, err
  736. }
  737. defer f.Close()
  738. content, err := ioutil.ReadAll(f)
  739. if err != nil {
  740. return nil, err
  741. }
  742. return content, nil
  743. }