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