docker_utils.go 32 KB

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