docker_utils.go 44 KB

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