docker_utils.go 40 KB

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