docker_utils.go 41 KB

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