daemon.go 24 KB

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