daemon.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/docker/docker/api/types/events"
  16. "github.com/docker/docker/opts"
  17. "github.com/docker/docker/pkg/integration/checker"
  18. "github.com/docker/docker/pkg/ioutils"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/go-connections/sockets"
  21. "github.com/docker/go-connections/tlsconfig"
  22. "github.com/go-check/check"
  23. )
  24. var daemonSockRoot = filepath.Join(os.TempDir(), "docker-integration")
  25. // Daemon represents a Docker daemon for the testing framework.
  26. type Daemon struct {
  27. GlobalFlags []string
  28. id string
  29. c *check.C
  30. logFile *os.File
  31. folder string
  32. root string
  33. stdin io.WriteCloser
  34. stdout, stderr io.ReadCloser
  35. cmd *exec.Cmd
  36. storageDriver string
  37. wait chan error
  38. userlandProxy bool
  39. useDefaultHost bool
  40. useDefaultTLSHost bool
  41. execRoot string
  42. }
  43. type clientConfig struct {
  44. transport *http.Transport
  45. scheme string
  46. addr string
  47. }
  48. // NewDaemon returns a Daemon instance to be used for testing.
  49. // This will create a directory such as d123456789 in the folder specified by $DEST.
  50. // The daemon will not automatically start.
  51. func NewDaemon(c *check.C) *Daemon {
  52. dest := os.Getenv("DEST")
  53. c.Assert(dest, check.Not(check.Equals), "", check.Commentf("Please set the DEST environment variable"))
  54. err := os.MkdirAll(daemonSockRoot, 0700)
  55. c.Assert(err, checker.IsNil, check.Commentf("could not create daemon socket root"))
  56. id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
  57. dir := filepath.Join(dest, id)
  58. daemonFolder, err := filepath.Abs(dir)
  59. c.Assert(err, check.IsNil, check.Commentf("Could not make %q an absolute path", dir))
  60. daemonRoot := filepath.Join(daemonFolder, "root")
  61. c.Assert(os.MkdirAll(daemonRoot, 0755), check.IsNil, check.Commentf("Could not create daemon root %q", dir))
  62. userlandProxy := true
  63. if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
  64. if val, err := strconv.ParseBool(env); err != nil {
  65. userlandProxy = val
  66. }
  67. }
  68. return &Daemon{
  69. id: id,
  70. c: c,
  71. folder: daemonFolder,
  72. root: daemonRoot,
  73. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  74. userlandProxy: userlandProxy,
  75. execRoot: filepath.Join(os.TempDir(), "docker-execroot", id),
  76. }
  77. }
  78. // RootDir returns the root directory of the daemon.
  79. func (d *Daemon) RootDir() string {
  80. return d.root
  81. }
  82. func (d *Daemon) getClientConfig() (*clientConfig, error) {
  83. var (
  84. transport *http.Transport
  85. scheme string
  86. addr string
  87. proto string
  88. )
  89. if d.useDefaultTLSHost {
  90. option := &tlsconfig.Options{
  91. CAFile: "fixtures/https/ca.pem",
  92. CertFile: "fixtures/https/client-cert.pem",
  93. KeyFile: "fixtures/https/client-key.pem",
  94. }
  95. tlsConfig, err := tlsconfig.Client(*option)
  96. if err != nil {
  97. return nil, err
  98. }
  99. transport = &http.Transport{
  100. TLSClientConfig: tlsConfig,
  101. }
  102. addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
  103. scheme = "https"
  104. proto = "tcp"
  105. } else if d.useDefaultHost {
  106. addr = opts.DefaultUnixSocket
  107. proto = "unix"
  108. scheme = "http"
  109. transport = &http.Transport{}
  110. } else {
  111. addr = d.sockPath()
  112. proto = "unix"
  113. scheme = "http"
  114. transport = &http.Transport{}
  115. }
  116. d.c.Assert(sockets.ConfigureTransport(transport, proto, addr), check.IsNil)
  117. return &clientConfig{
  118. transport: transport,
  119. scheme: scheme,
  120. addr: addr,
  121. }, nil
  122. }
  123. // Start will start the daemon and return once it is ready to receive requests.
  124. // You can specify additional daemon flags.
  125. func (d *Daemon) Start(args ...string) error {
  126. logFile, err := os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  127. d.c.Assert(err, check.IsNil, check.Commentf("[%s] Could not create %s/docker.log", d.id, d.folder))
  128. return d.StartWithLogFile(logFile, args...)
  129. }
  130. // StartWithLogFile will start the daemon and attach its streams to a given file.
  131. func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
  132. dockerdBinary, err := exec.LookPath(dockerdBinary)
  133. d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not find docker binary in $PATH", d.id))
  134. args := append(d.GlobalFlags,
  135. "--containerd", "/var/run/docker/libcontainerd/docker-containerd.sock",
  136. "--graph", d.root,
  137. "--exec-root", d.execRoot,
  138. "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder),
  139. fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
  140. )
  141. if experimentalDaemon {
  142. args = append(args, "--experimental", "--init")
  143. }
  144. if !(d.useDefaultHost || d.useDefaultTLSHost) {
  145. args = append(args, []string{"--host", d.sock()}...)
  146. }
  147. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  148. args = append(args, []string{"--userns-remap", root}...)
  149. }
  150. // If we don't explicitly set the log-level or debug flag(-D) then
  151. // turn on debug mode
  152. foundLog := false
  153. foundSd := false
  154. for _, a := range providedArgs {
  155. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
  156. foundLog = true
  157. }
  158. if strings.Contains(a, "--storage-driver") {
  159. foundSd = true
  160. }
  161. }
  162. if !foundLog {
  163. args = append(args, "--debug")
  164. }
  165. if d.storageDriver != "" && !foundSd {
  166. args = append(args, "--storage-driver", d.storageDriver)
  167. }
  168. args = append(args, providedArgs...)
  169. d.cmd = exec.Command(dockerdBinary, args...)
  170. d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
  171. d.cmd.Stdout = out
  172. d.cmd.Stderr = out
  173. d.logFile = out
  174. if err := d.cmd.Start(); err != nil {
  175. return fmt.Errorf("[%s] could not start daemon container: %v", d.id, err)
  176. }
  177. wait := make(chan error)
  178. go func() {
  179. wait <- d.cmd.Wait()
  180. d.c.Logf("[%s] exiting daemon", d.id)
  181. close(wait)
  182. }()
  183. d.wait = wait
  184. tick := time.Tick(500 * time.Millisecond)
  185. // make sure daemon is ready to receive requests
  186. startTime := time.Now().Unix()
  187. for {
  188. d.c.Logf("[%s] waiting for daemon to start", d.id)
  189. if time.Now().Unix()-startTime > 5 {
  190. // After 5 seconds, give up
  191. return fmt.Errorf("[%s] Daemon exited and never started", d.id)
  192. }
  193. select {
  194. case <-time.After(2 * time.Second):
  195. return fmt.Errorf("[%s] timeout: daemon does not respond", d.id)
  196. case <-tick:
  197. clientConfig, err := d.getClientConfig()
  198. if err != nil {
  199. return err
  200. }
  201. client := &http.Client{
  202. Transport: clientConfig.transport,
  203. }
  204. req, err := http.NewRequest("GET", "/_ping", nil)
  205. d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not create new request", d.id))
  206. req.URL.Host = clientConfig.addr
  207. req.URL.Scheme = clientConfig.scheme
  208. resp, err := client.Do(req)
  209. if err != nil {
  210. continue
  211. }
  212. if resp.StatusCode != http.StatusOK {
  213. d.c.Logf("[%s] received status != 200 OK: %s", d.id, resp.Status)
  214. }
  215. d.c.Logf("[%s] daemon started", d.id)
  216. d.root, err = d.queryRootDir()
  217. if err != nil {
  218. return fmt.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
  219. }
  220. return nil
  221. case <-d.wait:
  222. return fmt.Errorf("[%s] Daemon exited during startup", d.id)
  223. }
  224. }
  225. }
  226. // StartWithBusybox will first start the daemon with Daemon.Start()
  227. // then save the busybox image from the main daemon and load it into this Daemon instance.
  228. func (d *Daemon) StartWithBusybox(arg ...string) error {
  229. if err := d.Start(arg...); err != nil {
  230. return err
  231. }
  232. return d.LoadBusybox()
  233. }
  234. // Kill will send a SIGKILL to the daemon
  235. func (d *Daemon) Kill() error {
  236. if d.cmd == nil || d.wait == nil {
  237. return errors.New("daemon not started")
  238. }
  239. defer func() {
  240. d.logFile.Close()
  241. d.cmd = nil
  242. }()
  243. if err := d.cmd.Process.Kill(); err != nil {
  244. d.c.Logf("Could not kill daemon: %v", err)
  245. return err
  246. }
  247. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.folder)); err != nil {
  248. return err
  249. }
  250. return nil
  251. }
  252. // DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
  253. // stack to its log file and exit
  254. // This is used primarily for gathering debug information on test timeout
  255. func (d *Daemon) DumpStackAndQuit() {
  256. if d.cmd == nil || d.cmd.Process == nil {
  257. return
  258. }
  259. signalDaemonDump(d.cmd.Process.Pid)
  260. }
  261. // Stop will send a SIGINT every second and wait for the daemon to stop.
  262. // If it timeouts, a SIGKILL is sent.
  263. // Stop will not delete the daemon directory. If a purged daemon is needed,
  264. // instantiate a new one with NewDaemon.
  265. func (d *Daemon) Stop() error {
  266. if d.cmd == nil || d.wait == nil {
  267. return errors.New("daemon not started")
  268. }
  269. defer func() {
  270. d.logFile.Close()
  271. d.cmd = nil
  272. }()
  273. i := 1
  274. tick := time.Tick(time.Second)
  275. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  276. return fmt.Errorf("could not send signal: %v", err)
  277. }
  278. out1:
  279. for {
  280. select {
  281. case err := <-d.wait:
  282. return err
  283. case <-time.After(20 * time.Second):
  284. // time for stopping jobs and run onShutdown hooks
  285. d.c.Logf("timeout: %v", d.id)
  286. break out1
  287. }
  288. }
  289. out2:
  290. for {
  291. select {
  292. case err := <-d.wait:
  293. return err
  294. case <-tick:
  295. i++
  296. if i > 5 {
  297. d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  298. break out2
  299. }
  300. d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  301. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  302. return fmt.Errorf("could not send signal: %v", err)
  303. }
  304. }
  305. }
  306. if err := d.cmd.Process.Kill(); err != nil {
  307. d.c.Logf("Could not kill daemon: %v", err)
  308. return err
  309. }
  310. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.folder)); err != nil {
  311. return err
  312. }
  313. return nil
  314. }
  315. // Restart will restart the daemon by first stopping it and then starting it.
  316. func (d *Daemon) Restart(arg ...string) error {
  317. d.Stop()
  318. // in the case of tests running a user namespace-enabled daemon, we have resolved
  319. // d.root to be the actual final path of the graph dir after the "uid.gid" of
  320. // remapped root is added--we need to subtract it from the path before calling
  321. // start or else we will continue making subdirectories rather than truly restarting
  322. // with the same location/root:
  323. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  324. d.root = filepath.Dir(d.root)
  325. }
  326. return d.Start(arg...)
  327. }
  328. // LoadBusybox will load the stored busybox into a newly started daemon
  329. func (d *Daemon) LoadBusybox() error {
  330. bb := filepath.Join(d.folder, "busybox.tar")
  331. if _, err := os.Stat(bb); err != nil {
  332. if !os.IsNotExist(err) {
  333. return fmt.Errorf("unexpected error on busybox.tar stat: %v", err)
  334. }
  335. // saving busybox image from main daemon
  336. if out, err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").CombinedOutput(); err != nil {
  337. imagesOut, _ := exec.Command(dockerBinary, "images", "--format", "{{ .Repository }}:{{ .Tag }}").CombinedOutput()
  338. return fmt.Errorf("could not save busybox image: %s\n%s", string(out), strings.TrimSpace(string(imagesOut)))
  339. }
  340. }
  341. // loading busybox image to this daemon
  342. if out, err := d.Cmd("load", "--input", bb); err != nil {
  343. return fmt.Errorf("could not load busybox image: %s", out)
  344. }
  345. if err := os.Remove(bb); err != nil {
  346. d.c.Logf("could not remove %s: %v", bb, err)
  347. }
  348. return nil
  349. }
  350. func (d *Daemon) queryRootDir() (string, error) {
  351. // update daemon root by asking /info endpoint (to support user
  352. // namespaced daemon with root remapped uid.gid directory)
  353. clientConfig, err := d.getClientConfig()
  354. if err != nil {
  355. return "", err
  356. }
  357. client := &http.Client{
  358. Transport: clientConfig.transport,
  359. }
  360. req, err := http.NewRequest("GET", "/info", nil)
  361. if err != nil {
  362. return "", err
  363. }
  364. req.Header.Set("Content-Type", "application/json")
  365. req.URL.Host = clientConfig.addr
  366. req.URL.Scheme = clientConfig.scheme
  367. resp, err := client.Do(req)
  368. if err != nil {
  369. return "", err
  370. }
  371. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  372. return resp.Body.Close()
  373. })
  374. type Info struct {
  375. DockerRootDir string
  376. }
  377. var b []byte
  378. var i Info
  379. b, err = readBody(body)
  380. if err == nil && resp.StatusCode == http.StatusOK {
  381. // read the docker root dir
  382. if err = json.Unmarshal(b, &i); err == nil {
  383. return i.DockerRootDir, nil
  384. }
  385. }
  386. return "", err
  387. }
  388. func (d *Daemon) sock() string {
  389. return fmt.Sprintf("unix://" + d.sockPath())
  390. }
  391. func (d *Daemon) sockPath() string {
  392. return filepath.Join(daemonSockRoot, d.id+".sock")
  393. }
  394. func (d *Daemon) waitRun(contID string) error {
  395. args := []string{"--host", d.sock()}
  396. return waitInspectWithArgs(contID, "{{.State.Running}}", "true", 10*time.Second, args...)
  397. }
  398. func (d *Daemon) getBaseDeviceSize(c *check.C) int64 {
  399. infoCmdOutput, _, err := runCommandPipelineWithOutput(
  400. exec.Command(dockerBinary, "-H", d.sock(), "info"),
  401. exec.Command("grep", "Base Device Size"),
  402. )
  403. c.Assert(err, checker.IsNil)
  404. basesizeSlice := strings.Split(infoCmdOutput, ":")
  405. basesize := strings.Trim(basesizeSlice[1], " ")
  406. basesize = strings.Trim(basesize, "\n")[:len(basesize)-3]
  407. basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
  408. c.Assert(err, checker.IsNil)
  409. basesizeBytes := int64(basesizeFloat) * (1024 * 1024 * 1024)
  410. return basesizeBytes
  411. }
  412. // Cmd will execute a docker CLI command against this Daemon.
  413. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  414. func (d *Daemon) Cmd(args ...string) (string, error) {
  415. b, err := d.command(args...).CombinedOutput()
  416. return string(b), err
  417. }
  418. func (d *Daemon) command(args ...string) *exec.Cmd {
  419. return exec.Command(dockerBinary, d.prependHostArg(args)...)
  420. }
  421. func (d *Daemon) prependHostArg(args []string) []string {
  422. for _, arg := range args {
  423. if arg == "--host" || arg == "-H" {
  424. return args
  425. }
  426. }
  427. return append([]string{"--host", d.sock()}, args...)
  428. }
  429. // SockRequest executes a socket request on a daemon and returns statuscode and output.
  430. func (d *Daemon) SockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  431. jsonData := bytes.NewBuffer(nil)
  432. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  433. return -1, nil, err
  434. }
  435. res, body, err := d.SockRequestRaw(method, endpoint, jsonData, "application/json")
  436. if err != nil {
  437. return -1, nil, err
  438. }
  439. b, err := readBody(body)
  440. return res.StatusCode, b, err
  441. }
  442. // SockRequestRaw executes a socket request on a daemon and returns an http
  443. // response and a reader for the output data.
  444. func (d *Daemon) SockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
  445. return sockRequestRawToDaemon(method, endpoint, data, ct, d.sock())
  446. }
  447. // LogFileName returns the path the the daemon's log file
  448. func (d *Daemon) LogFileName() string {
  449. return d.logFile.Name()
  450. }
  451. func (d *Daemon) getIDByName(name string) (string, error) {
  452. return d.inspectFieldWithError(name, "Id")
  453. }
  454. func (d *Daemon) activeContainers() (ids []string) {
  455. out, _ := d.Cmd("ps", "-q")
  456. for _, id := range strings.Split(out, "\n") {
  457. if id = strings.TrimSpace(id); id != "" {
  458. ids = append(ids, id)
  459. }
  460. }
  461. return
  462. }
  463. func (d *Daemon) inspectFilter(name, filter string) (string, error) {
  464. format := fmt.Sprintf("{{%s}}", filter)
  465. out, err := d.Cmd("inspect", "-f", format, name)
  466. if err != nil {
  467. return "", fmt.Errorf("failed to inspect %s: %s", name, out)
  468. }
  469. return strings.TrimSpace(out), nil
  470. }
  471. func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
  472. return d.inspectFilter(name, fmt.Sprintf(".%s", field))
  473. }
  474. func (d *Daemon) findContainerIP(id string) string {
  475. out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id)
  476. if err != nil {
  477. d.c.Log(err)
  478. }
  479. return strings.Trim(out, " \r\n'")
  480. }
  481. func (d *Daemon) buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, int, error) {
  482. buildCmd := buildImageCmdWithHost(name, dockerfile, d.sock(), useCache, buildFlags...)
  483. return runCommandWithOutput(buildCmd)
  484. }
  485. func (d *Daemon) checkActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) {
  486. out, err := d.Cmd("ps", "-q")
  487. c.Assert(err, checker.IsNil)
  488. if len(strings.TrimSpace(out)) == 0 {
  489. return 0, nil
  490. }
  491. return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
  492. }
  493. func (d *Daemon) reloadConfig() error {
  494. if d.cmd == nil || d.cmd.Process == nil {
  495. return fmt.Errorf("daemon is not running")
  496. }
  497. errCh := make(chan error)
  498. started := make(chan struct{})
  499. go func() {
  500. _, body, err := sockRequestRawToDaemon("GET", "/events", nil, "", d.sock())
  501. close(started)
  502. if err != nil {
  503. errCh <- err
  504. }
  505. defer body.Close()
  506. dec := json.NewDecoder(body)
  507. for {
  508. var e events.Message
  509. if err := dec.Decode(&e); err != nil {
  510. errCh <- err
  511. return
  512. }
  513. if e.Type != events.DaemonEventType {
  514. continue
  515. }
  516. if e.Action != "reload" {
  517. continue
  518. }
  519. close(errCh) // notify that we are done
  520. return
  521. }
  522. }()
  523. <-started
  524. if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
  525. return fmt.Errorf("error signaling daemon reload: %v", err)
  526. }
  527. select {
  528. case err := <-errCh:
  529. if err != nil {
  530. return fmt.Errorf("error waiting for daemon reload event: %v", err)
  531. }
  532. case <-time.After(30 * time.Second):
  533. return fmt.Errorf("timeout waiting for daemon reload event")
  534. }
  535. return nil
  536. }