docker_utils_test.go 37 KB

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