docker_utils.go 33 KB

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