docker_utils.go 28 KB

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