docker_utils.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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. return integration.DockerCmdWithError(dockerBinary, args...)
  776. }
  777. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  778. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  779. }
  780. func dockerCmd(c *check.C, args ...string) (string, int) {
  781. return integration.DockerCmd(dockerBinary, c, args...)
  782. }
  783. // execute a docker command with a timeout
  784. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  785. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  786. }
  787. // execute a docker command in a directory
  788. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  789. return integration.DockerCmdInDir(dockerBinary, path, args...)
  790. }
  791. // execute a docker command in a directory with a timeout
  792. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  793. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  794. }
  795. // find the State.ExitCode in container metadata
  796. func findContainerExitCode(c *check.C, name string, vargs ...string) string {
  797. args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
  798. cmd := exec.Command(dockerBinary, args...)
  799. out, _, err := runCommandWithOutput(cmd)
  800. if err != nil {
  801. c.Fatal(err, out)
  802. }
  803. return out
  804. }
  805. func findContainerIP(c *check.C, id string, network string) string {
  806. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  807. return strings.Trim(out, " \r\n'")
  808. }
  809. func (d *Daemon) findContainerIP(id string) string {
  810. out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id)
  811. if err != nil {
  812. d.c.Log(err)
  813. }
  814. return strings.Trim(out, " \r\n'")
  815. }
  816. func getContainerCount() (int, error) {
  817. const containers = "Containers:"
  818. cmd := exec.Command(dockerBinary, "info")
  819. out, _, err := runCommandWithOutput(cmd)
  820. if err != nil {
  821. return 0, err
  822. }
  823. lines := strings.Split(out, "\n")
  824. for _, line := range lines {
  825. if strings.Contains(line, containers) {
  826. output := strings.TrimSpace(line)
  827. output = strings.TrimLeft(output, containers)
  828. output = strings.Trim(output, " ")
  829. containerCount, err := strconv.Atoi(output)
  830. if err != nil {
  831. return 0, err
  832. }
  833. return containerCount, nil
  834. }
  835. }
  836. return 0, fmt.Errorf("couldn't find the Container count in the output")
  837. }
  838. // FakeContext creates directories that can be used as a build context
  839. type FakeContext struct {
  840. Dir string
  841. }
  842. // Add a file at a path, creating directories where necessary
  843. func (f *FakeContext) Add(file, content string) error {
  844. return f.addFile(file, []byte(content))
  845. }
  846. func (f *FakeContext) addFile(file string, content []byte) error {
  847. filepath := path.Join(f.Dir, file)
  848. dirpath := path.Dir(filepath)
  849. if dirpath != "." {
  850. if err := os.MkdirAll(dirpath, 0755); err != nil {
  851. return err
  852. }
  853. }
  854. return ioutil.WriteFile(filepath, content, 0644)
  855. }
  856. // Delete a file at a path
  857. func (f *FakeContext) Delete(file string) error {
  858. filepath := path.Join(f.Dir, file)
  859. return os.RemoveAll(filepath)
  860. }
  861. // Close deletes the context
  862. func (f *FakeContext) Close() error {
  863. return os.RemoveAll(f.Dir)
  864. }
  865. func fakeContextFromNewTempDir() (*FakeContext, error) {
  866. tmp, err := ioutil.TempDir("", "fake-context")
  867. if err != nil {
  868. return nil, err
  869. }
  870. if err := os.Chmod(tmp, 0755); err != nil {
  871. return nil, err
  872. }
  873. return fakeContextFromDir(tmp), nil
  874. }
  875. func fakeContextFromDir(dir string) *FakeContext {
  876. return &FakeContext{dir}
  877. }
  878. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  879. ctx, err := fakeContextFromNewTempDir()
  880. if err != nil {
  881. return nil, err
  882. }
  883. for file, content := range files {
  884. if err := ctx.Add(file, content); err != nil {
  885. ctx.Close()
  886. return nil, err
  887. }
  888. }
  889. return ctx, nil
  890. }
  891. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  892. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  893. ctx.Close()
  894. return err
  895. }
  896. return nil
  897. }
  898. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  899. ctx, err := fakeContextWithFiles(files)
  900. if err != nil {
  901. return nil, err
  902. }
  903. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  904. return nil, err
  905. }
  906. return ctx, nil
  907. }
  908. // FakeStorage is a static file server. It might be running locally or remotely
  909. // on test host.
  910. type FakeStorage interface {
  911. Close() error
  912. URL() string
  913. CtxDir() string
  914. }
  915. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  916. ctx, err := fakeContextFromNewTempDir()
  917. if err != nil {
  918. return nil, err
  919. }
  920. for name, content := range archives {
  921. if err := ctx.addFile(name, content.Bytes()); err != nil {
  922. return nil, err
  923. }
  924. }
  925. return fakeStorageWithContext(ctx)
  926. }
  927. // fakeStorage returns either a local or remote (at daemon machine) file server
  928. func fakeStorage(files map[string]string) (FakeStorage, error) {
  929. ctx, err := fakeContextWithFiles(files)
  930. if err != nil {
  931. return nil, err
  932. }
  933. return fakeStorageWithContext(ctx)
  934. }
  935. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  936. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  937. if isLocalDaemon {
  938. return newLocalFakeStorage(ctx)
  939. }
  940. return newRemoteFileServer(ctx)
  941. }
  942. // localFileStorage is a file storage on the running machine
  943. type localFileStorage struct {
  944. *FakeContext
  945. *httptest.Server
  946. }
  947. func (s *localFileStorage) URL() string {
  948. return s.Server.URL
  949. }
  950. func (s *localFileStorage) CtxDir() string {
  951. return s.FakeContext.Dir
  952. }
  953. func (s *localFileStorage) Close() error {
  954. defer s.Server.Close()
  955. return s.FakeContext.Close()
  956. }
  957. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  958. handler := http.FileServer(http.Dir(ctx.Dir))
  959. server := httptest.NewServer(handler)
  960. return &localFileStorage{
  961. FakeContext: ctx,
  962. Server: server,
  963. }, nil
  964. }
  965. // remoteFileServer is a containerized static file server started on the remote
  966. // testing machine to be used in URL-accepting docker build functionality.
  967. type remoteFileServer struct {
  968. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  969. container string
  970. image string
  971. ctx *FakeContext
  972. }
  973. func (f *remoteFileServer) URL() string {
  974. u := url.URL{
  975. Scheme: "http",
  976. Host: f.host}
  977. return u.String()
  978. }
  979. func (f *remoteFileServer) CtxDir() string {
  980. return f.ctx.Dir
  981. }
  982. func (f *remoteFileServer) Close() error {
  983. defer func() {
  984. if f.ctx != nil {
  985. f.ctx.Close()
  986. }
  987. if f.image != "" {
  988. deleteImages(f.image)
  989. }
  990. }()
  991. if f.container == "" {
  992. return nil
  993. }
  994. return deleteContainer(f.container)
  995. }
  996. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  997. var (
  998. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  999. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  1000. )
  1001. // Build the image
  1002. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  1003. COPY . /static`); err != nil {
  1004. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  1005. }
  1006. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  1007. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  1008. }
  1009. // Start the container
  1010. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  1011. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1012. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  1013. }
  1014. // Find out the system assigned port
  1015. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  1016. if err != nil {
  1017. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  1018. }
  1019. fileserverHostPort := strings.Trim(out, "\n")
  1020. _, port, err := net.SplitHostPort(fileserverHostPort)
  1021. if err != nil {
  1022. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  1023. }
  1024. dockerHostURL, err := url.Parse(daemonHost())
  1025. if err != nil {
  1026. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  1027. }
  1028. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  1029. if err != nil {
  1030. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  1031. }
  1032. return &remoteFileServer{
  1033. container: container,
  1034. image: image,
  1035. host: fmt.Sprintf("%s:%s", host, port),
  1036. ctx: ctx}, nil
  1037. }
  1038. func inspectFieldAndMarshall(c *check.C, name, field string, output interface{}) {
  1039. str := inspectFieldJSON(c, name, field)
  1040. err := json.Unmarshal([]byte(str), output)
  1041. if c != nil {
  1042. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  1043. }
  1044. }
  1045. func inspectFilter(name, filter string) (string, error) {
  1046. format := fmt.Sprintf("{{%s}}", filter)
  1047. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  1048. out, exitCode, err := runCommandWithOutput(inspectCmd)
  1049. if err != nil || exitCode != 0 {
  1050. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  1051. }
  1052. return strings.TrimSpace(out), nil
  1053. }
  1054. func inspectFieldWithError(name, field string) (string, error) {
  1055. return inspectFilter(name, fmt.Sprintf(".%s", field))
  1056. }
  1057. func inspectField(c *check.C, name, field string) string {
  1058. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  1059. if c != nil {
  1060. c.Assert(err, check.IsNil)
  1061. }
  1062. return out
  1063. }
  1064. func inspectFieldJSON(c *check.C, name, field string) string {
  1065. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  1066. if c != nil {
  1067. c.Assert(err, check.IsNil)
  1068. }
  1069. return out
  1070. }
  1071. func inspectFieldMap(c *check.C, name, path, field string) string {
  1072. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  1073. if c != nil {
  1074. c.Assert(err, check.IsNil)
  1075. }
  1076. return out
  1077. }
  1078. func inspectMountSourceField(name, destination string) (string, error) {
  1079. m, err := inspectMountPoint(name, destination)
  1080. if err != nil {
  1081. return "", err
  1082. }
  1083. return m.Source, nil
  1084. }
  1085. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  1086. out, err := inspectFilter(name, "json .Mounts")
  1087. if err != nil {
  1088. return types.MountPoint{}, err
  1089. }
  1090. return inspectMountPointJSON(out, destination)
  1091. }
  1092. var errMountNotFound = errors.New("mount point not found")
  1093. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  1094. var mp []types.MountPoint
  1095. if err := unmarshalJSON([]byte(j), &mp); err != nil {
  1096. return types.MountPoint{}, err
  1097. }
  1098. var m *types.MountPoint
  1099. for _, c := range mp {
  1100. if c.Destination == destination {
  1101. m = &c
  1102. break
  1103. }
  1104. }
  1105. if m == nil {
  1106. return types.MountPoint{}, errMountNotFound
  1107. }
  1108. return *m, nil
  1109. }
  1110. func getIDByName(name string) (string, error) {
  1111. return inspectFieldWithError(name, "Id")
  1112. }
  1113. // getContainerState returns the exit code of the container
  1114. // and true if it's running
  1115. // the exit code should be ignored if it's running
  1116. func getContainerState(c *check.C, id string) (int, bool, error) {
  1117. var (
  1118. exitStatus int
  1119. running bool
  1120. )
  1121. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  1122. if exitCode != 0 {
  1123. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  1124. }
  1125. out = strings.Trim(out, "\n")
  1126. splitOutput := strings.Split(out, " ")
  1127. if len(splitOutput) != 2 {
  1128. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  1129. }
  1130. if splitOutput[0] == "true" {
  1131. running = true
  1132. }
  1133. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  1134. exitStatus = n
  1135. } else {
  1136. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  1137. }
  1138. return exitStatus, running, nil
  1139. }
  1140. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  1141. args := []string{"-D", "build", "-t", name}
  1142. if !useCache {
  1143. args = append(args, "--no-cache")
  1144. }
  1145. args = append(args, buildFlags...)
  1146. args = append(args, "-")
  1147. buildCmd := exec.Command(dockerBinary, args...)
  1148. buildCmd.Stdin = strings.NewReader(dockerfile)
  1149. return buildCmd
  1150. }
  1151. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  1152. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1153. out, exitCode, err := runCommandWithOutput(buildCmd)
  1154. if err != nil || exitCode != 0 {
  1155. return "", out, fmt.Errorf("failed to build the image: %s", out)
  1156. }
  1157. id, err := getIDByName(name)
  1158. if err != nil {
  1159. return "", out, err
  1160. }
  1161. return id, out, nil
  1162. }
  1163. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  1164. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1165. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1166. if err != nil || exitCode != 0 {
  1167. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1168. }
  1169. id, err := getIDByName(name)
  1170. if err != nil {
  1171. return "", stdout, stderr, err
  1172. }
  1173. return id, stdout, stderr, nil
  1174. }
  1175. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1176. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1177. return id, err
  1178. }
  1179. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1180. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  1181. if err != nil {
  1182. return "", err
  1183. }
  1184. return id, nil
  1185. }
  1186. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  1187. args := []string{"build", "-t", name}
  1188. if !useCache {
  1189. args = append(args, "--no-cache")
  1190. }
  1191. args = append(args, buildFlags...)
  1192. args = append(args, ".")
  1193. buildCmd := exec.Command(dockerBinary, args...)
  1194. buildCmd.Dir = ctx.Dir
  1195. out, exitCode, err := runCommandWithOutput(buildCmd)
  1196. if err != nil || exitCode != 0 {
  1197. return "", "", fmt.Errorf("failed to build the image: %s", out)
  1198. }
  1199. id, err := getIDByName(name)
  1200. if err != nil {
  1201. return "", "", err
  1202. }
  1203. return id, out, nil
  1204. }
  1205. func buildImageFromContextWithStdoutStderr(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, string, error) {
  1206. args := []string{"build", "-t", name}
  1207. if !useCache {
  1208. args = append(args, "--no-cache")
  1209. }
  1210. args = append(args, buildFlags...)
  1211. args = append(args, ".")
  1212. buildCmd := exec.Command(dockerBinary, args...)
  1213. buildCmd.Dir = ctx.Dir
  1214. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1215. if err != nil || exitCode != 0 {
  1216. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1217. }
  1218. id, err := getIDByName(name)
  1219. if err != nil {
  1220. return "", stdout, stderr, err
  1221. }
  1222. return id, stdout, stderr, nil
  1223. }
  1224. func buildImageFromGitWithStdoutStderr(name string, ctx *fakeGit, useCache bool, buildFlags ...string) (string, string, string, error) {
  1225. args := []string{"build", "-t", name}
  1226. if !useCache {
  1227. args = append(args, "--no-cache")
  1228. }
  1229. args = append(args, buildFlags...)
  1230. args = append(args, ctx.RepoURL)
  1231. buildCmd := exec.Command(dockerBinary, args...)
  1232. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1233. if err != nil || exitCode != 0 {
  1234. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1235. }
  1236. id, err := getIDByName(name)
  1237. if err != nil {
  1238. return "", stdout, stderr, err
  1239. }
  1240. return id, stdout, stderr, nil
  1241. }
  1242. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1243. args := []string{"build", "-t", name}
  1244. if !useCache {
  1245. args = append(args, "--no-cache")
  1246. }
  1247. args = append(args, buildFlags...)
  1248. args = append(args, path)
  1249. buildCmd := exec.Command(dockerBinary, args...)
  1250. out, exitCode, err := runCommandWithOutput(buildCmd)
  1251. if err != nil || exitCode != 0 {
  1252. return "", fmt.Errorf("failed to build the image: %s", out)
  1253. }
  1254. return getIDByName(name)
  1255. }
  1256. type gitServer interface {
  1257. URL() string
  1258. Close() error
  1259. }
  1260. type localGitServer struct {
  1261. *httptest.Server
  1262. }
  1263. func (r *localGitServer) Close() error {
  1264. r.Server.Close()
  1265. return nil
  1266. }
  1267. func (r *localGitServer) URL() string {
  1268. return r.Server.URL
  1269. }
  1270. type fakeGit struct {
  1271. root string
  1272. server gitServer
  1273. RepoURL string
  1274. }
  1275. func (g *fakeGit) Close() {
  1276. g.server.Close()
  1277. os.RemoveAll(g.root)
  1278. }
  1279. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1280. ctx, err := fakeContextWithFiles(files)
  1281. if err != nil {
  1282. return nil, err
  1283. }
  1284. defer ctx.Close()
  1285. curdir, err := os.Getwd()
  1286. if err != nil {
  1287. return nil, err
  1288. }
  1289. defer os.Chdir(curdir)
  1290. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1291. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1292. }
  1293. err = os.Chdir(ctx.Dir)
  1294. if err != nil {
  1295. return nil, err
  1296. }
  1297. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1298. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1299. }
  1300. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1301. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1302. }
  1303. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1304. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1305. }
  1306. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1307. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1308. }
  1309. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. repoPath := filepath.Join(root, name+".git")
  1314. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1315. os.RemoveAll(root)
  1316. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1317. }
  1318. err = os.Chdir(repoPath)
  1319. if err != nil {
  1320. os.RemoveAll(root)
  1321. return nil, err
  1322. }
  1323. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1324. os.RemoveAll(root)
  1325. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1326. }
  1327. err = os.Chdir(curdir)
  1328. if err != nil {
  1329. os.RemoveAll(root)
  1330. return nil, err
  1331. }
  1332. var server gitServer
  1333. if !enforceLocalServer {
  1334. // use fakeStorage server, which might be local or remote (at test daemon)
  1335. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1336. if err != nil {
  1337. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1338. }
  1339. } else {
  1340. // always start a local http server on CLI test machine
  1341. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1342. server = &localGitServer{httpServer}
  1343. }
  1344. return &fakeGit{
  1345. root: root,
  1346. server: server,
  1347. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1348. }, nil
  1349. }
  1350. // Write `content` to the file at path `dst`, creating it if necessary,
  1351. // as well as any missing directories.
  1352. // The file is truncated if it already exists.
  1353. // Fail the test when error occurs.
  1354. func writeFile(dst, content string, c *check.C) {
  1355. // Create subdirectories if necessary
  1356. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1357. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1358. c.Assert(err, check.IsNil)
  1359. defer f.Close()
  1360. // Write content (truncate if it exists)
  1361. _, err = io.Copy(f, strings.NewReader(content))
  1362. c.Assert(err, check.IsNil)
  1363. }
  1364. // Return the contents of file at path `src`.
  1365. // Fail the test when error occurs.
  1366. func readFile(src string, c *check.C) (content string) {
  1367. data, err := ioutil.ReadFile(src)
  1368. c.Assert(err, check.IsNil)
  1369. return string(data)
  1370. }
  1371. func containerStorageFile(containerID, basename string) string {
  1372. return filepath.Join(containerStoragePath, containerID, basename)
  1373. }
  1374. // docker commands that use this function must be run with the '-d' switch.
  1375. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1376. out, _, err := runCommandWithOutput(cmd)
  1377. if err != nil {
  1378. return nil, fmt.Errorf("%v: %q", err, out)
  1379. }
  1380. contID := strings.TrimSpace(out)
  1381. if err := waitRun(contID); err != nil {
  1382. return nil, fmt.Errorf("%v: %q", contID, err)
  1383. }
  1384. return readContainerFile(contID, filename)
  1385. }
  1386. func readContainerFile(containerID, filename string) ([]byte, error) {
  1387. f, err := os.Open(containerStorageFile(containerID, filename))
  1388. if err != nil {
  1389. return nil, err
  1390. }
  1391. defer f.Close()
  1392. content, err := ioutil.ReadAll(f)
  1393. if err != nil {
  1394. return nil, err
  1395. }
  1396. return content, nil
  1397. }
  1398. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1399. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1400. return []byte(out), err
  1401. }
  1402. // daemonTime provides the current time on the daemon host
  1403. func daemonTime(c *check.C) time.Time {
  1404. if isLocalDaemon {
  1405. return time.Now()
  1406. }
  1407. status, body, err := sockRequest("GET", "/info", nil)
  1408. c.Assert(err, check.IsNil)
  1409. c.Assert(status, check.Equals, http.StatusOK)
  1410. type infoJSON struct {
  1411. SystemTime string
  1412. }
  1413. var info infoJSON
  1414. err = json.Unmarshal(body, &info)
  1415. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1416. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1417. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1418. return dt
  1419. }
  1420. func setupRegistry(c *check.C, schema1, auth bool) *testRegistryV2 {
  1421. reg, err := newTestRegistryV2(c, schema1, auth)
  1422. c.Assert(err, check.IsNil)
  1423. // Wait for registry to be ready to serve requests.
  1424. for i := 0; i != 50; i++ {
  1425. if err = reg.Ping(); err == nil {
  1426. break
  1427. }
  1428. time.Sleep(100 * time.Millisecond)
  1429. }
  1430. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  1431. return reg
  1432. }
  1433. func setupNotary(c *check.C) *testNotary {
  1434. ts, err := newTestNotary(c)
  1435. c.Assert(err, check.IsNil)
  1436. return ts
  1437. }
  1438. // appendBaseEnv appends the minimum set of environment variables to exec the
  1439. // docker cli binary for testing with correct configuration to the given env
  1440. // list.
  1441. func appendBaseEnv(env []string) []string {
  1442. preserveList := []string{
  1443. // preserve remote test host
  1444. "DOCKER_HOST",
  1445. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1446. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1447. "SystemRoot",
  1448. }
  1449. for _, key := range preserveList {
  1450. if val := os.Getenv(key); val != "" {
  1451. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1452. }
  1453. }
  1454. return env
  1455. }
  1456. func createTmpFile(c *check.C, content string) string {
  1457. f, err := ioutil.TempFile("", "testfile")
  1458. c.Assert(err, check.IsNil)
  1459. filename := f.Name()
  1460. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1461. c.Assert(err, check.IsNil)
  1462. return filename
  1463. }
  1464. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1465. args := []string{"--host", socket}
  1466. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1467. out, exitCode, err := runCommandWithOutput(buildCmd)
  1468. if err != nil || exitCode != 0 {
  1469. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1470. }
  1471. return out, nil
  1472. }
  1473. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1474. args = append(args, []string{"-D", "build", "-t", name}...)
  1475. if !useCache {
  1476. args = append(args, "--no-cache")
  1477. }
  1478. args = append(args, "-")
  1479. buildCmd := exec.Command(dockerBinary, args...)
  1480. buildCmd.Stdin = strings.NewReader(dockerfile)
  1481. return buildCmd
  1482. }
  1483. func waitForContainer(contID string, args ...string) error {
  1484. args = append([]string{"run", "--name", contID}, args...)
  1485. cmd := exec.Command(dockerBinary, args...)
  1486. if _, err := runCommand(cmd); err != nil {
  1487. return err
  1488. }
  1489. if err := waitRun(contID); err != nil {
  1490. return err
  1491. }
  1492. return nil
  1493. }
  1494. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1495. func waitRun(contID string) error {
  1496. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1497. }
  1498. // waitExited will wait for the specified container to state exit, subject
  1499. // to a maximum time limit in seconds supplied by the caller
  1500. func waitExited(contID string, duration time.Duration) error {
  1501. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1502. }
  1503. // waitInspect will wait for the specified container to have the specified string
  1504. // in the inspect output. It will wait until the specified timeout (in seconds)
  1505. // is reached.
  1506. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1507. return waitInspectWithArgs(name, expr, expected, timeout)
  1508. }
  1509. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1510. after := time.After(timeout)
  1511. args := append(arg, "inspect", "-f", expr, name)
  1512. for {
  1513. cmd := exec.Command(dockerBinary, args...)
  1514. out, _, err := runCommandWithOutput(cmd)
  1515. if err != nil {
  1516. if !strings.Contains(out, "No such") {
  1517. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1518. }
  1519. select {
  1520. case <-after:
  1521. return err
  1522. default:
  1523. time.Sleep(10 * time.Millisecond)
  1524. continue
  1525. }
  1526. }
  1527. out = strings.TrimSpace(out)
  1528. if out == expected {
  1529. break
  1530. }
  1531. select {
  1532. case <-after:
  1533. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1534. default:
  1535. }
  1536. time.Sleep(100 * time.Millisecond)
  1537. }
  1538. return nil
  1539. }
  1540. func getInspectBody(c *check.C, version, id string) []byte {
  1541. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1542. status, body, err := sockRequest("GET", endpoint, nil)
  1543. c.Assert(err, check.IsNil)
  1544. c.Assert(status, check.Equals, http.StatusOK)
  1545. return body
  1546. }
  1547. // Run a long running idle task in a background container using the
  1548. // system-specific default image and command.
  1549. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1550. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1551. }
  1552. // Run a long running idle task in a background container using the specified
  1553. // image and the system-specific command.
  1554. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1555. args := []string{"run", "-d"}
  1556. args = append(args, extraArgs...)
  1557. args = append(args, image)
  1558. args = append(args, defaultSleepCommand...)
  1559. return dockerCmd(c, args...)
  1560. }
  1561. func getRootUIDGID() (int, int, error) {
  1562. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1563. if len(uidgid) == 1 {
  1564. //user namespace remapping is not turned on; return 0
  1565. return 0, 0, nil
  1566. }
  1567. uid, err := strconv.Atoi(uidgid[0])
  1568. if err != nil {
  1569. return 0, 0, err
  1570. }
  1571. gid, err := strconv.Atoi(uidgid[1])
  1572. if err != nil {
  1573. return 0, 0, err
  1574. }
  1575. return uid, gid, nil
  1576. }
  1577. // minimalBaseImage returns the name of the minimal base image for the current
  1578. // daemon platform.
  1579. func minimalBaseImage() string {
  1580. if daemonPlatform == "windows" {
  1581. return WindowsBaseImage
  1582. }
  1583. return "scratch"
  1584. }