docker_utils.go 52 KB

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