docker_utils.go 43 KB

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