docker_utils.go 36 KB

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