docker_utils.go 44 KB

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