daemon.go 23 KB

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