daemon.go 25 KB

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