docker_utils.go 28 KB

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