docker_utils.go 41 KB

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