docker_utils.go 49 KB

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