10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use MediaWiki\Http\HttpRequestFactory
;
16 use MediaWiki\Preferences\PreferencesFactory
;
17 use MediaWiki\Shell\CommandFactory
;
18 use MediaWiki\Storage\BlobStore
;
19 use MediaWiki\Storage\BlobStoreFactory
;
20 use MediaWiki\Storage\NameTableStore
;
21 use MediaWiki\Storage\RevisionFactory
;
22 use MediaWiki\Storage\RevisionLookup
;
23 use MediaWiki\Storage\RevisionStore
;
24 use OldRevisionImporter
;
25 use UploadRevisionImporter
;
26 use Wikimedia\Rdbms\LBFactory
;
28 use Wikimedia\Rdbms\LoadBalancer
;
29 use MediaHandlerFactory
;
30 use MediaWiki\Config\ConfigRepository
;
31 use MediaWiki\Linker\LinkRenderer
;
32 use MediaWiki\Linker\LinkRendererFactory
;
33 use MediaWiki\Services\SalvageableService
;
34 use MediaWiki\Services\ServiceContainer
;
35 use MediaWiki\Services\NoSuchServiceException
;
44 use SearchEngineConfig
;
45 use SearchEngineFactory
;
48 use WatchedItemStoreInterface
;
49 use WatchedItemQueryService
;
53 use VirtualRESTServiceClient
;
54 use MediaWiki\Interwiki\InterwikiLookup
;
58 * Service locator for MediaWiki core services.
60 * This program is free software; you can redistribute it and/or modify
61 * it under the terms of the GNU General Public License as published by
62 * the Free Software Foundation; either version 2 of the License, or
63 * (at your option) any later version.
65 * This program is distributed in the hope that it will be useful,
66 * but WITHOUT ANY WARRANTY; without even the implied warranty of
67 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
68 * GNU General Public License for more details.
70 * You should have received a copy of the GNU General Public License along
71 * with this program; if not, write to the Free Software Foundation, Inc.,
72 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
73 * http://www.gnu.org/copyleft/gpl.html
81 * MediaWikiServices is the service locator for the application scope of MediaWiki.
82 * Its implemented as a simple configurable DI container.
83 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
84 * the network of service objects that defines MediaWiki's application logic.
85 * It acts as an entry point to MediaWiki's dependency injection mechanism.
87 * Services are defined in the "wiring" array passed to the constructor,
88 * or by calling defineService().
90 * @see docs/injection.txt for an overview of using dependency injection in the
91 * MediaWiki code base.
93 class MediaWikiServices
extends ServiceContainer
{
96 * @var MediaWikiServices|null
98 private static $instance = null;
101 * Returns the global default instance of the top level service locator.
105 * The default instance is initialized using the service instantiator functions
106 * defined in ServiceWiring.php.
108 * @note This should only be called by static functions! The instance returned here
109 * should not be passed around! Objects that need access to a service should have
110 * that service injected into the constructor, never a service locator!
112 * @return MediaWikiServices
114 public static function getInstance() {
115 if ( self
::$instance === null ) {
116 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
117 // but some information from the global scope has to be injected here,
118 // even if it's just a file name or database credentials to load
119 // configuration from.
120 $bootstrapConfig = new GlobalVarConfig();
121 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
124 return self
::$instance;
128 * Replaces the global MediaWikiServices instance.
132 * @note This is for use in PHPUnit tests only!
134 * @throws MWException if called outside of PHPUnit tests.
136 * @param MediaWikiServices $services The new MediaWikiServices object.
138 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
140 public static function forceGlobalInstance( MediaWikiServices
$services ) {
141 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
142 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
145 $old = self
::getInstance();
146 self
::$instance = $services;
152 * Creates a new instance of MediaWikiServices and sets it as the global default
153 * instance. getInstance() will return a different MediaWikiServices object
154 * after every call to resetGlobalInstance().
158 * @warning This should not be used during normal operation. It is intended for use
159 * when the configuration has changed significantly since bootstrap time, e.g.
160 * during the installation process or during testing.
162 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
163 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
164 * any of the services managed by MediaWikiServices exist. If any service objects
165 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
166 * with the operation of the services managed by the new MediaWikiServices.
167 * Operating with a mix of services created by the old and the new
168 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
169 * Any class implementing LAZY LOADING is especially prone to this problem,
170 * since instances would typically retain a reference to a storage layer service.
172 * @see forceGlobalInstance()
173 * @see resetGlobalInstance()
174 * @see resetBetweenTest()
176 * @param Config|null $bootstrapConfig The Config object to be registered as the
177 * 'BootstrapConfig' service. This has to contain at least the information
178 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
179 * config of the old instance of MediaWikiServices will be re-used. If there
180 * was no previous instance, a new GlobalVarConfig object will be used to
181 * bootstrap the services.
183 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
184 * See SalvageableService for details.
186 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
187 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
190 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
191 if ( self
::$instance === null ) {
192 // no global instance yet, nothing to reset
196 self
::failIfResetNotAllowed( __METHOD__
);
198 if ( $bootstrapConfig === null ) {
199 $bootstrapConfig = self
::$instance->getBootstrapConfig();
202 $oldInstance = self
::$instance;
204 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
205 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
207 if ( $quick === 'quick' ) {
208 self
::$instance->salvage( $oldInstance );
210 $oldInstance->destroy();
215 * Salvages the state of any salvageable service instances in $other.
217 * @note $other will have been destroyed when salvage() returns.
219 * @param MediaWikiServices $other
221 private function salvage( self
$other ) {
222 foreach ( $this->getServiceNames() as $name ) {
223 // The service could be new in the new instance and not registered in the
224 // other instance (e.g. an extension that was loaded after the instantiation of
225 // the other instance. Skip this service in this case. See T143974
227 $oldService = $other->peekService( $name );
228 } catch ( NoSuchServiceException
$e ) {
232 if ( $oldService instanceof SalvageableService
) {
233 /** @var SalvageableService $newService */
234 $newService = $this->getService( $name );
235 $newService->salvage( $oldService );
243 * Creates a new MediaWikiServices instance and initializes it according to the
244 * given $bootstrapConfig. In particular, all wiring files defined in the
245 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
247 * @param Config|null $bootstrapConfig The Config object to be registered as the
248 * 'BootstrapConfig' service.
250 * @param string $loadWiring set this to 'load' to load the wiring files specified
251 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
253 * @return MediaWikiServices
254 * @throws MWException
255 * @throws \FatalError
257 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
258 $instance = new self( $bootstrapConfig );
260 // Load the default wiring from the specified files.
261 if ( $loadWiring === 'load' ) {
262 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
263 $instance->loadWiringFiles( $wiringFiles );
266 // Provide a traditional hook point to allow extensions to configure services.
267 Hooks
::run( 'MediaWikiServices', [ $instance ] );
273 * Disables all storage layer services. After calling this, any attempt to access the
274 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
279 * @warning This is intended for extreme situations only and should never be used
280 * while serving normal web requests. Legitimate use cases for this method include
281 * the installation process. Test fixtures may also use this, if the fixture relies
284 * @see resetGlobalInstance()
285 * @see resetChildProcessServices()
287 public static function disableStorageBackend() {
288 // TODO: also disable some Caches, JobQueues, etc
289 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
290 $services = self
::getInstance();
292 foreach ( $destroy as $name ) {
293 $services->disableService( $name );
296 ObjectCache
::clear();
300 * Resets any services that may have become stale after a child process
301 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
302 * to call this method from the parent process.
306 * @note This is intended for use in the context of process forking only!
308 * @see resetGlobalInstance()
309 * @see disableStorageBackend()
311 public static function resetChildProcessServices() {
312 // NOTE: for now, just reset everything. Since we don't know the interdependencies
313 // between services, we can't do this more selectively at this time.
314 self
::resetGlobalInstance();
316 // Child, reseed because there is no bug in PHP:
317 // https://bugs.php.net/bug.php?id=42465
318 mt_srand( getmypid() );
322 * Resets the given service for testing purposes.
326 * @warning This is generally unsafe! Other services may still retain references
327 * to the stale service instance, leading to failures and inconsistencies. Subclasses
328 * may use this method to reset specific services under specific instances, but
329 * it should not be exposed to application logic.
331 * @note With proper dependency injection used throughout the codebase, this method
332 * should not be needed. It is provided to allow tests that pollute global service
333 * instances to clean up.
335 * @param string $name
336 * @param bool $destroy Whether the service instance should be destroyed if it exists.
337 * When set to false, any existing service instance will effectively be detached
338 * from the container.
340 * @throws MWException if called outside of PHPUnit tests.
342 public function resetServiceForTesting( $name, $destroy = true ) {
343 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
344 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
347 $this->resetService( $name, $destroy );
351 * Convenience method that throws an exception unless it is called during a phase in which
352 * resetting of global services is allowed. In general, services should not be reset
353 * individually, since that may introduce inconsistencies.
357 * This method will throw an exception if:
359 * - self::$resetInProgress is false (to allow all services to be reset together
360 * via resetGlobalInstance)
361 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
362 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
364 * This method is intended to be used to safeguard against accidentally resetting
365 * global service instances that are not yet managed by MediaWikiServices. It is
366 * defined here in the MediaWikiServices services class to have a central place
367 * for managing service bootstrapping and resetting.
369 * @param string $method the name of the caller method, as given by __METHOD__.
371 * @throws MWException if called outside bootstrap mode.
373 * @see resetGlobalInstance()
374 * @see forceGlobalInstance()
375 * @see disableStorageBackend()
377 public static function failIfResetNotAllowed( $method ) {
378 if ( !defined( 'MW_PHPUNIT_TEST' )
379 && !defined( 'MW_PARSER_TEST' )
380 && !defined( 'MEDIAWIKI_INSTALL' )
381 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
382 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
384 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
389 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
390 * This has to contain at least the information needed to set up the 'ConfigFactory'
393 public function __construct( Config
$config ) {
394 parent
::__construct();
396 // Register the given Config object as the bootstrap config service.
397 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
402 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
405 * Returns the Config object containing the bootstrap configuration.
406 * Bootstrap configuration would typically include database credentials
407 * and other information that may be needed before the ConfigFactory
408 * service can be instantiated.
410 * @note This should only be used during bootstrapping, in particular
411 * when creating the MainConfig service. Application logic should
412 * use getMainConfig() to get a Config instances.
417 public function getBootstrapConfig() {
418 return $this->getService( 'BootstrapConfig' );
423 * @return ConfigFactory
425 public function getConfigFactory() {
426 return $this->getService( 'ConfigFactory' );
430 * Returns the Config object that provides configuration for MediaWiki core.
431 * This may or may not be the same object that is returned by getBootstrapConfig().
436 public function getMainConfig() {
437 return $this->getService( 'MainConfig' );
444 public function getSiteLookup() {
445 return $this->getService( 'SiteLookup' );
452 public function getSiteStore() {
453 return $this->getService( 'SiteStore' );
458 * @return InterwikiLookup
460 public function getInterwikiLookup() {
461 return $this->getService( 'InterwikiLookup' );
466 * @return IBufferingStatsdDataFactory
468 public function getStatsdDataFactory() {
469 return $this->getService( 'StatsdDataFactory' );
474 * @return IBufferingStatsdDataFactory
476 public function getPerDbNameStatsdDataFactory() {
477 return $this->getService( 'PerDbNameStatsdDataFactory' );
482 * @return EventRelayerGroup
484 public function getEventRelayerGroup() {
485 return $this->getService( 'EventRelayerGroup' );
490 * @return SearchEngine
492 public function newSearchEngine() {
493 // New engine object every time, since they keep state
494 return $this->getService( 'SearchEngineFactory' )->create();
499 * @return SearchEngineFactory
501 public function getSearchEngineFactory() {
502 return $this->getService( 'SearchEngineFactory' );
507 * @return SearchEngineConfig
509 public function getSearchEngineConfig() {
510 return $this->getService( 'SearchEngineConfig' );
515 * @return SkinFactory
517 public function getSkinFactory() {
518 return $this->getService( 'SkinFactory' );
525 public function getDBLoadBalancerFactory() {
526 return $this->getService( 'DBLoadBalancerFactory' );
531 * @return LoadBalancer The main DB load balancer for the local wiki.
533 public function getDBLoadBalancer() {
534 return $this->getService( 'DBLoadBalancer' );
539 * @return WatchedItemStoreInterface
541 public function getWatchedItemStore() {
542 return $this->getService( 'WatchedItemStore' );
547 * @return WatchedItemQueryService
549 public function getWatchedItemQueryService() {
550 return $this->getService( 'WatchedItemQueryService' );
555 * @deprecated since 1.32, use random_bytes()/random_int()
558 public function getCryptRand() {
559 return $this->getService( 'CryptRand' );
566 public function getCryptHKDF() {
567 return $this->getService( 'CryptHKDF' );
572 * @return MediaHandlerFactory
574 public function getMediaHandlerFactory() {
575 return $this->getService( 'MediaHandlerFactory' );
580 * @return MimeAnalyzer
582 public function getMimeAnalyzer() {
583 return $this->getService( 'MimeAnalyzer' );
588 * @return ProxyLookup
590 public function getProxyLookup() {
591 return $this->getService( 'ProxyLookup' );
598 public function getParser() {
599 return $this->getService( 'Parser' );
604 * @return ParserCache
606 public function getParserCache() {
607 return $this->getService( 'ParserCache' );
612 * @return GenderCache
614 public function getGenderCache() {
615 return $this->getService( 'GenderCache' );
622 public function getLinkCache() {
623 return $this->getService( 'LinkCache' );
628 * @return LinkRendererFactory
630 public function getLinkRendererFactory() {
631 return $this->getService( 'LinkRendererFactory' );
635 * LinkRenderer instance that can be used
636 * if no custom options are needed
639 * @return LinkRenderer
641 public function getLinkRenderer() {
642 return $this->getService( 'LinkRenderer' );
647 * @return TitleFormatter
649 public function getTitleFormatter() {
650 return $this->getService( 'TitleFormatter' );
655 * @return TitleParser
657 public function getTitleParser() {
658 return $this->getService( 'TitleParser' );
665 public function getMainObjectStash() {
666 return $this->getService( 'MainObjectStash' );
671 * @return \WANObjectCache
673 public function getMainWANObjectCache() {
674 return $this->getService( 'MainWANObjectCache' );
681 public function getLocalServerObjectCache() {
682 return $this->getService( 'LocalServerObjectCache' );
687 * @return VirtualRESTServiceClient
689 public function getVirtualRESTServiceClient() {
690 return $this->getService( 'VirtualRESTServiceClient' );
695 * @return \ConfiguredReadOnlyMode
697 public function getConfiguredReadOnlyMode() {
698 return $this->getService( 'ConfiguredReadOnlyMode' );
703 * @return \ReadOnlyMode
705 public function getReadOnlyMode() {
706 return $this->getService( 'ReadOnlyMode' );
711 * @return \UploadRevisionImporter
713 public function getWikiRevisionUploadImporter() {
714 return $this->getService( 'UploadRevisionImporter' );
719 * @return \OldRevisionImporter
721 public function getWikiRevisionOldRevisionImporter() {
722 return $this->getService( 'OldRevisionImporter' );
727 * @return \OldRevisionImporter
729 public function getWikiRevisionOldRevisionImporterNoUpdates() {
730 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
735 * @return CommandFactory
737 public function getShellCommandFactory() {
738 return $this->getService( 'ShellCommandFactory' );
743 * @return \ExternalStoreFactory
745 public function getExternalStoreFactory() {
746 return $this->getService( 'ExternalStoreFactory' );
751 * @return BlobStoreFactory
753 public function getBlobStoreFactory() {
754 return $this->getService( 'BlobStoreFactory' );
761 public function getBlobStore() {
762 return $this->getService( '_SqlBlobStore' );
767 * @return RevisionStore
769 public function getRevisionStore() {
770 return $this->getService( 'RevisionStore' );
775 * @return RevisionLookup
777 public function getRevisionLookup() {
778 return $this->getService( 'RevisionLookup' );
783 * @return RevisionFactory
785 public function getRevisionFactory() {
786 return $this->getService( 'RevisionFactory' );
791 * @return NameTableStore
793 public function getContentModelStore() {
794 return $this->getService( 'ContentModelStore' );
799 * @return NameTableStore
801 public function getSlotRoleStore() {
802 return $this->getService( 'SlotRoleStore' );
807 * @return NameTableStore
809 public function getChangeTagDefStore() {
810 return $this->getService( 'ChangeTagDefStore' );
815 * @return PreferencesFactory
817 public function getPreferencesFactory() {
818 return $this->getService( 'PreferencesFactory' );
823 * @return HttpRequestFactory
825 public function getHttpRequestFactory() {
826 return $this->getService( 'HttpRequestFactory' );
831 * @return CommentStore
833 public function getCommentStore() {
834 return $this->getService( 'CommentStore' );
839 * @return ActorMigration
841 public function getActorMigration() {
842 return $this->getService( 'ActorMigration' );
847 * @return UploadRevisionImporter
849 public function getUploadRevisionImporter() {
850 return $this->getService( 'UploadRevisionImporter' );
855 * @return OldRevisionImporter
857 public function getOldRevisionImporter() {
858 return $this->getService( 'OldRevisionImporter' );
863 * @return ConfigRepository
865 public function getConfigRepository() {
866 return $this->getService( 'ConfigRepository' );
871 * @return MagicWordFactory
873 public function getMagicWordFactory() {
874 return $this->getService( 'MagicWordFactory' );
881 public function getContentLanguage() {
882 return $this->getService( 'ContentLanguage' );
887 * @return PasswordFactory
889 public function getPasswordFactory() {
890 return $this->getService( 'PasswordFactory' );
893 ///////////////////////////////////////////////////////////////////////////
894 // NOTE: When adding a service getter here, don't forget to add a test
895 // case for it in MediaWikiServicesTest::provideGetters() and in
896 // MediaWikiServicesTest::provideGetService()!
897 ///////////////////////////////////////////////////////////////////////////