docker_utils.go 48 KB

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