docker_utils.go 40 KB

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