docker_utils_test.go 37 KB

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