docker_utils.go 41 KB

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