docker_utils.go 43 KB

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