docker_utils.go 30 KB

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