docker_utils.go 52 KB

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