docker_utils.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  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. d.c.Assert(sockets.ConfigureTransport(transport, proto, addr), check.IsNil)
  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. func getRootUIDGID() (int, int, error) {
  1558. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1559. if len(uidgid) == 1 {
  1560. //user namespace remapping is not turned on; return 0
  1561. return 0, 0, nil
  1562. }
  1563. uid, err := strconv.Atoi(uidgid[0])
  1564. if err != nil {
  1565. return 0, 0, err
  1566. }
  1567. gid, err := strconv.Atoi(uidgid[1])
  1568. if err != nil {
  1569. return 0, 0, err
  1570. }
  1571. return uid, gid, nil
  1572. }
  1573. // minimalBaseImage returns the name of the minimal base image for the current
  1574. // daemon platform.
  1575. func minimalBaseImage() string {
  1576. if daemonPlatform == "windows" {
  1577. return WindowsBaseImage
  1578. }
  1579. return "scratch"
  1580. }