daemon.go 27 KB

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