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