docker_utils.go 52 KB

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