docker_utils.go 43 KB

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