Allow resources to be salvaged across service resets.
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use Config;
5 use ConfigFactory;
6 use EventRelayerGroup;
7 use GenderCache;
8 use GlobalVarConfig;
9 use Hooks;
10 use LBFactory;
11 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
12 use LoadBalancer;
13 use MediaWiki\Services\SalvageableService;
14 use MediaWiki\Services\ServiceContainer;
15 use MWException;
16 use ResourceLoader;
17 use SearchEngine;
18 use SearchEngineConfig;
19 use SearchEngineFactory;
20 use SiteLookup;
21 use SiteStore;
22 use WatchedItemStore;
23 use SkinFactory;
24 use TitleFormatter;
25 use TitleParser;
26
27 /**
28 * Service locator for MediaWiki core services.
29 *
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2 of the License, or
33 * (at your option) any later version.
34 *
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
39 *
40 * You should have received a copy of the GNU General Public License along
41 * with this program; if not, write to the Free Software Foundation, Inc.,
42 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
43 * http://www.gnu.org/copyleft/gpl.html
44 *
45 * @file
46 *
47 * @since 1.27
48 */
49
50 /**
51 * MediaWikiServices is the service locator for the application scope of MediaWiki.
52 * Its implemented as a simple configurable DI container.
53 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
54 * the network of service objects that defines MediaWiki's application logic.
55 * It acts as an entry point to MediaWiki's dependency injection mechanism.
56 *
57 * Services are defined in the "wiring" array passed to the constructor,
58 * or by calling defineService().
59 *
60 * @see docs/injection.txt for an overview of using dependency injection in the
61 * MediaWiki code base.
62 */
63 class MediaWikiServices extends ServiceContainer {
64
65 /**
66 * @var MediaWikiServices|null
67 */
68 private static $instance = null;
69
70 /**
71 * Returns the global default instance of the top level service locator.
72 *
73 * @since 1.27
74 *
75 * The default instance is initialized using the service instantiator functions
76 * defined in ServiceWiring.php.
77 *
78 * @note This should only be called by static functions! The instance returned here
79 * should not be passed around! Objects that need access to a service should have
80 * that service injected into the constructor, never a service locator!
81 *
82 * @return MediaWikiServices
83 */
84 public static function getInstance() {
85 if ( self::$instance === null ) {
86 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
87 // but some information from the global scope has to be injected here,
88 // even if it's just a file name or database credentials to load
89 // configuration from.
90 $bootstrapConfig = new GlobalVarConfig();
91 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
92 }
93
94 return self::$instance;
95 }
96
97 /**
98 * Replaces the global MediaWikiServices instance.
99 *
100 * @since 1.28
101 *
102 * @note This is for use in PHPUnit tests only!
103 *
104 * @throws MWException if called outside of PHPUnit tests.
105 *
106 * @param MediaWikiServices $services The new MediaWikiServices object.
107 *
108 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
109 */
110 public static function forceGlobalInstance( MediaWikiServices $services ) {
111 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
112 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
113 }
114
115 $old = self::getInstance();
116 self::$instance = $services;
117
118 return $old;
119 }
120
121 /**
122 * Creates a new instance of MediaWikiServices and sets it as the global default
123 * instance. getInstance() will return a different MediaWikiServices object
124 * after every call to resetGlobalInstance().
125 *
126 * @since 1.28
127 *
128 * @warning This should not be used during normal operation. It is intended for use
129 * when the configuration has changed significantly since bootstrap time, e.g.
130 * during the installation process or during testing.
131 *
132 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
133 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
134 * any of the services managed by MediaWikiServices exist. If any service objects
135 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
136 * with the operation of the services managed by the new MediaWikiServices.
137 * Operating with a mix of services created by the old and the new
138 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
139 * Any class implementing LAZY LOADING is especially prone to this problem,
140 * since instances would typically retain a reference to a storage layer service.
141 *
142 * @see forceGlobalInstance()
143 * @see resetGlobalInstance()
144 * @see resetBetweenTest()
145 *
146 * @param Config|null $bootstrapConfig The Config object to be registered as the
147 * 'BootstrapConfig' service. This has to contain at least the information
148 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
149 * config of the old instance of MediaWikiServices will be re-used. If there
150 * was no previous instance, a new GlobalVarConfig object will be used to
151 * bootstrap the services.
152 *
153 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
154 * See SalvageableService for details.
155 *
156 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
157 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
158 * is defined).
159 */
160 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
161 if ( self::$instance === null ) {
162 // no global instance yet, nothing to reset
163 return;
164 }
165
166 self::failIfResetNotAllowed( __METHOD__ );
167
168 if ( $bootstrapConfig === null ) {
169 $bootstrapConfig = self::$instance->getBootstrapConfig();
170 }
171
172 $oldInstance = self::$instance;
173
174 self::$instance = self::newInstance( $bootstrapConfig );
175 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
176
177 if ( $quick === 'quick' ) {
178 self::$instance->salvage( $oldInstance );
179 } else {
180 $oldInstance->destroy();
181 }
182
183 }
184
185 /**
186 * Salvages the state of any salvageable service instances in $other.
187 *
188 * @note $other will have been destroyed when salvage() returns.
189 *
190 * @param MediaWikiServices $other
191 */
192 private function salvage( self $other ) {
193 foreach ( $this->getServiceNames() as $name ) {
194 $oldService = $other->peekService( $name );
195
196 if ( $oldService instanceof SalvageableService ) {
197 /** @var SalvageableService $newService */
198 $newService = $this->getService( $name );
199 $newService->salvage( $oldService );
200 }
201 }
202
203 $other->destroy();
204 }
205
206 /**
207 * Creates a new MediaWikiServices instance and initializes it according to the
208 * given $bootstrapConfig. In particular, all wiring files defined in the
209 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
210 *
211 * @param Config|null $bootstrapConfig The Config object to be registered as the
212 * 'BootstrapConfig' service.
213 *
214 * @param string $loadWiring set this to 'load' to load the wiring files specified
215 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
216 *
217 * @return MediaWikiServices
218 * @throws MWException
219 * @throws \FatalError
220 */
221 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
222 $instance = new self( $bootstrapConfig );
223
224 // Load the default wiring from the specified files.
225 if ( $loadWiring === 'load' ) {
226 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
227 $instance->loadWiringFiles( $wiringFiles );
228 }
229
230 // Provide a traditional hook point to allow extensions to configure services.
231 Hooks::run( 'MediaWikiServices', [ $instance ] );
232
233 return $instance;
234 }
235
236 /**
237 * Disables all storage layer services. After calling this, any attempt to access the
238 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
239 * operation.
240 *
241 * @since 1.28
242 *
243 * @warning This is intended for extreme situations only and should never be used
244 * while serving normal web requests. Legitimate use cases for this method include
245 * the installation process. Test fixtures may also use this, if the fixture relies
246 * on globalState.
247 *
248 * @see resetGlobalInstance()
249 * @see resetChildProcessServices()
250 */
251 public static function disableStorageBackend() {
252 // TODO: also disable some Caches, JobQueues, etc
253 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
254 $services = self::getInstance();
255
256 foreach ( $destroy as $name ) {
257 $services->disableService( $name );
258 }
259 }
260
261 /**
262 * Resets any services that may have become stale after a child process
263 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
264 * to call this method from the parent process.
265 *
266 * @since 1.28
267 *
268 * @note This is intended for use in the context of process forking only!
269 *
270 * @see resetGlobalInstance()
271 * @see disableStorageBackend()
272 */
273 public static function resetChildProcessServices() {
274 // NOTE: for now, just reset everything. Since we don't know the interdependencies
275 // between services, we can't do this more selectively at this time.
276 self::resetGlobalInstance();
277
278 // Child, reseed because there is no bug in PHP:
279 // http://bugs.php.net/bug.php?id=42465
280 mt_srand( getmypid() );
281 }
282
283 /**
284 * Resets the given service for testing purposes.
285 *
286 * @since 1.28
287 *
288 * @warning This is generally unsafe! Other services may still retain references
289 * to the stale service instance, leading to failures and inconsistencies. Subclasses
290 * may use this method to reset specific services under specific instances, but
291 * it should not be exposed to application logic.
292 *
293 * @note With proper dependency injection used throughout the codebase, this method
294 * should not be needed. It is provided to allow tests that pollute global service
295 * instances to clean up.
296 *
297 * @param string $name
298 * @param string $destroy Whether the service instance should be destroyed if it exists.
299 * When set to false, any existing service instance will effectively be detached
300 * from the container.
301 *
302 * @throws MWException if called outside of PHPUnit tests.
303 */
304 public function resetServiceForTesting( $name, $destroy = true ) {
305 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
306 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
307 }
308
309 $this->resetService( $name, $destroy );
310 }
311
312 /**
313 * Convenience method that throws an exception unless it is called during a phase in which
314 * resetting of global services is allowed. In general, services should not be reset
315 * individually, since that may introduce inconsistencies.
316 *
317 * @since 1.28
318 *
319 * This method will throw an exception if:
320 *
321 * - self::$resetInProgress is false (to allow all services to be reset together
322 * via resetGlobalInstance)
323 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
324 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
325 *
326 * This method is intended to be used to safeguard against accidentally resetting
327 * global service instances that are not yet managed by MediaWikiServices. It is
328 * defined here in the MediaWikiServices services class to have a central place
329 * for managing service bootstrapping and resetting.
330 *
331 * @param string $method the name of the caller method, as given by __METHOD__.
332 *
333 * @throws MWException if called outside bootstrap mode.
334 *
335 * @see resetGlobalInstance()
336 * @see forceGlobalInstance()
337 * @see disableStorageBackend()
338 */
339 public static function failIfResetNotAllowed( $method ) {
340 if ( !defined( 'MW_PHPUNIT_TEST' )
341 && !defined( 'MW_PARSER_TEST' )
342 && !defined( 'MEDIAWIKI_INSTALL' )
343 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
344 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
345 ) {
346 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
347 }
348 }
349
350 /**
351 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
352 * This has to contain at least the information needed to set up the 'ConfigFactory'
353 * service.
354 */
355 public function __construct( Config $config ) {
356 parent::__construct();
357
358 // Register the given Config object as the bootstrap config service.
359 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
360 return $config;
361 } );
362 }
363
364 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
365
366 /**
367 * Returns the Config object containing the bootstrap configuration.
368 * Bootstrap configuration would typically include database credentials
369 * and other information that may be needed before the ConfigFactory
370 * service can be instantiated.
371 *
372 * @note This should only be used during bootstrapping, in particular
373 * when creating the MainConfig service. Application logic should
374 * use getMainConfig() to get a Config instances.
375 *
376 * @since 1.27
377 * @return Config
378 */
379 public function getBootstrapConfig() {
380 return $this->getService( 'BootstrapConfig' );
381 }
382
383 /**
384 * @since 1.27
385 * @return ConfigFactory
386 */
387 public function getConfigFactory() {
388 return $this->getService( 'ConfigFactory' );
389 }
390
391 /**
392 * Returns the Config object that provides configuration for MediaWiki core.
393 * This may or may not be the same object that is returned by getBootstrapConfig().
394 *
395 * @since 1.27
396 * @return Config
397 */
398 public function getMainConfig() {
399 return $this->getService( 'MainConfig' );
400 }
401
402 /**
403 * @since 1.27
404 * @return SiteLookup
405 */
406 public function getSiteLookup() {
407 return $this->getService( 'SiteLookup' );
408 }
409
410 /**
411 * @since 1.27
412 * @return SiteStore
413 */
414 public function getSiteStore() {
415 return $this->getService( 'SiteStore' );
416 }
417
418 /**
419 * @since 1.27
420 * @return StatsdDataFactory
421 */
422 public function getStatsdDataFactory() {
423 return $this->getService( 'StatsdDataFactory' );
424 }
425
426 /**
427 * @since 1.27
428 * @return EventRelayerGroup
429 */
430 public function getEventRelayerGroup() {
431 return $this->getService( 'EventRelayerGroup' );
432 }
433
434 /**
435 * @since 1.27
436 * @return SearchEngine
437 */
438 public function newSearchEngine() {
439 // New engine object every time, since they keep state
440 return $this->getService( 'SearchEngineFactory' )->create();
441 }
442
443 /**
444 * @since 1.27
445 * @return SearchEngineFactory
446 */
447 public function getSearchEngineFactory() {
448 return $this->getService( 'SearchEngineFactory' );
449 }
450
451 /**
452 * @since 1.27
453 * @return SearchEngineConfig
454 */
455 public function getSearchEngineConfig() {
456 return $this->getService( 'SearchEngineConfig' );
457 }
458
459 /**
460 * @since 1.27
461 * @return SkinFactory
462 */
463 public function getSkinFactory() {
464 return $this->getService( 'SkinFactory' );
465 }
466
467 /**
468 * @since 1.28
469 * @return LBFactory
470 */
471 public function getDBLoadBalancerFactory() {
472 return $this->getService( 'DBLoadBalancerFactory' );
473 }
474
475 /**
476 * @since 1.28
477 * @return LoadBalancer The main DB load balancer for the local wiki.
478 */
479 public function getDBLoadBalancer() {
480 return $this->getService( 'DBLoadBalancer' );
481 }
482
483 /**
484 * @since 1.28
485 * @return WatchedItemStore
486 */
487 public function getWatchedItemStore() {
488 return $this->getService( 'WatchedItemStore' );
489 }
490
491 /**
492 * @since 1.28
493 * @return GenderCache
494 */
495 public function getGenderCache() {
496 return $this->getService( 'GenderCache' );
497 }
498 /**
499 * @since 1.28
500 * @return TitleFormatter
501 */
502 public function getTitleFormatter() {
503 return $this->getService( 'TitleFormatter' );
504 }
505
506 /**
507 * @since 1.28
508 * @return TitleParser
509 */
510 public function getTitleParser() {
511 return $this->getService( 'TitleParser' );
512 }
513
514 ///////////////////////////////////////////////////////////////////////////
515 // NOTE: When adding a service getter here, don't forget to add a test
516 // case for it in MediaWikiServicesTest::provideGetters() and in
517 // MediaWikiServicesTest::provideGetService()!
518 ///////////////////////////////////////////////////////////////////////////
519
520 }