12 use IBufferingStatsdDataFactory
;
13 use MediaWiki\Shell\CommandFactory
;
14 use MediaWiki\Storage\BlobStore
;
15 use MediaWiki\Storage\RevisionStore
;
16 use Wikimedia\Rdbms\LBFactory
;
18 use Wikimedia\Rdbms\LoadBalancer
;
19 use MediaHandlerFactory
;
20 use MediaWiki\Linker\LinkRenderer
;
21 use MediaWiki\Linker\LinkRendererFactory
;
22 use MediaWiki\Services\SalvageableService
;
23 use MediaWiki\Services\ServiceContainer
;
24 use MediaWiki\Services\NoSuchServiceException
;
32 use SearchEngineConfig
;
33 use SearchEngineFactory
;
36 use WatchedItemStoreInterface
;
37 use WatchedItemQueryService
;
41 use VirtualRESTServiceClient
;
42 use MediaWiki\Interwiki\InterwikiLookup
;
45 * Service locator for MediaWiki core services.
47 * This program is free software; you can redistribute it and/or modify
48 * it under the terms of the GNU General Public License as published by
49 * the Free Software Foundation; either version 2 of the License, or
50 * (at your option) any later version.
52 * This program is distributed in the hope that it will be useful,
53 * but WITHOUT ANY WARRANTY; without even the implied warranty of
54 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55 * GNU General Public License for more details.
57 * You should have received a copy of the GNU General Public License along
58 * with this program; if not, write to the Free Software Foundation, Inc.,
59 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
60 * http://www.gnu.org/copyleft/gpl.html
68 * MediaWikiServices is the service locator for the application scope of MediaWiki.
69 * Its implemented as a simple configurable DI container.
70 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
71 * the network of service objects that defines MediaWiki's application logic.
72 * It acts as an entry point to MediaWiki's dependency injection mechanism.
74 * Services are defined in the "wiring" array passed to the constructor,
75 * or by calling defineService().
77 * @see docs/injection.txt for an overview of using dependency injection in the
78 * MediaWiki code base.
80 class MediaWikiServices
extends ServiceContainer
{
83 * @var MediaWikiServices|null
85 private static $instance = null;
88 * Returns the global default instance of the top level service locator.
92 * The default instance is initialized using the service instantiator functions
93 * defined in ServiceWiring.php.
95 * @note This should only be called by static functions! The instance returned here
96 * should not be passed around! Objects that need access to a service should have
97 * that service injected into the constructor, never a service locator!
99 * @return MediaWikiServices
101 public static function getInstance() {
102 if ( self
::$instance === null ) {
103 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
104 // but some information from the global scope has to be injected here,
105 // even if it's just a file name or database credentials to load
106 // configuration from.
107 $bootstrapConfig = new GlobalVarConfig();
108 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
111 return self
::$instance;
115 * Replaces the global MediaWikiServices instance.
119 * @note This is for use in PHPUnit tests only!
121 * @throws MWException if called outside of PHPUnit tests.
123 * @param MediaWikiServices $services The new MediaWikiServices object.
125 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
127 public static function forceGlobalInstance( MediaWikiServices
$services ) {
128 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
129 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
132 $old = self
::getInstance();
133 self
::$instance = $services;
139 * Creates a new instance of MediaWikiServices and sets it as the global default
140 * instance. getInstance() will return a different MediaWikiServices object
141 * after every call to resetGlobalInstance().
145 * @warning This should not be used during normal operation. It is intended for use
146 * when the configuration has changed significantly since bootstrap time, e.g.
147 * during the installation process or during testing.
149 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
150 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
151 * any of the services managed by MediaWikiServices exist. If any service objects
152 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
153 * with the operation of the services managed by the new MediaWikiServices.
154 * Operating with a mix of services created by the old and the new
155 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
156 * Any class implementing LAZY LOADING is especially prone to this problem,
157 * since instances would typically retain a reference to a storage layer service.
159 * @see forceGlobalInstance()
160 * @see resetGlobalInstance()
161 * @see resetBetweenTest()
163 * @param Config|null $bootstrapConfig The Config object to be registered as the
164 * 'BootstrapConfig' service. This has to contain at least the information
165 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
166 * config of the old instance of MediaWikiServices will be re-used. If there
167 * was no previous instance, a new GlobalVarConfig object will be used to
168 * bootstrap the services.
170 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
171 * See SalvageableService for details.
173 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
174 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
177 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
178 if ( self
::$instance === null ) {
179 // no global instance yet, nothing to reset
183 self
::failIfResetNotAllowed( __METHOD__
);
185 if ( $bootstrapConfig === null ) {
186 $bootstrapConfig = self
::$instance->getBootstrapConfig();
189 $oldInstance = self
::$instance;
191 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
192 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
194 if ( $quick === 'quick' ) {
195 self
::$instance->salvage( $oldInstance );
197 $oldInstance->destroy();
202 * Salvages the state of any salvageable service instances in $other.
204 * @note $other will have been destroyed when salvage() returns.
206 * @param MediaWikiServices $other
208 private function salvage( self
$other ) {
209 foreach ( $this->getServiceNames() as $name ) {
210 // The service could be new in the new instance and not registered in the
211 // other instance (e.g. an extension that was loaded after the instantiation of
212 // the other instance. Skip this service in this case. See T143974
214 $oldService = $other->peekService( $name );
215 } catch ( NoSuchServiceException
$e ) {
219 if ( $oldService instanceof SalvageableService
) {
220 /** @var SalvageableService $newService */
221 $newService = $this->getService( $name );
222 $newService->salvage( $oldService );
230 * Creates a new MediaWikiServices instance and initializes it according to the
231 * given $bootstrapConfig. In particular, all wiring files defined in the
232 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
234 * @param Config|null $bootstrapConfig The Config object to be registered as the
235 * 'BootstrapConfig' service.
237 * @param string $loadWiring set this to 'load' to load the wiring files specified
238 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
240 * @return MediaWikiServices
241 * @throws MWException
242 * @throws \FatalError
244 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
245 $instance = new self( $bootstrapConfig );
247 // Load the default wiring from the specified files.
248 if ( $loadWiring === 'load' ) {
249 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
250 $instance->loadWiringFiles( $wiringFiles );
253 // Provide a traditional hook point to allow extensions to configure services.
254 Hooks
::run( 'MediaWikiServices', [ $instance ] );
260 * Disables all storage layer services. After calling this, any attempt to access the
261 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
266 * @warning This is intended for extreme situations only and should never be used
267 * while serving normal web requests. Legitimate use cases for this method include
268 * the installation process. Test fixtures may also use this, if the fixture relies
271 * @see resetGlobalInstance()
272 * @see resetChildProcessServices()
274 public static function disableStorageBackend() {
275 // TODO: also disable some Caches, JobQueues, etc
276 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
277 $services = self
::getInstance();
279 foreach ( $destroy as $name ) {
280 $services->disableService( $name );
283 ObjectCache
::clear();
287 * Resets any services that may have become stale after a child process
288 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
289 * to call this method from the parent process.
293 * @note This is intended for use in the context of process forking only!
295 * @see resetGlobalInstance()
296 * @see disableStorageBackend()
298 public static function resetChildProcessServices() {
299 // NOTE: for now, just reset everything. Since we don't know the interdependencies
300 // between services, we can't do this more selectively at this time.
301 self
::resetGlobalInstance();
303 // Child, reseed because there is no bug in PHP:
304 // https://bugs.php.net/bug.php?id=42465
305 mt_srand( getmypid() );
309 * Resets the given service for testing purposes.
313 * @warning This is generally unsafe! Other services may still retain references
314 * to the stale service instance, leading to failures and inconsistencies. Subclasses
315 * may use this method to reset specific services under specific instances, but
316 * it should not be exposed to application logic.
318 * @note With proper dependency injection used throughout the codebase, this method
319 * should not be needed. It is provided to allow tests that pollute global service
320 * instances to clean up.
322 * @param string $name
323 * @param bool $destroy Whether the service instance should be destroyed if it exists.
324 * When set to false, any existing service instance will effectively be detached
325 * from the container.
327 * @throws MWException if called outside of PHPUnit tests.
329 public function resetServiceForTesting( $name, $destroy = true ) {
330 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
331 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
334 $this->resetService( $name, $destroy );
338 * Convenience method that throws an exception unless it is called during a phase in which
339 * resetting of global services is allowed. In general, services should not be reset
340 * individually, since that may introduce inconsistencies.
344 * This method will throw an exception if:
346 * - self::$resetInProgress is false (to allow all services to be reset together
347 * via resetGlobalInstance)
348 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
349 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
351 * This method is intended to be used to safeguard against accidentally resetting
352 * global service instances that are not yet managed by MediaWikiServices. It is
353 * defined here in the MediaWikiServices services class to have a central place
354 * for managing service bootstrapping and resetting.
356 * @param string $method the name of the caller method, as given by __METHOD__.
358 * @throws MWException if called outside bootstrap mode.
360 * @see resetGlobalInstance()
361 * @see forceGlobalInstance()
362 * @see disableStorageBackend()
364 public static function failIfResetNotAllowed( $method ) {
365 if ( !defined( 'MW_PHPUNIT_TEST' )
366 && !defined( 'MW_PARSER_TEST' )
367 && !defined( 'MEDIAWIKI_INSTALL' )
368 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
369 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
371 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
376 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
377 * This has to contain at least the information needed to set up the 'ConfigFactory'
380 public function __construct( Config
$config ) {
381 parent
::__construct();
383 // Register the given Config object as the bootstrap config service.
384 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
389 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
392 * Returns the Config object containing the bootstrap configuration.
393 * Bootstrap configuration would typically include database credentials
394 * and other information that may be needed before the ConfigFactory
395 * service can be instantiated.
397 * @note This should only be used during bootstrapping, in particular
398 * when creating the MainConfig service. Application logic should
399 * use getMainConfig() to get a Config instances.
404 public function getBootstrapConfig() {
405 return $this->getService( 'BootstrapConfig' );
410 * @return ConfigFactory
412 public function getConfigFactory() {
413 return $this->getService( 'ConfigFactory' );
417 * Returns the Config object that provides configuration for MediaWiki core.
418 * This may or may not be the same object that is returned by getBootstrapConfig().
423 public function getMainConfig() {
424 return $this->getService( 'MainConfig' );
431 public function getSiteLookup() {
432 return $this->getService( 'SiteLookup' );
439 public function getSiteStore() {
440 return $this->getService( 'SiteStore' );
445 * @return InterwikiLookup
447 public function getInterwikiLookup() {
448 return $this->getService( 'InterwikiLookup' );
453 * @return IBufferingStatsdDataFactory
455 public function getStatsdDataFactory() {
456 return $this->getService( 'StatsdDataFactory' );
461 * @return EventRelayerGroup
463 public function getEventRelayerGroup() {
464 return $this->getService( 'EventRelayerGroup' );
469 * @return SearchEngine
471 public function newSearchEngine() {
472 // New engine object every time, since they keep state
473 return $this->getService( 'SearchEngineFactory' )->create();
478 * @return SearchEngineFactory
480 public function getSearchEngineFactory() {
481 return $this->getService( 'SearchEngineFactory' );
486 * @return SearchEngineConfig
488 public function getSearchEngineConfig() {
489 return $this->getService( 'SearchEngineConfig' );
494 * @return SkinFactory
496 public function getSkinFactory() {
497 return $this->getService( 'SkinFactory' );
504 public function getDBLoadBalancerFactory() {
505 return $this->getService( 'DBLoadBalancerFactory' );
510 * @return LoadBalancer The main DB load balancer for the local wiki.
512 public function getDBLoadBalancer() {
513 return $this->getService( 'DBLoadBalancer' );
518 * @return WatchedItemStoreInterface
520 public function getWatchedItemStore() {
521 return $this->getService( 'WatchedItemStore' );
526 * @return WatchedItemQueryService
528 public function getWatchedItemQueryService() {
529 return $this->getService( 'WatchedItemQueryService' );
536 public function getCryptRand() {
537 return $this->getService( 'CryptRand' );
544 public function getCryptHKDF() {
545 return $this->getService( 'CryptHKDF' );
550 * @return MediaHandlerFactory
552 public function getMediaHandlerFactory() {
553 return $this->getService( 'MediaHandlerFactory' );
558 * @return MimeAnalyzer
560 public function getMimeAnalyzer() {
561 return $this->getService( 'MimeAnalyzer' );
566 * @return ProxyLookup
568 public function getProxyLookup() {
569 return $this->getService( 'ProxyLookup' );
576 public function getParser() {
577 return $this->getService( 'Parser' );
582 * @return ParserCache
584 public function getParserCache() {
585 return $this->getService( 'ParserCache' );
590 * @return GenderCache
592 public function getGenderCache() {
593 return $this->getService( 'GenderCache' );
600 public function getLinkCache() {
601 return $this->getService( 'LinkCache' );
606 * @return LinkRendererFactory
608 public function getLinkRendererFactory() {
609 return $this->getService( 'LinkRendererFactory' );
613 * LinkRenderer instance that can be used
614 * if no custom options are needed
617 * @return LinkRenderer
619 public function getLinkRenderer() {
620 return $this->getService( 'LinkRenderer' );
625 * @return TitleFormatter
627 public function getTitleFormatter() {
628 return $this->getService( 'TitleFormatter' );
633 * @return TitleParser
635 public function getTitleParser() {
636 return $this->getService( 'TitleParser' );
643 public function getMainObjectStash() {
644 return $this->getService( 'MainObjectStash' );
649 * @return \WANObjectCache
651 public function getMainWANObjectCache() {
652 return $this->getService( 'MainWANObjectCache' );
659 public function getLocalServerObjectCache() {
660 return $this->getService( 'LocalServerObjectCache' );
665 * @return VirtualRESTServiceClient
667 public function getVirtualRESTServiceClient() {
668 return $this->getService( 'VirtualRESTServiceClient' );
673 * @return \ConfiguredReadOnlyMode
675 public function getConfiguredReadOnlyMode() {
676 return $this->getService( 'ConfiguredReadOnlyMode' );
681 * @return \ReadOnlyMode
683 public function getReadOnlyMode() {
684 return $this->getService( 'ReadOnlyMode' );
689 * @return CommandFactory
691 public function getShellCommandFactory() {
692 return $this->getService( 'ShellCommandFactory' );
697 * @return \ExternalStoreFactory
699 public function getExternalStoreFactory() {
700 return $this->getService( 'ExternalStoreFactory' );
707 public function getBlobStore() {
708 return $this->getService( 'BlobStore' );
713 * @return RevisionStore
715 public function getRevisionStore() {
716 return $this->getService( 'RevisionStore' );
719 ///////////////////////////////////////////////////////////////////////////
720 // NOTE: When adding a service getter here, don't forget to add a test
721 // case for it in MediaWikiServicesTest::provideGetters() and in
722 // MediaWikiServicesTest::provideGetService()!
723 ///////////////////////////////////////////////////////////////////////////