docker_utils.go 42 KB

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