Repository navigation
Expand file tree
/
Copy pathSentryCheckInAdvice.java
More file actions
239 lines (215 loc) · 8.57 KB
/
Copy pathSentryCheckInAdvice.java
File metadata and controls
239 lines (215 loc) · 8.57 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
package io.sentry.spring7.checkin;
import com.jakewharton.nopen.annotation.Open;
import io.sentry.CheckIn;
import io.sentry.CheckInStatus;
import io.sentry.DateUtils;
import io.sentry.IScopes;
import io.sentry.ISentryLifecycleToken;
import io.sentry.MonitorConfig;
import io.sentry.ScopesAdapter;
import io.sentry.SentryLevel;
import io.sentry.protocol.SentryId;
import io.sentry.time.Stopwatch;
import io.sentry.util.MonitorConfigUtils;
import io.sentry.util.Objects;
import io.sentry.util.TracingUtils;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringValueResolver;
/**
* Reports execution of every bean method annotated with {@link SentryCheckIn} as a monitor
* check-in.
*/
@ApiStatus.Internal
@Open
public class SentryCheckInAdvice implements MethodInterceptor, EmbeddedValueResolverAware {
// Spring before 5.3 parses crons with CronSequenceGenerator
private static final boolean LEGACY_CRON_PARSER =
!ClassUtils.isPresent(
"org.springframework.scheduling.support.CronExpression",
SentryCheckInAdvice.class.getClassLoader());
private final @NotNull IScopes scopes;
private @Nullable StringValueResolver resolver;
private final @NotNull Map<Method, CachedMonitorConfig> monitorConfigs =
new ConcurrentHashMap<>();
public SentryCheckInAdvice() {
this(ScopesAdapter.getInstance());
}
public SentryCheckInAdvice(final @NotNull IScopes scopes) {
this.scopes = Objects.requireNonNull(scopes, "scopes are required");
}
@Override
public @Nullable Object invoke(final @NotNull MethodInvocation invocation) throws Throwable {
final @Nullable Object target = invocation.getThis();
final Method mostSpecificMethod =
AopUtils.getMostSpecificMethod(
invocation.getMethod(), target != null ? target.getClass() : null);
@Nullable
SentryCheckIn checkInAnnotation =
AnnotationUtils.findAnnotation(mostSpecificMethod, SentryCheckIn.class);
if (checkInAnnotation == null) {
return invocation.proceed();
}
final boolean isHeartbeatOnly = checkInAnnotation.heartbeat();
@Nullable String monitorSlug = checkInAnnotation.value();
if (resolver != null) {
try {
monitorSlug = resolver.resolveStringValue(checkInAnnotation.value());
} catch (Throwable e) {
// When resolving fails, we fall back to the original string which may contain unresolved
// expressions. Testing shows this can also happen if properties cannot be resolved (without
// an exception being thrown). Sentry should alert the user about missed checkins in this
// case since the monitor slug won't match what is configured in Sentry.
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Slug for method annotated with @SentryCheckIn could not be resolved from properties.",
e);
}
}
if (ObjectUtils.isEmpty(monitorSlug)) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Not capturing check-in for method annotated with @SentryCheckIn because it does not specify a monitor slug.");
return invocation.proceed();
}
final @Nullable MonitorConfig monitorConfig =
!isHeartbeatOnly && checkInAnnotation.upsertMonitorConfig()
? monitorConfig(mostSpecificMethod)
: null;
try (final @NotNull ISentryLifecycleToken ignored =
scopes.forkedScopes("SentryCheckInAdvice").makeCurrent()) {
TracingUtils.startNewTrace(scopes);
@Nullable SentryId checkInId = null;
final @NotNull Stopwatch stopwatch =
Stopwatch.started(scopes.getOptions().getMonotonicTicker());
boolean didError = false;
try {
if (!isHeartbeatOnly) {
final @NotNull CheckIn inProgress = new CheckIn(monitorSlug, CheckInStatus.IN_PROGRESS);
inProgress.setMonitorConfig(monitorConfig);
checkInId = scopes.captureCheckIn(inProgress);
}
return invocation.proceed();
} catch (Throwable e) {
didError = true;
throw e;
} finally {
final @NotNull CheckInStatus status = didError ? CheckInStatus.ERROR : CheckInStatus.OK;
CheckIn checkIn = new CheckIn(checkInId, monitorSlug, status);
checkIn.setDuration(DateUtils.nanosToSeconds(stopwatch.elapsedNanos()));
scopes.captureCheckIn(checkIn);
}
}
}
private @Nullable MonitorConfig monitorConfig(final @NotNull Method method) {
return monitorConfigs.computeIfAbsent(
method, key -> new CachedMonitorConfig(monitorConfigFromScheduled(key)))
.config;
}
private @Nullable MonitorConfig monitorConfigFromScheduled(final @NotNull Method method) {
try {
final @NotNull Set<Scheduled> schedules =
AnnotatedElementUtils.getMergedRepeatableAnnotations(
method, Scheduled.class, Schedules.class);
if (schedules.size() != 1) {
return null;
}
final @NotNull Scheduled scheduled = schedules.iterator().next();
// timeUnit only exists from Spring 5.3.10, so read it as an attribute
final @Nullable Object timeUnitAttribute =
AnnotationUtils.getAnnotationAttributes(scheduled).get("timeUnit");
final @NotNull TimeUnit timeUnit =
timeUnitAttribute instanceof TimeUnit unit ? unit : TimeUnit.MILLISECONDS;
final @Nullable String cron = resolve(scheduled.cron());
// Spring only reads the zone for a cron
final @Nullable String zone =
cron == null || cron.isEmpty() ? null : resolve(scheduled.zone());
return MonitorConfigUtils.fromSpringScheduled(
cron,
zone,
periodMillis(scheduled.fixedRate(), scheduled.fixedRateString(), timeUnit),
periodMillis(scheduled.fixedDelay(), scheduled.fixedDelayString(), timeUnit),
LEGACY_CRON_PARSER);
} catch (RuntimeException e) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Could not derive a monitor config from @Scheduled for method annotated with @SentryCheckIn.",
e);
return null;
}
}
private @Nullable Long periodMillis(
final long value, final @NotNull String valueString, final @NotNull TimeUnit timeUnit) {
if (value >= 0) {
return timeUnit.toMillis(value);
}
final @Nullable String resolved = resolve(valueString);
if (resolved == null || resolved.isEmpty()) {
return null;
}
final @NotNull String trimmed = resolved.trim();
@Nullable Long millis = null;
if (trimmed.startsWith("P") || trimmed.startsWith("p")) {
try {
millis = Duration.parse(trimmed).toMillis();
} catch (DateTimeParseException | ArithmeticException e) {
// logged below
}
} else {
millis = MonitorConfigUtils.parsePeriodMillis(trimmed, timeUnit);
}
if (millis == null) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"Not sending a monitor config for @SentryCheckIn because the @Scheduled period '%s' could not be parsed.",
trimmed);
}
return millis;
}
private @Nullable String resolve(final @NotNull String value) {
if (resolver == null || value.isEmpty()) {
return value;
}
return resolver.resolveStringValue(value);
}
private static final class CachedMonitorConfig {
private final @Nullable MonitorConfig config;
private CachedMonitorConfig(final @Nullable MonitorConfig config) {
this.config = config;
}
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.resolver = resolver;
}
}