docker_utils.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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. result := icmd.RunCmd(transformCmd(buildCmd))
  793. err := result.Error
  794. exitCode := result.ExitCode
  795. if err != nil || exitCode != 0 {
  796. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  797. }
  798. id, err := getIDByName(name)
  799. if err != nil {
  800. return "", result.Stdout(), result.Stderr(), err
  801. }
  802. return id, result.Stdout(), result.Stderr(), nil
  803. }
  804. func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
  805. id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
  806. return id, err
  807. }
  808. func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
  809. id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
  810. if err != nil {
  811. return "", err
  812. }
  813. return id, nil
  814. }
  815. func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
  816. args := []string{"build", "-t", name}
  817. if !useCache {
  818. args = append(args, "--no-cache")
  819. }
  820. args = append(args, buildFlags...)
  821. args = append(args, ".")
  822. buildCmd := exec.Command(dockerBinary, args...)
  823. buildCmd.Dir = ctx.Dir
  824. out, exitCode, err := runCommandWithOutput(buildCmd)
  825. if err != nil || exitCode != 0 {
  826. return "", "", fmt.Errorf("failed to build the image: %s", out)
  827. }
  828. id, err := getIDByName(name)
  829. if err != nil {
  830. return "", "", err
  831. }
  832. return id, out, nil
  833. }
  834. func buildImageFromContextWithStdoutStderr(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, string, error) {
  835. args := []string{"build", "-t", name}
  836. if !useCache {
  837. args = append(args, "--no-cache")
  838. }
  839. args = append(args, buildFlags...)
  840. args = append(args, ".")
  841. result := icmd.RunCmd(icmd.Cmd{
  842. Command: append([]string{dockerBinary}, args...),
  843. Dir: ctx.Dir,
  844. })
  845. exitCode := result.ExitCode
  846. err := result.Error
  847. if err != nil || exitCode != 0 {
  848. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  849. }
  850. id, err := getIDByName(name)
  851. if err != nil {
  852. return "", result.Stdout(), result.Stderr(), err
  853. }
  854. return id, result.Stdout(), result.Stderr(), nil
  855. }
  856. func buildImageFromGitWithStdoutStderr(name string, ctx *fakeGit, useCache bool, buildFlags ...string) (string, string, string, error) {
  857. args := []string{"build", "-t", name}
  858. if !useCache {
  859. args = append(args, "--no-cache")
  860. }
  861. args = append(args, buildFlags...)
  862. args = append(args, ctx.RepoURL)
  863. result := icmd.RunCmd(icmd.Cmd{
  864. Command: append([]string{dockerBinary}, args...),
  865. })
  866. exitCode := result.ExitCode
  867. err := result.Error
  868. if err != nil || exitCode != 0 {
  869. return "", result.Stdout(), result.Stderr(), fmt.Errorf("failed to build the image: %s", result.Combined())
  870. }
  871. id, err := getIDByName(name)
  872. if err != nil {
  873. return "", result.Stdout(), result.Stderr(), err
  874. }
  875. return id, result.Stdout(), result.Stderr(), nil
  876. }
  877. func buildImageFromPath(name, path string, useCache bool, buildFlags ...string) (string, error) {
  878. args := []string{"build", "-t", name}
  879. if !useCache {
  880. args = append(args, "--no-cache")
  881. }
  882. args = append(args, buildFlags...)
  883. args = append(args, path)
  884. buildCmd := exec.Command(dockerBinary, args...)
  885. out, exitCode, err := runCommandWithOutput(buildCmd)
  886. if err != nil || exitCode != 0 {
  887. return "", fmt.Errorf("failed to build the image: %s", out)
  888. }
  889. return getIDByName(name)
  890. }
  891. type gitServer interface {
  892. URL() string
  893. Close() error
  894. }
  895. type localGitServer struct {
  896. *httptest.Server
  897. }
  898. func (r *localGitServer) Close() error {
  899. r.Server.Close()
  900. return nil
  901. }
  902. func (r *localGitServer) URL() string {
  903. return r.Server.URL
  904. }
  905. type fakeGit struct {
  906. root string
  907. server gitServer
  908. RepoURL string
  909. }
  910. func (g *fakeGit) Close() {
  911. g.server.Close()
  912. os.RemoveAll(g.root)
  913. }
  914. func newFakeGit(name string, files map[string]string, enforceLocalServer bool) (*fakeGit, error) {
  915. ctx, err := fakeContextWithFiles(files)
  916. if err != nil {
  917. return nil, err
  918. }
  919. defer ctx.Close()
  920. curdir, err := os.Getwd()
  921. if err != nil {
  922. return nil, err
  923. }
  924. defer os.Chdir(curdir)
  925. if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil {
  926. return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output)
  927. }
  928. err = os.Chdir(ctx.Dir)
  929. if err != nil {
  930. return nil, err
  931. }
  932. if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil {
  933. return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output)
  934. }
  935. if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil {
  936. return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output)
  937. }
  938. if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil {
  939. return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output)
  940. }
  941. if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil {
  942. return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output)
  943. }
  944. root, err := ioutil.TempDir("", "docker-test-git-repo")
  945. if err != nil {
  946. return nil, err
  947. }
  948. repoPath := filepath.Join(root, name+".git")
  949. if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil {
  950. os.RemoveAll(root)
  951. return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output)
  952. }
  953. err = os.Chdir(repoPath)
  954. if err != nil {
  955. os.RemoveAll(root)
  956. return nil, err
  957. }
  958. if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil {
  959. os.RemoveAll(root)
  960. return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output)
  961. }
  962. err = os.Chdir(curdir)
  963. if err != nil {
  964. os.RemoveAll(root)
  965. return nil, err
  966. }
  967. var server gitServer
  968. if !enforceLocalServer {
  969. // use fakeStorage server, which might be local or remote (at test daemon)
  970. server, err = fakeStorageWithContext(fakeContextFromDir(root))
  971. if err != nil {
  972. return nil, fmt.Errorf("cannot start fake storage: %v", err)
  973. }
  974. } else {
  975. // always start a local http server on CLI test machine
  976. httpServer := httptest.NewServer(http.FileServer(http.Dir(root)))
  977. server = &localGitServer{httpServer}
  978. }
  979. return &fakeGit{
  980. root: root,
  981. server: server,
  982. RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name),
  983. }, nil
  984. }
  985. // Write `content` to the file at path `dst`, creating it if necessary,
  986. // as well as any missing directories.
  987. // The file is truncated if it already exists.
  988. // Fail the test when error occurs.
  989. func writeFile(dst, content string, c *check.C) {
  990. // Create subdirectories if necessary
  991. c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil)
  992. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  993. c.Assert(err, check.IsNil)
  994. defer f.Close()
  995. // Write content (truncate if it exists)
  996. _, err = io.Copy(f, strings.NewReader(content))
  997. c.Assert(err, check.IsNil)
  998. }
  999. // Return the contents of file at path `src`.
  1000. // Fail the test when error occurs.
  1001. func readFile(src string, c *check.C) (content string) {
  1002. data, err := ioutil.ReadFile(src)
  1003. c.Assert(err, check.IsNil)
  1004. return string(data)
  1005. }
  1006. func containerStorageFile(containerID, basename string) string {
  1007. return filepath.Join(containerStoragePath, containerID, basename)
  1008. }
  1009. // docker commands that use this function must be run with the '-d' switch.
  1010. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) {
  1011. out, _, err := runCommandWithOutput(cmd)
  1012. if err != nil {
  1013. return nil, fmt.Errorf("%v: %q", err, out)
  1014. }
  1015. contID := strings.TrimSpace(out)
  1016. if err := waitRun(contID); err != nil {
  1017. return nil, fmt.Errorf("%v: %q", contID, err)
  1018. }
  1019. return readContainerFile(contID, filename)
  1020. }
  1021. func readContainerFile(containerID, filename string) ([]byte, error) {
  1022. f, err := os.Open(containerStorageFile(containerID, filename))
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. defer f.Close()
  1027. content, err := ioutil.ReadAll(f)
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. return content, nil
  1032. }
  1033. func readContainerFileWithExec(containerID, filename string) ([]byte, error) {
  1034. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerID, "cat", filename))
  1035. return []byte(out), err
  1036. }
  1037. // daemonTime provides the current time on the daemon host
  1038. func daemonTime(c *check.C) time.Time {
  1039. if isLocalDaemon {
  1040. return time.Now()
  1041. }
  1042. status, body, err := sockRequest("GET", "/info", nil)
  1043. c.Assert(err, check.IsNil)
  1044. c.Assert(status, check.Equals, http.StatusOK)
  1045. type infoJSON struct {
  1046. SystemTime string
  1047. }
  1048. var info infoJSON
  1049. err = json.Unmarshal(body, &info)
  1050. c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
  1051. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  1052. c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
  1053. return dt
  1054. }
  1055. // daemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  1056. // It return the time formatted how the client sends timestamps to the server.
  1057. func daemonUnixTime(c *check.C) string {
  1058. return parseEventTime(daemonTime(c))
  1059. }
  1060. func parseEventTime(t time.Time) string {
  1061. return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond()))
  1062. }
  1063. func setupRegistry(c *check.C, schema1 bool, auth, tokenURL string) *testRegistryV2 {
  1064. reg, err := newTestRegistryV2(c, schema1, auth, tokenURL)
  1065. c.Assert(err, check.IsNil)
  1066. // Wait for registry to be ready to serve requests.
  1067. for i := 0; i != 50; i++ {
  1068. if err = reg.Ping(); err == nil {
  1069. break
  1070. }
  1071. time.Sleep(100 * time.Millisecond)
  1072. }
  1073. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for test registry to become available: %v", err))
  1074. return reg
  1075. }
  1076. func setupNotary(c *check.C) *testNotary {
  1077. ts, err := newTestNotary(c)
  1078. c.Assert(err, check.IsNil)
  1079. return ts
  1080. }
  1081. // appendBaseEnv appends the minimum set of environment variables to exec the
  1082. // docker cli binary for testing with correct configuration to the given env
  1083. // list.
  1084. func appendBaseEnv(isTLS bool, env ...string) []string {
  1085. preserveList := []string{
  1086. // preserve remote test host
  1087. "DOCKER_HOST",
  1088. // windows: requires preserving SystemRoot, otherwise dial tcp fails
  1089. // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup."
  1090. "SystemRoot",
  1091. // testing help text requires the $PATH to dockerd is set
  1092. "PATH",
  1093. }
  1094. if isTLS {
  1095. preserveList = append(preserveList, "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")
  1096. }
  1097. for _, key := range preserveList {
  1098. if val := os.Getenv(key); val != "" {
  1099. env = append(env, fmt.Sprintf("%s=%s", key, val))
  1100. }
  1101. }
  1102. return env
  1103. }
  1104. func createTmpFile(c *check.C, content string) string {
  1105. f, err := ioutil.TempFile("", "testfile")
  1106. c.Assert(err, check.IsNil)
  1107. filename := f.Name()
  1108. err = ioutil.WriteFile(filename, []byte(content), 0644)
  1109. c.Assert(err, check.IsNil)
  1110. return filename
  1111. }
  1112. func buildImageWithOutInDamon(socket string, name, dockerfile string, useCache bool) (string, error) {
  1113. args := []string{"--host", socket}
  1114. buildCmd := buildImageCmdArgs(args, name, dockerfile, useCache)
  1115. out, exitCode, err := runCommandWithOutput(buildCmd)
  1116. if err != nil || exitCode != 0 {
  1117. return out, fmt.Errorf("failed to build the image: %s, error: %v", out, err)
  1118. }
  1119. return out, nil
  1120. }
  1121. func buildImageCmdArgs(args []string, name, dockerfile string, useCache bool) *exec.Cmd {
  1122. args = append(args, []string{"-D", "build", "-t", name}...)
  1123. if !useCache {
  1124. args = append(args, "--no-cache")
  1125. }
  1126. args = append(args, "-")
  1127. buildCmd := exec.Command(dockerBinary, args...)
  1128. buildCmd.Stdin = strings.NewReader(dockerfile)
  1129. return buildCmd
  1130. }
  1131. func waitForContainer(contID string, args ...string) error {
  1132. args = append([]string{dockerBinary, "run", "--name", contID}, args...)
  1133. result := icmd.RunCmd(icmd.Cmd{Command: args})
  1134. if result.Error != nil {
  1135. return result.Error
  1136. }
  1137. return waitRun(contID)
  1138. }
  1139. // waitRestart will wait for the specified container to restart once
  1140. func waitRestart(contID string, duration time.Duration) error {
  1141. return waitInspect(contID, "{{.RestartCount}}", "1", duration)
  1142. }
  1143. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1144. func waitRun(contID string) error {
  1145. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1146. }
  1147. // waitExited will wait for the specified container to state exit, subject
  1148. // to a maximum time limit in seconds supplied by the caller
  1149. func waitExited(contID string, duration time.Duration) error {
  1150. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1151. }
  1152. // waitInspect will wait for the specified container to have the specified string
  1153. // in the inspect output. It will wait until the specified timeout (in seconds)
  1154. // is reached.
  1155. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1156. return waitInspectWithArgs(name, expr, expected, timeout)
  1157. }
  1158. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1159. return daemon.WaitInspectWithArgs(dockerBinary, name, expr, expected, timeout, arg...)
  1160. }
  1161. func getInspectBody(c *check.C, version, id string) []byte {
  1162. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1163. status, body, err := sockRequest("GET", endpoint, nil)
  1164. c.Assert(err, check.IsNil)
  1165. c.Assert(status, check.Equals, http.StatusOK)
  1166. return body
  1167. }
  1168. // Run a long running idle task in a background container using the
  1169. // system-specific default image and command.
  1170. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1171. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1172. }
  1173. // Run a long running idle task in a background container using the specified
  1174. // image and the system-specific command.
  1175. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1176. args := []string{"run", "-d"}
  1177. args = append(args, extraArgs...)
  1178. args = append(args, image)
  1179. args = append(args, sleepCommandForDaemonPlatform()...)
  1180. return dockerCmd(c, args...)
  1181. }
  1182. func getRootUIDGID() (int, int, error) {
  1183. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1184. if len(uidgid) == 1 {
  1185. //user namespace remapping is not turned on; return 0
  1186. return 0, 0, nil
  1187. }
  1188. uid, err := strconv.Atoi(uidgid[0])
  1189. if err != nil {
  1190. return 0, 0, err
  1191. }
  1192. gid, err := strconv.Atoi(uidgid[1])
  1193. if err != nil {
  1194. return 0, 0, err
  1195. }
  1196. return uid, gid, nil
  1197. }
  1198. // minimalBaseImage returns the name of the minimal base image for the current
  1199. // daemon platform.
  1200. func minimalBaseImage() string {
  1201. if daemonPlatform == "windows" {
  1202. return WindowsBaseImage
  1203. }
  1204. return "scratch"
  1205. }
  1206. func getGoroutineNumber() (int, error) {
  1207. i := struct {
  1208. NGoroutines int
  1209. }{}
  1210. status, b, err := sockRequest("GET", "/info", nil)
  1211. if err != nil {
  1212. return 0, err
  1213. }
  1214. if status != http.StatusOK {
  1215. return 0, fmt.Errorf("http status code: %d", status)
  1216. }
  1217. if err := json.Unmarshal(b, &i); err != nil {
  1218. return 0, err
  1219. }
  1220. return i.NGoroutines, nil
  1221. }
  1222. func waitForGoroutines(expected int) error {
  1223. t := time.After(30 * time.Second)
  1224. for {
  1225. select {
  1226. case <-t:
  1227. n, err := getGoroutineNumber()
  1228. if err != nil {
  1229. return err
  1230. }
  1231. if n > expected {
  1232. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  1233. }
  1234. default:
  1235. n, err := getGoroutineNumber()
  1236. if err != nil {
  1237. return err
  1238. }
  1239. if n <= expected {
  1240. return nil
  1241. }
  1242. time.Sleep(200 * time.Millisecond)
  1243. }
  1244. }
  1245. }
  1246. // getErrorMessage returns the error message from an error API response
  1247. func getErrorMessage(c *check.C, body []byte) string {
  1248. var resp types.ErrorResponse
  1249. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  1250. return strings.TrimSpace(resp.Message)
  1251. }
  1252. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  1253. after := time.After(timeout)
  1254. for {
  1255. v, comment := f(c)
  1256. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  1257. select {
  1258. case <-after:
  1259. assert = true
  1260. default:
  1261. }
  1262. if assert {
  1263. if comment != nil {
  1264. args = append(args, comment)
  1265. }
  1266. c.Assert(v, checker, args...)
  1267. return
  1268. }
  1269. time.Sleep(100 * time.Millisecond)
  1270. }
  1271. }
  1272. type checkF func(*check.C) (interface{}, check.CommentInterface)
  1273. type reducer func(...interface{}) interface{}
  1274. func reducedCheck(r reducer, funcs ...checkF) checkF {
  1275. return func(c *check.C) (interface{}, check.CommentInterface) {
  1276. var values []interface{}
  1277. var comments []string
  1278. for _, f := range funcs {
  1279. v, comment := f(c)
  1280. values = append(values, v)
  1281. if comment != nil {
  1282. comments = append(comments, comment.CheckCommentString())
  1283. }
  1284. }
  1285. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  1286. }
  1287. }
  1288. func sumAsIntegers(vals ...interface{}) interface{} {
  1289. var s int
  1290. for _, v := range vals {
  1291. s += v.(int)
  1292. }
  1293. return s
  1294. }