-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisMetricsRepository.php
More file actions
482 lines (424 loc) · 12.2 KB
/
Copy pathRedisMetricsRepository.php
File metadata and controls
482 lines (424 loc) · 12.2 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
<?php
namespace Laravel\Horizon\Repositories;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Redis\Factory as RedisFactory;
use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Support\Str;
use Laravel\Horizon\Contracts\MetricsRepository;
use Laravel\Horizon\Lock;
use Laravel\Horizon\LuaScripts;
use Laravel\Horizon\WaitTimeCalculator;
use Throwable;
class RedisMetricsRepository implements MetricsRepository
{
/**
* The Redis connection instance.
*
* @var \Illuminate\Contracts\Redis\Factory
*/
public $redis;
/**
* Create a new repository instance.
*
* @param \Illuminate\Contracts\Redis\Factory $redis
* @return void
*/
public function __construct(RedisFactory $redis)
{
$this->redis = $redis;
}
/**
* Get all of the class names that have metrics measurements.
*
* @return array
*/
public function measuredJobs()
{
$classes = (array) $this->connection()->smembers('measured_jobs');
return collect($classes)
->map(fn ($class) => preg_match('/job:(.*)$/', $class, $matches) ? $matches[1] : $class)
->sort()
->values()
->all();
}
/**
* Get all of the queues that have metrics measurements.
*
* @return array
*/
public function measuredQueues()
{
$queues = (array) $this->connection()->smembers('measured_queues');
return collect($queues)
->map(fn ($class) => preg_match('/queue:(.*)$/', $class, $matches) ? $matches[1] : $class)
->sort()
->values()
->all();
}
/**
* Get the jobs processed per minute since the last snapshot.
*
* @return float
*/
public function jobsProcessedPerMinute()
{
return round($this->throughput() / $this->minutesSinceLastSnapshot());
}
/**
* Get the application's total throughput since the last snapshot.
*
* @return int
*/
public function throughput()
{
return collect($this->measuredQueues())
->reduce(fn ($carry, $queue) => $carry + $this->connection()->hget('queue:'.$queue, 'throughput'), 0);
}
/**
* Get the throughput for a given job.
*
* @param string $job
* @return int
*/
public function throughputForJob($job)
{
return $this->throughputFor('job:'.$job);
}
/**
* Get the throughput for a given queue.
*
* @param string $queue
* @return int
*/
public function throughputForQueue($queue)
{
return $this->throughputFor('queue:'.$queue);
}
/**
* Get the throughput for a given key.
*
* @param string $key
* @return int
*/
protected function throughputFor($key)
{
return (int) $this->connection()->hget($key, 'throughput');
}
/**
* Get the average runtime for a given job in milliseconds.
*
* @param string $job
* @return float
*/
public function runtimeForJob($job)
{
return $this->runtimeFor('job:'.$job);
}
/**
* Get the average runtime for a given queue in milliseconds.
*
* @param string $queue
* @return float
*/
public function runtimeForQueue($queue)
{
return $this->runtimeFor('queue:'.$queue);
}
/**
* Get the average runtime for a given key in milliseconds.
*
* @param string $key
* @return float
*/
protected function runtimeFor($key)
{
return (float) $this->connection()->hget($key, 'runtime');
}
/**
* Get the queue that has the longest runtime.
*
* @return int
*/
public function queueWithMaximumRuntime()
{
return collect($this->measuredQueues())
->sortBy(function ($queue) {
if ($snapshots = $this->connection()->zrange('snapshot:queue:'.$queue, -1, -1)) {
return json_decode($snapshots[0])->runtime;
}
})
->last();
}
/**
* Get the queue that has the most throughput.
*
* @return int
*/
public function queueWithMaximumThroughput()
{
return collect($this->measuredQueues())
->sortBy(function ($queue) {
if ($snapshots = $this->connection()->zrange('snapshot:queue:'.$queue, -1, -1)) {
return json_decode($snapshots[0])->throughput;
}
})
->last();
}
/**
* Increment the metrics information for a job.
*
* @param string $job
* @param float|null $runtime
* @return void
*/
public function incrementJob($job, $runtime)
{
$this->connection()->eval(LuaScripts::updateMetrics(), 2,
'job:'.$job, 'measured_jobs', str_replace(',', '.', (string) $runtime)
);
}
/**
* Increment the metrics information for a queue.
*
* @param string $queue
* @param float|null $runtime
* @return void
*/
public function incrementQueue($queue, $runtime)
{
$this->connection()->eval(LuaScripts::updateMetrics(), 2,
'queue:'.$queue, 'measured_queues', str_replace(',', '.', (string) $runtime)
);
}
/**
* Get all of the snapshots for the given job.
*
* @param string $job
* @return array
*/
public function snapshotsForJob($job)
{
return $this->snapshotsFor('job:'.$job);
}
/**
* Get all of the snapshots for the given queue.
*
* @param string $queue
* @return array
*/
public function snapshotsForQueue($queue)
{
return $this->snapshotsFor('queue:'.$queue);
}
/**
* Get all of the snapshots for the given key.
*
* @param string $key
* @return array
*/
protected function snapshotsFor($key)
{
return collect($this->connection()->zrange('snapshot:'.$key, 0, -1))
->map(fn ($snapshot) => (object) json_decode($snapshot, true))
->values()
->all();
}
/**
* Store a snapshot of the metrics information.
*
* @return void
*/
public function snapshot()
{
collect($this->measuredJobs())->each(function ($job) {
$this->storeSnapshotForJob($job);
});
collect($this->measuredQueues())->each(function ($queue) {
$this->storeSnapshotForQueue($queue);
});
$this->storeSnapshotTimestamp();
}
/**
* Store a snapshot for the given job.
*
* @param string $job
* @return void
*/
protected function storeSnapshotForJob($job)
{
$data = $this->baseSnapshotData($key = 'job:'.$job);
$this->connection()->zadd(
'snapshot:'.$key, $time = CarbonImmutable::now()->getTimestamp(), json_encode([
'throughput' => $data['throughput'],
'runtime' => $data['runtime'],
'time' => $time,
])
);
$this->connection()->zremrangebyrank(
'snapshot:'.$key, 0, -abs(1 + config('horizon.metrics.trim_snapshots.job', 24))
);
}
/**
* Store a snapshot for the given queue.
*
* @param string $queue
* @return void
*/
protected function storeSnapshotForQueue($queue)
{
$data = $this->baseSnapshotData($key = 'queue:'.$queue);
$this->connection()->zadd(
'snapshot:'.$key, $time = CarbonImmutable::now()->getTimestamp(), json_encode([
'throughput' => $data['throughput'],
'runtime' => $data['runtime'],
'wait' => app(WaitTimeCalculator::class)->calculateFor($queue),
'time' => $time,
])
);
$this->connection()->zremrangebyrank(
'snapshot:'.$key, 0, -abs(1 + config('horizon.metrics.trim_snapshots.queue', 24))
);
}
/**
* Get the base snapshot data for a given key.
*
* @param string $key
* @return array
*/
protected function baseSnapshotData($key)
{
$responses = $this->connection()->transaction(function ($trans) use ($key) {
$trans->hmget($key, ['throughput', 'runtime']);
$trans->del($key);
});
if (! is_array($responses[0])) {
return ['throughput' => null, 'runtime' => null];
}
$snapshot = array_values($responses[0]);
return [
'throughput' => $snapshot[0],
'runtime' => $snapshot[1],
];
}
/**
* Get the number of minutes passed since the last snapshot.
*
* @return float
*/
protected function minutesSinceLastSnapshot()
{
$lastSnapshotAt = (int) ($this->connection()->get('last_snapshot_at')
?: $this->storeSnapshotTimestamp());
return max(
(CarbonImmutable::now()->getTimestamp() - $lastSnapshotAt) / 60, 1
);
}
/**
* Store the current timestamp as the "last snapshot timestamp".
*
* @return int
*/
protected function storeSnapshotTimestamp()
{
return tap(CarbonImmutable::now()->getTimestamp(), function ($timestamp) {
$this->connection()->set('last_snapshot_at', $timestamp);
});
}
/**
* Attempt to acquire a lock to monitor the queue wait times.
*
* @return bool
*/
public function acquireWaitTimeMonitorLock()
{
return app(Lock::class)->get('monitor:time-to-clear');
}
/**
* Clear the metrics for a key.
*
* @param string $key
* @return void
*/
public function forget($key)
{
$this->connection()->del($key);
}
/**
* Delete all stored metrics information.
*
* @return void
*/
public function clear()
{
$this->forget('last_snapshot_at');
$this->forget('measured_jobs');
$this->forget('measured_queues');
$this->forget('metrics:snapshot');
$connection = $this->connection();
// phpredis 6.1+ requires the SCAN cursor to start as null, while predis and older phpredis expect "0"...
$defaultCursorValue = match (true) {
$connection instanceof PhpRedisConnection && version_compare(phpversion('redis'), '6.1.0', '>=') => null,
default => '0',
};
foreach (['queue:*', 'job:*', 'snapshot:*'] as $pattern) {
$cursor = $defaultCursorValue;
do {
$scanResult = $connection->scan(
$cursor, ['match' => $this->snapshotPatternToMatch($pattern)]
);
if (! is_array($scanResult)) {
break;
}
[$cursor, $keys] = $scanResult;
foreach ($keys ?? [] as $key) {
$this->forget(Str::after($key, config('horizon.prefix')));
}
} while (((string) $cursor) !== $defaultCursorValue);
}
}
/**
* Get the Redis SCAN match pattern for the given metric pattern.
*
* @param string $pattern
* @return string
*/
protected function snapshotPatternToMatch($pattern)
{
return $this->usesPhpRedisScanPrefix()
? $pattern
: config('horizon.prefix').$pattern;
}
/**
* Determine if PhpRedis prefixes SCAN patterns itself.
*
* @return bool
*/
protected function usesPhpRedisScanPrefix()
{
if (! defined('Redis::OPT_SCAN') || ! defined('Redis::SCAN_PREFIX')) {
return false;
}
$connection = $this->connection();
if (! method_exists($connection, 'client')) {
return false;
}
$client = $connection->client();
if (! is_object($client) || ! method_exists($client, 'getOption')) {
return false;
}
try {
return (int) $client->getOption(\Redis::OPT_SCAN) === \Redis::SCAN_PREFIX;
} catch (Throwable) {
return false;
}
}
/**
* Get the Redis connection instance.
*
* @return \Illuminate\Redis\Connections\Connection
*/
public function connection()
{
return $this->redis->connection('horizon');
}
}