docker_utils.go 29 KB

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