docker_utils.go 47 KB

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