docker_utils.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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 dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  484. stdout, stderr, status, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, args...))
  485. c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), stderr, err))
  486. return stdout, stderr, status
  487. }
  488. func dockerCmd(c *check.C, args ...string) (string, int) {
  489. out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
  490. c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err))
  491. return out, status
  492. }
  493. // execute a docker command with a timeout
  494. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  495. out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout)
  496. if err != nil {
  497. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  498. }
  499. return out, status, err
  500. }
  501. // execute a docker command in a directory
  502. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  503. dockerCommand := exec.Command(dockerBinary, args...)
  504. dockerCommand.Dir = path
  505. out, status, err := runCommandWithOutput(dockerCommand)
  506. if err != nil {
  507. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  508. }
  509. return out, status, err
  510. }
  511. // execute a docker command in a directory with a timeout
  512. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  513. dockerCommand := exec.Command(dockerBinary, args...)
  514. dockerCommand.Dir = path
  515. out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout)
  516. if err != nil {
  517. return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out)
  518. }
  519. return out, status, err
  520. }
  521. func findContainerIP(c *check.C, id string, vargs ...string) string {
  522. args := append(vargs, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  523. cmd := exec.Command(dockerBinary, args...)
  524. out, _, err := runCommandWithOutput(cmd)
  525. if err != nil {
  526. c.Fatal(err, out)
  527. }
  528. return strings.Trim(out, " \r\n'")
  529. }
  530. func (d *Daemon) findContainerIP(id string) string {
  531. return findContainerIP(d.c, id, "--host", d.sock())
  532. }
  533. func getContainerCount() (int, error) {
  534. const containers = "Containers:"
  535. cmd := exec.Command(dockerBinary, "info")
  536. out, _, err := runCommandWithOutput(cmd)
  537. if err != nil {
  538. return 0, err
  539. }
  540. lines := strings.Split(out, "\n")
  541. for _, line := range lines {
  542. if strings.Contains(line, containers) {
  543. output := strings.TrimSpace(line)
  544. output = strings.TrimLeft(output, containers)
  545. output = strings.Trim(output, " ")
  546. containerCount, err := strconv.Atoi(output)
  547. if err != nil {
  548. return 0, err
  549. }
  550. return containerCount, nil
  551. }
  552. }
  553. return 0, fmt.Errorf("couldn't find the Container count in the output")
  554. }
  555. type FakeContext struct {
  556. Dir string
  557. }
  558. func (f *FakeContext) Add(file, content string) error {
  559. return f.addFile(file, []byte(content))
  560. }
  561. func (f *FakeContext) addFile(file string, content []byte) error {
  562. filepath := path.Join(f.Dir, file)
  563. dirpath := path.Dir(filepath)
  564. if dirpath != "." {
  565. if err := os.MkdirAll(dirpath, 0755); err != nil {
  566. return err
  567. }
  568. }
  569. return ioutil.WriteFile(filepath, content, 0644)
  570. }
  571. func (f *FakeContext) Delete(file string) error {
  572. filepath := path.Join(f.Dir, file)
  573. return os.RemoveAll(filepath)
  574. }
  575. func (f *FakeContext) Close() error {
  576. return os.RemoveAll(f.Dir)
  577. }
  578. func fakeContextFromNewTempDir() (*FakeContext, error) {
  579. tmp, err := ioutil.TempDir("", "fake-context")
  580. if err != nil {
  581. return nil, err
  582. }
  583. if err := os.Chmod(tmp, 0755); err != nil {
  584. return nil, err
  585. }
  586. return fakeContextFromDir(tmp), nil
  587. }
  588. func fakeContextFromDir(dir string) *FakeContext {
  589. return &FakeContext{dir}
  590. }
  591. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  592. ctx, err := fakeContextFromNewTempDir()
  593. if err != nil {
  594. return nil, err
  595. }
  596. for file, content := range files {
  597. if err := ctx.Add(file, content); err != nil {
  598. ctx.Close()
  599. return nil, err
  600. }
  601. }
  602. return ctx, nil
  603. }
  604. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  605. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  606. ctx.Close()
  607. return err
  608. }
  609. return nil
  610. }
  611. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  612. ctx, err := fakeContextWithFiles(files)
  613. if err != nil {
  614. return nil, err
  615. }
  616. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  617. return nil, err
  618. }
  619. return ctx, nil
  620. }
  621. // FakeStorage is a static file server. It might be running locally or remotely
  622. // on test host.
  623. type FakeStorage interface {
  624. Close() error
  625. URL() string
  626. CtxDir() string
  627. }
  628. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  629. ctx, err := fakeContextFromNewTempDir()
  630. if err != nil {
  631. return nil, err
  632. }
  633. for name, content := range archives {
  634. if err := ctx.addFile(name, content.Bytes()); err != nil {
  635. return nil, err
  636. }
  637. }
  638. return fakeStorageWithContext(ctx)
  639. }
  640. // fakeStorage returns either a local or remote (at daemon machine) file server
  641. func fakeStorage(files map[string]string) (FakeStorage, error) {
  642. ctx, err := fakeContextWithFiles(files)
  643. if err != nil {
  644. return nil, err
  645. }
  646. return fakeStorageWithContext(ctx)
  647. }
  648. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  649. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  650. if isLocalDaemon {
  651. return newLocalFakeStorage(ctx)
  652. }
  653. return newRemoteFileServer(ctx)
  654. }
  655. // localFileStorage is a file storage on the running machine
  656. type localFileStorage struct {
  657. *FakeContext
  658. *httptest.Server
  659. }
  660. func (s *localFileStorage) URL() string {
  661. return s.Server.URL
  662. }
  663. func (s *localFileStorage) CtxDir() string {
  664. return s.FakeContext.Dir
  665. }
  666. func (s *localFileStorage) Close() error {
  667. defer s.Server.Close()
  668. return s.FakeContext.Close()
  669. }
  670. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  671. handler := http.FileServer(http.Dir(ctx.Dir))
  672. server := httptest.NewServer(handler)
  673. return &localFileStorage{
  674. FakeContext: ctx,
  675. Server: server,
  676. }, nil
  677. }
  678. // remoteFileServer is a containerized static file server started on the remote
  679. // testing machine to be used in URL-accepting docker build functionality.
  680. type remoteFileServer struct {
  681. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  682. container string
  683. image string
  684. ctx *FakeContext
  685. }
  686. func (f *remoteFileServer) URL() string {
  687. u := url.URL{
  688. Scheme: "http",
  689. Host: f.host}
  690. return u.String()
  691. }
  692. func (f *remoteFileServer) CtxDir() string {
  693. return f.ctx.Dir
  694. }
  695. func (f *remoteFileServer) Close() error {
  696. defer func() {
  697. if f.ctx != nil {
  698. f.ctx.Close()
  699. }
  700. if f.image != "" {
  701. deleteImages(f.image)
  702. }
  703. }()
  704. if f.container == "" {
  705. return nil
  706. }
  707. return deleteContainer(f.container)
  708. }
  709. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  710. var (
  711. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  712. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  713. )
  714. // Build the image
  715. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  716. COPY . /static`); err != nil {
  717. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  718. }
  719. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  720. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  721. }
  722. // Start the container
  723. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  724. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  725. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  726. }
  727. // Find out the system assigned port
  728. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  729. if err != nil {
  730. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  731. }
  732. return &remoteFileServer{
  733. container: container,
  734. image: image,
  735. host: strings.Trim(out, "\n"),
  736. ctx: ctx}, nil
  737. }
  738. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  739. str, err := inspectFieldJSON(name, field)
  740. if err != nil {
  741. return err
  742. }
  743. return json.Unmarshal([]byte(str), output)
  744. }
  745. func inspectFilter(name, filter string) (string, error) {
  746. format := fmt.Sprintf("{{%s}}", filter)
  747. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  748. out, exitCode, err := runCommandWithOutput(inspectCmd)
  749. if err != nil || exitCode != 0 {
  750. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  751. }
  752. return strings.TrimSpace(out), nil
  753. }
  754. func inspectField(name, field string) (string, error) {
  755. return inspectFilter(name, fmt.Sprintf(".%s", field))
  756. }
  757. func inspectFieldJSON(name, field string) (string, error) {
  758. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  759. }
  760. func inspectFieldMap(name, path, field string) (string, error) {
  761. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  762. }
  763. func getIDByName(name string) (string, error) {
  764. return inspectField(name, "Id")
  765. }
  766. // getContainerState returns the exit code of the container
  767. // and true if it's running
  768. // the exit code should be ignored if it's running
  769. func getContainerState(c *check.C, id string) (int, bool, error) {
  770. var (
  771. exitStatus int
  772. running bool
  773. )
  774. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  775. if exitCode != 0 {
  776. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  777. }
  778. out = strings.Trim(out, "\n")
  779. splitOutput := strings.Split(out, " ")
  780. if len(splitOutput) != 2 {
  781. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  782. }
  783. if splitOutput[0] == "true" {
  784. running = true
  785. }
  786. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  787. exitStatus = n
  788. } else {
  789. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  790. }
  791. return exitStatus, running, nil
  792. }
  793. func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) {
  794. args := []string{"build", "-t", name}
  795. if !useCache {
  796. args = append(args, "--no-cache")
  797. }
  798. args = append(args, "-")
  799. buildCmd := exec.Command(dockerBinary, args...)
  800. buildCmd.Stdin = strings.NewReader(dockerfile)
  801. out, exitCode, err := runCommandWithOutput(buildCmd)
  802. if err != nil || exitCode != 0 {
  803. return "", out, fmt.Errorf("failed to build the image: %s", out)
  804. }
  805. id, err := getIDByName(name)
  806. if err != nil {
  807. return "", out, err
  808. }
  809. return id, out, nil
  810. }
  811. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) {
  812. args := []string{"build", "-t", name}
  813. if !useCache {
  814. args = append(args, "--no-cache")
  815. }
  816. args = append(args, "-")
  817. buildCmd := exec.Command(dockerBinary, args...)
  818. buildCmd.Stdin = strings.NewReader(dockerfile)
  819. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  820. if err != nil || exitCode != 0 {
  821. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  822. }
  823. id, err := getIDByName(name)
  824. if err != nil {
  825. return "", stdout, stderr, err
  826. }
  827. return id, stdout, stderr, nil
  828. }
  829. func buildImage(name, dockerfile string, useCache bool) (string, error) {
  830. id, _, err := buildImageWithOut(name, dockerfile, useCache)
  831. return id, err
  832. }
  833. func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) {
  834. args := []string{"build", "-t", name}
  835. if !useCache {
  836. args = append(args, "--no-cache")
  837. }
  838. args = append(args, ".")
  839. buildCmd := exec.Command(dockerBinary, args...)
  840. buildCmd.Dir = ctx.Dir
  841. out, exitCode, err := runCommandWithOutput(buildCmd)
  842. if err != nil || exitCode != 0 {
  843. return "", fmt.Errorf("failed to build the image: %s", out)
  844. }
  845. return getIDByName(name)
  846. }
  847. func buildImageFromPath(name, path string, useCache bool) (string, error) {
  848. args := []string{"build", "-t", name}
  849. if !useCache {
  850. args = append(args, "--no-cache")
  851. }
  852. args = append(args, path)
  853. buildCmd := exec.Command(dockerBinary, args...)
  854. out, exitCode, err := runCommandWithOutput(buildCmd)
  855. if err != nil || exitCode != 0 {
  856. return "", fmt.Errorf("failed to build the image: %s", out)
  857. }
  858. return getIDByName(name)
  859. }
  860. type GitServer interface {
  861. URL() string
  862. Close() error
  863. }
  864. type localGitServer struct {
  865. *httptest.Server
  866. }
  867. func (r *localGitServer) Close() error {
  868. r.Server.Close()
  869. return nil
  870. }
  871. func (r *localGitServer) URL() string {
  872. return r.Server.URL
  873. }
  874. type FakeGIT struct {
  875. root string
  876. server GitServer
  877. RepoURL string
  878. }
  879. func (g *FakeGIT) Close() {
  880. g.server.Close()
  881. os.RemoveAll(g.root)
  882. }
  883. func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) {
  884. ctx, err := fakeContextWithFiles(files)
  885. if err != nil {
  886. return nil, err
  887. }
  888. defer ctx.Close()
  889. curdir, err := os.Getwd()
  890. if err != nil {
  891. return nil, err
  892. }
  893. defer os.Chdir(curdir)
  894. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  895. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  896. }
  897. err = os.Chdir(ctx.Dir)
  898. if err != nil {
  899. return nil, err
  900. }
  901. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  902. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  903. }
  904. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  905. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  906. }
  907. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  908. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  909. }
  910. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  911. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  912. }
  913. root, err := ioutil.TempDir("", "docker-test-git-repo")
  914. if err != nil {
  915. return nil, err
  916. }
  917. repoPath := filepath.Join(root, name+".git")
  918. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  919. os.RemoveAll(root)
  920. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  921. }
  922. err = os.Chdir(repoPath)
  923. if err != nil {
  924. os.RemoveAll(root)
  925. return nil, err
  926. }
  927. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  928. os.RemoveAll(root)
  929. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  930. }
  931. err = os.Chdir(curdir)
  932. if err != nil {
  933. os.RemoveAll(root)
  934. return nil, err
  935. }
  936. var server GitServer
  937. if !enforceLocalServer {
  938. // use fakeStorage server, which might be local or remote (at test daemon)
  939. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  940. if err != nil {
  941. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  942. }
  943. } else {
  944. // always start a local http server on CLI test machin
  945. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  946. server = &localGitServer{httpServer}
  947. }
  948. return &FakeGIT{
  949. root: root,
  950. server: server,
  951. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  952. }, nil
  953. }
  954. // Write `content` to the file at path `dst`, creating it if necessary,
  955. // as well as any missing directories.
  956. // The file is truncated if it already exists.
  957. // Call c.Fatal() at the first error.
  958. func writeFile(dst, content string, c *check.C) {
  959. // Create subdirectories if necessary
  960. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  961. c.Fatal(err)
  962. }
  963. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  964. if err != nil {
  965. c.Fatal(err)
  966. }
  967. defer f.Close()
  968. // Write content (truncate if it exists)
  969. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  970. c.Fatal(err)
  971. }
  972. }
  973. // Return the contents of file at path `src`.
  974. // Call c.Fatal() at the first error (including if the file doesn't exist)
  975. func readFile(src string, c *check.C) (content string) {
  976. data, err := ioutil.ReadFile(src)
  977. if err != nil {
  978. c.Fatal(err)
  979. }
  980. return string(data)
  981. }
  982. func containerStorageFile(containerId, basename string) string {
  983. return filepath.Join("/var/lib/docker/containers", containerId, basename)
  984. }
  985. // docker commands that use this function must be run with the '-d' switch.
  986. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  987. out, _, err := runCommandWithOutput(cmd)
  988. if err != nil {
  989. return nil, fmt.Errorf("%v: %q", err, out)
  990. }
  991. time.Sleep(1 * time.Second)
  992. contID := strings.TrimSpace(out)
  993. return readContainerFile(contID, filename)
  994. }
  995. func readContainerFile(containerId, filename string) ([]byte, error) {
  996. f, err := os.Open(containerStorageFile(containerId, filename))
  997. if err != nil {
  998. return nil, err
  999. }
  1000. defer f.Close()
  1001. content, err := ioutil.ReadAll(f)
  1002. if err != nil {
  1003. return nil, err
  1004. }
  1005. return content, nil
  1006. }
  1007. func readContainerFileWithExec(containerId, filename string) ([]byte, error) {
  1008. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename))
  1009. return []byte(out), err
  1010. }
  1011. // daemonTime provides the current time on the daemon host
  1012. func daemonTime(c *check.C) time.Time {
  1013. if isLocalDaemon {
  1014. return time.Now()
  1015. }
  1016. status, body, err := sockRequest("GET", "/info", nil)
  1017. c.Assert(status, check.Equals, http.StatusOK)
  1018. c.Assert(err, check.IsNil)
  1019. type infoJSON struct {
  1020. SystemTime string
  1021. }
  1022. var info infoJSON
  1023. if err = json.Unmarshal(body, &info); err != nil {
  1024. c.Fatalf("unable to unmarshal /info response: %v", err)
  1025. }
  1026. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1027. if err != nil {
  1028. c.Fatal(err)
  1029. }
  1030. return dt
  1031. }
  1032. func setupRegistry(c *check.C) *testRegistryV2 {
  1033. testRequires(c, RegistryHosting)
  1034. reg, err := newTestRegistryV2(c)
  1035. if err != nil {
  1036. c.Fatal(err)
  1037. }
  1038. // Wait for registry to be ready to serve requests.
  1039. for i := 0; i != 5; i++ {
  1040. if err = reg.Ping(); err == nil {
  1041. break
  1042. }
  1043. time.Sleep(100 * time.Millisecond)
  1044. }
  1045. if err != nil {
  1046. c.Fatal("Timeout waiting for test registry to become available")
  1047. }
  1048. return reg
  1049. }
  1050. // appendBaseEnv appends the minimum set of environment variables to exec the
  1051. // docker cli binary for testing with correct configuration to the given env
  1052. // list.
  1053. func appendBaseEnv(env []string) []string {
  1054. preserveList := []string{
  1055. // preserve remote test host
  1056. "DOCKER_HOST",
  1057. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1058. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1059. "SystemRoot",
  1060. }
  1061. for _, key := range preserveList {
  1062. if val := os.Getenv(key); val != "" {
  1063. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1064. }
  1065. }
  1066. return env
  1067. }