docker_cli_service_logs_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // +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/assert"
  14. "gotest.tools/icmd"
  15. "gotest.tools/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. c.Logf("log for %q: %q", name, out)
  41. assert.Assert(c, strings.Contains(out, message))
  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", string(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 /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 /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. cmd.Stdout = w
  140. cmd.Stderr = w
  141. assert.NilError(c, cmd.Start())
  142. go cmd.Wait()
  143. // Make sure pipe is written to
  144. ch := make(chan *logMessage)
  145. done := make(chan struct{})
  146. go func() {
  147. reader := bufio.NewReader(r)
  148. for {
  149. msg := &logMessage{}
  150. msg.data, _, msg.err = reader.ReadLine()
  151. select {
  152. case ch <- msg:
  153. case <-done:
  154. return
  155. }
  156. }
  157. }()
  158. for i := 0; i < 3; i++ {
  159. msg := <-ch
  160. assert.NilError(c, msg.err)
  161. assert.Assert(c, strings.Contains(string(msg.data), "log test"))
  162. }
  163. close(done)
  164. assert.NilError(c, cmd.Process.Kill())
  165. }
  166. func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *testing.T) {
  167. d := s.AddDaemon(c, true, true)
  168. name := "TestServicelogsTaskLogs"
  169. replicas := 2
  170. result := icmd.RunCmd(d.Command(
  171. // create a service with the name
  172. "service", "create", "--detach", "--no-resolve-image", "--name", name,
  173. // which has some number of replicas
  174. fmt.Sprintf("--replicas=%v", replicas),
  175. // which has this the task id as an environment variable templated in
  176. "--env", "TASK={{.Task.ID}}",
  177. // and runs this command to print exactly 6 logs lines
  178. "busybox", "sh", "-c", "trap 'exit 0' TERM; for line in $(seq 0 5); do echo $TASK log test $line; done; sleep 100000",
  179. ))
  180. result.Assert(c, icmd.Expected{})
  181. // ^^ verify that we get no error
  182. // then verify that we have an id in stdout
  183. id := strings.TrimSpace(result.Stdout())
  184. assert.Assert(c, id != "")
  185. // so, right here, we're basically inspecting by id and returning only
  186. // the ID. if they don't match, the service doesn't exist.
  187. result = icmd.RunCmd(d.Command("service", "inspect", "--format=\"{{.ID}}\"", id))
  188. result.Assert(c, icmd.Expected{Out: id})
  189. // make sure task has been deployed.
  190. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(replicas)), poll.WithTimeout(defaultReconciliationTimeout))
  191. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(6*replicas)), poll.WithTimeout(defaultReconciliationTimeout))
  192. // get the task ids
  193. result = icmd.RunCmd(d.Command("service", "ps", "-q", name))
  194. result.Assert(c, icmd.Expected{})
  195. // make sure we have two tasks
  196. taskIDs := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  197. assert.Equal(c, len(taskIDs), replicas)
  198. for _, taskID := range taskIDs {
  199. c.Logf("checking task %v", taskID)
  200. result := icmd.RunCmd(d.Command("service", "logs", taskID))
  201. result.Assert(c, icmd.Expected{})
  202. lines := strings.Split(strings.TrimSpace(result.Stdout()), "\n")
  203. c.Logf("checking messages for %v", taskID)
  204. for i, line := range lines {
  205. // make sure the message is in order
  206. assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i)))
  207. // make sure it contains the task id
  208. assert.Assert(c, strings.Contains(line, taskID))
  209. }
  210. }
  211. }
  212. func (s *DockerSwarmSuite) TestServiceLogsTTY(c *testing.T) {
  213. d := s.AddDaemon(c, true, true)
  214. name := "TestServiceLogsTTY"
  215. result := icmd.RunCmd(d.Command(
  216. // create a service
  217. "service", "create", "--detach", "--no-resolve-image",
  218. // name it $name
  219. "--name", name,
  220. // use a TTY
  221. "-t",
  222. // busybox image, shell string
  223. "busybox", "sh", "-c",
  224. // echo to stdout and stderr
  225. "echo out; (echo err 1>&2); sleep 10000",
  226. ))
  227. result.Assert(c, icmd.Expected{})
  228. id := strings.TrimSpace(result.Stdout())
  229. assert.Assert(c, id != "")
  230. // so, right here, we're basically inspecting by id and returning only
  231. // the ID. if they don't match, the service doesn't exist.
  232. result = icmd.RunCmd(d.Command("service", "inspect", "--format=\"{{.ID}}\"", id))
  233. result.Assert(c, icmd.Expected{Out: id})
  234. // make sure task has been deployed.
  235. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  236. // and make sure we have all the log lines
  237. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(2)), poll.WithTimeout(defaultReconciliationTimeout))
  238. cmd := d.Command("service", "logs", "--raw", name)
  239. result = icmd.RunCmd(cmd)
  240. // for some reason there is carriage return in the output. i think this is
  241. // just expected.
  242. result.Assert(c, icmd.Expected{Out: "out\r\nerr\r\n"})
  243. }
  244. func (s *DockerSwarmSuite) TestServiceLogsNoHangDeletedContainer(c *testing.T) {
  245. d := s.AddDaemon(c, true, true)
  246. name := "TestServiceLogsNoHangDeletedContainer"
  247. result := icmd.RunCmd(d.Command(
  248. // create a service
  249. "service", "create", "--detach", "--no-resolve-image",
  250. // name it $name
  251. "--name", name,
  252. // busybox image, shell string
  253. "busybox", "sh", "-c",
  254. // echo to stdout and stderr
  255. "while true; do echo line; sleep 2; done",
  256. ))
  257. // confirm that the command succeeded
  258. result.Assert(c, icmd.Expected{})
  259. // get the service id
  260. id := strings.TrimSpace(result.Stdout())
  261. assert.Assert(c, id != "")
  262. // make sure task has been deployed.
  263. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  264. // and make sure we have all the log lines
  265. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(2)), poll.WithTimeout(defaultReconciliationTimeout))
  266. // now find and nuke the container
  267. result = icmd.RunCmd(d.Command("ps", "-q"))
  268. containerID := strings.TrimSpace(result.Stdout())
  269. assert.Assert(c, containerID != "")
  270. result = icmd.RunCmd(d.Command("rm", "-f", containerID))
  271. result.Assert(c, icmd.Expected{Out: containerID})
  272. // run logs. use tail 2 to make sure we don't try to get a bunch of logs
  273. // somehow and slow down execution time
  274. cmd := d.Command("service", "logs", "--tail", "2", id)
  275. // start the command and then wait for it to finish with a 3 second timeout
  276. result = icmd.StartCmd(cmd)
  277. result = icmd.WaitOnCmd(3*time.Second, result)
  278. // then, assert that the result matches expected. if the command timed out,
  279. // if the command is timed out, result.Timeout will be true, but the
  280. // Expected defaults to false
  281. result.Assert(c, icmd.Expected{})
  282. }
  283. func (s *DockerSwarmSuite) TestServiceLogsDetails(c *testing.T) {
  284. d := s.AddDaemon(c, true, true)
  285. name := "TestServiceLogsDetails"
  286. result := icmd.RunCmd(d.Command(
  287. // create a service
  288. "service", "create", "--detach", "--no-resolve-image",
  289. // name it $name
  290. "--name", name,
  291. // add an environment variable
  292. "--env", "asdf=test1",
  293. // add a log driver (without explicitly setting a driver, log-opt doesn't work)
  294. "--log-driver", "json-file",
  295. // add a log option to print the environment variable
  296. "--log-opt", "env=asdf",
  297. // busybox image, shell string
  298. "busybox", "sh", "-c",
  299. // make a log line
  300. "trap 'exit 0' TERM; echo LogLine; while true; do sleep 1; done;",
  301. ))
  302. result.Assert(c, icmd.Expected{})
  303. id := strings.TrimSpace(result.Stdout())
  304. assert.Assert(c, id != "")
  305. // make sure task has been deployed
  306. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  307. // and make sure we have all the log lines
  308. poll.WaitOn(c, pollCheck(c, countLogLines(d, name), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  309. // First, test without pretty printing
  310. // call service logs with details. set raw to skip pretty printing
  311. result = icmd.RunCmd(d.Command("service", "logs", "--raw", "--details", name))
  312. // in this case, we should get details and we should get log message, but
  313. // there will also be context as details (which will fall after the detail
  314. // we inserted in alphabetical order
  315. result.Assert(c, icmd.Expected{Out: "asdf=test1"})
  316. result.Assert(c, icmd.Expected{Out: "LogLine"})
  317. // call service logs with details. this time, don't pass raw
  318. result = icmd.RunCmd(d.Command("service", "logs", "--details", id))
  319. // in this case, we should get details space logmessage as well. the context
  320. // is part of the pretty part of the logline
  321. result.Assert(c, icmd.Expected{Out: "asdf=test1 LogLine"})
  322. }