logtail_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package logtail
  4. import (
  5. "bytes"
  6. "context"
  7. "encoding/json"
  8. "io"
  9. "net/http"
  10. "net/http/httptest"
  11. "strings"
  12. "testing"
  13. "time"
  14. "tailscale.com/tstest"
  15. )
  16. func TestFastShutdown(t *testing.T) {
  17. ctx, cancel := context.WithCancel(context.Background())
  18. cancel()
  19. testServ := httptest.NewServer(http.HandlerFunc(
  20. func(w http.ResponseWriter, r *http.Request) {}))
  21. defer testServ.Close()
  22. l := NewLogger(Config{
  23. BaseURL: testServ.URL,
  24. }, t.Logf)
  25. err := l.Shutdown(ctx)
  26. if err != nil {
  27. t.Error(err)
  28. }
  29. }
  30. // maximum number of times a test will call l.Write()
  31. const logLines = 3
  32. type LogtailTestServer struct {
  33. srv *httptest.Server // Log server
  34. uploaded chan []byte
  35. }
  36. func NewLogtailTestHarness(t *testing.T) (*LogtailTestServer, *Logger) {
  37. ts := LogtailTestServer{}
  38. // max channel backlog = 1 "started" + #logLines x "log line" + 1 "closed"
  39. ts.uploaded = make(chan []byte, 2+logLines)
  40. ts.srv = httptest.NewServer(http.HandlerFunc(
  41. func(w http.ResponseWriter, r *http.Request) {
  42. body, err := io.ReadAll(r.Body)
  43. if err != nil {
  44. t.Error("failed to read HTTP request")
  45. }
  46. ts.uploaded <- body
  47. }))
  48. t.Cleanup(ts.srv.Close)
  49. l := NewLogger(Config{BaseURL: ts.srv.URL}, t.Logf)
  50. // There is always an initial "logtail started" message
  51. body := <-ts.uploaded
  52. if !strings.Contains(string(body), "started") {
  53. t.Errorf("unknown start logging statement: %q", string(body))
  54. }
  55. return &ts, l
  56. }
  57. func TestDrainPendingMessages(t *testing.T) {
  58. ts, l := NewLogtailTestHarness(t)
  59. for i := 0; i < logLines; i++ {
  60. l.Write([]byte("log line"))
  61. }
  62. // all of the "log line" messages usually arrive at once, but poll if needed.
  63. body := ""
  64. for i := 0; i <= logLines; i++ {
  65. body += string(<-ts.uploaded)
  66. count := strings.Count(body, "log line")
  67. if count == logLines {
  68. break
  69. }
  70. // if we never find count == logLines, the test will eventually time out.
  71. }
  72. err := l.Shutdown(context.Background())
  73. if err != nil {
  74. t.Error(err)
  75. }
  76. }
  77. func TestEncodeAndUploadMessages(t *testing.T) {
  78. ts, l := NewLogtailTestHarness(t)
  79. tests := []struct {
  80. name string
  81. log string
  82. want string
  83. }{
  84. {
  85. "plain text",
  86. "log line",
  87. "log line",
  88. },
  89. {
  90. "simple JSON",
  91. `{"text": "log line"}`,
  92. "log line",
  93. },
  94. }
  95. for _, tt := range tests {
  96. io.WriteString(l, tt.log)
  97. body := <-ts.uploaded
  98. data := unmarshalOne(t, body)
  99. got := data["text"]
  100. if got != tt.want {
  101. t.Errorf("%s: got %q; want %q", tt.name, got.(string), tt.want)
  102. }
  103. ltail, ok := data["logtail"]
  104. if ok {
  105. logtailmap := ltail.(map[string]any)
  106. _, ok = logtailmap["client_time"]
  107. if !ok {
  108. t.Errorf("%s: no client_time present", tt.name)
  109. }
  110. } else {
  111. t.Errorf("%s: no logtail map present", tt.name)
  112. }
  113. }
  114. err := l.Shutdown(context.Background())
  115. if err != nil {
  116. t.Error(err)
  117. }
  118. }
  119. func TestEncodeSpecialCases(t *testing.T) {
  120. ts, l := NewLogtailTestHarness(t)
  121. // -------------------------------------------------------------------------
  122. // JSON log message already contains a logtail field.
  123. io.WriteString(l, `{"logtail": "LOGTAIL", "text": "text"}`)
  124. body := <-ts.uploaded
  125. data := unmarshalOne(t, body)
  126. errorHasLogtail, ok := data["error_has_logtail"]
  127. if ok {
  128. if errorHasLogtail != "LOGTAIL" {
  129. t.Errorf("error_has_logtail: got:%q; want:%q",
  130. errorHasLogtail, "LOGTAIL")
  131. }
  132. } else {
  133. t.Errorf("no error_has_logtail field: %v", data)
  134. }
  135. // -------------------------------------------------------------------------
  136. // special characters
  137. io.WriteString(l, "\b\f\n\r\t"+`"\`)
  138. bodytext := string(<-ts.uploaded)
  139. // json.Unmarshal would unescape the characters, we have to look at the encoded text
  140. escaped := strings.Contains(bodytext, `\b\f\n\r\t\"\`)
  141. if !escaped {
  142. t.Errorf("special characters got %s", bodytext)
  143. }
  144. // -------------------------------------------------------------------------
  145. // skipClientTime to omit the logtail metadata
  146. l.skipClientTime = true
  147. io.WriteString(l, "text")
  148. body = <-ts.uploaded
  149. data = unmarshalOne(t, body)
  150. _, ok = data["logtail"]
  151. if ok {
  152. t.Errorf("skipClientTime: unexpected logtail map present: %v", data)
  153. }
  154. // -------------------------------------------------------------------------
  155. // lowMem + long string
  156. l.skipClientTime = false
  157. l.lowMem = true
  158. longStr := strings.Repeat("0", 5120)
  159. io.WriteString(l, longStr)
  160. body = <-ts.uploaded
  161. data = unmarshalOne(t, body)
  162. text, ok := data["text"]
  163. if !ok {
  164. t.Errorf("lowMem: no text %v", data)
  165. }
  166. if n := len(text.(string)); n > 4500 {
  167. t.Errorf("lowMem: got %d chars; want <4500 chars", n)
  168. }
  169. // -------------------------------------------------------------------------
  170. err := l.Shutdown(context.Background())
  171. if err != nil {
  172. t.Error(err)
  173. }
  174. }
  175. var sink []byte
  176. func TestLoggerEncodeTextAllocs(t *testing.T) {
  177. lg := &Logger{timeNow: time.Now}
  178. inBuf := []byte("some text to encode")
  179. procID := uint32(0x24d32ee9)
  180. procSequence := uint64(0x12346)
  181. err := tstest.MinAllocsPerRun(t, 1, func() {
  182. sink = lg.encodeText(inBuf, false, procID, procSequence, 0)
  183. })
  184. if err != nil {
  185. t.Fatal(err)
  186. }
  187. }
  188. func TestLoggerWriteLength(t *testing.T) {
  189. lg := &Logger{
  190. timeNow: time.Now,
  191. buffer: NewMemoryBuffer(1024),
  192. }
  193. inBuf := []byte("some text to encode")
  194. n, err := lg.Write(inBuf)
  195. if err != nil {
  196. t.Error(err)
  197. }
  198. if n != len(inBuf) {
  199. t.Errorf("logger.Write wrote %d bytes, expected %d", n, len(inBuf))
  200. }
  201. }
  202. func TestParseAndRemoveLogLevel(t *testing.T) {
  203. tests := []struct {
  204. log string
  205. wantLevel int
  206. wantLog string
  207. }{
  208. {
  209. "no level",
  210. 0,
  211. "no level",
  212. },
  213. {
  214. "[v1] level 1",
  215. 1,
  216. "level 1",
  217. },
  218. {
  219. "level 1 [v1] ",
  220. 1,
  221. "level 1 ",
  222. },
  223. {
  224. "[v2] level 2",
  225. 2,
  226. "level 2",
  227. },
  228. {
  229. "level [v2] 2",
  230. 2,
  231. "level 2",
  232. },
  233. {
  234. "[v3] no level 3",
  235. 0,
  236. "[v3] no level 3",
  237. },
  238. {
  239. "some ignored text then [v\x00JSON]5{\"foo\":1234}",
  240. 5,
  241. `{"foo":1234}`,
  242. },
  243. }
  244. for _, tt := range tests {
  245. gotLevel, gotLog := parseAndRemoveLogLevel([]byte(tt.log))
  246. if gotLevel != tt.wantLevel {
  247. t.Errorf("parseAndRemoveLogLevel(%q): got:%d; want %d",
  248. tt.log, gotLevel, tt.wantLevel)
  249. }
  250. if string(gotLog) != tt.wantLog {
  251. t.Errorf("parseAndRemoveLogLevel(%q): got:%q; want %q",
  252. tt.log, gotLog, tt.wantLog)
  253. }
  254. }
  255. }
  256. func unmarshalOne(t *testing.T, body []byte) map[string]any {
  257. t.Helper()
  258. var entries []map[string]any
  259. err := json.Unmarshal(body, &entries)
  260. if err != nil {
  261. t.Error(err)
  262. }
  263. if len(entries) != 1 {
  264. t.Fatalf("expected one entry, got %d", len(entries))
  265. }
  266. return entries[0]
  267. }
  268. func TestEncodeTextTruncation(t *testing.T) {
  269. lg := &Logger{timeNow: time.Now, lowMem: true}
  270. in := bytes.Repeat([]byte("a"), 5120)
  271. b := lg.encodeText(in, true, 0, 0, 0)
  272. got := string(b)
  273. want := `{"text": "` + strings.Repeat("a", 4096) + `…+1024"}` + "\n"
  274. if got != want {
  275. t.Errorf("got:\n%qwant:\n%q\n", got, want)
  276. }
  277. }
  278. type simpleMemBuf struct {
  279. Buffer
  280. buf bytes.Buffer
  281. }
  282. func (b *simpleMemBuf) Write(p []byte) (n int, err error) { return b.buf.Write(p) }
  283. func TestEncode(t *testing.T) {
  284. tests := []struct {
  285. in string
  286. want string
  287. }{
  288. {
  289. "normal",
  290. `{"logtail": {"client_time": "1970-01-01T00:02:03.000000456Z","proc_id": 7,"proc_seq": 1}, "text": "normal"}` + "\n",
  291. },
  292. {
  293. "and a [v1] level one",
  294. `{"logtail": {"client_time": "1970-01-01T00:02:03.000000456Z","proc_id": 7,"proc_seq": 1}, "v":1,"text": "and a level one"}` + "\n",
  295. },
  296. {
  297. "[v2] some verbose two",
  298. `{"logtail": {"client_time": "1970-01-01T00:02:03.000000456Z","proc_id": 7,"proc_seq": 1}, "v":2,"text": "some verbose two"}` + "\n",
  299. },
  300. {
  301. "{}",
  302. `{"logtail":{"client_time":"1970-01-01T00:02:03.000000456Z","proc_id":7,"proc_seq":1}}` + "\n",
  303. },
  304. {
  305. `{"foo":"bar"}`,
  306. `{"foo":"bar","logtail":{"client_time":"1970-01-01T00:02:03.000000456Z","proc_id":7,"proc_seq":1}}` + "\n",
  307. },
  308. {
  309. "foo: [v\x00JSON]0{\"foo\":1}",
  310. "{\"foo\":1,\"logtail\":{\"client_time\":\"1970-01-01T00:02:03.000000456Z\",\"proc_id\":7,\"proc_seq\":1}}\n",
  311. },
  312. {
  313. "foo: [v\x00JSON]2{\"foo\":1}",
  314. "{\"foo\":1,\"logtail\":{\"client_time\":\"1970-01-01T00:02:03.000000456Z\",\"proc_id\":7,\"proc_seq\":1},\"v\":2}\n",
  315. },
  316. }
  317. for _, tt := range tests {
  318. buf := new(simpleMemBuf)
  319. lg := &Logger{
  320. timeNow: func() time.Time { return time.Unix(123, 456).UTC() },
  321. buffer: buf,
  322. procID: 7,
  323. procSequence: 1,
  324. }
  325. io.WriteString(lg, tt.in)
  326. got := buf.buf.String()
  327. if got != tt.want {
  328. t.Errorf("for %q,\n got: %#q\nwant: %#q\n", tt.in, got, tt.want)
  329. }
  330. if err := json.Compact(new(bytes.Buffer), buf.buf.Bytes()); err != nil {
  331. t.Errorf("invalid output JSON for %q: %s", tt.in, got)
  332. }
  333. }
  334. }