daemon.go 23 KB

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