docker_cli_service_logs_test.go 14 KB

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