docker_utils.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  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 daemonHost() string {
  472. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  473. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  474. daemonURLStr = daemonHostVar
  475. }
  476. return daemonURLStr
  477. }
  478. func getTLSConfig() (*tls.Config, error) {
  479. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  480. if dockerCertPath == "" {
  481. return nil, fmt.Errorf("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  482. }
  483. option := &tlsconfig.Options{
  484. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  485. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  486. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  487. }
  488. tlsConfig, err := tlsconfig.Client(*option)
  489. if err != nil {
  490. return nil, err
  491. }
  492. return tlsConfig, nil
  493. }
  494. func sockConn(timeout time.Duration) (net.Conn, error) {
  495. daemon := daemonHost()
  496. daemonURL, err := url.Parse(daemon)
  497. if err != nil {
  498. return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
  499. }
  500. var c net.Conn
  501. switch daemonURL.Scheme {
  502. case "unix":
  503. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  504. case "tcp":
  505. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  506. // Setup the socket TLS configuration.
  507. tlsConfig, err := getTLSConfig()
  508. if err != nil {
  509. return nil, err
  510. }
  511. dialer := &net.Dialer{Timeout: timeout}
  512. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  513. }
  514. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  515. default:
  516. return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  517. }
  518. }
  519. func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  520. jsonData := bytes.NewBuffer(nil)
  521. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  522. return -1, nil, err
  523. }
  524. res, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
  525. if err != nil {
  526. return -1, nil, err
  527. }
  528. b, err := readBody(body)
  529. return res.StatusCode, b, err
  530. }
  531. func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
  532. req, client, err := newRequestClient(method, endpoint, data, ct)
  533. if err != nil {
  534. return nil, nil, err
  535. }
  536. resp, err := client.Do(req)
  537. if err != nil {
  538. client.Close()
  539. return nil, nil, err
  540. }
  541. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  542. defer resp.Body.Close()
  543. return client.Close()
  544. })
  545. return resp, body, nil
  546. }
  547. func sockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {
  548. req, client, err := newRequestClient(method, endpoint, data, ct)
  549. if err != nil {
  550. return nil, nil, err
  551. }
  552. client.Do(req)
  553. conn, br := client.Hijack()
  554. return conn, br, nil
  555. }
  556. func newRequestClient(method, endpoint string, data io.Reader, ct string) (*http.Request, *httputil.ClientConn, error) {
  557. c, err := sockConn(time.Duration(10 * time.Second))
  558. if err != nil {
  559. return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  560. }
  561. client := httputil.NewClientConn(c, nil)
  562. req, err := http.NewRequest(method, endpoint, data)
  563. if err != nil {
  564. client.Close()
  565. return nil, nil, fmt.Errorf("could not create new request: %v", err)
  566. }
  567. if ct != "" {
  568. req.Header.Set("Content-Type", ct)
  569. }
  570. return req, client, nil
  571. }
  572. func readBody(b io.ReadCloser) ([]byte, error) {
  573. defer b.Close()
  574. return ioutil.ReadAll(b)
  575. }
  576. func deleteContainer(container string) error {
  577. container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
  578. rmArgs := strings.Split(fmt.Sprintf("rm -fv %v", container), " ")
  579. exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
  580. // set error manually if not set
  581. if exitCode != 0 && err == nil {
  582. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  583. }
  584. return err
  585. }
  586. func getAllContainers() (string, error) {
  587. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  588. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  589. if exitCode != 0 && err == nil {
  590. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  591. }
  592. return out, err
  593. }
  594. func deleteAllContainers() error {
  595. containers, err := getAllContainers()
  596. if err != nil {
  597. fmt.Println(containers)
  598. return err
  599. }
  600. if containers != "" {
  601. if err = deleteContainer(containers); err != nil {
  602. return err
  603. }
  604. }
  605. return nil
  606. }
  607. func deleteAllNetworks() error {
  608. networks, err := getAllNetworks()
  609. if err != nil {
  610. return err
  611. }
  612. var errors []string
  613. for _, n := range networks {
  614. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  615. continue
  616. }
  617. status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
  618. if err != nil {
  619. errors = append(errors, err.Error())
  620. continue
  621. }
  622. if status != http.StatusNoContent {
  623. errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  624. }
  625. }
  626. if len(errors) > 0 {
  627. return fmt.Errorf(strings.Join(errors, "\n"))
  628. }
  629. return nil
  630. }
  631. func getAllNetworks() ([]types.NetworkResource, error) {
  632. var networks []types.NetworkResource
  633. _, b, err := sockRequest("GET", "/networks", nil)
  634. if err != nil {
  635. return nil, err
  636. }
  637. if err := json.Unmarshal(b, &networks); err != nil {
  638. return nil, err
  639. }
  640. return networks, nil
  641. }
  642. func deleteAllVolumes() error {
  643. volumes, err := getAllVolumes()
  644. if err != nil {
  645. return err
  646. }
  647. var errors []string
  648. for _, v := range volumes {
  649. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
  650. if err != nil {
  651. errors = append(errors, err.Error())
  652. continue
  653. }
  654. if status != http.StatusNoContent {
  655. errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  656. }
  657. }
  658. if len(errors) > 0 {
  659. return fmt.Errorf(strings.Join(errors, "\n"))
  660. }
  661. return nil
  662. }
  663. func getAllVolumes() ([]*types.Volume, error) {
  664. var volumes types.VolumesListResponse
  665. _, b, err := sockRequest("GET", "/volumes", nil)
  666. if err != nil {
  667. return nil, err
  668. }
  669. if err := json.Unmarshal(b, &volumes); err != nil {
  670. return nil, err
  671. }
  672. return volumes.Volumes, nil
  673. }
  674. var protectedImages = map[string]struct{}{}
  675. func deleteAllImages() error {
  676. cmd := exec.Command(dockerBinary, "images")
  677. cmd.Env = appendBaseEnv(true)
  678. out, err := cmd.CombinedOutput()
  679. if err != nil {
  680. return err
  681. }
  682. lines := strings.Split(string(out), "\n")[1:]
  683. var imgs []string
  684. for _, l := range lines {
  685. if l == "" {
  686. continue
  687. }
  688. fields := strings.Fields(l)
  689. imgTag := fields[0] + ":" + fields[1]
  690. if _, ok := protectedImages[imgTag]; !ok {
  691. if fields[0] == "<none>" {
  692. imgs = append(imgs, fields[2])
  693. continue
  694. }
  695. imgs = append(imgs, imgTag)
  696. }
  697. }
  698. if len(imgs) == 0 {
  699. return nil
  700. }
  701. args := append([]string{"rmi", "-f"}, imgs...)
  702. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  703. return err
  704. }
  705. return nil
  706. }
  707. func getPausedContainers() (string, error) {
  708. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  709. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  710. if exitCode != 0 && err == nil {
  711. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  712. }
  713. return out, err
  714. }
  715. func getSliceOfPausedContainers() ([]string, error) {
  716. out, err := getPausedContainers()
  717. if err == nil {
  718. if len(out) == 0 {
  719. return nil, err
  720. }
  721. slice := strings.Split(strings.TrimSpace(out), "\n")
  722. return slice, err
  723. }
  724. return []string{out}, err
  725. }
  726. func unpauseContainer(container string) error {
  727. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  728. exitCode, err := runCommand(unpauseCmd)
  729. if exitCode != 0 && err == nil {
  730. err = fmt.Errorf("failed to unpause container")
  731. }
  732. return nil
  733. }
  734. func unpauseAllContainers() error {
  735. containers, err := getPausedContainers()
  736. if err != nil {
  737. fmt.Println(containers)
  738. return err
  739. }
  740. containers = strings.Replace(containers, "\n", " ", -1)
  741. containers = strings.Trim(containers, " ")
  742. containerList := strings.Split(containers, " ")
  743. for _, value := range containerList {
  744. if err = unpauseContainer(value); err != nil {
  745. return err
  746. }
  747. }
  748. return nil
  749. }
  750. func deleteImages(images ...string) error {
  751. args := []string{"rmi", "-f"}
  752. args = append(args, images...)
  753. rmiCmd := exec.Command(dockerBinary, args...)
  754. exitCode, err := runCommand(rmiCmd)
  755. // set error manually if not set
  756. if exitCode != 0 && err == nil {
  757. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  758. }
  759. return err
  760. }
  761. func imageExists(image string) error {
  762. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  763. exitCode, err := runCommand(inspectCmd)
  764. if exitCode != 0 && err == nil {
  765. err = fmt.Errorf("couldn't find image %q", image)
  766. }
  767. return err
  768. }
  769. func pullImageIfNotExist(image string) error {
  770. if err := imageExists(image); err != nil {
  771. pullCmd := exec.Command(dockerBinary, "pull", image)
  772. _, exitCode, err := runCommandWithOutput(pullCmd)
  773. if err != nil || exitCode != 0 {
  774. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  775. }
  776. }
  777. return nil
  778. }
  779. func dockerCmdWithError(args ...string) (string, int, error) {
  780. if err := validateArgs(args...); err != nil {
  781. return "", 0, err
  782. }
  783. return integration.DockerCmdWithError(dockerBinary, args...)
  784. }
  785. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  786. if err := validateArgs(args...); err != nil {
  787. c.Fatalf(err.Error())
  788. }
  789. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  790. }
  791. func dockerCmd(c *check.C, args ...string) (string, int) {
  792. if err := validateArgs(args...); err != nil {
  793. c.Fatalf(err.Error())
  794. }
  795. return integration.DockerCmd(dockerBinary, c, args...)
  796. }
  797. // execute a docker command with a timeout
  798. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  799. if err := validateArgs(args...); err != nil {
  800. return "", 0, err
  801. }
  802. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  803. }
  804. // execute a docker command in a directory
  805. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  806. if err := validateArgs(args...); err != nil {
  807. c.Fatalf(err.Error())
  808. }
  809. return integration.DockerCmdInDir(dockerBinary, path, args...)
  810. }
  811. // execute a docker command in a directory with a timeout
  812. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  813. if err := validateArgs(args...); err != nil {
  814. return "", 0, err
  815. }
  816. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  817. }
  818. // validateArgs is a checker to ensure tests are not running commands which are
  819. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  820. func validateArgs(args ...string) error {
  821. if daemonPlatform != "windows" {
  822. return nil
  823. }
  824. foundBusybox := -1
  825. for key, value := range args {
  826. if strings.ToLower(value) == "busybox" {
  827. foundBusybox = key
  828. }
  829. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  830. return errors.New("Cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  831. }
  832. }
  833. return nil
  834. }
  835. // find the State.ExitCode in container metadata
  836. func findContainerExitCode(c *check.C, name string, vargs ...string) string {
  837. args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
  838. cmd := exec.Command(dockerBinary, args...)
  839. out, _, err := runCommandWithOutput(cmd)
  840. if err != nil {
  841. c.Fatal(err, out)
  842. }
  843. return out
  844. }
  845. func findContainerIP(c *check.C, id string, network string) string {
  846. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  847. return strings.Trim(out, " \r\n'")
  848. }
  849. func (d *Daemon) findContainerIP(id string) string {
  850. out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id)
  851. if err != nil {
  852. d.c.Log(err)
  853. }
  854. return strings.Trim(out, " \r\n'")
  855. }
  856. func getContainerCount() (int, error) {
  857. const containers = "Containers:"
  858. cmd := exec.Command(dockerBinary, "info")
  859. out, _, err := runCommandWithOutput(cmd)
  860. if err != nil {
  861. return 0, err
  862. }
  863. lines := strings.Split(out, "\n")
  864. for _, line := range lines {
  865. if strings.Contains(line, containers) {
  866. output := strings.TrimSpace(line)
  867. output = strings.TrimLeft(output, containers)
  868. output = strings.Trim(output, " ")
  869. containerCount, err := strconv.Atoi(output)
  870. if err != nil {
  871. return 0, err
  872. }
  873. return containerCount, nil
  874. }
  875. }
  876. return 0, fmt.Errorf("couldn't find the Container count in the output")
  877. }
  878. // FakeContext creates directories that can be used as a build context
  879. type FakeContext struct {
  880. Dir string
  881. }
  882. // Add a file at a path, creating directories where necessary
  883. func (f *FakeContext) Add(file, content string) error {
  884. return f.addFile(file, []byte(content))
  885. }
  886. func (f *FakeContext) addFile(file string, content []byte) error {
  887. filepath := path.Join(f.Dir, file)
  888. dirpath := path.Dir(filepath)
  889. if dirpath != "." {
  890. if err := os.MkdirAll(dirpath, 0755); err != nil {
  891. return err
  892. }
  893. }
  894. return ioutil.WriteFile(filepath, content, 0644)
  895. }
  896. // Delete a file at a path
  897. func (f *FakeContext) Delete(file string) error {
  898. filepath := path.Join(f.Dir, file)
  899. return os.RemoveAll(filepath)
  900. }
  901. // Close deletes the context
  902. func (f *FakeContext) Close() error {
  903. return os.RemoveAll(f.Dir)
  904. }
  905. func fakeContextFromNewTempDir() (*FakeContext, error) {
  906. tmp, err := ioutil.TempDir("", "fake-context")
  907. if err != nil {
  908. return nil, err
  909. }
  910. if err := os.Chmod(tmp, 0755); err != nil {
  911. return nil, err
  912. }
  913. return fakeContextFromDir(tmp), nil
  914. }
  915. func fakeContextFromDir(dir string) *FakeContext {
  916. return &FakeContext{dir}
  917. }
  918. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  919. ctx, err := fakeContextFromNewTempDir()
  920. if err != nil {
  921. return nil, err
  922. }
  923. for file, content := range files {
  924. if err := ctx.Add(file, content); err != nil {
  925. ctx.Close()
  926. return nil, err
  927. }
  928. }
  929. return ctx, nil
  930. }
  931. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  932. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  933. ctx.Close()
  934. return err
  935. }
  936. return nil
  937. }
  938. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  939. ctx, err := fakeContextWithFiles(files)
  940. if err != nil {
  941. return nil, err
  942. }
  943. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  944. return nil, err
  945. }
  946. return ctx, nil
  947. }
  948. // FakeStorage is a static file server. It might be running locally or remotely
  949. // on test host.
  950. type FakeStorage interface {
  951. Close() error
  952. URL() string
  953. CtxDir() string
  954. }
  955. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  956. ctx, err := fakeContextFromNewTempDir()
  957. if err != nil {
  958. return nil, err
  959. }
  960. for name, content := range archives {
  961. if err := ctx.addFile(name, content.Bytes()); err != nil {
  962. return nil, err
  963. }
  964. }
  965. return fakeStorageWithContext(ctx)
  966. }
  967. // fakeStorage returns either a local or remote (at daemon machine) file server
  968. func fakeStorage(files map[string]string) (FakeStorage, error) {
  969. ctx, err := fakeContextWithFiles(files)
  970. if err != nil {
  971. return nil, err
  972. }
  973. return fakeStorageWithContext(ctx)
  974. }
  975. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  976. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  977. if isLocalDaemon {
  978. return newLocalFakeStorage(ctx)
  979. }
  980. return newRemoteFileServer(ctx)
  981. }
  982. // localFileStorage is a file storage on the running machine
  983. type localFileStorage struct {
  984. *FakeContext
  985. *httptest.Server
  986. }
  987. func (s *localFileStorage) URL() string {
  988. return s.Server.URL
  989. }
  990. func (s *localFileStorage) CtxDir() string {
  991. return s.FakeContext.Dir
  992. }
  993. func (s *localFileStorage) Close() error {
  994. defer s.Server.Close()
  995. return s.FakeContext.Close()
  996. }
  997. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  998. handler := http.FileServer(http.Dir(ctx.Dir))
  999. server := httptest.NewServer(handler)
  1000. return &localFileStorage{
  1001. FakeContext: ctx,
  1002. Server: server,
  1003. }, nil
  1004. }
  1005. // remoteFileServer is a containerized static file server started on the remote
  1006. // testing machine to be used in URL-accepting docker build functionality.
  1007. type remoteFileServer struct {
  1008. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  1009. container string
  1010. image string
  1011. ctx *FakeContext
  1012. }
  1013. func (f *remoteFileServer) URL() string {
  1014. u := url.URL{
  1015. Scheme: "http",
  1016. Host: f.host}
  1017. return u.String()
  1018. }
  1019. func (f *remoteFileServer) CtxDir() string {
  1020. return f.ctx.Dir
  1021. }
  1022. func (f *remoteFileServer) Close() error {
  1023. defer func() {
  1024. if f.ctx != nil {
  1025. f.ctx.Close()
  1026. }
  1027. if f.image != "" {
  1028. deleteImages(f.image)
  1029. }
  1030. }()
  1031. if f.container == "" {
  1032. return nil
  1033. }
  1034. return deleteContainer(f.container)
  1035. }
  1036. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  1037. var (
  1038. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  1039. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  1040. )
  1041. // Build the image
  1042. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  1043. COPY . /static`); err != nil {
  1044. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  1045. }
  1046. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  1047. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  1048. }
  1049. // Start the container
  1050. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  1051. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1052. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  1053. }
  1054. // Find out the system assigned port
  1055. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  1056. if err != nil {
  1057. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  1058. }
  1059. fileserverHostPort := strings.Trim(out, "\n")
  1060. _, port, err := net.SplitHostPort(fileserverHostPort)
  1061. if err != nil {
  1062. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  1063. }
  1064. dockerHostURL, err := url.Parse(daemonHost())
  1065. if err != nil {
  1066. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  1067. }
  1068. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  1069. if err != nil {
  1070. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  1071. }
  1072. return &remoteFileServer{
  1073. container: container,
  1074. image: image,
  1075. host: fmt.Sprintf("%s:%s", host, port),
  1076. ctx: ctx}, nil
  1077. }
  1078. func inspectFieldAndMarshall(c *check.C, name, field string, output interface{}) {
  1079. str := inspectFieldJSON(c, name, field)
  1080. err := json.Unmarshal([]byte(str), output)
  1081. if c != nil {
  1082. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  1083. }
  1084. }
  1085. func inspectFilter(name, filter string) (string, error) {
  1086. format := fmt.Sprintf("{{%s}}", filter)
  1087. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  1088. out, exitCode, err := runCommandWithOutput(inspectCmd)
  1089. if err != nil || exitCode != 0 {
  1090. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  1091. }
  1092. return strings.TrimSpace(out), nil
  1093. }
  1094. func inspectFieldWithError(name, field string) (string, error) {
  1095. return inspectFilter(name, fmt.Sprintf(".%s", field))
  1096. }
  1097. func inspectField(c *check.C, name, field string) string {
  1098. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  1099. if c != nil {
  1100. c.Assert(err, check.IsNil)
  1101. }
  1102. return out
  1103. }
  1104. func inspectFieldJSON(c *check.C, name, field string) string {
  1105. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  1106. if c != nil {
  1107. c.Assert(err, check.IsNil)
  1108. }
  1109. return out
  1110. }
  1111. func inspectFieldMap(c *check.C, name, path, field string) string {
  1112. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  1113. if c != nil {
  1114. c.Assert(err, check.IsNil)
  1115. }
  1116. return out
  1117. }
  1118. func inspectMountSourceField(name, destination string) (string, error) {
  1119. m, err := inspectMountPoint(name, destination)
  1120. if err != nil {
  1121. return "", err
  1122. }
  1123. return m.Source, nil
  1124. }
  1125. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  1126. out, err := inspectFilter(name, "json .Mounts")
  1127. if err != nil {
  1128. return types.MountPoint{}, err
  1129. }
  1130. return inspectMountPointJSON(out, destination)
  1131. }
  1132. var errMountNotFound = errors.New("mount point not found")
  1133. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  1134. var mp []types.MountPoint
  1135. if err := unmarshalJSON([]byte(j), &mp); err != nil {
  1136. return types.MountPoint{}, err
  1137. }
  1138. var m *types.MountPoint
  1139. for _, c := range mp {
  1140. if c.Destination == destination {
  1141. m = &c
  1142. break
  1143. }
  1144. }
  1145. if m == nil {
  1146. return types.MountPoint{}, errMountNotFound
  1147. }
  1148. return *m, nil
  1149. }
  1150. func getIDByName(name string) (string, error) {
  1151. return inspectFieldWithError(name, "Id")
  1152. }
  1153. // getContainerState returns the exit code of the container
  1154. // and true if it's running
  1155. // the exit code should be ignored if it's running
  1156. func getContainerState(c *check.C, id string) (int, bool, error) {
  1157. var (
  1158. exitStatus int
  1159. running bool
  1160. )
  1161. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  1162. if exitCode != 0 {
  1163. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  1164. }
  1165. out = strings.Trim(out, "\n")
  1166. splitOutput := strings.Split(out, " ")
  1167. if len(splitOutput) != 2 {
  1168. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  1169. }
  1170. if splitOutput[0] == "true" {
  1171. running = true
  1172. }
  1173. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  1174. exitStatus = n
  1175. } else {
  1176. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  1177. }
  1178. return exitStatus, running, nil
  1179. }
  1180. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  1181. args := []string{"build", "-t", name}
  1182. if !useCache {
  1183. args = append(args, "--no-cache")
  1184. }
  1185. args = append(args, buildFlags...)
  1186. args = append(args, "-")
  1187. buildCmd := exec.Command(dockerBinary, args...)
  1188. buildCmd.Stdin = strings.NewReader(dockerfile)
  1189. return buildCmd
  1190. }
  1191. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  1192. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1193. out, exitCode, err := runCommandWithOutput(buildCmd)
  1194. if err != nil || exitCode != 0 {
  1195. return "", out, fmt.Errorf("failed to build the image: %s", out)
  1196. }
  1197. id, err := getIDByName(name)
  1198. if err != nil {
  1199. return "", out, err
  1200. }
  1201. return id, out, nil
  1202. }
  1203. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  1204. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1205. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1206. if err != nil || exitCode != 0 {
  1207. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1208. }
  1209. id, err := getIDByName(name)
  1210. if err != nil {
  1211. return "", stdout, stderr, err
  1212. }
  1213. return id, stdout, stderr, nil
  1214. }
  1215. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1216. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1217. return id, err
  1218. }
  1219. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1220. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  1221. if err != nil {
  1222. return "", err
  1223. }
  1224. return id, nil
  1225. }
  1226. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  1227. args := []string{"build", "-t", name}
  1228. if !useCache {
  1229. args = append(args, "--no-cache")
  1230. }
  1231. args = append(args, buildFlags...)
  1232. args = append(args, ".")
  1233. buildCmd := exec.Command(dockerBinary, args...)
  1234. buildCmd.Dir = ctx.Dir
  1235. out, exitCode, err := runCommandWithOutput(buildCmd)
  1236. if err != nil || exitCode != 0 {
  1237. return "", "", fmt.Errorf("failed to build the image: %s", out)
  1238. }
  1239. id, err := getIDByName(name)
  1240. if err != nil {
  1241. return "", "", err
  1242. }
  1243. return id, out, nil
  1244. }
  1245. func buildImageFromContextWithStdoutStderr(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, string, error) {
  1246. args := []string{"build", "-t", name}
  1247. if !useCache {
  1248. args = append(args, "--no-cache")
  1249. }
  1250. args = append(args, buildFlags...)
  1251. args = append(args, ".")
  1252. buildCmd := exec.Command(dockerBinary, args...)
  1253. buildCmd.Dir = ctx.Dir
  1254. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1255. if err != nil || exitCode != 0 {
  1256. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1257. }
  1258. id, err := getIDByName(name)
  1259. if err != nil {
  1260. return "", stdout, stderr, err
  1261. }
  1262. return id, stdout, stderr, nil
  1263. }
  1264. func buildImageFromGitWithStdoutStderr(name string, ctx *fakeGit, useCache bool, buildFlags ...string) (string, string, string, error) {
  1265. args := []string{"build", "-t", name}
  1266. if !useCache {
  1267. args = append(args, "--no-cache")
  1268. }
  1269. args = append(args, buildFlags...)
  1270. args = append(args, ctx.RepoURL)
  1271. buildCmd := exec.Command(dockerBinary, args...)
  1272. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1273. if err != nil || exitCode != 0 {
  1274. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1275. }
  1276. id, err := getIDByName(name)
  1277. if err != nil {
  1278. return "", stdout, stderr, err
  1279. }
  1280. return id, stdout, stderr, nil
  1281. }
  1282. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1283. args := []string{"build", "-t", name}
  1284. if !useCache {
  1285. args = append(args, "--no-cache")
  1286. }
  1287. args = append(args, buildFlags...)
  1288. args = append(args, path)
  1289. buildCmd := exec.Command(dockerBinary, args...)
  1290. out, exitCode, err := runCommandWithOutput(buildCmd)
  1291. if err != nil || exitCode != 0 {
  1292. return "", fmt.Errorf("failed to build the image: %s", out)
  1293. }
  1294. return getIDByName(name)
  1295. }
  1296. type gitServer interface {
  1297. URL() string
  1298. Close() error
  1299. }
  1300. type localGitServer struct {
  1301. *httptest.Server
  1302. }
  1303. func (r *localGitServer) Close() error {
  1304. r.Server.Close()
  1305. return nil
  1306. }
  1307. func (r *localGitServer) URL() string {
  1308. return r.Server.URL
  1309. }
  1310. type fakeGit struct {
  1311. root string
  1312. server gitServer
  1313. RepoURL string
  1314. }
  1315. func (g *fakeGit) Close() {
  1316. g.server.Close()
  1317. os.RemoveAll(g.root)
  1318. }
  1319. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1320. ctx, err := fakeContextWithFiles(files)
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. defer ctx.Close()
  1325. curdir, err := os.Getwd()
  1326. if err != nil {
  1327. return nil, err
  1328. }
  1329. defer os.Chdir(curdir)
  1330. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1331. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1332. }
  1333. err = os.Chdir(ctx.Dir)
  1334. if err != nil {
  1335. return nil, err
  1336. }
  1337. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1338. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1339. }
  1340. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1341. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1342. }
  1343. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1344. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1345. }
  1346. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1347. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1348. }
  1349. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1350. if err != nil {
  1351. return nil, err
  1352. }
  1353. repoPath := filepath.Join(root, name+".git")
  1354. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1355. os.RemoveAll(root)
  1356. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1357. }
  1358. err = os.Chdir(repoPath)
  1359. if err != nil {
  1360. os.RemoveAll(root)
  1361. return nil, err
  1362. }
  1363. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1364. os.RemoveAll(root)
  1365. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1366. }
  1367. err = os.Chdir(curdir)
  1368. if err != nil {
  1369. os.RemoveAll(root)
  1370. return nil, err
  1371. }
  1372. var server gitServer
  1373. if !enforceLocalServer {
  1374. // use fakeStorage server, which might be local or remote (at test daemon)
  1375. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1376. if err != nil {
  1377. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1378. }
  1379. } else {
  1380. // always start a local http server on CLI test machine
  1381. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1382. server = &localGitServer{httpServer}
  1383. }
  1384. return &fakeGit{
  1385. root: root,
  1386. server: server,
  1387. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1388. }, nil
  1389. }
  1390. // Write `content` to the file at path `dst`, creating it if necessary,
  1391. // as well as any missing directories.
  1392. // The file is truncated if it already exists.
  1393. // Fail the test when error occurs.
  1394. func writeFile(dst, content string, c *check.C) {
  1395. // Create subdirectories if necessary
  1396. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1397. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1398. c.Assert(err, check.IsNil)
  1399. defer f.Close()
  1400. // Write content (truncate if it exists)
  1401. _, err = io.Copy(f, strings.NewReader(content))
  1402. c.Assert(err, check.IsNil)
  1403. }
  1404. // Return the contents of file at path `src`.
  1405. // Fail the test when error occurs.
  1406. func readFile(src string, c *check.C) (content string) {
  1407. data, err := ioutil.ReadFile(src)
  1408. c.Assert(err, check.IsNil)
  1409. return string(data)
  1410. }
  1411. func containerStorageFile(containerID, basename string) string {
  1412. return filepath.Join(containerStoragePath, containerID, basename)
  1413. }
  1414. // docker commands that use this function must be run with the '-d' switch.
  1415. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1416. out, _, err := runCommandWithOutput(cmd)
  1417. if err != nil {
  1418. return nil, fmt.Errorf("%v: %q", err, out)
  1419. }
  1420. contID := strings.TrimSpace(out)
  1421. if err := waitRun(contID); err != nil {
  1422. return nil, fmt.Errorf("%v: %q", contID, err)
  1423. }
  1424. return readContainerFile(contID, filename)
  1425. }
  1426. func readContainerFile(containerID, filename string) ([]byte, error) {
  1427. f, err := os.Open(containerStorageFile(containerID, filename))
  1428. if err != nil {
  1429. return nil, err
  1430. }
  1431. defer f.Close()
  1432. content, err := ioutil.ReadAll(f)
  1433. if err != nil {
  1434. return nil, err
  1435. }
  1436. return content, nil
  1437. }
  1438. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1439. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1440. return []byte(out), err
  1441. }
  1442. // daemonTime provides the current time on the daemon host
  1443. func daemonTime(c *check.C) time.Time {
  1444. if isLocalDaemon {
  1445. return time.Now()
  1446. }
  1447. status, body, err := sockRequest("GET", "/info", nil)
  1448. c.Assert(err, check.IsNil)
  1449. c.Assert(status, check.Equals, http.StatusOK)
  1450. type infoJSON struct {
  1451. SystemTime string
  1452. }
  1453. var info infoJSON
  1454. err = json.Unmarshal(body, &info)
  1455. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1456. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1457. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1458. return dt
  1459. }
  1460. func setupRegistry(c *check.C, schema1, auth bool) *testRegistryV2 {
  1461. reg, err := newTestRegistryV2(c, schema1, auth)
  1462. c.Assert(err, check.IsNil)
  1463. // Wait for registry to be ready to serve requests.
  1464. for i := 0; i != 50; i++ {
  1465. if err = reg.Ping(); err == nil {
  1466. break
  1467. }
  1468. time.Sleep(100 * time.Millisecond)
  1469. }
  1470. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  1471. return reg
  1472. }
  1473. func setupNotary(c *check.C) *testNotary {
  1474. ts, err := newTestNotary(c)
  1475. c.Assert(err, check.IsNil)
  1476. return ts
  1477. }
  1478. // appendBaseEnv appends the minimum set of environment variables to exec the
  1479. // docker cli binary for testing with correct configuration to the given env
  1480. // list.
  1481. func appendBaseEnv(isTLS bool, env ...string) []string {
  1482. preserveList := []string{
  1483. // preserve remote test host
  1484. "DOCKER_HOST",
  1485. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1486. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1487. "SystemRoot",
  1488. }
  1489. if isTLS {
  1490. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  1491. }
  1492. for _, key := range preserveList {
  1493. if val := os.Getenv(key); val != "" {
  1494. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1495. }
  1496. }
  1497. return env
  1498. }
  1499. func createTmpFile(c *check.C, content string) string {
  1500. f, err := ioutil.TempFile("", "testfile")
  1501. c.Assert(err, check.IsNil)
  1502. filename := f.Name()
  1503. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1504. c.Assert(err, check.IsNil)
  1505. return filename
  1506. }
  1507. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1508. args := []string{"--host", socket}
  1509. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1510. out, exitCode, err := runCommandWithOutput(buildCmd)
  1511. if err != nil || exitCode != 0 {
  1512. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1513. }
  1514. return out, nil
  1515. }
  1516. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1517. args = append(args, []string{"-D", "build", "-t", name}...)
  1518. if !useCache {
  1519. args = append(args, "--no-cache")
  1520. }
  1521. args = append(args, "-")
  1522. buildCmd := exec.Command(dockerBinary, args...)
  1523. buildCmd.Stdin = strings.NewReader(dockerfile)
  1524. return buildCmd
  1525. }
  1526. func waitForContainer(contID string, args ...string) error {
  1527. args = append([]string{"run", "--name", contID}, args...)
  1528. cmd := exec.Command(dockerBinary, args...)
  1529. if _, err := runCommand(cmd); err != nil {
  1530. return err
  1531. }
  1532. if err := waitRun(contID); err != nil {
  1533. return err
  1534. }
  1535. return nil
  1536. }
  1537. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1538. func waitRun(contID string) error {
  1539. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1540. }
  1541. // waitExited will wait for the specified container to state exit, subject
  1542. // to a maximum time limit in seconds supplied by the caller
  1543. func waitExited(contID string, duration time.Duration) error {
  1544. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1545. }
  1546. // waitInspect will wait for the specified container to have the specified string
  1547. // in the inspect output. It will wait until the specified timeout (in seconds)
  1548. // is reached.
  1549. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1550. return waitInspectWithArgs(name, expr, expected, timeout)
  1551. }
  1552. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1553. after := time.After(timeout)
  1554. args := append(arg, "inspect", "-f", expr, name)
  1555. for {
  1556. cmd := exec.Command(dockerBinary, args...)
  1557. out, _, err := runCommandWithOutput(cmd)
  1558. if err != nil {
  1559. if !strings.Contains(out, "No such") {
  1560. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1561. }
  1562. select {
  1563. case <-after:
  1564. return err
  1565. default:
  1566. time.Sleep(10 * time.Millisecond)
  1567. continue
  1568. }
  1569. }
  1570. out = strings.TrimSpace(out)
  1571. if out == expected {
  1572. break
  1573. }
  1574. select {
  1575. case <-after:
  1576. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1577. default:
  1578. }
  1579. time.Sleep(100 * time.Millisecond)
  1580. }
  1581. return nil
  1582. }
  1583. func getInspectBody(c *check.C, version, id string) []byte {
  1584. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1585. status, body, err := sockRequest("GET", endpoint, nil)
  1586. c.Assert(err, check.IsNil)
  1587. c.Assert(status, check.Equals, http.StatusOK)
  1588. return body
  1589. }
  1590. // Run a long running idle task in a background container using the
  1591. // system-specific default image and command.
  1592. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1593. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1594. }
  1595. // Run a long running idle task in a background container using the specified
  1596. // image and the system-specific command.
  1597. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1598. args := []string{"run", "-d"}
  1599. args = append(args, extraArgs...)
  1600. args = append(args, image)
  1601. args = append(args, defaultSleepCommand...)
  1602. return dockerCmd(c, args...)
  1603. }
  1604. func getRootUIDGID() (int, int, error) {
  1605. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1606. if len(uidgid) == 1 {
  1607. //user namespace remapping is not turned on; return 0
  1608. return 0, 0, nil
  1609. }
  1610. uid, err := strconv.Atoi(uidgid[0])
  1611. if err != nil {
  1612. return 0, 0, err
  1613. }
  1614. gid, err := strconv.Atoi(uidgid[1])
  1615. if err != nil {
  1616. return 0, 0, err
  1617. }
  1618. return uid, gid, nil
  1619. }
  1620. // minimalBaseImage returns the name of the minimal base image for the current
  1621. // daemon platform.
  1622. func minimalBaseImage() string {
  1623. if daemonPlatform == "windows" {
  1624. return WindowsBaseImage
  1625. }
  1626. return "scratch"
  1627. }