docker_cli_events_unix_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. //go:build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "strings"
  10. "testing"
  11. "time"
  12. "unicode"
  13. "github.com/creack/pty"
  14. "github.com/docker/docker/integration-cli/cli"
  15. "github.com/docker/docker/integration-cli/cli/build"
  16. "golang.org/x/sys/unix"
  17. "gotest.tools/v3/assert"
  18. is "gotest.tools/v3/assert/cmp"
  19. "gotest.tools/v3/skip"
  20. )
  21. // #5979
  22. func (s *DockerCLIEventSuite) TestEventsRedirectStdout(c *testing.T) {
  23. since := daemonUnixTime(c)
  24. cli.DockerCmd(c, "run", "busybox", "true")
  25. file, err := os.CreateTemp("", "")
  26. assert.NilError(c, err, "could not create temp file")
  27. defer os.Remove(file.Name())
  28. command := fmt.Sprintf("%s events --since=%s --until=%s > %s", dockerBinary, since, daemonUnixTime(c), file.Name())
  29. _, tty, err := pty.Open()
  30. assert.NilError(c, err, "Could not open pty")
  31. cmd := exec.Command("sh", "-c", command)
  32. cmd.Stdin = tty
  33. cmd.Stdout = tty
  34. cmd.Stderr = tty
  35. assert.NilError(c, cmd.Run(), "run err for command %q", command)
  36. scanner := bufio.NewScanner(file)
  37. for scanner.Scan() {
  38. for _, ch := range scanner.Text() {
  39. assert.Check(c, unicode.IsControl(ch) == false, "found control character %v", []byte(string(ch)))
  40. }
  41. }
  42. assert.NilError(c, scanner.Err(), "Scan err for command %q", command)
  43. }
  44. func (s *DockerCLIEventSuite) TestEventsOOMDisableFalse(c *testing.T) {
  45. testRequires(c, DaemonIsLinux, oomControl, memoryLimitSupport, swapMemorySupport, NotPpc64le)
  46. skip.If(c, GitHubActions, "FIXME: https://github.com/moby/moby/pull/36541")
  47. errChan := make(chan error, 1)
  48. go func() {
  49. defer close(errChan)
  50. out, exitCode, _ := dockerCmdWithError("run", "--name", "oomFalse", "-m", "10MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  51. if expected := 137; exitCode != expected {
  52. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  53. }
  54. }()
  55. select {
  56. case err := <-errChan:
  57. assert.NilError(c, err)
  58. case <-time.After(30 * time.Second):
  59. c.Fatal("Timeout waiting for container to die on OOM")
  60. }
  61. out := cli.DockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", "--until", daemonUnixTime(c)).Stdout()
  62. events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
  63. nEvents := len(events)
  64. assert.Assert(c, nEvents >= 5)
  65. assert.Equal(c, parseEventAction(c, events[nEvents-5]), "create")
  66. assert.Equal(c, parseEventAction(c, events[nEvents-4]), "attach")
  67. assert.Equal(c, parseEventAction(c, events[nEvents-3]), "start")
  68. assert.Equal(c, parseEventAction(c, events[nEvents-2]), "oom")
  69. assert.Equal(c, parseEventAction(c, events[nEvents-1]), "die")
  70. }
  71. func (s *DockerCLIEventSuite) TestEventsOOMDisableTrue(c *testing.T) {
  72. testRequires(c, DaemonIsLinux, oomControl, memoryLimitSupport, swapMemorySupport, NotPpc64le)
  73. skip.If(c, GitHubActions, "FIXME: https://github.com/moby/moby/pull/36541")
  74. errChan := make(chan error, 1)
  75. observer, err := newEventObserver(c)
  76. assert.NilError(c, err)
  77. err = observer.Start()
  78. assert.NilError(c, err)
  79. defer observer.Stop()
  80. go func() {
  81. defer close(errChan)
  82. out, exitCode, _ := dockerCmdWithError("run", "--oom-kill-disable=true", "--name", "oomTrue", "-m", "10MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  83. if expected := 137; exitCode != expected {
  84. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  85. }
  86. }()
  87. cli.WaitRun(c, "oomTrue")
  88. defer dockerCmdWithResult("kill", "oomTrue")
  89. containerID := inspectField(c, "oomTrue", "Id")
  90. testActions := map[string]chan bool{
  91. "oom": make(chan bool),
  92. }
  93. matcher := matchEventLine(containerID, "container", testActions)
  94. processor := processEventMatch(testActions)
  95. go observer.Match(matcher, processor)
  96. select {
  97. case <-time.After(20 * time.Second):
  98. observer.CheckEventError(c, containerID, "oom", matcher)
  99. case <-testActions["oom"]:
  100. // ignore, done
  101. case errRun := <-errChan:
  102. if errRun != nil {
  103. c.Fatalf("%v", errRun)
  104. } else {
  105. c.Fatalf("container should be still running but it's not")
  106. }
  107. }
  108. status := inspectField(c, "oomTrue", "State.Status")
  109. assert.Equal(c, strings.TrimSpace(status), "running", "container should be still running")
  110. }
  111. // #18453
  112. func (s *DockerCLIEventSuite) TestEventsContainerFilterByName(c *testing.T) {
  113. testRequires(c, DaemonIsLinux)
  114. cOut := cli.DockerCmd(c, "run", "--name=foo", "-d", "busybox", "top").Stdout()
  115. c1 := strings.TrimSpace(cOut)
  116. cli.WaitRun(c, "foo")
  117. cOut = cli.DockerCmd(c, "run", "--name=bar", "-d", "busybox", "top").Stdout()
  118. c2 := strings.TrimSpace(cOut)
  119. cli.WaitRun(c, "bar")
  120. out := cli.DockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", daemonUnixTime(c)).Stdout()
  121. assert.Assert(c, strings.Contains(out, c1), out)
  122. assert.Assert(c, !strings.Contains(out, c2), out)
  123. }
  124. // #18453
  125. func (s *DockerCLIEventSuite) TestEventsContainerFilterBeforeCreate(c *testing.T) {
  126. testRequires(c, DaemonIsLinux)
  127. buf := &bytes.Buffer{}
  128. cmd := exec.Command(dockerBinary, "events", "-f", "container=foo", "--since=0")
  129. cmd.Stdout = buf
  130. assert.NilError(c, cmd.Start())
  131. defer cmd.Wait()
  132. defer cmd.Process.Kill()
  133. // Sleep for a second to make sure we are testing the case where events are listened before container starts.
  134. time.Sleep(time.Second)
  135. id := cli.DockerCmd(c, "run", "--name=foo", "-d", "busybox", "top").Stdout()
  136. cID := strings.TrimSpace(id)
  137. for i := 0; ; i++ {
  138. out := buf.String()
  139. if strings.Contains(out, cID) {
  140. break
  141. }
  142. if i > 30 {
  143. c.Fatalf("Missing event of container (foo, %v), got %q", cID, out)
  144. }
  145. time.Sleep(500 * time.Millisecond)
  146. }
  147. }
  148. func (s *DockerCLIEventSuite) TestVolumeEvents(c *testing.T) {
  149. testRequires(c, DaemonIsLinux)
  150. since := daemonUnixTime(c)
  151. // Observe create/mount volume actions
  152. cli.DockerCmd(c, "volume", "create", "test-event-volume-local")
  153. cli.DockerCmd(c, "run", "--name", "test-volume-container", "--volume", "test-event-volume-local:/foo", "-d", "busybox", "true")
  154. // Observe unmount/destroy volume actions
  155. cli.DockerCmd(c, "rm", "-f", "test-volume-container")
  156. cli.DockerCmd(c, "volume", "rm", "test-event-volume-local")
  157. until := daemonUnixTime(c)
  158. out := cli.DockerCmd(c, "events", "--since", since, "--until", until).Stdout()
  159. events := strings.Split(strings.TrimSpace(out), "\n")
  160. assert.Assert(c, len(events) > 3)
  161. volumeEvents := eventActionsByIDAndType(c, events, "test-event-volume-local", "volume")
  162. assert.Equal(c, len(volumeEvents), 4)
  163. assert.Equal(c, volumeEvents[0], "create")
  164. assert.Equal(c, volumeEvents[1], "mount")
  165. assert.Equal(c, volumeEvents[2], "unmount")
  166. assert.Equal(c, volumeEvents[3], "destroy")
  167. }
  168. func (s *DockerCLIEventSuite) TestNetworkEvents(c *testing.T) {
  169. testRequires(c, DaemonIsLinux)
  170. since := daemonUnixTime(c)
  171. // Observe create/connect network actions
  172. cli.DockerCmd(c, "network", "create", "test-event-network-local")
  173. cli.DockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local", "-d", "busybox", "true")
  174. // Observe disconnect/destroy network actions
  175. cli.DockerCmd(c, "rm", "-f", "test-network-container")
  176. cli.DockerCmd(c, "network", "rm", "test-event-network-local")
  177. until := daemonUnixTime(c)
  178. out := cli.DockerCmd(c, "events", "--since", since, "--until", until).Stdout()
  179. events := strings.Split(strings.TrimSpace(out), "\n")
  180. assert.Assert(c, len(events) > 4)
  181. netEvents := eventActionsByIDAndType(c, events, "test-event-network-local", "network")
  182. assert.Equal(c, len(netEvents), 4)
  183. assert.Equal(c, netEvents[0], "create")
  184. assert.Equal(c, netEvents[1], "connect")
  185. assert.Equal(c, netEvents[2], "disconnect")
  186. assert.Equal(c, netEvents[3], "destroy")
  187. }
  188. func (s *DockerCLIEventSuite) TestEventsContainerWithMultiNetwork(c *testing.T) {
  189. testRequires(c, DaemonIsLinux)
  190. // Observe create/connect network actions
  191. cli.DockerCmd(c, "network", "create", "test-event-network-local-1")
  192. cli.DockerCmd(c, "network", "create", "test-event-network-local-2")
  193. cli.DockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local-1", "-td", "busybox", "sh")
  194. cli.WaitRun(c, "test-network-container")
  195. cli.DockerCmd(c, "network", "connect", "test-event-network-local-2", "test-network-container")
  196. since := daemonUnixTime(c)
  197. cli.DockerCmd(c, "stop", "-t", "1", "test-network-container")
  198. until := daemonUnixTime(c)
  199. out := cli.DockerCmd(c, "events", "--since", since, "--until", until, "-f", "type=network").Stdout()
  200. netEvents := strings.Split(strings.TrimSpace(out), "\n")
  201. // received two network disconnect events
  202. assert.Equal(c, len(netEvents), 2)
  203. assert.Assert(c, strings.Contains(netEvents[0], "disconnect"))
  204. assert.Assert(c, strings.Contains(netEvents[1], "disconnect"))
  205. // both networks appeared in the network event output
  206. assert.Assert(c, strings.Contains(out, "test-event-network-local-1"))
  207. assert.Assert(c, strings.Contains(out, "test-event-network-local-2"))
  208. }
  209. func (s *DockerCLIEventSuite) TestEventsStreaming(c *testing.T) {
  210. testRequires(c, DaemonIsLinux)
  211. observer, err := newEventObserver(c)
  212. assert.NilError(c, err)
  213. err = observer.Start()
  214. assert.NilError(c, err)
  215. defer observer.Stop()
  216. out := cli.DockerCmd(c, "run", "-d", "busybox:latest", "true").Stdout()
  217. containerID := strings.TrimSpace(out)
  218. testActions := map[string]chan bool{
  219. "create": make(chan bool, 1),
  220. "start": make(chan bool, 1),
  221. "die": make(chan bool, 1),
  222. "destroy": make(chan bool, 1),
  223. }
  224. matcher := matchEventLine(containerID, "container", testActions)
  225. processor := processEventMatch(testActions)
  226. go observer.Match(matcher, processor)
  227. select {
  228. case <-time.After(5 * time.Second):
  229. observer.CheckEventError(c, containerID, "create", matcher)
  230. case <-testActions["create"]:
  231. // ignore, done
  232. }
  233. select {
  234. case <-time.After(5 * time.Second):
  235. observer.CheckEventError(c, containerID, "start", matcher)
  236. case <-testActions["start"]:
  237. // ignore, done
  238. }
  239. select {
  240. case <-time.After(5 * time.Second):
  241. observer.CheckEventError(c, containerID, "die", matcher)
  242. case <-testActions["die"]:
  243. // ignore, done
  244. }
  245. cli.DockerCmd(c, "rm", containerID)
  246. select {
  247. case <-time.After(5 * time.Second):
  248. observer.CheckEventError(c, containerID, "destroy", matcher)
  249. case <-testActions["destroy"]:
  250. // ignore, done
  251. }
  252. }
  253. func (s *DockerCLIEventSuite) TestEventsImageUntagDelete(c *testing.T) {
  254. testRequires(c, DaemonIsLinux)
  255. observer, err := newEventObserver(c)
  256. assert.NilError(c, err)
  257. err = observer.Start()
  258. assert.NilError(c, err)
  259. defer observer.Stop()
  260. name := "testimageevents"
  261. buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch
  262. MAINTAINER "docker"`))
  263. imageID := getIDByName(c, name)
  264. assert.NilError(c, deleteImages(name))
  265. testActions := map[string]chan bool{
  266. "untag": make(chan bool, 1),
  267. "delete": make(chan bool, 1),
  268. }
  269. matcher := matchEventLine(imageID, "image", testActions)
  270. processor := processEventMatch(testActions)
  271. go observer.Match(matcher, processor)
  272. select {
  273. case <-time.After(10 * time.Second):
  274. observer.CheckEventError(c, imageID, "untag", matcher)
  275. case <-testActions["untag"]:
  276. // ignore, done
  277. }
  278. select {
  279. case <-time.After(10 * time.Second):
  280. observer.CheckEventError(c, imageID, "delete", matcher)
  281. case <-testActions["delete"]:
  282. // ignore, done
  283. }
  284. }
  285. func (s *DockerCLIEventSuite) TestEventsFilterVolumeAndNetworkType(c *testing.T) {
  286. testRequires(c, DaemonIsLinux)
  287. since := daemonUnixTime(c)
  288. cli.DockerCmd(c, "network", "create", "test-event-network-type")
  289. cli.DockerCmd(c, "volume", "create", "test-event-volume-type")
  290. out := cli.DockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", "--since", since, "--until", daemonUnixTime(c)).Stdout()
  291. events := strings.Split(strings.TrimSpace(out), "\n")
  292. assert.Assert(c, len(events) >= 2, out)
  293. networkActions := eventActionsByIDAndType(c, events, "test-event-network-type", "network")
  294. volumeActions := eventActionsByIDAndType(c, events, "test-event-volume-type", "volume")
  295. assert.Equal(c, volumeActions[0], "create")
  296. assert.Equal(c, networkActions[0], "create")
  297. }
  298. func (s *DockerCLIEventSuite) TestEventsFilterVolumeID(c *testing.T) {
  299. testRequires(c, DaemonIsLinux)
  300. since := daemonUnixTime(c)
  301. cli.DockerCmd(c, "volume", "create", "test-event-volume-id")
  302. out := cli.DockerCmd(c, "events", "--filter", "volume=test-event-volume-id", "--since", since, "--until", daemonUnixTime(c)).Stdout()
  303. events := strings.Split(strings.TrimSpace(out), "\n")
  304. assert.Equal(c, len(events), 1)
  305. assert.Equal(c, len(events), 1)
  306. assert.Assert(c, strings.Contains(events[0], "test-event-volume-id"))
  307. assert.Assert(c, strings.Contains(events[0], "driver=local"))
  308. }
  309. func (s *DockerCLIEventSuite) TestEventsFilterNetworkID(c *testing.T) {
  310. testRequires(c, DaemonIsLinux)
  311. since := daemonUnixTime(c)
  312. cli.DockerCmd(c, "network", "create", "test-event-network-local")
  313. out := cli.DockerCmd(c, "events", "--filter", "network=test-event-network-local", "--since", since, "--until", daemonUnixTime(c)).Stdout()
  314. events := strings.Split(strings.TrimSpace(out), "\n")
  315. assert.Equal(c, len(events), 1)
  316. assert.Assert(c, strings.Contains(events[0], "test-event-network-local"))
  317. assert.Assert(c, strings.Contains(events[0], "type=bridge"))
  318. }
  319. func (s *DockerDaemonSuite) TestDaemonEvents(c *testing.T) {
  320. // daemon config file
  321. configFilePath := "test.json"
  322. defer os.Remove(configFilePath)
  323. daemonConfig := `{"labels":["foo=bar"]}`
  324. err := os.WriteFile(configFilePath, []byte(daemonConfig), 0o644)
  325. assert.NilError(c, err)
  326. s.d.Start(c, "--config-file="+configFilePath)
  327. info := s.d.Info(c)
  328. daemonConfig = `{"max-concurrent-downloads":1,"labels":["bar=foo"], "shutdown-timeout": 10}`
  329. err = os.WriteFile(configFilePath, []byte(daemonConfig), 0o644)
  330. assert.NilError(c, err)
  331. assert.NilError(c, s.d.Signal(unix.SIGHUP))
  332. time.Sleep(3 * time.Second)
  333. out, err := s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c))
  334. assert.NilError(c, err)
  335. // only check for values known (daemon ID/name) or explicitly set above,
  336. // otherwise just check for names being present.
  337. expectedSubstrings := []string{
  338. ` daemon reload ` + info.ID + " ",
  339. `(allow-nondistributable-artifacts=[`,
  340. ` debug=true, `,
  341. ` default-ipc-mode=`,
  342. ` default-runtime=`,
  343. ` default-shm-size=`,
  344. ` insecure-registries=[`,
  345. ` labels=["bar=foo"], `,
  346. ` live-restore=`,
  347. ` max-concurrent-downloads=1, `,
  348. ` max-concurrent-uploads=5, `,
  349. ` name=` + info.Name,
  350. ` registry-mirrors=[`,
  351. ` runtimes=`,
  352. ` shutdown-timeout=10)`,
  353. }
  354. for _, s := range expectedSubstrings {
  355. assert.Check(c, is.Contains(out, s))
  356. }
  357. }
  358. func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *testing.T) {
  359. // daemon config file
  360. configFilePath := "test.json"
  361. defer os.Remove(configFilePath)
  362. daemonConfig := `{"labels":["foo=bar"]}`
  363. err := os.WriteFile(configFilePath, []byte(daemonConfig), 0o644)
  364. assert.NilError(c, err)
  365. s.d.Start(c, "--config-file="+configFilePath)
  366. info := s.d.Info(c)
  367. assert.NilError(c, s.d.Signal(unix.SIGHUP))
  368. time.Sleep(3 * time.Second)
  369. out, err := s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("daemon=%s", info.ID))
  370. assert.NilError(c, err)
  371. assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", info.ID)))
  372. out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("daemon=%s", info.ID))
  373. assert.NilError(c, err)
  374. assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", info.ID)))
  375. out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "daemon=foo")
  376. assert.NilError(c, err)
  377. assert.Assert(c, !strings.Contains(out, fmt.Sprintf("daemon reload %s", info.ID)))
  378. out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "type=daemon")
  379. assert.NilError(c, err)
  380. assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", info.ID)))
  381. out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "type=container")
  382. assert.NilError(c, err)
  383. assert.Assert(c, !strings.Contains(out, fmt.Sprintf("daemon reload %s", info.ID)))
  384. }