docker_utils.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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/opts"
  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://" + opts.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 := []string{"rmi", "-f"}
  392. args = append(args, images...)
  393. rmiCmd := exec.Command(dockerBinary, args...)
  394. exitCode, err := runCommand(rmiCmd)
  395. // set error manually if not set
  396. if exitCode != 0 && err == nil {
  397. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  398. }
  399. return err
  400. }
  401. func imageExists(image string) error {
  402. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  403. exitCode, err := runCommand(inspectCmd)
  404. if exitCode != 0 && err == nil {
  405. err = fmt.Errorf("couldn't find image %q", image)
  406. }
  407. return err
  408. }
  409. func pullImageIfNotExist(image string) (err error) {
  410. if err := imageExists(image); err != nil {
  411. pullCmd := exec.Command(dockerBinary, "pull", image)
  412. _, exitCode, err := runCommandWithOutput(pullCmd)
  413. if err != nil || exitCode != 0 {
  414. err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  415. }
  416. }
  417. return
  418. }
  419. func dockerCmd(c *check.C, args ...string) (string, int) {
  420. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  421. if err != nil {
  422. c.Fatalf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)
  423. }
  424. return out, status
  425. }
  426. // execute a docker command with a timeout
  427. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  428. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  429. if err != nil {
  430. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  431. }
  432. return out, status, err
  433. }
  434. // execute a docker command in a directory
  435. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  436. dockerCommand := exec.Command(dockerBinary, args...)
  437. dockerCommand.Dir = path
  438. out, status, err := runCommandWithOutput(dockerCommand)
  439. if err != nil {
  440. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  441. }
  442. return out, status, err
  443. }
  444. // execute a docker command in a directory with a timeout
  445. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  446. dockerCommand := exec.Command(dockerBinary, args...)
  447. dockerCommand.Dir = path
  448. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  449. if err != nil {
  450. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  451. }
  452. return out, status, err
  453. }
  454. func findContainerIP(c *check.C, id string) string {
  455. cmd := exec.Command(dockerBinary, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  456. out, _, err := runCommandWithOutput(cmd)
  457. if err != nil {
  458. c.Fatal(err, out)
  459. }
  460. return strings.Trim(out, " \r\n'")
  461. }
  462. func getContainerCount() (int, error) {
  463. const containers = "Containers:"
  464. cmd := exec.Command(dockerBinary, "info")
  465. out, _, err := runCommandWithOutput(cmd)
  466. if err != nil {
  467. return 0, err
  468. }
  469. lines := strings.Split(out, "\n")
  470. for _, line := range lines {
  471. if strings.Contains(line, containers) {
  472. output := strings.TrimSpace(line)
  473. output = strings.TrimLeft(output, containers)
  474. output = strings.Trim(output, " ")
  475. containerCount, err := strconv.Atoi(output)
  476. if err != nil {
  477. return 0, err
  478. }
  479. return containerCount, nil
  480. }
  481. }
  482. return 0, fmt.Errorf("couldn't find the Container count in the output")
  483. }
  484. type FakeContext struct {
  485. Dir string
  486. }
  487. func (f *FakeContext) Add(file, content string) error {
  488. filepath := path.Join(f.Dir, file)
  489. dirpath := path.Dir(filepath)
  490. if dirpath != "." {
  491. if err := os.MkdirAll(dirpath, 0755); err != nil {
  492. return err
  493. }
  494. }
  495. return ioutil.WriteFile(filepath, []byte(content), 0644)
  496. }
  497. func (f *FakeContext) Delete(file string) error {
  498. filepath := path.Join(f.Dir, file)
  499. return os.RemoveAll(filepath)
  500. }
  501. func (f *FakeContext) Close() error {
  502. return os.RemoveAll(f.Dir)
  503. }
  504. func fakeContextFromDir(dir string) *FakeContext {
  505. return &FakeContext{dir}
  506. }
  507. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  508. tmp, err := ioutil.TempDir("", "fake-context")
  509. if err != nil {
  510. return nil, err
  511. }
  512. if err := os.Chmod(tmp, 0755); err != nil {
  513. return nil, err
  514. }
  515. ctx := fakeContextFromDir(tmp)
  516. for file, content := range files {
  517. if err := ctx.Add(file, content); err != nil {
  518. ctx.Close()
  519. return nil, err
  520. }
  521. }
  522. return ctx, nil
  523. }
  524. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  525. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  526. ctx.Close()
  527. return err
  528. }
  529. return nil
  530. }
  531. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  532. ctx, err := fakeContextWithFiles(files)
  533. if err != nil {
  534. ctx.Close()
  535. return nil, err
  536. }
  537. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  538. return nil, err
  539. }
  540. return ctx, nil
  541. }
  542. // FakeStorage is a static file server. It might be running locally or remotely
  543. // on test host.
  544. type FakeStorage interface {
  545. Close() error
  546. URL() string
  547. CtxDir() string
  548. }
  549. // fakeStorage returns either a local or remote (at daemon machine) file server
  550. func fakeStorage(files map[string]string) (FakeStorage, error) {
  551. ctx, err := fakeContextWithFiles(files)
  552. if err != nil {
  553. return nil, err
  554. }
  555. return fakeStorageWithContext(ctx)
  556. }
  557. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  558. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  559. if isLocalDaemon {
  560. return newLocalFakeStorage(ctx)
  561. }
  562. return newRemoteFileServer(ctx)
  563. }
  564. // localFileStorage is a file storage on the running machine
  565. type localFileStorage struct {
  566. *FakeContext
  567. *httptest.Server
  568. }
  569. func (s *localFileStorage) URL() string {
  570. return s.Server.URL
  571. }
  572. func (s *localFileStorage) CtxDir() string {
  573. return s.FakeContext.Dir
  574. }
  575. func (s *localFileStorage) Close() error {
  576. defer s.Server.Close()
  577. return s.FakeContext.Close()
  578. }
  579. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  580. handler := http.FileServer(http.Dir(ctx.Dir))
  581. server := httptest.NewServer(handler)
  582. return &localFileStorage{
  583. FakeContext: ctx,
  584. Server: server,
  585. }, nil
  586. }
  587. // remoteFileServer is a containerized static file server started on the remote
  588. // testing machine to be used in URL-accepting docker build functionality.
  589. type remoteFileServer struct {
  590. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  591. container string
  592. image string
  593. ctx *FakeContext
  594. }
  595. func (f *remoteFileServer) URL() string {
  596. u := url.URL{
  597. Scheme: "http",
  598. Host: f.host}
  599. return u.String()
  600. }
  601. func (f *remoteFileServer) CtxDir() string {
  602. return f.ctx.Dir
  603. }
  604. func (f *remoteFileServer) Close() error {
  605. defer func() {
  606. if f.ctx != nil {
  607. f.ctx.Close()
  608. }
  609. if f.image != "" {
  610. deleteImages(f.image)
  611. }
  612. }()
  613. if f.container == "" {
  614. return nil
  615. }
  616. return deleteContainer(f.container)
  617. }
  618. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  619. var (
  620. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  621. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  622. )
  623. // Build the image
  624. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  625. COPY . /static`); err != nil {
  626. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  627. }
  628. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  629. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  630. }
  631. // Start the container
  632. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  633. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  634. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  635. }
  636. // Find out the system assigned port
  637. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  638. if err != nil {
  639. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  640. }
  641. return &remoteFileServer{
  642. container: container,
  643. image: image,
  644. host: strings.Trim(out, "\n"),
  645. ctx: ctx}, nil
  646. }
  647. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  648. str, err := inspectFieldJSON(name, field)
  649. if err != nil {
  650. return err
  651. }
  652. return json.Unmarshal([]byte(str), output)
  653. }
  654. func inspectFilter(name, filter string) (string, error) {
  655. format := fmt.Sprintf("{{%s}}", filter)
  656. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  657. out, exitCode, err := runCommandWithOutput(inspectCmd)
  658. if err != nil || exitCode != 0 {
  659. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  660. }
  661. return strings.TrimSpace(out), nil
  662. }
  663. func inspectField(name, field string) (string, error) {
  664. return inspectFilter(name, fmt.Sprintf(".%s", field))
  665. }
  666. func inspectFieldJSON(name, field string) (string, error) {
  667. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  668. }
  669. func inspectFieldMap(name, path, field string) (string, error) {
  670. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  671. }
  672. func getIDByName(name string) (string, error) {
  673. return inspectField(name, "Id")
  674. }
  675. // getContainerState returns the exit code of the container
  676. // and true if it's running
  677. // the exit code should be ignored if it's running
  678. func getContainerState(c *check.C, id string) (int, bool, error) {
  679. var (
  680. exitStatus int
  681. running bool
  682. )
  683. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  684. if exitCode != 0 {
  685. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  686. }
  687. out = strings.Trim(out, "\n")
  688. splitOutput := strings.Split(out, " ")
  689. if len(splitOutput) != 2 {
  690. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  691. }
  692. if splitOutput[0] == "true" {
  693. running = true
  694. }
  695. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  696. exitStatus = n
  697. } else {
  698. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  699. }
  700. return exitStatus, running, nil
  701. }
  702. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  703. args := []string{"build", "-t", name}
  704. if !useCache {
  705. args = append(args, "--no-cache")
  706. }
  707. args = append(args, "-")
  708. buildCmd := exec.Command(dockerBinary, args...)
  709. buildCmd.Stdin = strings.NewReader(dockerfile)
  710. out, exitCode, err := runCommandWithOutput(buildCmd)
  711. if err != nil || exitCode != 0 {
  712. return "", out, fmt.Errorf("failed to build the image: %s", out)
  713. }
  714. id, err := getIDByName(name)
  715. if err != nil {
  716. return "", out, err
  717. }
  718. return id, out, nil
  719. }
  720. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  721. args := []string{"build", "-t", name}
  722. if !useCache {
  723. args = append(args, "--no-cache")
  724. }
  725. args = append(args, "-")
  726. buildCmd := exec.Command(dockerBinary, args...)
  727. buildCmd.Stdin = strings.NewReader(dockerfile)
  728. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  729. if err != nil || exitCode != 0 {
  730. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  731. }
  732. id, err := getIDByName(name)
  733. if err != nil {
  734. return "", stdout, stderr, err
  735. }
  736. return id, stdout, stderr, nil
  737. }
  738. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  739. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  740. return id, err
  741. }
  742. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  743. args := []string{"build", "-t", name}
  744. if !useCache {
  745. args = append(args, "--no-cache")
  746. }
  747. args = append(args, ".")
  748. buildCmd := exec.Command(dockerBinary, args...)
  749. buildCmd.Dir = ctx.Dir
  750. out, exitCode, err := runCommandWithOutput(buildCmd)
  751. if err != nil || exitCode != 0 {
  752. return "", fmt.Errorf("failed to build the image: %s", out)
  753. }
  754. return getIDByName(name)
  755. }
  756. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  757. args := []string{"build", "-t", name}
  758. if !useCache {
  759. args = append(args, "--no-cache")
  760. }
  761. args = append(args, path)
  762. buildCmd := exec.Command(dockerBinary, args...)
  763. out, exitCode, err := runCommandWithOutput(buildCmd)
  764. if err != nil || exitCode != 0 {
  765. return "", fmt.Errorf("failed to build the image: %s", out)
  766. }
  767. return getIDByName(name)
  768. }
  769. type GitServer interface {
  770. URL() string
  771. Close() error
  772. }
  773. type localGitServer struct {
  774. *httptest.Server
  775. }
  776. func (r *localGitServer) Close() error {
  777. r.Server.Close()
  778. return nil
  779. }
  780. func (r *localGitServer) URL() string {
  781. return r.Server.URL
  782. }
  783. type FakeGIT struct {
  784. root string
  785. server GitServer
  786. RepoURL string
  787. }
  788. func (g *FakeGIT) Close() {
  789. g.server.Close()
  790. os.RemoveAll(g.root)
  791. }
  792. func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) {
  793. ctx, err := fakeContextWithFiles(files)
  794. if err != nil {
  795. return nil, err
  796. }
  797. defer ctx.Close()
  798. curdir, err := os.Getwd()
  799. if err != nil {
  800. return nil, err
  801. }
  802. defer os.Chdir(curdir)
  803. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  804. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  805. }
  806. err = os.Chdir(ctx.Dir)
  807. if err != nil {
  808. return nil, err
  809. }
  810. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  811. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  812. }
  813. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  814. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  815. }
  816. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  817. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  818. }
  819. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  820. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  821. }
  822. root, err := ioutil.TempDir("", "docker-test-git-repo")
  823. if err != nil {
  824. return nil, err
  825. }
  826. repoPath := filepath.Join(root, name+".git")
  827. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  828. os.RemoveAll(root)
  829. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  830. }
  831. err = os.Chdir(repoPath)
  832. if err != nil {
  833. os.RemoveAll(root)
  834. return nil, err
  835. }
  836. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  837. os.RemoveAll(root)
  838. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  839. }
  840. err = os.Chdir(curdir)
  841. if err != nil {
  842. os.RemoveAll(root)
  843. return nil, err
  844. }
  845. var server GitServer
  846. if !enforceLocalServer {
  847. // use fakeStorage server, which might be local or remote (at test daemon)
  848. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  849. if err != nil {
  850. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  851. }
  852. } else {
  853. // always start a local http server on CLI test machin
  854. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  855. server = &localGitServer{httpServer}
  856. }
  857. return &FakeGIT{
  858. root: root,
  859. server: server,
  860. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  861. }, nil
  862. }
  863. // Write `content` to the file at path `dst`, creating it if necessary,
  864. // as well as any missing directories.
  865. // The file is truncated if it already exists.
  866. // Call c.Fatal() at the first error.
  867. func writeFile(dst, content string, c *check.C) {
  868. // Create subdirectories if necessary
  869. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  870. c.Fatal(err)
  871. }
  872. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  873. if err != nil {
  874. c.Fatal(err)
  875. }
  876. // Write content (truncate if it exists)
  877. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  878. c.Fatal(err)
  879. }
  880. }
  881. // Return the contents of file at path `src`.
  882. // Call c.Fatal() at the first error (including if the file doesn't exist)
  883. func readFile(src string, c *check.C) (content string) {
  884. data, err := ioutil.ReadFile(src)
  885. if err != nil {
  886. c.Fatal(err)
  887. }
  888. return string(data)
  889. }
  890. func containerStorageFile(containerId, basename string) string {
  891. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  892. }
  893. // docker commands that use this function must be run with the '-d' switch.
  894. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  895. out, _, err := runCommandWithOutput(cmd)
  896. if err != nil {
  897. return nil, fmt.Errorf("%v: %q", err, out)
  898. }
  899. time.Sleep(1 * time.Second)
  900. contID := strings.TrimSpace(out)
  901. return readContainerFile(contID, filename)
  902. }
  903. func readContainerFile(containerId, filename string) ([]byte, error) {
  904. f, err := os.Open(containerStorageFile(containerId, filename))
  905. if err != nil {
  906. return nil, err
  907. }
  908. defer f.Close()
  909. content, err := ioutil.ReadAll(f)
  910. if err != nil {
  911. return nil, err
  912. }
  913. return content, nil
  914. }
  915. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  916. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  917. return []byte(out), err
  918. }
  919. // daemonTime provides the current time on the daemon host
  920. func daemonTime(c *check.C) time.Time {
  921. if isLocalDaemon {
  922. return time.Now()
  923. }
  924. _, body, err := sockRequest("GET", "/info", nil)
  925. if err != nil {
  926. c.Fatalf("daemonTime: failed to get /info: %v", err)
  927. }
  928. type infoJSON struct {
  929. SystemTime string
  930. }
  931. var info infoJSON
  932. if err = json.Unmarshal(body, &info); err != nil {
  933. c.Fatalf("unable to unmarshal /info response: %v", err)
  934. }
  935. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  936. if err != nil {
  937. c.Fatal(err)
  938. }
  939. return dt
  940. }
  941. func setupRegistry(c *check.C) func() {
  942. testRequires(c, RegistryHosting)
  943. reg, err := newTestRegistryV2(c)
  944. if err != nil {
  945. c.Fatal(err)
  946. }
  947. // Wait for registry to be ready to serve requests.
  948. for i := 0; i != 5; i++ {
  949. if err = reg.Ping(); err == nil {
  950. break
  951. }
  952. time.Sleep(100 * time.Millisecond)
  953. }
  954. if err != nil {
  955. c.Fatal("Timeout waiting for test registry to become available")
  956. }
  957. return func() { reg.Close() }
  958. }
  959. // appendBaseEnv appends the minimum set of environment variables to exec the
  960. // docker cli binary for testing with correct configuration to the given env
  961. // list.
  962. func appendBaseEnv(env []string) []string {
  963. preserveList := []string{
  964. // preserve remote test host
  965. "DOCKER_HOST",
  966. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  967. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  968. "SystemRoot",
  969. }
  970. for _, key := range preserveList {
  971. if val := os.Getenv(key); val != "" {
  972. env = append(env, fmt.Sprintf("%s=%s", key, val))
  973. }
  974. }
  975. return env
  976. }