docker_utils.go 48 KB

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