docker_utils.go 43 KB

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