internal_txn.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. package newrelic
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "reflect"
  8. "sync"
  9. "time"
  10. "github.com/newrelic/go-agent/internal"
  11. )
  12. type txnInput struct {
  13. W http.ResponseWriter
  14. Config Config
  15. Reply *internal.ConnectReply
  16. Consumer dataConsumer
  17. attrConfig *internal.AttributeConfig
  18. }
  19. type txn struct {
  20. txnInput
  21. // This mutex is required since the consumer may call the public API
  22. // interface functions from different routines.
  23. sync.Mutex
  24. // finished indicates whether or not End() has been called. After
  25. // finished has been set to true, no recording should occur.
  26. finished bool
  27. numPayloadsCreated uint32
  28. ignore bool
  29. // wroteHeader prevents capturing multiple response code errors if the
  30. // user erroneously calls WriteHeader multiple times.
  31. wroteHeader bool
  32. internal.TxnData
  33. }
  34. func newTxn(input txnInput, req *http.Request, name string) *txn {
  35. txn := &txn{
  36. txnInput: input,
  37. }
  38. txn.Start = time.Now()
  39. txn.Name = name
  40. txn.IsWeb = nil != req
  41. txn.Attrs = internal.NewAttributes(input.attrConfig)
  42. if input.Config.DistributedTracer.Enabled {
  43. txn.BetterCAT.Enabled = true
  44. txn.BetterCAT.Priority = internal.NewPriority()
  45. txn.BetterCAT.ID = internal.NewSpanID()
  46. // Calculate sampled at the beginning of the transaction (rather
  47. // than lazily at payload creation time) because it controls the
  48. // creation of span events.
  49. txn.BetterCAT.Sampled = txn.Reply.AdaptiveSampler.ComputeSampled(txn.BetterCAT.Priority.Float32(), txn.Start)
  50. if txn.BetterCAT.Sampled {
  51. txn.BetterCAT.Priority += 1.0
  52. }
  53. txn.SpanEventsEnabled = input.Config.SpanEvents.Enabled
  54. }
  55. if nil != req {
  56. txn.Queuing = internal.QueueDuration(req.Header, txn.Start)
  57. internal.RequestAgentAttributes(txn.Attrs, req)
  58. }
  59. txn.Attrs.Agent.HostDisplayName = txn.Config.HostDisplayName
  60. txn.TxnTrace.Enabled = txn.txnTracesEnabled()
  61. txn.TxnTrace.SegmentThreshold = txn.Config.TransactionTracer.SegmentThreshold
  62. txn.StackTraceThreshold = txn.Config.TransactionTracer.StackTraceThreshold
  63. txn.SlowQueriesEnabled = txn.slowQueriesEnabled()
  64. txn.SlowQueryThreshold = txn.Config.DatastoreTracer.SlowQuery.Threshold
  65. if nil != req && nil != req.URL {
  66. txn.CleanURL = internal.SafeURL(req.URL)
  67. }
  68. // Synthetics support is tied up with a transaction's Old CAT field,
  69. // CrossProcess. To support Synthetics with either BetterCAT or Old CAT,
  70. // Initialize the CrossProcess field of the transaction, passing in
  71. // the top-level configuration.
  72. doOldCAT := txn.Config.CrossApplicationTracer.Enabled
  73. noGUID := txn.Config.DistributedTracer.Enabled
  74. txn.CrossProcess.InitFromHTTPRequest(doOldCAT, noGUID, input.Reply, req)
  75. return txn
  76. }
  77. func (txn *txn) slowQueriesEnabled() bool {
  78. return txn.Config.DatastoreTracer.SlowQuery.Enabled &&
  79. txn.Reply.CollectTraces
  80. }
  81. func (txn *txn) txnTracesEnabled() bool {
  82. return txn.Config.TransactionTracer.Enabled &&
  83. txn.Reply.CollectTraces
  84. }
  85. func (txn *txn) txnEventsEnabled() bool {
  86. return txn.Config.TransactionEvents.Enabled &&
  87. txn.Reply.CollectAnalyticsEvents
  88. }
  89. func (txn *txn) errorEventsEnabled() bool {
  90. return txn.Config.ErrorCollector.CaptureEvents &&
  91. txn.Reply.CollectErrorEvents
  92. }
  93. func (txn *txn) freezeName() {
  94. if txn.ignore || ("" != txn.FinalName) {
  95. return
  96. }
  97. txn.FinalName = internal.CreateFullTxnName(txn.Name, txn.Reply, txn.IsWeb)
  98. if "" == txn.FinalName {
  99. txn.ignore = true
  100. }
  101. }
  102. func (txn *txn) getsApdex() bool {
  103. return txn.IsWeb
  104. }
  105. func (txn *txn) txnTraceThreshold() time.Duration {
  106. if txn.Config.TransactionTracer.Threshold.IsApdexFailing {
  107. return internal.ApdexFailingThreshold(txn.ApdexThreshold)
  108. }
  109. return txn.Config.TransactionTracer.Threshold.Duration
  110. }
  111. func (txn *txn) shouldSaveTrace() bool {
  112. return txn.CrossProcess.IsSynthetics() ||
  113. (txn.txnTracesEnabled() && (txn.Duration >= txn.txnTraceThreshold()))
  114. }
  115. func (txn *txn) MergeIntoHarvest(h *internal.Harvest) {
  116. var priority internal.Priority
  117. if txn.BetterCAT.Enabled {
  118. priority = txn.BetterCAT.Priority
  119. } else {
  120. priority = internal.NewPriority()
  121. }
  122. internal.CreateTxnMetrics(&txn.TxnData, h.Metrics)
  123. internal.MergeBreakdownMetrics(&txn.TxnData, h.Metrics)
  124. if txn.txnEventsEnabled() {
  125. // Allocate a new TxnEvent to prevent a reference to the large transaction.
  126. alloc := new(internal.TxnEvent)
  127. *alloc = txn.TxnData.TxnEvent
  128. h.TxnEvents.AddTxnEvent(alloc, priority)
  129. }
  130. internal.MergeTxnErrors(&h.ErrorTraces, txn.Errors, txn.TxnEvent)
  131. if txn.errorEventsEnabled() {
  132. for _, e := range txn.Errors {
  133. errEvent := &internal.ErrorEvent{
  134. ErrorData: *e,
  135. TxnEvent: txn.TxnEvent,
  136. }
  137. // Since the stack trace is not used in error events, remove the reference
  138. // to minimize memory.
  139. errEvent.Stack = nil
  140. h.ErrorEvents.Add(errEvent, priority)
  141. }
  142. }
  143. if txn.shouldSaveTrace() {
  144. h.TxnTraces.Witness(internal.HarvestTrace{
  145. TxnEvent: txn.TxnEvent,
  146. Trace: txn.TxnTrace,
  147. })
  148. }
  149. if nil != txn.SlowQueries {
  150. h.SlowSQLs.Merge(txn.SlowQueries, txn.TxnEvent)
  151. }
  152. if txn.BetterCAT.Sampled && txn.Config.SpanEvents.Enabled {
  153. h.SpanEvents.MergeFromTransaction(&txn.TxnData)
  154. }
  155. }
  156. // TransportType's name field is not mutable outside of its package
  157. // however, it still periodically needs to be used and assigned within
  158. // the this package. For testing purposes only.
  159. func getTransport(transport string) string {
  160. var retVal string
  161. switch transport {
  162. case TransportHTTP.name:
  163. retVal = TransportHTTP.name
  164. case TransportHTTPS.name:
  165. retVal = TransportHTTPS.name
  166. case TransportKafka.name:
  167. retVal = TransportKafka.name
  168. case TransportJMS.name:
  169. retVal = TransportJMS.name
  170. case TransportIronMQ.name:
  171. retVal = TransportIronMQ.name
  172. case TransportAMQP.name:
  173. retVal = TransportAMQP.name
  174. case TransportQueue.name:
  175. retVal = TransportQueue.name
  176. case TransportOther.name:
  177. retVal = TransportOther.name
  178. case TransportUnknown.name:
  179. default:
  180. retVal = TransportUnknown.name
  181. }
  182. return retVal
  183. }
  184. func responseCodeIsError(cfg *Config, code int) bool {
  185. if code < http.StatusBadRequest { // 400
  186. return false
  187. }
  188. for _, ignoreCode := range cfg.ErrorCollector.IgnoreStatusCodes {
  189. if code == ignoreCode {
  190. return false
  191. }
  192. }
  193. return true
  194. }
  195. func headersJustWritten(txn *txn, code int) {
  196. txn.Lock()
  197. defer txn.Unlock()
  198. if txn.finished {
  199. return
  200. }
  201. if txn.wroteHeader {
  202. return
  203. }
  204. txn.wroteHeader = true
  205. internal.ResponseHeaderAttributes(txn.Attrs, txn.W.Header())
  206. internal.ResponseCodeAttribute(txn.Attrs, code)
  207. if responseCodeIsError(&txn.Config, code) {
  208. e := internal.TxnErrorFromResponseCode(time.Now(), code)
  209. e.Stack = internal.GetStackTrace(1)
  210. txn.noticeErrorInternal(e)
  211. }
  212. }
  213. func (txn *txn) responseHeader() http.Header {
  214. txn.Lock()
  215. defer txn.Unlock()
  216. if txn.finished {
  217. return nil
  218. }
  219. if txn.wroteHeader {
  220. return nil
  221. }
  222. if !txn.CrossProcess.Enabled {
  223. return nil
  224. }
  225. if !txn.CrossProcess.IsInbound() {
  226. return nil
  227. }
  228. txn.freezeName()
  229. contentLength := internal.GetContentLengthFromHeader(txn.W.Header())
  230. appData, err := txn.CrossProcess.CreateAppData(txn.FinalName, txn.Queuing, time.Since(txn.Start), contentLength)
  231. if err != nil {
  232. txn.Config.Logger.Debug("error generating outbound response header", map[string]interface{}{
  233. "error": err,
  234. })
  235. return nil
  236. }
  237. return internal.AppDataToHTTPHeader(appData)
  238. }
  239. func addCrossProcessHeaders(txn *txn) {
  240. // responseHeader() checks the wroteHeader field and returns a nil map if the
  241. // header has been written, so we don't need a check here.
  242. for key, values := range txn.responseHeader() {
  243. for _, value := range values {
  244. txn.W.Header().Add(key, value)
  245. }
  246. }
  247. }
  248. func (txn *txn) Header() http.Header { return txn.W.Header() }
  249. func (txn *txn) Write(b []byte) (int, error) {
  250. // This is safe to call unconditionally, even if Write() is called multiple
  251. // times; see also the commentary in addCrossProcessHeaders().
  252. addCrossProcessHeaders(txn)
  253. n, err := txn.W.Write(b)
  254. headersJustWritten(txn, http.StatusOK)
  255. return n, err
  256. }
  257. func (txn *txn) WriteHeader(code int) {
  258. addCrossProcessHeaders(txn)
  259. txn.W.WriteHeader(code)
  260. headersJustWritten(txn, code)
  261. }
  262. func (txn *txn) End() error {
  263. txn.Lock()
  264. defer txn.Unlock()
  265. if txn.finished {
  266. return errAlreadyEnded
  267. }
  268. txn.finished = true
  269. r := recover()
  270. if nil != r {
  271. e := internal.TxnErrorFromPanic(time.Now(), r)
  272. e.Stack = internal.GetStackTrace(0)
  273. txn.noticeErrorInternal(e)
  274. }
  275. txn.Stop = time.Now()
  276. txn.Duration = txn.Stop.Sub(txn.Start)
  277. if children := internal.TracerRootChildren(&txn.TxnData); txn.Duration > children {
  278. txn.Exclusive = txn.Duration - children
  279. }
  280. txn.freezeName()
  281. // Finalise the CAT state.
  282. if err := txn.CrossProcess.Finalise(txn.Name, txn.Config.AppName); err != nil {
  283. txn.Config.Logger.Debug("error finalising the cross process state", map[string]interface{}{
  284. "error": err,
  285. })
  286. }
  287. // Assign apdexThreshold regardless of whether or not the transaction
  288. // gets apdex since it may be used to calculate the trace threshold.
  289. txn.ApdexThreshold = internal.CalculateApdexThreshold(txn.Reply, txn.FinalName)
  290. if txn.getsApdex() {
  291. if txn.HasErrors() {
  292. txn.Zone = internal.ApdexFailing
  293. } else {
  294. txn.Zone = internal.CalculateApdexZone(txn.ApdexThreshold, txn.Duration)
  295. }
  296. } else {
  297. txn.Zone = internal.ApdexNone
  298. }
  299. if txn.Config.Logger.DebugEnabled() {
  300. txn.Config.Logger.Debug("transaction ended", map[string]interface{}{
  301. "name": txn.FinalName,
  302. "duration_ms": txn.Duration.Seconds() * 1000.0,
  303. "ignored": txn.ignore,
  304. "run": txn.Reply.RunID,
  305. })
  306. }
  307. if !txn.ignore {
  308. txn.Consumer.Consume(txn.Reply.RunID, txn)
  309. }
  310. // Note that if a consumer uses `panic(nil)`, the panic will not
  311. // propagate.
  312. if nil != r {
  313. panic(r)
  314. }
  315. return nil
  316. }
  317. func (txn *txn) AddAttribute(name string, value interface{}) error {
  318. txn.Lock()
  319. defer txn.Unlock()
  320. if txn.Config.HighSecurity {
  321. return errHighSecurityEnabled
  322. }
  323. if !txn.Reply.SecurityPolicies.CustomParameters.Enabled() {
  324. return errSecurityPolicy
  325. }
  326. if txn.finished {
  327. return errAlreadyEnded
  328. }
  329. return internal.AddUserAttribute(txn.Attrs, name, value, internal.DestAll)
  330. }
  331. var (
  332. errorsLocallyDisabled = errors.New("errors locally disabled")
  333. errorsRemotelyDisabled = errors.New("errors remotely disabled")
  334. errNilError = errors.New("nil error")
  335. errAlreadyEnded = errors.New("transaction has already ended")
  336. errSecurityPolicy = errors.New("disabled by security policy")
  337. )
  338. const (
  339. highSecurityErrorMsg = "message removed by high security setting"
  340. securityPolicyErrorMsg = "message removed by security policy"
  341. )
  342. func (txn *txn) noticeErrorInternal(err internal.ErrorData) error {
  343. if !txn.Config.ErrorCollector.Enabled {
  344. return errorsLocallyDisabled
  345. }
  346. if !txn.Reply.CollectErrors {
  347. return errorsRemotelyDisabled
  348. }
  349. if nil == txn.Errors {
  350. txn.Errors = internal.NewTxnErrors(internal.MaxTxnErrors)
  351. }
  352. if txn.Config.HighSecurity {
  353. err.Msg = highSecurityErrorMsg
  354. }
  355. if !txn.Reply.SecurityPolicies.AllowRawExceptionMessages.Enabled() {
  356. err.Msg = securityPolicyErrorMsg
  357. }
  358. txn.Errors.Add(err)
  359. txn.TxnData.TxnEvent.HasError = true //mark transaction as having an error
  360. return nil
  361. }
  362. var (
  363. errTooManyErrorAttributes = fmt.Errorf("too many extra attributes: limit is %d",
  364. internal.AttributeErrorLimit)
  365. )
  366. func (txn *txn) NoticeError(err error) error {
  367. txn.Lock()
  368. defer txn.Unlock()
  369. if txn.finished {
  370. return errAlreadyEnded
  371. }
  372. if nil == err {
  373. return errNilError
  374. }
  375. e := internal.ErrorData{
  376. When: time.Now(),
  377. Msg: err.Error(),
  378. }
  379. if ec, ok := err.(ErrorClasser); ok {
  380. e.Klass = ec.ErrorClass()
  381. }
  382. if "" == e.Klass {
  383. e.Klass = reflect.TypeOf(err).String()
  384. }
  385. if st, ok := err.(StackTracer); ok {
  386. e.Stack = st.StackTrace()
  387. // Note that if the provided stack trace is excessive in length,
  388. // it will be truncated during JSON creation.
  389. }
  390. if nil == e.Stack {
  391. e.Stack = internal.GetStackTrace(2)
  392. }
  393. if ea, ok := err.(ErrorAttributer); ok && !txn.Config.HighSecurity && txn.Reply.SecurityPolicies.CustomParameters.Enabled() {
  394. unvetted := ea.ErrorAttributes()
  395. if len(unvetted) > internal.AttributeErrorLimit {
  396. return errTooManyErrorAttributes
  397. }
  398. e.ExtraAttributes = make(map[string]interface{})
  399. for key, val := range unvetted {
  400. val, errr := internal.ValidateUserAttribute(key, val)
  401. if nil != errr {
  402. return errr
  403. }
  404. e.ExtraAttributes[key] = val
  405. }
  406. }
  407. return txn.noticeErrorInternal(e)
  408. }
  409. func (txn *txn) SetName(name string) error {
  410. txn.Lock()
  411. defer txn.Unlock()
  412. if txn.finished {
  413. return errAlreadyEnded
  414. }
  415. txn.Name = name
  416. return nil
  417. }
  418. func (txn *txn) Ignore() error {
  419. txn.Lock()
  420. defer txn.Unlock()
  421. if txn.finished {
  422. return errAlreadyEnded
  423. }
  424. txn.ignore = true
  425. return nil
  426. }
  427. func (txn *txn) StartSegmentNow() SegmentStartTime {
  428. var s internal.SegmentStartTime
  429. txn.Lock()
  430. if !txn.finished {
  431. s = internal.StartSegment(&txn.TxnData, time.Now())
  432. }
  433. txn.Unlock()
  434. return SegmentStartTime{
  435. segment: segment{
  436. start: s,
  437. txn: txn,
  438. },
  439. }
  440. }
  441. type segment struct {
  442. start internal.SegmentStartTime
  443. txn *txn
  444. }
  445. func endSegment(s *Segment) error {
  446. txn := s.StartTime.txn
  447. if nil == txn {
  448. return nil
  449. }
  450. var err error
  451. txn.Lock()
  452. if txn.finished {
  453. err = errAlreadyEnded
  454. } else {
  455. err = internal.EndBasicSegment(&txn.TxnData, s.StartTime.start, time.Now(), s.Name)
  456. }
  457. txn.Unlock()
  458. return err
  459. }
  460. func endDatastore(s *DatastoreSegment) error {
  461. txn := s.StartTime.txn
  462. if nil == txn {
  463. return nil
  464. }
  465. txn.Lock()
  466. defer txn.Unlock()
  467. if txn.finished {
  468. return errAlreadyEnded
  469. }
  470. if txn.Config.HighSecurity {
  471. s.QueryParameters = nil
  472. }
  473. if !txn.Config.DatastoreTracer.QueryParameters.Enabled {
  474. s.QueryParameters = nil
  475. }
  476. if txn.Reply.SecurityPolicies.RecordSQL.IsSet() {
  477. s.QueryParameters = nil
  478. if !txn.Reply.SecurityPolicies.RecordSQL.Enabled() {
  479. s.ParameterizedQuery = ""
  480. }
  481. }
  482. if !txn.Config.DatastoreTracer.DatabaseNameReporting.Enabled {
  483. s.DatabaseName = ""
  484. }
  485. if !txn.Config.DatastoreTracer.InstanceReporting.Enabled {
  486. s.Host = ""
  487. s.PortPathOrID = ""
  488. }
  489. return internal.EndDatastoreSegment(internal.EndDatastoreParams{
  490. Tracer: &txn.TxnData,
  491. Start: s.StartTime.start,
  492. Now: time.Now(),
  493. Product: string(s.Product),
  494. Collection: s.Collection,
  495. Operation: s.Operation,
  496. ParameterizedQuery: s.ParameterizedQuery,
  497. QueryParameters: s.QueryParameters,
  498. Host: s.Host,
  499. PortPathOrID: s.PortPathOrID,
  500. Database: s.DatabaseName,
  501. })
  502. }
  503. func externalSegmentMethod(s *ExternalSegment) string {
  504. r := s.Request
  505. // Is this a client request?
  506. if nil != s.Response && nil != s.Response.Request {
  507. r = s.Response.Request
  508. // Golang's http package states that when a client's
  509. // Request has an empty string for Method, the
  510. // method is GET.
  511. if "" == r.Method {
  512. return "GET"
  513. }
  514. }
  515. if nil == r {
  516. return ""
  517. }
  518. return r.Method
  519. }
  520. func externalSegmentURL(s *ExternalSegment) (*url.URL, error) {
  521. if "" != s.URL {
  522. return url.Parse(s.URL)
  523. }
  524. r := s.Request
  525. if nil != s.Response && nil != s.Response.Request {
  526. r = s.Response.Request
  527. }
  528. if r != nil {
  529. return r.URL, nil
  530. }
  531. return nil, nil
  532. }
  533. func endExternal(s *ExternalSegment) error {
  534. txn := s.StartTime.txn
  535. if nil == txn {
  536. return nil
  537. }
  538. txn.Lock()
  539. defer txn.Unlock()
  540. if txn.finished {
  541. return errAlreadyEnded
  542. }
  543. m := externalSegmentMethod(s)
  544. u, err := externalSegmentURL(s)
  545. if nil != err {
  546. return err
  547. }
  548. return internal.EndExternalSegment(&txn.TxnData, s.StartTime.start, time.Now(), u, m, s.Response)
  549. }
  550. // oldCATOutboundHeaders generates the Old CAT and Synthetics headers, depending
  551. // on whether Old CAT is enabled or any Synthetics functionality has been
  552. // triggered in the agent.
  553. func oldCATOutboundHeaders(txn *txn) http.Header {
  554. txn.Lock()
  555. defer txn.Unlock()
  556. if txn.finished {
  557. return http.Header{}
  558. }
  559. metadata, err := txn.CrossProcess.CreateCrossProcessMetadata(txn.Name, txn.Config.AppName)
  560. if err != nil {
  561. txn.Config.Logger.Debug("error generating outbound headers", map[string]interface{}{
  562. "error": err,
  563. })
  564. // It's possible for CreateCrossProcessMetadata() to error and still have a
  565. // Synthetics header, so we'll still fall through to returning headers
  566. // based on whatever metadata was returned.
  567. }
  568. return internal.MetadataToHTTPHeader(metadata)
  569. }
  570. func outboundHeaders(s *ExternalSegment) http.Header {
  571. txn := s.StartTime.txn
  572. if nil == txn {
  573. return http.Header{}
  574. }
  575. hdr := oldCATOutboundHeaders(txn)
  576. // hdr may be empty, or it may contain headers. If DistributedTracer
  577. // is enabled, add more to the existing hdr
  578. if p := txn.CreateDistributedTracePayload().HTTPSafe(); "" != p {
  579. hdr.Add(DistributedTracePayloadHeader, p)
  580. return hdr
  581. }
  582. return hdr
  583. }
  584. const (
  585. maxSampledDistributedPayloads = 35
  586. )
  587. type shimPayload struct{}
  588. func (s shimPayload) Text() string { return "" }
  589. func (s shimPayload) HTTPSafe() string { return "" }
  590. func (txn *txn) CreateDistributedTracePayload() (payload DistributedTracePayload) {
  591. payload = shimPayload{}
  592. txn.Lock()
  593. defer txn.Unlock()
  594. if !txn.BetterCAT.Enabled {
  595. return
  596. }
  597. if txn.finished {
  598. txn.CreatePayloadException = true
  599. return
  600. }
  601. if "" == txn.Reply.PrimaryAppID {
  602. // Return a shimPayload if the application is not yet connected.
  603. return
  604. }
  605. txn.numPayloadsCreated++
  606. var p internal.Payload
  607. p.Type = internal.CallerType
  608. p.Account = txn.Reply.AccountID
  609. p.App = txn.Reply.PrimaryAppID
  610. p.TracedID = txn.BetterCAT.TraceID()
  611. p.Priority = txn.BetterCAT.Priority
  612. p.Timestamp.Set(time.Now())
  613. p.TransactionID = txn.BetterCAT.ID // Set the transaction ID to the transaction guid.
  614. if txn.Reply.AccountID != txn.Reply.TrustedAccountKey {
  615. p.TrustedAccountKey = txn.Reply.TrustedAccountKey
  616. }
  617. if txn.BetterCAT.Sampled && txn.Config.SpanEvents.Enabled {
  618. p.ID = txn.CurrentSpanIdentifier()
  619. }
  620. // limit the number of outbound sampled=true payloads to prevent too
  621. // many downstream sampled events.
  622. p.SetSampled(false)
  623. if txn.numPayloadsCreated < maxSampledDistributedPayloads {
  624. p.SetSampled(txn.BetterCAT.Sampled)
  625. }
  626. txn.CreatePayloadSuccess = true
  627. payload = p
  628. return
  629. }
  630. var (
  631. errOutboundPayloadCreated = errors.New("outbound payload already created")
  632. errAlreadyAccepted = errors.New("AcceptDistributedTracePayload has already been called")
  633. errInboundPayloadDTDisabled = errors.New("DistributedTracer must be enabled to accept an inbound payload")
  634. )
  635. func (txn *txn) AcceptDistributedTracePayload(t TransportType, p interface{}) error {
  636. txn.Lock()
  637. defer txn.Unlock()
  638. if !txn.BetterCAT.Enabled {
  639. return errInboundPayloadDTDisabled
  640. }
  641. if txn.finished {
  642. txn.AcceptPayloadException = true
  643. return errAlreadyEnded
  644. }
  645. if txn.numPayloadsCreated > 0 {
  646. txn.AcceptPayloadCreateBeforeAccept = true
  647. return errOutboundPayloadCreated
  648. }
  649. if txn.BetterCAT.Inbound != nil {
  650. txn.AcceptPayloadIgnoredMultiple = true
  651. return errAlreadyAccepted
  652. }
  653. if nil == p {
  654. txn.AcceptPayloadNullPayload = true
  655. return nil
  656. }
  657. payload, err := internal.AcceptPayload(p)
  658. if nil != err {
  659. if _, ok := err.(internal.ErrPayloadParse); ok {
  660. txn.AcceptPayloadParseException = true
  661. } else if _, ok := err.(internal.ErrUnsupportedPayloadVersion); ok {
  662. txn.AcceptPayloadIgnoredVersion = true
  663. } else if _, ok := err.(internal.ErrPayloadMissingField); ok {
  664. txn.AcceptPayloadParseException = true
  665. } else {
  666. txn.AcceptPayloadException = true
  667. }
  668. return err
  669. }
  670. if nil == payload {
  671. return nil
  672. }
  673. // now that we have a parsed and alloc'd payload,
  674. // let's make sure it has the correct fields
  675. if err := payload.IsValid(); nil != err {
  676. txn.AcceptPayloadParseException = true
  677. return err
  678. }
  679. // and let's also do our trustedKey check
  680. receivedTrustKey := payload.TrustedAccountKey
  681. if "" == receivedTrustKey {
  682. receivedTrustKey = payload.Account
  683. }
  684. if receivedTrustKey != txn.Reply.TrustedAccountKey {
  685. txn.AcceptPayloadUntrustedAccount = true
  686. return internal.ErrTrustedAccountKey{Message: "trusted account key missing or does not match"}
  687. }
  688. if 0 != payload.Priority {
  689. txn.BetterCAT.Priority = payload.Priority
  690. }
  691. // a nul payload.Sampled means the a field wasn't provided
  692. if nil != payload.Sampled {
  693. txn.BetterCAT.Sampled = *payload.Sampled
  694. } else {
  695. txn.BetterCAT.Sampled = txn.Reply.AdaptiveSampler.ComputeSampled(txn.BetterCAT.Priority.Float32(), time.Now())
  696. }
  697. txn.BetterCAT.Inbound = payload
  698. // TransportType's name field is not mutable outside of its package
  699. // so the only check needed is if the caller is using an empty TransportType
  700. txn.BetterCAT.Inbound.TransportType = t.name
  701. if t.name == "" {
  702. txn.BetterCAT.Inbound.TransportType = TransportUnknown.name
  703. txn.Config.Logger.Debug("Invalid transport type, defaulting to Unknown", map[string]interface{}{})
  704. }
  705. if tm := payload.Timestamp.Time(); txn.Start.After(tm) {
  706. txn.BetterCAT.Inbound.TransportDuration = txn.Start.Sub(tm)
  707. }
  708. txn.AcceptPayloadSuccess = true
  709. return nil
  710. }