docker_utils.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  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 deleteAllNetworks() error {
  435. networks, err := getAllNetworks()
  436. if err != nil {
  437. return err
  438. }
  439. var errors []string
  440. for _, n := range networks {
  441. if n.Name != "bridge" {
  442. status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
  443. if err != nil {
  444. errors = append(errors, err.Error())
  445. continue
  446. }
  447. if status != http.StatusNoContent {
  448. errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  449. }
  450. }
  451. }
  452. if len(errors) > 0 {
  453. return fmt.Errorf(strings.Join(errors, "\n"))
  454. }
  455. return nil
  456. }
  457. func getAllNetworks() ([]types.NetworkResource, error) {
  458. var networks []types.NetworkResource
  459. _, b, err := sockRequest("GET", "/networks", nil)
  460. if err != nil {
  461. return nil, err
  462. }
  463. if err := json.Unmarshal(b, &networks); err != nil {
  464. return nil, err
  465. }
  466. return networks, nil
  467. }
  468. func deleteAllVolumes() error {
  469. volumes, err := getAllVolumes()
  470. if err != nil {
  471. return err
  472. }
  473. var errors []string
  474. for _, v := range volumes {
  475. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
  476. if err != nil {
  477. errors = append(errors, err.Error())
  478. continue
  479. }
  480. if status != http.StatusNoContent {
  481. errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  482. }
  483. }
  484. if len(errors) > 0 {
  485. return fmt.Errorf(strings.Join(errors, "\n"))
  486. }
  487. return nil
  488. }
  489. func getAllVolumes() ([]*types.Volume, error) {
  490. var volumes types.VolumesListResponse
  491. _, b, err := sockRequest("GET", "/volumes", nil)
  492. if err != nil {
  493. return nil, err
  494. }
  495. if err := json.Unmarshal(b, &volumes); err != nil {
  496. return nil, err
  497. }
  498. return volumes.Volumes, nil
  499. }
  500. var protectedImages = map[string]struct{}{}
  501. func init() {
  502. out, err := exec.Command(dockerBinary, "images").CombinedOutput()
  503. if err != nil {
  504. panic(err)
  505. }
  506. lines := strings.Split(string(out), "\n")[1:]
  507. for _, l := range lines {
  508. if l == "" {
  509. continue
  510. }
  511. fields := strings.Fields(l)
  512. imgTag := fields[0] + ":" + fields[1]
  513. // just for case if we have dangling images in tested daemon
  514. if imgTag != "<none>:<none>" {
  515. protectedImages[imgTag] = struct{}{}
  516. }
  517. }
  518. // Obtain the daemon platform so that it can be used by tests to make
  519. // intelligent decisions about how to configure themselves, and validate
  520. // that the target platform is valid.
  521. res, _, err := sockRequestRaw("GET", "/version", nil, "application/json")
  522. if err != nil || res == nil || (res != nil && res.StatusCode != http.StatusOK) {
  523. panic(fmt.Errorf("Init failed to get version: %v. Res=%v", err.Error(), res))
  524. }
  525. svrHeader, _ := httputils.ParseServerHeader(res.Header.Get("Server"))
  526. daemonPlatform = svrHeader.OS
  527. if daemonPlatform != "linux" && daemonPlatform != "windows" {
  528. panic("Cannot run tests against platform: " + daemonPlatform)
  529. }
  530. }
  531. func deleteAllImages() error {
  532. out, err := exec.Command(dockerBinary, "images").CombinedOutput()
  533. if err != nil {
  534. return err
  535. }
  536. lines := strings.Split(string(out), "\n")[1:]
  537. var imgs []string
  538. for _, l := range lines {
  539. if l == "" {
  540. continue
  541. }
  542. fields := strings.Fields(l)
  543. imgTag := fields[0] + ":" + fields[1]
  544. if _, ok := protectedImages[imgTag]; !ok {
  545. if fields[0] == "<none>" {
  546. imgs = append(imgs, fields[2])
  547. continue
  548. }
  549. imgs = append(imgs, imgTag)
  550. }
  551. }
  552. if len(imgs) == 0 {
  553. return nil
  554. }
  555. args := append([]string{"rmi", "-f"}, imgs...)
  556. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  557. return err
  558. }
  559. return nil
  560. }
  561. func getPausedContainers() (string, error) {
  562. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  563. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  564. if exitCode != 0 && err == nil {
  565. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  566. }
  567. return out, err
  568. }
  569. func getSliceOfPausedContainers() ([]string, error) {
  570. out, err := getPausedContainers()
  571. if err == nil {
  572. if len(out) == 0 {
  573. return nil, err
  574. }
  575. slice := strings.Split(strings.TrimSpace(out), "\n")
  576. return slice, err
  577. }
  578. return []string{out}, err
  579. }
  580. func unpauseContainer(container string) error {
  581. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  582. exitCode, err := runCommand(unpauseCmd)
  583. if exitCode != 0 && err == nil {
  584. err = fmt.Errorf("failed to unpause container")
  585. }
  586. return nil
  587. }
  588. func unpauseAllContainers() error {
  589. containers, err := getPausedContainers()
  590. if err != nil {
  591. fmt.Println(containers)
  592. return err
  593. }
  594. containers = strings.Replace(containers, "\n", " ", -1)
  595. containers = strings.Trim(containers, " ")
  596. containerList := strings.Split(containers, " ")
  597. for _, value := range containerList {
  598. if err = unpauseContainer(value); err != nil {
  599. return err
  600. }
  601. }
  602. return nil
  603. }
  604. func deleteImages(images ...string) error {
  605. args := []string{"rmi", "-f"}
  606. args = append(args, images...)
  607. rmiCmd := exec.Command(dockerBinary, args...)
  608. exitCode, err := runCommand(rmiCmd)
  609. // set error manually if not set
  610. if exitCode != 0 && err == nil {
  611. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  612. }
  613. return err
  614. }
  615. func imageExists(image string) error {
  616. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  617. exitCode, err := runCommand(inspectCmd)
  618. if exitCode != 0 && err == nil {
  619. err = fmt.Errorf("couldn't find image %q", image)
  620. }
  621. return err
  622. }
  623. func pullImageIfNotExist(image string) error {
  624. if err := imageExists(image); err != nil {
  625. pullCmd := exec.Command(dockerBinary, "pull", image)
  626. _, exitCode, err := runCommandWithOutput(pullCmd)
  627. if err != nil || exitCode != 0 {
  628. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  629. }
  630. }
  631. return nil
  632. }
  633. func dockerCmdWithError(args ...string) (string, int, error) {
  634. return integration.DockerCmdWithError(dockerBinary, args...)
  635. }
  636. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  637. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  638. }
  639. func dockerCmd(c *check.C, args ...string) (string, int) {
  640. return integration.DockerCmd(dockerBinary, c, args...)
  641. }
  642. // execute a docker command with a timeout
  643. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  644. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  645. }
  646. // execute a docker command in a directory
  647. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  648. return integration.DockerCmdInDir(dockerBinary, path, args...)
  649. }
  650. // execute a docker command in a directory with a timeout
  651. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  652. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  653. }
  654. func findContainerIP(c *check.C, id string, vargs ...string) string {
  655. out, _ := dockerCmd(c, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id)
  656. return strings.Trim(out, " \r\n'")
  657. }
  658. func (d *Daemon) findContainerIP(id string) string {
  659. return findContainerIP(d.c, id, "--host", d.sock())
  660. }
  661. func getContainerCount() (int, error) {
  662. const containers = "Containers:"
  663. cmd := exec.Command(dockerBinary, "info")
  664. out, _, err := runCommandWithOutput(cmd)
  665. if err != nil {
  666. return 0, err
  667. }
  668. lines := strings.Split(out, "\n")
  669. for _, line := range lines {
  670. if strings.Contains(line, containers) {
  671. output := strings.TrimSpace(line)
  672. output = strings.TrimLeft(output, containers)
  673. output = strings.Trim(output, " ")
  674. containerCount, err := strconv.Atoi(output)
  675. if err != nil {
  676. return 0, err
  677. }
  678. return containerCount, nil
  679. }
  680. }
  681. return 0, fmt.Errorf("couldn't find the Container count in the output")
  682. }
  683. // FakeContext creates directories that can be used as a build context
  684. type FakeContext struct {
  685. Dir string
  686. }
  687. // Add a file at a path, creating directories where necessary
  688. func (f *FakeContext) Add(file, content string) error {
  689. return f.addFile(file, []byte(content))
  690. }
  691. func (f *FakeContext) addFile(file string, content []byte) error {
  692. filepath := path.Join(f.Dir, file)
  693. dirpath := path.Dir(filepath)
  694. if dirpath != "." {
  695. if err := os.MkdirAll(dirpath, 0755); err != nil {
  696. return err
  697. }
  698. }
  699. return ioutil.WriteFile(filepath, content, 0644)
  700. }
  701. // Delete a file at a path
  702. func (f *FakeContext) Delete(file string) error {
  703. filepath := path.Join(f.Dir, file)
  704. return os.RemoveAll(filepath)
  705. }
  706. // Close deletes the context
  707. func (f *FakeContext) Close() error {
  708. return os.RemoveAll(f.Dir)
  709. }
  710. func fakeContextFromNewTempDir() (*FakeContext, error) {
  711. tmp, err := ioutil.TempDir("", "fake-context")
  712. if err != nil {
  713. return nil, err
  714. }
  715. if err := os.Chmod(tmp, 0755); err != nil {
  716. return nil, err
  717. }
  718. return fakeContextFromDir(tmp), nil
  719. }
  720. func fakeContextFromDir(dir string) *FakeContext {
  721. return &FakeContext{dir}
  722. }
  723. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  724. ctx, err := fakeContextFromNewTempDir()
  725. if err != nil {
  726. return nil, err
  727. }
  728. for file, content := range files {
  729. if err := ctx.Add(file, content); err != nil {
  730. ctx.Close()
  731. return nil, err
  732. }
  733. }
  734. return ctx, nil
  735. }
  736. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  737. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  738. ctx.Close()
  739. return err
  740. }
  741. return nil
  742. }
  743. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  744. ctx, err := fakeContextWithFiles(files)
  745. if err != nil {
  746. return nil, err
  747. }
  748. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  749. return nil, err
  750. }
  751. return ctx, nil
  752. }
  753. // FakeStorage is a static file server. It might be running locally or remotely
  754. // on test host.
  755. type FakeStorage interface {
  756. Close() error
  757. URL() string
  758. CtxDir() string
  759. }
  760. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  761. ctx, err := fakeContextFromNewTempDir()
  762. if err != nil {
  763. return nil, err
  764. }
  765. for name, content := range archives {
  766. if err := ctx.addFile(name, content.Bytes()); err != nil {
  767. return nil, err
  768. }
  769. }
  770. return fakeStorageWithContext(ctx)
  771. }
  772. // fakeStorage returns either a local or remote (at daemon machine) file server
  773. func fakeStorage(files map[string]string) (FakeStorage, error) {
  774. ctx, err := fakeContextWithFiles(files)
  775. if err != nil {
  776. return nil, err
  777. }
  778. return fakeStorageWithContext(ctx)
  779. }
  780. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  781. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  782. if isLocalDaemon {
  783. return newLocalFakeStorage(ctx)
  784. }
  785. return newRemoteFileServer(ctx)
  786. }
  787. // localFileStorage is a file storage on the running machine
  788. type localFileStorage struct {
  789. *FakeContext
  790. *httptest.Server
  791. }
  792. func (s *localFileStorage) URL() string {
  793. return s.Server.URL
  794. }
  795. func (s *localFileStorage) CtxDir() string {
  796. return s.FakeContext.Dir
  797. }
  798. func (s *localFileStorage) Close() error {
  799. defer s.Server.Close()
  800. return s.FakeContext.Close()
  801. }
  802. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  803. handler := http.FileServer(http.Dir(ctx.Dir))
  804. server := httptest.NewServer(handler)
  805. return &localFileStorage{
  806. FakeContext: ctx,
  807. Server: server,
  808. }, nil
  809. }
  810. // remoteFileServer is a containerized static file server started on the remote
  811. // testing machine to be used in URL-accepting docker build functionality.
  812. type remoteFileServer struct {
  813. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  814. container string
  815. image string
  816. ctx *FakeContext
  817. }
  818. func (f *remoteFileServer) URL() string {
  819. u := url.URL{
  820. Scheme: "http",
  821. Host: f.host}
  822. return u.String()
  823. }
  824. func (f *remoteFileServer) CtxDir() string {
  825. return f.ctx.Dir
  826. }
  827. func (f *remoteFileServer) Close() error {
  828. defer func() {
  829. if f.ctx != nil {
  830. f.ctx.Close()
  831. }
  832. if f.image != "" {
  833. deleteImages(f.image)
  834. }
  835. }()
  836. if f.container == "" {
  837. return nil
  838. }
  839. return deleteContainer(f.container)
  840. }
  841. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  842. var (
  843. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  844. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  845. )
  846. // Build the image
  847. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  848. COPY . /static`); err != nil {
  849. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  850. }
  851. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  852. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  853. }
  854. // Start the container
  855. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  856. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  857. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  858. }
  859. // Find out the system assigned port
  860. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  861. if err != nil {
  862. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  863. }
  864. fileserverHostPort := strings.Trim(out, "\n")
  865. _, port, err := net.SplitHostPort(fileserverHostPort)
  866. if err != nil {
  867. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  868. }
  869. dockerHostURL, err := url.Parse(daemonHost())
  870. if err != nil {
  871. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  872. }
  873. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  874. if err != nil {
  875. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  876. }
  877. return &remoteFileServer{
  878. container: container,
  879. image: image,
  880. host: fmt.Sprintf("%s:%s", host, port),
  881. ctx: ctx}, nil
  882. }
  883. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  884. str, err := inspectFieldJSON(name, field)
  885. if err != nil {
  886. return err
  887. }
  888. return json.Unmarshal([]byte(str), output)
  889. }
  890. func inspectFilter(name, filter string) (string, error) {
  891. format := fmt.Sprintf("{{%s}}", filter)
  892. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  893. out, exitCode, err := runCommandWithOutput(inspectCmd)
  894. if err != nil || exitCode != 0 {
  895. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  896. }
  897. return strings.TrimSpace(out), nil
  898. }
  899. func inspectField(name, field string) (string, error) {
  900. return inspectFilter(name, fmt.Sprintf(".%s", field))
  901. }
  902. func inspectFieldJSON(name, field string) (string, error) {
  903. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  904. }
  905. func inspectFieldMap(name, path, field string) (string, error) {
  906. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  907. }
  908. func inspectMountSourceField(name, destination string) (string, error) {
  909. m, err := inspectMountPoint(name, destination)
  910. if err != nil {
  911. return "", err
  912. }
  913. return m.Source, nil
  914. }
  915. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  916. out, err := inspectFieldJSON(name, "Mounts")
  917. if err != nil {
  918. return types.MountPoint{}, err
  919. }
  920. return inspectMountPointJSON(out, destination)
  921. }
  922. var errMountNotFound = errors.New("mount point not found")
  923. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  924. var mp []types.MountPoint
  925. if err := unmarshalJSON([]byte(j), &mp); err != nil {
  926. return types.MountPoint{}, err
  927. }
  928. var m *types.MountPoint
  929. for _, c := range mp {
  930. if c.Destination == destination {
  931. m = &c
  932. break
  933. }
  934. }
  935. if m == nil {
  936. return types.MountPoint{}, errMountNotFound
  937. }
  938. return *m, nil
  939. }
  940. func getIDByName(name string) (string, error) {
  941. return inspectField(name, "Id")
  942. }
  943. // getContainerState returns the exit code of the container
  944. // and true if it's running
  945. // the exit code should be ignored if it's running
  946. func getContainerState(c *check.C, id string) (int, bool, error) {
  947. var (
  948. exitStatus int
  949. running bool
  950. )
  951. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  952. if exitCode != 0 {
  953. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  954. }
  955. out = strings.Trim(out, "\n")
  956. splitOutput := strings.Split(out, " ")
  957. if len(splitOutput) != 2 {
  958. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  959. }
  960. if splitOutput[0] == "true" {
  961. running = true
  962. }
  963. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  964. exitStatus = n
  965. } else {
  966. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  967. }
  968. return exitStatus, running, nil
  969. }
  970. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  971. args := []string{"-D", "build", "-t", name}
  972. if !useCache {
  973. args = append(args, "--no-cache")
  974. }
  975. args = append(args, buildFlags...)
  976. args = append(args, "-")
  977. buildCmd := exec.Command(dockerBinary, args...)
  978. buildCmd.Stdin = strings.NewReader(dockerfile)
  979. return buildCmd
  980. }
  981. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  982. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  983. out, exitCode, err := runCommandWithOutput(buildCmd)
  984. if err != nil || exitCode != 0 {
  985. return "", out, fmt.Errorf("failed to build the image: %s", out)
  986. }
  987. id, err := getIDByName(name)
  988. if err != nil {
  989. return "", out, err
  990. }
  991. return id, out, nil
  992. }
  993. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  994. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  995. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  996. if err != nil || exitCode != 0 {
  997. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  998. }
  999. id, err := getIDByName(name)
  1000. if err != nil {
  1001. return "", stdout, stderr, err
  1002. }
  1003. return id, stdout, stderr, nil
  1004. }
  1005. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1006. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1007. return id, err
  1008. }
  1009. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1010. args := []string{"build", "-t", name}
  1011. if !useCache {
  1012. args = append(args, "--no-cache")
  1013. }
  1014. args = append(args, buildFlags...)
  1015. args = append(args, ".")
  1016. buildCmd := exec.Command(dockerBinary, args...)
  1017. buildCmd.Dir = ctx.Dir
  1018. out, exitCode, err := runCommandWithOutput(buildCmd)
  1019. if err != nil || exitCode != 0 {
  1020. return "", fmt.Errorf("failed to build the image: %s", out)
  1021. }
  1022. return getIDByName(name)
  1023. }
  1024. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1025. args := []string{"build", "-t", name}
  1026. if !useCache {
  1027. args = append(args, "--no-cache")
  1028. }
  1029. args = append(args, buildFlags...)
  1030. args = append(args, path)
  1031. buildCmd := exec.Command(dockerBinary, args...)
  1032. out, exitCode, err := runCommandWithOutput(buildCmd)
  1033. if err != nil || exitCode != 0 {
  1034. return "", fmt.Errorf("failed to build the image: %s", out)
  1035. }
  1036. return getIDByName(name)
  1037. }
  1038. type gitServer interface {
  1039. URL() string
  1040. Close() error
  1041. }
  1042. type localGitServer struct {
  1043. *httptest.Server
  1044. }
  1045. func (r *localGitServer) Close() error {
  1046. r.Server.Close()
  1047. return nil
  1048. }
  1049. func (r *localGitServer) URL() string {
  1050. return r.Server.URL
  1051. }
  1052. type fakeGit struct {
  1053. root string
  1054. server gitServer
  1055. RepoURL string
  1056. }
  1057. func (g *fakeGit) Close() {
  1058. g.server.Close()
  1059. os.RemoveAll(g.root)
  1060. }
  1061. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1062. ctx, err := fakeContextWithFiles(files)
  1063. if err != nil {
  1064. return nil, err
  1065. }
  1066. defer ctx.Close()
  1067. curdir, err := os.Getwd()
  1068. if err != nil {
  1069. return nil, err
  1070. }
  1071. defer os.Chdir(curdir)
  1072. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1073. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1074. }
  1075. err = os.Chdir(ctx.Dir)
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1080. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1081. }
  1082. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1083. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1084. }
  1085. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1086. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1087. }
  1088. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1089. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1090. }
  1091. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1092. if err != nil {
  1093. return nil, err
  1094. }
  1095. repoPath := filepath.Join(root, name+".git")
  1096. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1097. os.RemoveAll(root)
  1098. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1099. }
  1100. err = os.Chdir(repoPath)
  1101. if err != nil {
  1102. os.RemoveAll(root)
  1103. return nil, err
  1104. }
  1105. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1106. os.RemoveAll(root)
  1107. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1108. }
  1109. err = os.Chdir(curdir)
  1110. if err != nil {
  1111. os.RemoveAll(root)
  1112. return nil, err
  1113. }
  1114. var server gitServer
  1115. if !enforceLocalServer {
  1116. // use fakeStorage server, which might be local or remote (at test daemon)
  1117. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1118. if err != nil {
  1119. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1120. }
  1121. } else {
  1122. // always start a local http server on CLI test machin
  1123. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1124. server = &localGitServer{httpServer}
  1125. }
  1126. return &fakeGit{
  1127. root: root,
  1128. server: server,
  1129. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1130. }, nil
  1131. }
  1132. // Write `content` to the file at path `dst`, creating it if necessary,
  1133. // as well as any missing directories.
  1134. // The file is truncated if it already exists.
  1135. // Fail the test when error occures.
  1136. func writeFile(dst, content string, c *check.C) {
  1137. // Create subdirectories if necessary
  1138. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1139. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1140. c.Assert(err, check.IsNil)
  1141. defer f.Close()
  1142. // Write content (truncate if it exists)
  1143. _, err = io.Copy(f, strings.NewReader(content))
  1144. c.Assert(err, check.IsNil)
  1145. }
  1146. // Return the contents of file at path `src`.
  1147. // Fail the test when error occures.
  1148. func readFile(src string, c *check.C) (content string) {
  1149. data, err := ioutil.ReadFile(src)
  1150. c.Assert(err, check.IsNil)
  1151. return string(data)
  1152. }
  1153. func containerStorageFile(containerID, basename string) string {
  1154. return filepath.Join(containerStoragePath, containerID, basename)
  1155. }
  1156. // docker commands that use this function must be run with the '-d' switch.
  1157. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1158. out, _, err := runCommandWithOutput(cmd)
  1159. if err != nil {
  1160. return nil, fmt.Errorf("%v: %q", err, out)
  1161. }
  1162. contID := strings.TrimSpace(out)
  1163. if err := waitRun(contID); err != nil {
  1164. return nil, fmt.Errorf("%v: %q", contID, err)
  1165. }
  1166. return readContainerFile(contID, filename)
  1167. }
  1168. func readContainerFile(containerID, filename string) ([]byte, error) {
  1169. f, err := os.Open(containerStorageFile(containerID, filename))
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. defer f.Close()
  1174. content, err := ioutil.ReadAll(f)
  1175. if err != nil {
  1176. return nil, err
  1177. }
  1178. return content, nil
  1179. }
  1180. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1181. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1182. return []byte(out), err
  1183. }
  1184. // daemonTime provides the current time on the daemon host
  1185. func daemonTime(c *check.C) time.Time {
  1186. if isLocalDaemon {
  1187. return time.Now()
  1188. }
  1189. status, body, err := sockRequest("GET", "/info", nil)
  1190. c.Assert(err, check.IsNil)
  1191. c.Assert(status, check.Equals, http.StatusOK)
  1192. type infoJSON struct {
  1193. SystemTime string
  1194. }
  1195. var info infoJSON
  1196. err = json.Unmarshal(body, &info)
  1197. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1198. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1199. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1200. return dt
  1201. }
  1202. func setupRegistry(c *check.C) *testRegistryV2 {
  1203. testRequires(c, RegistryHosting)
  1204. reg, err := newTestRegistryV2(c)
  1205. c.Assert(err, check.IsNil)
  1206. // Wait for registry to be ready to serve requests.
  1207. for i := 0; i != 5; i++ {
  1208. if err = reg.Ping(); err == nil {
  1209. break
  1210. }
  1211. time.Sleep(100 * time.Millisecond)
  1212. }
  1213. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available"))
  1214. return reg
  1215. }
  1216. func setupNotary(c *check.C) *testNotary {
  1217. testRequires(c, NotaryHosting)
  1218. ts, err := newTestNotary(c)
  1219. c.Assert(err, check.IsNil)
  1220. return ts
  1221. }
  1222. // appendBaseEnv appends the minimum set of environment variables to exec the
  1223. // docker cli binary for testing with correct configuration to the given env
  1224. // list.
  1225. func appendBaseEnv(env []string) []string {
  1226. preserveList := []string{
  1227. // preserve remote test host
  1228. "DOCKER_HOST",
  1229. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1230. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1231. "SystemRoot",
  1232. }
  1233. for _, key := range preserveList {
  1234. if val := os.Getenv(key); val != "" {
  1235. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1236. }
  1237. }
  1238. return env
  1239. }
  1240. func createTmpFile(c *check.C, content string) string {
  1241. f, err := ioutil.TempFile("", "testfile")
  1242. c.Assert(err, check.IsNil)
  1243. filename := f.Name()
  1244. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1245. c.Assert(err, check.IsNil)
  1246. return filename
  1247. }
  1248. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1249. args := []string{"--host", socket}
  1250. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1251. out, exitCode, err := runCommandWithOutput(buildCmd)
  1252. if err != nil || exitCode != 0 {
  1253. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1254. }
  1255. return out, nil
  1256. }
  1257. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1258. args = append(args, []string{"-D", "build", "-t", name}...)
  1259. if !useCache {
  1260. args = append(args, "--no-cache")
  1261. }
  1262. args = append(args, "-")
  1263. buildCmd := exec.Command(dockerBinary, args...)
  1264. buildCmd.Stdin = strings.NewReader(dockerfile)
  1265. return buildCmd
  1266. }
  1267. func waitForContainer(contID string, args ...string) error {
  1268. args = append([]string{"run", "--name", contID}, args...)
  1269. cmd := exec.Command(dockerBinary, args...)
  1270. if _, err := runCommand(cmd); err != nil {
  1271. return err
  1272. }
  1273. if err := waitRun(contID); err != nil {
  1274. return err
  1275. }
  1276. return nil
  1277. }
  1278. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1279. func waitRun(contID string) error {
  1280. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1281. }
  1282. // waitExited will wait for the specified container to state exit, subject
  1283. // to a maximum time limit in seconds supplied by the caller
  1284. func waitExited(contID string, duration time.Duration) error {
  1285. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1286. }
  1287. // waitInspect will wait for the specified container to have the specified string
  1288. // in the inspect output. It will wait until the specified timeout (in seconds)
  1289. // is reached.
  1290. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1291. after := time.After(timeout)
  1292. for {
  1293. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  1294. out, _, err := runCommandWithOutput(cmd)
  1295. if err != nil {
  1296. if !strings.Contains(out, "No such") {
  1297. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1298. }
  1299. select {
  1300. case <-after:
  1301. return err
  1302. default:
  1303. time.Sleep(10 * time.Millisecond)
  1304. continue
  1305. }
  1306. }
  1307. out = strings.TrimSpace(out)
  1308. if out == expected {
  1309. break
  1310. }
  1311. select {
  1312. case <-after:
  1313. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1314. default:
  1315. }
  1316. time.Sleep(100 * time.Millisecond)
  1317. }
  1318. return nil
  1319. }