12 use IBufferingStatsdDataFactory
;
13 use MediaWiki\Http\HttpRequestFactory
;
14 use MediaWiki\Preferences\PreferencesFactory
;
15 use MediaWiki\Shell\CommandFactory
;
16 use MediaWiki\Storage\BlobStore
;
17 use MediaWiki\Storage\BlobStoreFactory
;
18 use MediaWiki\Storage\RevisionFactory
;
19 use MediaWiki\Storage\RevisionLookup
;
20 use MediaWiki\Storage\RevisionStore
;
21 use Wikimedia\Rdbms\LBFactory
;
23 use Wikimedia\Rdbms\LoadBalancer
;
24 use MediaHandlerFactory
;
25 use MediaWiki\Linker\LinkRenderer
;
26 use MediaWiki\Linker\LinkRendererFactory
;
27 use MediaWiki\Services\SalvageableService
;
28 use MediaWiki\Services\ServiceContainer
;
29 use MediaWiki\Services\NoSuchServiceException
;
37 use SearchEngineConfig
;
38 use SearchEngineFactory
;
41 use WatchedItemStoreInterface
;
42 use WatchedItemQueryService
;
46 use VirtualRESTServiceClient
;
47 use MediaWiki\Interwiki\InterwikiLookup
;
50 * Service locator for MediaWiki core services.
52 * This program is free software; you can redistribute it and/or modify
53 * it under the terms of the GNU General Public License as published by
54 * the Free Software Foundation; either version 2 of the License, or
55 * (at your option) any later version.
57 * This program is distributed in the hope that it will be useful,
58 * but WITHOUT ANY WARRANTY; without even the implied warranty of
59 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
60 * GNU General Public License for more details.
62 * You should have received a copy of the GNU General Public License along
63 * with this program; if not, write to the Free Software Foundation, Inc.,
64 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
65 * http://www.gnu.org/copyleft/gpl.html
73 * MediaWikiServices is the service locator for the application scope of MediaWiki.
74 * Its implemented as a simple configurable DI container.
75 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
76 * the network of service objects that defines MediaWiki's application logic.
77 * It acts as an entry point to MediaWiki's dependency injection mechanism.
79 * Services are defined in the "wiring" array passed to the constructor,
80 * or by calling defineService().
82 * @see docs/injection.txt for an overview of using dependency injection in the
83 * MediaWiki code base.
85 class MediaWikiServices
extends ServiceContainer
{
88 * @var MediaWikiServices|null
90 private static $instance = null;
93 * Returns the global default instance of the top level service locator.
97 * The default instance is initialized using the service instantiator functions
98 * defined in ServiceWiring.php.
100 * @note This should only be called by static functions! The instance returned here
101 * should not be passed around! Objects that need access to a service should have
102 * that service injected into the constructor, never a service locator!
104 * @return MediaWikiServices
106 public static function getInstance() {
107 if ( self
::$instance === null ) {
108 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
109 // but some information from the global scope has to be injected here,
110 // even if it's just a file name or database credentials to load
111 // configuration from.
112 $bootstrapConfig = new GlobalVarConfig();
113 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
116 return self
::$instance;
120 * Replaces the global MediaWikiServices instance.
124 * @note This is for use in PHPUnit tests only!
126 * @throws MWException if called outside of PHPUnit tests.
128 * @param MediaWikiServices $services The new MediaWikiServices object.
130 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
132 public static function forceGlobalInstance( MediaWikiServices
$services ) {
133 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
134 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
137 $old = self
::getInstance();
138 self
::$instance = $services;
144 * Creates a new instance of MediaWikiServices and sets it as the global default
145 * instance. getInstance() will return a different MediaWikiServices object
146 * after every call to resetGlobalInstance().
150 * @warning This should not be used during normal operation. It is intended for use
151 * when the configuration has changed significantly since bootstrap time, e.g.
152 * during the installation process or during testing.
154 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
155 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
156 * any of the services managed by MediaWikiServices exist. If any service objects
157 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
158 * with the operation of the services managed by the new MediaWikiServices.
159 * Operating with a mix of services created by the old and the new
160 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
161 * Any class implementing LAZY LOADING is especially prone to this problem,
162 * since instances would typically retain a reference to a storage layer service.
164 * @see forceGlobalInstance()
165 * @see resetGlobalInstance()
166 * @see resetBetweenTest()
168 * @param Config|null $bootstrapConfig The Config object to be registered as the
169 * 'BootstrapConfig' service. This has to contain at least the information
170 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
171 * config of the old instance of MediaWikiServices will be re-used. If there
172 * was no previous instance, a new GlobalVarConfig object will be used to
173 * bootstrap the services.
175 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
176 * See SalvageableService for details.
178 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
179 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
182 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
183 if ( self
::$instance === null ) {
184 // no global instance yet, nothing to reset
188 self
::failIfResetNotAllowed( __METHOD__
);
190 if ( $bootstrapConfig === null ) {
191 $bootstrapConfig = self
::$instance->getBootstrapConfig();
194 $oldInstance = self
::$instance;
196 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
197 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
199 if ( $quick === 'quick' ) {
200 self
::$instance->salvage( $oldInstance );
202 $oldInstance->destroy();
207 * Salvages the state of any salvageable service instances in $other.
209 * @note $other will have been destroyed when salvage() returns.
211 * @param MediaWikiServices $other
213 private function salvage( self
$other ) {
214 foreach ( $this->getServiceNames() as $name ) {
215 // The service could be new in the new instance and not registered in the
216 // other instance (e.g. an extension that was loaded after the instantiation of
217 // the other instance. Skip this service in this case. See T143974
219 $oldService = $other->peekService( $name );
220 } catch ( NoSuchServiceException
$e ) {
224 if ( $oldService instanceof SalvageableService
) {
225 /** @var SalvageableService $newService */
226 $newService = $this->getService( $name );
227 $newService->salvage( $oldService );
235 * Creates a new MediaWikiServices instance and initializes it according to the
236 * given $bootstrapConfig. In particular, all wiring files defined in the
237 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
239 * @param Config|null $bootstrapConfig The Config object to be registered as the
240 * 'BootstrapConfig' service.
242 * @param string $loadWiring set this to 'load' to load the wiring files specified
243 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
245 * @return MediaWikiServices
246 * @throws MWException
247 * @throws \FatalError
249 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
250 $instance = new self( $bootstrapConfig );
252 // Load the default wiring from the specified files.
253 if ( $loadWiring === 'load' ) {
254 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
255 $instance->loadWiringFiles( $wiringFiles );
258 // Provide a traditional hook point to allow extensions to configure services.
259 Hooks
::run( 'MediaWikiServices', [ $instance ] );
265 * Disables all storage layer services. After calling this, any attempt to access the
266 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
271 * @warning This is intended for extreme situations only and should never be used
272 * while serving normal web requests. Legitimate use cases for this method include
273 * the installation process. Test fixtures may also use this, if the fixture relies
276 * @see resetGlobalInstance()
277 * @see resetChildProcessServices()
279 public static function disableStorageBackend() {
280 // TODO: also disable some Caches, JobQueues, etc
281 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
282 $services = self
::getInstance();
284 foreach ( $destroy as $name ) {
285 $services->disableService( $name );
288 ObjectCache
::clear();
292 * Resets any services that may have become stale after a child process
293 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
294 * to call this method from the parent process.
298 * @note This is intended for use in the context of process forking only!
300 * @see resetGlobalInstance()
301 * @see disableStorageBackend()
303 public static function resetChildProcessServices() {
304 // NOTE: for now, just reset everything. Since we don't know the interdependencies
305 // between services, we can't do this more selectively at this time.
306 self
::resetGlobalInstance();
308 // Child, reseed because there is no bug in PHP:
309 // https://bugs.php.net/bug.php?id=42465
310 mt_srand( getmypid() );
314 * Resets the given service for testing purposes.
318 * @warning This is generally unsafe! Other services may still retain references
319 * to the stale service instance, leading to failures and inconsistencies. Subclasses
320 * may use this method to reset specific services under specific instances, but
321 * it should not be exposed to application logic.
323 * @note With proper dependency injection used throughout the codebase, this method
324 * should not be needed. It is provided to allow tests that pollute global service
325 * instances to clean up.
327 * @param string $name
328 * @param bool $destroy Whether the service instance should be destroyed if it exists.
329 * When set to false, any existing service instance will effectively be detached
330 * from the container.
332 * @throws MWException if called outside of PHPUnit tests.
334 public function resetServiceForTesting( $name, $destroy = true ) {
335 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
336 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
339 $this->resetService( $name, $destroy );
343 * Convenience method that throws an exception unless it is called during a phase in which
344 * resetting of global services is allowed. In general, services should not be reset
345 * individually, since that may introduce inconsistencies.
349 * This method will throw an exception if:
351 * - self::$resetInProgress is false (to allow all services to be reset together
352 * via resetGlobalInstance)
353 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
354 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
356 * This method is intended to be used to safeguard against accidentally resetting
357 * global service instances that are not yet managed by MediaWikiServices. It is
358 * defined here in the MediaWikiServices services class to have a central place
359 * for managing service bootstrapping and resetting.
361 * @param string $method the name of the caller method, as given by __METHOD__.
363 * @throws MWException if called outside bootstrap mode.
365 * @see resetGlobalInstance()
366 * @see forceGlobalInstance()
367 * @see disableStorageBackend()
369 public static function failIfResetNotAllowed( $method ) {
370 if ( !defined( 'MW_PHPUNIT_TEST' )
371 && !defined( 'MW_PARSER_TEST' )
372 && !defined( 'MEDIAWIKI_INSTALL' )
373 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
374 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
376 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
381 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
382 * This has to contain at least the information needed to set up the 'ConfigFactory'
385 public function __construct( Config
$config ) {
386 parent
::__construct();
388 // Register the given Config object as the bootstrap config service.
389 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
394 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
397 * Returns the Config object containing the bootstrap configuration.
398 * Bootstrap configuration would typically include database credentials
399 * and other information that may be needed before the ConfigFactory
400 * service can be instantiated.
402 * @note This should only be used during bootstrapping, in particular
403 * when creating the MainConfig service. Application logic should
404 * use getMainConfig() to get a Config instances.
409 public function getBootstrapConfig() {
410 return $this->getService( 'BootstrapConfig' );
415 * @return ConfigFactory
417 public function getConfigFactory() {
418 return $this->getService( 'ConfigFactory' );
422 * Returns the Config object that provides configuration for MediaWiki core.
423 * This may or may not be the same object that is returned by getBootstrapConfig().
428 public function getMainConfig() {
429 return $this->getService( 'MainConfig' );
436 public function getSiteLookup() {
437 return $this->getService( 'SiteLookup' );
444 public function getSiteStore() {
445 return $this->getService( 'SiteStore' );
450 * @return InterwikiLookup
452 public function getInterwikiLookup() {
453 return $this->getService( 'InterwikiLookup' );
458 * @return IBufferingStatsdDataFactory
460 public function getStatsdDataFactory() {
461 return $this->getService( 'StatsdDataFactory' );
466 * @return EventRelayerGroup
468 public function getEventRelayerGroup() {
469 return $this->getService( 'EventRelayerGroup' );
474 * @return SearchEngine
476 public function newSearchEngine() {
477 // New engine object every time, since they keep state
478 return $this->getService( 'SearchEngineFactory' )->create();
483 * @return SearchEngineFactory
485 public function getSearchEngineFactory() {
486 return $this->getService( 'SearchEngineFactory' );
491 * @return SearchEngineConfig
493 public function getSearchEngineConfig() {
494 return $this->getService( 'SearchEngineConfig' );
499 * @return SkinFactory
501 public function getSkinFactory() {
502 return $this->getService( 'SkinFactory' );
509 public function getDBLoadBalancerFactory() {
510 return $this->getService( 'DBLoadBalancerFactory' );
515 * @return LoadBalancer The main DB load balancer for the local wiki.
517 public function getDBLoadBalancer() {
518 return $this->getService( 'DBLoadBalancer' );
523 * @return WatchedItemStoreInterface
525 public function getWatchedItemStore() {
526 return $this->getService( 'WatchedItemStore' );
531 * @return WatchedItemQueryService
533 public function getWatchedItemQueryService() {
534 return $this->getService( 'WatchedItemQueryService' );
541 public function getCryptRand() {
542 return $this->getService( 'CryptRand' );
549 public function getCryptHKDF() {
550 return $this->getService( 'CryptHKDF' );
555 * @return MediaHandlerFactory
557 public function getMediaHandlerFactory() {
558 return $this->getService( 'MediaHandlerFactory' );
563 * @return MimeAnalyzer
565 public function getMimeAnalyzer() {
566 return $this->getService( 'MimeAnalyzer' );
571 * @return ProxyLookup
573 public function getProxyLookup() {
574 return $this->getService( 'ProxyLookup' );
581 public function getParser() {
582 return $this->getService( 'Parser' );
587 * @return ParserCache
589 public function getParserCache() {
590 return $this->getService( 'ParserCache' );
595 * @return GenderCache
597 public function getGenderCache() {
598 return $this->getService( 'GenderCache' );
605 public function getLinkCache() {
606 return $this->getService( 'LinkCache' );
611 * @return LinkRendererFactory
613 public function getLinkRendererFactory() {
614 return $this->getService( 'LinkRendererFactory' );
618 * LinkRenderer instance that can be used
619 * if no custom options are needed
622 * @return LinkRenderer
624 public function getLinkRenderer() {
625 return $this->getService( 'LinkRenderer' );
630 * @return TitleFormatter
632 public function getTitleFormatter() {
633 return $this->getService( 'TitleFormatter' );
638 * @return TitleParser
640 public function getTitleParser() {
641 return $this->getService( 'TitleParser' );
648 public function getMainObjectStash() {
649 return $this->getService( 'MainObjectStash' );
654 * @return \WANObjectCache
656 public function getMainWANObjectCache() {
657 return $this->getService( 'MainWANObjectCache' );
664 public function getLocalServerObjectCache() {
665 return $this->getService( 'LocalServerObjectCache' );
670 * @return VirtualRESTServiceClient
672 public function getVirtualRESTServiceClient() {
673 return $this->getService( 'VirtualRESTServiceClient' );
678 * @return \ConfiguredReadOnlyMode
680 public function getConfiguredReadOnlyMode() {
681 return $this->getService( 'ConfiguredReadOnlyMode' );
686 * @return \ReadOnlyMode
688 public function getReadOnlyMode() {
689 return $this->getService( 'ReadOnlyMode' );
694 * @return CommandFactory
696 public function getShellCommandFactory() {
697 return $this->getService( 'ShellCommandFactory' );
702 * @return \ExternalStoreFactory
704 public function getExternalStoreFactory() {
705 return $this->getService( 'ExternalStoreFactory' );
710 * @return BlobStoreFactory
712 public function getBlobStoreFactory() {
713 return $this->getService( 'BlobStoreFactory' );
720 public function getBlobStore() {
721 return $this->getService( '_SqlBlobStore' );
726 * @return RevisionStore
728 public function getRevisionStore() {
729 return $this->getService( 'RevisionStore' );
734 * @return RevisionLookup
736 public function getRevisionLookup() {
737 return $this->getService( 'RevisionLookup' );
742 * @return RevisionFactory
744 public function getRevisionFactory() {
745 return $this->getService( 'RevisionFactory' );
750 * @return PreferencesFactory
752 public function getPreferencesFactory() {
753 return $this->getService( 'PreferencesFactory' );
758 * @return HttpRequestFactory
760 public function getHttpRequestFactory() {
761 return $this->getService( 'HttpRequestFactory' );
764 ///////////////////////////////////////////////////////////////////////////
765 // NOTE: When adding a service getter here, don't forget to add a test
766 // case for it in MediaWikiServicesTest::provideGetters() and in
767 // MediaWikiServicesTest::provideGetService()!
768 ///////////////////////////////////////////////////////////////////////////