docker_utils.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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. "net/url"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/docker/docker/api"
  22. "github.com/docker/docker/pkg/ioutils"
  23. "github.com/docker/docker/pkg/stringutils"
  24. "github.com/go-check/check"
  25. )
  26. // Daemon represents a Docker daemon for the testing framework.
  27. type Daemon struct {
  28. c *check.C
  29. logFile *os.File
  30. folder string
  31. stdin io.WriteCloser
  32. stdout, stderr io.ReadCloser
  33. cmd *exec.Cmd
  34. storageDriver string
  35. execDriver string
  36. wait chan error
  37. }
  38. // NewDaemon returns a Daemon instance to be used for testing.
  39. // This will create a directory such as daemon123456789 in the folder specified by $DEST.
  40. // The daemon will not automatically start.
  41. func NewDaemon(c *check.C) *Daemon {
  42. dest := os.Getenv("DEST")
  43. if dest == "" {
  44. c.Fatal("Please set the DEST environment variable")
  45. }
  46. dir := filepath.Join(dest, fmt.Sprintf("daemon%d", time.Now().UnixNano()%100000000))
  47. daemonFolder, err := filepath.Abs(dir)
  48. if err != nil {
  49. c.Fatalf("Could not make %q an absolute path: %v", dir, err)
  50. }
  51. if err := os.MkdirAll(filepath.Join(daemonFolder, "graph"), 0600); err != nil {
  52. c.Fatalf("Could not create %s/graph directory", daemonFolder)
  53. }
  54. return &Daemon{
  55. c: c,
  56. folder: daemonFolder,
  57. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  58. execDriver: os.Getenv("DOCKER_EXECDRIVER"),
  59. }
  60. }
  61. // Start will start the daemon and return once it is ready to receive requests.
  62. // You can specify additional daemon flags.
  63. func (d *Daemon) Start(arg ...string) error {
  64. dockerBinary, err := exec.LookPath(dockerBinary)
  65. if err != nil {
  66. d.c.Fatalf("could not find docker binary in $PATH: %v", err)
  67. }
  68. args := []string{
  69. "--host", d.sock(),
  70. "--daemon",
  71. "--graph", fmt.Sprintf("%s/graph", d.folder),
  72. "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
  73. }
  74. // If we don't explicitly set the log-level or debug flag(-D) then
  75. // turn on debug mode
  76. foundIt := false
  77. for _, a := range arg {
  78. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") {
  79. foundIt = true
  80. }
  81. }
  82. if !foundIt {
  83. args = append(args, "--debug")
  84. }
  85. if d.storageDriver != "" {
  86. args = append(args, "--storage-driver", d.storageDriver)
  87. }
  88. if d.execDriver != "" {
  89. args = append(args, "--exec-driver", d.execDriver)
  90. }
  91. args = append(args, arg...)
  92. d.cmd = exec.Command(dockerBinary, args...)
  93. d.logFile, err = os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  94. if err != nil {
  95. d.c.Fatalf("Could not create %s/docker.log: %v", d.folder, err)
  96. }
  97. d.cmd.Stdout = d.logFile
  98. d.cmd.Stderr = d.logFile
  99. if err := d.cmd.Start(); err != nil {
  100. return fmt.Errorf("could not start daemon container: %v", err)
  101. }
  102. wait := make(chan error)
  103. go func() {
  104. wait <- d.cmd.Wait()
  105. d.c.Log("exiting daemon")
  106. close(wait)
  107. }()
  108. d.wait = wait
  109. tick := time.Tick(500 * time.Millisecond)
  110. // make sure daemon is ready to receive requests
  111. startTime := time.Now().Unix()
  112. for {
  113. d.c.Log("waiting for daemon to start")
  114. if time.Now().Unix()-startTime > 5 {
  115. // After 5 seconds, give up
  116. return errors.New("Daemon exited and never started")
  117. }
  118. select {
  119. case <-time.After(2 * time.Second):
  120. return errors.New("timeout: daemon does not respond")
  121. case <-tick:
  122. c, err := net.Dial("unix", filepath.Join(d.folder, "docker.sock"))
  123. if err != nil {
  124. continue
  125. }
  126. client := httputil.NewClientConn(c, nil)
  127. defer client.Close()
  128. req, err := http.NewRequest("GET", "/_ping", nil)
  129. if err != nil {
  130. d.c.Fatalf("could not create new request: %v", err)
  131. }
  132. resp, err := client.Do(req)
  133. if err != nil {
  134. continue
  135. }
  136. if resp.StatusCode != http.StatusOK {
  137. d.c.Logf("received status != 200 OK: %s", resp.Status)
  138. }
  139. d.c.Log("daemon started")
  140. return nil
  141. }
  142. }
  143. }
  144. // StartWithBusybox will first start the daemon with Daemon.Start()
  145. // then save the busybox image from the main daemon and load it into this Daemon instance.
  146. func (d *Daemon) StartWithBusybox(arg ...string) error {
  147. if err := d.Start(arg...); err != nil {
  148. return err
  149. }
  150. bb := filepath.Join(d.folder, "busybox.tar")
  151. if _, err := os.Stat(bb); err != nil {
  152. if !os.IsNotExist(err) {
  153. return fmt.Errorf("unexpected error on busybox.tar stat: %v", err)
  154. }
  155. // saving busybox image from main daemon
  156. if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil {
  157. return fmt.Errorf("could not save busybox image: %v", err)
  158. }
  159. }
  160. // loading busybox image to this daemon
  161. if _, err := d.Cmd("load", "--input", bb); err != nil {
  162. return fmt.Errorf("could not load busybox image: %v", err)
  163. }
  164. if err := os.Remove(bb); err != nil {
  165. d.c.Logf("Could not remove %s: %v", bb, err)
  166. }
  167. return nil
  168. }
  169. // Stop will send a SIGINT every second and wait for the daemon to stop.
  170. // If it timeouts, a SIGKILL is sent.
  171. // Stop will not delete the daemon directory. If a purged daemon is needed,
  172. // instantiate a new one with NewDaemon.
  173. func (d *Daemon) Stop() error {
  174. if d.cmd == nil || d.wait == nil {
  175. return errors.New("daemon not started")
  176. }
  177. defer func() {
  178. d.logFile.Close()
  179. d.cmd = nil
  180. }()
  181. i := 1
  182. tick := time.Tick(time.Second)
  183. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  184. return fmt.Errorf("could not send signal: %v", err)
  185. }
  186. out1:
  187. for {
  188. select {
  189. case err := <-d.wait:
  190. return err
  191. case <-time.After(15 * time.Second):
  192. // time for stopping jobs and run onShutdown hooks
  193. d.c.Log("timeout")
  194. break out1
  195. }
  196. }
  197. out2:
  198. for {
  199. select {
  200. case err := <-d.wait:
  201. return err
  202. case <-tick:
  203. i++
  204. if i > 4 {
  205. d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  206. break out2
  207. }
  208. d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  209. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  210. return fmt.Errorf("could not send signal: %v", err)
  211. }
  212. }
  213. }
  214. if err := d.cmd.Process.Kill(); err != nil {
  215. d.c.Logf("Could not kill daemon: %v", err)
  216. return err
  217. }
  218. return nil
  219. }
  220. // Restart will restart the daemon by first stopping it and then starting it.
  221. func (d *Daemon) Restart(arg ...string) error {
  222. d.Stop()
  223. return d.Start(arg...)
  224. }
  225. func (d *Daemon) sock() string {
  226. return fmt.Sprintf("unix://%s/docker.sock", d.folder)
  227. }
  228. // Cmd will execute a docker CLI command against this Daemon.
  229. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  230. func (d *Daemon) Cmd(name string, arg ...string) (string, error) {
  231. args := []string{"--host", d.sock(), name}
  232. args = append(args, arg...)
  233. c := exec.Command(dockerBinary, args...)
  234. b, err := c.CombinedOutput()
  235. return string(b), err
  236. }
  237. func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) {
  238. args := append(daemonArgs, name)
  239. args = append(args, arg...)
  240. c := exec.Command(dockerBinary, args...)
  241. b, err := c.CombinedOutput()
  242. return string(b), err
  243. }
  244. func (d *Daemon) LogfileName() string {
  245. return d.logFile.Name()
  246. }
  247. func daemonHost() string {
  248. daemonUrlStr := "unix://" + api.DEFAULTUNIXSOCKET
  249. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  250. daemonUrlStr = daemonHostVar
  251. }
  252. return daemonUrlStr
  253. }
  254. func sockConn(timeout time.Duration) (net.Conn, error) {
  255. daemon := daemonHost()
  256. daemonUrl, err := url.Parse(daemon)
  257. if err != nil {
  258. return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
  259. }
  260. var c net.Conn
  261. switch daemonUrl.Scheme {
  262. case "unix":
  263. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Path, timeout)
  264. case "tcp":
  265. return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Host, timeout)
  266. default:
  267. return c, fmt.Errorf("unknown scheme %v (%s)", daemonUrl.Scheme, daemon)
  268. }
  269. }
  270. func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  271. jsonData := bytes.NewBuffer(nil)
  272. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  273. return -1, nil, err
  274. }
  275. status, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
  276. if err != nil {
  277. b, _ := ioutil.ReadAll(body)
  278. return status, b, err
  279. }
  280. var b []byte
  281. b, err = readBody(body)
  282. return status, b, err
  283. }
  284. func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (int, io.ReadCloser, error) {
  285. c, err := sockConn(time.Duration(10 * time.Second))
  286. if err != nil {
  287. return -1, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  288. }
  289. client := httputil.NewClientConn(c, nil)
  290. req, err := http.NewRequest(method, endpoint, data)
  291. if err != nil {
  292. client.Close()
  293. return -1, nil, fmt.Errorf("could not create new request: %v", err)
  294. }
  295. if ct != "" {
  296. req.Header.Set("Content-Type", ct)
  297. }
  298. resp, err := client.Do(req)
  299. if err != nil {
  300. client.Close()
  301. return -1, nil, fmt.Errorf("could not perform request: %v", err)
  302. }
  303. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  304. defer client.Close()
  305. return resp.Body.Close()
  306. })
  307. if resp.StatusCode != http.StatusOK {
  308. return resp.StatusCode, body, fmt.Errorf("received status != 200 OK: %s", resp.Status)
  309. }
  310. return resp.StatusCode, body, err
  311. }
  312. func readBody(b io.ReadCloser) ([]byte, error) {
  313. defer b.Close()
  314. return ioutil.ReadAll(b)
  315. }
  316. func deleteContainer(container string) error {
  317. container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
  318. killArgs := strings.Split(fmt.Sprintf("kill %v", container), " ")
  319. runCommand(exec.Command(dockerBinary, killArgs...))
  320. rmArgs := strings.Split(fmt.Sprintf("rm -v %v", container), " ")
  321. exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
  322. // set error manually if not set
  323. if exitCode != 0 && err == nil {
  324. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  325. }
  326. return err
  327. }
  328. func getAllContainers() (string, error) {
  329. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  330. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  331. if exitCode != 0 && err == nil {
  332. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  333. }
  334. return out, err
  335. }
  336. func deleteAllContainers() error {
  337. containers, err := getAllContainers()
  338. if err != nil {
  339. fmt.Println(containers)
  340. return err
  341. }
  342. if err = deleteContainer(containers); err != nil {
  343. return err
  344. }
  345. return nil
  346. }
  347. func getPausedContainers() (string, error) {
  348. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  349. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  350. if exitCode != 0 && err == nil {
  351. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  352. }
  353. return out, err
  354. }
  355. func getSliceOfPausedContainers() ([]string, error) {
  356. out, err := getPausedContainers()
  357. if err == nil {
  358. if len(out) == 0 {
  359. return nil, err
  360. }
  361. slice := strings.Split(strings.TrimSpace(out), "\n")
  362. return slice, err
  363. }
  364. return []string{out}, err
  365. }
  366. func unpauseContainer(container string) error {
  367. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  368. exitCode, err := runCommand(unpauseCmd)
  369. if exitCode != 0 && err == nil {
  370. err = fmt.Errorf("failed to unpause container")
  371. }
  372. return nil
  373. }
  374. func unpauseAllContainers() error {
  375. containers, err := getPausedContainers()
  376. if err != nil {
  377. fmt.Println(containers)
  378. return err
  379. }
  380. containers = strings.Replace(containers, "\n", " ", -1)
  381. containers = strings.Trim(containers, " ")
  382. containerList := strings.Split(containers, " ")
  383. for _, value := range containerList {
  384. if err = unpauseContainer(value); err != nil {
  385. return err
  386. }
  387. }
  388. return nil
  389. }
  390. func deleteImages(images ...string) error {
  391. args := make([]string, 1, 2)
  392. args[0] = "rmi"
  393. args = append(args, images...)
  394. rmiCmd := exec.Command(dockerBinary, args...)
  395. exitCode, err := runCommand(rmiCmd)
  396. // set error manually if not set
  397. if exitCode != 0 && err == nil {
  398. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  399. }
  400. return err
  401. }
  402. func imageExists(image string) error {
  403. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  404. exitCode, err := runCommand(inspectCmd)
  405. if exitCode != 0 && err == nil {
  406. err = fmt.Errorf("couldn't find image %q", image)
  407. }
  408. return err
  409. }
  410. func pullImageIfNotExist(image string) (err error) {
  411. if err := imageExists(image); err != nil {
  412. pullCmd := exec.Command(dockerBinary, "pull", image)
  413. _, exitCode, err := runCommandWithOutput(pullCmd)
  414. if err != nil || exitCode != 0 {
  415. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  416. }
  417. }
  418. return
  419. }
  420. func dockerCmd(c *check.C, args ...string) (string, int) {
  421. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  422. if err != nil {
  423. c.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  424. }
  425. return out, status
  426. }
  427. // execute a docker command with a timeout
  428. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  429. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  430. if err != nil {
  431. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  432. }
  433. return out, status, err
  434. }
  435. // execute a docker command in a directory
  436. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  437. dockerCommand := exec.Command(dockerBinary, args...)
  438. dockerCommand.Dir = path
  439. out, status, err := runCommandWithOutput(dockerCommand)
  440. if err != nil {
  441. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  442. }
  443. return out, status, err
  444. }
  445. // execute a docker command in a directory with a timeout
  446. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  447. dockerCommand := exec.Command(dockerBinary, args...)
  448. dockerCommand.Dir = path
  449. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  450. if err != nil {
  451. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  452. }
  453. return out, status, err
  454. }
  455. func findContainerIP(c *check.C, id string) string {
  456. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  457. out, _, err := runCommandWithOutput(cmd)
  458. if err != nil {
  459. c.Fatal(err, out)
  460. }
  461. return strings.Trim(out, " \r\n'")
  462. }
  463. func getContainerCount() (int, error) {
  464. const containers = "Containers:"
  465. cmd := exec.Command(dockerBinary, "info")
  466. out, _, err := runCommandWithOutput(cmd)
  467. if err != nil {
  468. return 0, err
  469. }
  470. lines := strings.Split(out, "\n")
  471. for _, line := range lines {
  472. if strings.Contains(line, containers) {
  473. output := strings.TrimSpace(line)
  474. output = strings.TrimLeft(output, containers)
  475. output = strings.Trim(output, " ")
  476. containerCount, err := strconv.Atoi(output)
  477. if err != nil {
  478. return 0, err
  479. }
  480. return containerCount, nil
  481. }
  482. }
  483. return 0, fmt.Errorf("couldn't find the Container count in the output")
  484. }
  485. type FakeContext struct {
  486. Dir string
  487. }
  488. func (f *FakeContext) Add(file, content string) error {
  489. filepath := path.Join(f.Dir, file)
  490. dirpath := path.Dir(filepath)
  491. if dirpath != "." {
  492. if err := os.MkdirAll(dirpath, 0755); err != nil {
  493. return err
  494. }
  495. }
  496. return ioutil.WriteFile(filepath, []byte(content), 0644)
  497. }
  498. func (f *FakeContext) Delete(file string) error {
  499. filepath := path.Join(f.Dir, file)
  500. return os.RemoveAll(filepath)
  501. }
  502. func (f *FakeContext) Close() error {
  503. return os.RemoveAll(f.Dir)
  504. }
  505. func fakeContextFromDir(dir string) *FakeContext {
  506. return &FakeContext{dir}
  507. }
  508. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  509. tmp, err := ioutil.TempDir("", "fake-context")
  510. if err != nil {
  511. return nil, err
  512. }
  513. if err := os.Chmod(tmp, 0755); err != nil {
  514. return nil, err
  515. }
  516. ctx := fakeContextFromDir(tmp)
  517. for file, content := range files {
  518. if err := ctx.Add(file, content); err != nil {
  519. ctx.Close()
  520. return nil, err
  521. }
  522. }
  523. return ctx, nil
  524. }
  525. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  526. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  527. ctx.Close()
  528. return err
  529. }
  530. return nil
  531. }
  532. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  533. ctx, err := fakeContextWithFiles(files)
  534. if err != nil {
  535. ctx.Close()
  536. return nil, err
  537. }
  538. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  539. return nil, err
  540. }
  541. return ctx, nil
  542. }
  543. // FakeStorage is a static file server. It might be running locally or remotely
  544. // on test host.
  545. type FakeStorage interface {
  546. Close() error
  547. URL() string
  548. CtxDir() string
  549. }
  550. // fakeStorage returns either a local or remote (at daemon machine) file server
  551. func fakeStorage(files map[string]string) (FakeStorage, error) {
  552. ctx, err := fakeContextWithFiles(files)
  553. if err != nil {
  554. return nil, err
  555. }
  556. return fakeStorageWithContext(ctx)
  557. }
  558. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  559. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  560. if isLocalDaemon {
  561. return newLocalFakeStorage(ctx)
  562. }
  563. return newRemoteFileServer(ctx)
  564. }
  565. // localFileStorage is a file storage on the running machine
  566. type localFileStorage struct {
  567. *FakeContext
  568. *httptest.Server
  569. }
  570. func (s *localFileStorage) URL() string {
  571. return s.Server.URL
  572. }
  573. func (s *localFileStorage) CtxDir() string {
  574. return s.FakeContext.Dir
  575. }
  576. func (s *localFileStorage) Close() error {
  577. defer s.Server.Close()
  578. return s.FakeContext.Close()
  579. }
  580. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  581. handler := http.FileServer(http.Dir(ctx.Dir))
  582. server := httptest.NewServer(handler)
  583. return &localFileStorage{
  584. FakeContext: ctx,
  585. Server: server,
  586. }, nil
  587. }
  588. // remoteFileServer is a containerized static file server started on the remote
  589. // testing machine to be used in URL-accepting docker build functionality.
  590. type remoteFileServer struct {
  591. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  592. container string
  593. image string
  594. ctx *FakeContext
  595. }
  596. func (f *remoteFileServer) URL() string {
  597. u := url.URL{
  598. Scheme: "http",
  599. Host: f.host}
  600. return u.String()
  601. }
  602. func (f *remoteFileServer) CtxDir() string {
  603. return f.ctx.Dir
  604. }
  605. func (f *remoteFileServer) Close() error {
  606. defer func() {
  607. if f.ctx != nil {
  608. f.ctx.Close()
  609. }
  610. if f.image != "" {
  611. deleteImages(f.image)
  612. }
  613. }()
  614. if f.container == "" {
  615. return nil
  616. }
  617. return deleteContainer(f.container)
  618. }
  619. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  620. var (
  621. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  622. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  623. )
  624. // Build the image
  625. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  626. COPY . /static`); err != nil {
  627. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  628. }
  629. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  630. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  631. }
  632. // Start the container
  633. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  634. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  635. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  636. }
  637. // Find out the system assigned port
  638. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  639. if err != nil {
  640. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  641. }
  642. return &remoteFileServer{
  643. container: container,
  644. image: image,
  645. host: strings.Trim(out, "\n"),
  646. ctx: ctx}, nil
  647. }
  648. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  649. str, err := inspectFieldJSON(name, field)
  650. if err != nil {
  651. return err
  652. }
  653. return json.Unmarshal([]byte(str), output)
  654. }
  655. func inspectFilter(name, filter string) (string, error) {
  656. format := fmt.Sprintf("{{%s}}", filter)
  657. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  658. out, exitCode, err := runCommandWithOutput(inspectCmd)
  659. if err != nil || exitCode != 0 {
  660. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  661. }
  662. return strings.TrimSpace(out), nil
  663. }
  664. func inspectField(name, field string) (string, error) {
  665. return inspectFilter(name, fmt.Sprintf(".%s", field))
  666. }
  667. func inspectFieldJSON(name, field string) (string, error) {
  668. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  669. }
  670. func inspectFieldMap(name, path, field string) (string, error) {
  671. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  672. }
  673. func getIDByName(name string) (string, error) {
  674. return inspectField(name, "Id")
  675. }
  676. // getContainerState returns the exit code of the container
  677. // and true if it's running
  678. // the exit code should be ignored if it's running
  679. func getContainerState(c *check.C, id string) (int, bool, error) {
  680. var (
  681. exitStatus int
  682. running bool
  683. )
  684. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  685. if exitCode != 0 {
  686. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  687. }
  688. out = strings.Trim(out, "\n")
  689. splitOutput := strings.Split(out, " ")
  690. if len(splitOutput) != 2 {
  691. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  692. }
  693. if splitOutput[0] == "true" {
  694. running = true
  695. }
  696. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  697. exitStatus = n
  698. } else {
  699. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  700. }
  701. return exitStatus, running, nil
  702. }
  703. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  704. args := []string{"build", "-t", name}
  705. if !useCache {
  706. args = append(args, "--no-cache")
  707. }
  708. args = append(args, "-")
  709. buildCmd := exec.Command(dockerBinary, args...)
  710. buildCmd.Stdin = strings.NewReader(dockerfile)
  711. out, exitCode, err := runCommandWithOutput(buildCmd)
  712. if err != nil || exitCode != 0 {
  713. return "", out, fmt.Errorf("failed to build the image: %s", out)
  714. }
  715. id, err := getIDByName(name)
  716. if err != nil {
  717. return "", out, err
  718. }
  719. return id, out, nil
  720. }
  721. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  722. args := []string{"build", "-t", name}
  723. if !useCache {
  724. args = append(args, "--no-cache")
  725. }
  726. args = append(args, "-")
  727. buildCmd := exec.Command(dockerBinary, args...)
  728. buildCmd.Stdin = strings.NewReader(dockerfile)
  729. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  730. if err != nil || exitCode != 0 {
  731. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  732. }
  733. id, err := getIDByName(name)
  734. if err != nil {
  735. return "", stdout, stderr, err
  736. }
  737. return id, stdout, stderr, nil
  738. }
  739. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  740. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  741. return id, err
  742. }
  743. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  744. args := []string{"build", "-t", name}
  745. if !useCache {
  746. args = append(args, "--no-cache")
  747. }
  748. args = append(args, ".")
  749. buildCmd := exec.Command(dockerBinary, args...)
  750. buildCmd.Dir = ctx.Dir
  751. out, exitCode, err := runCommandWithOutput(buildCmd)
  752. if err != nil || exitCode != 0 {
  753. return "", fmt.Errorf("failed to build the image: %s", out)
  754. }
  755. return getIDByName(name)
  756. }
  757. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  758. args := []string{"build", "-t", name}
  759. if !useCache {
  760. args = append(args, "--no-cache")
  761. }
  762. args = append(args, path)
  763. buildCmd := exec.Command(dockerBinary, args...)
  764. out, exitCode, err := runCommandWithOutput(buildCmd)
  765. if err != nil || exitCode != 0 {
  766. return "", fmt.Errorf("failed to build the image: %s", out)
  767. }
  768. return getIDByName(name)
  769. }
  770. type GitServer interface {
  771. URL() string
  772. Close() error
  773. }
  774. type localGitServer struct {
  775. *httptest.Server
  776. }
  777. func (r *localGitServer) Close() error {
  778. r.Server.Close()
  779. return nil
  780. }
  781. func (r *localGitServer) URL() string {
  782. return r.Server.URL
  783. }
  784. type FakeGIT struct {
  785. root string
  786. server GitServer
  787. RepoURL string
  788. }
  789. func (g *FakeGIT) Close() {
  790. g.server.Close()
  791. os.RemoveAll(g.root)
  792. }
  793. func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) {
  794. ctx, err := fakeContextWithFiles(files)
  795. if err != nil {
  796. return nil, err
  797. }
  798. defer ctx.Close()
  799. curdir, err := os.Getwd()
  800. if err != nil {
  801. return nil, err
  802. }
  803. defer os.Chdir(curdir)
  804. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  805. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  806. }
  807. err = os.Chdir(ctx.Dir)
  808. if err != nil {
  809. return nil, err
  810. }
  811. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  812. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  813. }
  814. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  815. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  816. }
  817. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  818. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  819. }
  820. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  821. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  822. }
  823. root, err := ioutil.TempDir("", "docker-test-git-repo")
  824. if err != nil {
  825. return nil, err
  826. }
  827. repoPath := filepath.Join(root, name+".git")
  828. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  829. os.RemoveAll(root)
  830. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  831. }
  832. err = os.Chdir(repoPath)
  833. if err != nil {
  834. os.RemoveAll(root)
  835. return nil, err
  836. }
  837. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  838. os.RemoveAll(root)
  839. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  840. }
  841. err = os.Chdir(curdir)
  842. if err != nil {
  843. os.RemoveAll(root)
  844. return nil, err
  845. }
  846. var server GitServer
  847. if !enforceLocalServer {
  848. // use fakeStorage server, which might be local or remote (at test daemon)
  849. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  850. if err != nil {
  851. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  852. }
  853. } else {
  854. // always start a local http server on CLI test machin
  855. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  856. server = &localGitServer{httpServer}
  857. }
  858. return &FakeGIT{
  859. root: root,
  860. server: server,
  861. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  862. }, nil
  863. }
  864. // Write `content` to the file at path `dst`, creating it if necessary,
  865. // as well as any missing directories.
  866. // The file is truncated if it already exists.
  867. // Call c.Fatal() at the first error.
  868. func writeFile(dst, content string, c *check.C) {
  869. // Create subdirectories if necessary
  870. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  871. c.Fatal(err)
  872. }
  873. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  874. if err != nil {
  875. c.Fatal(err)
  876. }
  877. // Write content (truncate if it exists)
  878. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  879. c.Fatal(err)
  880. }
  881. }
  882. // Return the contents of file at path `src`.
  883. // Call c.Fatal() at the first error (including if the file doesn't exist)
  884. func readFile(src string, c *check.C) (content string) {
  885. data, err := ioutil.ReadFile(src)
  886. if err != nil {
  887. c.Fatal(err)
  888. }
  889. return string(data)
  890. }
  891. func containerStorageFile(containerId, basename string) string {
  892. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  893. }
  894. // docker commands that use this function must be run with the '-d' switch.
  895. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  896. out, _, err := runCommandWithOutput(cmd)
  897. if err != nil {
  898. return nil, fmt.Errorf("%v: %q", err, out)
  899. }
  900. time.Sleep(1 * time.Second)
  901. contID := strings.TrimSpace(out)
  902. return readContainerFile(contID, filename)
  903. }
  904. func readContainerFile(containerId, filename string) ([]byte, error) {
  905. f, err := os.Open(containerStorageFile(containerId, filename))
  906. if err != nil {
  907. return nil, err
  908. }
  909. defer f.Close()
  910. content, err := ioutil.ReadAll(f)
  911. if err != nil {
  912. return nil, err
  913. }
  914. return content, nil
  915. }
  916. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  917. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  918. return []byte(out), err
  919. }
  920. // daemonTime provides the current time on the daemon host
  921. func daemonTime(c *check.C) time.Time {
  922. if isLocalDaemon {
  923. return time.Now()
  924. }
  925. _, body, err := sockRequest("GET", "/info", nil)
  926. if err != nil {
  927. c.Fatalf("daemonTime: failed to get /info: %v", err)
  928. }
  929. type infoJSON struct {
  930. SystemTime string
  931. }
  932. var info infoJSON
  933. if err = json.Unmarshal(body, &info); err != nil {
  934. c.Fatalf("unable to unmarshal /info response: %v", err)
  935. }
  936. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  937. if err != nil {
  938. c.Fatal(err)
  939. }
  940. return dt
  941. }
  942. func setupRegistry(c *check.C) func() {
  943. testRequires(c, RegistryHosting)
  944. reg, err := newTestRegistryV2(c)
  945. if err != nil {
  946. c.Fatal(err)
  947. }
  948. // Wait for registry to be ready to serve requests.
  949. for i := 0; i != 5; i++ {
  950. if err = reg.Ping(); err == nil {
  951. break
  952. }
  953. time.Sleep(100 * time.Millisecond)
  954. }
  955. if err != nil {
  956. c.Fatal("Timeout waiting for test registry to become available")
  957. }
  958. return func() { reg.Close() }
  959. }
  960. // appendBaseEnv appends the minimum set of environment variables to exec the
  961. // docker cli binary for testing with correct configuration to the given env
  962. // list.
  963. func appendBaseEnv(env []string) []string {
  964. preserveList := []string{
  965. // preserve remote test host
  966. "DOCKER_HOST",
  967. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  968. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  969. "SystemRoot",
  970. }
  971. for _, key := range preserveList {
  972. if val := os.Getenv(key); val != "" {
  973. env = append(env, fmt.Sprintf("%s=%s", key, val))
  974. }
  975. }
  976. return env
  977. }