docker_utils.go 38 KB

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