docker_utils_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/docker/docker/api/types"
  21. volumetypes "github.com/docker/docker/api/types/volume"
  22. "github.com/docker/docker/integration-cli/checker"
  23. "github.com/docker/docker/integration-cli/daemon"
  24. "github.com/docker/docker/integration-cli/registry"
  25. "github.com/docker/docker/integration-cli/request"
  26. "github.com/docker/docker/opts"
  27. "github.com/docker/docker/pkg/stringutils"
  28. icmd "github.com/docker/docker/pkg/testutil/cmd"
  29. "github.com/go-check/check"
  30. )
  31. func daemonHost() string {
  32. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  33. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  34. daemonURLStr = daemonHostVar
  35. }
  36. return daemonURLStr
  37. }
  38. // FIXME(vdemeester) move this away are remove ignoreNoSuchContainer bool
  39. func deleteContainer(ignoreNoSuchContainer bool, container ...string) error {
  40. result := icmd.RunCommand(dockerBinary, append([]string{"rm", "-fv"}, container...)...)
  41. if ignoreNoSuchContainer && result.Error != nil {
  42. // If the error is "No such container: ..." this means the container doesn't exists anymore,
  43. // we can safely ignore that one.
  44. if strings.Contains(result.Stderr(), "No such container") {
  45. return nil
  46. }
  47. }
  48. return result.Compare(icmd.Success)
  49. }
  50. func getAllContainers() (string, error) {
  51. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  52. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  53. if exitCode != 0 && err == nil {
  54. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  55. }
  56. return out, err
  57. }
  58. func deleteAllContainers(c *check.C) {
  59. containers, err := getAllContainers()
  60. c.Assert(err, checker.IsNil, check.Commentf("containers: %v", containers))
  61. if containers != "" {
  62. err = deleteContainer(true, strings.Split(strings.TrimSpace(containers), "\n")...)
  63. c.Assert(err, checker.IsNil)
  64. }
  65. }
  66. func deleteAllNetworks(c *check.C) {
  67. networks, err := getAllNetworks()
  68. c.Assert(err, check.IsNil)
  69. var errs []string
  70. for _, n := range networks {
  71. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  72. continue
  73. }
  74. if testEnv.DaemonPlatform() == "windows" && strings.ToLower(n.Name) == "nat" {
  75. // nat is a pre-defined network on Windows and cannot be removed
  76. continue
  77. }
  78. status, b, err := request.SockRequest("DELETE", "/networks/"+n.Name, nil, daemonHost())
  79. if err != nil {
  80. errs = append(errs, err.Error())
  81. continue
  82. }
  83. if status != http.StatusNoContent {
  84. errs = append(errs, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  85. }
  86. }
  87. c.Assert(errs, checker.HasLen, 0, check.Commentf(strings.Join(errs, "\n")))
  88. }
  89. func getAllNetworks() ([]types.NetworkResource, error) {
  90. var networks []types.NetworkResource
  91. _, b, err := request.SockRequest("GET", "/networks", nil, daemonHost())
  92. if err != nil {
  93. return nil, err
  94. }
  95. if err := json.Unmarshal(b, &networks); err != nil {
  96. return nil, err
  97. }
  98. return networks, nil
  99. }
  100. func deleteAllPlugins(c *check.C) {
  101. plugins, err := getAllPlugins()
  102. c.Assert(err, checker.IsNil)
  103. var errs []string
  104. for _, p := range plugins {
  105. pluginName := p.Name
  106. status, b, err := request.SockRequest("DELETE", "/plugins/"+pluginName+"?force=1", nil, daemonHost())
  107. if err != nil {
  108. errs = append(errs, err.Error())
  109. continue
  110. }
  111. if status != http.StatusOK {
  112. errs = append(errs, fmt.Sprintf("error deleting plugin %s: %s", p.Name, string(b)))
  113. }
  114. }
  115. c.Assert(errs, checker.HasLen, 0, check.Commentf(strings.Join(errs, "\n")))
  116. }
  117. func getAllPlugins() (types.PluginsListResponse, error) {
  118. var plugins types.PluginsListResponse
  119. _, b, err := request.SockRequest("GET", "/plugins", nil, daemonHost())
  120. if err != nil {
  121. return nil, err
  122. }
  123. if err := json.Unmarshal(b, &plugins); err != nil {
  124. return nil, err
  125. }
  126. return plugins, nil
  127. }
  128. func deleteAllVolumes(c *check.C) {
  129. volumes, err := getAllVolumes()
  130. c.Assert(err, checker.IsNil)
  131. var errs []string
  132. for _, v := range volumes {
  133. status, b, err := request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost())
  134. if err != nil {
  135. errs = append(errs, err.Error())
  136. continue
  137. }
  138. if status != http.StatusNoContent {
  139. errs = append(errs, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  140. }
  141. }
  142. c.Assert(errs, checker.HasLen, 0, check.Commentf(strings.Join(errs, "\n")))
  143. }
  144. func getAllVolumes() ([]*types.Volume, error) {
  145. var volumes volumetypes.VolumesListOKBody
  146. _, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost())
  147. if err != nil {
  148. return nil, err
  149. }
  150. if err := json.Unmarshal(b, &volumes); err != nil {
  151. return nil, err
  152. }
  153. return volumes.Volumes, nil
  154. }
  155. func deleteAllImages(c *check.C) {
  156. cmd := exec.Command(dockerBinary, "images", "--digests")
  157. cmd.Env = appendBaseEnv(true)
  158. out, err := cmd.CombinedOutput()
  159. c.Assert(err, checker.IsNil)
  160. lines := strings.Split(string(out), "\n")[1:]
  161. imgMap := map[string]struct{}{}
  162. for _, l := range lines {
  163. if l == "" {
  164. continue
  165. }
  166. fields := strings.Fields(l)
  167. imgTag := fields[0] + ":" + fields[1]
  168. if _, ok := protectedImages[imgTag]; !ok {
  169. if fields[0] == "<none>" || fields[1] == "<none>" {
  170. if fields[2] != "<none>" {
  171. imgMap[fields[0]+"@"+fields[2]] = struct{}{}
  172. } else {
  173. imgMap[fields[3]] = struct{}{}
  174. }
  175. // continue
  176. } else {
  177. imgMap[imgTag] = struct{}{}
  178. }
  179. }
  180. }
  181. if len(imgMap) != 0 {
  182. imgs := make([]string, 0, len(imgMap))
  183. for k := range imgMap {
  184. imgs = append(imgs, k)
  185. }
  186. dockerCmd(c, append([]string{"rmi", "-f"}, imgs...)...)
  187. }
  188. }
  189. func getPausedContainers() ([]string, error) {
  190. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  191. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  192. if exitCode != 0 && err == nil {
  193. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  194. }
  195. if err != nil {
  196. return nil, err
  197. }
  198. return strings.Fields(out), nil
  199. }
  200. func unpauseContainer(c *check.C, container string) {
  201. dockerCmd(c, "unpause", container)
  202. }
  203. func unpauseAllContainers(c *check.C) {
  204. containers, err := getPausedContainers()
  205. c.Assert(err, checker.IsNil, check.Commentf("containers: %v", containers))
  206. for _, value := range containers {
  207. unpauseContainer(c, value)
  208. }
  209. }
  210. func deleteImages(images ...string) error {
  211. args := []string{dockerBinary, "rmi", "-f"}
  212. return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error
  213. }
  214. func dockerCmdWithError(args ...string) (string, int, error) {
  215. if err := validateArgs(args...); err != nil {
  216. return "", 0, err
  217. }
  218. result := icmd.RunCommand(dockerBinary, args...)
  219. if result.Error != nil {
  220. return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
  221. }
  222. return result.Combined(), result.ExitCode, result.Error
  223. }
  224. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  225. if err := validateArgs(args...); err != nil {
  226. c.Fatalf(err.Error())
  227. }
  228. result := icmd.RunCommand(dockerBinary, args...)
  229. c.Assert(result, icmd.Matches, icmd.Success)
  230. return result.Stdout(), result.Stderr(), result.ExitCode
  231. }
  232. func dockerCmd(c *check.C, args ...string) (string, int) {
  233. if err := validateArgs(args...); err != nil {
  234. c.Fatalf(err.Error())
  235. }
  236. result := icmd.RunCommand(dockerBinary, args...)
  237. c.Assert(result, icmd.Matches, icmd.Success)
  238. return result.Combined(), result.ExitCode
  239. }
  240. func dockerCmdWithResult(args ...string) *icmd.Result {
  241. return icmd.RunCommand(dockerBinary, args...)
  242. }
  243. func binaryWithArgs(args ...string) []string {
  244. return append([]string{dockerBinary}, args...)
  245. }
  246. // execute a docker command with a timeout
  247. func dockerCmdWithTimeout(timeout time.Duration, args ...string) *icmd.Result {
  248. if err := validateArgs(args...); err != nil {
  249. return &icmd.Result{Error: err}
  250. }
  251. return icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Timeout: timeout})
  252. }
  253. // execute a docker command in a directory
  254. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  255. if err := validateArgs(args...); err != nil {
  256. c.Fatalf(err.Error())
  257. }
  258. result := icmd.RunCmd(icmd.Cmd{Command: binaryWithArgs(args...), Dir: path})
  259. return result.Combined(), result.ExitCode, result.Error
  260. }
  261. // validateArgs is a checker to ensure tests are not running commands which are
  262. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  263. func validateArgs(args ...string) error {
  264. if testEnv.DaemonPlatform() != "windows" {
  265. return nil
  266. }
  267. foundBusybox := -1
  268. for key, value := range args {
  269. if strings.ToLower(value) == "busybox" {
  270. foundBusybox = key
  271. }
  272. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  273. return errors.New("cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  274. }
  275. }
  276. return nil
  277. }
  278. func findContainerIP(c *check.C, id string, network string) string {
  279. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  280. return strings.Trim(out, " \r\n'")
  281. }
  282. func getContainerCount() (int, error) {
  283. const containers = "Containers:"
  284. cmd := exec.Command(dockerBinary, "info")
  285. out, _, err := runCommandWithOutput(cmd)
  286. if err != nil {
  287. return 0, err
  288. }
  289. lines := strings.Split(out, "\n")
  290. for _, line := range lines {
  291. if strings.Contains(line, containers) {
  292. output := strings.TrimSpace(line)
  293. output = strings.TrimLeft(output, containers)
  294. output = strings.Trim(output, " ")
  295. containerCount, err := strconv.Atoi(output)
  296. if err != nil {
  297. return 0, err
  298. }
  299. return containerCount, nil
  300. }
  301. }
  302. return 0, fmt.Errorf("couldn't find the Container count in the output")
  303. }
  304. // FakeContext creates directories that can be used as a build context
  305. type FakeContext struct {
  306. Dir string
  307. }
  308. // Add a file at a path, creating directories where necessary
  309. func (f *FakeContext) Add(file, content string) error {
  310. return f.addFile(file, []byte(content))
  311. }
  312. func (f *FakeContext) addFile(file string, content []byte) error {
  313. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  314. dirpath := filepath.Dir(fp)
  315. if dirpath != "." {
  316. if err := os.MkdirAll(dirpath, 0755); err != nil {
  317. return err
  318. }
  319. }
  320. return ioutil.WriteFile(fp, content, 0644)
  321. }
  322. // Delete a file at a path
  323. func (f *FakeContext) Delete(file string) error {
  324. fp := filepath.Join(f.Dir, filepath.FromSlash(file))
  325. return os.RemoveAll(fp)
  326. }
  327. // Close deletes the context
  328. func (f *FakeContext) Close() error {
  329. return os.RemoveAll(f.Dir)
  330. }
  331. func fakeContextFromNewTempDir(c *check.C) *FakeContext {
  332. tmp, err := ioutil.TempDir("", "fake-context")
  333. c.Assert(err, checker.IsNil)
  334. if err := os.Chmod(tmp, 0755); err != nil {
  335. c.Fatal(err)
  336. }
  337. return fakeContextFromDir(tmp)
  338. }
  339. func fakeContextFromDir(dir string) *FakeContext {
  340. return &FakeContext{dir}
  341. }
  342. func fakeContextWithFiles(c *check.C, files map[string]string) *FakeContext {
  343. ctx := fakeContextFromNewTempDir(c)
  344. for file, content := range files {
  345. if err := ctx.Add(file, content); err != nil {
  346. ctx.Close()
  347. c.Fatal(err)
  348. }
  349. }
  350. return ctx
  351. }
  352. func fakeContextAddDockerfile(c *check.C, ctx *FakeContext, dockerfile string) {
  353. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  354. ctx.Close()
  355. c.Fatal(err)
  356. }
  357. }
  358. func fakeContext(c *check.C, dockerfile string, files map[string]string) *FakeContext {
  359. ctx := fakeContextWithFiles(c, files)
  360. fakeContextAddDockerfile(c, ctx, dockerfile)
  361. return ctx
  362. }
  363. // FakeStorage is a static file server. It might be running locally or remotely
  364. // on test host.
  365. type FakeStorage interface {
  366. Close() error
  367. URL() string
  368. CtxDir() string
  369. }
  370. func fakeBinaryStorage(c *check.C, archives map[string]*bytes.Buffer) FakeStorage {
  371. ctx := fakeContextFromNewTempDir(c)
  372. for name, content := range archives {
  373. if err := ctx.addFile(name, content.Bytes()); err != nil {
  374. c.Fatal(err)
  375. }
  376. }
  377. return fakeStorageWithContext(c, ctx)
  378. }
  379. // fakeStorage returns either a local or remote (at daemon machine) file server
  380. func fakeStorage(c *check.C, files map[string]string) FakeStorage {
  381. ctx := fakeContextWithFiles(c, files)
  382. return fakeStorageWithContext(c, ctx)
  383. }
  384. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  385. func fakeStorageWithContext(c *check.C, ctx *FakeContext) FakeStorage {
  386. if testEnv.LocalDaemon() {
  387. return newLocalFakeStorage(c, ctx)
  388. }
  389. return newRemoteFileServer(c, ctx)
  390. }
  391. // localFileStorage is a file storage on the running machine
  392. type localFileStorage struct {
  393. *FakeContext
  394. *httptest.Server
  395. }
  396. func (s *localFileStorage) URL() string {
  397. return s.Server.URL
  398. }
  399. func (s *localFileStorage) CtxDir() string {
  400. return s.FakeContext.Dir
  401. }
  402. func (s *localFileStorage) Close() error {
  403. defer s.Server.Close()
  404. return s.FakeContext.Close()
  405. }
  406. func newLocalFakeStorage(c *check.C, ctx *FakeContext) *localFileStorage {
  407. handler := http.FileServer(http.Dir(ctx.Dir))
  408. server := httptest.NewServer(handler)
  409. return &localFileStorage{
  410. FakeContext: ctx,
  411. Server: server,
  412. }
  413. }
  414. // remoteFileServer is a containerized static file server started on the remote
  415. // testing machine to be used in URL-accepting docker build functionality.
  416. type remoteFileServer struct {
  417. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  418. container string
  419. image string
  420. ctx *FakeContext
  421. }
  422. func (f *remoteFileServer) URL() string {
  423. u := url.URL{
  424. Scheme: "http",
  425. Host: f.host}
  426. return u.String()
  427. }
  428. func (f *remoteFileServer) CtxDir() string {
  429. return f.ctx.Dir
  430. }
  431. func (f *remoteFileServer) Close() error {
  432. defer func() {
  433. if f.ctx != nil {
  434. f.ctx.Close()
  435. }
  436. if f.image != "" {
  437. deleteImages(f.image)
  438. }
  439. }()
  440. if f.container == "" {
  441. return nil
  442. }
  443. return deleteContainer(false, f.container)
  444. }
  445. func newRemoteFileServer(c *check.C, ctx *FakeContext) *remoteFileServer {
  446. var (
  447. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  448. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  449. )
  450. c.Assert(ensureHTTPServerImage(), checker.IsNil)
  451. // Build the image
  452. fakeContextAddDockerfile(c, ctx, `FROM httpserver
  453. COPY . /static`)
  454. buildImageSuccessfully(c, image, withoutCache, withExternalBuildContext(ctx))
  455. // Start the container
  456. dockerCmd(c, "run", "-d", "-P", "--name", container, image)
  457. // Find out the system assigned port
  458. out, _ := dockerCmd(c, "port", container, "80/tcp")
  459. fileserverHostPort := strings.Trim(out, "\n")
  460. _, port, err := net.SplitHostPort(fileserverHostPort)
  461. if err != nil {
  462. c.Fatalf("unable to parse file server host:port: %v", err)
  463. }
  464. dockerHostURL, err := url.Parse(daemonHost())
  465. if err != nil {
  466. c.Fatalf("unable to parse daemon host URL: %v", err)
  467. }
  468. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  469. if err != nil {
  470. c.Fatalf("unable to parse docker daemon host:port: %v", err)
  471. }
  472. return &remoteFileServer{
  473. container: container,
  474. image: image,
  475. host: fmt.Sprintf("%s:%s", host, port),
  476. ctx: ctx}
  477. }
  478. func inspectFieldAndUnmarshall(c *check.C, name, field string, output interface{}) {
  479. str := inspectFieldJSON(c, name, field)
  480. err := json.Unmarshal([]byte(str), output)
  481. if c != nil {
  482. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  483. }
  484. }
  485. func inspectFilter(name, filter string) (string, error) {
  486. format := fmt.Sprintf("{{%s}}", filter)
  487. result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
  488. if result.Error != nil || result.ExitCode != 0 {
  489. return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
  490. }
  491. return strings.TrimSpace(result.Combined()), nil
  492. }
  493. func inspectFieldWithError(name, field string) (string, error) {
  494. return inspectFilter(name, fmt.Sprintf(".%s", field))
  495. }
  496. func inspectField(c *check.C, name, field string) string {
  497. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  498. if c != nil {
  499. c.Assert(err, check.IsNil)
  500. }
  501. return out
  502. }
  503. func inspectFieldJSON(c *check.C, name, field string) string {
  504. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  505. if c != nil {
  506. c.Assert(err, check.IsNil)
  507. }
  508. return out
  509. }
  510. func inspectFieldMap(c *check.C, name, path, field string) string {
  511. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  512. if c != nil {
  513. c.Assert(err, check.IsNil)
  514. }
  515. return out
  516. }
  517. func inspectMountSourceField(name, destination string) (string, error) {
  518. m, err := inspectMountPoint(name, destination)
  519. if err != nil {
  520. return "", err
  521. }
  522. return m.Source, nil
  523. }
  524. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  525. out, err := inspectFilter(name, "json .Mounts")
  526. if err != nil {
  527. return types.MountPoint{}, err
  528. }
  529. return inspectMountPointJSON(out, destination)
  530. }
  531. var errMountNotFound = errors.New("mount point not found")
  532. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  533. var mp []types.MountPoint
  534. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  535. return types.MountPoint{}, err
  536. }
  537. var m *types.MountPoint
  538. for _, c := range mp {
  539. if c.Destination == destination {
  540. m = &c
  541. break
  542. }
  543. }
  544. if m == nil {
  545. return types.MountPoint{}, errMountNotFound
  546. }
  547. return *m, nil
  548. }
  549. func inspectImage(name, filter string) (string, error) {
  550. args := []string{"inspect", "--type", "image"}
  551. if filter != "" {
  552. format := fmt.Sprintf("{{%s}}", filter)
  553. args = append(args, "-f", format)
  554. }
  555. args = append(args, name)
  556. inspectCmd := exec.Command(dockerBinary, args...)
  557. out, exitCode, err := runCommandWithOutput(inspectCmd)
  558. if err != nil || exitCode != 0 {
  559. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  560. }
  561. return strings.TrimSpace(out), nil
  562. }
  563. func getIDByName(c *check.C, name string) string {
  564. id, err := inspectFieldWithError(name, "Id")
  565. c.Assert(err, checker.IsNil)
  566. return id
  567. }
  568. func buildImageSuccessfully(c *check.C, name string, cmdOperators ...func(*icmd.Cmd) func()) {
  569. buildImage(name, cmdOperators...).Assert(c, icmd.Success)
  570. }
  571. func buildImage(name string, cmdOperators ...func(*icmd.Cmd) func()) *icmd.Result {
  572. cmd := icmd.Command(dockerBinary, "build", "-t", name)
  573. for _, op := range cmdOperators {
  574. deferFn := op(&cmd)
  575. if deferFn != nil {
  576. defer deferFn()
  577. }
  578. }
  579. return icmd.RunCmd(cmd)
  580. }
  581. func withBuildContextPath(path string) func(*icmd.Cmd) func() {
  582. return func(cmd *icmd.Cmd) func() {
  583. cmd.Command = append(cmd.Command, path)
  584. return nil
  585. }
  586. }
  587. func withExternalBuildContext(ctx *FakeContext) func(*icmd.Cmd) func() {
  588. return func(cmd *icmd.Cmd) func() {
  589. cmd.Dir = ctx.Dir
  590. cmd.Command = append(cmd.Command, ".")
  591. return nil
  592. }
  593. }
  594. func withBuildContext(c *check.C, contextOperators ...func(*FakeContext) error) func(*icmd.Cmd) func() {
  595. ctx := fakeContextFromNewTempDir(c)
  596. for _, op := range contextOperators {
  597. if err := op(ctx); err != nil {
  598. c.Fatal(err)
  599. }
  600. }
  601. return func(cmd *icmd.Cmd) func() {
  602. cmd.Dir = ctx.Dir
  603. cmd.Command = append(cmd.Command, ".")
  604. return closeBuildContext(c, ctx)
  605. }
  606. }
  607. func withBuildFlags(flags ...string) func(*icmd.Cmd) func() {
  608. return func(cmd *icmd.Cmd) func() {
  609. cmd.Command = append(cmd.Command, flags...)
  610. return nil
  611. }
  612. }
  613. func withoutCache(cmd *icmd.Cmd) func() {
  614. cmd.Command = append(cmd.Command, "--no-cache")
  615. return nil
  616. }
  617. func withFile(name, content string) func(*FakeContext) error {
  618. return func(ctx *FakeContext) error {
  619. return ctx.Add(name, content)
  620. }
  621. }
  622. func closeBuildContext(c *check.C, ctx *FakeContext) func() {
  623. return func() {
  624. if err := ctx.Close(); err != nil {
  625. c.Fatal(err)
  626. }
  627. }
  628. }
  629. func withDockerfile(dockerfile string) func(*icmd.Cmd) func() {
  630. return func(cmd *icmd.Cmd) func() {
  631. cmd.Command = append(cmd.Command, "-")
  632. cmd.Stdin = strings.NewReader(dockerfile)
  633. return nil
  634. }
  635. }
  636. func trustedBuild(cmd *icmd.Cmd) func() {
  637. trustedCmd(cmd)
  638. return nil
  639. }
  640. func withEnvironmentVariales(envs ...string) func(cmd *icmd.Cmd) func() {
  641. return func(cmd *icmd.Cmd) func() {
  642. cmd.Env = envs
  643. return nil
  644. }
  645. }
  646. type gitServer interface {
  647. URL() string
  648. Close() error
  649. }
  650. type localGitServer struct {
  651. *httptest.Server
  652. }
  653. func (r *localGitServer) Close() error {
  654. r.Server.Close()
  655. return nil
  656. }
  657. func (r *localGitServer) URL() string {
  658. return r.Server.URL
  659. }
  660. type fakeGit struct {
  661. root string
  662. server gitServer
  663. RepoURL string
  664. }
  665. func (g *fakeGit) Close() {
  666. g.server.Close()
  667. os.RemoveAll(g.root)
  668. }
  669. func newFakeGit(c *check.C, name string, files map[string]string, enforceLocalServer bool) *fakeGit {
  670. ctx := fakeContextWithFiles(c, files)
  671. defer ctx.Close()
  672. curdir, err := os.Getwd()
  673. if err != nil {
  674. c.Fatal(err)
  675. }
  676. defer os.Chdir(curdir)
  677. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  678. c.Fatalf("error trying to init repo: %s (%s)", err, output)
  679. }
  680. err = os.Chdir(ctx.Dir)
  681. if err != nil {
  682. c.Fatal(err)
  683. }
  684. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  685. c.Fatalf("error trying to set 'user.name': %s (%s)", err, output)
  686. }
  687. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  688. c.Fatalf("error trying to set 'user.email': %s (%s)", err, output)
  689. }
  690. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  691. c.Fatalf("error trying to add files to repo: %s (%s)", err, output)
  692. }
  693. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  694. c.Fatalf("error trying to commit to repo: %s (%s)", err, output)
  695. }
  696. root, err := ioutil.TempDir("", "docker-test-git-repo")
  697. if err != nil {
  698. c.Fatal(err)
  699. }
  700. repoPath := filepath.Join(root, name+".git")
  701. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  702. os.RemoveAll(root)
  703. c.Fatalf("error trying to clone --bare: %s (%s)", err, output)
  704. }
  705. err = os.Chdir(repoPath)
  706. if err != nil {
  707. os.RemoveAll(root)
  708. c.Fatal(err)
  709. }
  710. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  711. os.RemoveAll(root)
  712. c.Fatalf("error trying to git update-server-info: %s (%s)", err, output)
  713. }
  714. err = os.Chdir(curdir)
  715. if err != nil {
  716. os.RemoveAll(root)
  717. c.Fatal(err)
  718. }
  719. var server gitServer
  720. if !enforceLocalServer {
  721. // use fakeStorage server, which might be local or remote (at test daemon)
  722. server = fakeStorageWithContext(c, fakeContextFromDir(root))
  723. } else {
  724. // always start a local http server on CLI test machine
  725. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  726. server = &localGitServer{httpServer}
  727. }
  728. return &fakeGit{
  729. root: root,
  730. server: server,
  731. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  732. }
  733. }
  734. // Write `content` to the file at path `dst`, creating it if necessary,
  735. // as well as any missing directories.
  736. // The file is truncated if it already exists.
  737. // Fail the test when error occurs.
  738. func writeFile(dst, content string, c *check.C) {
  739. // Create subdirectories if necessary
  740. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  741. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  742. c.Assert(err, check.IsNil)
  743. defer f.Close()
  744. // Write content (truncate if it exists)
  745. _, err = io.Copy(f, strings.NewReader(content))
  746. c.Assert(err, check.IsNil)
  747. }
  748. // Return the contents of file at path `src`.
  749. // Fail the test when error occurs.
  750. func readFile(src string, c *check.C) (content string) {
  751. data, err := ioutil.ReadFile(src)
  752. c.Assert(err, check.IsNil)
  753. return string(data)
  754. }
  755. func containerStorageFile(containerID, basename string) string {
  756. return filepath.Join(testEnv.ContainerStoragePath(), containerID, basename)
  757. }
  758. // docker commands that use this function must be run with the '-d' switch.
  759. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  760. out, _, err := runCommandWithOutput(cmd)
  761. if err != nil {
  762. return nil, fmt.Errorf("%v: %q", err, out)
  763. }
  764. contID := strings.TrimSpace(out)
  765. if err := waitRun(contID); err != nil {
  766. return nil, fmt.Errorf("%v: %q", contID, err)
  767. }
  768. return readContainerFile(contID, filename)
  769. }
  770. func readContainerFile(containerID, filename string) ([]byte, error) {
  771. f, err := os.Open(containerStorageFile(containerID, filename))
  772. if err != nil {
  773. return nil, err
  774. }
  775. defer f.Close()
  776. content, err := ioutil.ReadAll(f)
  777. if err != nil {
  778. return nil, err
  779. }
  780. return content, nil
  781. }
  782. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  783. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  784. return []byte(out), err
  785. }
  786. // daemonTime provides the current time on the daemon host
  787. func daemonTime(c *check.C) time.Time {
  788. if testEnv.LocalDaemon() {
  789. return time.Now()
  790. }
  791. status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
  792. c.Assert(err, check.IsNil)
  793. c.Assert(status, check.Equals, http.StatusOK)
  794. type infoJSON struct {
  795. SystemTime string
  796. }
  797. var info infoJSON
  798. err = json.Unmarshal(body, &info)
  799. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  800. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  801. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  802. return dt
  803. }
  804. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  805. // It return the time formatted how the client sends timestamps to the server.
  806. func daemonUnixTime(c *check.C) string {
  807. return parseEventTime(daemonTime(c))
  808. }
  809. func parseEventTime(t time.Time) string {
  810. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  811. }
  812. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 {
  813. reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL)
  814. c.Assert(err, check.IsNil)
  815. // Wait for registry to be ready to serve requests.
  816. for i := 0; i != 50; i++ {
  817. if err = reg.Ping(); err == nil {
  818. break
  819. }
  820. time.Sleep(100 * time.Millisecond)
  821. }
  822. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  823. return reg
  824. }
  825. func setupNotary(c *check.C) *testNotary {
  826. ts, err := newTestNotary(c)
  827. c.Assert(err, check.IsNil)
  828. return ts
  829. }
  830. // appendBaseEnv appends the minimum set of environment variables to exec the
  831. // docker cli binary for testing with correct configuration to the given env
  832. // list.
  833. func appendBaseEnv(isTLS bool, env ...string) []string {
  834. preserveList := []string{
  835. // preserve remote test host
  836. "DOCKER_HOST",
  837. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  838. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  839. "SystemRoot",
  840. // testing help text requires the $PATH to dockerd is set
  841. "PATH",
  842. }
  843. if isTLS {
  844. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  845. }
  846. for _, key := range preserveList {
  847. if val := os.Getenv(key); val != "" {
  848. env = append(env, fmt.Sprintf("%s=%s", key, val))
  849. }
  850. }
  851. return env
  852. }
  853. func createTmpFile(c *check.C, content string) string {
  854. f, err := ioutil.TempFile("", "testfile")
  855. c.Assert(err, check.IsNil)
  856. filename := f.Name()
  857. err = ioutil.WriteFile(filename, []byte(content), 0644)
  858. c.Assert(err, check.IsNil)
  859. return filename
  860. }
  861. func waitForContainer(contID string, args ...string) error {
  862. args = append([]string{dockerBinary, "run", "--name", contID}, args...)
  863. result := icmd.RunCmd(icmd.Cmd{Command: args})
  864. if result.Error != nil {
  865. return result.Error
  866. }
  867. return waitRun(contID)
  868. }
  869. // waitRestart will wait for the specified container to restart once
  870. func waitRestart(contID string, duration time.Duration) error {
  871. return waitInspect(contID, "{{.RestartCount}}", "1", duration)
  872. }
  873. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  874. func waitRun(contID string) error {
  875. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  876. }
  877. // waitExited will wait for the specified container to state exit, subject
  878. // to a maximum time limit in seconds supplied by the caller
  879. func waitExited(contID string, duration time.Duration) error {
  880. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  881. }
  882. // waitInspect will wait for the specified container to have the specified string
  883. // in the inspect output. It will wait until the specified timeout (in seconds)
  884. // is reached.
  885. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  886. return waitInspectWithArgs(name, expr, expected, timeout)
  887. }
  888. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  889. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  890. }
  891. func getInspectBody(c *check.C, version, id string) []byte {
  892. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  893. status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
  894. c.Assert(err, check.IsNil)
  895. c.Assert(status, check.Equals, http.StatusOK)
  896. return body
  897. }
  898. // Run a long running idle task in a background container using the
  899. // system-specific default image and command.
  900. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  901. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  902. }
  903. // Run a long running idle task in a background container using the specified
  904. // image and the system-specific command.
  905. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  906. args := []string{"run", "-d"}
  907. args = append(args, extraArgs...)
  908. args = append(args, image)
  909. args = append(args, sleepCommandForDaemonPlatform()...)
  910. return dockerCmd(c, args...)
  911. }
  912. // minimalBaseImage returns the name of the minimal base image for the current
  913. // daemon platform.
  914. func minimalBaseImage() string {
  915. return testEnv.MinimalBaseImage()
  916. }
  917. func getGoroutineNumber() (int, error) {
  918. i := struct {
  919. NGoroutines int
  920. }{}
  921. status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
  922. if err != nil {
  923. return 0, err
  924. }
  925. if status != http.StatusOK {
  926. return 0, fmt.Errorf("http status code: %d", status)
  927. }
  928. if err := json.Unmarshal(b, &i); err != nil {
  929. return 0, err
  930. }
  931. return i.NGoroutines, nil
  932. }
  933. func waitForGoroutines(expected int) error {
  934. t := time.After(30 * time.Second)
  935. for {
  936. select {
  937. case <-t:
  938. n, err := getGoroutineNumber()
  939. if err != nil {
  940. return err
  941. }
  942. if n > expected {
  943. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  944. }
  945. default:
  946. n, err := getGoroutineNumber()
  947. if err != nil {
  948. return err
  949. }
  950. if n <= expected {
  951. return nil
  952. }
  953. time.Sleep(200 * time.Millisecond)
  954. }
  955. }
  956. }
  957. // getErrorMessage returns the error message from an error API response
  958. func getErrorMessage(c *check.C, body []byte) string {
  959. var resp types.ErrorResponse
  960. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  961. return strings.TrimSpace(resp.Message)
  962. }
  963. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  964. after := time.After(timeout)
  965. for {
  966. v, comment := f(c)
  967. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  968. select {
  969. case <-after:
  970. assert = true
  971. default:
  972. }
  973. if assert {
  974. if comment != nil {
  975. args = append(args, comment)
  976. }
  977. c.Assert(v, checker, args...)
  978. return
  979. }
  980. time.Sleep(100 * time.Millisecond)
  981. }
  982. }
  983. type checkF func(*check.C) (interface{}, check.CommentInterface)
  984. type reducer func(...interface{}) interface{}
  985. func reducedCheck(r reducer, funcs ...checkF) checkF {
  986. return func(c *check.C) (interface{}, check.CommentInterface) {
  987. var values []interface{}
  988. var comments []string
  989. for _, f := range funcs {
  990. v, comment := f(c)
  991. values = append(values, v)
  992. if comment != nil {
  993. comments = append(comments, comment.CheckCommentString())
  994. }
  995. }
  996. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  997. }
  998. }
  999. func sumAsIntegers(vals ...interface{}) interface{} {
  1000. var s int
  1001. for _, v := range vals {
  1002. s += v.(int)
  1003. }
  1004. return s
  1005. }