-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathConsoleSchedulingIntegration.php
337 lines (279 loc) · 11.4 KB
/
ConsoleSchedulingIntegration.php
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
<?php
namespace Sentry\Laravel\Features;
use DateTimeZone;
use Illuminate\Console\Application as ConsoleApplication;
use Illuminate\Console\Events\ScheduledTaskFailed;
use Illuminate\Console\Events\ScheduledTaskFinished;
use Illuminate\Console\Events\ScheduledTaskStarting;
use Illuminate\Console\Scheduling\Event as SchedulingEvent;
use Illuminate\Contracts\Cache\Factory as Cache;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\ProcessUtils;
use Illuminate\Support\Str;
use RuntimeException;
use Sentry\CheckIn;
use Sentry\CheckInStatus;
use Sentry\Event as SentryEvent;
use Sentry\Laravel\Features\Concerns\TracksPushedScopesAndSpans;
use Sentry\MonitorConfig;
use Sentry\MonitorSchedule;
use Sentry\SentrySdk;
use Sentry\Tracing\SpanStatus;
use Sentry\Tracing\TransactionContext;
use Sentry\Tracing\TransactionSource;
class ConsoleSchedulingIntegration extends Feature
{
use TracksPushedScopesAndSpans;
/**
* @var string|null
*/
private $cacheStore = null;
/**
* @var array<string, CheckIn> The list of checkins that are currently in progress.
*/
private $checkInStore = [];
private $shouldHandleCheckIn = false;
public function register(): void
{
$startCheckIn = function (
?string $slug,
SchedulingEvent $scheduled,
?int $checkInMargin,
?int $maxRuntime,
bool $updateMonitorConfig,
?int $failureIssueThreshold,
?int $recoveryThreshold
) {
$this->startCheckIn(
$slug,
$scheduled,
$checkInMargin,
$maxRuntime,
$updateMonitorConfig,
$failureIssueThreshold,
$recoveryThreshold
);
};
$finishCheckIn = function (?string $slug, SchedulingEvent $scheduled, CheckInStatus $status) {
$this->finishCheckIn($slug, $scheduled, $status);
};
SchedulingEvent::macro('sentryMonitor', function (
?string $monitorSlug = null,
?int $checkInMargin = null,
?int $maxRuntime = null,
bool $updateMonitorConfig = true,
?int $failureIssueThreshold = null,
?int $recoveryThreshold = null
) use ($startCheckIn, $finishCheckIn) {
/** @var SchedulingEvent $this */
if ($monitorSlug === null && $this->command === null) {
throw new RuntimeException('The command string is null, please set a slug manually for this scheduled command using the `sentryMonitor(\'your-monitor-slug\')` macro.');
}
return $this
->before(function () use (
$startCheckIn,
$monitorSlug,
$checkInMargin,
$maxRuntime,
$updateMonitorConfig,
$failureIssueThreshold,
$recoveryThreshold
) {
/** @var SchedulingEvent $this */
$startCheckIn(
$monitorSlug,
$this,
$checkInMargin,
$maxRuntime,
$updateMonitorConfig,
$failureIssueThreshold,
$recoveryThreshold
);
})
->onSuccess(function () use ($finishCheckIn, $monitorSlug) {
/** @var SchedulingEvent $this */
$finishCheckIn($monitorSlug, $this, CheckInStatus::ok());
})
->onFailure(function () use ($finishCheckIn, $monitorSlug) {
/** @var SchedulingEvent $this */
$finishCheckIn($monitorSlug, $this, CheckInStatus::error());
});
});
}
public function isApplicable(): bool
{
return true;
}
public function onBoot(Dispatcher $events): void
{
$this->shouldHandleCheckIn = true;
$events->listen(ScheduledTaskStarting::class, [$this, 'handleScheduledTaskStarting']);
$events->listen(ScheduledTaskFinished::class, [$this, 'handleScheduledTaskFinished']);
$events->listen(ScheduledTaskFailed::class, [$this, 'handleScheduledTaskFailed']);
}
public function onBootInactive(): void
{
$this->shouldHandleCheckIn = false;
}
public function useCacheStore(?string $name): void
{
$this->cacheStore = $name;
}
public function handleScheduledTaskStarting(ScheduledTaskStarting $event): void
{
if (!$event->task) {
return;
}
// If the command is run in the background we need to add the trace argument to the command string
if ($event->task->command && $event->task->runInBackground) {
if (Str::contains($event->task->command, '--sentry-trace')) {
return;
}
$traceArgument = ProcessUtils::escapeArgument('console.command.scheduled');
$event->task->command = "{$event->task->command} --sentry-trace={$traceArgument}";
// We have modified the command string and at this point there is nothing for us to do
// The framework will create a child process and run the command in the background with the new command
// We will pick up the `--sentry-trace` option in the new process and start a new transaction from there
return;
}
// If the command is run in the background we don't want to start a transaction here since it will be useless because the actual work will take place in a different process
if ($event->task->runInBackground) {
return;
}
// When scheduling a command class the command name will be the most descriptive
// When a job is scheduled the command name is `null` and the job class name (or display name) is set as the description
// When a closure is scheduled both the command name and description are `null`
$name = $this->getCommandNameForScheduled($event->task) ?? $event->task->description ?? 'Closure';
$context = TransactionContext::make()
->setName($name)
->setSource(TransactionSource::task())
->setOp('console.command.scheduled')
->setStartTimestamp(microtime(true));
$transaction = SentrySdk::getCurrentHub()->startTransaction($context);
$this->pushSpan($transaction);
}
public function handleScheduledTaskFinished(): void
{
$this->maybeFinishSpan(SpanStatus::ok());
$this->maybePopScope();
}
public function handleScheduledTaskFailed(): void
{
$this->maybeFinishSpan(SpanStatus::internalError());
$this->maybePopScope();
}
private function startCheckIn(
?string $slug,
SchedulingEvent $scheduled,
?int $checkInMargin,
?int $maxRuntime,
bool $updateMonitorConfig,
?int $failureIssueThreshold,
?int $recoveryThreshold
): void {
if (!$this->shouldHandleCheckIn) {
return;
}
$checkInSlug = $slug ?? $this->makeSlugForScheduled($scheduled);
$checkIn = $this->createCheckIn($checkInSlug, CheckInStatus::inProgress());
if ($updateMonitorConfig || $slug === null) {
$timezone = $scheduled->timezone;
if ($timezone instanceof DateTimeZone) {
$timezone = $timezone->getName();
}
$checkIn->setMonitorConfig(new MonitorConfig(
MonitorSchedule::crontab($scheduled->getExpression()),
$checkInMargin,
$maxRuntime,
$timezone,
$failureIssueThreshold,
$recoveryThreshold
));
}
$cacheKey = $this->buildCacheKey($scheduled->mutexName(), $checkInSlug);
$this->checkInStore[$cacheKey] = $checkIn;
if ($scheduled->runInBackground) {
$this->resolveCache()->put($cacheKey, $checkIn->getId(), $scheduled->expiresAt * 60);
}
$this->sendCheckIn($checkIn);
}
private function finishCheckIn(?string $slug, SchedulingEvent $scheduled, CheckInStatus $status): void
{
if (!$this->shouldHandleCheckIn) {
return;
}
$mutex = $scheduled->mutexName();
$checkInSlug = $slug ?? $this->makeSlugForScheduled($scheduled);
$cacheKey = $this->buildCacheKey($mutex, $checkInSlug);
$checkIn = $this->checkInStore[$cacheKey] ?? null;
if ($checkIn === null && $scheduled->runInBackground) {
$checkInId = $this->resolveCache()->get($cacheKey);
if ($checkInId !== null) {
$checkIn = $this->createCheckIn($checkInSlug, $status, $checkInId);
}
}
// This should never happen (because we should always start before we finish), but better safe than sorry
if ($checkIn === null) {
return;
}
// We don't need to keep the checkIn ID stored since we finished executing the command
unset($this->checkInStore[$mutex]);
if ($scheduled->runInBackground) {
$this->resolveCache()->forget($cacheKey);
}
$checkIn->setStatus($status);
$this->sendCheckIn($checkIn);
}
private function sendCheckIn(CheckIn $checkIn): void
{
$event = SentryEvent::createCheckIn();
$event->setCheckIn($checkIn);
SentrySdk::getCurrentHub()->captureEvent($event);
}
private function createCheckIn(string $slug, CheckInStatus $status, ?string $id = null): CheckIn
{
$options = SentrySdk::getCurrentHub()->getClient()->getOptions();
return new CheckIn(
$slug,
$status,
$id,
$options->getRelease(),
$options->getEnvironment()
);
}
private function buildCacheKey(string $mutex, string $slug): string
{
// We use the mutex name as part of the cache key to avoid collisions between the same commands with the same schedule but with different slugs
return 'sentry:checkIn:' . sha1("{$mutex}:{$slug}");
}
private function makeSlugForScheduled(SchedulingEvent $scheduled): string
{
$generatedSlug = Str::slug(
str_replace(
// `:` is commonly used in the command name, so we replace it with `-` to avoid it being stripped out by the slug function
':',
'-',
trim(
// The command string always starts with the PHP binary, so we remove it since it's not relevant to the slug
Str::after($scheduled->command, ConsoleApplication::phpBinary())
)
)
);
return "scheduled_{$generatedSlug}";
}
private function getCommandNameForScheduled(SchedulingEvent $scheduled): ?string
{
if (!$scheduled->command) {
return null;
}
// The command string always starts with the PHP binary and artisan binary, so we remove it since it's not relevant to the name
return trim(
Str::after($scheduled->command, ConsoleApplication::phpBinary() . ' ' . ConsoleApplication::artisanBinary())
);
}
private function resolveCache(): Repository
{
return $this->container()->make(Cache::class)->store($this->cacheStore);
}
}