docker_utils.go 44 KB

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