docker_utils.go 29 KB

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