Repository navigation
Expand file tree
/
Copy pathSentryTracer.java
More file actions
1151 lines (1007 loc) · 37.3 KB
/
Copy pathSentryTracer.java
File metadata and controls
1151 lines (1007 loc) · 37.3 KB
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
package io.sentry;
import io.sentry.profiling.ProfileRecordingState;
import io.sentry.protocol.Contexts;
import io.sentry.protocol.SentryId;
import io.sentry.protocol.SentryTransaction;
import io.sentry.protocol.TransactionNameSource;
import io.sentry.time.Deadline;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.CollectionUtils;
import io.sentry.util.Objects;
import io.sentry.util.SpanUtils;
import io.sentry.util.thread.IThreadChecker;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
@ApiStatus.Internal
public final class SentryTracer implements ITransaction {
private final @NotNull SentryId eventId = new SentryId();
private final @NotNull Span root;
private final @NotNull List<Span> children = new CopyOnWriteArrayList<>();
private final @NotNull IScopes scopes;
private @NotNull String name;
/**
* Holds the status for finished tracer. Tracer can have finishedStatus set, but not be finished
* itself when `waitForChildren` is set to `true`, `#finish()` method was called but there are
* unfinished children spans.
*/
private @NotNull FinishStatus finishStatus = FinishStatus.NOT_FINISHED;
private volatile @Nullable Future<?> idleTimeoutFuture;
private volatile @Nullable Future<?> deadlineTimeoutFuture;
// Whether timeout tasks may still be scheduled. Set to false once the tracer is finished. The
// executor itself is owned by the options (shared SDK-wide) and obtained from there when needed.
private volatile boolean timersEnabled = false;
private final @NotNull AutoClosableReentrantLock timerLock = new AutoClosableReentrantLock();
private final @NotNull AutoClosableReentrantLock tracerLock = new AutoClosableReentrantLock();
private final @NotNull AtomicBoolean isIdleFinishTimerRunning = new AtomicBoolean(false);
private final @NotNull AtomicBoolean isDeadlineTimerRunning = new AtomicBoolean(false);
/**
* When the deadline timeout is reached, or null without one.
*
* <p>The deadline timer counts on a clock that stops while an Android device is suspended, so it
* runs late after the device slept, and after the process was frozen the app's own threads can
* finish spans before it. This deadline keeps counting through both.
*/
private volatile @Nullable Deadline deadline;
private @NotNull TransactionNameSource transactionNameSource;
private final @NotNull Instrumenter instrumenter;
private final @NotNull Contexts contexts = new Contexts();
private final @Nullable CompositePerformanceCollector compositePerformanceCollector;
private final @NotNull TransactionOptions transactionOptions;
public SentryTracer(final @NotNull TransactionContext context, final @NotNull IScopes scopes) {
this(context, scopes, new TransactionOptions(), null);
}
public SentryTracer(
final @NotNull TransactionContext context,
final @NotNull IScopes scopes,
final @NotNull TransactionOptions transactionOptions) {
this(context, scopes, transactionOptions, null);
}
SentryTracer(
final @NotNull TransactionContext context,
final @NotNull IScopes scopes,
final @NotNull TransactionOptions transactionOptions,
final @Nullable CompositePerformanceCollector compositePerformanceCollector) {
Objects.requireNonNull(context, "context is required");
Objects.requireNonNull(scopes, "scopes are required");
this.root = new Span(context, this, scopes, transactionOptions);
this.name = context.getName();
this.instrumenter = context.getInstrumenter();
this.scopes = scopes;
// Let's collect performance data (cpu, ram, frames) only when the transaction is sampled
this.compositePerformanceCollector =
Boolean.TRUE.equals(isSampled()) ? compositePerformanceCollector : null;
this.transactionNameSource = context.getTransactionNameSource();
this.transactionOptions = transactionOptions;
setDefaultSpanData(root);
final @NotNull SentryId continuousProfilerId = getProfilerId();
if (!continuousProfilerId.equals(SentryId.EMPTY_ID) && Boolean.TRUE.equals(isSampled())) {
this.contexts.setProfile(new ProfileContext(continuousProfilerId));
}
// We are currently sending the performance data only in profiles, but we are always sending
// performance measurements (frames data in spans).
if (this.compositePerformanceCollector != null) {
this.compositePerformanceCollector.start(this);
}
if (transactionOptions.getIdleTimeout() != null
|| transactionOptions.getDeadlineTimeout() != null) {
timersEnabled = true;
scheduleDeadlineTimeout();
scheduleFinish();
}
}
@Override
public void scheduleFinish() {
try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) {
if (timersEnabled) {
final @Nullable Long idleTimeout = transactionOptions.getIdleTimeout();
if (idleTimeout != null) {
cancelIdleTimer();
isIdleFinishTimerRunning.set(true);
try {
idleTimeoutFuture =
scopes
.getOptions()
.getTimerExecutorService()
.schedule(this::onIdleTimeoutReached, idleTimeout);
} catch (Throwable e) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.WARNING, "Failed to schedule finish timer", e);
// if we failed to schedule the finish timer for some reason, we finish it here right
// away
onIdleTimeoutReached();
}
}
}
}
}
private void onIdleTimeoutReached() {
final @Nullable SpanStatus status = getStatus();
finish((status != null) ? status : SpanStatus.OK);
isIdleFinishTimerRunning.set(false);
}
private void onDeadlineTimeoutReached() {
final @Nullable SpanStatus status = getStatus();
forceFinish(
(status != null) ? status : SpanStatus.DEADLINE_EXCEEDED,
transactionOptions.getIdleTimeout() != null,
null);
isDeadlineTimerRunning.set(false);
}
/**
* The status a span finishing now must take because the deadline timeout has been reached, even
* if the deadline timer has not run yet, or null if it has not been reached.
*/
@Nullable
SpanStatus getDeadlineExceededStatus() {
final @Nullable Deadline deadline = this.deadline;
if (deadline == null || !deadline.hasPassed()) {
return null;
}
final @Nullable SpanStatus status = getStatus();
return (status != null) ? status : SpanStatus.DEADLINE_EXCEEDED;
}
@Override
public void forceFinish(
final @NotNull SpanStatus status, final boolean dropIfNoChildren, final @Nullable Hint hint) {
if (isFinished()) {
return;
}
final @NotNull SentryDate finishTimestamp = scopes.getOptions().getDateProvider().now();
// abort all child-spans first, this ensures the transaction can be finished,
// even if waitForChildren is true
// iterate in reverse order to ensure leaf spans are processed before their parents
@NotNull
final ListIterator<Span> iterator =
CollectionUtils.reverseListIterator((CopyOnWriteArrayList<Span>) this.children);
while (iterator.hasPrevious()) {
@NotNull final Span span = iterator.previous();
span.setSpanFinishedCallback(null);
span.finish(status, finishTimestamp);
}
finish(status, finishTimestamp, dropIfNoChildren, hint);
}
@Override
public void finish(
@Nullable SpanStatus status,
@Nullable SentryDate finishDate,
boolean dropIfNoChildren,
@Nullable Hint hint) {
// try to get the high precision timestamp from the root span
SentryDate finishTimestamp = root.getFinishDate();
// if a finishDate was passed in, use that instead
if (finishDate != null) {
finishTimestamp = finishDate;
}
// if it's not set -> fallback to the current time
if (finishTimestamp == null) {
finishTimestamp = scopes.getOptions().getDateProvider().now();
}
// auto-finish any idle spans first
for (final Span span : children) {
if (span.getOptions().isIdle()) {
span.finish((status != null) ? status : getSpanContext().status, finishTimestamp);
}
}
this.finishStatus = FinishStatus.finishing(status);
if (!root.isFinished()
&& (!transactionOptions.isWaitForChildren() || hasAllChildrenFinished())) {
final @NotNull AtomicReference<List<PerformanceCollectionData>> performanceCollectionData =
new AtomicReference<>();
// We set the new spanFinishedCallback here instead of creation time, calling the old one to
// avoid the user overwrites it by setting a custom spanFinishedCallback on the root span
final @Nullable SpanFinishedCallback oldCallback = this.root.getSpanFinishedCallback();
this.root.setSpanFinishedCallback(span -> {
if (oldCallback != null) {
oldCallback.execute(span);
}
// Let's call the finishCallback here, when the root span has a finished date but it's
// not finished, yet
final @Nullable TransactionFinishedCallback finishedCallback =
transactionOptions.getTransactionFinishedCallback();
if (finishedCallback != null) {
finishedCallback.execute(this);
}
if (compositePerformanceCollector != null) {
performanceCollectionData.set(compositePerformanceCollector.stop(this));
}
});
// any un-finished children will remain unfinished
// as relay takes care of setting the end-timestamp + deadline_exceeded
// see
// https://github.com/getsentry/relay/blob/40697d0a1c54e5e7ad8d183fc7f9543b94fe3839/relay-general/src/store/transactions/processor.rs#L374-L378
root.finish(finishStatus.spanStatus, finishTimestamp);
ProfilingTraceData profilingTraceData = null;
if (Boolean.TRUE.equals(isSampled()) && Boolean.TRUE.equals(isProfileSampled())) {
profilingTraceData =
scopes
.getOptions()
.getTransactionProfiler()
.onTransactionFinish(this, performanceCollectionData.get(), scopes.getOptions());
}
if (scopes.getOptions().isContinuousProfilingEnabled()
&& scopes.getOptions().getProfileLifecycle() == ProfileLifecycle.TRACE
&& root.getSpanContext().getProfilerId().equals(SentryId.EMPTY_ID)) {
scopes.getOptions().getContinuousProfiler().stopProfiler(ProfileLifecycle.TRACE);
}
if (performanceCollectionData.get() != null) {
performanceCollectionData.get().clear();
}
scopes.configureScope(scope -> {
scope.withTransaction(transaction -> {
if (transaction == this) {
scope.clearTransaction();
}
});
});
dropUnrecordedProfilerIds(finishTimestamp);
final SentryTransaction transaction = new SentryTransaction(this);
if (timersEnabled) {
try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) {
if (timersEnabled) {
cancelIdleTimer();
cancelDeadlineTimer();
timersEnabled = false;
}
}
}
if (dropIfNoChildren && children.isEmpty() && transactionOptions.getIdleTimeout() != null) {
// if it's an idle transaction which has no children, we drop it to save user's quota
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"Dropping idle transaction %s because it has no child spans",
name);
return;
}
transaction.getMeasurements().putAll(root.getMeasurements());
scopes.captureTransaction(transaction, traceContext(), hint, profilingTraceData);
}
}
private void cancelIdleTimer() {
try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) {
if (idleTimeoutFuture != null) {
idleTimeoutFuture.cancel(false);
isIdleFinishTimerRunning.set(false);
idleTimeoutFuture = null;
}
}
}
private void scheduleDeadlineTimeout() {
final @Nullable Long deadlineTimeOut = transactionOptions.getDeadlineTimeout();
if (deadlineTimeOut != null) {
try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) {
if (timersEnabled) {
cancelDeadlineTimer();
isDeadlineTimerRunning.set(true);
deadline =
Deadline.after(
scopes.getOptions().getMonotonicTicker(), deadlineTimeOut, TimeUnit.MILLISECONDS);
try {
deadlineTimeoutFuture =
scopes
.getOptions()
.getTimerExecutorService()
.schedule(this::onDeadlineTimeoutReached, deadlineTimeOut);
} catch (Throwable e) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.WARNING, "Failed to schedule finish timer", e);
// if we failed to schedule the finish timer for some reason, we finish it here right
// away
onDeadlineTimeoutReached();
}
}
}
}
}
private void cancelDeadlineTimer() {
try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) {
if (deadlineTimeoutFuture != null) {
deadlineTimeoutFuture.cancel(false);
isDeadlineTimerRunning.set(false);
deadlineTimeoutFuture = null;
}
}
}
public @NotNull List<Span> getChildren() {
return children;
}
@Override
public @NotNull SentryDate getStartDate() {
return this.root.getStartDate();
}
@Override
public @Nullable SentryDate getFinishDate() {
return this.root.getFinishDate();
}
/**
* Starts a child Span with given trace id and parent span id.
*
* @param parentSpanId - parent span id
* @param operation - span operation name
* @param description - span description
* @return a new transaction span
*/
@NotNull
ISpan startChild(
final @NotNull SpanId parentSpanId,
final @NotNull String operation,
final @Nullable String description) {
return startChild(parentSpanId, operation, description, new SpanOptions());
}
/**
* Starts a child Span with given trace id and parent span id.
*
* @param parentSpanId - parent span id
* @param operation - span operation name
* @param description - span description
* @param spanOptions - span options
* @return a new transaction span
*/
@NotNull
ISpan startChild(
final @NotNull SpanId parentSpanId,
final @NotNull String operation,
final @Nullable String description,
final @NotNull SpanOptions spanOptions) {
return createChild(parentSpanId, operation, description, spanOptions);
}
@NotNull
ISpan startChild(
final @NotNull SpanId parentSpanId,
final @NotNull String operation,
final @Nullable String description,
final @Nullable SentryDate timestamp,
final @NotNull Instrumenter instrumenter) {
final @NotNull SpanContext spanContext =
getSpanContext().copyForChild(operation, parentSpanId, null);
spanContext.setDescription(description);
spanContext.setInstrumenter(instrumenter);
final @NotNull SpanOptions spanOptions = new SpanOptions();
spanOptions.setStartTimestamp(timestamp);
return createChild(spanContext, spanOptions);
}
@NotNull
ISpan startChild(
final @NotNull SpanId parentSpanId,
final @NotNull String operation,
final @Nullable String description,
final @Nullable SentryDate timestamp,
final @NotNull Instrumenter instrumenter,
final @NotNull SpanOptions spanOptions) {
final @NotNull SpanContext spanContext =
getSpanContext().copyForChild(operation, parentSpanId, null);
spanContext.setDescription(description);
spanContext.setInstrumenter(instrumenter);
spanOptions.setStartTimestamp(timestamp);
return createChild(spanContext, spanOptions);
}
/**
* Starts a child Span with given trace id and parent span id.
*
* @param parentSpanId - parent span id
* @param operation - the span operation
* @param description - the optional span description
* @param options - span options
* @return a new transaction span
*/
@NotNull
private ISpan createChild(
final @NotNull SpanId parentSpanId,
final @NotNull String operation,
final @Nullable String description,
final @NotNull SpanOptions options) {
final @NotNull SpanContext spanContext =
getSpanContext().copyForChild(operation, parentSpanId, null);
spanContext.setDescription(description);
spanContext.setInstrumenter(Instrumenter.SENTRY);
return createChild(spanContext, options);
}
@NotNull
private ISpan createChild(
final @NotNull SpanContext spanContext, final @NotNull SpanOptions spanOptions) {
if (root.isFinished()) {
return NoOpSpan.getInstance();
}
if (!this.instrumenter.equals(spanContext.getInstrumenter())) {
return NoOpSpan.getInstance();
}
if (SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOrigins(), spanOptions.getOrigin())) {
return NoOpSpan.getInstance();
}
final @Nullable SpanId parentSpanId = spanContext.getParentSpanId();
final @NotNull String operation = spanContext.getOperation();
final @Nullable String description = spanContext.getDescription();
if (children.size() < scopes.getOptions().getMaxSpans()) {
Objects.requireNonNull(parentSpanId, "parentSpanId is required");
Objects.requireNonNull(operation, "operation is required");
// When this transaction finishes, we want its idle spans to finish as well. We don't let idle
// spans cancel the idle timer b/c it would keep the transaction alive until its deadline.
if (!spanOptions.isIdle()) {
cancelIdleTimer();
}
final Span span =
new Span(
this,
scopes,
spanContext,
spanOptions,
finishingSpan -> {
if (compositePerformanceCollector != null) {
compositePerformanceCollector.onSpanFinished(finishingSpan);
}
final FinishStatus finishStatus = this.finishStatus;
if (transactionOptions.getIdleTimeout() != null) {
// if it's an idle transaction, no matter the status, we'll reset the timeout here
// so the transaction will either idle and finish itself, or a new child will be
// added and we'll wait for it again
if (!transactionOptions.isWaitForChildren() || hasAllChildrenFinished()) {
scheduleFinish();
}
} else if (finishStatus.isFinishing) {
finish(finishStatus.spanStatus);
}
});
// TODO [POTEL] missing features
// final Span span =
// new Span(
// root.getTraceId(),
// parentSpanId,
// this,
// operation,
// this.scopes,
// timestamp,
// spanOptions,
// finishingSpan -> {
// if (compositePerformanceCollector != null) {
// compositePerformanceCollector.onSpanFinished(finishingSpan);
// }
// final FinishStatus finishStatus = this.finishStatus;
// if (transactionOptions.getIdleTimeout() != null) {
// // if it's an idle transaction, no matter the status, we'll reset the
// timeout here
// // so the transaction will either idle and finish itself, or a new child
// will be
// // added and we'll wait for it again
// if (!transactionOptions.isWaitForChildren() || hasAllChildrenFinished()) {
// scheduleFinish();
// }
// } else if (finishStatus.isFinishing) {
// finish(finishStatus.spanStatus);
// }
// });
// span.setDescription(description);
setDefaultSpanData(span);
this.children.add(span);
if (compositePerformanceCollector != null) {
compositePerformanceCollector.onSpanStarted(span);
}
return span;
} else {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Span operation: %s, description: %s dropped due to limit reached. Returning NoOpSpan.",
operation,
description);
return NoOpSpan.getInstance();
}
}
/** Sets the default data in the span, including profiler _id, thread id and thread name */
private void setDefaultSpanData(final @NotNull ISpan span) {
final @NotNull IThreadChecker threadChecker = scopes.getOptions().getThreadChecker();
final @NotNull SentryId profilerId = getProfilerId();
if (!profilerId.equals(SentryId.EMPTY_ID) && Boolean.TRUE.equals(span.isSampled())) {
span.setData(SpanDataConvention.PROFILER_ID, profilerId.toString());
}
span.setData(
SpanDataConvention.THREAD_ID, String.valueOf(threadChecker.currentThreadSystemId()));
span.setData(SpanDataConvention.THREAD_NAME, threadChecker.getCurrentThreadName());
}
/**
* Spans are tagged with the profiler id when they start, but the profiler may only learn later
* that no profile was recorded, e.g. when the OS rate limits profiling requests. Spans that no
* profile covers drop the reference here, so they don't point to a profile that never arrives.
*/
private void dropUnrecordedProfilerIds(final @NotNull SentryDate finishTimestamp) {
final @NotNull IContinuousProfiler continuousProfiler =
scopes.getOptions().getContinuousProfiler();
if (continuousProfiler instanceof NoOpContinuousProfiler) {
// Without a profiler no span can carry a profiler id, so the children are not worth walking
return;
}
if (isProfileMissing(continuousProfiler, root, finishTimestamp)) {
root.setData(SpanDataConvention.PROFILER_ID, null);
contexts.remove(ProfileContext.TYPE);
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"No profile was recorded for transaction, dropping its profiler id.");
}
for (final @NotNull Span child : children) {
if (isProfileMissing(continuousProfiler, child, finishTimestamp)) {
child.setData(SpanDataConvention.PROFILER_ID, null);
}
}
}
/**
* Whether the profiler knows that no profile covers the given span.
*
* @param finishTimestamp end of the window for a span that never finished
*/
private boolean isProfileMissing(
final @NotNull IContinuousProfiler continuousProfiler,
final @NotNull Span span,
final @NotNull SentryDate finishTimestamp) {
final @Nullable Object data = span.getData(SpanDataConvention.PROFILER_ID);
if (!(data instanceof String)) {
return false;
}
final @NotNull SentryId profilerId;
try {
profilerId = new SentryId((String) data);
} catch (IllegalArgumentException e) {
// The span data key is public API, so the value is not necessarily an id the SDK wrote
return false;
}
final @Nullable SentryDate spanFinishDate = span.getFinishDate();
return continuousProfiler.getProfileRecordingState(
profilerId,
span.getStartDate(),
spanFinishDate != null ? spanFinishDate : finishTimestamp)
== ProfileRecordingState.NOT_RECORDED;
}
private @NotNull SentryId getProfilerId() {
return !root.getSpanContext().getProfilerId().equals(SentryId.EMPTY_ID)
? root.getSpanContext().getProfilerId()
: scopes.getOptions().getContinuousProfiler().getProfilerId();
}
@Override
public @NotNull ISpan startChild(final @NotNull String operation) {
return this.startChild(operation, (String) null);
}
@Override
public @NotNull ISpan startChild(
@NotNull String operation,
@Nullable String description,
@Nullable SentryDate timestamp,
@NotNull Instrumenter instrumenter) {
return startChild(operation, description, timestamp, instrumenter, new SpanOptions());
}
@Override
public @NotNull ISpan startChild(
final @NotNull String operation,
@Nullable String description,
@Nullable SentryDate timestamp,
@NotNull Instrumenter instrumenter,
@NotNull SpanOptions spanOptions) {
return createChild(operation, description, timestamp, instrumenter, spanOptions);
}
@Override
public @NotNull ISpan startChild(
final @NotNull String operation,
@Nullable String description,
@Nullable SentryDate timestamp) {
return createChild(operation, description, timestamp, Instrumenter.SENTRY, new SpanOptions());
}
@Override
public @NotNull ISpan startChild(
final @NotNull String operation, final @Nullable String description) {
return startChild(operation, description, null, Instrumenter.SENTRY, new SpanOptions());
}
@Override
public @NotNull ISpan startChild(
@NotNull String operation, @Nullable String description, @NotNull SpanOptions spanOptions) {
return createChild(operation, description, null, Instrumenter.SENTRY, spanOptions);
}
@Override
public @NotNull ISpan startChild(
@NotNull SpanContext spanContext, @NotNull SpanOptions spanOptions) {
return createChild(spanContext, spanOptions);
}
private @NotNull ISpan createChild(
final @NotNull String operation,
final @Nullable String description,
@Nullable SentryDate timestamp,
final @NotNull Instrumenter instrumenter,
final @NotNull SpanOptions spanOptions) {
if (root.isFinished()) {
return NoOpSpan.getInstance();
}
if (!this.instrumenter.equals(instrumenter)) {
return NoOpSpan.getInstance();
}
if (children.size() < scopes.getOptions().getMaxSpans()) {
return root.startChild(operation, description, timestamp, instrumenter, spanOptions);
} else {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Span operation: %s, description: %s dropped due to limit reached. Returning NoOpSpan.",
operation,
description);
return NoOpSpan.getInstance();
}
}
@Override
public @NotNull SentryTraceHeader toSentryTrace() {
return root.toSentryTrace();
}
@Override
public void finish() {
this.finish(this.getStatus());
}
@Override
public void finish(@Nullable SpanStatus status) {
this.finish(status, null);
}
@SuppressWarnings({"JdkObsolete", "JavaUtilDate"})
@Override
@ApiStatus.Internal
public void finish(@Nullable SpanStatus status, @Nullable SentryDate finishDate) {
finish(status, finishDate, true, null);
}
@Override
public @Nullable TraceContext traceContext() {
if (scopes.getOptions().isTraceSampling()) {
final @Nullable Baggage baggage = getSpanContext().getBaggage();
if (baggage != null) {
updateBaggageValues(baggage);
return baggage.toTraceContext();
}
}
return null;
}
private void updateBaggageValues(final @NotNull Baggage baggage) {
try (final @NotNull ISentryLifecycleToken ignored = tracerLock.acquire()) {
if (baggage.isMutable()) {
final AtomicReference<SentryId> replayId = new AtomicReference<>();
final AtomicReference<String> environment = new AtomicReference<>();
// the combined view resolves current -> isolation -> global, matching what event capture
// sees, so the DSC cannot disagree with the environment on the events of the same trace
scopes.configureScope(
ScopeType.COMBINED,
scope -> {
replayId.set(scope.getReplayId());
environment.set(scope.getEnvironment());
});
baggage.setValuesFromTransaction(
getSpanContext().getTraceId(),
replayId.get(),
scopes.getOptions(),
environment.get(),
this.getSamplingDecision(),
getName(),
getTransactionNameSource());
baggage.freeze();
}
}
}
@Override
public @Nullable BaggageHeader toBaggageHeader(@Nullable List<String> thirdPartyBaggageHeaders) {
if (scopes.getOptions().isTraceSampling()) {
final @Nullable Baggage baggage = getSpanContext().getBaggage();
if (baggage != null) {
updateBaggageValues(baggage);
return BaggageHeader.fromBaggageAndOutgoingHeader(baggage, thirdPartyBaggageHeaders);
}
}
return null;
}
/**
* Returns true if no child span should keep this transaction from finishing.
*
* <p>Ignores idle spans. Including them would mean an idle transaction would never restart its
* idle timer once it had an unfinished idle span, causing the transaction to always live until
* its deadline.
*/
private boolean hasAllChildrenFinished() {
@NotNull final ListIterator<Span> iterator = this.children.listIterator();
while (iterator.hasNext()) {
@NotNull final Span span = iterator.next();
if (span.getOptions().isIdle()) {
continue;
}
// This is used in the spanFinishCallback, when the span isn't finished, but has a finish
// date
if (!span.isFinished() && span.getFinishDate() == null) {
return false;
}
}
return true;
}
@Override
public void setOperation(final @NotNull String operation) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"The transaction is already finished. Operation %s cannot be set",
operation);
return;
}
this.root.setOperation(operation);
}
@Override
public @NotNull String getOperation() {
return this.root.getOperation();
}
@Override
public void setDescription(final @Nullable String description) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"The transaction is already finished. Description %s cannot be set",
description);
return;
}
this.root.setDescription(description);
}
@Override
public @Nullable String getDescription() {
return this.root.getDescription();
}
@Override
public void setStatus(final @Nullable SpanStatus status) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"The transaction is already finished. Status %s cannot be set",
status == null ? "null" : status.name());
return;
}
this.root.setStatus(status);
}
@Override
public @Nullable SpanStatus getStatus() {
return this.root.getStatus();
}
@Override
public void setThrowable(final @Nullable Throwable throwable) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.DEBUG, "The transaction is already finished. Throwable cannot be set");
return;
}
this.root.setThrowable(throwable);
}
@Override
public @Nullable Throwable getThrowable() {
return this.root.getThrowable();
}
@Override
public @NotNull SpanContext getSpanContext() {
return this.root.getSpanContext();
}
@Override
public void setTag(final @Nullable String key, final @Nullable String value) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.DEBUG, "The transaction is already finished. Tag %s cannot be set", key);
return;
}
this.root.setTag(key, value);
}
@Override
public @Nullable String getTag(final @Nullable String key) {
return this.root.getTag(key);
}
@Override
public boolean isFinished() {
return this.root.isFinished();
}
@Override
public void setData(@Nullable String key, @Nullable Object value) {
if (root.isFinished()) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG, "The transaction is already finished. Data %s cannot be set", key);
return;
}
this.root.setData(key, value);
}
@Override
public @Nullable Object getData(@Nullable String key) {
return this.root.getData(key);
}
@ApiStatus.Internal
public void setMeasurementFromChild(final @NotNull String name, final @NotNull Number value) {
// We don't want to overwrite the root span measurement, if it comes from a child.
if (!root.getMeasurements().containsKey(name)) {
setMeasurement(name, value);
}
}
@ApiStatus.Internal
public void setMeasurementFromChild(
final @NotNull String name,
final @NotNull Number value,
final @NotNull MeasurementUnit unit) {
// We don't want to overwrite the root span measurement, if it comes from a child.
if (!root.getMeasurements().containsKey(name)) {
setMeasurement(name, value, unit);
}
}
@Override
public void setMeasurement(final @NotNull String name, final @NotNull Number value) {
root.setMeasurement(name, value);
}
@Override
public void setMeasurement(
final @NotNull String name,
final @NotNull Number value,
final @NotNull MeasurementUnit unit) {
root.setMeasurement(name, value, unit);
}
public @Nullable Map<String, Object> getData() {
return this.root.getData();
}
@Override
public @Nullable Boolean isSampled() {
return this.root.isSampled();
}
@Override
public @Nullable Boolean isProfileSampled() {
return this.root.isProfileSampled();
}
@Override
public @Nullable TracesSamplingDecision getSamplingDecision() {