docker_utils_test.go 36 KB

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