docker_cli_service_logs_test.go 14 KB

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