Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.40% covered (warning)
81.40%
140 / 172
55.00% covered (warning)
55.00%
11 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
TransactionProfiler
81.40% covered (warning)
81.40%
140 / 172
55.00% covered (warning)
55.00%
11 / 20
105.38
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 setLogger
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setStatsFactory
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setRequestMethod
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 silenceForScope
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
6
 setExpectation
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 setExpectations
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 resetExpectations
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 redefineExpectations
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getExpectation
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 recordConnection
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 transactionWritingIn
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
 recordQueryCompletion
71.43% covered (warning)
71.43%
20 / 28
0.00% covered (danger)
0.00%
0 / 1
29.33
 transactionWritingOut
71.43% covered (warning)
71.43%
30 / 42
0.00% covered (danger)
0.00%
0 / 1
12.33
 initPlaceholderExpectations
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 isAboveThreshold
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 pingAndCheckThreshold
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 reportExpectationViolated
82.14% covered (warning)
82.14%
23 / 28
0.00% covered (danger)
0.00%
0 / 1
4.09
 getGeneralizedSql
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getRawSql
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getCurrentTime
n/a
0 / 0
n/a
0 / 0
2
 setMockTime
n/a
0 / 0
n/a
0 / 0
1
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20namespace Wikimedia\Rdbms;
21
22use InvalidArgumentException;
23use Psr\Log\LoggerAwareInterface;
24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
26use RuntimeException;
27use Wikimedia\ScopedCallback;
28use Wikimedia\Stats\StatsFactory;
29
30/**
31 * Detect high-contention DB queries via profiling calls.
32 *
33 * This class is meant to work with an IDatabase object, which manages queries.
34 *
35 * @internal For use by Database only
36 * @since 1.24
37 * @ingroup Profiler
38 * @ingroup Database
39 */
40class TransactionProfiler implements LoggerAwareInterface {
41    /** @var LoggerInterface */
42    private $logger;
43    /** @var StatsFactory */
44    private $statsFactory;
45    /** @var array<string,array> Map of (event name => map of FLD_* class constants) */
46    private $expect;
47    /** @var array<string,int> Map of (event name => current hits) */
48    private $hits;
49    /** @var array<string,int> Map of (event name => violation counter) */
50    private $violations;
51    /** @var array<string,int> Map of (event name => silence counter) */
52    private $silenced;
53
54    /**
55     * @var array<string,array> Map of (trx ID => (write start time, list of DBs involved))
56     * @phan-var array<string,array{start:float,conns:array<string,int>}>
57     */
58    private $dbTrxHoldingLocks;
59
60    /**
61     * @var array[][] Map of (trx ID => list of (query name, start time, end time))
62     * @phan-var array<string,array<int,array{0:string|GeneralizedSQL,1:float,2:float}>>
63     */
64    private $dbTrxMethodTimes;
65
66    /** @var string|null HTTP request method; null for CLI mode */
67    private $method;
68
69    /** @var float|null */
70    private $wallClockOverride;
71
72    /** Treat locks as long-running if they last longer than this many seconds */
73    private const DB_LOCK_THRESHOLD_SEC = 3.0;
74    /** Include events in any violation logs if they last longer than this many seconds */
75    private const EVENT_THRESHOLD_SEC = 0.25;
76
77    /** List of event names */
78    private const EVENT_NAMES = [
79        'writes',
80        'queries',
81        'conns',
82        'masterConns',
83        'maxAffected',
84        'readQueryRows',
85        'readQueryTime',
86        'writeQueryTime'
87    ];
88
89    /** List of event names with hit counters */
90    private const COUNTER_EVENT_NAMES = [
91        'writes',
92        'queries',
93        'conns',
94        'masterConns'
95    ];
96
97    /** Key to max expected value */
98    private const FLD_LIMIT = 0;
99    /** Key to the function that set the max expected value */
100    private const FLD_FNAME = 1;
101
102    /** Any type of expectation */
103    public const EXPECTATION_ANY = 'any';
104    /** Any expectations about replica usage never occurring */
105    public const EXPECTATION_REPLICAS_ONLY = 'replicas-only';
106
107    public function __construct() {
108        $this->initPlaceholderExpectations();
109
110        $this->dbTrxHoldingLocks = [];
111        $this->dbTrxMethodTimes = [];
112
113        $this->silenced = array_fill_keys( self::EVENT_NAMES, 0 );
114
115        $this->setLogger( new NullLogger() );
116        $this->statsFactory = StatsFactory::newNull();
117    }
118
119    public function setLogger( LoggerInterface $logger ) {
120        $this->logger = $logger;
121    }
122
123    /**
124     * Set statsFactory
125     *
126     * @param StatsFactory $statsFactory
127     * @return void
128     */
129    public function setStatsFactory( StatsFactory $statsFactory ) {
130        $this->statsFactory = $statsFactory;
131    }
132
133    /**
134     * @param ?string $method HTTP method; null for CLI mode
135     * @return void
136     */
137    public function setRequestMethod( ?string $method ) {
138        $this->method = $method;
139    }
140
141    /**
142     * Temporarily ignore expectations until the returned object goes out of scope
143     *
144     * During this time, violation of expectations will not be logged and counters
145     * for expectations (e.g. "conns") will not be incremented.
146     *
147     * This will suppress warnings about event counters which have a limit of zero.
148     * The main use case is too avoid warnings about primary connections/writes and
149     * warnings about getting any primary/replica connections at all.
150     *
151     * @param string $type Class EXPECTATION_* constant [default: TransactionProfiler::EXPECTATION_ANY]
152     * @return ScopedCallback
153     */
154    public function silenceForScope( string $type = self::EXPECTATION_ANY ) {
155        if ( $type === self::EXPECTATION_REPLICAS_ONLY ) {
156            $events = [];
157            foreach ( [ 'writes', 'masterConns' ] as $event ) {
158                if ( $this->expect[$event][self::FLD_LIMIT] === 0 ) {
159                    $events[] = $event;
160                }
161            }
162        } else {
163            $events = self::EVENT_NAMES;
164        }
165
166        foreach ( $events as $event ) {
167            ++$this->silenced[$event];
168        }
169
170        return new ScopedCallback( function () use ( $events ) {
171            foreach ( $events as $event ) {
172                --$this->silenced[$event];
173            }
174        } );
175    }
176
177    /**
178     * Set performance expectations
179     *
180     * With conflicting expectations, the most narrow ones will be used
181     *
182     * @param string $event Event name, {@see self::EVENT_NAMES}
183     * @param float|int $limit Maximum event count, event value, or total event value
184     * @param string $fname Caller
185     * @since 1.25
186     */
187    public function setExpectation( string $event, $limit, string $fname ) {
188        if ( !isset( $this->expect[$event] ) ) {
189            return; // obsolete/bogus expectation
190        }
191
192        if ( $limit <= $this->expect[$event][self::FLD_LIMIT] ) {
193            // New limit is more restrictive
194            $this->expect[$event] = [
195                self::FLD_LIMIT => $limit,
196                self::FLD_FNAME => $fname
197            ];
198        }
199    }
200
201    /**
202     * Set one or multiple performance expectations
203     *
204     * With conflicting expectations, the most narrow ones will be used
205     *
206     * Use this to initialize expectations or make them stricter mid-request
207     *
208     * @param array $expects Map of (event name => limit), {@see self::EVENT_NAMES}
209     * @param string $fname
210     * @since 1.26
211     */
212    public function setExpectations( array $expects, string $fname ) {
213        foreach ( $expects as $event => $value ) {
214            $this->setExpectation( $event, $value, $fname );
215        }
216    }
217
218    /**
219     * Reset all performance expectations and hit counters
220     *
221     * Use this for unit testing or before applying a totally different set of expectations
222     * for a different part of the request, such as during "post-send" (execution after HTTP
223     * response completion)
224     *
225     * @since 1.25
226     */
227    public function resetExpectations() {
228        $this->initPlaceholderExpectations();
229    }
230
231    /**
232     * Clear all expectations and hit counters and set new performance expectations
233     *
234     * Use this to apply a totally different set of expectations for a different part
235     * of the request, such as during "post-send" (execution after HTTP response completion)
236     *
237     * @param array $expects Map of (event name => limit), {@see self::EVENT_NAMES}
238     * @param string $fname
239     * @since 1.33
240     */
241    public function redefineExpectations( array $expects, string $fname ) {
242        $this->initPlaceholderExpectations();
243        $this->setExpectations( $expects, $fname );
244    }
245
246    /**
247     * Get the expectation associated with a specific event name.
248     *
249     * This will return the value of the expectation even if the event is silenced.
250     *
251     * Use this to check if a specific event is allowed before performing it, such as checking
252     * if the request will allow writes before performing them and instead deferring the writes
253     * to outside the request.
254     *
255     * @since 1.44
256     * @param string $event Event name. Valid event names are defined in {@see self::EVENT_NAMES}
257     * @return float|int Maximum event count, event value, or total event value
258     *    depending on the type of event.
259     * @throws InvalidArgumentException If the provided event name is not one in {@see self::EVENT_NAMES}
260     */
261    public function getExpectation( string $event ) {
262        if ( !isset( $this->expect[$event] ) ) {
263            throw new InvalidArgumentException( "Unrecognised event name '$event' provided." );
264        }
265
266        return $this->expect[$event][self::FLD_LIMIT];
267    }
268
269    /**
270     * Mark a DB as having been connected to with a new handle
271     *
272     * Note that there can be multiple connections to a single DB.
273     *
274     * @param string $server DB server
275     * @param string|null $db DB name
276     * @param bool $isPrimaryWithReplicas If the server is the primary and there are replicas
277     */
278    public function recordConnection( $server, $db, bool $isPrimaryWithReplicas ) {
279        // Report when too many connections happen...
280        if ( $this->pingAndCheckThreshold( 'conns' ) ) {
281            $this->reportExpectationViolated(
282                'conns',
283                "[connect to $server ($db)]",
284                $this->hits['conns']
285            );
286        }
287
288        // Report when too many primary connections happen...
289        if ( $isPrimaryWithReplicas && $this->pingAndCheckThreshold( 'masterConns' ) ) {
290            $this->reportExpectationViolated(
291                'masterConns',
292                "[connect to $server ($db)]",
293                $this->hits['masterConns']
294            );
295        }
296    }
297
298    /**
299     * Mark a DB as in a transaction with one or more writes pending
300     *
301     * Note that there can be multiple connections to a single DB.
302     *
303     * @param string $server DB server
304     * @param string|null $db DB name
305     * @param string $id ID string of transaction
306     * @param float $startTime UNIX timestamp
307     */
308    public function transactionWritingIn( $server, $db, string $id, float $startTime ) {
309        $name = "{$db} {$server} TRX#$id";
310        if ( isset( $this->dbTrxHoldingLocks[$name] ) ) {
311            $this->logger->warning( "Nested transaction for '$name' - out of sync." );
312        }
313        $this->dbTrxHoldingLocks[$name] = [
314            'start' => $startTime,
315            'conns' => [], // all connections involved
316        ];
317        $this->dbTrxMethodTimes[$name] = [];
318
319        foreach ( $this->dbTrxHoldingLocks as $name => &$info ) {
320            // Track all DBs in transactions for this transaction
321            $info['conns'][$name] = 1;
322        }
323    }
324
325    /**
326     * Register the name and time of a method for slow DB trx detection
327     *
328     * This assumes that all queries are synchronous (non-overlapping)
329     *
330     * @param string|GeneralizedSql $query Function name or generalized SQL
331     * @param float $sTime Starting UNIX wall time
332     * @param bool $isWrite Whether this is a write query
333     * @param int|null $rowCount Number of affected/read rows
334     * @param string $trxId Transaction id
335     * @param string|null $serverName db host name like db1234
336     */
337    public function recordQueryCompletion(
338        $query,
339        float $sTime,
340        bool $isWrite,
341        ?int $rowCount,
342        string $trxId,
343        ?string $serverName = null
344    ) {
345        $eTime = $this->getCurrentTime();
346        $elapsed = ( $eTime - $sTime );
347
348        if ( $isWrite && $this->isAboveThreshold( $rowCount, 'maxAffected' ) ) {
349            $this->reportExpectationViolated( 'maxAffected', $query, $rowCount, $trxId, $serverName );
350        } elseif ( !$isWrite && $this->isAboveThreshold( $rowCount, 'readQueryRows' ) ) {
351            $this->reportExpectationViolated( 'readQueryRows', $query, $rowCount, $trxId, $serverName );
352        }
353
354        // Report when too many writes/queries happen...
355        if ( $this->pingAndCheckThreshold( 'queries' ) ) {
356            $this->reportExpectationViolated( 'queries', $query, $this->hits['queries'], $trxId, $serverName );
357        }
358        if ( $isWrite && $this->pingAndCheckThreshold( 'writes' ) ) {
359            $this->reportExpectationViolated( 'writes', $query, $this->hits['writes'], $trxId, $serverName );
360        }
361        // Report slow queries...
362        if ( !$isWrite && $this->isAboveThreshold( $elapsed, 'readQueryTime' ) ) {
363            $this->reportExpectationViolated( 'readQueryTime', $query, $elapsed, $trxId, $serverName );
364        }
365        if ( $isWrite && $this->isAboveThreshold( $elapsed, 'writeQueryTime' ) ) {
366            $this->reportExpectationViolated( 'writeQueryTime', $query, $elapsed, $trxId, $serverName );
367        }
368
369        if ( !$this->dbTrxHoldingLocks ) {
370            // Short-circuit
371            return;
372        } elseif ( !$isWrite && $elapsed < self::EVENT_THRESHOLD_SEC ) {
373            // Not an important query nor slow enough
374            return;
375        }
376
377        foreach ( $this->dbTrxHoldingLocks as $name => $info ) {
378            $lastQuery = end( $this->dbTrxMethodTimes[$name] );
379            if ( $lastQuery ) {
380                // Additional query in the trx...
381                $lastEnd = $lastQuery[2];
382                if ( $sTime >= $lastEnd ) {
383                    if ( ( $sTime - $lastEnd ) > self::EVENT_THRESHOLD_SEC ) {
384                        // Add an entry representing the time spent doing non-queries
385                        $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $sTime ];
386                    }
387                    $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
388                }
389            } else {
390                // First query in the trx...
391                if ( $sTime >= $info['start'] ) {
392                    $this->dbTrxMethodTimes[$name][] = [ $query, $sTime, $eTime ];
393                }
394            }
395        }
396    }
397
398    /**
399     * Mark a DB as no longer in a transaction
400     *
401     * This will check if locks are possibly held for longer than
402     * needed and log any affected transactions to a special DB log.
403     * Note that there can be multiple connections to a single DB.
404     *
405     * @param string $server DB server
406     * @param string|null $db DB name
407     * @param string $id ID string of transaction
408     * @param float $writeTime Time spent in write queries
409     * @param int $affected Number of rows affected by writes
410     */
411    public function transactionWritingOut(
412        $server,
413        $db,
414        string $id,
415        float $writeTime,
416        int $affected
417    ) {
418        // Must match $name in transactionWritingIn()
419        $name = "{$db} {$server} TRX#$id";
420        if ( !isset( $this->dbTrxMethodTimes[$name] ) ) {
421            $this->logger->warning( "Detected no transaction for '$name' - out of sync." );
422            return;
423        }
424
425        $slow = false;
426
427        // Warn if too much time was spend writing...
428        if ( $this->isAboveThreshold( $writeTime, 'writeQueryTime' ) ) {
429            $this->reportExpectationViolated(
430                'writeQueryTime',
431                "[transaction writes to {$db} at {$server}]",
432                $writeTime,
433                $id
434            );
435            $slow = true;
436        }
437        // Warn if too many rows were changed...
438        if ( $this->isAboveThreshold( $affected, 'maxAffected' ) ) {
439            $this->reportExpectationViolated(
440                'maxAffected',
441                "[transaction writes to {$db} at {$server}]",
442                $affected,
443                $id
444            );
445        }
446        // Fill in the last non-query period...
447        $lastQuery = end( $this->dbTrxMethodTimes[$name] );
448        if ( $lastQuery ) {
449            $now = $this->getCurrentTime();
450            $lastEnd = $lastQuery[2];
451            if ( ( $now - $lastEnd ) > self::EVENT_THRESHOLD_SEC ) {
452                $this->dbTrxMethodTimes[$name][] = [ '...delay...', $lastEnd, $now ];
453            }
454        }
455        // Check for any slow queries or non-query periods...
456        foreach ( $this->dbTrxMethodTimes[$name] as $info ) {
457            $elapsed = ( $info[2] - $info[1] );
458            if ( $elapsed >= self::DB_LOCK_THRESHOLD_SEC ) {
459                $slow = true;
460                break;
461            }
462        }
463        if ( $slow ) {
464            $trace = '';
465            foreach ( $this->dbTrxMethodTimes[$name] as $i => [ $query, $sTime, $end ] ) {
466                $trace .= sprintf(
467                    "%-2d %.3fs %s\n", $i, ( $end - $sTime ), $this->getGeneralizedSql( $query ) );
468            }
469            $this->logger->warning( "Suboptimal transaction [{dbs}]:\n{trace}", [
470                'dbs' => implode( ', ', array_keys( $this->dbTrxHoldingLocks[$name]['conns'] ) ),
471                'trace' => mb_substr( $trace, 0, 2000 )
472            ] );
473        }
474        unset( $this->dbTrxHoldingLocks[$name] );
475        unset( $this->dbTrxMethodTimes[$name] );
476    }
477
478    private function initPlaceholderExpectations() {
479        $this->expect = array_fill_keys(
480            self::EVENT_NAMES,
481            [ self::FLD_LIMIT => INF, self::FLD_FNAME => null ]
482        );
483
484        $this->hits = array_fill_keys( self::COUNTER_EVENT_NAMES, 0 );
485        $this->violations = array_fill_keys( self::EVENT_NAMES, 0 );
486    }
487
488    /**
489     * @param float|int $value
490     * @param string $event
491     * @return bool
492     */
493    private function isAboveThreshold( $value, string $event ) {
494        if ( $this->silenced[$event] > 0 ) {
495            return false;
496        }
497
498        return ( $value > $this->expect[$event][self::FLD_LIMIT] );
499    }
500
501    /**
502     * @param string $event
503     * @return bool
504     */
505    private function pingAndCheckThreshold( string $event ) {
506        if ( $this->silenced[$event] > 0 ) {
507            return false;
508        }
509
510        $newValue = ++$this->hits[$event];
511        $limit = $this->expect[$event][self::FLD_LIMIT];
512
513        return ( $newValue > $limit );
514    }
515
516    /**
517     * @param string $event
518     * @param string|GeneralizedSql $query
519     * @param float|int $actual
520     * @param string|null $trxId Transaction id
521     * @param string|null $serverName db host name like db1234
522     */
523    private function reportExpectationViolated(
524        $event,
525        $query,
526        $actual,
527        ?string $trxId = null,
528        ?string $serverName = null
529    ) {
530        $violations = ++$this->violations[$event];
531        // First violation; check if this is a web request
532        if ( $violations === 1 && $this->method !== null ) {
533            $this->statsFactory->getCounter( 'rdbms_trxprofiler_warnings_total' )
534                ->setLabel( 'event', $event )
535                ->setLabel( 'method', $this->method )
536                ->copyToStatsdAt( "rdbms_trxprofiler_warnings.$event.{$this->method}" )
537                ->increment();
538        }
539
540        $max = $this->expect[$event][self::FLD_LIMIT];
541        $by = $this->expect[$event][self::FLD_FNAME];
542
543        $message = "Expectation ($event <= $max) by $by not met (actual: {actualSeconds})";
544        if ( $trxId ) {
545            $message .= ' in trx #{trxId}';
546        }
547        $message .= ":\n{query}\n";
548
549        $this->logger->warning(
550            $message,
551            [
552                'db_log_category' => 'performance',
553                'measure' => $event,
554                'maxSeconds' => $max,
555                'by' => $by,
556                'actualSeconds' => $actual,
557                'query' => $this->getGeneralizedSql( $query ),
558                'exception' => new RuntimeException(),
559                'trxId' => $trxId,
560                // Avoid truncated JSON in Logstash (T349140)
561                'fullQuery' => mb_substr( $this->getRawSql( $query ), 0, 2000 ),
562                'dbHost' => $serverName
563            ]
564        );
565    }
566
567    /**
568     * @param GeneralizedSql|string $query
569     * @return string
570     */
571    private function getGeneralizedSql( $query ) {
572        return $query instanceof GeneralizedSql ? $query->stringify() : $query;
573    }
574
575    /**
576     * @param GeneralizedSql|string $query
577     * @return string
578     */
579    private function getRawSql( $query ) {
580        return $query instanceof GeneralizedSql ? $query->getRawSql() : $query;
581    }
582
583    /**
584     * @return float UNIX timestamp
585     * @codeCoverageIgnore
586     */
587    private function getCurrentTime() {
588        return $this->wallClockOverride ?: microtime( true );
589    }
590
591    /**
592     * @param float|null &$time Mock UNIX timestamp for testing
593     * @codeCoverageIgnore
594     */
595    public function setMockTime( &$time ) {
596        $this->wallClockOverride =& $time;
597    }
598}