docker_utils.go 42 KB

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