eeeca6283c1bc1a3898ec906823a00483d939b7b
[lhc/web/wiklou.git] / includes / db / loadbalancer / LBFactory.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * An interface for generating database load balancers
26 * @ingroup Database
27 */
28 abstract class LBFactory {
29 /** @var ChronologyProtector */
30 protected $chronProt;
31
32 /** @var LBFactory */
33 private static $instance;
34
35 /** @var string|bool Reason all LBs are read-only or false if not */
36 protected $readOnlyReason = false;
37
38 const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
39
40 /**
41 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
42 * @param array $conf
43 */
44 public function __construct( array $conf ) {
45 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
46 $this->readOnlyReason = $conf['readOnlyReason'];
47 }
48
49 $this->chronProt = $this->newChronologyProtector();
50 }
51
52 /**
53 * Disables all access to the load balancer, will cause all database access
54 * to throw a DBAccessError
55 */
56 public static function disableBackend() {
57 global $wgLBFactoryConf;
58 self::$instance = new LBFactoryFake( $wgLBFactoryConf );
59 }
60
61 /**
62 * Get an LBFactory instance
63 *
64 * @return LBFactory
65 */
66 public static function singleton() {
67 global $wgLBFactoryConf;
68
69 if ( is_null( self::$instance ) ) {
70 $class = self::getLBFactoryClass( $wgLBFactoryConf );
71 $config = $wgLBFactoryConf;
72 if ( !isset( $config['readOnlyReason'] ) ) {
73 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
74 }
75 self::$instance = new $class( $config );
76 }
77
78 return self::$instance;
79 }
80
81 /**
82 * Returns the LBFactory class to use and the load balancer configuration.
83 *
84 * @param array $config (e.g. $wgLBFactoryConf)
85 * @return string Class name
86 */
87 public static function getLBFactoryClass( array $config ) {
88 // For configuration backward compatibility after removing
89 // underscores from class names in MediaWiki 1.23.
90 $bcClasses = array(
91 'LBFactory_Simple' => 'LBFactorySimple',
92 'LBFactory_Single' => 'LBFactorySingle',
93 'LBFactory_Multi' => 'LBFactoryMulti',
94 'LBFactory_Fake' => 'LBFactoryFake',
95 );
96
97 $class = $config['class'];
98
99 if ( isset( $bcClasses[$class] ) ) {
100 $class = $bcClasses[$class];
101 wfDeprecated(
102 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
103 '1.23'
104 );
105 }
106
107 return $class;
108 }
109
110 /**
111 * Shut down, close connections and destroy the cached instance.
112 */
113 public static function destroyInstance() {
114 if ( self::$instance ) {
115 self::$instance->shutdown();
116 self::$instance->forEachLBCallMethod( 'closeAll' );
117 self::$instance = null;
118 }
119 }
120
121 /**
122 * Set the instance to be the given object
123 *
124 * @param LBFactory $instance
125 */
126 public static function setInstance( $instance ) {
127 self::destroyInstance();
128 self::$instance = $instance;
129 }
130
131 /**
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.
134 *
135 * @param bool|string $wiki Wiki ID, or false for the current wiki
136 * @return LoadBalancer
137 */
138 abstract public function newMainLB( $wiki = false );
139
140 /**
141 * Get a cached (tracked) load balancer object.
142 *
143 * @param bool|string $wiki Wiki ID, or false for the current wiki
144 * @return LoadBalancer
145 */
146 abstract public function getMainLB( $wiki = false );
147
148 /**
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
151 * cleaning it up.
152 *
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
156 */
157 abstract protected function newExternalLB( $cluster, $wiki = false );
158
159 /**
160 * Get a cached (tracked) load balancer for external storage
161 *
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
165 */
166 abstract public function &getExternalLB( $cluster, $wiki = false );
167
168 /**
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.
172 *
173 * @param callable $callback
174 * @param array $params
175 */
176 abstract public function forEachLB( $callback, array $params = array() );
177
178 /**
179 * Prepare all tracked load balancers for shutdown
180 * @param integer $flags Supports SHUTDOWN_* flags
181 * STUB
182 */
183 public function shutdown( $flags = 0 ) {
184 }
185
186 /**
187 * Call a method of each tracked load balancer
188 *
189 * @param string $methodName
190 * @param array $args
191 */
192 private function forEachLBCallMethod( $methodName, array $args = array() ) {
193 $this->forEachLB( function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
194 call_user_func_array( array( $loadBalancer, $methodName ), $args );
195 }, array( $methodName, $args ) );
196 }
197
198 /**
199 * Commit on all connections. Done for two reasons:
200 * 1. To commit changes to the masters.
201 * 2. To release the snapshot on all connections, master and slave.
202 */
203 public function commitAll() {
204 $this->forEachLBCallMethod( 'commitAll' );
205 }
206
207 /**
208 * Commit changes on all master connections
209 */
210 public function commitMasterChanges() {
211 $start = microtime( true );
212 $this->forEachLBCallMethod( 'commitMasterChanges' );
213 $timeMs = 1000 * ( microtime( true ) - $start );
214 RequestContext::getMain()->getStats()->timing( "db.commit-masters", $timeMs );
215 }
216
217 /**
218 * Rollback changes on all master connections
219 * @since 1.23
220 */
221 public function rollbackMasterChanges() {
222 $this->forEachLBCallMethod( 'rollbackMasterChanges' );
223 }
224
225 /**
226 * Determine if any master connection has pending changes
227 * @return bool
228 * @since 1.23
229 */
230 public function hasMasterChanges() {
231 $ret = false;
232 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
233 $ret = $ret || $lb->hasMasterChanges();
234 } );
235
236 return $ret;
237 }
238
239 /**
240 * Detemine if any lagged slave connection was used
241 * @since 1.27
242 * @return bool
243 */
244 public function laggedSlaveUsed() {
245 $ret = false;
246 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
247 $ret = $ret || $lb->laggedSlaveUsed();
248 } );
249
250 return $ret;
251 }
252
253 /**
254 * Determine if any master connection has pending/written changes from this request
255 * @return bool
256 * @since 1.27
257 */
258 public function hasOrMadeRecentMasterChanges() {
259 $ret = false;
260 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
261 $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
262 } );
263 return $ret;
264 }
265
266 /**
267 * Disable the ChronologyProtector for all load balancers
268 *
269 * This can be called at the start of special API entry points
270 *
271 * @since 1.27
272 */
273 public function disableChronologyProtection() {
274 $this->chronProt->setEnabled( false );
275 }
276
277 /**
278 * @return ChronologyProtector
279 */
280 protected function newChronologyProtector() {
281 $request = RequestContext::getMain()->getRequest();
282 $chronProt = new ChronologyProtector(
283 ObjectCache::getMainStashInstance(),
284 array(
285 'ip' => $request->getIP(),
286 'agent' => $request->getHeader( 'User-Agent' )
287 )
288 );
289 if ( PHP_SAPI === 'cli' ) {
290 $chronProt->setEnabled( false );
291 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
292 // Request opted out of using position wait logic. This is useful for requests
293 // done by the job queue or background ETL that do not have a meaningful session.
294 $chronProt->setWaitEnabled( false );
295 }
296
297 return $chronProt;
298 }
299
300 /**
301 * @param ChronologyProtector $cp
302 */
303 protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
304 // Get all the master positions needed
305 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
306 $cp->shutdownLB( $lb );
307 } );
308 // Write them to the stash
309 $unsavedPositions = $cp->shutdown();
310 // If the positions failed to write to the stash, at least wait on local datacenter
311 // slaves to catch up before responding. Even if there are several DCs, this increases
312 // the chance that the user will see their own changes immediately afterwards. As long
313 // as the sticky DC cookie applies (same domain), this is not even an issue.
314 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
315 $masterName = $lb->getServerName( $lb->getWriterIndex() );
316 if ( isset( $unsavedPositions[$masterName] ) ) {
317 $lb->waitForAll( $unsavedPositions[$masterName] );
318 }
319 } );
320 }
321 }
322
323 /**
324 * Exception class for attempted DB access
325 */
326 class DBAccessError extends MWException {
327 public function __construct() {
328 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
329 "This is not allowed." );
330 }
331 }