docker_utils.go 31 KB

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