docker_utils.go 40 KB

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