docker_cli_service_logs_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. //go:build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "os/exec"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/docker/docker/integration-cli/checker"
  12. "github.com/docker/docker/integration-cli/daemon"
  13. "github.com/docker/docker/testutil"
  14. "gotest.tools/v3/assert"
  15. "gotest.tools/v3/icmd"
  16. "gotest.tools/v3/poll"
  17. )
  18. type logMessage struct {
  19. err error
  20. data []byte
  21. }
  22. func (s *DockerSwarmSuite) TestServiceLogs(c *testing.T) {
  23. ctx := testutil.GetContext(c)
  24. d := s.AddDaemon(ctx, c, true, true)
  25. // we have multiple services here for detecting the goroutine issue #28915
  26. services := map[string]string{
  27. "TestServiceLogs1": "hello1",
  28. "TestServiceLogs2": "hello2",
  29. }
  30. for name, message := range services {
  31. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox",
  32. "sh", "-c", fmt.Sprintf("echo %s; exec tail -f /dev/null", message))
  33. assert.NilError(c, err)
  34. assert.Assert(c, strings.TrimSpace(out) != "")
  35. }
  36. // make sure task has been deployed.
  37. poll.WaitOn(c, pollCheck(c,
  38. d.CheckRunningTaskImages(ctx), checker.DeepEquals(map[string]int{"busybox:latest": len(services)})), poll.WithTimeout(defaultReconciliationTimeout))
  39. for name, message := range services {
  40. out, err := d.Cmd("service", "logs", name)
  41. assert.NilError(c, err)
  42. assert.Assert(c, strings.Contains(out, message), "log for %q: %q", name, out)
  43. }
  44. }
  45. // countLogLines returns a closure that can be used with poll.WaitOn() to
  46. // verify that a minimum number of expected container log messages have been
  47. // output.
  48. func countLogLines(d *daemon.Daemon, name string) func(*testing.T) (interface{}, string) {
  49. return func(c *testing.T) (interface{}, string) {
  50. result := icmd.RunCmd(d.Command("service", "logs", "-t", "--raw", name))
  51. result.Assert(c, icmd.Expected{})
  52. // if this returns an emptystring, trying to split it later will return
  53. // an array containing emptystring. a valid log line will NEVER be
  54. // emptystring because we ask for the timestamp.
  55. if result.Stdout() == "" {
  56. return 0, "Empty stdout"
  57. }
  58. lines := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  59. return len(lines), fmt.Sprintf("output, %q", result.Stdout())
  60. }
  61. }
  62. func (s *DockerSwarmSuite) TestServiceLogsCompleteness(c *testing.T) {
  63. ctx := testutil.GetContext(c)
  64. d := s.AddDaemon(ctx, c, true, true)
  65. name := "TestServiceLogsCompleteness"
  66. // make a service that prints 6 lines
  67. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for line in $(seq 0 5); do echo log test $line; done; exec tail -f /dev/null")
  68. assert.NilError(c, err)
  69. assert.Assert(c, strings.TrimSpace(out) != "")
  70. // make sure task has been deployed.
  71. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  72. // and make sure we have all the log lines
  73. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(6)), poll.WithTimeout(defaultReconciliationTimeout))
  74. out, err = d.Cmd("service", "logs", name)
  75. assert.NilError(c, err)
  76. lines := strings.Split(strings.TrimSpace(out), "\n")
  77. // i have heard anecdotal reports that logs may come back from the engine
  78. // mis-ordered. if this tests fails, consider the possibility that that
  79. // might be occurring
  80. for i, line := range lines {
  81. assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i)))
  82. }
  83. }
  84. func (s *DockerSwarmSuite) TestServiceLogsTail(c *testing.T) {
  85. ctx := testutil.GetContext(c)
  86. d := s.AddDaemon(ctx, c, true, true)
  87. name := "TestServiceLogsTail"
  88. // make a service that prints 6 lines
  89. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for line in $(seq 1 6); do echo log test $line; done; sleep 100000")
  90. assert.NilError(c, err)
  91. assert.Assert(c, strings.TrimSpace(out) != "")
  92. // make sure task has been deployed.
  93. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  94. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(6)), poll.WithTimeout(defaultReconciliationTimeout))
  95. out, err = d.Cmd("service", "logs", "--tail=2", name)
  96. assert.NilError(c, err)
  97. lines := strings.Split(strings.TrimSpace(out), "\n")
  98. for i, line := range lines {
  99. // doing i+5 is hacky but not too fragile, it's good enough. if it flakes something else is wrong
  100. assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i+5)))
  101. }
  102. }
  103. func (s *DockerSwarmSuite) TestServiceLogsSince(c *testing.T) {
  104. ctx := testutil.GetContext(c)
  105. // See DockerSuite.TestLogsSince, which is where this comes from
  106. d := s.AddDaemon(ctx, c, true, true)
  107. name := "TestServiceLogsSince"
  108. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for i in $(seq 1 3); do usleep 100000; echo log$i; done; exec tail -f /dev/null")
  109. assert.NilError(c, err)
  110. assert.Assert(c, strings.TrimSpace(out) != "")
  111. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  112. // wait a sec for the logs to come in
  113. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(3)), poll.WithTimeout(defaultReconciliationTimeout))
  114. out, err = d.Cmd("service", "logs", "-t", name)
  115. assert.NilError(c, err)
  116. log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
  117. t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // timestamp log2 is written
  118. assert.NilError(c, err)
  119. u := t.Add(50 * time.Millisecond) // add .05s so log1 & log2 don't show up
  120. since := u.Format(time.RFC3339Nano)
  121. out, err = d.Cmd("service", "logs", "-t", fmt.Sprintf("--since=%v", since), name)
  122. assert.NilError(c, err)
  123. unexpected := []string{"log1", "log2"}
  124. expected := []string{"log3"}
  125. for _, v := range unexpected {
  126. assert.Assert(c, !strings.Contains(out, v), "unexpected log message returned, since=%v", u)
  127. }
  128. for _, v := range expected {
  129. assert.Assert(c, strings.Contains(out, v), "expected log message %v, was not present, since=%v", u)
  130. }
  131. }
  132. func (s *DockerSwarmSuite) TestServiceLogsFollow(c *testing.T) {
  133. ctx := testutil.GetContext(c)
  134. d := s.AddDaemon(ctx, c, true, true)
  135. name := "TestServiceLogsFollow"
  136. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "trap 'exit 0' TERM; while true; do echo log test; usleep 100000; done")
  137. assert.NilError(c, err)
  138. assert.Assert(c, strings.TrimSpace(out) != "")
  139. // make sure task has been deployed.
  140. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  141. args := []string{"service", "logs", "-f", name}
  142. cmd := exec.Command(dockerBinary, d.PrependHostArg(args)...)
  143. r, w := io.Pipe()
  144. defer r.Close()
  145. defer w.Close()
  146. cmd.Stdout = w
  147. cmd.Stderr = w
  148. assert.NilError(c, cmd.Start())
  149. go cmd.Wait()
  150. // Make sure pipe is written to
  151. ch := make(chan *logMessage)
  152. done := make(chan struct{})
  153. stop := make(chan struct{})
  154. defer close(stop)
  155. go func() {
  156. reader := bufio.NewReader(r)
  157. for {
  158. msg := &logMessage{}
  159. msg.data, _, msg.err = reader.ReadLine()
  160. select {
  161. case ch <- msg:
  162. case <-stop:
  163. return
  164. case <-done:
  165. return
  166. }
  167. }
  168. }()
  169. for i := 0; i < 3; i++ {
  170. msg := <-ch
  171. assert.NilError(c, msg.err)
  172. assert.Assert(c, strings.Contains(string(msg.data), "log test"))
  173. }
  174. close(done)
  175. assert.NilError(c, cmd.Process.Kill())
  176. }
  177. func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *testing.T) {
  178. ctx := testutil.GetContext(c)
  179. d := s.AddDaemon(ctx, c, true, true)
  180. name := "TestServicelogsTaskLogs"
  181. replicas := 2
  182. result := icmd.RunCmd(d.Command(
  183. // create a service with the name
  184. "service", "create", "--detach", "--no-resolve-image", "--name", name,
  185. // which has some number of replicas
  186. fmt.Sprintf("--replicas=%v", replicas),
  187. // which has this the task id as an environment variable templated in
  188. "--env", "TASK={{.Task.ID}}",
  189. // and runs this command to print exactly 6 logs lines
  190. "busybox", "sh", "-c", "trap 'exit 0' TERM; for line in $(seq 0 5); do echo $TASK log test $line; done; sleep 100000",
  191. ))
  192. result.Assert(c, icmd.Expected{})
  193. // ^^ verify that we get no error
  194. // then verify that we have an id in stdout
  195. id := strings.TrimSpace(result.Stdout())
  196. assert.Assert(c, id != "")
  197. // so, right here, we're basically inspecting by id and returning only
  198. // the ID. if they don't match, the service doesn't exist.
  199. result = icmd.RunCmd(d.Command("service", "inspect", `--format="{{.ID}}"`, id))
  200. result.Assert(c, icmd.Expected{Out: id})
  201. // make sure task has been deployed.
  202. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(replicas)), poll.WithTimeout(defaultReconciliationTimeout))
  203. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(6*replicas)), poll.WithTimeout(defaultReconciliationTimeout))
  204. // get the task ids
  205. result = icmd.RunCmd(d.Command("service", "ps", "-q", name))
  206. result.Assert(c, icmd.Expected{})
  207. // make sure we have two tasks
  208. taskIDs := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  209. assert.Equal(c, len(taskIDs), replicas)
  210. for _, taskID := range taskIDs {
  211. c.Logf("checking task %v", taskID)
  212. result := icmd.RunCmd(d.Command("service", "logs", taskID))
  213. result.Assert(c, icmd.Expected{})
  214. lines := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  215. c.Logf("checking messages for %v", taskID)
  216. for i, line := range lines {
  217. // make sure the message is in order
  218. assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i)))
  219. // make sure it contains the task id
  220. assert.Assert(c, strings.Contains(line, taskID))
  221. }
  222. }
  223. }
  224. func (s *DockerSwarmSuite) TestServiceLogsTTY(c *testing.T) {
  225. ctx := testutil.GetContext(c)
  226. d := s.AddDaemon(ctx, c, true, true)
  227. name := "TestServiceLogsTTY"
  228. result := icmd.RunCmd(d.Command(
  229. // create a service
  230. "service", "create", "--detach", "--no-resolve-image",
  231. // name it $name
  232. "--name", name,
  233. // use a TTY
  234. "-t",
  235. // busybox image, shell string
  236. "busybox", "sh", "-c",
  237. // echo to stdout and stderr
  238. "echo out; (echo err 1>&2); sleep 10000",
  239. ))
  240. result.Assert(c, icmd.Expected{})
  241. id := strings.TrimSpace(result.Stdout())
  242. assert.Assert(c, id != "")
  243. // so, right here, we're basically inspecting by id and returning only
  244. // the ID. if they don't match, the service doesn't exist.
  245. result = icmd.RunCmd(d.Command("service", "inspect", `--format="{{.ID}}"`, id))
  246. result.Assert(c, icmd.Expected{Out: id})
  247. // make sure task has been deployed.
  248. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  249. // and make sure we have all the log lines
  250. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(2)), poll.WithTimeout(defaultReconciliationTimeout))
  251. cmd := d.Command("service", "logs", "--raw", name)
  252. result = icmd.RunCmd(cmd)
  253. // for some reason there is carriage return in the output. i think this is
  254. // just expected.
  255. result.Assert(c, icmd.Expected{Out: "out\r\nerr\r\n"})
  256. }
  257. func (s *DockerSwarmSuite) TestServiceLogsNoHangDeletedContainer(c *testing.T) {
  258. ctx := testutil.GetContext(c)
  259. d := s.AddDaemon(ctx, c, true, true)
  260. name := "TestServiceLogsNoHangDeletedContainer"
  261. result := icmd.RunCmd(d.Command(
  262. // create a service
  263. "service", "create", "--detach", "--no-resolve-image",
  264. // name it $name
  265. "--name", name,
  266. // busybox image, shell string
  267. "busybox", "sh", "-c",
  268. // echo to stdout and stderr
  269. "while true; do echo line; sleep 2; done",
  270. ))
  271. // confirm that the command succeeded
  272. result.Assert(c, icmd.Expected{})
  273. // get the service id
  274. id := strings.TrimSpace(result.Stdout())
  275. assert.Assert(c, id != "")
  276. // make sure task has been deployed.
  277. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  278. // and make sure we have all the log lines
  279. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(2)), poll.WithTimeout(defaultReconciliationTimeout))
  280. // now find and nuke the container
  281. result = icmd.RunCmd(d.Command("ps", "-q"))
  282. containerID := strings.TrimSpace(result.Stdout())
  283. assert.Assert(c, containerID != "")
  284. result = icmd.RunCmd(d.Command("rm", "-f", containerID))
  285. result.Assert(c, icmd.Expected{Out: containerID})
  286. // run logs. use tail 2 to make sure we don't try to get a bunch of logs
  287. // somehow and slow down execution time
  288. cmd := d.Command("service", "logs", "--tail", "2", id)
  289. // start the command and then wait for it to finish with a 3 second timeout
  290. result = icmd.StartCmd(cmd)
  291. result = icmd.WaitOnCmd(3*time.Second, result)
  292. // then, assert that the result matches expected. if the command timed out,
  293. // if the command is timed out, result.Timeout will be true, but the
  294. // Expected defaults to false
  295. result.Assert(c, icmd.Expected{})
  296. }
  297. func (s *DockerSwarmSuite) TestServiceLogsDetails(c *testing.T) {
  298. ctx := testutil.GetContext(c)
  299. d := s.AddDaemon(ctx, c, true, true)
  300. name := "TestServiceLogsDetails"
  301. result := icmd.RunCmd(d.Command(
  302. // create a service
  303. "service", "create", "--detach", "--no-resolve-image",
  304. // name it $name
  305. "--name", name,
  306. // add an environment variable
  307. "--env", "asdf=test1",
  308. // add a log driver (without explicitly setting a driver, log-opt doesn't work)
  309. "--log-driver", "json-file",
  310. // add a log option to print the environment variable
  311. "--log-opt", "env=asdf",
  312. // busybox image, shell string
  313. "busybox", "sh", "-c",
  314. // make a log line
  315. "trap 'exit 0' TERM; echo LogLine; while true; do sleep 1; done;",
  316. ))
  317. result.Assert(c, icmd.Expected{})
  318. id := strings.TrimSpace(result.Stdout())
  319. assert.Assert(c, id != "")
  320. // make sure task has been deployed
  321. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount(ctx), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  322. // and make sure we have all the log lines
  323. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  324. // First, test without pretty printing
  325. // call service logs with details. set raw to skip pretty printing
  326. result = icmd.RunCmd(d.Command("service", "logs", "--raw", "--details", name))
  327. // in this case, we should get details and we should get log message, but
  328. // there will also be context as details (which will fall after the detail
  329. // we inserted in alphabetical order
  330. result.Assert(c, icmd.Expected{Out: "asdf=test1"})
  331. result.Assert(c, icmd.Expected{Out: "LogLine"})
  332. // call service logs with details. this time, don't pass raw
  333. result = icmd.RunCmd(d.Command("service", "logs", "--details", id))
  334. // in this case, we should get details space logmessage as well. the context
  335. // is part of the pretty part of the logline
  336. result.Assert(c, icmd.Expected{Out: "asdf=test1 LogLine"})
  337. }