Debian Codegraph @

server/msgtrace.go

raw
1 // Copyright 2024-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "encoding/json"
19 "fmt"
20 "math/rand"
21 "strconv"
22 "strings"
23 "sync"
24 "sync/atomic"
25 "time"
26 )
27
28 const (
29 MsgTraceDest = "Nats-Trace-Dest"
30 MsgTraceDestDisabled = "trace disabled" // This must be an invalid NATS subject
31 MsgTraceHop = "Nats-Trace-Hop"
32 MsgTraceOriginAccount = "Nats-Trace-Origin-Account"
33 MsgTraceOnly = "Nats-Trace-Only"
34
35 // External trace header. Note that this header is normally in lower
36 // case (https://www.w3.org/TR/trace-context/#header-name). Vendors
37 // MUST expect the header in any case (upper, lower, mixed), and
38 // SHOULD send the header name in lowercase. We used to change it
39 // to lower case, but no longer do that in 2.14.
40 traceParentHdr = "traceparent"
41 )
42
43 var (
44 traceDestHdrAsBytes = stringToBytes(MsgTraceDest)
45 traceDestDisabledAsBytes = stringToBytes(MsgTraceDestDisabled)
46 traceParentHdrAsBytes = stringToBytes(traceParentHdr)
47 crLFAsBytes = stringToBytes(CR_LF)
48 dashAsBytes = stringToBytes("-")
49 )
50
51 type MsgTraceType string
52
53 // Type of message trace events in the MsgTraceEvents list.
54 // This is needed to unmarshal the list.
55 const (
56 MsgTraceIngressType = "in"
57 MsgTraceSubjectMappingType = "sm"
58 MsgTraceStreamExportType = "se"
59 MsgTraceServiceImportType = "si"
60 MsgTraceJetStreamType = "js"
61 MsgTraceEgressType = "eg"
62 )
63
64 type MsgTraceEvent struct {
65 Server ServerInfo `json:"server"`
66 Request MsgTraceRequest `json:"request"`
67 Hops int `json:"hops,omitempty"`
68 Events MsgTraceEvents `json:"events"`
69 }
70
71 type MsgTraceRequest struct {
72 // We are not making this an http.Header so that header name case is preserved.
73 Header map[string][]string `json:"header,omitempty"`
74 MsgSize int `json:"msgsize,omitempty"`
75 }
76
77 type MsgTraceEvents []MsgTrace
78
79 type MsgTrace interface {
80 new() MsgTrace
81 typ() MsgTraceType
82 }
83
84 type MsgTraceBase struct {
85 Type MsgTraceType `json:"type"`
86 Timestamp time.Time `json:"ts"`
87 }
88
89 type MsgTraceIngress struct {
90 MsgTraceBase
91 Kind int `json:"kind"`
92 CID uint64 `json:"cid"`
93 Name string `json:"name,omitempty"`
94 Account string `json:"acc"`
95 Subject string `json:"subj"`
96 Error string `json:"error,omitempty"`
97 }
98
99 type MsgTraceSubjectMapping struct {
100 MsgTraceBase
101 MappedTo string `json:"to"`
102 }
103
104 type MsgTraceStreamExport struct {
105 MsgTraceBase
106 Account string `json:"acc"`
107 To string `json:"to"`
108 }
109
110 type MsgTraceServiceImport struct {
111 MsgTraceBase
112 Account string `json:"acc"`
113 From string `json:"from"`
114 To string `json:"to"`
115 }
116
117 type MsgTraceJetStream struct {
118 MsgTraceBase
119 Stream string `json:"stream"`
120 Subject string `json:"subject,omitempty"`
121 NoInterest bool `json:"nointerest,omitempty"`
122 Error string `json:"error,omitempty"`
123 }
124
125 type MsgTraceEgress struct {
126 MsgTraceBase
127 Kind int `json:"kind"`
128 CID uint64 `json:"cid"`
129 Name string `json:"name,omitempty"`
130 Hop string `json:"hop,omitempty"`
131 Account string `json:"acc,omitempty"`
132 Subscription string `json:"sub,omitempty"`
133 Queue string `json:"queue,omitempty"`
134 Error string `json:"error,omitempty"`
135
136 // This is for applications that unmarshal the trace events
137 // and want to link an egress to route/leaf/gateway with
138 // the MsgTraceEvent from that server.
139 Link *MsgTraceEvent `json:"-"`
140 }
141
142 // -------------------------------------------------------------
143
144 func (t MsgTraceBase) typ() MsgTraceType { return t.Type }
145 func (MsgTraceIngress) new() MsgTrace { return &MsgTraceIngress{} }
146 func (MsgTraceSubjectMapping) new() MsgTrace { return &MsgTraceSubjectMapping{} }
147 func (MsgTraceStreamExport) new() MsgTrace { return &MsgTraceStreamExport{} }
148 func (MsgTraceServiceImport) new() MsgTrace { return &MsgTraceServiceImport{} }
149 func (MsgTraceJetStream) new() MsgTrace { return &MsgTraceJetStream{} }
150 func (MsgTraceEgress) new() MsgTrace { return &MsgTraceEgress{} }
151
152 var msgTraceInterfaces = map[MsgTraceType]MsgTrace{
153 MsgTraceIngressType: MsgTraceIngress{},
154 MsgTraceSubjectMappingType: MsgTraceSubjectMapping{},
155 MsgTraceStreamExportType: MsgTraceStreamExport{},
156 MsgTraceServiceImportType: MsgTraceServiceImport{},
157 MsgTraceJetStreamType: MsgTraceJetStream{},
158 MsgTraceEgressType: MsgTraceEgress{},
159 }
160
161 func (t *MsgTraceEvents) UnmarshalJSON(data []byte) error {
162 var raw []json.RawMessage
163 err := json.Unmarshal(data, &raw)
164 if err != nil {
165 return err
166 }
167 *t = make(MsgTraceEvents, len(raw))
168 var tt MsgTraceBase
169 for i, r := range raw {
170 if err = json.Unmarshal(r, &tt); err != nil {
171 return err
172 }
173 tr, ok := msgTraceInterfaces[tt.Type]
174 if !ok {
175 return fmt.Errorf("unknown trace type %v", tt.Type)
176 }
177 te := tr.new()
178 if err := json.Unmarshal(r, te); err != nil {
179 return err
180 }
181 (*t)[i] = te
182 }
183 return nil
184 }
185
186 func getTraceAs[T MsgTrace](e any) *T {
187 v, ok := e.(*T)
188 if ok {
189 return v
190 }
191 return nil
192 }
193
194 func (t *MsgTraceEvent) Ingress() *MsgTraceIngress {
195 if len(t.Events) < 1 {
196 return nil
197 }
198 return getTraceAs[MsgTraceIngress](t.Events[0])
199 }
200
201 func (t *MsgTraceEvent) SubjectMapping() *MsgTraceSubjectMapping {
202 for _, e := range t.Events {
203 if e.typ() == MsgTraceSubjectMappingType {
204 return getTraceAs[MsgTraceSubjectMapping](e)
205 }
206 }
207 return nil
208 }
209
210 func (t *MsgTraceEvent) StreamExports() []*MsgTraceStreamExport {
211 var se []*MsgTraceStreamExport
212 for _, e := range t.Events {
213 if e.typ() == MsgTraceStreamExportType {
214 se = append(se, getTraceAs[MsgTraceStreamExport](e))
215 }
216 }
217 return se
218 }
219
220 func (t *MsgTraceEvent) ServiceImports() []*MsgTraceServiceImport {
221 var si []*MsgTraceServiceImport
222 for _, e := range t.Events {
223 if e.typ() == MsgTraceServiceImportType {
224 si = append(si, getTraceAs[MsgTraceServiceImport](e))
225 }
226 }
227 return si
228 }
229
230 func (t *MsgTraceEvent) JetStream() *MsgTraceJetStream {
231 for _, e := range t.Events {
232 if e.typ() == MsgTraceJetStreamType {
233 return getTraceAs[MsgTraceJetStream](e)
234 }
235 }
236 return nil
237 }
238
239 func (t *MsgTraceEvent) Egresses() []*MsgTraceEgress {
240 var eg []*MsgTraceEgress
241 for _, e := range t.Events {
242 if e.typ() == MsgTraceEgressType {
243 eg = append(eg, getTraceAs[MsgTraceEgress](e))
244 }
245 }
246 return eg
247 }
248
249 const (
250 errMsgTraceOnlyNoSupport = "Not delivered because remote does not support message tracing"
251 errMsgTraceNoSupport = "Message delivered but remote does not support message tracing so no trace event generated from there"
252 errMsgTraceNoEcho = "Not delivered because of no echo"
253 errMsgTracePubViolation = "Not delivered because publish denied for this subject"
254 errMsgTraceSubDeny = "Not delivered because subscription denies this subject"
255 errMsgTraceSubClosed = "Not delivered because subscription is closed"
256 errMsgTraceClientClosed = "Not delivered because client is closed"
257 errMsgTraceAutoSubExceeded = "Not delivered because auto-unsubscribe exceeded"
258 errMsgTraceFastProdNoStall = "Not delivered because fast producer not stalled and consumer is slow"
259 )
260
261 type msgTrace struct {
262 kind int
263 ready int32
264 srv *Server
265 acc *Account
266 dest string
267 event *MsgTraceEvent
268 js *MsgTraceJetStream
269 siMu sync.RWMutex
270 si []*msgTraceServiceImport
271 rsi *msgTraceRespServiceImport
272 hop string
273 nhop string
274 tonly bool // Will only trace the message, not do delivery.
275 ct compressionType
276 }
277
278 type msgTraceServiceImport struct {
279 si *serviceImport
280 acc *Account
281 }
282
283 type msgTraceRespServiceImport struct {
284 hops int
285 received int
286 tree map[string]*msgTraceRespServiceImport
287 }
288
289 // This will be false outside of the tests, so when building the server binary,
290 // any code where you see `if msgTraceRunInTests` statement will be compiled
291 // out, so this will have no performance penalty.
292 var (
293 msgTraceRunInTests bool
294 msgTraceCheckSupport bool
295 )
296
297 // Returns the message trace object, if message is being traced,
298 // and `true` if we want to only trace, not actually deliver the message.
299 func (c *client) isMsgTraceEnabled() (*msgTrace, bool) {
300 t := c.pa.trace
301 if t == nil {
302 return nil, false
303 }
304 return t, t.tonly
305 }
306
307 // For LEAF/ROUTER/GATEWAY, return false if the remote does not support
308 // message tracing (important if the tracing requests trace-only).
309 func (c *client) msgTraceSupport() bool {
310 // Exclude client connection from the protocol check.
311 return c.kind == CLIENT || c.opts.Protocol >= MsgTraceProto
312 }
313
314 func getConnName(c *client) string {
315 switch c.kind {
316 case ROUTER:
317 if n := c.route.remoteName; n != _EMPTY_ {
318 return n
319 }
320 case GATEWAY:
321 if n := c.gw.remoteName; n != _EMPTY_ {
322 return n
323 }
324 case LEAF:
325 if n := c.leaf.remoteServer; n != _EMPTY_ {
326 return n
327 }
328 }
329 return c.opts.Name
330 }
331
332 func getCompressionType(cts string) compressionType {
333 if cts == _EMPTY_ {
334 return noCompression
335 }
336 cts = strings.ToLower(cts)
337 if strings.Contains(cts, "snappy") || strings.Contains(cts, "s2") {
338 return snappyCompression
339 }
340 if strings.Contains(cts, "gzip") {
341 return gzipCompression
342 }
343 return unsupportedCompression
344 }
345
346 // Possibly initialize message tracing if appropriate headers are found in the
347 // given `hdr` byte slice.
348 // If there is an error and the header `MsgTraceOnly` is set to `true` (indicating
349 // that it should be a "trace only" message, without message delivery), then this
350 // function will return `true, nil`, so that the caller can skip message processing.
351 func (c *client) initMsgTrace(hdr []byte, ingressError error) (bool, *msgTrace) {
352 // The code in the "if" statement is only running in test mode.
353 if msgTraceRunInTests {
354 // Check the type of client that tries to initialize a trace struct.
355 if !(c.kind == CLIENT || c.kind == ROUTER || c.kind == GATEWAY || c.kind == LEAF) {
356 panic(fmt.Sprintf("Unexpected client type %q trying to initialize msgTrace", c.kindString()))
357 }
358 // In some tests, we want to make a server behave like an old server
359 // and so even if a trace header is received, we want the server to
360 // simply ignore it.
361 if msgTraceCheckSupport {
362 if c.srv == nil || c.srv.getServerProto() < MsgTraceProto {
363 return false, nil
364 }
365 }
366 }
367 // Get the headers if we find `Nats-Trace-Dest` or `traceparent` header.
368 // For `traceparent`, `external` will be true indicating that we need
369 // to get the destination and sampling from the account.
370 headers, external := genHeaderMapIfTraceHeadersPresent(hdr)
371 if len(headers) == 0 {
372 return false, nil
373 }
374 // Little helper to give us the first value of a given header, or _EMPTY_
375 // if key is not present.
376 getHdrVal := func(key string) string {
377 vv, ok := headers[key]
378 if !ok {
379 return _EMPTY_
380 }
381 return vv[0]
382 }
383 var (
384 dest string // The destination the trace message should be sent to
385 traceOnly bool // True if this is "trace only" and no message delivery should occur
386 hop string // The hop "id", taken from headers only when not from CLIENT
387 kind = c.kind // The type of connection this originates from
388 )
389 // Check for traceOnly only if not external.
390 if !external {
391 if to := getHdrVal(MsgTraceOnly); to != _EMPTY_ {
392 tos := strings.ToLower(to)
393 switch tos {
394 case "1", "true", "on":
395 traceOnly = true
396 }
397 }
398 dest = getHdrVal(MsgTraceDest)
399 // If no dest, bail out.
400 if dest == _EMPTY_ {
401 return traceOnly, nil
402 }
403 }
404 // Now that we know if there is `traceOnly` set or not, if we were to fail
405 // here by returning `nil` for `*msgTrace`, we will return `true, nil` to
406 // indicate to the caller that it should skip message processing (so that
407 // the failed trace message is not delivered to regular subscriptions).
408
409 // First, disable tracing if the message contains the old MsgTraceOriginAccount header.
410 if v := getHdrVal(MsgTraceOriginAccount); v != _EMPTY_ {
411 c.Errorf("Message tracing disabled because of header %q with value=%q",
412 MsgTraceOriginAccount, v)
413 // Skip this if we are invoked with ingressError, or if we are going to skip
414 // message processing anyway (if `traceOnly` is true).
415 if ingressError == nil && !traceOnly {
416 // Disable tracing by changing the `MsgTraceDest` header to `MsgTraceDestDisabled`.
417 c.msgBuf = c.setHeader(MsgTraceDest, MsgTraceDestDisabled, c.msgBuf)
418 }
419 // If `traceOnly` is false, the message will be delivered and possibly routed,
420 // but it will not be traced. If it is `true`, then there will be no tracing
421 // and the message will not be processed (so no chance to be routed).
422 return traceOnly, nil
423 }
424
425 // Get the account and server.
426 c.mu.Lock()
427 acc := c.acc
428 srv := c.srv
429 c.mu.Unlock()
430 // There should always be a server object, and for CLIENT and LEAF, the
431 // account should be available.
432 if srv == nil || (acc == nil && (kind == CLIENT || kind == LEAF)) {
433 // Make the caller skip message procesing if `traceOnly` is true.
434 return traceOnly, nil
435 }
436 // For non CLIENT connection, get the account and hop header.
437 if kind != CLIENT {
438 hop = getHdrVal(MsgTraceHop)
439 if kind != LEAF {
440 // Lookup the account, if not present, bail out.
441 if acci, ok := c.srv.accounts.Load(string(c.pa.account)); ok {
442 acc = acci.(*Account)
443 } else {
444 c.Errorf("Account %q was not found, won't be able to trace events", c.pa.account)
445 return traceOnly, nil
446 }
447 }
448 }
449 // If external, we need to have the account's trace destination set,
450 // otherwise, we are not enabling tracing.
451 if external {
452 var sampling int
453 dest, sampling = acc.getTraceDestAndSampling()
454 if dest == _EMPTY_ {
455 // No account destination, no tracing for external trace headers.
456 // This is not an error, so return false so that we don't skip
457 // message processing.
458 return false, nil
459 }
460 // Check sampling, but only from origin server.
461 if kind == CLIENT && !sample(sampling) {
462 // Need to disable tracing so that if the message is routed, it won't
463 // trigger a trace there. Skip this if we have an ingress error.
464 if ingressError == nil {
465 c.msgBuf = c.setHeader(MsgTraceDest, MsgTraceDestDisabled, c.msgBuf)
466 }
467 return false, nil
468 }
469 }
470 // Check the destination to see if this is a valid publish subject.
471 if !IsValidPublishSubject(dest) {
472 c.Errorf("Destination %q is not valid, won't be able to trace events", dest)
473 // Return `traceOnly` to cause the caller to skip message processing if
474 // this was supposed to be a trace only message.
475 return traceOnly, nil
476 }
477 // Now that we have a valid `dest`, make sure this connection is allowed
478 // to publish to it.
479 if !c.allowedToPublishOnMsgTraceDest(srv, acc, dest) {
480 // Send the error back only if CLIENT or LEAF, otherwise just log.
481 if kind == CLIENT || kind == LEAF {
482 c.pubPermissionViolation(stringToBytes(dest))
483 } else {
484 c.Errorf("Publish Violation - Subject %q", dest)
485 }
486 // Return `true, nil` to force skipping of message processing.
487 return true, nil
488 }
489 c.pa.trace = &msgTrace{
490 kind: kind,
491 srv: c.srv,
492 acc: acc,
493 dest: dest,
494 ct: getCompressionType(getHdrVal(acceptEncodingHeader)),
495 hop: hop,
496 event: &MsgTraceEvent{
497 Request: MsgTraceRequest{
498 Header: headers,
499 MsgSize: c.pa.size,
500 },
501 Events: append(MsgTraceEvents(nil), &MsgTraceIngress{
502 MsgTraceBase: MsgTraceBase{
503 Type: MsgTraceIngressType,
504 Timestamp: time.Now(),
505 },
506 Kind: kind,
507 CID: c.cid,
508 Name: getConnName(c),
509 Account: acc.GetName(),
510 Subject: string(c.pa.subject),
511 }),
512 },
513 tonly: traceOnly,
514 }
515 // If we are invoked with an ingress error, set it now.
516 if ingressError != nil {
517 c.pa.trace.event.Events[0].(*MsgTraceIngress).Error = ingressError.Error()
518 }
519 return false, c.pa.trace
520 }
521
522 func (c *client) allowedToPublishOnMsgTraceDest(s *Server, acc *Account, dest string) bool {
523 td := stringToBytes(dest)
524 if hasGWRoutedReplyPrefix(td) {
525 return false
526 }
527 if bytes.HasPrefix(td, clientNRGPrefix) && acc != s.SystemAccount() {
528 return false
529 }
530 allowed := true
531 c.mu.Lock()
532 if c.kind == LEAF {
533 if c.isSpokeLeafNode() {
534 allowed = c.leafReceiveAllowed(td)
535 } else {
536 allowed = c.leafSendAllowed(td)
537 }
538 } else if c.perms != nil && (c.perms.pub.allow != nil || c.perms.pub.deny != nil) && !c.pubAllowedFullCheck(dest, false, true) {
539 allowed = false
540 }
541 c.mu.Unlock()
542 return allowed
543 }
544
545 func sample(sampling int) bool {
546 // Option parsing should ensure that sampling is [1..100], but consider
547 // any value outside of this range to be 100%.
548 if sampling <= 0 || sampling >= 100 {
549 return true
550 }
551 return rand.Int31n(100) <= int32(sampling)
552 }
553
554 // This function will return the header as a map (instead of http.Header because
555 // we want to preserve the header names' case) and a boolean that indicates if
556 // the headers have been lifted due to the presence of the external trace header
557 // only.
558 // Note that because of the traceParentHdr, the search is done in a case
559 // insensitive way. We used to rewrite it in lower case but no longer do since v2.14.
560 func genHeaderMapIfTraceHeadersPresent(hdr []byte) (map[string][]string, bool) {
561
562 var (
563 _keys = [64][]byte{}
564 _vals = [64][]byte{}
565 m map[string][]string
566 traceDestHdrFound bool
567 traceParentHdrFound bool
568 )
569 // Skip the hdrLine
570 if !bytes.HasPrefix(hdr, stringToBytes(hdrLine)) {
571 return nil, false
572 }
573
574 keys := _keys[:0]
575 vals := _vals[:0]
576
577 for i := len(hdrLine); i < len(hdr); {
578 // Search for key/val delimiter
579 del := bytes.IndexByte(hdr[i:], ':')
580 if del < 0 {
581 break
582 }
583 keyStart := i
584 key := hdr[keyStart : keyStart+del]
585 i += del + 1
586 for i < len(hdr) && (hdr[i] == ' ' || hdr[i] == '\t') {
587 i++
588 }
589 valStart := i
590 nl := bytes.Index(hdr[valStart:], crLFAsBytes)
591 if nl < 0 {
592 break
593 }
594 valEnd := valStart + nl
595 for valEnd > valStart && (hdr[valEnd-1] == ' ' || hdr[valEnd-1] == '\t') {
596 valEnd--
597 }
598 val := hdr[valStart:valEnd]
599 if len(key) > 0 && len(val) > 0 {
600 vals = append(vals, val)
601
602 // We search for our special keys only if not already found.
603
604 // Check for the external trace header.
605 // Search needs to be case insensitive.
606 if !traceParentHdrFound && bytes.EqualFold(key, traceParentHdrAsBytes) {
607 // We will now check if the value has sampling or not.
608 // TODO(ik): Not sure if this header can have multiple values
609 // or not, and if so, what would be the rule to check for
610 // sampling. What is done here is to check them all until we
611 // found one with sampling.
612 tk := bytes.Split(val, dashAsBytes)
613 if len(tk) == 4 && len([]byte(tk[3])) == 2 {
614 if hexVal, err := strconv.ParseInt(bytesToString(tk[3]), 16, 8); err == nil {
615 if hexVal&0x1 == 0x1 {
616 traceParentHdrFound = true
617 }
618 }
619 }
620 } else if !traceDestHdrFound && bytes.Equal(key, traceDestHdrAsBytes) {
621 // This is the Nats-Trace-Dest header, check the value to see
622 // if it indicates that the trace was disabled.
623 if bytes.Equal(val, traceDestDisabledAsBytes) {
624 return nil, false
625 }
626 traceDestHdrFound = true
627 }
628 // Add to the keys and preserve the key's case
629 keys = append(keys, key)
630 }
631 i += nl + 2
632 }
633 if !traceDestHdrFound && !traceParentHdrFound {
634 return nil, false
635 }
636 m = make(map[string][]string, len(keys))
637 for i, k := range keys {
638 hname := string(k)
639 m[hname] = append(m[hname], string(vals[i]))
640 }
641 return m, !traceDestHdrFound && traceParentHdrFound
642 }
643
644 // Special case where we create a trace event before parsing the message.
645 // This is for cases where the connection will be closed when detecting
646 // an error during early message processing (for instance max payload).
647 func (c *client) sendMsgTraceIngressErrEvent(hdr []byte, ingressError error) {
648 if ingressError == nil {
649 return
650 }
651 if _, t := c.initMsgTrace(hdr, ingressError); t != nil {
652 t.sendEvent()
653 }
654 }
655
656 // Returns `true` if message tracing is enabled and we are tracing only,
657 // that is, we are not going to deliver the inbound message, returns
658 // `false` otherwise (no tracing, or tracing and message delivery).
659 func (t *msgTrace) traceOnly() bool {
660 return t != nil && t.tonly
661 }
662
663 func (t *msgTrace) setHopHeader(c *client, msg []byte) []byte {
664 e := t.event
665 e.Hops++
666 if len(t.hop) > 0 {
667 t.nhop = fmt.Sprintf("%s.%d", t.hop, e.Hops)
668 } else {
669 t.nhop = fmt.Sprintf("%d", e.Hops)
670 }
671 if t.kind == CLIENT && strings.HasPrefix(t.dest, replyPrefix) {
672 t.siMu.Lock()
673 if t.rsi == nil {
674 t.rsi = &msgTraceRespServiceImport{}
675 }
676 t.rsi.hops++
677 t.siMu.Unlock()
678 }
679 return c.setHeader(MsgTraceHop, t.nhop, msg)
680 }
681
682 func (t *msgTrace) setIngressError(err string) {
683 if i := t.event.Ingress(); i != nil {
684 i.Error = err
685 }
686 }
687
688 func (t *msgTrace) addSubjectMappingEvent(subj []byte) {
689 if t == nil {
690 return
691 }
692 t.event.Events = append(t.event.Events, &MsgTraceSubjectMapping{
693 MsgTraceBase: MsgTraceBase{
694 Type: MsgTraceSubjectMappingType,
695 Timestamp: time.Now(),
696 },
697 MappedTo: string(subj),
698 })
699 }
700
701 func (t *msgTrace) addEgressEvent(dc *client, sub *subscription, err string) {
702 if t == nil {
703 return
704 }
705 e := &MsgTraceEgress{
706 MsgTraceBase: MsgTraceBase{
707 Type: MsgTraceEgressType,
708 Timestamp: time.Now(),
709 },
710 Kind: dc.kind,
711 CID: dc.cid,
712 Name: getConnName(dc),
713 Hop: t.nhop,
714 Error: err,
715 }
716 t.nhop = _EMPTY_
717 // Specific to CLIENT connections...
718 if dc.kind == CLIENT {
719 // Set the subscription's subject and possibly queue name.
720 e.Subscription = string(sub.subject)
721 if len(sub.queue) > 0 {
722 e.Queue = string(sub.queue)
723 }
724 }
725 if dc.kind == CLIENT || dc.kind == LEAF {
726 if i := t.event.Ingress(); i != nil {
727 // If the Ingress' account is different from the destination's
728 // account, add the account name into the Egress trace event.
729 // This would happen with service imports.
730 if dcAccName := dc.acc.GetName(); dcAccName != i.Account {
731 e.Account = dcAccName
732 }
733 }
734 }
735 t.event.Events = append(t.event.Events, e)
736 }
737
738 func (t *msgTrace) addStreamExportEvent(dc *client, to []byte) {
739 if t == nil {
740 return
741 }
742 dc.mu.Lock()
743 accName := dc.acc.GetName()
744 dc.mu.Unlock()
745 t.event.Events = append(t.event.Events, &MsgTraceStreamExport{
746 MsgTraceBase: MsgTraceBase{
747 Type: MsgTraceStreamExportType,
748 Timestamp: time.Now(),
749 },
750 Account: accName,
751 To: string(to),
752 })
753 }
754
755 func (t *msgTrace) addServiceImportEvent(accName, from, to string) {
756 if t == nil {
757 return
758 }
759 t.event.Events = append(t.event.Events, &MsgTraceServiceImport{
760 MsgTraceBase: MsgTraceBase{
761 Type: MsgTraceServiceImportType,
762 Timestamp: time.Now(),
763 },
764 Account: accName,
765 From: from,
766 To: to,
767 })
768 }
769
770 func (t *msgTrace) addJetStreamEvent(streamName string) {
771 if t == nil {
772 return
773 }
774 t.js = &MsgTraceJetStream{
775 MsgTraceBase: MsgTraceBase{
776 Type: MsgTraceJetStreamType,
777 Timestamp: time.Now(),
778 },
779 Stream: streamName,
780 }
781 t.event.Events = append(t.event.Events, t.js)
782 }
783
784 func (t *msgTrace) updateJetStreamEvent(subject string, noInterest bool) {
785 if t == nil {
786 return
787 }
788 // JetStream event should have been created in addJetStreamEvent
789 if t.js == nil {
790 return
791 }
792 t.js.Subject = subject
793 t.js.NoInterest = noInterest
794 // Update the timestamp since this is more accurate than when it
795 // was first added in addJetStreamEvent().
796 t.js.Timestamp = time.Now()
797 }
798
799 func (t *msgTrace) sendEventFromJetStream(err error) {
800 if t == nil {
801 return
802 }
803 // JetStream event should have been created in addJetStreamEvent
804 if t.js == nil {
805 return
806 }
807 if err != nil {
808 t.js.Error = err.Error()
809 }
810 t.sendEvent()
811 }
812
813 func (t *msgTrace) sendEvent() {
814 if t == nil {
815 return
816 }
817 if t.js != nil {
818 ready := atomic.AddInt32(&t.ready, 1) == 2
819 if !ready {
820 return
821 }
822 }
823 t.srv.sendInternalAccountSysMsg(t.acc, t.dest, &t.event.Server, t.event, t.ct)
824 }
825
826 func (t *msgTrace) setupResponseServiceImport(c *client, acc *Account, si *serviceImport, msg []byte) (*serviceImport, []byte) {
827 rsi := si.acc.addRespServiceImport(acc, t.dest, si, false, nil, t)
828 t.dest = rsi.from
829 t.siMu.Lock()
830 t.si = append(t.si, &msgTraceServiceImport{rsi, si.acc})
831 t.siMu.Unlock()
832 return rsi, c.setHeader(MsgTraceDest, t.dest, msg)
833 }
834
835 func (t *msgTrace) handleRespServiceImport(e *MsgTraceEvent) {
836 t.siMu.Lock()
837 defer t.siMu.Unlock()
838
839 // If response service import were created and routed for message traces,
840 // we should have t.rsi created. If it is not, we are done. Note that
841 // if for any reason we bail out because we are not in a state that we
842 // expect, the response service imports will be cleaned-up on a timer based.
843 if t.rsi == nil {
844 return
845 }
846 t.updateRespServiceImport(e)
847
848 if t.allRespServiceImportReceived(t.rsi) {
849 for _, rsi := range t.si {
850 rsi.acc.removeRespServiceImport(rsi.si, rsiOk)
851 }
852 t.rsi, t.si = nil, nil
853 }
854 }
855
856 // For a given trace message event, update the tree of response service import
857 // trace messages.
858 // Lock is held on entry.
859 func (t *msgTrace) updateRespServiceImport(e *MsgTraceEvent) {
860 // Check for the hop header.
861 hop, ok := e.Request.Header[MsgTraceHop]
862 if !ok || len(hop) != 1 {
863 return
864 }
865 hops := strings.Split(hop[0], ".")
866 prsi := t.rsi
867 for i, h := range hops {
868 rsi := prsi.tree[h]
869 if rsi == nil {
870 if prsi.tree == nil {
871 prsi.tree = make(map[string]*msgTraceRespServiceImport)
872 }
873 // Create an entry and initializes the hops count to -1. It will be set
874 // when receiving the corresponding trace message.
875 rsi = &msgTraceRespServiceImport{hops: -1}
876 // Bind it to the parent tree for this "hop" id.
877 prsi.tree[h] = rsi
878 }
879 // When dealing with the last section of the `hop` string, we set the
880 // expected hops count based on the event's `Hops` field and bump the number
881 // of received trace messages on the parent's node. We do this only once
882 // per event (use rsi.hops == -1 as the indicator).
883 if rsi.hops == -1 && i == len(hops)-1 {
884 rsi.hops = e.Hops
885 prsi.received++
886 }
887 prsi = rsi
888 }
889 }
890
891 // Determine if all response service import traces have been received.
892 // Lock held on entry.
893 func (t *msgTrace) allRespServiceImportReceived(prsi *msgTraceRespServiceImport) bool {
894 if prsi.hops != prsi.received {
895 return false
896 }
897 for _, rsi := range prsi.tree {
898 if !t.allRespServiceImportReceived(rsi) {
899 return false
900 }
901 }
902 return true
903 }