objectcache: avoid using process cache in nested callbacks
[mediawiki.git] / includes / MediaWikiServices.php
blobba8b71b0f18c73201ed1059ae7ae8c89fe798c60
1 <?php
2 namespace MediaWiki;
4 use Config;
5 use ConfigFactory;
6 use CryptHKDF;
7 use CryptRand;
8 use EventRelayerGroup;
9 use GenderCache;
10 use GlobalVarConfig;
11 use Hooks;
12 use LBFactory;
13 use LinkCache;
14 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
15 use LoadBalancer;
16 use MediaHandlerFactory;
17 use MediaWiki\Linker\LinkRenderer;
18 use MediaWiki\Linker\LinkRendererFactory;
19 use MediaWiki\Services\SalvageableService;
20 use MediaWiki\Services\ServiceContainer;
21 use MediaWiki\Services\NoSuchServiceException;
22 use MWException;
23 use MimeAnalyzer;
24 use ObjectCache;
25 use ProxyLookup;
26 use SearchEngine;
27 use SearchEngineConfig;
28 use SearchEngineFactory;
29 use SiteLookup;
30 use SiteStore;
31 use WatchedItemStore;
32 use WatchedItemQueryService;
33 use SkinFactory;
34 use TitleFormatter;
35 use TitleParser;
36 use VirtualRESTServiceClient;
37 use MediaWiki\Interwiki\InterwikiLookup;
39 /**
40 * Service locator for MediaWiki core services.
42 * This program is free software; you can redistribute it and/or modify
43 * it under the terms of the GNU General Public License as published by
44 * the Free Software Foundation; either version 2 of the License, or
45 * (at your option) any later version.
47 * This program is distributed in the hope that it will be useful,
48 * but WITHOUT ANY WARRANTY; without even the implied warranty of
49 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
50 * GNU General Public License for more details.
52 * You should have received a copy of the GNU General Public License along
53 * with this program; if not, write to the Free Software Foundation, Inc.,
54 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
55 * http://www.gnu.org/copyleft/gpl.html
57 * @file
59 * @since 1.27
62 /**
63 * MediaWikiServices is the service locator for the application scope of MediaWiki.
64 * Its implemented as a simple configurable DI container.
65 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
66 * the network of service objects that defines MediaWiki's application logic.
67 * It acts as an entry point to MediaWiki's dependency injection mechanism.
69 * Services are defined in the "wiring" array passed to the constructor,
70 * or by calling defineService().
72 * @see docs/injection.txt for an overview of using dependency injection in the
73 * MediaWiki code base.
75 class MediaWikiServices extends ServiceContainer {
77 /**
78 * @var MediaWikiServices|null
80 private static $instance = null;
82 /**
83 * Returns the global default instance of the top level service locator.
85 * @since 1.27
87 * The default instance is initialized using the service instantiator functions
88 * defined in ServiceWiring.php.
90 * @note This should only be called by static functions! The instance returned here
91 * should not be passed around! Objects that need access to a service should have
92 * that service injected into the constructor, never a service locator!
94 * @return MediaWikiServices
96 public static function getInstance() {
97 if ( self::$instance === null ) {
98 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
99 // but some information from the global scope has to be injected here,
100 // even if it's just a file name or database credentials to load
101 // configuration from.
102 $bootstrapConfig = new GlobalVarConfig();
103 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
106 return self::$instance;
110 * Replaces the global MediaWikiServices instance.
112 * @since 1.28
114 * @note This is for use in PHPUnit tests only!
116 * @throws MWException if called outside of PHPUnit tests.
118 * @param MediaWikiServices $services The new MediaWikiServices object.
120 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
122 public static function forceGlobalInstance( MediaWikiServices $services ) {
123 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
124 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
127 $old = self::getInstance();
128 self::$instance = $services;
130 return $old;
134 * Creates a new instance of MediaWikiServices and sets it as the global default
135 * instance. getInstance() will return a different MediaWikiServices object
136 * after every call to resetGlobalInstance().
138 * @since 1.28
140 * @warning This should not be used during normal operation. It is intended for use
141 * when the configuration has changed significantly since bootstrap time, e.g.
142 * during the installation process or during testing.
144 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
145 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
146 * any of the services managed by MediaWikiServices exist. If any service objects
147 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
148 * with the operation of the services managed by the new MediaWikiServices.
149 * Operating with a mix of services created by the old and the new
150 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
151 * Any class implementing LAZY LOADING is especially prone to this problem,
152 * since instances would typically retain a reference to a storage layer service.
154 * @see forceGlobalInstance()
155 * @see resetGlobalInstance()
156 * @see resetBetweenTest()
158 * @param Config|null $bootstrapConfig The Config object to be registered as the
159 * 'BootstrapConfig' service. This has to contain at least the information
160 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
161 * config of the old instance of MediaWikiServices will be re-used. If there
162 * was no previous instance, a new GlobalVarConfig object will be used to
163 * bootstrap the services.
165 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
166 * See SalvageableService for details.
168 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
169 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
170 * is defined).
172 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
173 if ( self::$instance === null ) {
174 // no global instance yet, nothing to reset
175 return;
178 self::failIfResetNotAllowed( __METHOD__ );
180 if ( $bootstrapConfig === null ) {
181 $bootstrapConfig = self::$instance->getBootstrapConfig();
184 $oldInstance = self::$instance;
186 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
187 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
189 if ( $quick === 'quick' ) {
190 self::$instance->salvage( $oldInstance );
191 } else {
192 $oldInstance->destroy();
198 * Salvages the state of any salvageable service instances in $other.
200 * @note $other will have been destroyed when salvage() returns.
202 * @param MediaWikiServices $other
204 private function salvage( self $other ) {
205 foreach ( $this->getServiceNames() as $name ) {
206 // The service could be new in the new instance and not registered in the
207 // other instance (e.g. an extension that was loaded after the instantiation of
208 // the other instance. Skip this service in this case. See T143974
209 try {
210 $oldService = $other->peekService( $name );
211 } catch ( NoSuchServiceException $e ) {
212 continue;
215 if ( $oldService instanceof SalvageableService ) {
216 /** @var SalvageableService $newService */
217 $newService = $this->getService( $name );
218 $newService->salvage( $oldService );
222 $other->destroy();
226 * Creates a new MediaWikiServices instance and initializes it according to the
227 * given $bootstrapConfig. In particular, all wiring files defined in the
228 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
230 * @param Config|null $bootstrapConfig The Config object to be registered as the
231 * 'BootstrapConfig' service.
233 * @param string $loadWiring set this to 'load' to load the wiring files specified
234 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
236 * @return MediaWikiServices
237 * @throws MWException
238 * @throws \FatalError
240 private static function newInstance( Config $bootstrapConfig, $loadWiring = '' ) {
241 $instance = new self( $bootstrapConfig );
243 // Load the default wiring from the specified files.
244 if ( $loadWiring === 'load' ) {
245 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
246 $instance->loadWiringFiles( $wiringFiles );
249 // Provide a traditional hook point to allow extensions to configure services.
250 Hooks::run( 'MediaWikiServices', [ $instance ] );
252 return $instance;
256 * Disables all storage layer services. After calling this, any attempt to access the
257 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
258 * operation.
260 * @since 1.28
262 * @warning This is intended for extreme situations only and should never be used
263 * while serving normal web requests. Legitimate use cases for this method include
264 * the installation process. Test fixtures may also use this, if the fixture relies
265 * on globalState.
267 * @see resetGlobalInstance()
268 * @see resetChildProcessServices()
270 public static function disableStorageBackend() {
271 // TODO: also disable some Caches, JobQueues, etc
272 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
273 $services = self::getInstance();
275 foreach ( $destroy as $name ) {
276 $services->disableService( $name );
279 ObjectCache::clear();
283 * Resets any services that may have become stale after a child process
284 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
285 * to call this method from the parent process.
287 * @since 1.28
289 * @note This is intended for use in the context of process forking only!
291 * @see resetGlobalInstance()
292 * @see disableStorageBackend()
294 public static function resetChildProcessServices() {
295 // NOTE: for now, just reset everything. Since we don't know the interdependencies
296 // between services, we can't do this more selectively at this time.
297 self::resetGlobalInstance();
299 // Child, reseed because there is no bug in PHP:
300 // http://bugs.php.net/bug.php?id=42465
301 mt_srand( getmypid() );
305 * Resets the given service for testing purposes.
307 * @since 1.28
309 * @warning This is generally unsafe! Other services may still retain references
310 * to the stale service instance, leading to failures and inconsistencies. Subclasses
311 * may use this method to reset specific services under specific instances, but
312 * it should not be exposed to application logic.
314 * @note With proper dependency injection used throughout the codebase, this method
315 * should not be needed. It is provided to allow tests that pollute global service
316 * instances to clean up.
318 * @param string $name
319 * @param bool $destroy Whether the service instance should be destroyed if it exists.
320 * When set to false, any existing service instance will effectively be detached
321 * from the container.
323 * @throws MWException if called outside of PHPUnit tests.
325 public function resetServiceForTesting( $name, $destroy = true ) {
326 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
327 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
330 $this->resetService( $name, $destroy );
334 * Convenience method that throws an exception unless it is called during a phase in which
335 * resetting of global services is allowed. In general, services should not be reset
336 * individually, since that may introduce inconsistencies.
338 * @since 1.28
340 * This method will throw an exception if:
342 * - self::$resetInProgress is false (to allow all services to be reset together
343 * via resetGlobalInstance)
344 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
345 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
347 * This method is intended to be used to safeguard against accidentally resetting
348 * global service instances that are not yet managed by MediaWikiServices. It is
349 * defined here in the MediaWikiServices services class to have a central place
350 * for managing service bootstrapping and resetting.
352 * @param string $method the name of the caller method, as given by __METHOD__.
354 * @throws MWException if called outside bootstrap mode.
356 * @see resetGlobalInstance()
357 * @see forceGlobalInstance()
358 * @see disableStorageBackend()
360 public static function failIfResetNotAllowed( $method ) {
361 if ( !defined( 'MW_PHPUNIT_TEST' )
362 && !defined( 'MW_PARSER_TEST' )
363 && !defined( 'MEDIAWIKI_INSTALL' )
364 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
365 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
367 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
372 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
373 * This has to contain at least the information needed to set up the 'ConfigFactory'
374 * service.
376 public function __construct( Config $config ) {
377 parent::__construct();
379 // Register the given Config object as the bootstrap config service.
380 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
381 return $config;
382 } );
385 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
388 * Returns the Config object containing the bootstrap configuration.
389 * Bootstrap configuration would typically include database credentials
390 * and other information that may be needed before the ConfigFactory
391 * service can be instantiated.
393 * @note This should only be used during bootstrapping, in particular
394 * when creating the MainConfig service. Application logic should
395 * use getMainConfig() to get a Config instances.
397 * @since 1.27
398 * @return Config
400 public function getBootstrapConfig() {
401 return $this->getService( 'BootstrapConfig' );
405 * @since 1.27
406 * @return ConfigFactory
408 public function getConfigFactory() {
409 return $this->getService( 'ConfigFactory' );
413 * Returns the Config object that provides configuration for MediaWiki core.
414 * This may or may not be the same object that is returned by getBootstrapConfig().
416 * @since 1.27
417 * @return Config
419 public function getMainConfig() {
420 return $this->getService( 'MainConfig' );
424 * @since 1.27
425 * @return SiteLookup
427 public function getSiteLookup() {
428 return $this->getService( 'SiteLookup' );
432 * @since 1.27
433 * @return SiteStore
435 public function getSiteStore() {
436 return $this->getService( 'SiteStore' );
440 * @since 1.28
441 * @return InterwikiLookup
443 public function getInterwikiLookup() {
444 return $this->getService( 'InterwikiLookup' );
448 * @since 1.27
449 * @return StatsdDataFactory
451 public function getStatsdDataFactory() {
452 return $this->getService( 'StatsdDataFactory' );
456 * @since 1.27
457 * @return EventRelayerGroup
459 public function getEventRelayerGroup() {
460 return $this->getService( 'EventRelayerGroup' );
464 * @since 1.27
465 * @return SearchEngine
467 public function newSearchEngine() {
468 // New engine object every time, since they keep state
469 return $this->getService( 'SearchEngineFactory' )->create();
473 * @since 1.27
474 * @return SearchEngineFactory
476 public function getSearchEngineFactory() {
477 return $this->getService( 'SearchEngineFactory' );
481 * @since 1.27
482 * @return SearchEngineConfig
484 public function getSearchEngineConfig() {
485 return $this->getService( 'SearchEngineConfig' );
489 * @since 1.27
490 * @return SkinFactory
492 public function getSkinFactory() {
493 return $this->getService( 'SkinFactory' );
497 * @since 1.28
498 * @return LBFactory
500 public function getDBLoadBalancerFactory() {
501 return $this->getService( 'DBLoadBalancerFactory' );
505 * @since 1.28
506 * @return LoadBalancer The main DB load balancer for the local wiki.
508 public function getDBLoadBalancer() {
509 return $this->getService( 'DBLoadBalancer' );
513 * @since 1.28
514 * @return WatchedItemStore
516 public function getWatchedItemStore() {
517 return $this->getService( 'WatchedItemStore' );
521 * @since 1.28
522 * @return WatchedItemQueryService
524 public function getWatchedItemQueryService() {
525 return $this->getService( 'WatchedItemQueryService' );
529 * @since 1.28
530 * @return CryptRand
532 public function getCryptRand() {
533 return $this->getService( 'CryptRand' );
537 * @since 1.28
538 * @return CryptHKDF
540 public function getCryptHKDF() {
541 return $this->getService( 'CryptHKDF' );
545 * @since 1.28
546 * @return MediaHandlerFactory
548 public function getMediaHandlerFactory() {
549 return $this->getService( 'MediaHandlerFactory' );
553 * @since 1.28
554 * @return MimeAnalyzer
556 public function getMimeAnalyzer() {
557 return $this->getService( 'MimeAnalyzer' );
561 * @since 1.28
562 * @return ProxyLookup
564 public function getProxyLookup() {
565 return $this->getService( 'ProxyLookup' );
569 * @since 1.28
570 * @return GenderCache
572 public function getGenderCache() {
573 return $this->getService( 'GenderCache' );
577 * @since 1.28
578 * @return LinkCache
580 public function getLinkCache() {
581 return $this->getService( 'LinkCache' );
585 * @since 1.28
586 * @return LinkRendererFactory
588 public function getLinkRendererFactory() {
589 return $this->getService( 'LinkRendererFactory' );
593 * LinkRenderer instance that can be used
594 * if no custom options are needed
596 * @since 1.28
597 * @return LinkRenderer
599 public function getLinkRenderer() {
600 return $this->getService( 'LinkRenderer' );
604 * @since 1.28
605 * @return TitleFormatter
607 public function getTitleFormatter() {
608 return $this->getService( 'TitleFormatter' );
612 * @since 1.28
613 * @return TitleParser
615 public function getTitleParser() {
616 return $this->getService( 'TitleParser' );
620 * @since 1.28
621 * @return \BagOStuff
623 public function getMainObjectStash() {
624 return $this->getService( 'MainObjectStash' );
628 * @since 1.28
629 * @return \WANObjectCache
631 public function getMainWANObjectCache() {
632 return $this->getService( 'MainWANObjectCache' );
636 * @since 1.28
637 * @return \BagOStuff
639 public function getLocalServerObjectCache() {
640 return $this->getService( 'LocalServerObjectCache' );
644 * @since 1.28
645 * @return VirtualRESTServiceClient
647 public function getVirtualRESTServiceClient() {
648 return $this->getService( 'VirtualRESTServiceClient' );
651 ///////////////////////////////////////////////////////////////////////////
652 // NOTE: When adding a service getter here, don't forget to add a test
653 // case for it in MediaWikiServicesTest::provideGetters() and in
654 // MediaWikiServicesTest::provideGetService()!
655 ///////////////////////////////////////////////////////////////////////////