docker_utils.go 29 KB

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