docker_utils.go 38 KB

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