docker_utils.go 43 KB

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