docker_utils_test.go 35 KB

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