3 * Generator of database load balancing objects.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Psr\Log\LoggerInterface
;
25 use MediaWiki\Logger\LoggerFactory
;
28 * An interface for generating database load balancers
31 abstract class LBFactory
{
32 /** @var ChronologyProtector */
35 /** @var TransactionProfiler */
36 protected $trxProfiler;
38 /** @var LoggerInterface */
42 private static $instance;
44 /** @var string|bool Reason all LBs are read-only or false if not */
45 protected $readOnlyReason = false;
47 const SHUTDOWN_NO_CHRONPROT
= 1; // don't save ChronologyProtector positions (for async code)
50 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
53 public function __construct( array $conf ) {
54 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
55 $this->readOnlyReason
= $conf['readOnlyReason'];
58 $this->chronProt
= $this->newChronologyProtector();
59 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
60 $this->logger
= LoggerFactory
::getInstance( 'DBTransaction' );
64 * Disables all access to the load balancer, will cause all database access
65 * to throw a DBAccessError
67 public static function disableBackend() {
68 global $wgLBFactoryConf;
69 self
::$instance = new LBFactoryFake( $wgLBFactoryConf );
73 * Get an LBFactory instance
77 public static function singleton() {
78 global $wgLBFactoryConf;
80 if ( is_null( self
::$instance ) ) {
81 $class = self
::getLBFactoryClass( $wgLBFactoryConf );
82 $config = $wgLBFactoryConf;
83 if ( !isset( $config['readOnlyReason'] ) ) {
84 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
86 self
::$instance = new $class( $config );
89 return self
::$instance;
93 * Returns the LBFactory class to use and the load balancer configuration.
95 * @param array $config (e.g. $wgLBFactoryConf)
96 * @return string Class name
98 public static function getLBFactoryClass( array $config ) {
99 // For configuration backward compatibility after removing
100 // underscores from class names in MediaWiki 1.23.
102 'LBFactory_Simple' => 'LBFactorySimple',
103 'LBFactory_Single' => 'LBFactorySingle',
104 'LBFactory_Multi' => 'LBFactoryMulti',
105 'LBFactory_Fake' => 'LBFactoryFake',
108 $class = $config['class'];
110 if ( isset( $bcClasses[$class] ) ) {
111 $class = $bcClasses[$class];
113 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
122 * Shut down, close connections and destroy the cached instance.
124 public static function destroyInstance() {
125 if ( self
::$instance ) {
126 self
::$instance->shutdown();
127 self
::$instance->forEachLBCallMethod( 'closeAll' );
128 self
::$instance = null;
133 * Set the instance to be the given object
135 * @param LBFactory $instance
137 public static function setInstance( $instance ) {
138 self
::destroyInstance();
139 self
::$instance = $instance;
143 * Create a new load balancer object. The resulting object will be untracked,
144 * not chronology-protected, and the caller is responsible for cleaning it up.
146 * @param bool|string $wiki Wiki ID, or false for the current wiki
147 * @return LoadBalancer
149 abstract public function newMainLB( $wiki = false );
152 * Get a cached (tracked) load balancer object.
154 * @param bool|string $wiki Wiki ID, or false for the current wiki
155 * @return LoadBalancer
157 abstract public function getMainLB( $wiki = false );
160 * Create a new load balancer for external storage. The resulting object will be
161 * untracked, not chronology-protected, and the caller is responsible for
164 * @param string $cluster External storage cluster, or false for core
165 * @param bool|string $wiki Wiki ID, or false for the current wiki
166 * @return LoadBalancer
168 abstract protected function newExternalLB( $cluster, $wiki = false );
171 * Get a cached (tracked) load balancer for external storage
173 * @param string $cluster External storage cluster, or false for core
174 * @param bool|string $wiki Wiki ID, or false for the current wiki
175 * @return LoadBalancer
177 abstract public function &getExternalLB( $cluster, $wiki = false );
180 * Execute a function for each tracked load balancer
181 * The callback is called with the load balancer as the first parameter,
182 * and $params passed as the subsequent parameters.
184 * @param callable $callback
185 * @param array $params
187 abstract public function forEachLB( $callback, array $params = array() );
190 * Prepare all tracked load balancers for shutdown
191 * @param integer $flags Supports SHUTDOWN_* flags
194 public function shutdown( $flags = 0 ) {
198 * Call a method of each tracked load balancer
200 * @param string $methodName
203 private function forEachLBCallMethod( $methodName, array $args = array() ) {
205 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
206 call_user_func_array( array( $loadBalancer, $methodName ), $args );
208 array( $methodName, $args )
213 * Commit on all connections. Done for two reasons:
214 * 1. To commit changes to the masters.
215 * 2. To release the snapshot on all connections, master and slave.
216 * @param string $fname Caller name
218 public function commitAll( $fname = __METHOD__
) {
219 $this->logMultiDbTransaction();
221 $start = microtime( true );
222 $this->forEachLBCallMethod( 'commitAll', array( $fname ) );
223 $timeMs = 1000 * ( microtime( true ) - $start );
225 RequestContext
::getMain()->getStats()->timing( "db.commit-all", $timeMs );
229 * Commit changes on all master connections
230 * @param string $fname Caller name
232 public function commitMasterChanges( $fname = __METHOD__
) {
233 $this->logMultiDbTransaction();
235 $start = microtime( true );
236 $this->forEachLBCallMethod( 'commitMasterChanges', array( $fname ) );
237 $timeMs = 1000 * ( microtime( true ) - $start );
239 RequestContext
::getMain()->getStats()->timing( "db.commit-masters", $timeMs );
243 * Rollback changes on all master connections
244 * @param string $fname Caller name
247 public function rollbackMasterChanges( $fname = __METHOD__
) {
248 $this->forEachLBCallMethod( 'rollbackMasterChanges', array( $fname ) );
252 * Log query info if multi DB transactions are going to be committed now
254 private function logMultiDbTransaction() {
255 $callersByDB = array();
256 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
257 $masterName = $lb->getServerName( $lb->getWriterIndex() );
258 $callers = $lb->pendingMasterChangeCallers();
260 $callersByDB[$masterName] = $callers;
264 if ( count( $callersByDB ) >= 2 ) {
265 $dbs = implode( ', ', array_keys( $callersByDB ) );
266 $msg = "Multi-DB transaction [{$dbs}]:\n";
267 foreach ( $callersByDB as $db => $callers ) {
268 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
270 $this->logger
->info( $msg );
275 * Determine if any master connection has pending changes
279 public function hasMasterChanges() {
281 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
282 $ret = $ret ||
$lb->hasMasterChanges();
289 * Detemine if any lagged slave connection was used
293 public function laggedSlaveUsed() {
295 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
296 $ret = $ret ||
$lb->laggedSlaveUsed();
303 * Determine if any master connection has pending/written changes from this request
307 public function hasOrMadeRecentMasterChanges() {
309 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
310 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges();
316 * Disable the ChronologyProtector for all load balancers
318 * This can be called at the start of special API entry points
322 public function disableChronologyProtection() {
323 $this->chronProt
->setEnabled( false );
327 * @return ChronologyProtector
329 protected function newChronologyProtector() {
330 $request = RequestContext
::getMain()->getRequest();
331 $chronProt = new ChronologyProtector(
332 ObjectCache
::getMainStashInstance(),
334 'ip' => $request->getIP(),
335 'agent' => $request->getHeader( 'User-Agent' )
338 if ( PHP_SAPI
=== 'cli' ) {
339 $chronProt->setEnabled( false );
340 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
341 // Request opted out of using position wait logic. This is useful for requests
342 // done by the job queue or background ETL that do not have a meaningful session.
343 $chronProt->setWaitEnabled( false );
350 * @param ChronologyProtector $cp
352 protected function shutdownChronologyProtector( ChronologyProtector
$cp ) {
353 // Get all the master positions needed
354 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
355 $cp->shutdownLB( $lb );
357 // Write them to the stash
358 $unsavedPositions = $cp->shutdown();
359 // If the positions failed to write to the stash, at least wait on local datacenter
360 // slaves to catch up before responding. Even if there are several DCs, this increases
361 // the chance that the user will see their own changes immediately afterwards. As long
362 // as the sticky DC cookie applies (same domain), this is not even an issue.
363 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
364 $masterName = $lb->getServerName( $lb->getWriterIndex() );
365 if ( isset( $unsavedPositions[$masterName] ) ) {
366 $lb->waitForAll( $unsavedPositions[$masterName] );
373 * Exception class for attempted DB access
375 class DBAccessError
extends MWException
{
376 public function __construct() {
377 parent
::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
378 "This is not allowed." );