docker_utils.go 30 KB

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