docker_utils.go 35 KB

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