docker_utils.go 40 KB

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