docker_utils.go 41 KB

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