1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
|
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package newrelic
import (
"errors"
"fmt"
"log"
"net/http"
"net/url"
"reflect"
"runtime/debug"
"sync"
"time"
"github.com/newrelic/go-agent/v3/internal"
)
type txn struct {
app *app
*appRun
// This mutex is required since the consumer may call the public API
// interface functions from different routines.
sync.Mutex
// finished indicates whether or not End() has been called. After
// finished has been set to true, no recording should occur.
finished bool
numPayloadsCreated uint32
sampledCalculated bool
ignore bool
// wroteHeader prevents capturing multiple response code errors if the
// user erroneously calls WriteHeader multiple times.
wroteHeader bool
txnData
mainThread tracingThread
asyncThreads []*tracingThread
}
type thread struct {
*txn
// thread does not have locking because it should only be accessed while
// the txn is locked.
thread *tracingThread
}
func (txn *txn) markStart(now time.Time) {
txn.Start = now
// The mainThread is considered active now.
txn.mainThread.RecordActivity(now)
}
func (txn *txn) markEnd(now time.Time, thread *tracingThread) {
txn.Stop = now
// The thread on which End() was called is considered active now.
thread.RecordActivity(now)
txn.Duration = txn.Stop.Sub(txn.Start)
// TotalTime is the sum of "active time" across all threads. A thread
// was active when it started the transaction, stopped the transaction,
// started a segment, or stopped a segment.
txn.TotalTime = txn.mainThread.TotalTime()
for _, thd := range txn.asyncThreads {
txn.TotalTime += thd.TotalTime()
}
// Ensure that TotalTime is at least as large as Duration so that the
// graphs look sensible. This can happen under the following situation:
// goroutine1: txn.start----|segment1|
// goroutine2: |segment2|----txn.end
if txn.Duration > txn.TotalTime {
txn.TotalTime = txn.Duration
}
}
func newTxn(app *app, run *appRun, name string) *thread {
txn := &txn{
app: app,
appRun: run,
}
txn.markStart(time.Now())
txn.Name = name
txn.Attrs = newAttributes(run.AttributeConfig)
if run.Config.DistributedTracer.Enabled {
txn.BetterCAT.Enabled = true
txn.TraceIDGenerator = run.Reply.TraceIDGenerator
txn.BetterCAT.SetTraceAndTxnIDs(txn.TraceIDGenerator.GenerateTraceID())
txn.BetterCAT.Priority = newPriorityFromRandom(txn.TraceIDGenerator.Float32)
txn.ShouldCollectSpanEvents = txn.shouldCollectSpanEvents
txn.ShouldCreateSpanGUID = txn.shouldCreateSpanGUID
}
txn.Attrs.Agent.Add(AttributeHostDisplayName, txn.Config.HostDisplayName, nil)
txn.TxnTrace.Enabled = txn.Config.TransactionTracer.Enabled
txn.TxnTrace.SegmentThreshold = txn.Config.TransactionTracer.Segments.Threshold
txn.TxnTrace.StackTraceThreshold = txn.Config.TransactionTracer.Segments.StackTraceThreshold
txn.SlowQueriesEnabled = txn.Config.DatastoreTracer.SlowQuery.Enabled
txn.SlowQueryThreshold = txn.Config.DatastoreTracer.SlowQuery.Threshold
// Synthetics support is tied up with a transaction's Old CAT field,
// CrossProcess. To support Synthetics with either BetterCAT or Old CAT,
// Initialize the CrossProcess field of the transaction, passing in
// the top-level configuration.
doOldCAT := txn.Config.CrossApplicationTracer.Enabled
noGUID := txn.Config.DistributedTracer.Enabled
txn.CrossProcess.Init(doOldCAT, noGUID, run.Reply)
return &thread{
txn: txn,
thread: &txn.mainThread,
}
}
func (thd *thread) logAPIError(err error, operation string, extraDetails map[string]interface{}) {
if nil == thd {
return
}
if nil == err {
return
}
if extraDetails == nil {
extraDetails = make(map[string]interface{}, 1)
}
extraDetails["reason"] = err.Error()
thd.Config.Logger.Error("unable to "+operation, extraDetails)
}
func (txn *txn) shouldCollectSpanEvents() bool {
if !txn.Config.DistributedTracer.Enabled {
return false
}
if !txn.Config.SpanEvents.Enabled {
return false
}
if shouldUseTraceObserver(txn.Config) {
return true
}
return txn.lazilyCalculateSampled()
}
func (txn *txn) shouldCreateSpanGUID() bool {
if !txn.Config.DistributedTracer.Enabled {
return false
}
if !txn.Config.SpanEvents.Enabled {
return false
}
return true
}
// lazilyCalculateSampled calculates and returns whether or not the transaction
// should be sampled. Sampled is not computed at the beginning of the
// transaction because we want to calculate Sampled only for transactions that
// do not accept an inbound payload.
func (txn *txn) lazilyCalculateSampled() bool {
if !txn.BetterCAT.Enabled {
return false
}
if txn.sampledCalculated {
return txn.BetterCAT.Sampled
}
txn.BetterCAT.Sampled = txn.appRun.adaptiveSampler.computeSampled(txn.BetterCAT.Priority.Float32(), time.Now())
if txn.BetterCAT.Sampled {
txn.BetterCAT.Priority += 1.0
}
txn.sampledCalculated = true
return txn.BetterCAT.Sampled
}
func (txn *txn) SetWebRequest(r WebRequest) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
// Any call to SetWebRequest should indicate a web transaction.
txn.IsWeb = true
h := r.Header
if nil != h {
txn.Queuing = queueDuration(h, txn.Start)
txn.acceptDistributedTraceHeadersLocked(r.Transport, h)
txn.CrossProcess.InboundHTTPRequest(h)
}
requestAgentAttributes(txn.Attrs, r.Method, h, r.URL, r.Host)
return nil
}
type dummyResponseWriter struct{}
func (rw dummyResponseWriter) Header() http.Header { return nil }
func (rw dummyResponseWriter) Write(b []byte) (int, error) { return 0, nil }
func (rw dummyResponseWriter) WriteHeader(code int) {}
func (thd *thread) SetWebResponse(w http.ResponseWriter) http.ResponseWriter {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if w == nil {
// Accepting a nil parameter makes it easy for consumers to add
// a response code to the transaction without a response
// writer:
//
// txn.SetWebResponse(nil).WriteHeader(500)
//
w = dummyResponseWriter{}
}
return upgradeResponseWriter(&replacementResponseWriter{
thd: thd,
original: w,
})
}
func (txn *txn) freezeName() {
if txn.ignore || ("" != txn.FinalName) {
return
}
txn.FinalName = txn.appRun.createTransactionName(txn.Name, txn.IsWeb)
if "" == txn.FinalName {
txn.ignore = true
}
}
func (txn *txn) getsApdex() bool {
return txn.IsWeb
}
func (txn *txn) shouldSaveTrace() bool {
if !txn.Config.TransactionTracer.Enabled {
return false
}
if txn.CrossProcess.IsSynthetics() {
return true
}
return txn.Duration >= txn.txnTraceThreshold(txn.ApdexThreshold)
}
func (txn *txn) MergeIntoHarvest(h *harvest) {
var priority priority
if txn.BetterCAT.Enabled {
priority = txn.BetterCAT.Priority
} else {
priority = newPriority()
}
createTxnMetrics(&txn.txnData, h.Metrics)
mergeBreakdownMetrics(&txn.txnData, h.Metrics)
if txn.Config.TransactionEvents.Enabled {
// Allocate a new TxnEvent to prevent a reference to the large transaction.
alloc := new(txnEvent)
*alloc = txn.txnData.txnEvent
h.TxnEvents.AddTxnEvent(alloc, priority)
}
if txn.Reply.CollectErrors {
mergeTxnErrors(&h.ErrorTraces, txn.Errors, txn.txnEvent)
}
if txn.Config.ErrorCollector.CaptureEvents {
for _, e := range txn.Errors {
errEvent := &errorEvent{
errorData: *e,
txnEvent: txn.txnEvent,
}
// Since the stack trace is not used in error events, remove the reference
// to minimize memory.
errEvent.Stack = nil
h.ErrorEvents.Add(errEvent, priority)
}
}
if txn.shouldSaveTrace() {
h.TxnTraces.Witness(harvestTrace{
txnEvent: txn.txnEvent,
Trace: txn.TxnTrace,
})
}
if nil != txn.SlowQueries {
h.SlowSQLs.Merge(txn.SlowQueries, txn.txnEvent)
}
if txn.shouldCollectSpanEvents() && !shouldUseTraceObserver(txn.Config) {
h.SpanEvents.MergeSpanEvents(txn.txnData.SpanEvents)
}
}
func headersJustWritten(thd *thread, code int, hdr http.Header) {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
if txn.wroteHeader {
return
}
txn.wroteHeader = true
responseHeaderAttributes(txn.Attrs, hdr)
responseCodeAttribute(txn.Attrs, code)
if txn.appRun.responseCodeIsError(code) {
e := txnErrorFromResponseCode(time.Now(), code)
e.Stack = getStackTrace()
thd.noticeErrorInternal(e)
}
}
func (txn *txn) responseHeader(hdr http.Header) http.Header {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return nil
}
if txn.wroteHeader {
return nil
}
if !txn.CrossProcess.Enabled {
return nil
}
if !txn.CrossProcess.IsInbound() {
return nil
}
txn.freezeName()
contentLength := getContentLengthFromHeader(hdr)
appData, err := txn.CrossProcess.CreateAppData(txn.FinalName, txn.Queuing, time.Since(txn.Start), contentLength)
if err != nil {
txn.Config.Logger.Debug("error generating outbound response header", map[string]interface{}{
"error": err,
})
return nil
}
return appDataToHTTPHeader(appData)
}
func addCrossProcessHeaders(txn *txn, hdr http.Header) {
// responseHeader() checks the wroteHeader field and returns a nil map if the
// header has been written, so we don't need a check here.
if nil != hdr {
for key, values := range txn.responseHeader(hdr) {
for _, value := range values {
hdr.Add(key, value)
}
}
}
}
func (thd *thread) End(recovered interface{}) error {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
txn.finished = true
if nil != recovered {
e := txnErrorFromPanic(time.Now(), recovered)
e.Stack = getStackTrace()
thd.noticeErrorInternal(e)
log.Println(string(debug.Stack()))
}
txn.markEnd(time.Now(), thd.thread)
txn.freezeName()
// Make a sampling decision if there have been no segments or outbound
// payloads.
txn.lazilyCalculateSampled()
// Finalise the CAT state.
if err := txn.CrossProcess.Finalise(txn.Name, txn.Config.AppName); err != nil {
txn.Config.Logger.Debug("error finalising the cross process state", map[string]interface{}{
"error": err,
})
}
// Assign apdexThreshold regardless of whether or not the transaction
// gets apdex since it may be used to calculate the trace threshold.
txn.ApdexThreshold = internal.CalculateApdexThreshold(txn.Reply, txn.FinalName)
if txn.getsApdex() {
if txn.HasErrors() {
txn.Zone = apdexFailing
} else {
txn.Zone = calculateApdexZone(txn.ApdexThreshold, txn.Duration)
}
} else {
txn.Zone = apdexNone
}
if txn.Config.Logger.DebugEnabled() {
txn.Config.Logger.Debug("transaction ended", map[string]interface{}{
"name": txn.FinalName,
"duration_ms": txn.Duration.Seconds() * 1000.0,
"ignored": txn.ignore,
"app_connected": "" != txn.Reply.RunID,
})
}
if txn.shouldCollectSpanEvents() {
root := &spanEvent{
GUID: txn.GetRootSpanID(),
Timestamp: txn.Start,
Duration: txn.Duration,
Name: txn.FinalName,
TxnName: txn.FinalName,
Category: spanCategoryGeneric,
IsEntrypoint: true,
}
root.AgentAttributes.addAgentAttrs(txn.Attrs.Agent)
root.UserAttributes.addUserAttrs(txn.Attrs.user)
if txn.rootSpanErrData != nil {
root.AgentAttributes.addString(SpanAttributeErrorClass, txn.rootSpanErrData.Klass)
root.AgentAttributes.addString(SpanAttributeErrorMessage, txn.rootSpanErrData.Msg)
}
if p := txn.BetterCAT.Inbound; nil != p {
root.ParentID = txn.BetterCAT.Inbound.ID
root.TrustedParentID = txn.BetterCAT.Inbound.TrustedParentID
root.TracingVendors = txn.BetterCAT.Inbound.TracingVendors
if p.HasNewRelicTraceInfo {
root.AgentAttributes.addString("parent.type", p.Type)
root.AgentAttributes.addString("parent.app", p.App)
root.AgentAttributes.addString("parent.account", p.Account)
root.AgentAttributes.addFloat("parent.transportDuration", p.TransportDuration.Seconds())
}
root.AgentAttributes.addString("parent.transportType", txn.BetterCAT.TransportType)
}
root.AgentAttributes = txn.Attrs.filterSpanAttributes(root.AgentAttributes, destSpan)
txn.SpanEvents = append(txn.SpanEvents, root)
// Add transaction tracing fields to span events at the end of
// the transaction since we could accept payload after the early
// segments occur.
for _, evt := range txn.SpanEvents {
evt.TraceID = txn.BetterCAT.TraceID
evt.TransactionID = txn.BetterCAT.TxnID
evt.Sampled = txn.BetterCAT.Sampled
evt.Priority = txn.BetterCAT.Priority
}
}
if !txn.ignore {
txn.app.Consume(txn.Reply.RunID, txn)
if observer := txn.app.getObserver(); nil != observer {
for _, evt := range txn.SpanEvents {
observer.consumeSpan(evt)
}
}
}
// Note that if a consumer uses `panic(nil)`, the panic will not
// propagate.
if nil != recovered {
panic(recovered)
}
return nil
}
func (txn *txn) AddAttribute(name string, value interface{}) error {
txn.Lock()
defer txn.Unlock()
if txn.Config.HighSecurity {
return errHighSecurityEnabled
}
if !txn.Reply.SecurityPolicies.CustomParameters.Enabled() {
return errSecurityPolicy
}
if txn.finished {
return errAlreadyEnded
}
return addUserAttribute(txn.Attrs, name, value, destAll)
}
var (
errorsDisabled = errors.New("errors disabled")
errNilError = errors.New("nil error")
errAlreadyEnded = errors.New("transaction has already ended")
errSecurityPolicy = errors.New("disabled by security policy")
errTransactionIgnored = errors.New("transaction has been ignored")
errBrowserDisabled = errors.New("browser disabled by local configuration")
)
const (
highSecurityErrorMsg = "message removed by high security setting"
securityPolicyErrorMsg = "message removed by security policy"
)
func (thd *thread) noticeErrorInternal(err errorData) error {
txn := thd.txn
if !txn.Config.ErrorCollector.Enabled {
return errorsDisabled
}
if nil == txn.Errors {
txn.Errors = newTxnErrors(maxTxnErrors)
}
if txn.Config.HighSecurity {
err.Msg = highSecurityErrorMsg
}
if !txn.Reply.SecurityPolicies.AllowRawExceptionMessages.Enabled() {
err.Msg = securityPolicyErrorMsg
}
if txn.shouldCollectSpanEvents() {
err.SpanID = txn.CurrentSpanIdentifier(thd.thread)
addErrorAttrs(thd, err)
}
txn.Errors.Add(err)
txn.txnData.txnEvent.HasError = true //mark transaction as having an error
return nil
}
var errorAttrs = []string{
SpanAttributeErrorClass,
SpanAttributeErrorMessage,
}
func addErrorAttrs(t *thread, err errorData) {
// If there are no current segments, we'll add them to the root span when it is created later
if len(t.thread.stack) <= 0 {
t.rootSpanErrData = &err
return
}
for _, attr := range errorAttrs {
t.thread.RemoveErrorSpanAttribute(attr)
}
t.thread.AddAgentSpanAttribute(SpanAttributeErrorClass, err.Klass)
t.thread.AddAgentSpanAttribute(SpanAttributeErrorMessage, err.Msg)
}
var (
errTooManyErrorAttributes = fmt.Errorf("too many extra attributes: limit is %d",
attributeErrorLimit)
)
// errorCause returns the error's deepest wrapped ancestor.
func errorCause(err error) error {
for {
if unwrapper, ok := err.(interface{ Unwrap() error }); ok {
if next := unwrapper.Unwrap(); nil != next {
err = next
continue
}
}
return err
}
}
func errorClassMethod(err error) string {
if ec, ok := err.(errorClasser); ok {
return ec.ErrorClass()
}
return ""
}
func errorStackTraceMethod(err error) stackTrace {
if st, ok := err.(stackTracer); ok {
return st.StackTrace()
}
return nil
}
func errorAttributesMethod(err error) map[string]interface{} {
if st, ok := err.(errorAttributer); ok {
return st.ErrorAttributes()
}
return nil
}
func errDataFromError(input error) (data errorData, err error) {
cause := errorCause(input)
data = errorData{
When: time.Now(),
Msg: input.Error(),
}
if c := errorClassMethod(input); "" != c {
// If the error implements ErrorClasser, use that.
data.Klass = c
} else if c := errorClassMethod(cause); "" != c {
// Otherwise, if the error's cause implements ErrorClasser, use that.
data.Klass = c
} else {
// As a final fallback, use the type of the error's cause.
data.Klass = reflect.TypeOf(cause).String()
}
if st := errorStackTraceMethod(input); nil != st {
// If the error implements StackTracer, use that.
data.Stack = st
} else if st := errorStackTraceMethod(cause); nil != st {
// Otherwise, if the error's cause implements StackTracer, use that.
data.Stack = st
} else {
// As a final fallback, generate a StackTrace here.
data.Stack = getStackTrace()
}
var unvetted map[string]interface{}
if ats := errorAttributesMethod(input); nil != ats {
// If the error implements ErrorAttributer, use that.
unvetted = ats
} else {
// Otherwise, if the error's cause implements ErrorAttributer, use that.
unvetted = errorAttributesMethod(cause)
}
if unvetted != nil {
if len(unvetted) > attributeErrorLimit {
err = errTooManyErrorAttributes
return
}
data.ExtraAttributes = make(map[string]interface{})
for key, val := range unvetted {
val, err = validateUserAttribute(key, val)
if nil != err {
return
}
data.ExtraAttributes[key] = val
}
}
return data, nil
}
func (thd *thread) NoticeError(input error) error {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
if nil == input {
return errNilError
}
data, err := errDataFromError(input)
if nil != err {
return err
}
if txn.Config.HighSecurity || !txn.Reply.SecurityPolicies.CustomParameters.Enabled() {
data.ExtraAttributes = nil
}
return thd.noticeErrorInternal(data)
}
func (txn *txn) SetName(name string) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
txn.Name = name
return nil
}
func (txn *txn) Ignore() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
txn.ignore = true
return nil
}
func (thd *thread) startSegmentAt(at time.Time) SegmentStartTime {
var s segmentStartTime
txn := thd.txn
txn.Lock()
if !txn.finished {
s = startSegment(&txn.txnData, thd.thread, at)
}
txn.Unlock()
return SegmentStartTime{
start: s,
thread: thd,
}
}
const (
// Browser fields are encoded using the first digits of the license
// key.
browserEncodingKeyLimit = 13
)
func browserEncodingKey(licenseKey string) []byte {
key := []byte(licenseKey)
if len(key) > browserEncodingKeyLimit {
key = key[0:browserEncodingKeyLimit]
}
return key
}
func (txn *txn) BrowserTimingHeader() (*BrowserTimingHeader, error) {
txn.Lock()
defer txn.Unlock()
if !txn.Config.BrowserMonitoring.Enabled {
return nil, errBrowserDisabled
}
if txn.Reply.AgentLoader == "" {
// If the loader is empty, either browser has been disabled
// by the server or the application is not yet connected.
return nil, nil
}
if txn.finished {
return nil, errAlreadyEnded
}
txn.freezeName()
// Freezing the name might cause the transaction to be ignored, so check
// this after txn.freezeName().
if txn.ignore {
return nil, errTransactionIgnored
}
encodingKey := browserEncodingKey(txn.Config.License)
attrs, err := obfuscate(browserAttributes(txn.Attrs), encodingKey)
if err != nil {
return nil, fmt.Errorf("error getting browser attributes: %v", err)
}
name, err := obfuscate([]byte(txn.FinalName), encodingKey)
if err != nil {
return nil, fmt.Errorf("error obfuscating name: %v", err)
}
return &BrowserTimingHeader{
agentLoader: txn.Reply.AgentLoader,
info: browserInfo{
Beacon: txn.Reply.Beacon,
LicenseKey: txn.Reply.BrowserKey,
ApplicationID: txn.Reply.AppID,
TransactionName: name,
QueueTimeMillis: txn.Queuing.Nanoseconds() / (1000 * 1000),
ApplicationTimeMillis: time.Now().Sub(txn.Start).Nanoseconds() / (1000 * 1000),
ObfuscatedAttributes: attrs,
ErrorBeacon: txn.Reply.ErrorBeacon,
Agent: txn.Reply.JSAgentFile,
},
}, nil
}
func createThread(txn *txn) *tracingThread {
newThread := newTracingThread(&txn.txnData)
txn.asyncThreads = append(txn.asyncThreads, newThread)
return newThread
}
func (thd *thread) NewGoroutine() *Transaction {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
// If the transaction has finished, return the same thread.
return newTransaction(thd)
}
return newTransaction(&thread{
thread: createThread(txn),
txn: txn,
})
}
func endBasic(s *Segment) error {
thd := s.StartTime.thread
if nil == thd {
return nil
}
txn := thd.txn
var err error
txn.Lock()
if txn.finished {
err = errAlreadyEnded
} else {
err = endBasicSegment(&txn.txnData, thd.thread, s.StartTime.start, time.Now(), s.Name)
}
txn.Unlock()
return err
}
func endDatastore(s *DatastoreSegment) error {
thd := s.StartTime.thread
if nil == thd {
return nil
}
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
if txn.Config.HighSecurity {
s.QueryParameters = nil
}
if !txn.Config.DatastoreTracer.QueryParameters.Enabled {
s.QueryParameters = nil
}
if txn.Reply.SecurityPolicies.RecordSQL.IsSet() {
s.QueryParameters = nil
if !txn.Reply.SecurityPolicies.RecordSQL.Enabled() {
s.ParameterizedQuery = ""
}
}
if !txn.Config.DatastoreTracer.DatabaseNameReporting.Enabled {
s.DatabaseName = ""
}
if !txn.Config.DatastoreTracer.InstanceReporting.Enabled {
s.Host = ""
s.PortPathOrID = ""
}
return endDatastoreSegment(endDatastoreParams{
TxnData: &txn.txnData,
Thread: thd.thread,
Start: s.StartTime.start,
Now: time.Now(),
Product: string(s.Product),
Collection: s.Collection,
Operation: s.Operation,
ParameterizedQuery: s.ParameterizedQuery,
QueryParameters: s.QueryParameters,
Host: s.Host,
PortPathOrID: s.PortPathOrID,
Database: s.DatabaseName,
ThisHost: txn.appRun.Config.hostname,
})
}
func externalSegmentMethod(s *ExternalSegment) string {
if "" != s.Procedure {
return s.Procedure
}
r := s.Request
if nil != s.Response && nil != s.Response.Request {
r = s.Response.Request
}
if nil != r {
if "" != r.Method {
return r.Method
}
// Golang's http package states that when a client's Request has
// an empty string for Method, the method is GET.
return "GET"
}
return ""
}
func externalSegmentURL(s *ExternalSegment) (*url.URL, error) {
if "" != s.URL {
return url.Parse(s.URL)
}
r := s.Request
if nil != s.Response && nil != s.Response.Request {
r = s.Response.Request
}
if r != nil {
return r.URL, nil
}
return nil, nil
}
func endExternal(s *ExternalSegment) error {
thd := s.StartTime.thread
if nil == thd {
return nil
}
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
u, err := externalSegmentURL(s)
if nil != err {
return err
}
return endExternalSegment(endExternalParams{
TxnData: &txn.txnData,
Thread: thd.thread,
Start: s.StartTime.start,
Now: time.Now(),
Logger: txn.Config.Logger,
Response: s.Response,
URL: u,
Host: s.Host,
Library: s.Library,
Method: externalSegmentMethod(s),
StatusCode: s.statusCode,
})
}
func endMessage(s *MessageProducerSegment) error {
thd := s.StartTime.thread
if nil == thd {
return nil
}
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return errAlreadyEnded
}
if "" == s.DestinationType {
s.DestinationType = MessageQueue
}
return endMessageSegment(endMessageParams{
TxnData: &txn.txnData,
Thread: thd.thread,
Start: s.StartTime.start,
Now: time.Now(),
Library: s.Library,
Logger: txn.Config.Logger,
DestinationName: s.DestinationName,
DestinationType: string(s.DestinationType),
DestinationTemp: s.DestinationTemporary,
})
}
// oldCATOutboundHeaders generates the Old CAT and Synthetics headers, depending
// on whether Old CAT is enabled or any Synthetics functionality has been
// triggered in the agent.
func oldCATOutboundHeaders(txn *txn) http.Header {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return http.Header{}
}
metadata, err := txn.CrossProcess.CreateCrossProcessMetadata(txn.Name, txn.Config.AppName)
if err != nil {
txn.Config.Logger.Debug("error generating outbound headers", map[string]interface{}{
"error": err,
})
// It's possible for CreateCrossProcessMetadata() to error and still have a
// Synthetics header, so we'll still fall through to returning headers
// based on whatever metadata was returned.
}
return metadataToHTTPHeader(metadata)
}
func outboundHeaders(s *ExternalSegment) http.Header {
thd := s.StartTime.thread
if nil == thd {
return http.Header{}
}
txn := thd.txn
hdr := oldCATOutboundHeaders(txn)
// hdr may be empty, or it may contain headers. If DistributedTracer
// is enabled, add more to the existing hdr
thd.CreateDistributedTracePayload(hdr)
return hdr
}
const (
maxSampledDistributedPayloads = 35
)
func (thd *thread) CreateDistributedTracePayload(hdrs http.Header) {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if !txn.BetterCAT.Enabled {
return
}
support := &txn.DistributedTracingSupport
excludeNRHeader := thd.Config.DistributedTracer.ExcludeNewRelicHeader
if txn.finished {
support.TraceContextCreateException = true
if !excludeNRHeader {
support.CreatePayloadException = true
}
return
}
if "" == txn.Reply.AccountID || "" == txn.Reply.TrustedAccountKey {
// We can't create a payload: The application is not yet
// connected or serverless distributed tracing configuration was
// not provided.
return
}
txn.numPayloadsCreated++
p := &payload{}
// Calculate sampled first since this also changes the value for the
// priority
sampled := txn.lazilyCalculateSampled()
if txn.shouldCreateSpanGUID() {
p.ID = txn.CurrentSpanIdentifier(thd.thread)
}
p.Type = callerTypeApp
p.Account = txn.Reply.AccountID
p.App = txn.Reply.PrimaryAppID
p.TracedID = txn.BetterCAT.TraceID
p.Priority = txn.BetterCAT.Priority
p.Timestamp.Set(txn.Reply.DistributedTraceTimestampGenerator())
p.TrustedAccountKey = txn.Reply.TrustedAccountKey
p.TransactionID = txn.BetterCAT.TxnID // Set the transaction ID to the transaction guid.
if nil != txn.BetterCAT.Inbound {
p.NonTrustedTraceState = txn.BetterCAT.Inbound.NonTrustedTraceState
p.OriginalTraceState = txn.BetterCAT.Inbound.OriginalTraceState
}
// limit the number of outbound sampled=true payloads to prevent too
// many downstream sampled events.
p.SetSampled(false)
if txn.numPayloadsCreated < maxSampledDistributedPayloads {
p.SetSampled(sampled)
}
support.TraceContextCreateSuccess = true
if !excludeNRHeader {
hdrs.Set(DistributedTraceNewRelicHeader, p.NRHTTPSafe())
support.CreatePayloadSuccess = true
}
// ID must be present in the Traceparent header when span events are
// enabled, even if the transaction is not sampled. Note that this
// assignment occurs after setting the Newrelic header since the ID
// field of the Newrelic header should be empty if span events are
// disabled or the transaction is not sampled.
if p.ID == "" {
p.ID = txn.CurrentSpanIdentifier(thd.thread)
}
hdrs.Set(DistributedTraceW3CTraceParentHeader, p.W3CTraceParent())
if !txn.Config.SpanEvents.Enabled {
p.ID = ""
}
if !txn.Config.TransactionEvents.Enabled {
p.TransactionID = ""
}
hdrs.Set(DistributedTraceW3CTraceStateHeader, p.W3CTraceState())
}
var (
errOutboundPayloadCreated = errors.New("outbound payload already created")
errAlreadyAccepted = errors.New("AcceptDistributedTraceHeaders has already been called")
errInboundPayloadDTDisabled = errors.New("DistributedTracer must be enabled to accept an inbound payload")
errTrustedAccountKey = errors.New("trusted account key missing or does not match")
)
func (txn *txn) AcceptDistributedTraceHeaders(t TransportType, hdrs http.Header) error {
txn.Lock()
defer txn.Unlock()
return txn.acceptDistributedTraceHeadersLocked(t, hdrs)
}
func (txn *txn) acceptDistributedTraceHeadersLocked(t TransportType, hdrs http.Header) error {
if !txn.BetterCAT.Enabled {
return errInboundPayloadDTDisabled
}
if txn.finished {
return errAlreadyEnded
}
support := &txn.DistributedTracingSupport
if txn.numPayloadsCreated > 0 {
support.AcceptPayloadCreateBeforeAccept = true
return errOutboundPayloadCreated
}
if txn.BetterCAT.Inbound != nil {
support.AcceptPayloadIgnoredMultiple = true
return errAlreadyAccepted
}
if nil == hdrs {
support.AcceptPayloadNullPayload = true
return nil
}
if "" == txn.Reply.AccountID || "" == txn.Reply.TrustedAccountKey {
// We can't accept a payload: The application is not yet
// connected or serverless distributed tracing configuration was
// not provided.
return nil
}
txn.BetterCAT.TransportType = t.toString()
payload, err := acceptPayload(hdrs, txn.Reply.TrustedAccountKey, support)
if nil != err {
return err
}
if nil == payload {
return nil
}
// and let's also do our trustedKey check
receivedTrustKey := payload.TrustedAccountKey
if "" == receivedTrustKey {
receivedTrustKey = payload.Account
}
// If the trust key doesn't match but we don't have any New Relic trace info, this means
// we just got the TraceParent header, and we still need to save that info to BetterCAT
// farther down.
if receivedTrustKey != txn.Reply.TrustedAccountKey && payload.HasNewRelicTraceInfo {
support.AcceptPayloadUntrustedAccount = true
return errTrustedAccountKey
}
if 0 != payload.Priority {
txn.BetterCAT.Priority = payload.Priority
}
// a nul payload.Sampled means the a field wasn't provided
if nil != payload.Sampled {
txn.BetterCAT.Sampled = *payload.Sampled
txn.sampledCalculated = true
}
txn.BetterCAT.Inbound = payload
txn.BetterCAT.TraceID = payload.TracedID
if tm := payload.Timestamp.Time(); txn.Start.After(tm) {
txn.BetterCAT.Inbound.TransportDuration = txn.Start.Sub(tm)
}
return nil
}
func (txn *txn) Application() *Application {
return newApplication(txn.app)
}
// Note that Agent attributes added to spans must be on the allowed list of
// span attributes, which you can find in attributes.go
func (thd *thread) AddAgentSpanAttribute(key string, val string) {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
thd.thread.AddAgentSpanAttribute(key, val)
}
func (thd *thread) AddUserSpanAttribute(key string, val interface{}) error {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if outputDests := applyAttributeConfig(thd.Attrs.config, key, destSpan); 0 == outputDests {
return nil
}
if txn.Config.HighSecurity {
return errHighSecurityEnabled
}
if !txn.Reply.SecurityPolicies.CustomParameters.Enabled() {
return errSecurityPolicy
}
thd.thread.AddUserSpanAttribute(key, val)
return nil
}
var (
// Ensure that txn implements AddAgentAttributer to avoid breaking
// integration package type assertions.
_ internal.AddAgentAttributer = &txn{}
)
func (txn *txn) AddAgentAttribute(name string, stringVal string, otherVal interface{}) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
txn.Attrs.Agent.Add(name, stringVal, otherVal)
}
func (thd *thread) GetTraceMetadata() (metadata TraceMetadata) {
txn := thd.txn
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
if txn.BetterCAT.Enabled {
metadata.TraceID = txn.BetterCAT.TraceID
if txn.shouldCollectSpanEvents() {
metadata.SpanID = txn.CurrentSpanIdentifier(thd.thread)
}
}
return
}
func (thd *thread) GetLinkingMetadata() (metadata LinkingMetadata) {
txn := thd.txn
metadata.EntityName = txn.appRun.firstAppName
metadata.EntityType = "SERVICE"
metadata.EntityGUID = txn.appRun.Reply.EntityGUID
metadata.Hostname = txn.appRun.Config.hostname
md := thd.GetTraceMetadata()
metadata.TraceID = md.TraceID
metadata.SpanID = md.SpanID
return
}
func (txn *txn) IsSampled() bool {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return false
}
return txn.lazilyCalculateSampled()
}
|