daemon.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. package daemon // import "github.com/docker/docker/internal/test/daemon"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/events"
  16. "github.com/docker/docker/client"
  17. "github.com/docker/docker/internal/test"
  18. "github.com/docker/docker/internal/test/request"
  19. "github.com/docker/docker/opts"
  20. "github.com/docker/docker/pkg/ioutils"
  21. "github.com/docker/docker/pkg/stringid"
  22. "github.com/docker/go-connections/sockets"
  23. "github.com/docker/go-connections/tlsconfig"
  24. "github.com/pkg/errors"
  25. "gotest.tools/assert"
  26. )
  27. type testingT interface {
  28. assert.TestingT
  29. logT
  30. Fatalf(string, ...interface{})
  31. }
  32. type namer interface {
  33. Name() string
  34. }
  35. type testNamer interface {
  36. TestName() string
  37. }
  38. type logT interface {
  39. Logf(string, ...interface{})
  40. }
  41. const defaultDockerdBinary = "dockerd"
  42. const containerdSocket = "/var/run/docker/containerd/containerd.sock"
  43. var errDaemonNotStarted = errors.New("daemon not started")
  44. // SockRoot holds the path of the default docker integration daemon socket
  45. var SockRoot = filepath.Join(os.TempDir(), "docker-integration")
  46. type clientConfig struct {
  47. transport *http.Transport
  48. scheme string
  49. addr string
  50. }
  51. // Daemon represents a Docker daemon for the testing framework
  52. type Daemon struct {
  53. GlobalFlags []string
  54. Root string
  55. Folder string
  56. Wait chan error
  57. UseDefaultHost bool
  58. UseDefaultTLSHost bool
  59. id string
  60. logFile *os.File
  61. cmd *exec.Cmd
  62. storageDriver string
  63. userlandProxy bool
  64. execRoot string
  65. experimental bool
  66. init bool
  67. dockerdBinary string
  68. log logT
  69. // swarm related field
  70. swarmListenAddr string
  71. SwarmPort int // FIXME(vdemeester) should probably not be exported
  72. DefaultAddrPool []string
  73. SubnetSize uint32
  74. DataPathPort uint32
  75. // cached information
  76. CachedInfo types.Info
  77. }
  78. // New returns a Daemon instance to be used for testing.
  79. // This will create a directory such as d123456789 in the folder specified by $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
  80. // The daemon will not automatically start.
  81. func New(t testingT, ops ...func(*Daemon)) *Daemon {
  82. if ht, ok := t.(test.HelperT); ok {
  83. ht.Helper()
  84. }
  85. dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
  86. if dest == "" {
  87. dest = os.Getenv("DEST")
  88. }
  89. switch v := t.(type) {
  90. case namer:
  91. dest = filepath.Join(dest, v.Name())
  92. case testNamer:
  93. dest = filepath.Join(dest, v.TestName())
  94. }
  95. t.Logf("Creating a new daemon at: %s", dest)
  96. assert.Check(t, dest != "", "Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
  97. storageDriver := os.Getenv("DOCKER_GRAPHDRIVER")
  98. assert.NilError(t, os.MkdirAll(SockRoot, 0700), "could not create daemon socket root")
  99. id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
  100. dir := filepath.Join(dest, id)
  101. daemonFolder, err := filepath.Abs(dir)
  102. assert.NilError(t, err, "Could not make %q an absolute path", dir)
  103. daemonRoot := filepath.Join(daemonFolder, "root")
  104. assert.NilError(t, os.MkdirAll(daemonRoot, 0755), "Could not create daemon root %q", dir)
  105. userlandProxy := true
  106. if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
  107. if val, err := strconv.ParseBool(env); err != nil {
  108. userlandProxy = val
  109. }
  110. }
  111. d := &Daemon{
  112. id: id,
  113. Folder: daemonFolder,
  114. Root: daemonRoot,
  115. storageDriver: storageDriver,
  116. userlandProxy: userlandProxy,
  117. // dxr stands for docker-execroot (shortened for avoiding unix(7) path length limitation)
  118. execRoot: filepath.Join(os.TempDir(), "dxr", id),
  119. dockerdBinary: defaultDockerdBinary,
  120. swarmListenAddr: defaultSwarmListenAddr,
  121. SwarmPort: DefaultSwarmPort,
  122. log: t,
  123. }
  124. for _, op := range ops {
  125. op(d)
  126. }
  127. return d
  128. }
  129. // ContainersNamespace returns the containerd namespace used for containers.
  130. func (d *Daemon) ContainersNamespace() string {
  131. return d.id
  132. }
  133. // RootDir returns the root directory of the daemon.
  134. func (d *Daemon) RootDir() string {
  135. return d.Root
  136. }
  137. // ID returns the generated id of the daemon
  138. func (d *Daemon) ID() string {
  139. return d.id
  140. }
  141. // StorageDriver returns the configured storage driver of the daemon
  142. func (d *Daemon) StorageDriver() string {
  143. return d.storageDriver
  144. }
  145. // Sock returns the socket path of the daemon
  146. func (d *Daemon) Sock() string {
  147. return fmt.Sprintf("unix://" + d.sockPath())
  148. }
  149. func (d *Daemon) sockPath() string {
  150. return filepath.Join(SockRoot, d.id+".sock")
  151. }
  152. // LogFileName returns the path the daemon's log file
  153. func (d *Daemon) LogFileName() string {
  154. return d.logFile.Name()
  155. }
  156. // ReadLogFile returns the content of the daemon log file
  157. func (d *Daemon) ReadLogFile() ([]byte, error) {
  158. return ioutil.ReadFile(d.logFile.Name())
  159. }
  160. // NewClientT creates new client based on daemon's socket path
  161. func (d *Daemon) NewClientT(t assert.TestingT) *client.Client {
  162. if ht, ok := t.(test.HelperT); ok {
  163. ht.Helper()
  164. }
  165. c, err := client.NewClientWithOpts(
  166. client.FromEnv,
  167. client.WithHost(d.Sock()))
  168. assert.NilError(t, err, "cannot create daemon client")
  169. return c
  170. }
  171. // Cleanup cleans the daemon files : exec root (network namespaces, ...), swarmkit files
  172. func (d *Daemon) Cleanup(t testingT) {
  173. if ht, ok := t.(test.HelperT); ok {
  174. ht.Helper()
  175. }
  176. // Cleanup swarmkit wal files if present
  177. cleanupRaftDir(t, d.Root)
  178. cleanupNetworkNamespace(t, d.execRoot)
  179. }
  180. // Start starts the daemon and return once it is ready to receive requests.
  181. func (d *Daemon) Start(t testingT, args ...string) {
  182. if ht, ok := t.(test.HelperT); ok {
  183. ht.Helper()
  184. }
  185. if err := d.StartWithError(args...); err != nil {
  186. t.Fatalf("failed to start daemon with arguments %v : %v", args, err)
  187. }
  188. }
  189. // StartWithError starts the daemon and return once it is ready to receive requests.
  190. // It returns an error in case it couldn't start.
  191. func (d *Daemon) StartWithError(args ...string) error {
  192. logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  193. if err != nil {
  194. return errors.Wrapf(err, "[%s] Could not create %s/docker.log", d.id, d.Folder)
  195. }
  196. return d.StartWithLogFile(logFile, args...)
  197. }
  198. // StartWithLogFile will start the daemon and attach its streams to a given file.
  199. func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
  200. d.handleUserns()
  201. dockerdBinary, err := exec.LookPath(d.dockerdBinary)
  202. if err != nil {
  203. return errors.Wrapf(err, "[%s] could not find docker binary in $PATH", d.id)
  204. }
  205. args := append(d.GlobalFlags,
  206. "--containerd", containerdSocket,
  207. "--data-root", d.Root,
  208. "--exec-root", d.execRoot,
  209. "--pidfile", fmt.Sprintf("%s/docker.pid", d.Folder),
  210. fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
  211. "--containerd-namespace", d.id,
  212. "--containerd-plugins-namespace", d.id+"p",
  213. )
  214. if d.experimental {
  215. args = append(args, "--experimental")
  216. }
  217. if d.init {
  218. args = append(args, "--init")
  219. }
  220. if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
  221. args = append(args, []string{"--host", d.Sock()}...)
  222. }
  223. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  224. args = append(args, []string{"--userns-remap", root}...)
  225. }
  226. // If we don't explicitly set the log-level or debug flag(-D) then
  227. // turn on debug mode
  228. foundLog := false
  229. foundSd := false
  230. for _, a := range providedArgs {
  231. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
  232. foundLog = true
  233. }
  234. if strings.Contains(a, "--storage-driver") {
  235. foundSd = true
  236. }
  237. }
  238. if !foundLog {
  239. args = append(args, "--debug")
  240. }
  241. if d.storageDriver != "" && !foundSd {
  242. args = append(args, "--storage-driver", d.storageDriver)
  243. }
  244. args = append(args, providedArgs...)
  245. d.cmd = exec.Command(dockerdBinary, args...)
  246. d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
  247. d.cmd.Stdout = out
  248. d.cmd.Stderr = out
  249. d.logFile = out
  250. if err := d.cmd.Start(); err != nil {
  251. return errors.Errorf("[%s] could not start daemon container: %v", d.id, err)
  252. }
  253. wait := make(chan error, 1)
  254. go func() {
  255. ret := d.cmd.Wait()
  256. d.log.Logf("[%s] exiting daemon", d.id)
  257. // If we send before logging, we might accidentally log _after_ the test is done.
  258. // As of Go 1.12, this incurs a panic instead of silently being dropped.
  259. wait <- ret
  260. close(wait)
  261. }()
  262. d.Wait = wait
  263. clientConfig, err := d.getClientConfig()
  264. if err != nil {
  265. return err
  266. }
  267. client := &http.Client{
  268. Transport: clientConfig.transport,
  269. }
  270. req, err := http.NewRequest("GET", "/_ping", nil)
  271. if err != nil {
  272. return errors.Wrapf(err, "[%s] could not create new request", d.id)
  273. }
  274. req.URL.Host = clientConfig.addr
  275. req.URL.Scheme = clientConfig.scheme
  276. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  277. defer cancel()
  278. // make sure daemon is ready to receive requests
  279. for i := 0; ; i++ {
  280. d.log.Logf("[%s] waiting for daemon to start", d.id)
  281. select {
  282. case <-ctx.Done():
  283. return errors.Errorf("[%s] Daemon exited and never started: %s", d.id, ctx.Err())
  284. case err := <-d.Wait:
  285. return errors.Errorf("[%s] Daemon exited during startup: %v", d.id, err)
  286. default:
  287. rctx, rcancel := context.WithTimeout(context.TODO(), 2*time.Second)
  288. defer rcancel()
  289. resp, err := client.Do(req.WithContext(rctx))
  290. if err != nil {
  291. if i > 2 { // don't log the first couple, this ends up just being noise
  292. d.log.Logf("[%s] error pinging daemon on start: %v", d.id, err)
  293. }
  294. select {
  295. case <-ctx.Done():
  296. case <-time.After(500 * time.Microsecond):
  297. }
  298. continue
  299. }
  300. resp.Body.Close()
  301. if resp.StatusCode != http.StatusOK {
  302. d.log.Logf("[%s] received status != 200 OK: %s\n", d.id, resp.Status)
  303. }
  304. d.log.Logf("[%s] daemon started\n", d.id)
  305. d.Root, err = d.queryRootDir()
  306. if err != nil {
  307. return errors.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
  308. }
  309. return nil
  310. }
  311. }
  312. }
  313. // StartWithBusybox will first start the daemon with Daemon.Start()
  314. // then save the busybox image from the main daemon and load it into this Daemon instance.
  315. func (d *Daemon) StartWithBusybox(t testingT, arg ...string) {
  316. if ht, ok := t.(test.HelperT); ok {
  317. ht.Helper()
  318. }
  319. d.Start(t, arg...)
  320. d.LoadBusybox(t)
  321. }
  322. // Kill will send a SIGKILL to the daemon
  323. func (d *Daemon) Kill() error {
  324. if d.cmd == nil || d.Wait == nil {
  325. return errDaemonNotStarted
  326. }
  327. defer func() {
  328. d.logFile.Close()
  329. d.cmd = nil
  330. }()
  331. if err := d.cmd.Process.Kill(); err != nil {
  332. return err
  333. }
  334. return os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder))
  335. }
  336. // Pid returns the pid of the daemon
  337. func (d *Daemon) Pid() int {
  338. return d.cmd.Process.Pid
  339. }
  340. // Interrupt stops the daemon by sending it an Interrupt signal
  341. func (d *Daemon) Interrupt() error {
  342. return d.Signal(os.Interrupt)
  343. }
  344. // Signal sends the specified signal to the daemon if running
  345. func (d *Daemon) Signal(signal os.Signal) error {
  346. if d.cmd == nil || d.Wait == nil {
  347. return errDaemonNotStarted
  348. }
  349. return d.cmd.Process.Signal(signal)
  350. }
  351. // DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
  352. // stack to its log file and exit
  353. // This is used primarily for gathering debug information on test timeout
  354. func (d *Daemon) DumpStackAndQuit() {
  355. if d.cmd == nil || d.cmd.Process == nil {
  356. return
  357. }
  358. SignalDaemonDump(d.cmd.Process.Pid)
  359. }
  360. // Stop will send a SIGINT every second and wait for the daemon to stop.
  361. // If it times out, a SIGKILL is sent.
  362. // Stop will not delete the daemon directory. If a purged daemon is needed,
  363. // instantiate a new one with NewDaemon.
  364. // If an error occurs while starting the daemon, the test will fail.
  365. func (d *Daemon) Stop(t testingT) {
  366. if ht, ok := t.(test.HelperT); ok {
  367. ht.Helper()
  368. }
  369. err := d.StopWithError()
  370. if err != nil {
  371. if err != errDaemonNotStarted {
  372. t.Fatalf("Error while stopping the daemon %s : %v", d.id, err)
  373. } else {
  374. t.Logf("Daemon %s is not started", d.id)
  375. }
  376. }
  377. }
  378. // StopWithError will send a SIGINT every second and wait for the daemon to stop.
  379. // If it timeouts, a SIGKILL is sent.
  380. // Stop will not delete the daemon directory. If a purged daemon is needed,
  381. // instantiate a new one with NewDaemon.
  382. func (d *Daemon) StopWithError() (err error) {
  383. if d.cmd == nil || d.Wait == nil {
  384. return errDaemonNotStarted
  385. }
  386. defer func() {
  387. if err == nil {
  388. d.log.Logf("[%s] Daemon stopped", d.id)
  389. } else {
  390. d.log.Logf("[%s] Error when stopping daemon: %v", d.id, err)
  391. }
  392. d.logFile.Close()
  393. d.cmd = nil
  394. }()
  395. i := 1
  396. ticker := time.NewTicker(time.Second)
  397. defer ticker.Stop()
  398. tick := ticker.C
  399. d.log.Logf("[%s] Stopping daemon", d.id)
  400. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  401. if strings.Contains(err.Error(), "os: process already finished") {
  402. return errDaemonNotStarted
  403. }
  404. return errors.Errorf("could not send signal: %v", err)
  405. }
  406. out1:
  407. for {
  408. select {
  409. case err := <-d.Wait:
  410. return err
  411. case <-time.After(20 * time.Second):
  412. // time for stopping jobs and run onShutdown hooks
  413. d.log.Logf("[%s] daemon stop timeout", d.id)
  414. break out1
  415. }
  416. }
  417. out2:
  418. for {
  419. select {
  420. case err := <-d.Wait:
  421. return err
  422. case <-tick:
  423. i++
  424. if i > 5 {
  425. d.log.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  426. break out2
  427. }
  428. d.log.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  429. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  430. return errors.Errorf("could not send signal: %v", err)
  431. }
  432. }
  433. }
  434. if err := d.cmd.Process.Kill(); err != nil {
  435. d.log.Logf("Could not kill daemon: %v", err)
  436. return err
  437. }
  438. d.cmd.Wait()
  439. return os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder))
  440. }
  441. // Restart will restart the daemon by first stopping it and the starting it.
  442. // If an error occurs while starting the daemon, the test will fail.
  443. func (d *Daemon) Restart(t testingT, args ...string) {
  444. if ht, ok := t.(test.HelperT); ok {
  445. ht.Helper()
  446. }
  447. d.Stop(t)
  448. d.Start(t, args...)
  449. }
  450. // RestartWithError will restart the daemon by first stopping it and then starting it.
  451. func (d *Daemon) RestartWithError(arg ...string) error {
  452. if err := d.StopWithError(); err != nil {
  453. return err
  454. }
  455. return d.StartWithError(arg...)
  456. }
  457. func (d *Daemon) handleUserns() {
  458. // in the case of tests running a user namespace-enabled daemon, we have resolved
  459. // d.Root to be the actual final path of the graph dir after the "uid.gid" of
  460. // remapped root is added--we need to subtract it from the path before calling
  461. // start or else we will continue making subdirectories rather than truly restarting
  462. // with the same location/root:
  463. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  464. d.Root = filepath.Dir(d.Root)
  465. }
  466. }
  467. // ReloadConfig asks the daemon to reload its configuration
  468. func (d *Daemon) ReloadConfig() error {
  469. if d.cmd == nil || d.cmd.Process == nil {
  470. return errors.New("daemon is not running")
  471. }
  472. errCh := make(chan error)
  473. started := make(chan struct{})
  474. go func() {
  475. _, body, err := request.Get("/events", request.Host(d.Sock()))
  476. close(started)
  477. if err != nil {
  478. errCh <- err
  479. }
  480. defer body.Close()
  481. dec := json.NewDecoder(body)
  482. for {
  483. var e events.Message
  484. if err := dec.Decode(&e); err != nil {
  485. errCh <- err
  486. return
  487. }
  488. if e.Type != events.DaemonEventType {
  489. continue
  490. }
  491. if e.Action != "reload" {
  492. continue
  493. }
  494. close(errCh) // notify that we are done
  495. return
  496. }
  497. }()
  498. <-started
  499. if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
  500. return errors.Errorf("error signaling daemon reload: %v", err)
  501. }
  502. select {
  503. case err := <-errCh:
  504. if err != nil {
  505. return errors.Errorf("error waiting for daemon reload event: %v", err)
  506. }
  507. case <-time.After(30 * time.Second):
  508. return errors.New("timeout waiting for daemon reload event")
  509. }
  510. return nil
  511. }
  512. // LoadBusybox image into the daemon
  513. func (d *Daemon) LoadBusybox(t assert.TestingT) {
  514. if ht, ok := t.(test.HelperT); ok {
  515. ht.Helper()
  516. }
  517. clientHost, err := client.NewClientWithOpts(client.FromEnv)
  518. assert.NilError(t, err, "failed to create client")
  519. defer clientHost.Close()
  520. ctx := context.Background()
  521. reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
  522. assert.NilError(t, err, "failed to download busybox")
  523. defer reader.Close()
  524. c := d.NewClientT(t)
  525. defer c.Close()
  526. resp, err := c.ImageLoad(ctx, reader, true)
  527. assert.NilError(t, err, "failed to load busybox")
  528. defer resp.Body.Close()
  529. }
  530. func (d *Daemon) getClientConfig() (*clientConfig, error) {
  531. var (
  532. transport *http.Transport
  533. scheme string
  534. addr string
  535. proto string
  536. )
  537. if d.UseDefaultTLSHost {
  538. option := &tlsconfig.Options{
  539. CAFile: "fixtures/https/ca.pem",
  540. CertFile: "fixtures/https/client-cert.pem",
  541. KeyFile: "fixtures/https/client-key.pem",
  542. }
  543. tlsConfig, err := tlsconfig.Client(*option)
  544. if err != nil {
  545. return nil, err
  546. }
  547. transport = &http.Transport{
  548. TLSClientConfig: tlsConfig,
  549. }
  550. addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
  551. scheme = "https"
  552. proto = "tcp"
  553. } else if d.UseDefaultHost {
  554. addr = opts.DefaultUnixSocket
  555. proto = "unix"
  556. scheme = "http"
  557. transport = &http.Transport{}
  558. } else {
  559. addr = d.sockPath()
  560. proto = "unix"
  561. scheme = "http"
  562. transport = &http.Transport{}
  563. }
  564. if err := sockets.ConfigureTransport(transport, proto, addr); err != nil {
  565. return nil, err
  566. }
  567. transport.DisableKeepAlives = true
  568. if proto == "unix" {
  569. addr = filepath.Base(addr)
  570. }
  571. return &clientConfig{
  572. transport: transport,
  573. scheme: scheme,
  574. addr: addr,
  575. }, nil
  576. }
  577. func (d *Daemon) queryRootDir() (string, error) {
  578. // update daemon root by asking /info endpoint (to support user
  579. // namespaced daemon with root remapped uid.gid directory)
  580. clientConfig, err := d.getClientConfig()
  581. if err != nil {
  582. return "", err
  583. }
  584. c := &http.Client{
  585. Transport: clientConfig.transport,
  586. }
  587. req, err := http.NewRequest("GET", "/info", nil)
  588. if err != nil {
  589. return "", err
  590. }
  591. req.Header.Set("Content-Type", "application/json")
  592. req.URL.Host = clientConfig.addr
  593. req.URL.Scheme = clientConfig.scheme
  594. resp, err := c.Do(req)
  595. if err != nil {
  596. return "", err
  597. }
  598. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  599. return resp.Body.Close()
  600. })
  601. type Info struct {
  602. DockerRootDir string
  603. }
  604. var b []byte
  605. var i Info
  606. b, err = request.ReadBody(body)
  607. if err == nil && resp.StatusCode == http.StatusOK {
  608. // read the docker root dir
  609. if err = json.Unmarshal(b, &i); err == nil {
  610. return i.DockerRootDir, nil
  611. }
  612. }
  613. return "", err
  614. }
  615. // Info returns the info struct for this daemon
  616. func (d *Daemon) Info(t assert.TestingT) types.Info {
  617. if ht, ok := t.(test.HelperT); ok {
  618. ht.Helper()
  619. }
  620. c := d.NewClientT(t)
  621. info, err := c.Info(context.Background())
  622. assert.NilError(t, err)
  623. return info
  624. }
  625. func cleanupRaftDir(t testingT, rootPath string) {
  626. if ht, ok := t.(test.HelperT); ok {
  627. ht.Helper()
  628. }
  629. for _, p := range []string{"wal", "wal-v3-encrypted", "snap-v3-encrypted"} {
  630. dir := filepath.Join(rootPath, "swarm/raft", p)
  631. if err := os.RemoveAll(dir); err != nil {
  632. t.Logf("error removing %v: %v", dir, err)
  633. }
  634. }
  635. }