docker_utils.go 41 KB

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