docker_utils.go 48 KB

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