docker_utils.go 34 KB

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