docker_utils.go 45 KB

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