daemon.go 15 KB

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