docker_utils.go 38 KB

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