docker_utils.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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/api/types"
  24. "github.com/docker/docker/opts"
  25. "github.com/docker/docker/pkg/httputils"
  26. "github.com/docker/docker/pkg/integration"
  27. "github.com/docker/docker/pkg/ioutils"
  28. "github.com/docker/docker/pkg/sockets"
  29. "github.com/docker/docker/pkg/stringutils"
  30. "github.com/docker/docker/pkg/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 _, err := d.Cmd("load", "--input", bb); err != nil {
  292. return fmt.Errorf("could not load busybox image: %v", err)
  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 err = deleteContainer(containers); err != nil {
  556. return err
  557. }
  558. return nil
  559. }
  560. func deleteAllNetworks() error {
  561. networks, err := getAllNetworks()
  562. if err != nil {
  563. return err
  564. }
  565. var errors []string
  566. for _, n := range networks {
  567. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  568. continue
  569. }
  570. status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
  571. if err != nil {
  572. errors = append(errors, err.Error())
  573. continue
  574. }
  575. if status != http.StatusNoContent {
  576. errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  577. }
  578. }
  579. if len(errors) > 0 {
  580. return fmt.Errorf(strings.Join(errors, "\n"))
  581. }
  582. return nil
  583. }
  584. func getAllNetworks() ([]types.NetworkResource, error) {
  585. var networks []types.NetworkResource
  586. _, b, err := sockRequest("GET", "/networks", nil)
  587. if err != nil {
  588. return nil, err
  589. }
  590. if err := json.Unmarshal(b, &networks); err != nil {
  591. return nil, err
  592. }
  593. return networks, nil
  594. }
  595. func deleteAllVolumes() error {
  596. volumes, err := getAllVolumes()
  597. if err != nil {
  598. return err
  599. }
  600. var errors []string
  601. for _, v := range volumes {
  602. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
  603. if err != nil {
  604. errors = append(errors, err.Error())
  605. continue
  606. }
  607. if status != http.StatusNoContent {
  608. errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  609. }
  610. }
  611. if len(errors) > 0 {
  612. return fmt.Errorf(strings.Join(errors, "\n"))
  613. }
  614. return nil
  615. }
  616. func getAllVolumes() ([]*types.Volume, error) {
  617. var volumes types.VolumesListResponse
  618. _, b, err := sockRequest("GET", "/volumes", nil)
  619. if err != nil {
  620. return nil, err
  621. }
  622. if err := json.Unmarshal(b, &volumes); err != nil {
  623. return nil, err
  624. }
  625. return volumes.Volumes, nil
  626. }
  627. var protectedImages = map[string]struct{}{}
  628. func deleteAllImages() error {
  629. out, err := exec.Command(dockerBinary, "images").CombinedOutput()
  630. if err != nil {
  631. return err
  632. }
  633. lines := strings.Split(string(out), "\n")[1:]
  634. var imgs []string
  635. for _, l := range lines {
  636. if l == "" {
  637. continue
  638. }
  639. fields := strings.Fields(l)
  640. imgTag := fields[0] + ":" + fields[1]
  641. if _, ok := protectedImages[imgTag]; !ok {
  642. if fields[0] == "<none>" {
  643. imgs = append(imgs, fields[2])
  644. continue
  645. }
  646. imgs = append(imgs, imgTag)
  647. }
  648. }
  649. if len(imgs) == 0 {
  650. return nil
  651. }
  652. args := append([]string{"rmi", "-f"}, imgs...)
  653. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  654. return err
  655. }
  656. return nil
  657. }
  658. func getPausedContainers() (string, error) {
  659. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  660. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  661. if exitCode != 0 && err == nil {
  662. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  663. }
  664. return out, err
  665. }
  666. func getSliceOfPausedContainers() ([]string, error) {
  667. out, err := getPausedContainers()
  668. if err == nil {
  669. if len(out) == 0 {
  670. return nil, err
  671. }
  672. slice := strings.Split(strings.TrimSpace(out), "\n")
  673. return slice, err
  674. }
  675. return []string{out}, err
  676. }
  677. func unpauseContainer(container string) error {
  678. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  679. exitCode, err := runCommand(unpauseCmd)
  680. if exitCode != 0 && err == nil {
  681. err = fmt.Errorf("failed to unpause container")
  682. }
  683. return nil
  684. }
  685. func unpauseAllContainers() error {
  686. containers, err := getPausedContainers()
  687. if err != nil {
  688. fmt.Println(containers)
  689. return err
  690. }
  691. containers = strings.Replace(containers, "\n", " ", -1)
  692. containers = strings.Trim(containers, " ")
  693. containerList := strings.Split(containers, " ")
  694. for _, value := range containerList {
  695. if err = unpauseContainer(value); err != nil {
  696. return err
  697. }
  698. }
  699. return nil
  700. }
  701. func deleteImages(images ...string) error {
  702. args := []string{"rmi", "-f"}
  703. args = append(args, images...)
  704. rmiCmd := exec.Command(dockerBinary, args...)
  705. exitCode, err := runCommand(rmiCmd)
  706. // set error manually if not set
  707. if exitCode != 0 && err == nil {
  708. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  709. }
  710. return err
  711. }
  712. func imageExists(image string) error {
  713. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  714. exitCode, err := runCommand(inspectCmd)
  715. if exitCode != 0 && err == nil {
  716. err = fmt.Errorf("couldn't find image %q", image)
  717. }
  718. return err
  719. }
  720. func pullImageIfNotExist(image string) error {
  721. if err := imageExists(image); err != nil {
  722. pullCmd := exec.Command(dockerBinary, "pull", image)
  723. _, exitCode, err := runCommandWithOutput(pullCmd)
  724. if err != nil || exitCode != 0 {
  725. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  726. }
  727. }
  728. return nil
  729. }
  730. func dockerCmdWithError(args ...string) (string, int, error) {
  731. return integration.DockerCmdWithError(dockerBinary, args...)
  732. }
  733. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  734. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  735. }
  736. func dockerCmd(c *check.C, args ...string) (string, int) {
  737. return integration.DockerCmd(dockerBinary, c, args...)
  738. }
  739. // execute a docker command with a timeout
  740. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  741. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  742. }
  743. // execute a docker command in a directory
  744. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  745. return integration.DockerCmdInDir(dockerBinary, path, args...)
  746. }
  747. // execute a docker command in a directory with a timeout
  748. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  749. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  750. }
  751. // find the State.ExitCode in container metadata
  752. func findContainerExitCode(c *check.C, name string, vargs ...string) string {
  753. args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
  754. cmd := exec.Command(dockerBinary, args...)
  755. out, _, err := runCommandWithOutput(cmd)
  756. if err != nil {
  757. c.Fatal(err, out)
  758. }
  759. return out
  760. }
  761. func findContainerIP(c *check.C, id string, network string) string {
  762. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  763. return strings.Trim(out, " \r\n'")
  764. }
  765. func (d *Daemon) findContainerIP(id string) string {
  766. out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id)
  767. if err != nil {
  768. d.c.Log(err)
  769. }
  770. return strings.Trim(out, " \r\n'")
  771. }
  772. func getContainerCount() (int, error) {
  773. const containers = "Containers:"
  774. cmd := exec.Command(dockerBinary, "info")
  775. out, _, err := runCommandWithOutput(cmd)
  776. if err != nil {
  777. return 0, err
  778. }
  779. lines := strings.Split(out, "\n")
  780. for _, line := range lines {
  781. if strings.Contains(line, containers) {
  782. output := strings.TrimSpace(line)
  783. output = strings.TrimLeft(output, containers)
  784. output = strings.Trim(output, " ")
  785. containerCount, err := strconv.Atoi(output)
  786. if err != nil {
  787. return 0, err
  788. }
  789. return containerCount, nil
  790. }
  791. }
  792. return 0, fmt.Errorf("couldn't find the Container count in the output")
  793. }
  794. // FakeContext creates directories that can be used as a build context
  795. type FakeContext struct {
  796. Dir string
  797. }
  798. // Add a file at a path, creating directories where necessary
  799. func (f *FakeContext) Add(file, content string) error {
  800. return f.addFile(file, []byte(content))
  801. }
  802. func (f *FakeContext) addFile(file string, content []byte) error {
  803. filepath := path.Join(f.Dir, file)
  804. dirpath := path.Dir(filepath)
  805. if dirpath != "." {
  806. if err := os.MkdirAll(dirpath, 0755); err != nil {
  807. return err
  808. }
  809. }
  810. return ioutil.WriteFile(filepath, content, 0644)
  811. }
  812. // Delete a file at a path
  813. func (f *FakeContext) Delete(file string) error {
  814. filepath := path.Join(f.Dir, file)
  815. return os.RemoveAll(filepath)
  816. }
  817. // Close deletes the context
  818. func (f *FakeContext) Close() error {
  819. return os.RemoveAll(f.Dir)
  820. }
  821. func fakeContextFromNewTempDir() (*FakeContext, error) {
  822. tmp, err := ioutil.TempDir("", "fake-context")
  823. if err != nil {
  824. return nil, err
  825. }
  826. if err := os.Chmod(tmp, 0755); err != nil {
  827. return nil, err
  828. }
  829. return fakeContextFromDir(tmp), nil
  830. }
  831. func fakeContextFromDir(dir string) *FakeContext {
  832. return &FakeContext{dir}
  833. }
  834. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  835. ctx, err := fakeContextFromNewTempDir()
  836. if err != nil {
  837. return nil, err
  838. }
  839. for file, content := range files {
  840. if err := ctx.Add(file, content); err != nil {
  841. ctx.Close()
  842. return nil, err
  843. }
  844. }
  845. return ctx, nil
  846. }
  847. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  848. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  849. ctx.Close()
  850. return err
  851. }
  852. return nil
  853. }
  854. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  855. ctx, err := fakeContextWithFiles(files)
  856. if err != nil {
  857. return nil, err
  858. }
  859. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  860. return nil, err
  861. }
  862. return ctx, nil
  863. }
  864. // FakeStorage is a static file server. It might be running locally or remotely
  865. // on test host.
  866. type FakeStorage interface {
  867. Close() error
  868. URL() string
  869. CtxDir() string
  870. }
  871. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  872. ctx, err := fakeContextFromNewTempDir()
  873. if err != nil {
  874. return nil, err
  875. }
  876. for name, content := range archives {
  877. if err := ctx.addFile(name, content.Bytes()); err != nil {
  878. return nil, err
  879. }
  880. }
  881. return fakeStorageWithContext(ctx)
  882. }
  883. // fakeStorage returns either a local or remote (at daemon machine) file server
  884. func fakeStorage(files map[string]string) (FakeStorage, error) {
  885. ctx, err := fakeContextWithFiles(files)
  886. if err != nil {
  887. return nil, err
  888. }
  889. return fakeStorageWithContext(ctx)
  890. }
  891. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  892. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  893. if isLocalDaemon {
  894. return newLocalFakeStorage(ctx)
  895. }
  896. return newRemoteFileServer(ctx)
  897. }
  898. // localFileStorage is a file storage on the running machine
  899. type localFileStorage struct {
  900. *FakeContext
  901. *httptest.Server
  902. }
  903. func (s *localFileStorage) URL() string {
  904. return s.Server.URL
  905. }
  906. func (s *localFileStorage) CtxDir() string {
  907. return s.FakeContext.Dir
  908. }
  909. func (s *localFileStorage) Close() error {
  910. defer s.Server.Close()
  911. return s.FakeContext.Close()
  912. }
  913. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  914. handler := http.FileServer(http.Dir(ctx.Dir))
  915. server := httptest.NewServer(handler)
  916. return &localFileStorage{
  917. FakeContext: ctx,
  918. Server: server,
  919. }, nil
  920. }
  921. // remoteFileServer is a containerized static file server started on the remote
  922. // testing machine to be used in URL-accepting docker build functionality.
  923. type remoteFileServer struct {
  924. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  925. container string
  926. image string
  927. ctx *FakeContext
  928. }
  929. func (f *remoteFileServer) URL() string {
  930. u := url.URL{
  931. Scheme: "http",
  932. Host: f.host}
  933. return u.String()
  934. }
  935. func (f *remoteFileServer) CtxDir() string {
  936. return f.ctx.Dir
  937. }
  938. func (f *remoteFileServer) Close() error {
  939. defer func() {
  940. if f.ctx != nil {
  941. f.ctx.Close()
  942. }
  943. if f.image != "" {
  944. deleteImages(f.image)
  945. }
  946. }()
  947. if f.container == "" {
  948. return nil
  949. }
  950. return deleteContainer(f.container)
  951. }
  952. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  953. var (
  954. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  955. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  956. )
  957. // Build the image
  958. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  959. COPY . /static`); err != nil {
  960. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  961. }
  962. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  963. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  964. }
  965. // Start the container
  966. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  967. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  968. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  969. }
  970. // Find out the system assigned port
  971. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  972. if err != nil {
  973. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  974. }
  975. fileserverHostPort := strings.Trim(out, "\n")
  976. _, port, err := net.SplitHostPort(fileserverHostPort)
  977. if err != nil {
  978. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  979. }
  980. dockerHostURL, err := url.Parse(daemonHost())
  981. if err != nil {
  982. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  983. }
  984. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  985. if err != nil {
  986. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  987. }
  988. return &remoteFileServer{
  989. container: container,
  990. image: image,
  991. host: fmt.Sprintf("%s:%s", host, port),
  992. ctx: ctx}, nil
  993. }
  994. func inspectFieldAndMarshall(name, field string, output interface{}) error {
  995. str, err := inspectFieldJSON(name, field)
  996. if err != nil {
  997. return err
  998. }
  999. return json.Unmarshal([]byte(str), output)
  1000. }
  1001. func inspectFilter(name, filter string) (string, error) {
  1002. format := fmt.Sprintf("{{%s}}", filter)
  1003. inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
  1004. out, exitCode, err := runCommandWithOutput(inspectCmd)
  1005. if err != nil || exitCode != 0 {
  1006. return "", fmt.Errorf("failed to inspect container %s: %s", name, out)
  1007. }
  1008. return strings.TrimSpace(out), nil
  1009. }
  1010. func inspectField(name, field string) (string, error) {
  1011. return inspectFilter(name, fmt.Sprintf(".%s", field))
  1012. }
  1013. func inspectFieldJSON(name, field string) (string, error) {
  1014. return inspectFilter(name, fmt.Sprintf("json .%s", field))
  1015. }
  1016. func inspectFieldMap(name, path, field string) (string, error) {
  1017. return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  1018. }
  1019. func inspectMountSourceField(name, destination string) (string, error) {
  1020. m, err := inspectMountPoint(name, destination)
  1021. if err != nil {
  1022. return "", err
  1023. }
  1024. return m.Source, nil
  1025. }
  1026. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  1027. out, err := inspectFieldJSON(name, "Mounts")
  1028. if err != nil {
  1029. return types.MountPoint{}, err
  1030. }
  1031. return inspectMountPointJSON(out, destination)
  1032. }
  1033. var errMountNotFound = errors.New("mount point not found")
  1034. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  1035. var mp []types.MountPoint
  1036. if err := unmarshalJSON([]byte(j), &mp); err != nil {
  1037. return types.MountPoint{}, err
  1038. }
  1039. var m *types.MountPoint
  1040. for _, c := range mp {
  1041. if c.Destination == destination {
  1042. m = &c
  1043. break
  1044. }
  1045. }
  1046. if m == nil {
  1047. return types.MountPoint{}, errMountNotFound
  1048. }
  1049. return *m, nil
  1050. }
  1051. func getIDByName(name string) (string, error) {
  1052. return inspectField(name, "Id")
  1053. }
  1054. // getContainerState returns the exit code of the container
  1055. // and true if it's running
  1056. // the exit code should be ignored if it's running
  1057. func getContainerState(c *check.C, id string) (int, bool, error) {
  1058. var (
  1059. exitStatus int
  1060. running bool
  1061. )
  1062. out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
  1063. if exitCode != 0 {
  1064. return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
  1065. }
  1066. out = strings.Trim(out, "\n")
  1067. splitOutput := strings.Split(out, " ")
  1068. if len(splitOutput) != 2 {
  1069. return 0, false, fmt.Errorf("failed to get container state: output is broken")
  1070. }
  1071. if splitOutput[0] == "true" {
  1072. running = true
  1073. }
  1074. if n, err := strconv.Atoi(splitOutput[1]); err == nil {
  1075. exitStatus = n
  1076. } else {
  1077. return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
  1078. }
  1079. return exitStatus, running, nil
  1080. }
  1081. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  1082. args := []string{"-D", "build", "-t", name}
  1083. if !useCache {
  1084. args = append(args, "--no-cache")
  1085. }
  1086. args = append(args, buildFlags...)
  1087. args = append(args, "-")
  1088. buildCmd := exec.Command(dockerBinary, args...)
  1089. buildCmd.Stdin = strings.NewReader(dockerfile)
  1090. return buildCmd
  1091. }
  1092. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  1093. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1094. out, exitCode, err := runCommandWithOutput(buildCmd)
  1095. if err != nil || exitCode != 0 {
  1096. return "", out, fmt.Errorf("failed to build the image: %s", out)
  1097. }
  1098. id, err := getIDByName(name)
  1099. if err != nil {
  1100. return "", out, err
  1101. }
  1102. return id, out, nil
  1103. }
  1104. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  1105. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  1106. stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
  1107. if err != nil || exitCode != 0 {
  1108. return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
  1109. }
  1110. id, err := getIDByName(name)
  1111. if err != nil {
  1112. return "", stdout, stderr, err
  1113. }
  1114. return id, stdout, stderr, nil
  1115. }
  1116. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  1117. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  1118. return id, err
  1119. }
  1120. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  1121. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  1122. if err != nil {
  1123. return "", err
  1124. }
  1125. return id, nil
  1126. }
  1127. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  1128. args := []string{"build", "-t", name}
  1129. if !useCache {
  1130. args = append(args, "--no-cache")
  1131. }
  1132. args = append(args, buildFlags...)
  1133. args = append(args, ".")
  1134. buildCmd := exec.Command(dockerBinary, args...)
  1135. buildCmd.Dir = ctx.Dir
  1136. out, exitCode, err := runCommandWithOutput(buildCmd)
  1137. if err != nil || exitCode != 0 {
  1138. return "", "", fmt.Errorf("failed to build the image: %s", out)
  1139. }
  1140. id, err := getIDByName(name)
  1141. if err != nil {
  1142. return "", "", err
  1143. }
  1144. return id, out, nil
  1145. }
  1146. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  1147. args := []string{"build", "-t", name}
  1148. if !useCache {
  1149. args = append(args, "--no-cache")
  1150. }
  1151. args = append(args, buildFlags...)
  1152. args = append(args, path)
  1153. buildCmd := exec.Command(dockerBinary, args...)
  1154. out, exitCode, err := runCommandWithOutput(buildCmd)
  1155. if err != nil || exitCode != 0 {
  1156. return "", fmt.Errorf("failed to build the image: %s", out)
  1157. }
  1158. return getIDByName(name)
  1159. }
  1160. type gitServer interface {
  1161. URL() string
  1162. Close() error
  1163. }
  1164. type localGitServer struct {
  1165. *httptest.Server
  1166. }
  1167. func (r *localGitServer) Close() error {
  1168. r.Server.Close()
  1169. return nil
  1170. }
  1171. func (r *localGitServer) URL() string {
  1172. return r.Server.URL
  1173. }
  1174. type fakeGit struct {
  1175. root string
  1176. server gitServer
  1177. RepoURL string
  1178. }
  1179. func (g *fakeGit) Close() {
  1180. g.server.Close()
  1181. os.RemoveAll(g.root)
  1182. }
  1183. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  1184. ctx, err := fakeContextWithFiles(files)
  1185. if err != nil {
  1186. return nil, err
  1187. }
  1188. defer ctx.Close()
  1189. curdir, err := os.Getwd()
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. defer os.Chdir(curdir)
  1194. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  1195. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  1196. }
  1197. err = os.Chdir(ctx.Dir)
  1198. if err != nil {
  1199. return nil, err
  1200. }
  1201. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  1202. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  1203. }
  1204. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  1205. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  1206. }
  1207. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  1208. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  1209. }
  1210. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  1211. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  1212. }
  1213. root, err := ioutil.TempDir("", "docker-test-git-repo")
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. repoPath := filepath.Join(root, name+".git")
  1218. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  1219. os.RemoveAll(root)
  1220. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  1221. }
  1222. err = os.Chdir(repoPath)
  1223. if err != nil {
  1224. os.RemoveAll(root)
  1225. return nil, err
  1226. }
  1227. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  1228. os.RemoveAll(root)
  1229. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  1230. }
  1231. err = os.Chdir(curdir)
  1232. if err != nil {
  1233. os.RemoveAll(root)
  1234. return nil, err
  1235. }
  1236. var server gitServer
  1237. if !enforceLocalServer {
  1238. // use fakeStorage server, which might be local or remote (at test daemon)
  1239. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  1240. if err != nil {
  1241. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  1242. }
  1243. } else {
  1244. // always start a local http server on CLI test machin
  1245. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  1246. server = &localGitServer{httpServer}
  1247. }
  1248. return &fakeGit{
  1249. root: root,
  1250. server: server,
  1251. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  1252. }, nil
  1253. }
  1254. // Write `content` to the file at path `dst`, creating it if necessary,
  1255. // as well as any missing directories.
  1256. // The file is truncated if it already exists.
  1257. // Fail the test when error occures.
  1258. func writeFile(dst, content string, c *check.C) {
  1259. // Create subdirectories if necessary
  1260. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  1261. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  1262. c.Assert(err, check.IsNil)
  1263. defer f.Close()
  1264. // Write content (truncate if it exists)
  1265. _, err = io.Copy(f, strings.NewReader(content))
  1266. c.Assert(err, check.IsNil)
  1267. }
  1268. // Return the contents of file at path `src`.
  1269. // Fail the test when error occures.
  1270. func readFile(src string, c *check.C) (content string) {
  1271. data, err := ioutil.ReadFile(src)
  1272. c.Assert(err, check.IsNil)
  1273. return string(data)
  1274. }
  1275. func containerStorageFile(containerID, basename string) string {
  1276. return filepath.Join(containerStoragePath, containerID, basename)
  1277. }
  1278. // docker commands that use this function must be run with the '-d' switch.
  1279. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1280. out, _, err := runCommandWithOutput(cmd)
  1281. if err != nil {
  1282. return nil, fmt.Errorf("%v: %q", err, out)
  1283. }
  1284. contID := strings.TrimSpace(out)
  1285. if err := waitRun(contID); err != nil {
  1286. return nil, fmt.Errorf("%v: %q", contID, err)
  1287. }
  1288. return readContainerFile(contID, filename)
  1289. }
  1290. func readContainerFile(containerID, filename string) ([]byte, error) {
  1291. f, err := os.Open(containerStorageFile(containerID, filename))
  1292. if err != nil {
  1293. return nil, err
  1294. }
  1295. defer f.Close()
  1296. content, err := ioutil.ReadAll(f)
  1297. if err != nil {
  1298. return nil, err
  1299. }
  1300. return content, nil
  1301. }
  1302. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1303. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1304. return []byte(out), err
  1305. }
  1306. // daemonTime provides the current time on the daemon host
  1307. func daemonTime(c *check.C) time.Time {
  1308. if isLocalDaemon {
  1309. return time.Now()
  1310. }
  1311. status, body, err := sockRequest("GET", "/info", nil)
  1312. c.Assert(err, check.IsNil)
  1313. c.Assert(status, check.Equals, http.StatusOK)
  1314. type infoJSON struct {
  1315. SystemTime string
  1316. }
  1317. var info infoJSON
  1318. err = json.Unmarshal(body, &info)
  1319. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1320. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1321. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1322. return dt
  1323. }
  1324. func setupRegistry(c *check.C) *testRegistryV2 {
  1325. testRequires(c, RegistryHosting)
  1326. reg, err := newTestRegistryV2(c)
  1327. c.Assert(err, check.IsNil)
  1328. // Wait for registry to be ready to serve requests.
  1329. for i := 0; i != 50; i++ {
  1330. if err = reg.Ping(); err == nil {
  1331. break
  1332. }
  1333. time.Sleep(100 * time.Millisecond)
  1334. }
  1335. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available"))
  1336. return reg
  1337. }
  1338. func setupNotary(c *check.C) *testNotary {
  1339. testRequires(c, NotaryHosting)
  1340. ts, err := newTestNotary(c)
  1341. c.Assert(err, check.IsNil)
  1342. return ts
  1343. }
  1344. // appendBaseEnv appends the minimum set of environment variables to exec the
  1345. // docker cli binary for testing with correct configuration to the given env
  1346. // list.
  1347. func appendBaseEnv(env []string) []string {
  1348. preserveList := []string{
  1349. // preserve remote test host
  1350. "DOCKER_HOST",
  1351. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1352. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1353. "SystemRoot",
  1354. }
  1355. for _, key := range preserveList {
  1356. if val := os.Getenv(key); val != "" {
  1357. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1358. }
  1359. }
  1360. return env
  1361. }
  1362. func createTmpFile(c *check.C, content string) string {
  1363. f, err := ioutil.TempFile("", "testfile")
  1364. c.Assert(err, check.IsNil)
  1365. filename := f.Name()
  1366. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1367. c.Assert(err, check.IsNil)
  1368. return filename
  1369. }
  1370. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1371. args := []string{"--host", socket}
  1372. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1373. out, exitCode, err := runCommandWithOutput(buildCmd)
  1374. if err != nil || exitCode != 0 {
  1375. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1376. }
  1377. return out, nil
  1378. }
  1379. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1380. args = append(args, []string{"-D", "build", "-t", name}...)
  1381. if !useCache {
  1382. args = append(args, "--no-cache")
  1383. }
  1384. args = append(args, "-")
  1385. buildCmd := exec.Command(dockerBinary, args...)
  1386. buildCmd.Stdin = strings.NewReader(dockerfile)
  1387. return buildCmd
  1388. }
  1389. func waitForContainer(contID string, args ...string) error {
  1390. args = append([]string{"run", "--name", contID}, args...)
  1391. cmd := exec.Command(dockerBinary, args...)
  1392. if _, err := runCommand(cmd); err != nil {
  1393. return err
  1394. }
  1395. if err := waitRun(contID); err != nil {
  1396. return err
  1397. }
  1398. return nil
  1399. }
  1400. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1401. func waitRun(contID string) error {
  1402. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1403. }
  1404. // waitExited will wait for the specified container to state exit, subject
  1405. // to a maximum time limit in seconds supplied by the caller
  1406. func waitExited(contID string, duration time.Duration) error {
  1407. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1408. }
  1409. // waitInspect will wait for the specified container to have the specified string
  1410. // in the inspect output. It will wait until the specified timeout (in seconds)
  1411. // is reached.
  1412. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1413. after := time.After(timeout)
  1414. for {
  1415. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  1416. out, _, err := runCommandWithOutput(cmd)
  1417. if err != nil {
  1418. if !strings.Contains(out, "No such") {
  1419. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1420. }
  1421. select {
  1422. case <-after:
  1423. return err
  1424. default:
  1425. time.Sleep(10 * time.Millisecond)
  1426. continue
  1427. }
  1428. }
  1429. out = strings.TrimSpace(out)
  1430. if out == expected {
  1431. break
  1432. }
  1433. select {
  1434. case <-after:
  1435. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1436. default:
  1437. }
  1438. time.Sleep(100 * time.Millisecond)
  1439. }
  1440. return nil
  1441. }
  1442. func getInspectBody(c *check.C, version, id string) []byte {
  1443. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1444. status, body, err := sockRequest("GET", endpoint, nil)
  1445. c.Assert(err, check.IsNil)
  1446. c.Assert(status, check.Equals, http.StatusOK)
  1447. return body
  1448. }