docker_cli_service_logs_test.go 14 KB

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