docker_utils.go 41 KB

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