docker_utils_test.go 36 KB

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