docker_utils_test.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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() (*FakeContext, error) {
  332. tmp, err := ioutil.TempDir("", "fake-context")
  333. if err != nil {
  334. return nil, err
  335. }
  336. if err := os.Chmod(tmp, 0755); err != nil {
  337. return nil, err
  338. }
  339. return fakeContextFromDir(tmp), nil
  340. }
  341. func fakeContextFromDir(dir string) *FakeContext {
  342. return &FakeContext{dir}
  343. }
  344. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  345. ctx, err := fakeContextFromNewTempDir()
  346. if err != nil {
  347. return nil, err
  348. }
  349. for file, content := range files {
  350. if err := ctx.Add(file, content); err != nil {
  351. ctx.Close()
  352. return nil, err
  353. }
  354. }
  355. return ctx, nil
  356. }
  357. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  358. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  359. ctx.Close()
  360. return err
  361. }
  362. return nil
  363. }
  364. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  365. ctx, err := fakeContextWithFiles(files)
  366. if err != nil {
  367. return nil, err
  368. }
  369. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  370. return nil, err
  371. }
  372. return ctx, nil
  373. }
  374. // FakeStorage is a static file server. It might be running locally or remotely
  375. // on test host.
  376. type FakeStorage interface {
  377. Close() error
  378. URL() string
  379. CtxDir() string
  380. }
  381. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  382. ctx, err := fakeContextFromNewTempDir()
  383. if err != nil {
  384. return nil, err
  385. }
  386. for name, content := range archives {
  387. if err := ctx.addFile(name, content.Bytes()); err != nil {
  388. return nil, err
  389. }
  390. }
  391. return fakeStorageWithContext(ctx)
  392. }
  393. // fakeStorage returns either a local or remote (at daemon machine) file server
  394. func fakeStorage(files map[string]string) (FakeStorage, error) {
  395. ctx, err := fakeContextWithFiles(files)
  396. if err != nil {
  397. return nil, err
  398. }
  399. return fakeStorageWithContext(ctx)
  400. }
  401. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  402. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  403. if testEnv.LocalDaemon() {
  404. return newLocalFakeStorage(ctx)
  405. }
  406. return newRemoteFileServer(ctx)
  407. }
  408. // localFileStorage is a file storage on the running machine
  409. type localFileStorage struct {
  410. *FakeContext
  411. *httptest.Server
  412. }
  413. func (s *localFileStorage) URL() string {
  414. return s.Server.URL
  415. }
  416. func (s *localFileStorage) CtxDir() string {
  417. return s.FakeContext.Dir
  418. }
  419. func (s *localFileStorage) Close() error {
  420. defer s.Server.Close()
  421. return s.FakeContext.Close()
  422. }
  423. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  424. handler := http.FileServer(http.Dir(ctx.Dir))
  425. server := httptest.NewServer(handler)
  426. return &localFileStorage{
  427. FakeContext: ctx,
  428. Server: server,
  429. }, nil
  430. }
  431. // remoteFileServer is a containerized static file server started on the remote
  432. // testing machine to be used in URL-accepting docker build functionality.
  433. type remoteFileServer struct {
  434. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  435. container string
  436. image string
  437. ctx *FakeContext
  438. }
  439. func (f *remoteFileServer) URL() string {
  440. u := url.URL{
  441. Scheme: "http",
  442. Host: f.host}
  443. return u.String()
  444. }
  445. func (f *remoteFileServer) CtxDir() string {
  446. return f.ctx.Dir
  447. }
  448. func (f *remoteFileServer) Close() error {
  449. defer func() {
  450. if f.ctx != nil {
  451. f.ctx.Close()
  452. }
  453. if f.image != "" {
  454. deleteImages(f.image)
  455. }
  456. }()
  457. if f.container == "" {
  458. return nil
  459. }
  460. return deleteContainer(false, f.container)
  461. }
  462. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  463. var (
  464. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  465. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  466. )
  467. if err := ensureHTTPServerImage(); err != nil {
  468. return nil, err
  469. }
  470. // Build the image
  471. if err := fakeContextAddDockerfile(ctx, `FROM httpserver
  472. COPY . /static`); err != nil {
  473. return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
  474. }
  475. if _, err := buildImageFromContext(image, ctx, false); err != nil {
  476. return nil, fmt.Errorf("failed building file storage container image: %v", err)
  477. }
  478. // Start the container
  479. runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
  480. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  481. return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
  482. }
  483. // Find out the system assigned port
  484. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
  485. if err != nil {
  486. return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
  487. }
  488. fileserverHostPort := strings.Trim(out, "\n")
  489. _, port, err := net.SplitHostPort(fileserverHostPort)
  490. if err != nil {
  491. return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
  492. }
  493. dockerHostURL, err := url.Parse(daemonHost())
  494. if err != nil {
  495. return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
  496. }
  497. host, _, err := net.SplitHostPort(dockerHostURL.Host)
  498. if err != nil {
  499. return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
  500. }
  501. return &remoteFileServer{
  502. container: container,
  503. image: image,
  504. host: fmt.Sprintf("%s:%s", host, port),
  505. ctx: ctx}, nil
  506. }
  507. func inspectFieldAndUnmarshall(c *check.C, name, field string, output interface{}) {
  508. str := inspectFieldJSON(c, name, field)
  509. err := json.Unmarshal([]byte(str), output)
  510. if c != nil {
  511. c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
  512. }
  513. }
  514. func inspectFilter(name, filter string) (string, error) {
  515. format := fmt.Sprintf("{{%s}}", filter)
  516. result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
  517. if result.Error != nil || result.ExitCode != 0 {
  518. return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
  519. }
  520. return strings.TrimSpace(result.Combined()), nil
  521. }
  522. func inspectFieldWithError(name, field string) (string, error) {
  523. return inspectFilter(name, fmt.Sprintf(".%s", field))
  524. }
  525. func inspectField(c *check.C, name, field string) string {
  526. out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
  527. if c != nil {
  528. c.Assert(err, check.IsNil)
  529. }
  530. return out
  531. }
  532. func inspectFieldJSON(c *check.C, name, field string) string {
  533. out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
  534. if c != nil {
  535. c.Assert(err, check.IsNil)
  536. }
  537. return out
  538. }
  539. func inspectFieldMap(c *check.C, name, path, field string) string {
  540. out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
  541. if c != nil {
  542. c.Assert(err, check.IsNil)
  543. }
  544. return out
  545. }
  546. func inspectMountSourceField(name, destination string) (string, error) {
  547. m, err := inspectMountPoint(name, destination)
  548. if err != nil {
  549. return "", err
  550. }
  551. return m.Source, nil
  552. }
  553. func inspectMountPoint(name, destination string) (types.MountPoint, error) {
  554. out, err := inspectFilter(name, "json .Mounts")
  555. if err != nil {
  556. return types.MountPoint{}, err
  557. }
  558. return inspectMountPointJSON(out, destination)
  559. }
  560. var errMountNotFound = errors.New("mount point not found")
  561. func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
  562. var mp []types.MountPoint
  563. if err := json.Unmarshal([]byte(j), &mp); err != nil {
  564. return types.MountPoint{}, err
  565. }
  566. var m *types.MountPoint
  567. for _, c := range mp {
  568. if c.Destination == destination {
  569. m = &c
  570. break
  571. }
  572. }
  573. if m == nil {
  574. return types.MountPoint{}, errMountNotFound
  575. }
  576. return *m, nil
  577. }
  578. func inspectImage(name, filter string) (string, error) {
  579. args := []string{"inspect", "--type", "image"}
  580. if filter != "" {
  581. format := fmt.Sprintf("{{%s}}", filter)
  582. args = append(args, "-f", format)
  583. }
  584. args = append(args, name)
  585. inspectCmd := exec.Command(dockerBinary, args...)
  586. out, exitCode, err := runCommandWithOutput(inspectCmd)
  587. if err != nil || exitCode != 0 {
  588. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  589. }
  590. return strings.TrimSpace(out), nil
  591. }
  592. func getIDByName(name string) (string, error) {
  593. return inspectFieldWithError(name, "Id")
  594. }
  595. // Deprecated
  596. func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
  597. return daemon.BuildImageCmdWithHost(dockerBinary, name, dockerfile, "", useCache, buildFlags...)
  598. }
  599. // Deprecated
  600. func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
  601. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  602. out, exitCode, err := runCommandWithOutput(buildCmd)
  603. if err != nil || exitCode != 0 {
  604. return "", out, fmt.Errorf("failed to build the image: %s", out)
  605. }
  606. id, err := getIDByName(name)
  607. if err != nil {
  608. return "", out, err
  609. }
  610. return id, out, nil
  611. }
  612. // Deprecated
  613. func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
  614. buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
  615. result := icmd.RunCmd(transformCmd(buildCmd))
  616. err := result.Error
  617. exitCode := result.ExitCode
  618. if err != nil || exitCode != 0 {
  619. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  620. }
  621. id, err := getIDByName(name)
  622. if err != nil {
  623. return "", result.Stdout(), result.Stderr(), err
  624. }
  625. return id, result.Stdout(), result.Stderr(), nil
  626. }
  627. func buildImageSuccessfully(c *check.C, name string, cmdOperators ...func(*icmd.Cmd) func()) {
  628. buildImageNew(name, cmdOperators...).Assert(c, icmd.Success)
  629. }
  630. // FIXME(vdemeester) rename this buildImage once deprecated buildImage is no more
  631. func buildImageNew(name string, cmdOperators ...func(*icmd.Cmd) func()) *icmd.Result {
  632. cmd := icmd.Command(dockerBinary, "build", "-t", name)
  633. for _, op := range cmdOperators {
  634. deferFn := op(&cmd)
  635. if deferFn != nil {
  636. defer deferFn()
  637. }
  638. }
  639. return icmd.RunCmd(cmd)
  640. }
  641. func withBuildContextPath(path string) func(*icmd.Cmd) func() {
  642. return func(cmd *icmd.Cmd) func() {
  643. cmd.Command = append(cmd.Command, path)
  644. return nil
  645. }
  646. }
  647. func withBuildContext(c *check.C, contextOperators ...func(*FakeContext) error) func(*icmd.Cmd) func() {
  648. ctx, err := fakeContextFromNewTempDir()
  649. if err != nil {
  650. c.Fatalf("error creating build context : %v", err)
  651. }
  652. for _, op := range contextOperators {
  653. if err := op(ctx); err != nil {
  654. c.Fatal(err)
  655. }
  656. }
  657. return func(cmd *icmd.Cmd) func() {
  658. cmd.Dir = ctx.Dir
  659. cmd.Command = append(cmd.Command, ".")
  660. return closeBuildContext(c, ctx)
  661. }
  662. }
  663. func withBuildFlags(flags ...string) func(*icmd.Cmd) func() {
  664. return func(cmd *icmd.Cmd) func() {
  665. cmd.Command = append(cmd.Command, flags...)
  666. return nil
  667. }
  668. }
  669. func withoutCache(cmd *icmd.Cmd) func() {
  670. cmd.Command = append(cmd.Command, "--no-cache")
  671. return nil
  672. }
  673. func withFile(name, content string) func(*FakeContext) error {
  674. return func(ctx *FakeContext) error {
  675. return ctx.Add(name, content)
  676. }
  677. }
  678. func closeBuildContext(c *check.C, ctx *FakeContext) func() {
  679. return func() {
  680. if err := ctx.Close(); err != nil {
  681. c.Fatal(err)
  682. }
  683. }
  684. }
  685. func withDockerfile(dockerfile string) func(*icmd.Cmd) func() {
  686. return func(cmd *icmd.Cmd) func() {
  687. cmd.Command = append(cmd.Command, "-")
  688. cmd.Stdin = strings.NewReader(dockerfile)
  689. return nil
  690. }
  691. }
  692. func trustedBuild(cmd *icmd.Cmd) func() {
  693. trustedCmd(cmd)
  694. return nil
  695. }
  696. func withEnvironmentVariales(envs ...string) func(cmd *icmd.Cmd) func() {
  697. return func(cmd *icmd.Cmd) func() {
  698. cmd.Env = envs
  699. return nil
  700. }
  701. }
  702. // Deprecated
  703. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  704. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  705. return id, err
  706. }
  707. // Deprecated
  708. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  709. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  710. if err != nil {
  711. return "", err
  712. }
  713. return id, nil
  714. }
  715. // Deprecated
  716. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  717. args := []string{"build", "-t", name}
  718. if !useCache {
  719. args = append(args, "--no-cache")
  720. }
  721. args = append(args, buildFlags...)
  722. args = append(args, ".")
  723. result := icmd.RunCmd(icmd.Cmd{
  724. Command: append([]string{dockerBinary}, args...),
  725. Dir: ctx.Dir,
  726. })
  727. out := result.Combined()
  728. if result.Error != nil || result.ExitCode != 0 {
  729. return "", "", fmt.Errorf("failed to build the image: %s", out)
  730. }
  731. id, err := getIDByName(name)
  732. if err != nil {
  733. return "", "", err
  734. }
  735. return id, out, nil
  736. }
  737. // Deprecated
  738. func buildImageFromContextWithStdoutStderr(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, string, error) {
  739. args := []string{"build", "-t", name}
  740. if !useCache {
  741. args = append(args, "--no-cache")
  742. }
  743. args = append(args, buildFlags...)
  744. args = append(args, ".")
  745. result := icmd.RunCmd(icmd.Cmd{
  746. Command: append([]string{dockerBinary}, args...),
  747. Dir: ctx.Dir,
  748. })
  749. exitCode := result.ExitCode
  750. err := result.Error
  751. if err != nil || exitCode != 0 {
  752. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  753. }
  754. id, err := getIDByName(name)
  755. if err != nil {
  756. return "", result.Stdout(), result.Stderr(), err
  757. }
  758. return id, result.Stdout(), result.Stderr(), nil
  759. }
  760. // Deprecated
  761. func buildImageFromGitWithStdoutStderr(name string, ctx *fakeGit, useCache bool, buildFlags ...string) (string, string, string, error) {
  762. args := []string{"build", "-t", name}
  763. if !useCache {
  764. args = append(args, "--no-cache")
  765. }
  766. args = append(args, buildFlags...)
  767. args = append(args, ctx.RepoURL)
  768. result := icmd.RunCmd(icmd.Cmd{
  769. Command: append([]string{dockerBinary}, args...),
  770. })
  771. exitCode := result.ExitCode
  772. err := result.Error
  773. if err != nil || exitCode != 0 {
  774. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  775. }
  776. id, err := getIDByName(name)
  777. if err != nil {
  778. return "", result.Stdout(), result.Stderr(), err
  779. }
  780. return id, result.Stdout(), result.Stderr(), nil
  781. }
  782. // Deprecated
  783. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  784. args := []string{"build", "-t", name}
  785. if !useCache {
  786. args = append(args, "--no-cache")
  787. }
  788. args = append(args, buildFlags...)
  789. args = append(args, path)
  790. buildCmd := exec.Command(dockerBinary, args...)
  791. out, exitCode, err := runCommandWithOutput(buildCmd)
  792. if err != nil || exitCode != 0 {
  793. return "", fmt.Errorf("failed to build the image: %s", out)
  794. }
  795. return getIDByName(name)
  796. }
  797. type gitServer interface {
  798. URL() string
  799. Close() error
  800. }
  801. type localGitServer struct {
  802. *httptest.Server
  803. }
  804. func (r *localGitServer) Close() error {
  805. r.Server.Close()
  806. return nil
  807. }
  808. func (r *localGitServer) URL() string {
  809. return r.Server.URL
  810. }
  811. type fakeGit struct {
  812. root string
  813. server gitServer
  814. RepoURL string
  815. }
  816. func (g *fakeGit) Close() {
  817. g.server.Close()
  818. os.RemoveAll(g.root)
  819. }
  820. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  821. ctx, err := fakeContextWithFiles(files)
  822. if err != nil {
  823. return nil, err
  824. }
  825. defer ctx.Close()
  826. curdir, err := os.Getwd()
  827. if err != nil {
  828. return nil, err
  829. }
  830. defer os.Chdir(curdir)
  831. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  832. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  833. }
  834. err = os.Chdir(ctx.Dir)
  835. if err != nil {
  836. return nil, err
  837. }
  838. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  839. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  840. }
  841. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  842. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  843. }
  844. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  845. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  846. }
  847. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  848. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  849. }
  850. root, err := ioutil.TempDir("", "docker-test-git-repo")
  851. if err != nil {
  852. return nil, err
  853. }
  854. repoPath := filepath.Join(root, name+".git")
  855. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  856. os.RemoveAll(root)
  857. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  858. }
  859. err = os.Chdir(repoPath)
  860. if err != nil {
  861. os.RemoveAll(root)
  862. return nil, err
  863. }
  864. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  865. os.RemoveAll(root)
  866. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  867. }
  868. err = os.Chdir(curdir)
  869. if err != nil {
  870. os.RemoveAll(root)
  871. return nil, err
  872. }
  873. var server gitServer
  874. if !enforceLocalServer {
  875. // use fakeStorage server, which might be local or remote (at test daemon)
  876. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  877. if err != nil {
  878. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  879. }
  880. } else {
  881. // always start a local http server on CLI test machine
  882. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  883. server = &localGitServer{httpServer}
  884. }
  885. return &fakeGit{
  886. root: root,
  887. server: server,
  888. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  889. }, nil
  890. }
  891. // Write `content` to the file at path `dst`, creating it if necessary,
  892. // as well as any missing directories.
  893. // The file is truncated if it already exists.
  894. // Fail the test when error occurs.
  895. func writeFile(dst, content string, c *check.C) {
  896. // Create subdirectories if necessary
  897. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  898. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  899. c.Assert(err, check.IsNil)
  900. defer f.Close()
  901. // Write content (truncate if it exists)
  902. _, err = io.Copy(f, strings.NewReader(content))
  903. c.Assert(err, check.IsNil)
  904. }
  905. // Return the contents of file at path `src`.
  906. // Fail the test when error occurs.
  907. func readFile(src string, c *check.C) (content string) {
  908. data, err := ioutil.ReadFile(src)
  909. c.Assert(err, check.IsNil)
  910. return string(data)
  911. }
  912. func containerStorageFile(containerID, basename string) string {
  913. return filepath.Join(testEnv.ContainerStoragePath(), containerID, basename)
  914. }
  915. // docker commands that use this function must be run with the '-d' switch.
  916. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  917. out, _, err := runCommandWithOutput(cmd)
  918. if err != nil {
  919. return nil, fmt.Errorf("%v: %q", err, out)
  920. }
  921. contID := strings.TrimSpace(out)
  922. if err := waitRun(contID); err != nil {
  923. return nil, fmt.Errorf("%v: %q", contID, err)
  924. }
  925. return readContainerFile(contID, filename)
  926. }
  927. func readContainerFile(containerID, filename string) ([]byte, error) {
  928. f, err := os.Open(containerStorageFile(containerID, filename))
  929. if err != nil {
  930. return nil, err
  931. }
  932. defer f.Close()
  933. content, err := ioutil.ReadAll(f)
  934. if err != nil {
  935. return nil, err
  936. }
  937. return content, nil
  938. }
  939. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  940. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  941. return []byte(out), err
  942. }
  943. // daemonTime provides the current time on the daemon host
  944. func daemonTime(c *check.C) time.Time {
  945. if testEnv.LocalDaemon() {
  946. return time.Now()
  947. }
  948. status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
  949. c.Assert(err, check.IsNil)
  950. c.Assert(status, check.Equals, http.StatusOK)
  951. type infoJSON struct {
  952. SystemTime string
  953. }
  954. var info infoJSON
  955. err = json.Unmarshal(body, &info)
  956. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  957. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  958. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  959. return dt
  960. }
  961. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  962. // It return the time formatted how the client sends timestamps to the server.
  963. func daemonUnixTime(c *check.C) string {
  964. return parseEventTime(daemonTime(c))
  965. }
  966. func parseEventTime(t time.Time) string {
  967. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  968. }
  969. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *registry.V2 {
  970. reg, err := registry.NewV2(schema1, auth, tokenURL, privateRegistryURL)
  971. c.Assert(err, check.IsNil)
  972. // Wait for registry to be ready to serve requests.
  973. for i := 0; i != 50; i++ {
  974. if err = reg.Ping(); err == nil {
  975. break
  976. }
  977. time.Sleep(100 * time.Millisecond)
  978. }
  979. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  980. return reg
  981. }
  982. func setupNotary(c *check.C) *testNotary {
  983. ts, err := newTestNotary(c)
  984. c.Assert(err, check.IsNil)
  985. return ts
  986. }
  987. // appendBaseEnv appends the minimum set of environment variables to exec the
  988. // docker cli binary for testing with correct configuration to the given env
  989. // list.
  990. func appendBaseEnv(isTLS bool, env ...string) []string {
  991. preserveList := []string{
  992. // preserve remote test host
  993. "DOCKER_HOST",
  994. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  995. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  996. "SystemRoot",
  997. // testing help text requires the $PATH to dockerd is set
  998. "PATH",
  999. }
  1000. if isTLS {
  1001. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  1002. }
  1003. for _, key := range preserveList {
  1004. if val := os.Getenv(key); val != "" {
  1005. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1006. }
  1007. }
  1008. return env
  1009. }
  1010. func createTmpFile(c *check.C, content string) string {
  1011. f, err := ioutil.TempFile("", "testfile")
  1012. c.Assert(err, check.IsNil)
  1013. filename := f.Name()
  1014. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1015. c.Assert(err, check.IsNil)
  1016. return filename
  1017. }
  1018. func waitForContainer(contID string, args ...string) error {
  1019. args = append([]string{dockerBinary, "run", "--name", contID}, args...)
  1020. result := icmd.RunCmd(icmd.Cmd{Command: args})
  1021. if result.Error != nil {
  1022. return result.Error
  1023. }
  1024. return waitRun(contID)
  1025. }
  1026. // waitRestart will wait for the specified container to restart once
  1027. func waitRestart(contID string, duration time.Duration) error {
  1028. return waitInspect(contID, "{{.RestartCount}}", "1", duration)
  1029. }
  1030. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1031. func waitRun(contID string) error {
  1032. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1033. }
  1034. // waitExited will wait for the specified container to state exit, subject
  1035. // to a maximum time limit in seconds supplied by the caller
  1036. func waitExited(contID string, duration time.Duration) error {
  1037. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1038. }
  1039. // waitInspect will wait for the specified container to have the specified string
  1040. // in the inspect output. It will wait until the specified timeout (in seconds)
  1041. // is reached.
  1042. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1043. return waitInspectWithArgs(name, expr, expected, timeout)
  1044. }
  1045. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1046. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  1047. }
  1048. func getInspectBody(c *check.C, version, id string) []byte {
  1049. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1050. status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost())
  1051. c.Assert(err, check.IsNil)
  1052. c.Assert(status, check.Equals, http.StatusOK)
  1053. return body
  1054. }
  1055. // Run a long running idle task in a background container using the
  1056. // system-specific default image and command.
  1057. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1058. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1059. }
  1060. // Run a long running idle task in a background container using the specified
  1061. // image and the system-specific command.
  1062. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1063. args := []string{"run", "-d"}
  1064. args = append(args, extraArgs...)
  1065. args = append(args, image)
  1066. args = append(args, sleepCommandForDaemonPlatform()...)
  1067. return dockerCmd(c, args...)
  1068. }
  1069. // minimalBaseImage returns the name of the minimal base image for the current
  1070. // daemon platform.
  1071. func minimalBaseImage() string {
  1072. return testEnv.MinimalBaseImage()
  1073. }
  1074. func getGoroutineNumber() (int, error) {
  1075. i := struct {
  1076. NGoroutines int
  1077. }{}
  1078. status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
  1079. if err != nil {
  1080. return 0, err
  1081. }
  1082. if status != http.StatusOK {
  1083. return 0, fmt.Errorf("http status code: %d", status)
  1084. }
  1085. if err := json.Unmarshal(b, &i); err != nil {
  1086. return 0, err
  1087. }
  1088. return i.NGoroutines, nil
  1089. }
  1090. func waitForGoroutines(expected int) error {
  1091. t := time.After(30 * time.Second)
  1092. for {
  1093. select {
  1094. case <-t:
  1095. n, err := getGoroutineNumber()
  1096. if err != nil {
  1097. return err
  1098. }
  1099. if n > expected {
  1100. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  1101. }
  1102. default:
  1103. n, err := getGoroutineNumber()
  1104. if err != nil {
  1105. return err
  1106. }
  1107. if n <= expected {
  1108. return nil
  1109. }
  1110. time.Sleep(200 * time.Millisecond)
  1111. }
  1112. }
  1113. }
  1114. // getErrorMessage returns the error message from an error API response
  1115. func getErrorMessage(c *check.C, body []byte) string {
  1116. var resp types.ErrorResponse
  1117. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  1118. return strings.TrimSpace(resp.Message)
  1119. }
  1120. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  1121. after := time.After(timeout)
  1122. for {
  1123. v, comment := f(c)
  1124. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  1125. select {
  1126. case <-after:
  1127. assert = true
  1128. default:
  1129. }
  1130. if assert {
  1131. if comment != nil {
  1132. args = append(args, comment)
  1133. }
  1134. c.Assert(v, checker, args...)
  1135. return
  1136. }
  1137. time.Sleep(100 * time.Millisecond)
  1138. }
  1139. }
  1140. type checkF func(*check.C) (interface{}, check.CommentInterface)
  1141. type reducer func(...interface{}) interface{}
  1142. func reducedCheck(r reducer, funcs ...checkF) checkF {
  1143. return func(c *check.C) (interface{}, check.CommentInterface) {
  1144. var values []interface{}
  1145. var comments []string
  1146. for _, f := range funcs {
  1147. v, comment := f(c)
  1148. values = append(values, v)
  1149. if comment != nil {
  1150. comments = append(comments, comment.CheckCommentString())
  1151. }
  1152. }
  1153. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  1154. }
  1155. }
  1156. func sumAsIntegers(vals ...interface{}) interface{} {
  1157. var s int
  1158. for _, v := range vals {
  1159. s += v.(int)
  1160. }
  1161. return s
  1162. }