daemon.go 15 KB

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