logtail.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package logtail sends logs to log.tailscale.io.
  4. package logtail
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/rand"
  9. "encoding/binary"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "log"
  14. "net/http"
  15. "os"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "tailscale.com/envknob"
  22. "tailscale.com/logtail/backoff"
  23. "tailscale.com/net/interfaces"
  24. "tailscale.com/net/sockstats"
  25. tslogger "tailscale.com/types/logger"
  26. "tailscale.com/types/logid"
  27. "tailscale.com/util/set"
  28. "tailscale.com/wgengine/monitor"
  29. )
  30. // DefaultHost is the default host name to upload logs to when
  31. // Config.BaseURL isn't provided.
  32. const DefaultHost = "log.tailscale.io"
  33. const defaultFlushDelay = 2 * time.Second
  34. const (
  35. // CollectionNode is the name of a logtail Config.Collection
  36. // for tailscaled (or equivalent: IPNExtension, Android app).
  37. CollectionNode = "tailnode.log.tailscale.io"
  38. )
  39. type Encoder interface {
  40. EncodeAll(src, dst []byte) []byte
  41. Close() error
  42. }
  43. type Config struct {
  44. Collection string // collection name, a domain name
  45. PrivateID logid.PrivateID // private ID for the primary log stream
  46. CopyPrivateID logid.PrivateID // private ID for a log stream that is a superset of this log stream
  47. BaseURL string // if empty defaults to "https://log.tailscale.io"
  48. HTTPC *http.Client // if empty defaults to http.DefaultClient
  49. SkipClientTime bool // if true, client_time is not written to logs
  50. LowMemory bool // if true, logtail minimizes memory use
  51. TimeNow func() time.Time // if set, substitutes uses of time.Now
  52. Stderr io.Writer // if set, logs are sent here instead of os.Stderr
  53. StderrLevel int // max verbosity level to write to stderr; 0 means the non-verbose messages only
  54. Buffer Buffer // temp storage, if nil a MemoryBuffer
  55. NewZstdEncoder func() Encoder // if set, used to compress logs for transmission
  56. // MetricsDelta, if non-nil, is a func that returns an encoding
  57. // delta in clientmetrics to upload alongside existing logs.
  58. // It can return either an empty string (for nothing) or a string
  59. // that's safe to embed in a JSON string literal without further escaping.
  60. MetricsDelta func() string
  61. // FlushDelayFn, if non-nil is a func that returns how long to wait to
  62. // accumulate logs before uploading them. 0 or negative means to upload
  63. // immediately.
  64. //
  65. // If nil, a default value is used. (currently 2 seconds)
  66. FlushDelayFn func() time.Duration
  67. // IncludeProcID, if true, results in an ephemeral process identifier being
  68. // included in logs. The ID is random and not guaranteed to be globally
  69. // unique, but it can be used to distinguish between different instances
  70. // running with same PrivateID.
  71. IncludeProcID bool
  72. // IncludeProcSequence, if true, results in an ephemeral sequence number
  73. // being included in the logs. The sequence number is incremented for each
  74. // log message sent, but is not persisted across process restarts.
  75. IncludeProcSequence bool
  76. }
  77. func NewLogger(cfg Config, logf tslogger.Logf) *Logger {
  78. if cfg.BaseURL == "" {
  79. cfg.BaseURL = "https://" + DefaultHost
  80. }
  81. if cfg.HTTPC == nil {
  82. cfg.HTTPC = http.DefaultClient
  83. }
  84. if cfg.TimeNow == nil {
  85. cfg.TimeNow = time.Now
  86. }
  87. if cfg.Stderr == nil {
  88. cfg.Stderr = os.Stderr
  89. }
  90. if cfg.Buffer == nil {
  91. pendingSize := 256
  92. if cfg.LowMemory {
  93. pendingSize = 64
  94. }
  95. cfg.Buffer = NewMemoryBuffer(pendingSize)
  96. }
  97. var procID uint32
  98. if cfg.IncludeProcID {
  99. keyBytes := make([]byte, 4)
  100. rand.Read(keyBytes)
  101. procID = binary.LittleEndian.Uint32(keyBytes)
  102. if procID == 0 {
  103. // 0 is the empty/off value, assign a different (non-zero) value to
  104. // make sure we still include an ID (actual value does not matter).
  105. procID = 7
  106. }
  107. }
  108. if s := envknob.String("TS_DEBUG_LOGTAIL_FLUSHDELAY"); s != "" {
  109. if delay, err := time.ParseDuration(s); err == nil {
  110. cfg.FlushDelayFn = func() time.Duration { return delay }
  111. } else {
  112. log.Fatalf("invalid TS_DEBUG_LOGTAIL_FLUSHDELAY: %v", err)
  113. }
  114. } else if cfg.FlushDelayFn == nil && envknob.Bool("IN_TS_TEST") {
  115. cfg.FlushDelayFn = func() time.Duration { return 0 }
  116. }
  117. stdLogf := func(f string, a ...any) {
  118. fmt.Fprintf(cfg.Stderr, strings.TrimSuffix(f, "\n")+"\n", a...)
  119. }
  120. var urlSuffix string
  121. if !cfg.CopyPrivateID.IsZero() {
  122. urlSuffix = "?copyId=" + cfg.CopyPrivateID.String()
  123. }
  124. l := &Logger{
  125. privateID: cfg.PrivateID,
  126. stderr: cfg.Stderr,
  127. stderrLevel: int64(cfg.StderrLevel),
  128. httpc: cfg.HTTPC,
  129. url: cfg.BaseURL + "/c/" + cfg.Collection + "/" + cfg.PrivateID.String() + urlSuffix,
  130. lowMem: cfg.LowMemory,
  131. buffer: cfg.Buffer,
  132. skipClientTime: cfg.SkipClientTime,
  133. drainWake: make(chan struct{}, 1),
  134. sentinel: make(chan int32, 16),
  135. flushDelayFn: cfg.FlushDelayFn,
  136. timeNow: cfg.TimeNow,
  137. bo: backoff.NewBackoff("logtail", stdLogf, 30*time.Second),
  138. metricsDelta: cfg.MetricsDelta,
  139. sockstatsLabel: sockstats.LabelLogtailLogger,
  140. procID: procID,
  141. includeProcSequence: cfg.IncludeProcSequence,
  142. shutdownStart: make(chan struct{}),
  143. shutdownDone: make(chan struct{}),
  144. }
  145. if cfg.NewZstdEncoder != nil {
  146. l.zstdEncoder = cfg.NewZstdEncoder()
  147. }
  148. ctx, cancel := context.WithCancel(context.Background())
  149. l.uploadCancel = cancel
  150. go l.uploading(ctx)
  151. l.Write([]byte("logtail started"))
  152. return l
  153. }
  154. // Logger writes logs, splitting them as configured between local
  155. // logging facilities and uploading to a log server.
  156. type Logger struct {
  157. stderr io.Writer
  158. stderrLevel int64 // accessed atomically
  159. httpc *http.Client
  160. url string
  161. lowMem bool
  162. skipClientTime bool
  163. linkMonitor *monitor.Mon
  164. buffer Buffer
  165. drainWake chan struct{} // signal to speed up drain
  166. flushDelayFn func() time.Duration // negative or zero return value to upload aggressively, or >0 to batch at this delay
  167. flushPending atomic.Bool
  168. sentinel chan int32
  169. timeNow func() time.Time
  170. bo *backoff.Backoff
  171. zstdEncoder Encoder
  172. uploadCancel func()
  173. explainedRaw bool
  174. metricsDelta func() string // or nil
  175. privateID logid.PrivateID
  176. httpDoCalls atomic.Int32
  177. sockstatsLabel sockstats.Label
  178. procID uint32
  179. includeProcSequence bool
  180. writeLock sync.Mutex // guards procSequence, flushTimer, buffer.Write calls
  181. procSequence uint64
  182. flushTimer *time.Timer // used when flushDelay is >0
  183. shutdownStartMu sync.Mutex // guards the closing of shutdownStart
  184. shutdownStart chan struct{} // closed when shutdown begins
  185. shutdownDone chan struct{} // closed when shutdown complete
  186. }
  187. // SetVerbosityLevel controls the verbosity level that should be
  188. // written to stderr. 0 is the default (not verbose). Levels 1 or higher
  189. // are increasingly verbose.
  190. func (l *Logger) SetVerbosityLevel(level int) {
  191. atomic.StoreInt64(&l.stderrLevel, int64(level))
  192. }
  193. // SetLinkMonitor sets the optional the link monitor.
  194. //
  195. // It should not be changed concurrently with log writes and should
  196. // only be set once.
  197. func (l *Logger) SetLinkMonitor(lm *monitor.Mon) {
  198. l.linkMonitor = lm
  199. }
  200. // SetSockstatsLabel sets the label used in sockstat logs to identify network traffic from this logger.
  201. func (l *Logger) SetSockstatsLabel(label sockstats.Label) {
  202. l.sockstatsLabel = label
  203. }
  204. // PrivateID returns the logger's private log ID.
  205. //
  206. // It exists for internal use only.
  207. func (l *Logger) PrivateID() logid.PrivateID { return l.privateID }
  208. // Shutdown gracefully shuts down the logger while completing any
  209. // remaining uploads.
  210. //
  211. // It will block, continuing to try and upload unless the passed
  212. // context object interrupts it by being done.
  213. // If the shutdown is interrupted, an error is returned.
  214. func (l *Logger) Shutdown(ctx context.Context) error {
  215. done := make(chan struct{})
  216. go func() {
  217. select {
  218. case <-ctx.Done():
  219. l.uploadCancel()
  220. <-l.shutdownDone
  221. case <-l.shutdownDone:
  222. }
  223. close(done)
  224. }()
  225. l.shutdownStartMu.Lock()
  226. select {
  227. case <-l.shutdownStart:
  228. l.shutdownStartMu.Unlock()
  229. return nil
  230. default:
  231. }
  232. close(l.shutdownStart)
  233. l.shutdownStartMu.Unlock()
  234. io.WriteString(l, "logger closing down\n")
  235. <-done
  236. if l.zstdEncoder != nil {
  237. return l.zstdEncoder.Close()
  238. }
  239. return nil
  240. }
  241. // Close shuts down this logger object, the background log uploader
  242. // process, and any associated goroutines.
  243. //
  244. // Deprecated: use Shutdown
  245. func (l *Logger) Close() {
  246. l.Shutdown(context.Background())
  247. }
  248. // drainBlock is called by drainPending when there are no logs to drain.
  249. //
  250. // In typical operation, every call to the Write method unblocks and triggers a
  251. // buffer.TryReadline, so logs are written with very low latency.
  252. //
  253. // If the caller specified FlushInterface, drainWake is only sent to
  254. // periodically.
  255. func (l *Logger) drainBlock() (shuttingDown bool) {
  256. select {
  257. case <-l.shutdownStart:
  258. return true
  259. case <-l.drainWake:
  260. }
  261. return false
  262. }
  263. // drainPending drains and encodes a batch of logs from the buffer for upload.
  264. // It uses scratch as its initial buffer.
  265. // If no logs are available, drainPending blocks until logs are available.
  266. func (l *Logger) drainPending(scratch []byte) (res []byte) {
  267. buf := bytes.NewBuffer(scratch[:0])
  268. buf.WriteByte('[')
  269. entries := 0
  270. var batchDone bool
  271. const maxLen = 256 << 10
  272. for buf.Len() < maxLen && !batchDone {
  273. b, err := l.buffer.TryReadLine()
  274. if err == io.EOF {
  275. break
  276. } else if err != nil {
  277. b = fmt.Appendf(nil, "reading ringbuffer: %v", err)
  278. batchDone = true
  279. } else if b == nil {
  280. if entries > 0 {
  281. break
  282. }
  283. batchDone = l.drainBlock()
  284. continue
  285. }
  286. if len(b) == 0 {
  287. continue
  288. }
  289. if b[0] != '{' || !json.Valid(b) {
  290. // This is probably a log added to stderr by filch
  291. // outside of the logtail logger. Encode it.
  292. if !l.explainedRaw {
  293. fmt.Fprintf(l.stderr, "RAW-STDERR: ***\n")
  294. fmt.Fprintf(l.stderr, "RAW-STDERR: *** Lines prefixed with RAW-STDERR below bypassed logtail and probably come from a previous run of the program\n")
  295. fmt.Fprintf(l.stderr, "RAW-STDERR: ***\n")
  296. fmt.Fprintf(l.stderr, "RAW-STDERR:\n")
  297. l.explainedRaw = true
  298. }
  299. fmt.Fprintf(l.stderr, "RAW-STDERR: %s", b)
  300. // Do not add a client time, as it could have been
  301. // been written a long time ago. Don't include instance key or ID
  302. // either, since this came from a different instance.
  303. b = l.encodeText(b, true, 0, 0, 0)
  304. }
  305. if entries > 0 {
  306. buf.WriteByte(',')
  307. }
  308. buf.Write(b)
  309. entries++
  310. }
  311. buf.WriteByte(']')
  312. if buf.Len() <= len("[]") {
  313. return nil
  314. }
  315. return buf.Bytes()
  316. }
  317. // This is the goroutine that repeatedly uploads logs in the background.
  318. func (l *Logger) uploading(ctx context.Context) {
  319. defer close(l.shutdownDone)
  320. scratch := make([]byte, 4096) // reusable buffer to write into
  321. for {
  322. body := l.drainPending(scratch)
  323. origlen := -1 // sentinel value: uncompressed
  324. // Don't attempt to compress tiny bodies; not worth the CPU cycles.
  325. if l.zstdEncoder != nil && len(body) > 256 {
  326. zbody := l.zstdEncoder.EncodeAll(body, nil)
  327. // Only send it compressed if the bandwidth savings are sufficient.
  328. // Just the extra headers associated with enabling compression
  329. // are 50 bytes by themselves.
  330. if len(body)-len(zbody) > 64 {
  331. origlen = len(body)
  332. body = zbody
  333. }
  334. }
  335. for len(body) > 0 {
  336. select {
  337. case <-ctx.Done():
  338. return
  339. default:
  340. }
  341. uploaded, err := l.upload(ctx, body, origlen)
  342. if err != nil {
  343. if !l.internetUp() {
  344. fmt.Fprintf(l.stderr, "logtail: internet down; waiting\n")
  345. l.awaitInternetUp(ctx)
  346. continue
  347. }
  348. fmt.Fprintf(l.stderr, "logtail: upload: %v\n", err)
  349. }
  350. l.bo.BackOff(ctx, err)
  351. if uploaded {
  352. break
  353. }
  354. }
  355. select {
  356. case <-l.shutdownStart:
  357. return
  358. default:
  359. }
  360. }
  361. }
  362. func (l *Logger) internetUp() bool {
  363. if l.linkMonitor == nil {
  364. // No way to tell, so assume it is.
  365. return true
  366. }
  367. return l.linkMonitor.InterfaceState().AnyInterfaceUp()
  368. }
  369. func (l *Logger) awaitInternetUp(ctx context.Context) {
  370. upc := make(chan bool, 1)
  371. defer l.linkMonitor.RegisterChangeCallback(func(changed bool, st *interfaces.State) {
  372. if st.AnyInterfaceUp() {
  373. select {
  374. case upc <- true:
  375. default:
  376. }
  377. }
  378. })()
  379. if l.internetUp() {
  380. return
  381. }
  382. select {
  383. case <-upc:
  384. fmt.Fprintf(l.stderr, "logtail: internet back up\n")
  385. case <-ctx.Done():
  386. }
  387. }
  388. // upload uploads body to the log server.
  389. // origlen indicates the pre-compression body length.
  390. // origlen of -1 indicates that the body is not compressed.
  391. func (l *Logger) upload(ctx context.Context, body []byte, origlen int) (uploaded bool, err error) {
  392. const maxUploadTime = 45 * time.Second
  393. ctx = sockstats.WithSockStats(ctx, l.sockstatsLabel)
  394. ctx, cancel := context.WithTimeout(ctx, maxUploadTime)
  395. defer cancel()
  396. req, err := http.NewRequestWithContext(ctx, "POST", l.url, bytes.NewReader(body))
  397. if err != nil {
  398. // I know of no conditions under which this could fail.
  399. // Report it very loudly.
  400. // TODO record logs to disk
  401. panic("logtail: cannot build http request: " + err.Error())
  402. }
  403. if origlen != -1 {
  404. req.Header.Add("Content-Encoding", "zstd")
  405. req.Header.Add("Orig-Content-Length", strconv.Itoa(origlen))
  406. }
  407. req.Header["User-Agent"] = nil // not worth writing one; save some bytes
  408. compressedNote := "not-compressed"
  409. if origlen != -1 {
  410. compressedNote = "compressed"
  411. }
  412. l.httpDoCalls.Add(1)
  413. resp, err := l.httpc.Do(req)
  414. if err != nil {
  415. return false, fmt.Errorf("log upload of %d bytes %s failed: %v", len(body), compressedNote, err)
  416. }
  417. defer resp.Body.Close()
  418. if resp.StatusCode != 200 {
  419. uploaded = resp.StatusCode == 400 // the server saved the logs anyway
  420. b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
  421. return uploaded, fmt.Errorf("log upload of %d bytes %s failed %d: %q", len(body), compressedNote, resp.StatusCode, b)
  422. }
  423. return true, nil
  424. }
  425. // Flush uploads all logs to the server. It blocks until complete or there is an
  426. // unrecoverable error.
  427. //
  428. // TODO(bradfitz): this apparently just returns nil, as of tailscale/corp@9c2ec35.
  429. // Finish cleaning this up.
  430. func (l *Logger) Flush() error {
  431. return nil
  432. }
  433. // StartFlush starts a log upload, if anything is pending.
  434. //
  435. // If l is nil, StartFlush is a no-op.
  436. func (l *Logger) StartFlush() {
  437. if l != nil {
  438. l.tryDrainWake()
  439. }
  440. }
  441. // logtailDisabled is whether logtail uploads to logcatcher are disabled.
  442. var logtailDisabled atomic.Bool
  443. // Disable disables logtail uploads for the lifetime of the process.
  444. func Disable() {
  445. logtailDisabled.Store(true)
  446. }
  447. var debugWakesAndUploads = envknob.RegisterBool("TS_DEBUG_LOGTAIL_WAKES")
  448. // tryDrainWake tries to send to lg.drainWake, to cause an uploading wakeup.
  449. // It does not block.
  450. func (l *Logger) tryDrainWake() {
  451. l.flushPending.Store(false)
  452. if debugWakesAndUploads() {
  453. // Using println instead of log.Printf here to avoid recursing back into
  454. // ourselves.
  455. println("logtail: try drain wake, numHTTP:", l.httpDoCalls.Load())
  456. }
  457. select {
  458. case l.drainWake <- struct{}{}:
  459. default:
  460. }
  461. }
  462. func (l *Logger) sendLocked(jsonBlob []byte) (int, error) {
  463. tapSend(jsonBlob)
  464. if logtailDisabled.Load() {
  465. return len(jsonBlob), nil
  466. }
  467. n, err := l.buffer.Write(jsonBlob)
  468. flushDelay := defaultFlushDelay
  469. if l.flushDelayFn != nil {
  470. flushDelay = l.flushDelayFn()
  471. }
  472. if flushDelay > 0 {
  473. if l.flushPending.CompareAndSwap(false, true) {
  474. if l.flushTimer == nil {
  475. l.flushTimer = time.AfterFunc(flushDelay, l.tryDrainWake)
  476. } else {
  477. l.flushTimer.Reset(flushDelay)
  478. }
  479. }
  480. } else {
  481. l.tryDrainWake()
  482. }
  483. return n, err
  484. }
  485. // TODO: instead of allocating, this should probably just append
  486. // directly into the output log buffer.
  487. func (l *Logger) encodeText(buf []byte, skipClientTime bool, procID uint32, procSequence uint64, level int) []byte {
  488. now := l.timeNow()
  489. // Factor in JSON encoding overhead to try to only do one alloc
  490. // in the make below (so appends don't resize the buffer).
  491. overhead := len(`{"text": ""}\n`)
  492. includeLogtail := !skipClientTime || procID != 0 || procSequence != 0
  493. if includeLogtail {
  494. overhead += len(`"logtail": {},`)
  495. }
  496. if !skipClientTime {
  497. overhead += len(`"client_time": "2006-01-02T15:04:05.999999999Z07:00",`)
  498. }
  499. if procID != 0 {
  500. overhead += len(`"proc_id": 4294967296,`)
  501. }
  502. if procSequence != 0 {
  503. overhead += len(`"proc_seq": 9007199254740992,`)
  504. }
  505. // TODO: do a pass over buf and count how many backslashes will be needed?
  506. // For now just factor in a dozen.
  507. overhead += 12
  508. // Put a sanity cap on buf's size.
  509. max := 16 << 10
  510. if l.lowMem {
  511. max = 4 << 10
  512. }
  513. var nTruncated int
  514. if len(buf) > max {
  515. nTruncated = len(buf) - max
  516. // TODO: this can break a UTF-8 character
  517. // mid-encoding. We don't tend to log
  518. // non-ASCII stuff ourselves, but e.g. client
  519. // names might be.
  520. buf = buf[:max]
  521. }
  522. b := make([]byte, 0, len(buf)+overhead)
  523. b = append(b, '{')
  524. if includeLogtail {
  525. b = append(b, `"logtail": {`...)
  526. if !skipClientTime {
  527. b = append(b, `"client_time": "`...)
  528. b = now.UTC().AppendFormat(b, time.RFC3339Nano)
  529. b = append(b, `",`...)
  530. }
  531. if procID != 0 {
  532. b = append(b, `"proc_id": `...)
  533. b = strconv.AppendUint(b, uint64(procID), 10)
  534. b = append(b, ',')
  535. }
  536. if procSequence != 0 {
  537. b = append(b, `"proc_seq": `...)
  538. b = strconv.AppendUint(b, procSequence, 10)
  539. b = append(b, ',')
  540. }
  541. b = bytes.TrimRight(b, ",")
  542. b = append(b, "}, "...)
  543. }
  544. if l.metricsDelta != nil {
  545. if d := l.metricsDelta(); d != "" {
  546. b = append(b, `"metrics": "`...)
  547. b = append(b, d...)
  548. b = append(b, `",`...)
  549. }
  550. }
  551. // Add the log level, if non-zero. Note that we only use log
  552. // levels 1 and 2 currently. It's unlikely we'll ever make it
  553. // past 9.
  554. if level > 0 && level < 10 {
  555. b = append(b, `"v":`...)
  556. b = append(b, '0'+byte(level))
  557. b = append(b, ',')
  558. }
  559. b = append(b, "\"text\": \""...)
  560. for _, c := range buf {
  561. switch c {
  562. case '\b':
  563. b = append(b, '\\', 'b')
  564. case '\f':
  565. b = append(b, '\\', 'f')
  566. case '\n':
  567. b = append(b, '\\', 'n')
  568. case '\r':
  569. b = append(b, '\\', 'r')
  570. case '\t':
  571. b = append(b, '\\', 't')
  572. case '"':
  573. b = append(b, '\\', '"')
  574. case '\\':
  575. b = append(b, '\\', '\\')
  576. default:
  577. // TODO: what about binary gibberish or non UTF-8?
  578. b = append(b, c)
  579. }
  580. }
  581. if nTruncated > 0 {
  582. b = append(b, "…+"...)
  583. b = strconv.AppendInt(b, int64(nTruncated), 10)
  584. }
  585. b = append(b, "\"}\n"...)
  586. return b
  587. }
  588. func (l *Logger) encodeLocked(buf []byte, level int) []byte {
  589. if l.includeProcSequence {
  590. l.procSequence++
  591. }
  592. if buf[0] != '{' {
  593. return l.encodeText(buf, l.skipClientTime, l.procID, l.procSequence, level) // text fast-path
  594. }
  595. now := l.timeNow()
  596. obj := make(map[string]any)
  597. if err := json.Unmarshal(buf, &obj); err != nil {
  598. for k := range obj {
  599. delete(obj, k)
  600. }
  601. obj["text"] = string(buf)
  602. }
  603. if txt, isStr := obj["text"].(string); l.lowMem && isStr && len(txt) > 254 {
  604. // TODO(crawshaw): trim to unicode code point
  605. obj["text"] = txt[:254] + "…"
  606. }
  607. hasLogtail := obj["logtail"] != nil
  608. if hasLogtail {
  609. obj["error_has_logtail"] = obj["logtail"]
  610. obj["logtail"] = nil
  611. }
  612. if !l.skipClientTime || l.procID != 0 || l.procSequence != 0 {
  613. logtail := map[string]any{}
  614. if !l.skipClientTime {
  615. logtail["client_time"] = now.UTC().Format(time.RFC3339Nano)
  616. }
  617. if l.procID != 0 {
  618. logtail["proc_id"] = l.procID
  619. }
  620. if l.procSequence != 0 {
  621. logtail["proc_seq"] = l.procSequence
  622. }
  623. obj["logtail"] = logtail
  624. }
  625. if level > 0 {
  626. obj["v"] = level
  627. }
  628. b, err := json.Marshal(obj)
  629. if err != nil {
  630. fmt.Fprintf(l.stderr, "logtail: re-encoding JSON failed: %v\n", err)
  631. // I know of no conditions under which this could fail.
  632. // Report it very loudly.
  633. panic("logtail: re-encoding JSON failed: " + err.Error())
  634. }
  635. b = append(b, '\n')
  636. return b
  637. }
  638. // Logf logs to l using the provided fmt-style format and optional arguments.
  639. func (l *Logger) Logf(format string, args ...any) {
  640. fmt.Fprintf(l, format, args...)
  641. }
  642. // Write logs an encoded JSON blob.
  643. //
  644. // If the []byte passed to Write is not an encoded JSON blob,
  645. // then contents is fit into a JSON blob and written.
  646. //
  647. // This is intended as an interface for the stdlib "log" package.
  648. func (l *Logger) Write(buf []byte) (int, error) {
  649. if len(buf) == 0 {
  650. return 0, nil
  651. }
  652. level, buf := parseAndRemoveLogLevel(buf)
  653. if l.stderr != nil && l.stderr != io.Discard && int64(level) <= atomic.LoadInt64(&l.stderrLevel) {
  654. if buf[len(buf)-1] == '\n' {
  655. l.stderr.Write(buf)
  656. } else {
  657. // The log package always line-terminates logs,
  658. // so this is an uncommon path.
  659. withNL := append(buf[:len(buf):len(buf)], '\n')
  660. l.stderr.Write(withNL)
  661. }
  662. }
  663. l.writeLock.Lock()
  664. defer l.writeLock.Unlock()
  665. b := l.encodeLocked(buf, level)
  666. _, err := l.sendLocked(b)
  667. return len(buf), err
  668. }
  669. var (
  670. openBracketV = []byte("[v")
  671. v1 = []byte("[v1] ")
  672. v2 = []byte("[v2] ")
  673. vJSON = []byte("[v\x00JSON]") // precedes log level '0'-'9' byte, then JSON value
  674. )
  675. // level 0 is normal (or unknown) level; 1+ are increasingly verbose
  676. func parseAndRemoveLogLevel(buf []byte) (level int, cleanBuf []byte) {
  677. if len(buf) == 0 || buf[0] == '{' || !bytes.Contains(buf, openBracketV) {
  678. return 0, buf
  679. }
  680. if bytes.Contains(buf, v1) {
  681. return 1, bytes.ReplaceAll(buf, v1, nil)
  682. }
  683. if bytes.Contains(buf, v2) {
  684. return 2, bytes.ReplaceAll(buf, v2, nil)
  685. }
  686. if i := bytes.Index(buf, vJSON); i != -1 {
  687. rest := buf[i+len(vJSON):]
  688. if len(rest) >= 2 {
  689. v := rest[0]
  690. if v >= '0' && v <= '9' {
  691. return int(v - '0'), rest[1:]
  692. }
  693. }
  694. }
  695. return 0, buf
  696. }
  697. var (
  698. tapSetSize atomic.Int32
  699. tapMu sync.Mutex
  700. tapSet set.HandleSet[chan<- string]
  701. )
  702. // RegisterLogTap registers dst to get a copy of every log write. The caller
  703. // must call unregister when done watching.
  704. //
  705. // This would ideally be a method on Logger, but Logger isn't really available
  706. // in most places; many writes go via stderr which filch redirects to the
  707. // singleton Logger set up early. For better or worse, there's basically only
  708. // one Logger within the program. This mechanism at least works well for
  709. // tailscaled. It works less well for a binary with multiple tsnet.Servers. Oh
  710. // well. This then subscribes to all of them.
  711. func RegisterLogTap(dst chan<- string) (unregister func()) {
  712. tapMu.Lock()
  713. defer tapMu.Unlock()
  714. h := tapSet.Add(dst)
  715. tapSetSize.Store(int32(len(tapSet)))
  716. return func() {
  717. tapMu.Lock()
  718. defer tapMu.Unlock()
  719. delete(tapSet, h)
  720. tapSetSize.Store(int32(len(tapSet)))
  721. }
  722. }
  723. // tapSend relays the JSON blob to any/all registered local debug log watchers
  724. // (somebody running "tailscale debug daemon-logs").
  725. func tapSend(jsonBlob []byte) {
  726. if tapSetSize.Load() == 0 {
  727. return
  728. }
  729. s := string(jsonBlob)
  730. tapMu.Lock()
  731. defer tapMu.Unlock()
  732. for _, dst := range tapSet {
  733. select {
  734. case dst <- s:
  735. default:
  736. }
  737. }
  738. }