daemon.go 17 KB

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