MessageCache invalidation improvements
[mediawiki.git] / includes / MediaWikiServices.php
blob7c9363ca19a8d0bff51a615615655cda309a6ff8
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 Parser;
26 use ProxyLookup;
27 use SearchEngine;
28 use SearchEngineConfig;
29 use SearchEngineFactory;
30 use SiteLookup;
31 use SiteStore;
32 use WatchedItemStore;
33 use WatchedItemQueryService;
34 use SkinFactory;
35 use TitleFormatter;
36 use TitleParser;
37 use VirtualRESTServiceClient;
38 use MediaWiki\Interwiki\InterwikiLookup;
40 /**
41 * Service locator for MediaWiki core services.
43 * This program is free software; you can redistribute it and/or modify
44 * it under the terms of the GNU General Public License as published by
45 * the Free Software Foundation; either version 2 of the License, or
46 * (at your option) any later version.
48 * This program is distributed in the hope that it will be useful,
49 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51 * GNU General Public License for more details.
53 * You should have received a copy of the GNU General Public License along
54 * with this program; if not, write to the Free Software Foundation, Inc.,
55 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
56 * http://www.gnu.org/copyleft/gpl.html
58 * @file
60 * @since 1.27
63 /**
64 * MediaWikiServices is the service locator for the application scope of MediaWiki.
65 * Its implemented as a simple configurable DI container.
66 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
67 * the network of service objects that defines MediaWiki's application logic.
68 * It acts as an entry point to MediaWiki's dependency injection mechanism.
70 * Services are defined in the "wiring" array passed to the constructor,
71 * or by calling defineService().
73 * @see docs/injection.txt for an overview of using dependency injection in the
74 * MediaWiki code base.
76 class MediaWikiServices extends ServiceContainer {
78 /**
79 * @var MediaWikiServices|null
81 private static $instance = null;
83 /**
84 * Returns the global default instance of the top level service locator.
86 * @since 1.27
88 * The default instance is initialized using the service instantiator functions
89 * defined in ServiceWiring.php.
91 * @note This should only be called by static functions! The instance returned here
92 * should not be passed around! Objects that need access to a service should have
93 * that service injected into the constructor, never a service locator!
95 * @return MediaWikiServices
97 public static function getInstance() {
98 if ( self::$instance === null ) {
99 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
100 // but some information from the global scope has to be injected here,
101 // even if it's just a file name or database credentials to load
102 // configuration from.
103 $bootstrapConfig = new GlobalVarConfig();
104 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
107 return self::$instance;
111 * Replaces the global MediaWikiServices instance.
113 * @since 1.28
115 * @note This is for use in PHPUnit tests only!
117 * @throws MWException if called outside of PHPUnit tests.
119 * @param MediaWikiServices $services The new MediaWikiServices object.
121 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
123 public static function forceGlobalInstance( MediaWikiServices $services ) {
124 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
125 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
128 $old = self::getInstance();
129 self::$instance = $services;
131 return $old;
135 * Creates a new instance of MediaWikiServices and sets it as the global default
136 * instance. getInstance() will return a different MediaWikiServices object
137 * after every call to resetGlobalInstance().
139 * @since 1.28
141 * @warning This should not be used during normal operation. It is intended for use
142 * when the configuration has changed significantly since bootstrap time, e.g.
143 * during the installation process or during testing.
145 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
146 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
147 * any of the services managed by MediaWikiServices exist. If any service objects
148 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
149 * with the operation of the services managed by the new MediaWikiServices.
150 * Operating with a mix of services created by the old and the new
151 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
152 * Any class implementing LAZY LOADING is especially prone to this problem,
153 * since instances would typically retain a reference to a storage layer service.
155 * @see forceGlobalInstance()
156 * @see resetGlobalInstance()
157 * @see resetBetweenTest()
159 * @param Config|null $bootstrapConfig The Config object to be registered as the
160 * 'BootstrapConfig' service. This has to contain at least the information
161 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
162 * config of the old instance of MediaWikiServices will be re-used. If there
163 * was no previous instance, a new GlobalVarConfig object will be used to
164 * bootstrap the services.
166 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
167 * See SalvageableService for details.
169 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
170 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
171 * is defined).
173 public static function resetGlobalInstance( Config $bootstrapConfig = null, $quick = '' ) {
174 if ( self::$instance === null ) {
175 // no global instance yet, nothing to reset
176 return;
179 self::failIfResetNotAllowed( __METHOD__ );
181 if ( $bootstrapConfig === null ) {
182 $bootstrapConfig = self::$instance->getBootstrapConfig();
185 $oldInstance = self::$instance;
187 self::$instance = self::newInstance( $bootstrapConfig, 'load' );
188 self::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
190 if ( $quick === 'quick' ) {
191 self::$instance->salvage( $oldInstance );
192 } else {
193 $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 // https://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.29
570 * @return Parser
572 public function getParser() {
573 return $this->getService( 'Parser' );
577 * @since 1.28
578 * @return GenderCache
580 public function getGenderCache() {
581 return $this->getService( 'GenderCache' );
585 * @since 1.28
586 * @return LinkCache
588 public function getLinkCache() {
589 return $this->getService( 'LinkCache' );
593 * @since 1.28
594 * @return LinkRendererFactory
596 public function getLinkRendererFactory() {
597 return $this->getService( 'LinkRendererFactory' );
601 * LinkRenderer instance that can be used
602 * if no custom options are needed
604 * @since 1.28
605 * @return LinkRenderer
607 public function getLinkRenderer() {
608 return $this->getService( 'LinkRenderer' );
612 * @since 1.28
613 * @return TitleFormatter
615 public function getTitleFormatter() {
616 return $this->getService( 'TitleFormatter' );
620 * @since 1.28
621 * @return TitleParser
623 public function getTitleParser() {
624 return $this->getService( 'TitleParser' );
628 * @since 1.28
629 * @return \BagOStuff
631 public function getMainObjectStash() {
632 return $this->getService( 'MainObjectStash' );
636 * @since 1.28
637 * @return \WANObjectCache
639 public function getMainWANObjectCache() {
640 return $this->getService( 'MainWANObjectCache' );
644 * @since 1.28
645 * @return \BagOStuff
647 public function getLocalServerObjectCache() {
648 return $this->getService( 'LocalServerObjectCache' );
652 * @since 1.28
653 * @return VirtualRESTServiceClient
655 public function getVirtualRESTServiceClient() {
656 return $this->getService( 'VirtualRESTServiceClient' );
659 ///////////////////////////////////////////////////////////////////////////
660 // NOTE: When adding a service getter here, don't forget to add a test
661 // case for it in MediaWikiServicesTest::provideGetters() and in
662 // MediaWikiServicesTest::provideGetService()!
663 ///////////////////////////////////////////////////////////////////////////