docker_utils_test.go 31 KB

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