docker_utils.go 52 KB

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