docker_utils.go 39 KB

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