-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAJAXgetaql.php
More file actions
2004 lines (1887 loc) · 89 KB
/
AJAXgetaql.php
File metadata and controls
2004 lines (1887 loc) · 89 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
<?php
/*
*
* aql - Active Query Listing
*
* Copyright (C) 2018 Kevin Benton - kbcmdba [at] gmail [dot] com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
namespace com\kbcmdba\aql ;
require_once 'vendor/autoload.php';
use com\kbcmdba\aql\Libs\Config ;
use com\kbcmdba\aql\Libs\DBConnection ;
use com\kbcmdba\aql\Libs\MaintenanceWindow ;
use com\kbcmdba\aql\Libs\Tools ;
// Ensure AJAX response completes within 10 seconds
set_time_limit( 10 ) ;
header('Content-type: application/json') ;
header('Access-Control-Allow-Origin: *') ;
header('Expires: Thu, 01 Mar 2018 00:00:00 GMT') ;
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0') ;
header('Cache-Control: post-check=0, pre-check=0', false) ;
header('Pragma: no-cache') ;
$startTime = microtime( true ) ;
$overviewData = [
'aQPS' => -1
, 'blank' => 0
, 'blocked' => 0
, 'blocking' => 0
, 'duplicate' => 0
, 'level0' => 0
, 'level1' => 0
, 'level2' => 0
, 'level3' => 0
, 'level4' => 0
, 'level9' => 0
, 'longest_running' => -1
, 'maxConnections' => 0
, 'ro' => 0
, 'rw' => 0
, 'similar' => 0
, 'threads' => 0
, 'threadsConnected' => 0
, 'threadsRunning' => 0
, 'time' => 0
, 'unique' => 0
, 'uptime' => 0
, 'version' => ''
];
$queries = [] ;
$safeQueries = [] ;
$slaveData = [] ;
$longestRunning = -1 ;
// Blocking cache - stores recent blocking relationships for 60 seconds
// Supports Redis (preferred) with file-based fallback
define( 'BLOCKING_CACHE_DIR', __DIR__ . '/cache' ) ;
define( 'BLOCKING_CACHE_TTL', 60 ) ; // seconds
define( 'BLOCKING_CACHE_REDIS_HOST', '127.0.0.1' ) ;
define( 'BLOCKING_CACHE_REDIS_PORT', 6379 ) ;
define( 'BLOCKING_CACHE_REDIS_PREFIX', 'aql:blocking:' ) ;
// Cache backend detection - try Redis first, fall back to file
$_blockingCacheRedis = null ;
$_blockingCacheType = 'file' ;
function getBlockingCacheRedis() {
global $_blockingCacheRedis, $_blockingCacheType ;
if ( $_blockingCacheRedis === null && class_exists( 'Redis' ) ) {
try {
$_blockingCacheRedis = new \Redis() ;
if ( @$_blockingCacheRedis->connect( BLOCKING_CACHE_REDIS_HOST, BLOCKING_CACHE_REDIS_PORT, 0.5 ) ) {
$_blockingCacheType = 'redis' ;
} else {
$_blockingCacheRedis = false ;
}
} catch ( \Exception $e ) {
$_blockingCacheRedis = false ;
}
}
return $_blockingCacheRedis ?: null ;
}
function getBlockingCacheKey( $hostname ) {
$safeHost = preg_replace( '/[^a-zA-Z0-9._-]/', '_', $hostname ) ;
return BLOCKING_CACHE_REDIS_PREFIX . $safeHost ;
}
function getBlockingCacheFile( $hostname ) {
$safeHost = preg_replace( '/[^a-zA-Z0-9._-]/', '_', $hostname ) ;
return BLOCKING_CACHE_DIR . '/blocking_' . $safeHost . '.json' ;
}
function readBlockingCache( $hostname ) {
global $_blockingCacheType ;
$redis = getBlockingCacheRedis() ;
if ( $redis ) {
// Redis: get all entries, already filtered by TTL
$key = getBlockingCacheKey( $hostname ) ;
$data = $redis->get( $key ) ;
if ( $data === false ) {
return [] ;
}
$entries = @json_decode( $data, true ) ;
return is_array( $entries ) ? $entries : [] ;
}
// File fallback
$file = getBlockingCacheFile( $hostname ) ;
if ( !file_exists( $file ) ) {
return [] ;
}
$data = @json_decode( file_get_contents( $file ), true ) ;
if ( !is_array( $data ) ) {
return [] ;
}
// Filter out expired entries (file cache only - Redis handles TTL)
$now = time() ;
$valid = [] ;
foreach ( $data as $entry ) {
if ( isset( $entry['timestamp'] ) && ( $now - $entry['timestamp'] ) < BLOCKING_CACHE_TTL ) {
$valid[] = $entry ;
}
}
return $valid ;
}
function writeBlockingCache( $hostname, $entries ) {
$redis = getBlockingCacheRedis() ;
// Read existing, merge new
$existing = readBlockingCache( $hostname ) ;
$now = time() ;
// Add timestamp to new entries
foreach ( $entries as &$entry ) {
if ( !isset( $entry['timestamp'] ) ) {
$entry['timestamp'] = $now ;
}
}
// Merge: keep existing entries that aren't duplicates of new ones
$merged = $entries ;
foreach ( $existing as $old ) {
$isDupe = false ;
foreach ( $entries as $new ) {
if ( $old['blockerThreadId'] == $new['blockerThreadId']
&& $old['waitingThreadId'] == $new['waitingThreadId'] ) {
$isDupe = true ;
break ;
}
}
if ( !$isDupe ) {
$merged[] = $old ;
}
}
if ( $redis ) {
// Redis: set with TTL
$key = getBlockingCacheKey( $hostname ) ;
$redis->setex( $key, BLOCKING_CACHE_TTL, json_encode( $merged ) ) ;
} else {
// File fallback
@file_put_contents( getBlockingCacheFile( $hostname ), json_encode( $merged ), LOCK_EX ) ;
}
}
function getCachedBlockersForThread( $hostname, $waitingThreadId ) {
$cache = readBlockingCache( $hostname ) ;
$blockers = [] ;
foreach ( $cache as $entry ) {
if ( $entry['waitingThreadId'] == $waitingThreadId ) {
$blockers[] = $entry ;
}
}
return $blockers ;
}
function getBlockingCacheType() {
global $_blockingCacheType ;
getBlockingCacheRedis() ; // Initialize
return $_blockingCacheType ;
}
/**
* Normalize query for hashing - replace literals to create fingerprint
* Matches JavaScript normalizeQueryForHash() in common.js
* @param string $query SQL query text
* @return string Normalized query
*/
function normalizeQueryForHash( $query ) {
$normalized = $query ;
// Remove SQL comments first (may contain sensitive data)
// Multi-line comments: /* ... */
$normalized = preg_replace( '/\/\*.*?\*\//s', '/**/deleted', $normalized ) ;
// Single-line comments: -- ... (MySQL requires space after --)
$normalized = preg_replace( '/-- .*$/m', '-- deleted', $normalized ) ;
// Single-line comments: # ... (MySQL style)
$normalized = preg_replace( '/#.*$/m', '# deleted', $normalized ) ;
// Hex/binary literals BEFORE string literals (they use quotes too)
// Hex: 0xDEADBEEF, x'1A2B', X'1A2B'
$normalized = preg_replace( '/0x[0-9a-fA-F]+/', 'N', $normalized ) ;
$normalized = preg_replace( "/[xX]'[0-9a-fA-F]*'/", 'N', $normalized ) ;
// Binary: 0b1010, b'1010', B'1010'
$normalized = preg_replace( '/0b[01]+/', 'N', $normalized ) ;
$normalized = preg_replace( "/[bB]'[01]*'/", 'N', $normalized ) ;
// Single-quoted strings with escaped quotes -> 'S'
// Handles: 'simple', 'it\'s escaped', 'has ''doubled'' quotes'
$normalized = preg_replace( "/'(?:[^'\\\\]|\\\\.)*'/", "'S'", $normalized ) ;
$normalized = preg_replace( "/'(?:[^']|'')*'/", "'S'", $normalized ) ; // MySQL doubled quotes
// Double-quoted strings with escaped quotes -> "S"
$normalized = preg_replace( '/"(?:[^"\\\\]|\\\\.)*"/', '"S"', $normalized ) ;
// Numbers -> N (integers, decimals, scientific notation)
$normalized = preg_replace( '/\b\d+\.?\d*(?:[eE][+-]?\d+)?\b/', 'N', $normalized ) ;
// Collapse multiple blank lines into single newline for compact storage
$normalized = preg_replace( '/\n\s*\n/', "\n", $normalized ) ;
return $normalized ;
}
/**
* Hash string using djb2 algorithm - matches JavaScript hashString() in common.js
* @param string $str String to hash
* @return string Hex hash (16 chars)
*/
function hashQueryString( $str ) {
$hash = 5381 ;
$len = strlen( $str ) ;
for ( $i = 0 ; $i < $len ; $i++ ) {
$hash = ( ( $hash << 5 ) + $hash ) + ord( $str[$i] ) ;
$hash = $hash & 0xFFFFFFFF ; // Keep as 32-bit
}
return str_pad( dechex( abs( $hash ) ), 16, '0', STR_PAD_LEFT ) ;
}
/**
* Log a blocking query to the blocking_history table
* Uses INSERT ... ON DUPLICATE KEY UPDATE for deduplication by query_hash
* @param int $hostId Host ID from aql_db.host table
* @param string $user MySQL user executing the blocking query
* @param string $sourceHost Source host/IP of the connection
* @param string $dbName Database name (may be null)
* @param string $queryText Original query text (will be normalized)
* @param int $blockedCount Number of queries being blocked
* @param int $blockTimeSecs Duration of the blocking in seconds
*/
function logBlockingQuery( $hostId, $user, $sourceHost, $dbName, $queryText, $blockedCount, $blockTimeSecs ) {
try {
$dbc = new DBConnection() ;
$dbh = $dbc->getConnection() ;
// Handle negative time values (possible due to network time sync issues)
$blockTimeSecs = max( 0, (int) $blockTimeSecs ) ;
$normalizedQuery = normalizeQueryForHash( $queryText ) ;
$queryHash = hashQueryString( $normalizedQuery ) ;
// INSERT or UPDATE - increment counts if exists, track max block time
$sql = "INSERT INTO aql_db.blocking_history
(host_id, query_hash, user, source_host, db_name, query_text, blocked_count, total_blocked, max_block_secs)
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
ON DUPLICATE KEY UPDATE
blocked_count = blocked_count + 1,
total_blocked = total_blocked + VALUES(total_blocked),
max_block_secs = GREATEST(max_block_secs, VALUES(max_block_secs)),
last_seen = CURRENT_TIMESTAMP" ;
$stmt = $dbh->prepare( $sql ) ;
$stmt->bind_param( 'isssssii', $hostId, $queryHash, $user, $sourceHost, $dbName, $normalizedQuery, $blockedCount, $blockTimeSecs ) ;
$stmt->execute() ;
$stmt->close() ;
} catch ( \Exception $e ) {
// Silently fail - don't break AQL if logging fails
error_log( "AQL blocking_history logging failed: " . $e->getMessage() ) ;
}
}
/**
* Purge old entries from blocking_history (older than 90 days)
* Called occasionally to prevent unbounded table growth
*/
function purgeOldBlockingHistory() {
try {
$dbc = new DBConnection() ;
$dbh = $dbc->getConnection() ;
$dbh->query( "DELETE FROM aql_db.blocking_history WHERE last_seen < DATE_SUB(NOW(), INTERVAL 90 DAY)" ) ;
} catch ( \Exception $e ) {
error_log( "AQL blocking_history purge failed: " . $e->getMessage() ) ;
}
}
/**
* Look up host_id from hostname:port string
* @param string $hostnamePort Format "hostname:port"
* @return int|null Host ID or null if not found
*/
function getHostIdFromHostname( $hostnamePort ) {
static $cache = [] ;
if ( isset( $cache[$hostnamePort] ) ) {
return $cache[$hostnamePort] ;
}
try {
$parts = explode( ':', $hostnamePort ) ;
$hostname = $parts[0] ;
$port = isset( $parts[1] ) ? (int) $parts[1] : 3306 ;
$dbc = new DBConnection() ;
$dbh = $dbc->getConnection() ;
$stmt = $dbh->prepare( "SELECT host_id FROM aql_db.host WHERE hostname = ? AND port_number = ?" ) ;
$stmt->bind_param( 'si', $hostname, $port ) ;
$stmt->execute() ;
$result = $stmt->get_result() ;
$row = $result->fetch_assoc() ;
$stmt->close() ;
$hostId = $row ? (int) $row['host_id'] : null ;
$cache[$hostnamePort] = $hostId ;
return $hostId ;
} catch ( \Exception $e ) {
error_log( "AQL getHostIdFromHostname failed: " . $e->getMessage() ) ;
return null ;
}
}
/**
* Handle Redis host monitoring
* Gathers metrics from Redis INFO, CLIENT LIST, and SLOWLOG commands
*
* @param string $hostname Host:port string
* @param int|null $hostId Host ID from aql_db.host
* @param array $hostGroups Groups this host belongs to
* @param array|null $maintenanceInfo Active maintenance window info
* @param Config $config AQL configuration object
*/
function handleRedisHost( $hostname, $hostId, $hostGroups, $maintenanceInfo, $config, $debug = false, $startTime = 0, $dispatchMs = 0 ) {
if ( $startTime <= 0 ) { $startTime = microtime( true ) ; }
$renderTimeData = [ 'dispatch' => $dispatchMs ] ;
$redisOverviewData = [
'hostname' => $hostname,
'hostId' => $hostId,
'version' => '',
'uptime' => 0,
'uptimeHuman' => '',
'usedMemory' => 0,
'usedMemoryHuman' => '',
'maxMemory' => 0,
'maxMemoryHuman' => '',
'memoryPct' => 0,
'connectedClients' => 0,
'blockedClients' => 0,
'maxClients' => 0,
'keyspaceHits' => 0,
'keyspaceMisses' => 0,
'hitRatio' => 0,
'evictedKeys' => 0,
'rejectedConnections' => 0,
'fragmentationRatio' => 0,
'role' => '',
'replLag' => null,
'level' => 0,
// Persistence status
'rdbLastSaveTime' => null,
'rdbLastSaveAgo' => null,
'rdbChangesPending' => 0,
'aofEnabled' => false,
'aofLastRewriteSecs' => null,
] ;
$slowlogData = [] ;
$clientData = [] ;
$commandStats = [] ;
// Phase 3: Advanced diagnostics
$memoryStats = [] ;
$latencyData = [] ;
$latencyDoctor = '' ;
$latencyHistory = [] ;
$memoryDoctor = '' ;
$pubsubData = [ 'channels' => [], 'patterns' => 0 ] ;
$streamsData = [] ;
$pendingData = [] ;
// Debug mode data (only populated when $debug is true)
$debugData = [] ;
try {
// Parse hostname and port
$parts = explode( ':', $hostname ) ;
$redisHost = $parts[0] ;
$redisPort = isset( $parts[1] ) ? (int) $parts[1] : 6379 ;
// Check if phpredis extension is available
if ( !class_exists( 'Redis' ) ) {
throw new \Exception( 'phpredis extension not installed' ) ;
}
// Connect to Redis
$phaseStart = microtime( true ) ;
$redis = new \Redis() ;
$timeout = $config->getRedisConnectTimeout() ;
if ( !@$redis->connect( $redisHost, $redisPort, $timeout ) ) {
throw new \Exception( "Failed to connect to Redis at $redisHost:$redisPort" ) ;
}
// Authenticate if configured
$redisUser = $config->getRedisUser() ;
$redisPassword = $config->getRedisPassword() ;
if ( !empty( $redisPassword ) ) {
// Redis 6+ ACL authentication with username
if ( !empty( $redisUser ) ) {
if ( !@$redis->auth( [ $redisUser, $redisPassword ] ) ) {
throw new \Exception( 'Redis authentication failed (ACL)' ) ;
}
} else {
// Legacy AUTH with password only
if ( !@$redis->auth( $redisPassword ) ) {
throw new \Exception( 'Redis authentication failed' ) ;
}
}
}
// Select database if configured
$redisDb = $config->getRedisDatabase() ;
if ( $redisDb > 0 ) {
$redis->select( $redisDb ) ;
}
$renderTimeData['connect'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Get INFO (all sections)
$phaseStart = microtime( true ) ;
$infoRaw = $redis->info() ;
if ( $infoRaw === false ) {
throw new \Exception( 'Failed to get Redis INFO' ) ;
}
// Parse INFO into overview data
$redisOverviewData['version'] = $infoRaw['redis_version'] ?? '' ;
$redisOverviewData['uptime'] = (int) ( $infoRaw['uptime_in_seconds'] ?? 0 ) ;
$redisOverviewData['uptimeHuman'] = Tools::friendlyTime( $redisOverviewData['uptime'] ) ;
$redisOverviewData['usedMemory'] = (int) ( $infoRaw['used_memory'] ?? 0 ) ;
$redisOverviewData['usedMemoryHuman'] = $infoRaw['used_memory_human'] ?? '0B' ;
$redisOverviewData['usedMemoryRss'] = (int) ( $infoRaw['used_memory_rss'] ?? 0 ) ;
$redisOverviewData['maxMemory'] = (int) ( $infoRaw['maxmemory'] ?? 0 ) ;
$redisOverviewData['maxMemoryHuman'] = $infoRaw['maxmemory_human'] ?? '0B' ;
$redisOverviewData['connectedClients'] = (int) ( $infoRaw['connected_clients'] ?? 0 ) ;
$redisOverviewData['blockedClients'] = (int) ( $infoRaw['blocked_clients'] ?? 0 ) ;
$redisOverviewData['keyspaceHits'] = (int) ( $infoRaw['keyspace_hits'] ?? 0 ) ;
$redisOverviewData['keyspaceMisses'] = (int) ( $infoRaw['keyspace_misses'] ?? 0 ) ;
$redisOverviewData['evictedKeys'] = (int) ( $infoRaw['evicted_keys'] ?? 0 ) ;
$redisOverviewData['rejectedConnections'] = (int) ( $infoRaw['rejected_connections'] ?? 0 ) ;
$redisOverviewData['fragmentationRatio'] = (float) ( $infoRaw['mem_fragmentation_ratio'] ?? 1.0 ) ;
$redisOverviewData['role'] = $infoRaw['role'] ?? 'unknown' ;
// Calculate memory percentage (avoid division by zero)
if ( $redisOverviewData['maxMemory'] > 0 ) {
$redisOverviewData['memoryPct'] = round(
( $redisOverviewData['usedMemory'] / $redisOverviewData['maxMemory'] ) * 100, 1
) ;
}
// Calculate hit ratio
$totalRequests = $redisOverviewData['keyspaceHits'] + $redisOverviewData['keyspaceMisses'] ;
if ( $totalRequests > 0 ) {
$redisOverviewData['hitRatio'] = round(
( $redisOverviewData['keyspaceHits'] / $totalRequests ) * 100, 1
) ;
}
// Calculate replication lag for replicas
if ( $redisOverviewData['role'] === 'slave' ) {
$masterOffset = (int) ( $infoRaw['master_repl_offset'] ?? 0 ) ;
$slaveOffset = (int) ( $infoRaw['slave_repl_offset'] ?? 0 ) ;
if ( $masterOffset > 0 ) {
$redisOverviewData['replLag'] = $masterOffset - $slaveOffset ;
}
$redisOverviewData['masterLinkStatus'] = $infoRaw['master_link_status'] ?? 'unknown' ;
}
// Parse persistence status from INFO
$rdbLastSave = (int) ( $infoRaw['rdb_last_save_time'] ?? 0 ) ;
if ( $rdbLastSave > 0 ) {
$redisOverviewData['rdbLastSaveTime'] = date( 'Y-m-d H:i:s', $rdbLastSave ) ;
$redisOverviewData['rdbLastSaveAgo'] = time() - $rdbLastSave ;
}
$redisOverviewData['rdbChangesPending'] = (int) ( $infoRaw['rdb_changes_since_last_save'] ?? 0 ) ;
$redisOverviewData['aofEnabled'] = ( ( $infoRaw['aof_enabled'] ?? '0' ) === '1' ) ;
if ( $redisOverviewData['aofEnabled'] ) {
$aofRewrite = (int) ( $infoRaw['aof_last_rewrite_time_sec'] ?? -1 ) ;
$redisOverviewData['aofLastRewriteSecs'] = ( $aofRewrite >= 0 ) ? $aofRewrite : null ;
}
// Get max clients from CONFIG
try {
$maxClients = $redis->config( 'GET', 'maxclients' ) ;
$redisOverviewData['maxClients'] = (int) ( $maxClients['maxclients'] ?? 10000 ) ;
} catch ( \Exception $e ) {
$redisOverviewData['maxClients'] = 10000 ; // Default
}
$renderTimeData['info'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Parse commandstats from INFO commandstats section (not included in default INFO)
$phaseStart = microtime( true ) ;
try {
$cmdStatsRaw = $redis->info( 'commandstats' ) ;
if ( is_array( $cmdStatsRaw ) ) {
foreach ( $cmdStatsRaw as $key => $value ) {
if ( strpos( $key, 'cmdstat_' ) === 0 ) {
$cmdName = substr( $key, 8 ) ; // Remove 'cmdstat_' prefix
// Parse value string: "calls=N,usec=N,usec_per_call=N.NN,..."
$stats = [] ;
foreach ( explode( ',', $value ) as $part ) {
$kv = explode( '=', $part, 2 ) ;
if ( count( $kv ) === 2 ) {
$stats[ $kv[0] ] = is_numeric( $kv[1] ) ? (float) $kv[1] : $kv[1] ;
}
}
if ( !empty( $stats ) ) {
$commandStats[] = [
'command' => $cmdName,
'calls' => (int) ( $stats['calls'] ?? 0 ),
'usec' => (int) ( $stats['usec'] ?? 0 ),
'usecPerCall' => (float) ( $stats['usec_per_call'] ?? 0 ),
] ;
}
}
}
}
} catch ( \Exception $e ) {
// commandstats may not be available - log for verifyConfiguration.php to catch
error_log( "AQL Redis commandstats failed for $hostname: " . $e->getMessage() ) ;
}
// Sort by calls descending, keep top 10
usort( $commandStats, function( $a, $b ) { return $b['calls'] - $a['calls'] ; } ) ;
$commandStats = array_slice( $commandStats, 0, 10 ) ;
$renderTimeData['commandStats'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Calculate alert level based on metrics
$level = 0 ;
// Level 9: Connection error (handled in catch)
// Level 4: Critical - data loss or service unavailable
// Note: evictedKeys handled in JS via sessionStorage delta tracking
if ( $redisOverviewData['rejectedConnections'] > 0 ) {
$level = max( $level, 4 ) ; // Can't accept connections
}
if ( $redisOverviewData['memoryPct'] > 95 ) {
$level = max( $level, 4 ) ;
}
if ( $redisOverviewData['role'] === 'slave' && ( $infoRaw['master_link_status'] ?? 'up' ) === 'down' ) {
$level = max( $level, 4 ) ; // Replication broken
}
// Level 3: Warning
// Fragmentation: only warn if wasted bytes > 100MB (ratio alone misleads on small instances)
$fragBytes = $redisOverviewData['usedMemoryRss'] - $redisOverviewData['usedMemory'] ;
if ( $fragBytes > 100 * 1024 * 1024 ) {
$level = max( $level, 3 ) ;
}
if ( $redisOverviewData['blockedClients'] > 5 ) {
$level = max( $level, 3 ) ;
}
if ( $redisOverviewData['memoryPct'] > 80 ) {
$level = max( $level, 3 ) ;
}
// Level 2: Info
if ( $redisOverviewData['hitRatio'] < 90 && $totalRequests > 1000 ) {
$level = max( $level, 2 ) ;
}
if ( $redisOverviewData['replLag'] !== null && $redisOverviewData['replLag'] > 10000 ) {
$level = max( $level, 2 ) ; // Significant replication lag
}
// Level 1: Normal activity
if ( $redisOverviewData['connectedClients'] > 0 ) {
$level = max( $level, 1 ) ;
}
$redisOverviewData['level'] = $level ;
// Get SLOWLOG
$phaseStart = microtime( true ) ;
try {
$slowlogRaw = $redis->slowlog( 'get', 10 ) ;
if ( is_array( $slowlogRaw ) ) {
foreach ( $slowlogRaw as $entry ) {
$durationUs = (int) ( $entry[2] ?? 0 ) ;
$durationMs = round( $durationUs / 1000, 2 ) ;
$command = is_array( $entry[3] ?? null ) ? implode( ' ', $entry[3] ) : '' ;
// Calculate level based on duration
$entryLevel = 0 ;
if ( $durationMs >= 1000 ) {
$entryLevel = 4 ; // >= 1 second
} elseif ( $durationMs >= 100 ) {
$entryLevel = 3 ; // >= 100ms
} elseif ( $durationMs >= 50 ) {
$entryLevel = 2 ; // >= 50ms
} elseif ( $durationMs >= 10 ) {
$entryLevel = 1 ; // >= 10ms (default slowlog threshold)
}
$slowlogData[] = [
'id' => (int) ( $entry[0] ?? 0 ),
'timestamp' => (int) ( $entry[1] ?? 0 ),
'timestampHuman' => date( 'Y-m-d H:i:s', (int) ( $entry[1] ?? 0 ) ),
'durationUs' => $durationUs,
'durationMs' => $durationMs,
'command' => htmlspecialchars( substr( $command, 0, 500 ) ), // Truncate long commands
'level' => $entryLevel,
] ;
}
}
} catch ( \Exception $e ) {
// SLOWLOG may not be available - continue without it
}
$renderTimeData['slowlog'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Get CLIENT LIST for connection details
$phaseStart = microtime( true ) ;
try {
$clientListRaw = $redis->client( 'list' ) ;
if ( is_array( $clientListRaw ) ) {
foreach ( $clientListRaw as $client ) {
// Skip our own monitoring connection
if ( isset( $client['cmd'] ) && $client['cmd'] === 'client' ) {
continue ;
}
$clientData[] = [
'id' => (int) ( $client['id'] ?? 0 ),
'addr' => $client['addr'] ?? '',
'name' => $client['name'] ?? '',
'age' => (int) ( $client['age'] ?? 0 ),
'ageHuman' => Tools::friendlyTime( (int) ( $client['age'] ?? 0 ) ),
'idle' => (int) ( $client['idle'] ?? 0 ),
'idleHuman' => Tools::friendlyTime( (int) ( $client['idle'] ?? 0 ) ),
'db' => (int) ( $client['db'] ?? 0 ),
'cmd' => $client['cmd'] ?? '',
'flags' => $client['flags'] ?? '',
] ;
}
}
} catch ( \Exception $e ) {
// CLIENT LIST may not be available - continue without it
}
$renderTimeData['clients'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Phase 3: MEMORY STATS
$phaseStart = microtime( true ) ;
try {
$memRaw = $redis->rawCommand( 'MEMORY', 'STATS' ) ;
if ( is_array( $memRaw ) ) {
// Parse alternating key/value array into associative array
for ( $i = 0 ; $i < count( $memRaw ) - 1 ; $i += 2 ) {
$key = $memRaw[$i] ;
$val = $memRaw[$i + 1] ;
// Only include useful stats (skip nested arrays)
if ( !is_array( $val ) ) {
$memoryStats[$key] = $val ;
}
}
}
} catch ( \Exception $e ) {
error_log( "AQL Redis MEMORY STATS failed for $hostname: " . $e->getMessage() ) ;
}
// Phase 3: MEMORY DOCTOR - human-readable memory health report
try {
$memDocRaw = $redis->rawCommand( 'MEMORY', 'DOCTOR' ) ;
if ( is_string( $memDocRaw ) ) {
$memoryDoctor = $memDocRaw ;
}
} catch ( \Exception $e ) {
// MEMORY DOCTOR may not be available (requires Redis 4.0+)
}
$renderTimeData['memoryStats'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Phase 3: LATENCY LATEST
$phaseStart = microtime( true ) ;
try {
$latRaw = $redis->rawCommand( 'LATENCY', 'LATEST' ) ;
if ( is_array( $latRaw ) ) {
foreach ( $latRaw as $event ) {
if ( is_array( $event ) && count( $event ) >= 4 ) {
$latencyData[] = [
'event' => $event[0] ?? '',
'timestamp' => (int) ( $event[1] ?? 0 ),
'latencyMs' => (int) ( $event[2] ?? 0 ),
'maxMs' => (int) ( $event[3] ?? 0 ),
] ;
}
}
}
} catch ( \Exception $e ) {
error_log( "AQL Redis LATENCY LATEST failed for $hostname: " . $e->getMessage() ) ;
}
// Phase 3: LATENCY DOCTOR - human-readable latency analysis
try {
$docRaw = $redis->rawCommand( 'LATENCY', 'DOCTOR' ) ;
if ( is_string( $docRaw ) ) {
$latencyDoctor = $docRaw ;
}
} catch ( \Exception $e ) {
// LATENCY DOCTOR may not be available (requires Redis 2.8.13+)
}
// Phase 3: LATENCY HISTORY - get history for each known event from LATENCY LATEST
if ( !empty( $latencyData ) ) {
try {
foreach ( $latencyData as $event ) {
$eventName = $event['event'] ;
$histRaw = $redis->rawCommand( 'LATENCY', 'HISTORY', $eventName ) ;
if ( is_array( $histRaw ) ) {
foreach ( $histRaw as $histEntry ) {
if ( is_array( $histEntry ) && count( $histEntry ) >= 2 ) {
$latencyHistory[] = [
'event' => $eventName,
'timestamp' => (int) $histEntry[0],
'latencyMs' => (int) $histEntry[1],
] ;
}
}
}
}
} catch ( \Exception $e ) {
error_log( "AQL Redis LATENCY HISTORY failed for $hostname: " . $e->getMessage() ) ;
}
}
$renderTimeData['latency'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Phase 3: PUBSUB stats
$phaseStart = microtime( true ) ;
try {
$channels = $redis->pubsub( 'CHANNELS' ) ;
$pubsubData['channels'] = is_array( $channels ) ? $channels : [] ;
$pubsubData['channelCount'] = count( $pubsubData['channels'] ) ;
// NUMPAT returns count of pattern subscriptions
$numPat = $redis->pubsub( 'NUMPAT' ) ;
$pubsubData['patterns'] = is_int( $numPat ) ? $numPat : 0 ;
} catch ( \Exception $e ) {
error_log( "AQL Redis PUBSUB failed for $hostname: " . $e->getMessage() ) ;
}
// Phase 3: Streams - scan for stream keys and get basic info
try {
$streamKeys = [] ;
$cursor = '0' ;
// Scan for stream type keys (limit to first 100)
do {
$result = $redis->rawCommand( 'SCAN', $cursor, 'TYPE', 'stream', 'COUNT', '100' ) ;
if ( is_array( $result ) && count( $result ) >= 2 ) {
$cursor = $result[0] ;
if ( is_array( $result[1] ) ) {
$streamKeys = array_merge( $streamKeys, $result[1] ) ;
}
} else {
break ;
}
} while ( $cursor !== '0' && count( $streamKeys ) < 100 ) ;
foreach ( $streamKeys as $streamKey ) {
try {
$xinfo = $redis->rawCommand( 'XINFO', 'STREAM', $streamKey ) ;
if ( is_array( $xinfo ) ) {
// Parse alternating key/value array
$streamInfo = [] ;
for ( $i = 0 ; $i < count( $xinfo ) - 1 ; $i += 2 ) {
$key = $xinfo[$i] ;
$val = $xinfo[$i + 1] ;
if ( !is_array( $val ) ) {
$streamInfo[$key] = $val ;
}
}
$streamsData[] = [
'key' => $streamKey,
'length' => (int) ( $streamInfo['length'] ?? 0 ),
'groups' => (int) ( $streamInfo['groups'] ?? 0 ),
'firstId' => $streamInfo['first-entry'][0] ?? null,
'lastId' => $streamInfo['last-entry'][0] ?? null,
] ;
}
} catch ( \Exception $e ) {
// Skip streams we can't inspect
}
}
} catch ( \Exception $e ) {
error_log( "AQL Redis XINFO failed for $hostname: " . $e->getMessage() ) ;
}
// Phase 3: XPENDING - get pending entries for consumer groups
try {
foreach ( $streamsData as $streamInfo ) {
if ( $streamInfo['groups'] > 0 ) {
// Get consumer groups for this stream
$groups = $redis->rawCommand( 'XINFO', 'GROUPS', $streamInfo['key'] ) ;
if ( is_array( $groups ) ) {
foreach ( $groups as $group ) {
if ( is_array( $group ) ) {
// Parse alternating key/value array
$groupInfo = [] ;
for ( $i = 0 ; $i < count( $group ) - 1 ; $i += 2 ) {
$groupInfo[$group[$i]] = $group[$i + 1] ;
}
$groupName = $groupInfo['name'] ?? 'unknown' ;
// Get XPENDING summary for this group
$pending = $redis->rawCommand( 'XPENDING', $streamInfo['key'], $groupName ) ;
if ( is_array( $pending ) && count( $pending ) >= 4 ) {
$pendingCount = (int) $pending[0] ;
if ( $pendingCount > 0 ) {
$pendingData[] = [
'stream' => $streamInfo['key'],
'group' => $groupName,
'pending' => $pendingCount,
'minId' => $pending[1] ?? '-',
'maxId' => $pending[2] ?? '-',
'consumers' => is_array( $pending[3] ) ? count( $pending[3] ) : 0,
'lag' => $groupInfo['lag'] ?? 0,
] ;
}
}
}
}
}
}
}
} catch ( \Exception $e ) {
error_log( "AQL Redis XPENDING failed for $hostname: " . $e->getMessage() ) ;
}
$renderTimeData['pubsubStreams'] = round( ( microtime( true ) - $phaseStart ) * 1000, 1 ) ;
// Debug Mode: Additional diagnostics when $debug is true
if ( $debug ) {
// High Value: Keyspace breakdown - keys per DB, TTL info, expired count
$keyspaceInfo = [] ;
foreach ( $infoRaw as $key => $value ) {
if ( strpos( $key, 'db' ) === 0 && is_numeric( substr( $key, 2 ) ) ) {
// Parse db0, db1, etc: "keys=N,expires=N,avg_ttl=N"
$dbStats = [] ;
foreach ( explode( ',', $value ) as $part ) {
$kv = explode( '=', $part, 2 ) ;
if ( count( $kv ) === 2 ) {
$dbStats[$kv[0]] = (int) $kv[1] ;
}
}
$keyspaceInfo[] = [
'db' => $key,
'keys' => $dbStats['keys'] ?? 0,
'expires' => $dbStats['expires'] ?? 0,
'avgTtl' => $dbStats['avg_ttl'] ?? 0,
] ;
}
}
$debugData['keyspace'] = $keyspaceInfo ;
$debugData['expiredKeys'] = (int) ( $infoRaw['expired_keys'] ?? 0 ) ;
$debugData['expiredStalePerc'] = (float) ( $infoRaw['expired_stale_perc'] ?? 0 ) ;
// High Value: Ops/sec & throughput
$debugData['instantaneousOpsPerSec'] = (int) ( $infoRaw['instantaneous_ops_per_sec'] ?? 0 ) ;
$debugData['instantaneousInputKbps'] = (float) ( $infoRaw['instantaneous_input_kbps'] ?? 0 ) ;
$debugData['instantaneousOutputKbps'] = (float) ( $infoRaw['instantaneous_output_kbps'] ?? 0 ) ;
$debugData['totalConnectionsReceived'] = (int) ( $infoRaw['total_connections_received'] ?? 0 ) ;
$debugData['totalCommandsProcessed'] = (int) ( $infoRaw['total_commands_processed'] ?? 0 ) ;
$debugData['totalNetInputBytes'] = (int) ( $infoRaw['total_net_input_bytes'] ?? 0 ) ;
$debugData['totalNetOutputBytes'] = (int) ( $infoRaw['total_net_output_bytes'] ?? 0 ) ;
// High Value: CPU usage
$debugData['usedCpuSys'] = (float) ( $infoRaw['used_cpu_sys'] ?? 0 ) ;
$debugData['usedCpuUser'] = (float) ( $infoRaw['used_cpu_user'] ?? 0 ) ;
$debugData['usedCpuSysChildren'] = (float) ( $infoRaw['used_cpu_sys_children'] ?? 0 ) ;
$debugData['usedCpuUserChildren'] = (float) ( $infoRaw['used_cpu_user_children'] ?? 0 ) ;
// High Value: Persistence status (bgsave/AOF in progress)
$debugData['rdbBgsaveInProgress'] = ( ( $infoRaw['rdb_bgsave_in_progress'] ?? '0' ) === '1' ) ;
$debugData['rdbLastBgsaveStatus'] = $infoRaw['rdb_last_bgsave_status'] ?? 'unknown' ;
$debugData['rdbLastBgsaveTimeSec'] = (int) ( $infoRaw['rdb_last_bgsave_time_sec'] ?? -1 ) ;
$debugData['rdbCurrentBgsaveTimeSec'] = (int) ( $infoRaw['rdb_current_bgsave_time_sec'] ?? -1 ) ;
$debugData['aofRewriteInProgress'] = ( ( $infoRaw['aof_rewrite_in_progress'] ?? '0' ) === '1' ) ;
$debugData['aofLastRewriteStatus'] = $infoRaw['aof_last_rewrite_status'] ?? 'unknown' ;
$debugData['aofCurrentRewriteTimeSec'] = (int) ( $infoRaw['aof_current_rewrite_time_sec'] ?? -1 ) ;
$debugData['aofRewriteScheduled'] = ( ( $infoRaw['aof_rewrite_scheduled'] ?? '0' ) === '1' ) ;
// High Value: Client buffer details (omem, qbuf from CLIENT LIST)
$clientBuffers = [] ;
try {
$clientListRaw = $redis->client( 'list' ) ;
if ( is_array( $clientListRaw ) ) {
foreach ( $clientListRaw as $client ) {
// Only include clients with significant buffer usage
$omem = (int) ( $client['omem'] ?? 0 ) ;
$qbuf = (int) ( $client['qbuf'] ?? 0 ) ;
$qbufFree = (int) ( $client['qbuf-free'] ?? 0 ) ;
if ( $omem > 0 || $qbuf > 0 ) {
$clientBuffers[] = [
'id' => (int) ( $client['id'] ?? 0 ),
'addr' => $client['addr'] ?? '',
'name' => $client['name'] ?? '',
'omem' => $omem,
'qbuf' => $qbuf,
'qbufFree' => $qbufFree,
'cmd' => $client['cmd'] ?? '',
'flags' => $client['flags'] ?? '',
] ;
}
}
}
} catch ( \Exception $e ) {
// CLIENT LIST for debug may fail - continue without
}
$debugData['clientBuffers'] = $clientBuffers ;
}
$redis->close() ;
// Output successful response
$renderTimeData['total'] = round( ( microtime( true ) - $startTime ) * 1000, 1 ) ;
echo json_encode( [
'hostname' => $hostname,
'hostId' => $hostId,
'hostGroups' => $hostGroups,
'dbType' => 'Redis',
'redisOverviewData' => $redisOverviewData,
'slowlogData' => $slowlogData,
'clientData' => $clientData,
'commandStats' => $commandStats,
// Phase 3: Advanced diagnostics
'memoryStats' => $memoryStats,
'memoryDoctor' => $memoryDoctor,
'latencyData' => $latencyData,
'latencyDoctor' => $latencyDoctor,
'latencyHistory' => $latencyHistory,
'pubsubData' => $pubsubData,
'streamsData' => $streamsData,
'pendingData' => $pendingData,
'maintenanceInfo' => $maintenanceInfo,
// Debug mode data (only populated when debug=Redis)
'debugData' => $debugData,
'renderTimeData' => $renderTimeData,
] ) . "\n" ;
} catch ( \Exception $e ) {
// Connection or other error
$redisOverviewData['level'] = 9 ;
$renderTimeData['total'] = round( ( microtime( true ) - $startTime ) * 1000, 1 ) ;
echo json_encode( [
'hostname' => $hostname,
'hostId' => $hostId,
'hostGroups' => $hostGroups,
'dbType' => 'Redis',
'error_output' => $e->getMessage(),
'clientData' => [],
'commandStats' => [],
'redisOverviewData' => $redisOverviewData,
'slowlogData' => [],
// Phase 3: empty defaults on error
'memoryStats' => [],
'memoryDoctor' => '',
'latencyData' => [],
'latencyDoctor' => '',
'latencyHistory' => [],
'pubsubData' => [ 'channels' => [], 'channelCount' => 0, 'patterns' => 0 ],
'streamsData' => [],
'pendingData' => [],
'maintenanceInfo' => $maintenanceInfo,
// Debug mode data (empty on error)
'debugData' => [],
'renderTimeData' => $renderTimeData,
] ) . "\n" ;
}
}
// Get hostname early so we can look up hostId before connection attempt
$hostname = Tools::param('hostname') ;
// Look up host ID and db_type early (needed for Redis vs MySQL handling)