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
25 * An interface for generating database load balancers
28 abstract class LBFactory
{
29 /** @var ChronologyProtector */
33 private static $instance;
35 /** @var string|bool Reason all LBs are read-only or false if not */
36 protected $readOnlyReason = false;
38 const SHUTDOWN_NO_CHRONPROT
= 1; // don't save ChronologyProtector positions (for async code)
41 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
44 public function __construct( array $conf ) {
45 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
46 $this->readOnlyReason
= $conf['readOnlyReason'];
49 $this->chronProt
= $this->newChronologyProtector();
53 * Disables all access to the load balancer, will cause all database access
54 * to throw a DBAccessError
56 public static function disableBackend() {
57 global $wgLBFactoryConf;
58 self
::$instance = new LBFactoryFake( $wgLBFactoryConf );
62 * Get an LBFactory instance
66 public static function singleton() {
67 global $wgLBFactoryConf;
69 if ( is_null( self
::$instance ) ) {
70 $class = self
::getLBFactoryClass( $wgLBFactoryConf );
71 $config = $wgLBFactoryConf;
72 if ( !isset( $config['readOnlyReason'] ) ) {
73 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
75 self
::$instance = new $class( $config );
78 return self
::$instance;
82 * Returns the LBFactory class to use and the load balancer configuration.
84 * @param array $config (e.g. $wgLBFactoryConf)
85 * @return string Class name
87 public static function getLBFactoryClass( array $config ) {
88 // For configuration backward compatibility after removing
89 // underscores from class names in MediaWiki 1.23.
91 'LBFactory_Simple' => 'LBFactorySimple',
92 'LBFactory_Single' => 'LBFactorySingle',
93 'LBFactory_Multi' => 'LBFactoryMulti',
94 'LBFactory_Fake' => 'LBFactoryFake',
97 $class = $config['class'];
99 if ( isset( $bcClasses[$class] ) ) {
100 $class = $bcClasses[$class];
102 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
111 * Shut down, close connections and destroy the cached instance.
113 public static function destroyInstance() {
114 if ( self
::$instance ) {
115 self
::$instance->shutdown();
116 self
::$instance->forEachLBCallMethod( 'closeAll' );
117 self
::$instance = null;
122 * Set the instance to be the given object
124 * @param LBFactory $instance
126 public static function setInstance( $instance ) {
127 self
::destroyInstance();
128 self
::$instance = $instance;
132 * Create a new load balancer object. The resulting object will be untracked,
133 * not chronology-protected, and the caller is responsible for cleaning it up.
135 * @param bool|string $wiki Wiki ID, or false for the current wiki
136 * @return LoadBalancer
138 abstract public function newMainLB( $wiki = false );
141 * Get a cached (tracked) load balancer object.
143 * @param bool|string $wiki Wiki ID, or false for the current wiki
144 * @return LoadBalancer
146 abstract public function getMainLB( $wiki = false );
149 * Create a new load balancer for external storage. The resulting object will be
150 * untracked, not chronology-protected, and the caller is responsible for
153 * @param string $cluster External storage cluster, or false for core
154 * @param bool|string $wiki Wiki ID, or false for the current wiki
155 * @return LoadBalancer
157 abstract protected function newExternalLB( $cluster, $wiki = false );
160 * Get a cached (tracked) load balancer for external storage
162 * @param string $cluster External storage cluster, or false for core
163 * @param bool|string $wiki Wiki ID, or false for the current wiki
164 * @return LoadBalancer
166 abstract public function &getExternalLB( $cluster, $wiki = false );
169 * Execute a function for each tracked load balancer
170 * The callback is called with the load balancer as the first parameter,
171 * and $params passed as the subsequent parameters.
173 * @param callable $callback
174 * @param array $params
176 abstract public function forEachLB( $callback, array $params = array() );
179 * Prepare all tracked load balancers for shutdown
180 * @param integer $flags Supports SHUTDOWN_* flags
183 public function shutdown( $flags = 0 ) {
187 * Call a method of each tracked load balancer
189 * @param string $methodName
192 private function forEachLBCallMethod( $methodName, array $args = array() ) {
194 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
195 call_user_func_array( array( $loadBalancer, $methodName ), $args );
197 array( $methodName, $args )
202 * Commit on all connections. Done for two reasons:
203 * 1. To commit changes to the masters.
204 * 2. To release the snapshot on all connections, master and slave.
205 * @param string $fname Caller name
207 public function commitAll( $fname = __METHOD__
) {
208 $start = microtime( true );
209 $this->forEachLBCallMethod( 'commitAll', array( $fname ) );
210 $timeMs = 1000 * ( microtime( true ) - $start );
212 RequestContext
::getMain()->getStats()->timing( "db.commit-all", $timeMs );
216 * Commit changes on all master connections
217 * @param string $fname Caller name
219 public function commitMasterChanges( $fname = __METHOD__
) {
220 $start = microtime( true );
221 $this->forEachLBCallMethod( 'commitMasterChanges', array( $fname ) );
222 $timeMs = 1000 * ( microtime( true ) - $start );
224 RequestContext
::getMain()->getStats()->timing( "db.commit-masters", $timeMs );
228 * Rollback changes on all master connections
229 * @param string $fname Caller name
232 public function rollbackMasterChanges( $fname = __METHOD__
) {
233 $this->forEachLBCallMethod( 'rollbackMasterChanges', array( $fname ) );
237 * Determine if any master connection has pending changes
241 public function hasMasterChanges() {
243 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
244 $ret = $ret ||
$lb->hasMasterChanges();
251 * Detemine if any lagged slave connection was used
255 public function laggedSlaveUsed() {
257 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
258 $ret = $ret ||
$lb->laggedSlaveUsed();
265 * Determine if any master connection has pending/written changes from this request
269 public function hasOrMadeRecentMasterChanges() {
271 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
272 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges();
278 * Disable the ChronologyProtector for all load balancers
280 * This can be called at the start of special API entry points
284 public function disableChronologyProtection() {
285 $this->chronProt
->setEnabled( false );
289 * @return ChronologyProtector
291 protected function newChronologyProtector() {
292 $request = RequestContext
::getMain()->getRequest();
293 $chronProt = new ChronologyProtector(
294 ObjectCache
::getMainStashInstance(),
296 'ip' => $request->getIP(),
297 'agent' => $request->getHeader( 'User-Agent' )
300 if ( PHP_SAPI
=== 'cli' ) {
301 $chronProt->setEnabled( false );
302 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
303 // Request opted out of using position wait logic. This is useful for requests
304 // done by the job queue or background ETL that do not have a meaningful session.
305 $chronProt->setWaitEnabled( false );
312 * @param ChronologyProtector $cp
314 protected function shutdownChronologyProtector( ChronologyProtector
$cp ) {
315 // Get all the master positions needed
316 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
317 $cp->shutdownLB( $lb );
319 // Write them to the stash
320 $unsavedPositions = $cp->shutdown();
321 // If the positions failed to write to the stash, at least wait on local datacenter
322 // slaves to catch up before responding. Even if there are several DCs, this increases
323 // the chance that the user will see their own changes immediately afterwards. As long
324 // as the sticky DC cookie applies (same domain), this is not even an issue.
325 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
326 $masterName = $lb->getServerName( $lb->getWriterIndex() );
327 if ( isset( $unsavedPositions[$masterName] ) ) {
328 $lb->waitForAll( $unsavedPositions[$masterName] );
335 * Exception class for attempted DB access
337 class DBAccessError
extends MWException
{
338 public function __construct() {
339 parent
::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
340 "This is not allowed." );