Repository navigation
Expand file tree
/
Copy pathSentryCheckInAdvice.java
More file actions
338 lines (305 loc) · 12.6 KB
/
Copy pathSentryCheckInAdvice.java
File metadata and controls
338 lines (305 loc) · 12.6 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
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.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
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 static final @NotNull Pattern WORD_BOUNDARY =
Pattern.compile("(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])");
private static final int MAX_SLUG_LENGTH = 50;
private final @NotNull IScopes scopes;
private final boolean monitorScheduledTasks;
private @Nullable StringValueResolver resolver;
private final @NotNull Map<Method, CachedMonitorConfig> monitorConfigs =
new ConcurrentHashMap<>();
private final @NotNull Map<String, String> derivedSlugOwners = new ConcurrentHashMap<>();
private final @NotNull Set<String> collidingSlugs = ConcurrentHashMap.newKeySet();
public SentryCheckInAdvice() {
this(ScopesAdapter.getInstance());
}
public SentryCheckInAdvice(final @NotNull IScopes scopes) {
this(scopes, false);
}
/**
* @param monitorScheduledTasks whether to also monitor {@code @Scheduled} methods without {@link
* SentryCheckIn}, using a slug derived from the class and method name
*/
public SentryCheckInAdvice(final @NotNull IScopes scopes, final boolean monitorScheduledTasks) {
this.scopes = Objects.requireNonNull(scopes, "scopes are required");
this.monitorScheduledTasks = monitorScheduledTasks;
}
@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) {
if (monitorScheduledTasks && isScheduled(mostSpecificMethod)) {
final @NotNull Class<?> targetClass =
target != null ? target.getClass() : mostSpecificMethod.getDeclaringClass();
final @NotNull String taskName = scheduledTaskName(targetClass, mostSpecificMethod);
final @Nullable MonitorConfig monitorConfig = monitorConfig(mostSpecificMethod);
if (monitorConfig == null) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.DEBUG,
"Not monitoring %s because Sentry Crons can't express its @Scheduled schedule.",
taskName);
return invocation.proceed();
}
final @NotNull String monitorSlug = scheduledTaskSlug(taskName);
warnOnSlugCollision(monitorSlug, targetClass, mostSpecificMethod);
return captureCheckIns(invocation, monitorSlug, false, monitorConfig);
}
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;
return captureCheckIns(invocation, monitorSlug, isHeartbeatOnly, monitorConfig);
}
private @Nullable Object captureCheckIns(
final @NotNull MethodInvocation invocation,
final @NotNull String monitorSlug,
final boolean isHeartbeatOnly,
final @Nullable MonitorConfig monitorConfig)
throws Throwable {
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 void warnOnSlugCollision(
final @NotNull String monitorSlug,
final @NotNull Class<?> targetClass,
final @NotNull Method method) {
final @NotNull String identity =
ClassUtils.getUserClass(targetClass).getName() + "." + method.getName();
final @Nullable String owner = derivedSlugOwners.putIfAbsent(monitorSlug, identity);
if (owner != null && !owner.equals(identity) && collidingSlugs.add(monitorSlug)) {
scopes
.getOptions()
.getLogger()
.log(
SentryLevel.WARNING,
"Monitor slug \"%s\" is used by both %s and %s, so their check-ins go to one monitor. Add @SentryCheckIn(\"your-slug\") to one of them.",
monitorSlug,
owner,
identity);
}
}
static boolean isScheduled(final @NotNull Method method) {
return !AnnotatedElementUtils.getMergedRepeatableAnnotations(
method, Scheduled.class, Schedules.class)
.isEmpty();
}
/** {@code ClassName.methodName}, with nested classes as {@code Outer.Inner}. */
static @NotNull String scheduledTaskName(
final @NotNull Class<?> targetClass, final @NotNull Method method) {
return ClassUtils.getShortName(ClassUtils.getUserClass(targetClass)) + "." + method.getName();
}
static @NotNull String scheduledTaskSlug(final @NotNull String taskName) {
final @NotNull String slug =
WORD_BOUNDARY
.matcher(taskName)
.replaceAll("-")
.toLowerCase(Locale.ROOT)
.replaceAll("[^a-z0-9]+", "-")
.replaceAll("^-+|-+$", "");
if (slug.length() <= MAX_SLUG_LENGTH) {
return slug;
}
// keep truncated slugs unique
final @NotNull CRC32 crc = new CRC32();
crc.update(slug.getBytes(StandardCharsets.UTF_8));
final @NotNull String hash = String.format(Locale.ROOT, "%08x", crc.getValue());
return slug.substring(0, MAX_SLUG_LENGTH - hash.length() - 1).replaceAll("-+$", "")
+ "-"
+ hash;
}
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.", 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 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;
}
}