docker_utils.go 51 KB

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