docker_utils.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/tls"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/http/httputil"
  15. "net/url"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/httputils"
  25. "github.com/docker/docker/pkg/integration"
  26. "github.com/docker/docker/pkg/ioutils"
  27. "github.com/docker/docker/pkg/stringutils"
  28. "github.com/docker/engine-api/types"
  29. "github.com/docker/go-connections/tlsconfig"
  30. "github.com/docker/go-units"
  31. "github.com/go-check/check"
  32. )
  33. func init() {
  34. cmd := exec.Command(dockerBinary, "images", "-f", "dangling=false", "--format", "{{.Repository}}:{{.Tag}}")
  35. cmd.Env = appendBaseEnv(true)
  36. out, err := cmd.CombinedOutput()
  37. if err != nil {
  38. panic(fmt.Errorf("err=%v\nout=%s\n", err, out))
  39. }
  40. images := strings.Split(strings.TrimSpace(string(out)), "\n")
  41. for _, img := range images {
  42. protectedImages[img] = struct{}{}
  43. }
  44. res, body, err := sockRequestRaw("GET", "/info", nil, "application/json")
  45. if err != nil {
  46. panic(fmt.Errorf("Init failed to get /info: %v", err))
  47. }
  48. defer body.Close()
  49. if res.StatusCode != http.StatusOK {
  50. panic(fmt.Errorf("Init failed to get /info. Res=%v", res))
  51. }
  52. svrHeader, _ := httputils.ParseServerHeader(res.Header.Get("Server"))
  53. daemonPlatform = svrHeader.OS
  54. if daemonPlatform != "linux" && daemonPlatform != "windows" {
  55. panic("Cannot run tests against platform: " + daemonPlatform)
  56. }
  57. // Now we know the daemon platform, can set paths used by tests.
  58. var info types.Info
  59. err = json.NewDecoder(body).Decode(&info)
  60. if err != nil {
  61. panic(fmt.Errorf("Init failed to unmarshal docker info: %v", err))
  62. }
  63. daemonStorageDriver = info.Driver
  64. dockerBasePath = info.DockerRootDir
  65. volumesConfigPath = filepath.Join(dockerBasePath, "volumes")
  66. containerStoragePath = filepath.Join(dockerBasePath, "containers")
  67. // Make sure in context of daemon, not the local platform. Note we can't
  68. // use filepath.FromSlash or ToSlash here as they are a no-op on Unix.
  69. if daemonPlatform == "windows" {
  70. volumesConfigPath = strings.Replace(volumesConfigPath, `/`, `\`, -1)
  71. containerStoragePath = strings.Replace(containerStoragePath, `/`, `\`, -1)
  72. // On Windows, extract out the version as we need to make selective
  73. // decisions during integration testing as and when features are implemented.
  74. // eg in "10.0 10550 (10550.1000.amd64fre.branch.date-time)" we want 10550
  75. windowsDaemonKV, _ = strconv.Atoi(strings.Split(info.KernelVersion, " ")[1])
  76. } else {
  77. volumesConfigPath = strings.Replace(volumesConfigPath, `\`, `/`, -1)
  78. containerStoragePath = strings.Replace(containerStoragePath, `\`, `/`, -1)
  79. }
  80. }
  81. func convertBasesize(basesizeBytes int64) (int64, error) {
  82. basesize := units.HumanSize(float64(basesizeBytes))
  83. basesize = strings.Trim(basesize, " ")[:len(basesize)-3]
  84. basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
  85. if err != nil {
  86. return 0, err
  87. }
  88. return int64(basesizeFloat) * 1024 * 1024 * 1024, nil
  89. }
  90. func daemonHost() string {
  91. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  92. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  93. daemonURLStr = daemonHostVar
  94. }
  95. return daemonURLStr
  96. }
  97. func getTLSConfig() (*tls.Config, error) {
  98. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  99. if dockerCertPath == "" {
  100. return nil, fmt.Errorf("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  101. }
  102. option := &tlsconfig.Options{
  103. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  104. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  105. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  106. }
  107. tlsConfig, err := tlsconfig.Client(*option)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return tlsConfig, nil
  112. }
  113. func sockConn(timeout time.Duration, 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. container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
  204. rmArgs := strings.Split(fmt.Sprintf("rm -fv %v", container), " ")
  205. exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
  206. // set error manually if not set
  207. if exitCode != 0 && err == nil {
  208. err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
  209. }
  210. return err
  211. }
  212. func getAllContainers() (string, error) {
  213. getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
  214. out, exitCode, err := runCommandWithOutput(getContainersCmd)
  215. if exitCode != 0 && err == nil {
  216. err = fmt.Errorf("failed to get a list of containers: %v\n", out)
  217. }
  218. return out, err
  219. }
  220. func deleteAllContainers() error {
  221. containers, err := getAllContainers()
  222. if err != nil {
  223. fmt.Println(containers)
  224. return err
  225. }
  226. if containers != "" {
  227. if err = deleteContainer(containers); err != nil {
  228. return err
  229. }
  230. }
  231. return nil
  232. }
  233. func deleteAllNetworks() error {
  234. networks, err := getAllNetworks()
  235. if err != nil {
  236. return err
  237. }
  238. var errors []string
  239. for _, n := range networks {
  240. if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
  241. continue
  242. }
  243. if daemonPlatform == "windows" && strings.ToLower(n.Name) == "nat" {
  244. // nat is a pre-defined network on Windows and cannot be removed
  245. continue
  246. }
  247. status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
  248. if err != nil {
  249. errors = append(errors, err.Error())
  250. continue
  251. }
  252. if status != http.StatusNoContent {
  253. errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
  254. }
  255. }
  256. if len(errors) > 0 {
  257. return fmt.Errorf(strings.Join(errors, "\n"))
  258. }
  259. return nil
  260. }
  261. func getAllNetworks() ([]types.NetworkResource, error) {
  262. var networks []types.NetworkResource
  263. _, b, err := sockRequest("GET", "/networks", nil)
  264. if err != nil {
  265. return nil, err
  266. }
  267. if err := json.Unmarshal(b, &networks); err != nil {
  268. return nil, err
  269. }
  270. return networks, nil
  271. }
  272. func deleteAllVolumes() error {
  273. volumes, err := getAllVolumes()
  274. if err != nil {
  275. return err
  276. }
  277. var errors []string
  278. for _, v := range volumes {
  279. status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
  280. if err != nil {
  281. errors = append(errors, err.Error())
  282. continue
  283. }
  284. if status != http.StatusNoContent {
  285. errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
  286. }
  287. }
  288. if len(errors) > 0 {
  289. return fmt.Errorf(strings.Join(errors, "\n"))
  290. }
  291. return nil
  292. }
  293. func getAllVolumes() ([]*types.Volume, error) {
  294. var volumes types.VolumesListResponse
  295. _, b, err := sockRequest("GET", "/volumes", nil)
  296. if err != nil {
  297. return nil, err
  298. }
  299. if err := json.Unmarshal(b, &volumes); err != nil {
  300. return nil, err
  301. }
  302. return volumes.Volumes, nil
  303. }
  304. var protectedImages = map[string]struct{}{}
  305. func deleteAllImages() error {
  306. cmd := exec.Command(dockerBinary, "images")
  307. cmd.Env = appendBaseEnv(true)
  308. out, err := cmd.CombinedOutput()
  309. if err != nil {
  310. return err
  311. }
  312. lines := strings.Split(string(out), "\n")[1:]
  313. var imgs []string
  314. for _, l := range lines {
  315. if l == "" {
  316. continue
  317. }
  318. fields := strings.Fields(l)
  319. imgTag := fields[0] + ":" + fields[1]
  320. if _, ok := protectedImages[imgTag]; !ok {
  321. if fields[0] == "<none>" {
  322. imgs = append(imgs, fields[2])
  323. continue
  324. }
  325. imgs = append(imgs, imgTag)
  326. }
  327. }
  328. if len(imgs) == 0 {
  329. return nil
  330. }
  331. args := append([]string{"rmi", "-f"}, imgs...)
  332. if err := exec.Command(dockerBinary, args...).Run(); err != nil {
  333. return err
  334. }
  335. return nil
  336. }
  337. func getPausedContainers() (string, error) {
  338. getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
  339. out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
  340. if exitCode != 0 && err == nil {
  341. err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
  342. }
  343. return out, err
  344. }
  345. func getSliceOfPausedContainers() ([]string, error) {
  346. out, err := getPausedContainers()
  347. if err == nil {
  348. if len(out) == 0 {
  349. return nil, err
  350. }
  351. slice := strings.Split(strings.TrimSpace(out), "\n")
  352. return slice, err
  353. }
  354. return []string{out}, err
  355. }
  356. func unpauseContainer(container string) error {
  357. unpauseCmd := exec.Command(dockerBinary, "unpause", container)
  358. exitCode, err := runCommand(unpauseCmd)
  359. if exitCode != 0 && err == nil {
  360. err = fmt.Errorf("failed to unpause container")
  361. }
  362. return err
  363. }
  364. func unpauseAllContainers() error {
  365. containers, err := getPausedContainers()
  366. if err != nil {
  367. fmt.Println(containers)
  368. return err
  369. }
  370. containers = strings.Replace(containers, "\n", " ", -1)
  371. containers = strings.Trim(containers, " ")
  372. containerList := strings.Split(containers, " ")
  373. for _, value := range containerList {
  374. if err = unpauseContainer(value); err != nil {
  375. return err
  376. }
  377. }
  378. return nil
  379. }
  380. func deleteImages(images ...string) error {
  381. args := []string{"rmi", "-f"}
  382. args = append(args, images...)
  383. rmiCmd := exec.Command(dockerBinary, args...)
  384. exitCode, err := runCommand(rmiCmd)
  385. // set error manually if not set
  386. if exitCode != 0 && err == nil {
  387. err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
  388. }
  389. return err
  390. }
  391. func imageExists(image string) error {
  392. inspectCmd := exec.Command(dockerBinary, "inspect", image)
  393. exitCode, err := runCommand(inspectCmd)
  394. if exitCode != 0 && err == nil {
  395. err = fmt.Errorf("couldn't find image %q", image)
  396. }
  397. return err
  398. }
  399. func pullImageIfNotExist(image string) error {
  400. if err := imageExists(image); err != nil {
  401. pullCmd := exec.Command(dockerBinary, "pull", image)
  402. _, exitCode, err := runCommandWithOutput(pullCmd)
  403. if err != nil || exitCode != 0 {
  404. return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
  405. }
  406. }
  407. return nil
  408. }
  409. func dockerCmdWithError(args ...string) (string, int, error) {
  410. if err := validateArgs(args...); err != nil {
  411. return "", 0, err
  412. }
  413. out, code, err := integration.DockerCmdWithError(dockerBinary, args...)
  414. if err != nil {
  415. err = fmt.Errorf("%v: %s", err, out)
  416. }
  417. return out, code, err
  418. }
  419. func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
  420. if err := validateArgs(args...); err != nil {
  421. c.Fatalf(err.Error())
  422. }
  423. return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
  424. }
  425. func dockerCmd(c *check.C, args ...string) (string, int) {
  426. if err := validateArgs(args...); err != nil {
  427. c.Fatalf(err.Error())
  428. }
  429. return integration.DockerCmd(dockerBinary, c, args...)
  430. }
  431. // execute a docker command with a timeout
  432. func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
  433. if err := validateArgs(args...); err != nil {
  434. return "", 0, err
  435. }
  436. return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
  437. }
  438. // execute a docker command in a directory
  439. func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
  440. if err := validateArgs(args...); err != nil {
  441. c.Fatalf(err.Error())
  442. }
  443. return integration.DockerCmdInDir(dockerBinary, path, args...)
  444. }
  445. // execute a docker command in a directory with a timeout
  446. func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
  447. if err := validateArgs(args...); err != nil {
  448. return "", 0, err
  449. }
  450. return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
  451. }
  452. // validateArgs is a checker to ensure tests are not running commands which are
  453. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  454. func validateArgs(args ...string) error {
  455. if daemonPlatform != "windows" {
  456. return nil
  457. }
  458. foundBusybox := -1
  459. for key, value := range args {
  460. if strings.ToLower(value) == "busybox" {
  461. foundBusybox = key
  462. }
  463. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  464. return errors.New("Cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  465. }
  466. }
  467. return nil
  468. }
  469. // find the State.ExitCode in container metadata
  470. func findContainerExitCode(c *check.C, name string, vargs ...string) string {
  471. args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
  472. cmd := exec.Command(dockerBinary, args...)
  473. out, _, err := runCommandWithOutput(cmd)
  474. if err != nil {
  475. c.Fatal(err, out)
  476. }
  477. return out
  478. }
  479. func findContainerIP(c *check.C, id string, network string) string {
  480. out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
  481. return strings.Trim(out, " \r\n'")
  482. }
  483. func getContainerCount() (int, error) {
  484. const containers = "Containers:"
  485. cmd := exec.Command(dockerBinary, "info")
  486. out, _, err := runCommandWithOutput(cmd)
  487. if err != nil {
  488. return 0, err
  489. }
  490. lines := strings.Split(out, "\n")
  491. for _, line := range lines {
  492. if strings.Contains(line, containers) {
  493. output := strings.TrimSpace(line)
  494. output = strings.TrimLeft(output, containers)
  495. output = strings.Trim(output, " ")
  496. containerCount, err := strconv.Atoi(output)
  497. if err != nil {
  498. return 0, err
  499. }
  500. return containerCount, nil
  501. }
  502. }
  503. return 0, fmt.Errorf("couldn't find the Container count in the output")
  504. }
  505. // FakeContext creates directories that can be used as a build context
  506. type FakeContext struct {
  507. Dir string
  508. }
  509. // Add a file at a path, creating directories where necessary
  510. func (f *FakeContext) Add(file, content string) error {
  511. return f.addFile(file, []byte(content))
  512. }
  513. func (f *FakeContext) addFile(file string, content []byte) error {
  514. filepath := path.Join(f.Dir, file)
  515. dirpath := path.Dir(filepath)
  516. if dirpath != "." {
  517. if err := os.MkdirAll(dirpath, 0755); err != nil {
  518. return err
  519. }
  520. }
  521. return ioutil.WriteFile(filepath, content, 0644)
  522. }
  523. // Delete a file at a path
  524. func (f *FakeContext) Delete(file string) error {
  525. filepath := path.Join(f.Dir, file)
  526. return os.RemoveAll(filepath)
  527. }
  528. // Close deletes the context
  529. func (f *FakeContext) Close() error {
  530. return os.RemoveAll(f.Dir)
  531. }
  532. func fakeContextFromNewTempDir() (*FakeContext, error) {
  533. tmp, err := ioutil.TempDir("", "fake-context")
  534. if err != nil {
  535. return nil, err
  536. }
  537. if err := os.Chmod(tmp, 0755); err != nil {
  538. return nil, err
  539. }
  540. return fakeContextFromDir(tmp), nil
  541. }
  542. func fakeContextFromDir(dir string) *FakeContext {
  543. return &FakeContext{dir}
  544. }
  545. func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
  546. ctx, err := fakeContextFromNewTempDir()
  547. if err != nil {
  548. return nil, err
  549. }
  550. for file, content := range files {
  551. if err := ctx.Add(file, content); err != nil {
  552. ctx.Close()
  553. return nil, err
  554. }
  555. }
  556. return ctx, nil
  557. }
  558. func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
  559. if err := ctx.Add("Dockerfile", dockerfile); err != nil {
  560. ctx.Close()
  561. return err
  562. }
  563. return nil
  564. }
  565. func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
  566. ctx, err := fakeContextWithFiles(files)
  567. if err != nil {
  568. return nil, err
  569. }
  570. if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
  571. return nil, err
  572. }
  573. return ctx, nil
  574. }
  575. // FakeStorage is a static file server. It might be running locally or remotely
  576. // on test host.
  577. type FakeStorage interface {
  578. Close() error
  579. URL() string
  580. CtxDir() string
  581. }
  582. func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
  583. ctx, err := fakeContextFromNewTempDir()
  584. if err != nil {
  585. return nil, err
  586. }
  587. for name, content := range archives {
  588. if err := ctx.addFile(name, content.Bytes()); err != nil {
  589. return nil, err
  590. }
  591. }
  592. return fakeStorageWithContext(ctx)
  593. }
  594. // fakeStorage returns either a local or remote (at daemon machine) file server
  595. func fakeStorage(files map[string]string) (FakeStorage, error) {
  596. ctx, err := fakeContextWithFiles(files)
  597. if err != nil {
  598. return nil, err
  599. }
  600. return fakeStorageWithContext(ctx)
  601. }
  602. // fakeStorageWithContext returns either a local or remote (at daemon machine) file server
  603. func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
  604. if isLocalDaemon {
  605. return newLocalFakeStorage(ctx)
  606. }
  607. return newRemoteFileServer(ctx)
  608. }
  609. // localFileStorage is a file storage on the running machine
  610. type localFileStorage struct {
  611. *FakeContext
  612. *httptest.Server
  613. }
  614. func (s *localFileStorage) URL() string {
  615. return s.Server.URL
  616. }
  617. func (s *localFileStorage) CtxDir() string {
  618. return s.FakeContext.Dir
  619. }
  620. func (s *localFileStorage) Close() error {
  621. defer s.Server.Close()
  622. return s.FakeContext.Close()
  623. }
  624. func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
  625. handler := http.FileServer(http.Dir(ctx.Dir))
  626. server := httptest.NewServer(handler)
  627. return &localFileStorage{
  628. FakeContext: ctx,
  629. Server: server,
  630. }, nil
  631. }
  632. // remoteFileServer is a containerized static file server started on the remote
  633. // testing machine to be used in URL-accepting docker build functionality.
  634. type remoteFileServer struct {
  635. host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
  636. container string
  637. image string
  638. ctx *FakeContext
  639. }
  640. func (f *remoteFileServer) URL() string {
  641. u := url.URL{
  642. Scheme: "http",
  643. Host: f.host}
  644. return u.String()
  645. }
  646. func (f *remoteFileServer) CtxDir() string {
  647. return f.ctx.Dir
  648. }
  649. func (f *remoteFileServer) Close() error {
  650. defer func() {
  651. if f.ctx != nil {
  652. f.ctx.Close()
  653. }
  654. if f.image != "" {
  655. deleteImages(f.image)
  656. }
  657. }()
  658. if f.container == "" {
  659. return nil
  660. }
  661. return deleteContainer(f.container)
  662. }
  663. func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
  664. var (
  665. image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  666. container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
  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 := unmarshalJSON([]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{"run", "--name", contID}, args...)
  1186. cmd := exec.Command(dockerBinary, args...)
  1187. if _, err := runCommand(cmd); err != nil {
  1188. return err
  1189. }
  1190. if err := waitRun(contID); err != nil {
  1191. return err
  1192. }
  1193. return nil
  1194. }
  1195. // waitRun will wait for the specified container to be running, maximum 5 seconds.
  1196. func waitRun(contID string) error {
  1197. return waitInspect(contID, "{{.State.Running}}", "true", 5*time.Second)
  1198. }
  1199. // waitExited will wait for the specified container to state exit, subject
  1200. // to a maximum time limit in seconds supplied by the caller
  1201. func waitExited(contID string, duration time.Duration) error {
  1202. return waitInspect(contID, "{{.State.Status}}", "exited", duration)
  1203. }
  1204. // waitInspect will wait for the specified container to have the specified string
  1205. // in the inspect output. It will wait until the specified timeout (in seconds)
  1206. // is reached.
  1207. func waitInspect(name, expr, expected string, timeout time.Duration) error {
  1208. return waitInspectWithArgs(name, expr, expected, timeout)
  1209. }
  1210. func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg ...string) error {
  1211. after := time.After(timeout)
  1212. args := append(arg, "inspect", "-f", expr, name)
  1213. for {
  1214. cmd := exec.Command(dockerBinary, args...)
  1215. out, _, err := runCommandWithOutput(cmd)
  1216. if err != nil {
  1217. if !strings.Contains(out, "No such") {
  1218. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  1219. }
  1220. select {
  1221. case <-after:
  1222. return err
  1223. default:
  1224. time.Sleep(10 * time.Millisecond)
  1225. continue
  1226. }
  1227. }
  1228. out = strings.TrimSpace(out)
  1229. if out == expected {
  1230. break
  1231. }
  1232. select {
  1233. case <-after:
  1234. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  1235. default:
  1236. }
  1237. time.Sleep(100 * time.Millisecond)
  1238. }
  1239. return nil
  1240. }
  1241. func getInspectBody(c *check.C, version, id string) []byte {
  1242. endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id)
  1243. status, body, err := sockRequest("GET", endpoint, nil)
  1244. c.Assert(err, check.IsNil)
  1245. c.Assert(status, check.Equals, http.StatusOK)
  1246. return body
  1247. }
  1248. // Run a long running idle task in a background container using the
  1249. // system-specific default image and command.
  1250. func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) {
  1251. return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...)
  1252. }
  1253. // Run a long running idle task in a background container using the specified
  1254. // image and the system-specific command.
  1255. func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) {
  1256. args := []string{"run", "-d"}
  1257. args = append(args, extraArgs...)
  1258. args = append(args, image)
  1259. args = append(args, defaultSleepCommand...)
  1260. return dockerCmd(c, args...)
  1261. }
  1262. func getRootUIDGID() (int, int, error) {
  1263. uidgid := strings.Split(filepath.Base(dockerBasePath), ".")
  1264. if len(uidgid) == 1 {
  1265. //user namespace remapping is not turned on; return 0
  1266. return 0, 0, nil
  1267. }
  1268. uid, err := strconv.Atoi(uidgid[0])
  1269. if err != nil {
  1270. return 0, 0, err
  1271. }
  1272. gid, err := strconv.Atoi(uidgid[1])
  1273. if err != nil {
  1274. return 0, 0, err
  1275. }
  1276. return uid, gid, nil
  1277. }
  1278. // minimalBaseImage returns the name of the minimal base image for the current
  1279. // daemon platform.
  1280. func minimalBaseImage() string {
  1281. if daemonPlatform == "windows" {
  1282. return WindowsBaseImage
  1283. }
  1284. return "scratch"
  1285. }
  1286. func getGoroutineNumber() (int, error) {
  1287. i := struct {
  1288. NGoroutines int
  1289. }{}
  1290. status, b, err := sockRequest("GET", "/info", nil)
  1291. if err != nil {
  1292. return 0, err
  1293. }
  1294. if status != http.StatusOK {
  1295. return 0, fmt.Errorf("http status code: %d", status)
  1296. }
  1297. if err := json.Unmarshal(b, &i); err != nil {
  1298. return 0, err
  1299. }
  1300. return i.NGoroutines, nil
  1301. }
  1302. func waitForGoroutines(expected int) error {
  1303. t := time.After(30 * time.Second)
  1304. for {
  1305. select {
  1306. case <-t:
  1307. n, err := getGoroutineNumber()
  1308. if err != nil {
  1309. return err
  1310. }
  1311. if n > expected {
  1312. return fmt.Errorf("leaked goroutines: expected less than or equal to %d, got: %d", expected, n)
  1313. }
  1314. default:
  1315. n, err := getGoroutineNumber()
  1316. if err != nil {
  1317. return err
  1318. }
  1319. if n <= expected {
  1320. return nil
  1321. }
  1322. time.Sleep(200 * time.Millisecond)
  1323. }
  1324. }
  1325. }
  1326. // getErrorMessage returns the error message from an error API response
  1327. func getErrorMessage(c *check.C, body []byte) string {
  1328. var resp types.ErrorResponse
  1329. c.Assert(json.Unmarshal(body, &resp), check.IsNil)
  1330. return strings.TrimSpace(resp.Message)
  1331. }
  1332. func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) {
  1333. after := time.After(timeout)
  1334. for {
  1335. v, comment := f(c)
  1336. assert, _ := checker.Check(append([]interface{}{v}, args...), checker.Info().Params)
  1337. select {
  1338. case <-after:
  1339. assert = true
  1340. default:
  1341. }
  1342. if assert {
  1343. if comment != nil {
  1344. args = append(args, comment)
  1345. }
  1346. c.Assert(v, checker, args...)
  1347. return
  1348. }
  1349. time.Sleep(100 * time.Millisecond)
  1350. }
  1351. }
  1352. type checkF func(*check.C) (interface{}, check.CommentInterface)
  1353. type reducer func(...interface{}) interface{}
  1354. func reducedCheck(r reducer, funcs ...checkF) checkF {
  1355. return func(c *check.C) (interface{}, check.CommentInterface) {
  1356. var values []interface{}
  1357. var comments []string
  1358. for _, f := range funcs {
  1359. v, comment := f(c)
  1360. values = append(values, v)
  1361. if comment != nil {
  1362. comments = append(comments, comment.CheckCommentString())
  1363. }
  1364. }
  1365. return r(values...), check.Commentf("%v", strings.Join(comments, ", "))
  1366. }
  1367. }
  1368. func sumAsIntegers(vals ...interface{}) interface{} {
  1369. var s int
  1370. for _, v := range vals {
  1371. s += v.(int)
  1372. }
  1373. return s
  1374. }