logtail.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. "fmt"
  11. "io"
  12. "log"
  13. mrand "math/rand/v2"
  14. "net/http"
  15. "net/netip"
  16. "os"
  17. "regexp"
  18. "runtime"
  19. "slices"
  20. "strconv"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/go-json-experiment/json/jsontext"
  25. "tailscale.com/envknob"
  26. "tailscale.com/net/netmon"
  27. "tailscale.com/net/sockstats"
  28. "tailscale.com/net/tsaddr"
  29. "tailscale.com/tstime"
  30. tslogger "tailscale.com/types/logger"
  31. "tailscale.com/types/logid"
  32. "tailscale.com/util/set"
  33. "tailscale.com/util/truncate"
  34. "tailscale.com/util/zstdframe"
  35. )
  36. // maxSize is the maximum size that a single log entry can be.
  37. // It is also the maximum body size that may be uploaded at a time.
  38. const maxSize = 256 << 10
  39. // maxTextSize is the maximum size for a text log message.
  40. // Note that JSON log messages can be as large as maxSize.
  41. const maxTextSize = 16 << 10
  42. // lowMemRatio reduces maxSize and maxTextSize by this ratio in lowMem mode.
  43. const lowMemRatio = 4
  44. // bufferSize is the typical buffer size to retain.
  45. // It is large enough to handle most log messages,
  46. // but not too large to be a notable waste of memory if retained forever.
  47. const bufferSize = 4 << 10
  48. // DefaultHost is the default host name to upload logs to when
  49. // Config.BaseURL isn't provided.
  50. const DefaultHost = "log.tailscale.io"
  51. const defaultFlushDelay = 2 * time.Second
  52. const (
  53. // CollectionNode is the name of a logtail Config.Collection
  54. // for tailscaled (or equivalent: IPNExtension, Android app).
  55. CollectionNode = "tailnode.log.tailscale.io"
  56. )
  57. type Config struct {
  58. Collection string // collection name, a domain name
  59. PrivateID logid.PrivateID // private ID for the primary log stream
  60. CopyPrivateID logid.PrivateID // private ID for a log stream that is a superset of this log stream
  61. BaseURL string // if empty defaults to "https://log.tailscale.io"
  62. HTTPC *http.Client // if empty defaults to http.DefaultClient
  63. SkipClientTime bool // if true, client_time is not written to logs
  64. LowMemory bool // if true, logtail minimizes memory use
  65. Clock tstime.Clock // if set, Clock.Now substitutes uses of time.Now
  66. Stderr io.Writer // if set, logs are sent here instead of os.Stderr
  67. StderrLevel int // max verbosity level to write to stderr; 0 means the non-verbose messages only
  68. Buffer Buffer // temp storage, if nil a MemoryBuffer
  69. CompressLogs bool // whether to compress the log uploads
  70. // MetricsDelta, if non-nil, is a func that returns an encoding
  71. // delta in clientmetrics to upload alongside existing logs.
  72. // It can return either an empty string (for nothing) or a string
  73. // that's safe to embed in a JSON string literal without further escaping.
  74. MetricsDelta func() string
  75. // FlushDelayFn, if non-nil is a func that returns how long to wait to
  76. // accumulate logs before uploading them. 0 or negative means to upload
  77. // immediately.
  78. //
  79. // If nil, a default value is used. (currently 2 seconds)
  80. FlushDelayFn func() time.Duration
  81. // IncludeProcID, if true, results in an ephemeral process identifier being
  82. // included in logs. The ID is random and not guaranteed to be globally
  83. // unique, but it can be used to distinguish between different instances
  84. // running with same PrivateID.
  85. IncludeProcID bool
  86. // IncludeProcSequence, if true, results in an ephemeral sequence number
  87. // being included in the logs. The sequence number is incremented for each
  88. // log message sent, but is not persisted across process restarts.
  89. IncludeProcSequence bool
  90. }
  91. func NewLogger(cfg Config, logf tslogger.Logf) *Logger {
  92. if cfg.BaseURL == "" {
  93. cfg.BaseURL = "https://" + DefaultHost
  94. }
  95. if cfg.HTTPC == nil {
  96. cfg.HTTPC = http.DefaultClient
  97. }
  98. if cfg.Clock == nil {
  99. cfg.Clock = tstime.StdClock{}
  100. }
  101. if cfg.Stderr == nil {
  102. cfg.Stderr = os.Stderr
  103. }
  104. if cfg.Buffer == nil {
  105. pendingSize := 256
  106. if cfg.LowMemory {
  107. pendingSize = 64
  108. }
  109. cfg.Buffer = NewMemoryBuffer(pendingSize)
  110. }
  111. var procID uint32
  112. if cfg.IncludeProcID {
  113. keyBytes := make([]byte, 4)
  114. rand.Read(keyBytes)
  115. procID = binary.LittleEndian.Uint32(keyBytes)
  116. if procID == 0 {
  117. // 0 is the empty/off value, assign a different (non-zero) value to
  118. // make sure we still include an ID (actual value does not matter).
  119. procID = 7
  120. }
  121. }
  122. if s := envknob.String("TS_DEBUG_LOGTAIL_FLUSHDELAY"); s != "" {
  123. if delay, err := time.ParseDuration(s); err == nil {
  124. cfg.FlushDelayFn = func() time.Duration { return delay }
  125. } else {
  126. log.Fatalf("invalid TS_DEBUG_LOGTAIL_FLUSHDELAY: %v", err)
  127. }
  128. } else if cfg.FlushDelayFn == nil && envknob.Bool("IN_TS_TEST") {
  129. cfg.FlushDelayFn = func() time.Duration { return 0 }
  130. }
  131. var urlSuffix string
  132. if !cfg.CopyPrivateID.IsZero() {
  133. urlSuffix = "?copyId=" + cfg.CopyPrivateID.String()
  134. }
  135. l := &Logger{
  136. privateID: cfg.PrivateID,
  137. stderr: cfg.Stderr,
  138. stderrLevel: int64(cfg.StderrLevel),
  139. httpc: cfg.HTTPC,
  140. url: cfg.BaseURL + "/c/" + cfg.Collection + "/" + cfg.PrivateID.String() + urlSuffix,
  141. lowMem: cfg.LowMemory,
  142. buffer: cfg.Buffer,
  143. skipClientTime: cfg.SkipClientTime,
  144. drainWake: make(chan struct{}, 1),
  145. sentinel: make(chan int32, 16),
  146. flushDelayFn: cfg.FlushDelayFn,
  147. clock: cfg.Clock,
  148. metricsDelta: cfg.MetricsDelta,
  149. procID: procID,
  150. includeProcSequence: cfg.IncludeProcSequence,
  151. shutdownStart: make(chan struct{}),
  152. shutdownDone: make(chan struct{}),
  153. }
  154. l.SetSockstatsLabel(sockstats.LabelLogtailLogger)
  155. l.compressLogs = cfg.CompressLogs
  156. ctx, cancel := context.WithCancel(context.Background())
  157. l.uploadCancel = cancel
  158. go l.uploading(ctx)
  159. l.Write([]byte("logtail started"))
  160. return l
  161. }
  162. // Logger writes logs, splitting them as configured between local
  163. // logging facilities and uploading to a log server.
  164. type Logger struct {
  165. stderr io.Writer
  166. stderrLevel int64 // accessed atomically
  167. httpc *http.Client
  168. url string
  169. lowMem bool
  170. skipClientTime bool
  171. netMonitor *netmon.Monitor
  172. buffer Buffer
  173. drainWake chan struct{} // signal to speed up drain
  174. drainBuf []byte // owned by drainPending for reuse
  175. flushDelayFn func() time.Duration // negative or zero return value to upload aggressively, or >0 to batch at this delay
  176. flushPending atomic.Bool
  177. sentinel chan int32
  178. clock tstime.Clock
  179. compressLogs bool
  180. uploadCancel func()
  181. explainedRaw bool
  182. metricsDelta func() string // or nil
  183. privateID logid.PrivateID
  184. httpDoCalls atomic.Int32
  185. sockstatsLabel atomicSocktatsLabel
  186. procID uint32
  187. includeProcSequence bool
  188. writeLock sync.Mutex // guards procSequence, flushTimer, buffer.Write calls
  189. procSequence uint64
  190. flushTimer tstime.TimerController // used when flushDelay is >0
  191. writeBuf [bufferSize]byte // owned by Write for reuse
  192. jsonDec jsontext.Decoder // owned by appendTextOrJSONLocked for reuse
  193. shutdownStartMu sync.Mutex // guards the closing of shutdownStart
  194. shutdownStart chan struct{} // closed when shutdown begins
  195. shutdownDone chan struct{} // closed when shutdown complete
  196. }
  197. type atomicSocktatsLabel struct{ p atomic.Uint32 }
  198. func (p *atomicSocktatsLabel) Load() sockstats.Label { return sockstats.Label(p.p.Load()) }
  199. func (p *atomicSocktatsLabel) Store(label sockstats.Label) { p.p.Store(uint32(label)) }
  200. // SetVerbosityLevel controls the verbosity level that should be
  201. // written to stderr. 0 is the default (not verbose). Levels 1 or higher
  202. // are increasingly verbose.
  203. func (l *Logger) SetVerbosityLevel(level int) {
  204. atomic.StoreInt64(&l.stderrLevel, int64(level))
  205. }
  206. // SetNetMon sets the network monitor.
  207. //
  208. // It should not be changed concurrently with log writes and should
  209. // only be set once.
  210. func (l *Logger) SetNetMon(lm *netmon.Monitor) {
  211. l.netMonitor = lm
  212. }
  213. // SetSockstatsLabel sets the label used in sockstat logs to identify network traffic from this logger.
  214. func (l *Logger) SetSockstatsLabel(label sockstats.Label) {
  215. l.sockstatsLabel.Store(label)
  216. }
  217. // PrivateID returns the logger's private log ID.
  218. //
  219. // It exists for internal use only.
  220. func (l *Logger) PrivateID() logid.PrivateID { return l.privateID }
  221. // Shutdown gracefully shuts down the logger while completing any
  222. // remaining uploads.
  223. //
  224. // It will block, continuing to try and upload unless the passed
  225. // context object interrupts it by being done.
  226. // If the shutdown is interrupted, an error is returned.
  227. func (l *Logger) Shutdown(ctx context.Context) error {
  228. done := make(chan struct{})
  229. go func() {
  230. select {
  231. case <-ctx.Done():
  232. l.uploadCancel()
  233. <-l.shutdownDone
  234. case <-l.shutdownDone:
  235. }
  236. close(done)
  237. }()
  238. l.shutdownStartMu.Lock()
  239. select {
  240. case <-l.shutdownStart:
  241. l.shutdownStartMu.Unlock()
  242. return nil
  243. default:
  244. }
  245. close(l.shutdownStart)
  246. l.shutdownStartMu.Unlock()
  247. io.WriteString(l, "logger closing down\n")
  248. <-done
  249. return nil
  250. }
  251. // Close shuts down this logger object, the background log uploader
  252. // process, and any associated goroutines.
  253. //
  254. // Deprecated: use Shutdown
  255. func (l *Logger) Close() {
  256. l.Shutdown(context.Background())
  257. }
  258. // drainBlock is called by drainPending when there are no logs to drain.
  259. //
  260. // In typical operation, every call to the Write method unblocks and triggers a
  261. // buffer.TryReadline, so logs are written with very low latency.
  262. //
  263. // If the caller specified FlushInterface, drainWake is only sent to
  264. // periodically.
  265. func (l *Logger) drainBlock() (shuttingDown bool) {
  266. select {
  267. case <-l.shutdownStart:
  268. return true
  269. case <-l.drainWake:
  270. }
  271. return false
  272. }
  273. // drainPending drains and encodes a batch of logs from the buffer for upload.
  274. // If no logs are available, drainPending blocks until logs are available.
  275. // The returned buffer is only valid until the next call to drainPending.
  276. func (l *Logger) drainPending() (b []byte) {
  277. b = l.drainBuf[:0]
  278. b = append(b, '[')
  279. defer func() {
  280. b = bytes.TrimRight(b, ",")
  281. b = append(b, ']')
  282. l.drainBuf = b
  283. if len(b) <= len("[]") {
  284. b = nil
  285. }
  286. }()
  287. maxLen := maxSize
  288. if l.lowMem {
  289. // When operating in a low memory environment, it is better to upload
  290. // in multiple operations than it is to allocate a large body and OOM.
  291. // Even if maxLen is less than maxSize, we can still upload an entry
  292. // that is up to maxSize if we happen to encounter one.
  293. maxLen /= lowMemRatio
  294. }
  295. for len(b) < maxLen {
  296. line, err := l.buffer.TryReadLine()
  297. switch {
  298. case err == io.EOF:
  299. return b
  300. case err != nil:
  301. b = append(b, '{')
  302. b = l.appendMetadata(b, false, true, 0, 0, "reading ringbuffer: "+err.Error(), nil, 0)
  303. b = bytes.TrimRight(b, ",")
  304. b = append(b, '}')
  305. return b
  306. case line == nil:
  307. // If we read at least some log entries, return immediately.
  308. if len(b) > len("[") {
  309. return b
  310. }
  311. // We're about to block. If we're holding on to too much memory
  312. // in our buffer from a previous large write, let it go.
  313. if cap(b) > bufferSize {
  314. b = bytes.Clone(b)
  315. l.drainBuf = b
  316. }
  317. if shuttingDown := l.drainBlock(); shuttingDown {
  318. return b
  319. }
  320. continue
  321. }
  322. switch {
  323. case len(line) == 0:
  324. continue
  325. case line[0] == '{' && jsontext.Value(line).IsValid():
  326. // This is already a valid JSON object, so just append it.
  327. // This may exceed maxLen, but should be no larger than maxSize
  328. // so long as logic writing into the buffer enforces the limit.
  329. b = append(b, line...)
  330. default:
  331. // This is probably a log added to stderr by filch
  332. // outside of the logtail logger. Encode it.
  333. if !l.explainedRaw {
  334. fmt.Fprintf(l.stderr, "RAW-STDERR: ***\n")
  335. 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")
  336. fmt.Fprintf(l.stderr, "RAW-STDERR: ***\n")
  337. fmt.Fprintf(l.stderr, "RAW-STDERR:\n")
  338. l.explainedRaw = true
  339. }
  340. fmt.Fprintf(l.stderr, "RAW-STDERR: %s", b)
  341. // Do not add a client time, as it could be really old.
  342. // Do not include instance key or ID either,
  343. // since this came from a different instance.
  344. b = l.appendText(b, line, true, 0, 0, 0)
  345. }
  346. b = append(b, ',')
  347. }
  348. return b
  349. }
  350. // This is the goroutine that repeatedly uploads logs in the background.
  351. func (l *Logger) uploading(ctx context.Context) {
  352. defer close(l.shutdownDone)
  353. for {
  354. body := l.drainPending()
  355. origlen := -1 // sentinel value: uncompressed
  356. // Don't attempt to compress tiny bodies; not worth the CPU cycles.
  357. if l.compressLogs && len(body) > 256 {
  358. zbody := zstdframe.AppendEncode(nil, body,
  359. zstdframe.FastestCompression, zstdframe.LowMemory(true))
  360. // Only send it compressed if the bandwidth savings are sufficient.
  361. // Just the extra headers associated with enabling compression
  362. // are 50 bytes by themselves.
  363. if len(body)-len(zbody) > 64 {
  364. origlen = len(body)
  365. body = zbody
  366. }
  367. }
  368. var lastError string
  369. var numFailures int
  370. var firstFailure time.Time
  371. for len(body) > 0 && ctx.Err() == nil {
  372. retryAfter, err := l.upload(ctx, body, origlen)
  373. if err != nil {
  374. numFailures++
  375. firstFailure = l.clock.Now()
  376. if !l.internetUp() {
  377. fmt.Fprintf(l.stderr, "logtail: internet down; waiting\n")
  378. l.awaitInternetUp(ctx)
  379. continue
  380. }
  381. // Only print the same message once.
  382. if currError := err.Error(); lastError != currError {
  383. fmt.Fprintf(l.stderr, "logtail: upload: %v\n", err)
  384. lastError = currError
  385. }
  386. // Sleep for the specified retryAfter period,
  387. // otherwise default to some random value.
  388. if retryAfter <= 0 {
  389. retryAfter = mrand.N(30*time.Second) + 30*time.Second
  390. }
  391. tstime.Sleep(ctx, retryAfter)
  392. } else {
  393. // Only print a success message after recovery.
  394. if numFailures > 0 {
  395. fmt.Fprintf(l.stderr, "logtail: upload succeeded after %d failures and %s\n", numFailures, l.clock.Since(firstFailure).Round(time.Second))
  396. }
  397. break
  398. }
  399. }
  400. select {
  401. case <-l.shutdownStart:
  402. return
  403. default:
  404. }
  405. }
  406. }
  407. func (l *Logger) internetUp() bool {
  408. if l.netMonitor == nil {
  409. // No way to tell, so assume it is.
  410. return true
  411. }
  412. return l.netMonitor.InterfaceState().AnyInterfaceUp()
  413. }
  414. func (l *Logger) awaitInternetUp(ctx context.Context) {
  415. upc := make(chan bool, 1)
  416. defer l.netMonitor.RegisterChangeCallback(func(delta *netmon.ChangeDelta) {
  417. if delta.New.AnyInterfaceUp() {
  418. select {
  419. case upc <- true:
  420. default:
  421. }
  422. }
  423. })()
  424. if l.internetUp() {
  425. return
  426. }
  427. select {
  428. case <-upc:
  429. fmt.Fprintf(l.stderr, "logtail: internet back up\n")
  430. case <-ctx.Done():
  431. }
  432. }
  433. // upload uploads body to the log server.
  434. // origlen indicates the pre-compression body length.
  435. // origlen of -1 indicates that the body is not compressed.
  436. func (l *Logger) upload(ctx context.Context, body []byte, origlen int) (retryAfter time.Duration, err error) {
  437. const maxUploadTime = 45 * time.Second
  438. ctx = sockstats.WithSockStats(ctx, l.sockstatsLabel.Load(), l.Logf)
  439. ctx, cancel := context.WithTimeout(ctx, maxUploadTime)
  440. defer cancel()
  441. req, err := http.NewRequestWithContext(ctx, "POST", l.url, bytes.NewReader(body))
  442. if err != nil {
  443. // I know of no conditions under which this could fail.
  444. // Report it very loudly.
  445. // TODO record logs to disk
  446. panic("logtail: cannot build http request: " + err.Error())
  447. }
  448. if origlen != -1 {
  449. req.Header.Add("Content-Encoding", "zstd")
  450. req.Header.Add("Orig-Content-Length", strconv.Itoa(origlen))
  451. }
  452. if runtime.GOOS == "js" {
  453. // We once advertised we'd accept optional client certs (for internal use)
  454. // on log.tailscale.io but then Tailscale SSH js/wasm clients prompted
  455. // users (on some browsers?) to pick a client cert. We'll fix the server's
  456. // TLS ServerHello, but we can also fix it client side for good measure.
  457. //
  458. // Corp details: https://github.com/tailscale/corp/issues/18177#issuecomment-2026598715
  459. // and https://github.com/tailscale/corp/pull/18775#issuecomment-2027505036
  460. //
  461. // See https://github.com/golang/go/wiki/WebAssembly#configuring-fetch-options-while-using-nethttp
  462. // and https://developer.mozilla.org/en-US/docs/Web/API/fetch#credentials
  463. req.Header.Set("js.fetch:credentials", "omit")
  464. }
  465. req.Header["User-Agent"] = nil // not worth writing one; save some bytes
  466. compressedNote := "not-compressed"
  467. if origlen != -1 {
  468. compressedNote = "compressed"
  469. }
  470. l.httpDoCalls.Add(1)
  471. resp, err := l.httpc.Do(req)
  472. if err != nil {
  473. return 0, fmt.Errorf("log upload of %d bytes %s failed: %v", len(body), compressedNote, err)
  474. }
  475. defer resp.Body.Close()
  476. if resp.StatusCode != http.StatusOK {
  477. n, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
  478. b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<10))
  479. return time.Duration(n) * time.Second, fmt.Errorf("log upload of %d bytes %s failed %d: %s", len(body), compressedNote, resp.StatusCode, bytes.TrimSpace(b))
  480. }
  481. return 0, nil
  482. }
  483. // Flush uploads all logs to the server. It blocks until complete or there is an
  484. // unrecoverable error.
  485. //
  486. // TODO(bradfitz): this apparently just returns nil, as of tailscale/corp@9c2ec35.
  487. // Finish cleaning this up.
  488. func (l *Logger) Flush() error {
  489. return nil
  490. }
  491. // StartFlush starts a log upload, if anything is pending.
  492. //
  493. // If l is nil, StartFlush is a no-op.
  494. func (l *Logger) StartFlush() {
  495. if l != nil {
  496. l.tryDrainWake()
  497. }
  498. }
  499. // logtailDisabled is whether logtail uploads to logcatcher are disabled.
  500. var logtailDisabled atomic.Bool
  501. // Disable disables logtail uploads for the lifetime of the process.
  502. func Disable() {
  503. logtailDisabled.Store(true)
  504. }
  505. var debugWakesAndUploads = envknob.RegisterBool("TS_DEBUG_LOGTAIL_WAKES")
  506. // tryDrainWake tries to send to lg.drainWake, to cause an uploading wakeup.
  507. // It does not block.
  508. func (l *Logger) tryDrainWake() {
  509. l.flushPending.Store(false)
  510. if debugWakesAndUploads() {
  511. // Using println instead of log.Printf here to avoid recursing back into
  512. // ourselves.
  513. println("logtail: try drain wake, numHTTP:", l.httpDoCalls.Load())
  514. }
  515. select {
  516. case l.drainWake <- struct{}{}:
  517. default:
  518. }
  519. }
  520. func (l *Logger) sendLocked(jsonBlob []byte) (int, error) {
  521. tapSend(jsonBlob)
  522. if logtailDisabled.Load() {
  523. return len(jsonBlob), nil
  524. }
  525. n, err := l.buffer.Write(jsonBlob)
  526. flushDelay := defaultFlushDelay
  527. if l.flushDelayFn != nil {
  528. flushDelay = l.flushDelayFn()
  529. }
  530. if flushDelay > 0 {
  531. if l.flushPending.CompareAndSwap(false, true) {
  532. if l.flushTimer == nil {
  533. l.flushTimer = l.clock.AfterFunc(flushDelay, l.tryDrainWake)
  534. } else {
  535. l.flushTimer.Reset(flushDelay)
  536. }
  537. }
  538. } else {
  539. l.tryDrainWake()
  540. }
  541. return n, err
  542. }
  543. // appendMetadata appends optional "logtail", "metrics", and "v" JSON members.
  544. // This assumes dst is already within a JSON object.
  545. // Each member is comma-terminated.
  546. func (l *Logger) appendMetadata(dst []byte, skipClientTime, skipMetrics bool, procID uint32, procSequence uint64, errDetail string, errData jsontext.Value, level int) []byte {
  547. // Append optional logtail metadata.
  548. if !skipClientTime || procID != 0 || procSequence != 0 || errDetail != "" || errData != nil {
  549. dst = append(dst, `"logtail":{`...)
  550. if !skipClientTime {
  551. dst = append(dst, `"client_time":"`...)
  552. dst = l.clock.Now().UTC().AppendFormat(dst, time.RFC3339Nano)
  553. dst = append(dst, '"', ',')
  554. }
  555. if procID != 0 {
  556. dst = append(dst, `"proc_id":`...)
  557. dst = strconv.AppendUint(dst, uint64(procID), 10)
  558. dst = append(dst, ',')
  559. }
  560. if procSequence != 0 {
  561. dst = append(dst, `"proc_seq":`...)
  562. dst = strconv.AppendUint(dst, procSequence, 10)
  563. dst = append(dst, ',')
  564. }
  565. if errDetail != "" || errData != nil {
  566. dst = append(dst, `"error":{`...)
  567. if errDetail != "" {
  568. dst = append(dst, `"detail":`...)
  569. dst, _ = jsontext.AppendQuote(dst, errDetail)
  570. dst = append(dst, ',')
  571. }
  572. if errData != nil {
  573. dst = append(dst, `"bad_data":`...)
  574. dst = append(dst, errData...)
  575. dst = append(dst, ',')
  576. }
  577. dst = bytes.TrimRight(dst, ",")
  578. dst = append(dst, '}', ',')
  579. }
  580. dst = bytes.TrimRight(dst, ",")
  581. dst = append(dst, '}', ',')
  582. }
  583. // Append optional metrics metadata.
  584. if !skipMetrics && l.metricsDelta != nil {
  585. if d := l.metricsDelta(); d != "" {
  586. dst = append(dst, `"metrics":"`...)
  587. dst = append(dst, d...)
  588. dst = append(dst, '"', ',')
  589. }
  590. }
  591. // Add the optional log level, if non-zero.
  592. // Note that we only use log levels 1 and 2 currently.
  593. // It's unlikely we'll ever make it past 9.
  594. if level > 0 && level < 10 {
  595. dst = append(dst, `"v":`...)
  596. dst = append(dst, '0'+byte(level))
  597. dst = append(dst, ',')
  598. }
  599. return dst
  600. }
  601. // appendText appends a raw text message in the Tailscale JSON log entry format.
  602. func (l *Logger) appendText(dst, src []byte, skipClientTime bool, procID uint32, procSequence uint64, level int) []byte {
  603. dst = slices.Grow(dst, len(src))
  604. dst = append(dst, '{')
  605. dst = l.appendMetadata(dst, skipClientTime, false, procID, procSequence, "", nil, level)
  606. if len(src) == 0 {
  607. dst = bytes.TrimRight(dst, ",")
  608. return append(dst, "}\n"...)
  609. }
  610. // Append the text string, which may be truncated.
  611. // Invalid UTF-8 will be mangled with the Unicode replacement character.
  612. max := maxTextSize
  613. if l.lowMem {
  614. max /= lowMemRatio
  615. }
  616. dst = append(dst, `"text":`...)
  617. dst = appendTruncatedString(dst, src, max)
  618. return append(dst, "}\n"...)
  619. }
  620. // appendTruncatedString appends a JSON string for src,
  621. // truncating the src to be no larger than n.
  622. func appendTruncatedString(dst, src []byte, n int) []byte {
  623. srcLen := len(src)
  624. src = truncate.String(src, n)
  625. dst, _ = jsontext.AppendQuote(dst, src) // ignore error; only occurs for invalid UTF-8
  626. if srcLen > len(src) {
  627. dst = dst[:len(dst)-len(`"`)] // trim off preceding double-quote
  628. dst = append(dst, "…+"...)
  629. dst = strconv.AppendInt(dst, int64(srcLen-len(src)), 10)
  630. dst = append(dst, '"') // re-append succeeding double-quote
  631. }
  632. return dst
  633. }
  634. func (l *Logger) AppendTextOrJSONLocked(dst, src []byte) []byte {
  635. l.clock = tstime.StdClock{}
  636. return l.appendTextOrJSONLocked(dst, src, 0)
  637. }
  638. // appendTextOrJSONLocked appends a raw text message or a raw JSON object
  639. // in the Tailscale JSON log format.
  640. func (l *Logger) appendTextOrJSONLocked(dst, src []byte, level int) []byte {
  641. if l.includeProcSequence {
  642. l.procSequence++
  643. }
  644. if len(src) == 0 || src[0] != '{' {
  645. return l.appendText(dst, src, l.skipClientTime, l.procID, l.procSequence, level)
  646. }
  647. // Check whether the input is a valid JSON object and
  648. // whether it contains the reserved "logtail" name at the top-level.
  649. var logtailKeyOffset, logtailValOffset, logtailValLength int
  650. validJSON := func() bool {
  651. // TODO(dsnet): Avoid allocation of bytes.Buffer struct.
  652. dec := &l.jsonDec
  653. dec.Reset(bytes.NewBuffer(src))
  654. if tok, err := dec.ReadToken(); tok.Kind() != '{' || err != nil {
  655. return false
  656. }
  657. for dec.PeekKind() != '}' {
  658. keyOffset := dec.InputOffset()
  659. tok, err := dec.ReadToken()
  660. if err != nil {
  661. return false
  662. }
  663. isLogtail := tok.String() == "logtail"
  664. valOffset := dec.InputOffset()
  665. if dec.SkipValue() != nil {
  666. return false
  667. }
  668. if isLogtail {
  669. logtailKeyOffset = int(keyOffset)
  670. logtailValOffset = int(valOffset)
  671. logtailValLength = int(dec.InputOffset()) - logtailValOffset
  672. }
  673. }
  674. if tok, err := dec.ReadToken(); tok.Kind() != '}' || err != nil {
  675. return false
  676. }
  677. if _, err := dec.ReadToken(); err != io.EOF {
  678. return false // trailing junk after JSON object
  679. }
  680. return true
  681. }()
  682. // Treat invalid JSON as a raw text message.
  683. if !validJSON {
  684. return l.appendText(dst, src, l.skipClientTime, l.procID, l.procSequence, level)
  685. }
  686. // Check whether the JSON payload is too large.
  687. // Due to logtail metadata, the formatted log entry could exceed maxSize.
  688. // That's okay as the Tailscale log service limit is actually 2*maxSize.
  689. // However, so long as logging applications aim to target the maxSize limit,
  690. // there should be no trouble eventually uploading logs.
  691. if len(src) > maxSize {
  692. errDetail := fmt.Sprintf("entry too large: %d bytes", len(src))
  693. errData := appendTruncatedString(nil, src, maxSize/len(`\uffff`)) // escaping could increase size
  694. dst = append(dst, '{')
  695. dst = l.appendMetadata(dst, l.skipClientTime, true, l.procID, l.procSequence, errDetail, errData, level)
  696. dst = bytes.TrimRight(dst, ",")
  697. return append(dst, "}\n"...)
  698. }
  699. // Check whether the reserved logtail member occurs in the log data.
  700. // If so, it is moved to the the logtail/error member.
  701. const jsonSeperators = ",:" // per RFC 8259, section 2
  702. const jsonWhitespace = " \n\r\t" // per RFC 8259, section 2
  703. var errDetail string
  704. var errData jsontext.Value
  705. if logtailValLength > 0 {
  706. errDetail = "duplicate logtail member"
  707. errData = bytes.Trim(src[logtailValOffset:][:logtailValLength], jsonSeperators+jsonWhitespace)
  708. }
  709. dst = slices.Grow(dst, len(src))
  710. dst = append(dst, '{')
  711. dst = l.appendMetadata(dst, l.skipClientTime, true, l.procID, l.procSequence, errDetail, errData, level)
  712. if logtailValLength > 0 {
  713. // Exclude original logtail member from the message.
  714. dst = appendWithoutNewline(dst, src[len("{"):logtailKeyOffset])
  715. dst = bytes.TrimRight(dst, jsonSeperators+jsonWhitespace)
  716. dst = appendWithoutNewline(dst, src[logtailValOffset+logtailValLength:])
  717. } else {
  718. dst = appendWithoutNewline(dst, src[len("{"):])
  719. }
  720. dst = bytes.TrimRight(dst, jsonWhitespace)
  721. dst = dst[:len(dst)-len("}")]
  722. dst = bytes.TrimRight(dst, jsonSeperators+jsonWhitespace)
  723. return append(dst, "}\n"...)
  724. }
  725. // appendWithoutNewline appends src to dst except that it ignores newlines
  726. // since newlines are used to frame individual log entries.
  727. func appendWithoutNewline(dst, src []byte) []byte {
  728. for _, c := range src {
  729. if c != '\n' {
  730. dst = append(dst, c)
  731. }
  732. }
  733. return dst
  734. }
  735. // Logf logs to l using the provided fmt-style format and optional arguments.
  736. func (l *Logger) Logf(format string, args ...any) {
  737. fmt.Fprintf(l, format, args...)
  738. }
  739. var obscureIPs = envknob.RegisterBool("TS_OBSCURE_LOGGED_IPS")
  740. // Write logs an encoded JSON blob.
  741. //
  742. // If the []byte passed to Write is not an encoded JSON blob,
  743. // then contents is fit into a JSON blob and written.
  744. //
  745. // This is intended as an interface for the stdlib "log" package.
  746. func (l *Logger) Write(buf []byte) (int, error) {
  747. if len(buf) == 0 {
  748. return 0, nil
  749. }
  750. inLen := len(buf) // length as provided to us, before modifications to downstream writers
  751. level, buf := parseAndRemoveLogLevel(buf)
  752. if l.stderr != nil && l.stderr != io.Discard && int64(level) <= atomic.LoadInt64(&l.stderrLevel) {
  753. if buf[len(buf)-1] == '\n' {
  754. l.stderr.Write(buf)
  755. } else {
  756. // The log package always line-terminates logs,
  757. // so this is an uncommon path.
  758. withNL := append(buf[:len(buf):len(buf)], '\n')
  759. l.stderr.Write(withNL)
  760. }
  761. }
  762. if obscureIPs() {
  763. buf = redactIPs(buf)
  764. }
  765. l.writeLock.Lock()
  766. defer l.writeLock.Unlock()
  767. b := l.appendTextOrJSONLocked(l.writeBuf[:0], buf, level)
  768. _, err := l.sendLocked(b)
  769. return inLen, err
  770. }
  771. var (
  772. regexMatchesIPv6 = regexp.MustCompile(`([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4}):([0-9a-fA-F:]{1,4})*`)
  773. regexMatchesIPv4 = regexp.MustCompile(`(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}`)
  774. )
  775. // redactIPs is a helper function used in Write() to redact IPs (other than tailscale IPs).
  776. // This function takes a log line as a byte slice and
  777. // uses regex matching to parse and find IP addresses. Based on if the IP address is IPv4 or
  778. // IPv6, it parses and replaces the end of the addresses with an "x". This function returns the
  779. // log line with the IPs redacted.
  780. func redactIPs(buf []byte) []byte {
  781. out := regexMatchesIPv6.ReplaceAllFunc(buf, func(b []byte) []byte {
  782. ip, err := netip.ParseAddr(string(b))
  783. if err != nil || tsaddr.IsTailscaleIP(ip) {
  784. return b // don't change this one
  785. }
  786. prefix := bytes.Split(b, []byte(":"))
  787. return bytes.Join(append(prefix[:2], []byte("x")), []byte(":"))
  788. })
  789. out = regexMatchesIPv4.ReplaceAllFunc(out, func(b []byte) []byte {
  790. ip, err := netip.ParseAddr(string(b))
  791. if err != nil || tsaddr.IsTailscaleIP(ip) {
  792. return b // don't change this one
  793. }
  794. prefix := bytes.Split(b, []byte("."))
  795. return bytes.Join(append(prefix[:2], []byte("x.x")), []byte("."))
  796. })
  797. return []byte(out)
  798. }
  799. var (
  800. openBracketV = []byte("[v")
  801. v1 = []byte("[v1] ")
  802. v2 = []byte("[v2] ")
  803. vJSON = []byte("[v\x00JSON]") // precedes log level '0'-'9' byte, then JSON value
  804. )
  805. // level 0 is normal (or unknown) level; 1+ are increasingly verbose
  806. func parseAndRemoveLogLevel(buf []byte) (level int, cleanBuf []byte) {
  807. if len(buf) == 0 || buf[0] == '{' || !bytes.Contains(buf, openBracketV) {
  808. return 0, buf
  809. }
  810. if bytes.Contains(buf, v1) {
  811. return 1, bytes.ReplaceAll(buf, v1, nil)
  812. }
  813. if bytes.Contains(buf, v2) {
  814. return 2, bytes.ReplaceAll(buf, v2, nil)
  815. }
  816. if i := bytes.Index(buf, vJSON); i != -1 {
  817. rest := buf[i+len(vJSON):]
  818. if len(rest) >= 2 {
  819. v := rest[0]
  820. if v >= '0' && v <= '9' {
  821. return int(v - '0'), rest[1:]
  822. }
  823. }
  824. }
  825. return 0, buf
  826. }
  827. var (
  828. tapSetSize atomic.Int32
  829. tapMu sync.Mutex
  830. tapSet set.HandleSet[chan<- string]
  831. )
  832. // RegisterLogTap registers dst to get a copy of every log write. The caller
  833. // must call unregister when done watching.
  834. //
  835. // This would ideally be a method on Logger, but Logger isn't really available
  836. // in most places; many writes go via stderr which filch redirects to the
  837. // singleton Logger set up early. For better or worse, there's basically only
  838. // one Logger within the program. This mechanism at least works well for
  839. // tailscaled. It works less well for a binary with multiple tsnet.Servers. Oh
  840. // well. This then subscribes to all of them.
  841. func RegisterLogTap(dst chan<- string) (unregister func()) {
  842. tapMu.Lock()
  843. defer tapMu.Unlock()
  844. h := tapSet.Add(dst)
  845. tapSetSize.Store(int32(len(tapSet)))
  846. return func() {
  847. tapMu.Lock()
  848. defer tapMu.Unlock()
  849. delete(tapSet, h)
  850. tapSetSize.Store(int32(len(tapSet)))
  851. }
  852. }
  853. // tapSend relays the JSON blob to any/all registered local debug log watchers
  854. // (somebody running "tailscale debug daemon-logs").
  855. func tapSend(jsonBlob []byte) {
  856. if tapSetSize.Load() == 0 {
  857. return
  858. }
  859. s := string(jsonBlob)
  860. tapMu.Lock()
  861. defer tapMu.Unlock()
  862. for _, dst := range tapSet {
  863. select {
  864. case dst <- s:
  865. default:
  866. }
  867. }
  868. }