docker_utils.go 37 KB

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