docker_cli_events_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "strconv"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/api/types"
  16. eventtypes "github.com/docker/docker/api/types/events"
  17. "github.com/docker/docker/client"
  18. eventstestutils "github.com/docker/docker/daemon/events/testutils"
  19. "github.com/docker/docker/integration-cli/cli"
  20. "github.com/docker/docker/integration-cli/cli/build"
  21. "gotest.tools/assert"
  22. is "gotest.tools/assert/cmp"
  23. "gotest.tools/icmd"
  24. )
  25. func (s *DockerSuite) TestEventsTimestampFormats(c *testing.T) {
  26. name := "events-time-format-test"
  27. // Start stopwatch, generate an event
  28. start := daemonTime(c)
  29. time.Sleep(1100 * time.Millisecond) // so that first event occur in different second from since (just for the case)
  30. dockerCmd(c, "run", "--rm", "--name", name, "busybox", "true")
  31. time.Sleep(1100 * time.Millisecond) // so that until > since
  32. end := daemonTime(c)
  33. // List of available time formats to --since
  34. unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) }
  35. rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) }
  36. duration := func(t time.Time) string { return time.Since(t).String() }
  37. // --since=$start must contain only the 'untag' event
  38. for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} {
  39. since, until := f(start), f(end)
  40. out, _ := dockerCmd(c, "events", "--since="+since, "--until="+until)
  41. events := strings.Split(out, "\n")
  42. events = events[:len(events)-1]
  43. nEvents := len(events)
  44. assert.Assert(c, nEvents >= 5)
  45. containerEvents := eventActionsByIDAndType(c, events, name, "container")
  46. assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
  47. }
  48. }
  49. func (s *DockerSuite) TestEventsUntag(c *testing.T) {
  50. image := "busybox"
  51. dockerCmd(c, "tag", image, "utest:tag1")
  52. dockerCmd(c, "tag", image, "utest:tag2")
  53. dockerCmd(c, "rmi", "utest:tag1")
  54. dockerCmd(c, "rmi", "utest:tag2")
  55. result := icmd.RunCmd(icmd.Cmd{
  56. Command: []string{dockerBinary, "events", "--since=1"},
  57. Timeout: time.Millisecond * 2500,
  58. })
  59. result.Assert(c, icmd.Expected{Timeout: true})
  60. events := strings.Split(result.Stdout(), "\n")
  61. nEvents := len(events)
  62. // The last element after the split above will be an empty string, so we
  63. // get the two elements before the last, which are the untags we're
  64. // looking for.
  65. for _, v := range events[nEvents-3 : nEvents-1] {
  66. assert.Check(c, strings.Contains(v, "untag"), "event should be untag")
  67. }
  68. }
  69. func (s *DockerSuite) TestEventsContainerEvents(c *testing.T) {
  70. dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
  71. out, _ := dockerCmd(c, "events", "--until", daemonUnixTime(c))
  72. events := strings.Split(out, "\n")
  73. events = events[:len(events)-1]
  74. containerEvents := eventActionsByIDAndType(c, events, "container-events-test", "container")
  75. if len(containerEvents) > 5 {
  76. containerEvents = containerEvents[:5]
  77. }
  78. assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
  79. }
  80. func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) {
  81. since := daemonUnixTime(c)
  82. dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true")
  83. out, _ := dockerCmd(c, "events", "--filter", "container=container-events-test", "--since", since, "--until", daemonUnixTime(c))
  84. events := strings.Split(out, "\n")
  85. nEvents := len(events)
  86. assert.Assert(c, nEvents >= 3)
  87. matchedEvents := 0
  88. for _, event := range events {
  89. matches := eventstestutils.ScanMap(event)
  90. if matches["eventType"] == "container" && matches["action"] == "create" {
  91. matchedEvents++
  92. assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted")
  93. } else if matches["eventType"] == "container" && matches["action"] == "start" {
  94. matchedEvents++
  95. assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted")
  96. }
  97. }
  98. assert.Equal(c, matchedEvents, 2, "missing events for container container-events-test:\n%s", out)
  99. }
  100. func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) {
  101. dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
  102. timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
  103. timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
  104. out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
  105. events := strings.Split(out, "\n")
  106. events = events[:len(events)-1]
  107. nEvents := len(events)
  108. assert.Assert(c, nEvents >= 5)
  109. containerEvents := eventActionsByIDAndType(c, events, "since-epoch-test", "container")
  110. assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out)
  111. }
  112. func (s *DockerSuite) TestEventsImageTag(c *testing.T) {
  113. time.Sleep(1 * time.Second) // because API has seconds granularity
  114. since := daemonUnixTime(c)
  115. image := "testimageevents:tag"
  116. dockerCmd(c, "tag", "busybox", image)
  117. out, _ := dockerCmd(c, "events",
  118. "--since", since, "--until", daemonUnixTime(c))
  119. events := strings.Split(strings.TrimSpace(out), "\n")
  120. assert.Equal(c, len(events), 1, "was expecting 1 event. out=%s", out)
  121. event := strings.TrimSpace(events[0])
  122. matches := eventstestutils.ScanMap(event)
  123. assert.Assert(c, matchEventID(matches, image), "matches: %v\nout:\n%s", matches, out)
  124. assert.Equal(c, matches["action"], "tag")
  125. }
  126. func (s *DockerSuite) TestEventsImagePull(c *testing.T) {
  127. // TODO Windows: Enable this test once pull and reliable image names are available
  128. testRequires(c, DaemonIsLinux)
  129. since := daemonUnixTime(c)
  130. testRequires(c, Network)
  131. dockerCmd(c, "pull", "hello-world")
  132. out, _ := dockerCmd(c, "events",
  133. "--since", since, "--until", daemonUnixTime(c))
  134. events := strings.Split(strings.TrimSpace(out), "\n")
  135. event := strings.TrimSpace(events[len(events)-1])
  136. matches := eventstestutils.ScanMap(event)
  137. assert.Equal(c, matches["id"], "hello-world:latest")
  138. assert.Equal(c, matches["action"], "pull")
  139. }
  140. func (s *DockerSuite) TestEventsImageImport(c *testing.T) {
  141. // TODO Windows CI. This should be portable once export/import are
  142. // more reliable (@swernli)
  143. testRequires(c, DaemonIsLinux)
  144. out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
  145. cleanedContainerID := strings.TrimSpace(out)
  146. since := daemonUnixTime(c)
  147. out, err := RunCommandPipelineWithOutput(
  148. exec.Command(dockerBinary, "export", cleanedContainerID),
  149. exec.Command(dockerBinary, "import", "-"),
  150. )
  151. assert.NilError(c, err, "import failed with output: %q", out)
  152. imageRef := strings.TrimSpace(out)
  153. out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=import")
  154. events := strings.Split(strings.TrimSpace(out), "\n")
  155. assert.Equal(c, len(events), 1)
  156. matches := eventstestutils.ScanMap(events[0])
  157. assert.Equal(c, matches["id"], imageRef, "matches: %v\nout:\n%s\n", matches, out)
  158. assert.Equal(c, matches["action"], "import", "matches: %v\nout:\n%s\n", matches, out)
  159. }
  160. func (s *DockerSuite) TestEventsImageLoad(c *testing.T) {
  161. testRequires(c, DaemonIsLinux)
  162. myImageName := "footest:v1"
  163. dockerCmd(c, "tag", "busybox", myImageName)
  164. since := daemonUnixTime(c)
  165. out, _ := dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
  166. longImageID := strings.TrimSpace(out)
  167. assert.Assert(c, longImageID != "", "Id should not be empty")
  168. dockerCmd(c, "save", "-o", "saveimg.tar", myImageName)
  169. dockerCmd(c, "rmi", myImageName)
  170. out, _ = dockerCmd(c, "images", "-q", myImageName)
  171. noImageID := strings.TrimSpace(out)
  172. assert.Equal(c, noImageID, "", "Should not have any image")
  173. dockerCmd(c, "load", "-i", "saveimg.tar")
  174. result := icmd.RunCommand("rm", "-rf", "saveimg.tar")
  175. result.Assert(c, icmd.Success)
  176. out, _ = dockerCmd(c, "images", "-q", "--no-trunc", myImageName)
  177. imageID := strings.TrimSpace(out)
  178. assert.Equal(c, imageID, longImageID, "Should have same image id as before")
  179. out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load")
  180. events := strings.Split(strings.TrimSpace(out), "\n")
  181. assert.Equal(c, len(events), 1)
  182. matches := eventstestutils.ScanMap(events[0])
  183. assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out)
  184. assert.Equal(c, matches["action"], "load", "matches: %v\nout:\n%s\n", matches, out)
  185. out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=save")
  186. events = strings.Split(strings.TrimSpace(out), "\n")
  187. assert.Equal(c, len(events), 1)
  188. matches = eventstestutils.ScanMap(events[0])
  189. assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out)
  190. assert.Equal(c, matches["action"], "save", "matches: %v\nout:\n%s\n", matches, out)
  191. }
  192. func (s *DockerSuite) TestEventsPluginOps(c *testing.T) {
  193. testRequires(c, DaemonIsLinux, IsAmd64, Network)
  194. since := daemonUnixTime(c)
  195. dockerCmd(c, "plugin", "install", pNameWithTag, "--grant-all-permissions")
  196. dockerCmd(c, "plugin", "disable", pNameWithTag)
  197. dockerCmd(c, "plugin", "remove", pNameWithTag)
  198. out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c))
  199. events := strings.Split(out, "\n")
  200. events = events[:len(events)-1]
  201. assert.Assert(c, len(events) >= 4)
  202. pluginEvents := eventActionsByIDAndType(c, events, pNameWithTag, "plugin")
  203. assert.Assert(c, is.DeepEqual(pluginEvents, []string{"pull", "enable", "disable", "remove"}), out)
  204. }
  205. func (s *DockerSuite) TestEventsFilters(c *testing.T) {
  206. since := daemonUnixTime(c)
  207. dockerCmd(c, "run", "--rm", "busybox", "true")
  208. dockerCmd(c, "run", "--rm", "busybox", "true")
  209. out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die")
  210. parseEvents(c, out, "die")
  211. out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die", "--filter", "event=start")
  212. parseEvents(c, out, "die|start")
  213. // make sure we at least got 2 start events
  214. count := strings.Count(out, "start")
  215. assert.Assert(c, count >= 2, "should have had 2 start events but had %d, out: %s", count, out)
  216. }
  217. func (s *DockerSuite) TestEventsFilterImageName(c *testing.T) {
  218. since := daemonUnixTime(c)
  219. out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true")
  220. container1 := strings.TrimSpace(out)
  221. out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true")
  222. container2 := strings.TrimSpace(out)
  223. name := "busybox"
  224. out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name))
  225. events := strings.Split(out, "\n")
  226. events = events[:len(events)-1]
  227. assert.Assert(c, len(events) != 0, "Expected events but found none for the image busybox:latest")
  228. count1 := 0
  229. count2 := 0
  230. for _, e := range events {
  231. if strings.Contains(e, container1) {
  232. count1++
  233. } else if strings.Contains(e, container2) {
  234. count2++
  235. }
  236. }
  237. assert.Assert(c, count1 != 0, "Expected event from container but got %d from %s", count1, container1)
  238. assert.Assert(c, count2 != 0, "Expected event from container but got %d from %s", count2, container2)
  239. }
  240. func (s *DockerSuite) TestEventsFilterLabels(c *testing.T) {
  241. since := strconv.FormatUint(uint64(daemonTime(c).Unix()), 10)
  242. label := "io.docker.testing=foo"
  243. out, exit := dockerCmd(c, "create", "-l", label, "busybox")
  244. assert.Equal(c, exit, 0)
  245. container1 := strings.TrimSpace(out)
  246. out, exit = dockerCmd(c, "create", "busybox")
  247. assert.Equal(c, exit, 0)
  248. container2 := strings.TrimSpace(out)
  249. // fetch events with `--until`, so that the client detaches after a second
  250. // instead of staying attached, waiting for more events to arrive.
  251. out, _ = dockerCmd(
  252. c,
  253. "events",
  254. "--since", since,
  255. "--until", strconv.FormatUint(uint64(daemonTime(c).Add(time.Second).Unix()), 10),
  256. "--filter", "label="+label,
  257. )
  258. events := strings.Split(strings.TrimSpace(out), "\n")
  259. assert.Assert(c, len(events) > 0)
  260. var found bool
  261. for _, e := range events {
  262. if strings.Contains(e, container1) {
  263. found = true
  264. }
  265. assert.Assert(c, !strings.Contains(e, container2))
  266. }
  267. assert.Assert(c, found)
  268. }
  269. func (s *DockerSuite) TestEventsFilterImageLabels(c *testing.T) {
  270. since := daemonUnixTime(c)
  271. name := "labelfiltertest"
  272. label := "io.docker.testing=image"
  273. // Build a test image.
  274. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
  275. FROM busybox:latest
  276. LABEL %s`, label)))
  277. dockerCmd(c, "tag", name, "labelfiltertest:tag1")
  278. dockerCmd(c, "tag", name, "labelfiltertest:tag2")
  279. dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3")
  280. out, _ := dockerCmd(
  281. c,
  282. "events",
  283. "--since", since,
  284. "--until", daemonUnixTime(c),
  285. "--filter", fmt.Sprintf("label=%s", label),
  286. "--filter", "type=image")
  287. events := strings.Split(strings.TrimSpace(out), "\n")
  288. // 2 events from the "docker tag" command, another one is from "docker build"
  289. assert.Equal(c, len(events), 3, "Events == %s", events)
  290. for _, e := range events {
  291. assert.Check(c, strings.Contains(e, "labelfiltertest"))
  292. }
  293. }
  294. func (s *DockerSuite) TestEventsFilterContainer(c *testing.T) {
  295. since := daemonUnixTime(c)
  296. nameID := make(map[string]string)
  297. for _, name := range []string{"container_1", "container_2"} {
  298. dockerCmd(c, "run", "--name", name, "busybox", "true")
  299. id := inspectField(c, name, "Id")
  300. nameID[name] = id
  301. }
  302. until := daemonUnixTime(c)
  303. checkEvents := func(id string, events []string) error {
  304. if len(events) != 4 { // create, attach, start, die
  305. return fmt.Errorf("expected 4 events, got %v", events)
  306. }
  307. for _, event := range events {
  308. matches := eventstestutils.ScanMap(event)
  309. if !matchEventID(matches, id) {
  310. return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, matches["id"])
  311. }
  312. }
  313. return nil
  314. }
  315. for name, ID := range nameID {
  316. // filter by names
  317. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name)
  318. events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
  319. assert.NilError(c, checkEvents(ID, events))
  320. // filter by ID's
  321. out, _ = dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID)
  322. events = strings.Split(strings.TrimSuffix(out, "\n"), "\n")
  323. assert.NilError(c, checkEvents(ID, events))
  324. }
  325. }
  326. func (s *DockerSuite) TestEventsCommit(c *testing.T) {
  327. // Problematic on Windows as cannot commit a running container
  328. testRequires(c, DaemonIsLinux)
  329. out := runSleepingContainer(c)
  330. cID := strings.TrimSpace(out)
  331. cli.WaitRun(c, cID)
  332. cli.DockerCmd(c, "commit", "-m", "test", cID)
  333. cli.DockerCmd(c, "stop", cID)
  334. cli.WaitExited(c, cID, 5*time.Second)
  335. until := daemonUnixTime(c)
  336. out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined()
  337. assert.Assert(c, strings.Contains(out, "commit"), "Missing 'commit' log event")
  338. }
  339. func (s *DockerSuite) TestEventsCopy(c *testing.T) {
  340. // Build a test image.
  341. buildImageSuccessfully(c, "cpimg", build.WithDockerfile(`
  342. FROM busybox
  343. RUN echo HI > /file`))
  344. id := getIDByName(c, "cpimg")
  345. // Create an empty test file.
  346. tempFile, err := ioutil.TempFile("", "test-events-copy-")
  347. assert.NilError(c, err)
  348. defer os.Remove(tempFile.Name())
  349. assert.NilError(c, tempFile.Close())
  350. dockerCmd(c, "create", "--name=cptest", id)
  351. dockerCmd(c, "cp", "cptest:/file", tempFile.Name())
  352. until := daemonUnixTime(c)
  353. out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until)
  354. assert.Assert(c, strings.Contains(out, "archive-path"), "Missing 'archive-path' log event")
  355. dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy")
  356. until = daemonUnixTime(c)
  357. out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until)
  358. assert.Assert(c, strings.Contains(out, "extract-to-dir"), "Missing 'extract-to-dir' log event")
  359. }
  360. func (s *DockerSuite) TestEventsResize(c *testing.T) {
  361. out := runSleepingContainer(c, "-d")
  362. cID := strings.TrimSpace(out)
  363. assert.NilError(c, waitRun(cID))
  364. cli, err := client.NewClientWithOpts(client.FromEnv)
  365. assert.NilError(c, err)
  366. defer cli.Close()
  367. options := types.ResizeOptions{
  368. Height: 80,
  369. Width: 24,
  370. }
  371. err = cli.ContainerResize(context.Background(), cID, options)
  372. assert.NilError(c, err)
  373. dockerCmd(c, "stop", cID)
  374. until := daemonUnixTime(c)
  375. out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
  376. assert.Assert(c, strings.Contains(out, "resize"), "Missing 'resize' log event")
  377. }
  378. func (s *DockerSuite) TestEventsAttach(c *testing.T) {
  379. // TODO Windows CI: Figure out why this test fails intermittently (TP5).
  380. testRequires(c, DaemonIsLinux)
  381. out := cli.DockerCmd(c, "run", "-di", "busybox", "cat").Combined()
  382. cID := strings.TrimSpace(out)
  383. cli.WaitRun(c, cID)
  384. cmd := exec.Command(dockerBinary, "attach", cID)
  385. stdin, err := cmd.StdinPipe()
  386. assert.NilError(c, err)
  387. defer stdin.Close()
  388. stdout, err := cmd.StdoutPipe()
  389. assert.NilError(c, err)
  390. defer stdout.Close()
  391. assert.NilError(c, cmd.Start())
  392. defer func() {
  393. cmd.Process.Kill()
  394. cmd.Wait()
  395. }()
  396. // Make sure we're done attaching by writing/reading some stuff
  397. _, err = stdin.Write([]byte("hello\n"))
  398. assert.NilError(c, err)
  399. out, err = bufio.NewReader(stdout).ReadString('\n')
  400. assert.NilError(c, err)
  401. assert.Equal(c, strings.TrimSpace(out), "hello")
  402. assert.NilError(c, stdin.Close())
  403. cli.DockerCmd(c, "kill", cID)
  404. cli.WaitExited(c, cID, 5*time.Second)
  405. until := daemonUnixTime(c)
  406. out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined()
  407. assert.Assert(c, strings.Contains(out, "attach"), "Missing 'attach' log event")
  408. }
  409. func (s *DockerSuite) TestEventsRename(c *testing.T) {
  410. out, _ := dockerCmd(c, "run", "--name", "oldName", "busybox", "true")
  411. cID := strings.TrimSpace(out)
  412. dockerCmd(c, "rename", "oldName", "newName")
  413. until := daemonUnixTime(c)
  414. // filter by the container id because the name in the event will be the new name.
  415. out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until", until)
  416. assert.Assert(c, strings.Contains(out, "rename"), "Missing 'rename' log event")
  417. }
  418. func (s *DockerSuite) TestEventsTop(c *testing.T) {
  419. // Problematic on Windows as Windows does not support top
  420. testRequires(c, DaemonIsLinux)
  421. out := runSleepingContainer(c, "-d")
  422. cID := strings.TrimSpace(out)
  423. assert.NilError(c, waitRun(cID))
  424. dockerCmd(c, "top", cID)
  425. dockerCmd(c, "stop", cID)
  426. until := daemonUnixTime(c)
  427. out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until)
  428. assert.Assert(c, strings.Contains(out, "top"), "Missing 'top' log event")
  429. }
  430. // #14316
  431. func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *testing.T) {
  432. // Problematic to port for Windows CI during TP5 timeframe until
  433. // supporting push
  434. testRequires(c, DaemonIsLinux)
  435. testRequires(c, Network)
  436. repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL)
  437. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  438. cID := strings.TrimSpace(out)
  439. assert.NilError(c, waitRun(cID))
  440. dockerCmd(c, "commit", cID, repoName)
  441. dockerCmd(c, "stop", cID)
  442. dockerCmd(c, "push", repoName)
  443. until := daemonUnixTime(c)
  444. out, _ = dockerCmd(c, "events", "-f", "image="+repoName, "-f", "event=push", "--until", until)
  445. assert.Assert(c, strings.Contains(out, repoName), "Missing 'push' log event for %s", repoName)
  446. }
  447. func (s *DockerSuite) TestEventsFilterType(c *testing.T) {
  448. // FIXME(vdemeester) fails on e2e run
  449. testRequires(c, testEnv.IsLocalDaemon)
  450. since := daemonUnixTime(c)
  451. name := "labelfiltertest"
  452. label := "io.docker.testing=image"
  453. // Build a test image.
  454. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`
  455. FROM busybox:latest
  456. LABEL %s`, label)))
  457. dockerCmd(c, "tag", name, "labelfiltertest:tag1")
  458. dockerCmd(c, "tag", name, "labelfiltertest:tag2")
  459. dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3")
  460. out, _ := dockerCmd(
  461. c,
  462. "events",
  463. "--since", since,
  464. "--until", daemonUnixTime(c),
  465. "--filter", fmt.Sprintf("label=%s", label),
  466. "--filter", "type=image")
  467. events := strings.Split(strings.TrimSpace(out), "\n")
  468. // 2 events from the "docker tag" command, another one is from "docker build"
  469. assert.Equal(c, len(events), 3, "Events == %s", events)
  470. for _, e := range events {
  471. assert.Check(c, strings.Contains(e, "labelfiltertest"))
  472. }
  473. out, _ = dockerCmd(
  474. c,
  475. "events",
  476. "--since", since,
  477. "--until", daemonUnixTime(c),
  478. "--filter", fmt.Sprintf("label=%s", label),
  479. "--filter", "type=container")
  480. events = strings.Split(strings.TrimSpace(out), "\n")
  481. // Events generated by the container that builds the image
  482. assert.Equal(c, len(events), 2, "Events == %s", events)
  483. out, _ = dockerCmd(
  484. c,
  485. "events",
  486. "--since", since,
  487. "--until", daemonUnixTime(c),
  488. "--filter", "type=network")
  489. events = strings.Split(strings.TrimSpace(out), "\n")
  490. assert.Assert(c, len(events) >= 1, "Events == %s", events)
  491. }
  492. // #25798
  493. func (s *DockerSuite) TestEventsSpecialFiltersWithExecCreate(c *testing.T) {
  494. since := daemonUnixTime(c)
  495. runSleepingContainer(c, "--name", "test-container", "-d")
  496. waitRun("test-container")
  497. dockerCmd(c, "exec", "test-container", "echo", "hello-world")
  498. out, _ := dockerCmd(
  499. c,
  500. "events",
  501. "--since", since,
  502. "--until", daemonUnixTime(c),
  503. "--filter",
  504. "event='exec_create: echo hello-world'",
  505. )
  506. events := strings.Split(strings.TrimSpace(out), "\n")
  507. assert.Equal(c, len(events), 1, out)
  508. out, _ = dockerCmd(
  509. c,
  510. "events",
  511. "--since", since,
  512. "--until", daemonUnixTime(c),
  513. "--filter",
  514. "event=exec_create",
  515. )
  516. assert.Equal(c, len(events), 1, out)
  517. }
  518. func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *testing.T) {
  519. since := daemonUnixTime(c)
  520. dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
  521. waitRun("test-container")
  522. out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c))
  523. events := strings.Split(strings.TrimSpace(out), "\n")
  524. assert.Assert(c, len(events) > 1, out)
  525. }
  526. func (s *DockerSuite) TestEventsContainerRestart(c *testing.T) {
  527. dockerCmd(c, "run", "-d", "--name=testEvent", "--restart=on-failure:3", "busybox", "false")
  528. // wait until test2 is auto removed.
  529. waitTime := 10 * time.Second
  530. if testEnv.OSType == "windows" {
  531. // Windows takes longer...
  532. waitTime = 90 * time.Second
  533. }
  534. err := waitInspect("testEvent", "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTime)
  535. assert.NilError(c, err)
  536. var (
  537. createCount int
  538. startCount int
  539. dieCount int
  540. )
  541. out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container=testEvent")
  542. events := strings.Split(strings.TrimSpace(out), "\n")
  543. nEvents := len(events)
  544. assert.Assert(c, nEvents >= 1)
  545. actions := eventActionsByIDAndType(c, events, "testEvent", "container")
  546. for _, a := range actions {
  547. switch a {
  548. case "create":
  549. createCount++
  550. case "start":
  551. startCount++
  552. case "die":
  553. dieCount++
  554. }
  555. }
  556. assert.Equal(c, createCount, 1, "testEvent should be created 1 times: %v", actions)
  557. assert.Equal(c, startCount, 4, "testEvent should start 4 times: %v", actions)
  558. assert.Equal(c, dieCount, 4, "testEvent should die 4 times: %v", actions)
  559. }
  560. func (s *DockerSuite) TestEventsSinceInTheFuture(c *testing.T) {
  561. dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
  562. waitRun("test-container")
  563. since := daemonTime(c)
  564. until := since.Add(time.Duration(-24) * time.Hour)
  565. out, _, err := dockerCmdWithError("events", "--filter", "image=busybox", "--since", parseEventTime(since), "--until", parseEventTime(until))
  566. assert.ErrorContains(c, err, "")
  567. assert.Assert(c, strings.Contains(out, "cannot be after `until`"))
  568. }
  569. func (s *DockerSuite) TestEventsUntilInThePast(c *testing.T) {
  570. since := daemonUnixTime(c)
  571. dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true")
  572. waitRun("test-container")
  573. until := daemonUnixTime(c)
  574. dockerCmd(c, "run", "--name", "test-container2", "-d", "busybox", "true")
  575. waitRun("test-container2")
  576. out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until)
  577. assert.Assert(c, !strings.Contains(out, "test-container2"))
  578. assert.Assert(c, strings.Contains(out, "test-container"))
  579. }
  580. func (s *DockerSuite) TestEventsFormat(c *testing.T) {
  581. since := daemonUnixTime(c)
  582. dockerCmd(c, "run", "--rm", "busybox", "true")
  583. dockerCmd(c, "run", "--rm", "busybox", "true")
  584. out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--format", "{{json .}}")
  585. dec := json.NewDecoder(strings.NewReader(out))
  586. // make sure we got 2 start events
  587. startCount := 0
  588. for {
  589. var err error
  590. var ev eventtypes.Message
  591. if err = dec.Decode(&ev); err == io.EOF {
  592. break
  593. }
  594. assert.NilError(c, err)
  595. if ev.Status == "start" {
  596. startCount++
  597. }
  598. }
  599. assert.Equal(c, startCount, 2, "should have had 2 start events but had %d, out: %s", startCount, out)
  600. }
  601. func (s *DockerSuite) TestEventsFormatBadFunc(c *testing.T) {
  602. // make sure it fails immediately, without receiving any event
  603. result := dockerCmdWithResult("events", "--format", "{{badFuncString .}}")
  604. result.Assert(c, icmd.Expected{
  605. Error: "exit status 64",
  606. ExitCode: 64,
  607. Err: "Error parsing format: template: :1: function \"badFuncString\" not defined",
  608. })
  609. }
  610. func (s *DockerSuite) TestEventsFormatBadField(c *testing.T) {
  611. // make sure it fails immediately, without receiving any event
  612. result := dockerCmdWithResult("events", "--format", "{{.badFieldString}}")
  613. result.Assert(c, icmd.Expected{
  614. Error: "exit status 64",
  615. ExitCode: 64,
  616. Err: "Error parsing format: template: :1:2: executing \"\" at <.badFieldString>: can't evaluate field badFieldString in type *events.Message",
  617. })
  618. }