docker_utils.go 37 KB

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