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 MediaWiki\Storage\RevisionStoreFactory
;
26 use UploadRevisionImporter
;
27 use Wikimedia\Rdbms\LBFactory
;
29 use Wikimedia\Rdbms\LoadBalancer
;
30 use MediaHandlerFactory
;
31 use MediaWiki\Config\ConfigRepository
;
32 use MediaWiki\Linker\LinkRenderer
;
33 use MediaWiki\Linker\LinkRendererFactory
;
34 use MediaWiki\Services\SalvageableService
;
35 use MediaWiki\Services\ServiceContainer
;
36 use MediaWiki\Services\NoSuchServiceException
;
45 use SearchEngineConfig
;
46 use SearchEngineFactory
;
49 use WatchedItemStoreInterface
;
50 use WatchedItemQueryService
;
54 use VirtualRESTServiceClient
;
55 use MediaWiki\Interwiki\InterwikiLookup
;
59 * Service locator for MediaWiki core services.
61 * This program is free software; you can redistribute it and/or modify
62 * it under the terms of the GNU General Public License as published by
63 * the Free Software Foundation; either version 2 of the License, or
64 * (at your option) any later version.
66 * This program is distributed in the hope that it will be useful,
67 * but WITHOUT ANY WARRANTY; without even the implied warranty of
68 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 * GNU General Public License for more details.
71 * You should have received a copy of the GNU General Public License along
72 * with this program; if not, write to the Free Software Foundation, Inc.,
73 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
74 * http://www.gnu.org/copyleft/gpl.html
82 * MediaWikiServices is the service locator for the application scope of MediaWiki.
83 * Its implemented as a simple configurable DI container.
84 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
85 * the network of service objects that defines MediaWiki's application logic.
86 * It acts as an entry point to MediaWiki's dependency injection mechanism.
88 * Services are defined in the "wiring" array passed to the constructor,
89 * or by calling defineService().
91 * @see docs/injection.txt for an overview of using dependency injection in the
92 * MediaWiki code base.
94 class MediaWikiServices
extends ServiceContainer
{
97 * @var MediaWikiServices|null
99 private static $instance = null;
102 * Returns the global default instance of the top level service locator.
106 * The default instance is initialized using the service instantiator functions
107 * defined in ServiceWiring.php.
109 * @note This should only be called by static functions! The instance returned here
110 * should not be passed around! Objects that need access to a service should have
111 * that service injected into the constructor, never a service locator!
113 * @return MediaWikiServices
115 public static function getInstance() {
116 if ( self
::$instance === null ) {
117 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
118 // but some information from the global scope has to be injected here,
119 // even if it's just a file name or database credentials to load
120 // configuration from.
121 $bootstrapConfig = new GlobalVarConfig();
122 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
125 return self
::$instance;
129 * Replaces the global MediaWikiServices instance.
133 * @note This is for use in PHPUnit tests only!
135 * @throws MWException if called outside of PHPUnit tests.
137 * @param MediaWikiServices $services The new MediaWikiServices object.
139 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
141 public static function forceGlobalInstance( MediaWikiServices
$services ) {
142 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
143 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
146 $old = self
::getInstance();
147 self
::$instance = $services;
153 * Creates a new instance of MediaWikiServices and sets it as the global default
154 * instance. getInstance() will return a different MediaWikiServices object
155 * after every call to resetGlobalInstance().
159 * @warning This should not be used during normal operation. It is intended for use
160 * when the configuration has changed significantly since bootstrap time, e.g.
161 * during the installation process or during testing.
163 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
164 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
165 * any of the services managed by MediaWikiServices exist. If any service objects
166 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
167 * with the operation of the services managed by the new MediaWikiServices.
168 * Operating with a mix of services created by the old and the new
169 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
170 * Any class implementing LAZY LOADING is especially prone to this problem,
171 * since instances would typically retain a reference to a storage layer service.
173 * @see forceGlobalInstance()
174 * @see resetGlobalInstance()
175 * @see resetBetweenTest()
177 * @param Config|null $bootstrapConfig The Config object to be registered as the
178 * 'BootstrapConfig' service. This has to contain at least the information
179 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
180 * config of the old instance of MediaWikiServices will be re-used. If there
181 * was no previous instance, a new GlobalVarConfig object will be used to
182 * bootstrap the services.
184 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
185 * See SalvageableService for details.
187 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
188 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
191 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
192 if ( self
::$instance === null ) {
193 // no global instance yet, nothing to reset
197 self
::failIfResetNotAllowed( __METHOD__
);
199 if ( $bootstrapConfig === null ) {
200 $bootstrapConfig = self
::$instance->getBootstrapConfig();
203 $oldInstance = self
::$instance;
205 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
206 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
208 if ( $quick === 'quick' ) {
209 self
::$instance->salvage( $oldInstance );
211 $oldInstance->destroy();
216 * Salvages the state of any salvageable service instances in $other.
218 * @note $other will have been destroyed when salvage() returns.
220 * @param MediaWikiServices $other
222 private function salvage( self
$other ) {
223 foreach ( $this->getServiceNames() as $name ) {
224 // The service could be new in the new instance and not registered in the
225 // other instance (e.g. an extension that was loaded after the instantiation of
226 // the other instance. Skip this service in this case. See T143974
228 $oldService = $other->peekService( $name );
229 } catch ( NoSuchServiceException
$e ) {
233 if ( $oldService instanceof SalvageableService
) {
234 /** @var SalvageableService $newService */
235 $newService = $this->getService( $name );
236 $newService->salvage( $oldService );
244 * Creates a new MediaWikiServices instance and initializes it according to the
245 * given $bootstrapConfig. In particular, all wiring files defined in the
246 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
248 * @param Config|null $bootstrapConfig The Config object to be registered as the
249 * 'BootstrapConfig' service.
251 * @param string $loadWiring set this to 'load' to load the wiring files specified
252 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
254 * @return MediaWikiServices
255 * @throws MWException
256 * @throws \FatalError
258 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
259 $instance = new self( $bootstrapConfig );
261 // Load the default wiring from the specified files.
262 if ( $loadWiring === 'load' ) {
263 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
264 $instance->loadWiringFiles( $wiringFiles );
267 // Provide a traditional hook point to allow extensions to configure services.
268 Hooks
::run( 'MediaWikiServices', [ $instance ] );
274 * Disables all storage layer services. After calling this, any attempt to access the
275 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
280 * @warning This is intended for extreme situations only and should never be used
281 * while serving normal web requests. Legitimate use cases for this method include
282 * the installation process. Test fixtures may also use this, if the fixture relies
285 * @see resetGlobalInstance()
286 * @see resetChildProcessServices()
288 public static function disableStorageBackend() {
289 // TODO: also disable some Caches, JobQueues, etc
290 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
291 $services = self
::getInstance();
293 foreach ( $destroy as $name ) {
294 $services->disableService( $name );
297 ObjectCache
::clear();
301 * Resets any services that may have become stale after a child process
302 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
303 * to call this method from the parent process.
307 * @note This is intended for use in the context of process forking only!
309 * @see resetGlobalInstance()
310 * @see disableStorageBackend()
312 public static function resetChildProcessServices() {
313 // NOTE: for now, just reset everything. Since we don't know the interdependencies
314 // between services, we can't do this more selectively at this time.
315 self
::resetGlobalInstance();
317 // Child, reseed because there is no bug in PHP:
318 // https://bugs.php.net/bug.php?id=42465
319 mt_srand( getmypid() );
323 * Resets the given service for testing purposes.
327 * @warning This is generally unsafe! Other services may still retain references
328 * to the stale service instance, leading to failures and inconsistencies. Subclasses
329 * may use this method to reset specific services under specific instances, but
330 * it should not be exposed to application logic.
332 * @note With proper dependency injection used throughout the codebase, this method
333 * should not be needed. It is provided to allow tests that pollute global service
334 * instances to clean up.
336 * @param string $name
337 * @param bool $destroy Whether the service instance should be destroyed if it exists.
338 * When set to false, any existing service instance will effectively be detached
339 * from the container.
341 * @throws MWException if called outside of PHPUnit tests.
343 public function resetServiceForTesting( $name, $destroy = true ) {
344 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
345 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
348 $this->resetService( $name, $destroy );
352 * Convenience method that throws an exception unless it is called during a phase in which
353 * resetting of global services is allowed. In general, services should not be reset
354 * individually, since that may introduce inconsistencies.
358 * This method will throw an exception if:
360 * - self::$resetInProgress is false (to allow all services to be reset together
361 * via resetGlobalInstance)
362 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
363 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
365 * This method is intended to be used to safeguard against accidentally resetting
366 * global service instances that are not yet managed by MediaWikiServices. It is
367 * defined here in the MediaWikiServices services class to have a central place
368 * for managing service bootstrapping and resetting.
370 * @param string $method the name of the caller method, as given by __METHOD__.
372 * @throws MWException if called outside bootstrap mode.
374 * @see resetGlobalInstance()
375 * @see forceGlobalInstance()
376 * @see disableStorageBackend()
378 public static function failIfResetNotAllowed( $method ) {
379 if ( !defined( 'MW_PHPUNIT_TEST' )
380 && !defined( 'MW_PARSER_TEST' )
381 && !defined( 'MEDIAWIKI_INSTALL' )
382 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
383 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
385 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
390 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
391 * This has to contain at least the information needed to set up the 'ConfigFactory'
394 public function __construct( Config
$config ) {
395 parent
::__construct();
397 // Register the given Config object as the bootstrap config service.
398 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
403 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
407 * @return ActorMigration
409 public function getActorMigration() {
410 return $this->getService( 'ActorMigration' );
417 public function getBlobStore() {
418 return $this->getService( '_SqlBlobStore' );
423 * @return BlobStoreFactory
425 public function getBlobStoreFactory() {
426 return $this->getService( 'BlobStoreFactory' );
430 * Returns the Config object containing the bootstrap configuration.
431 * Bootstrap configuration would typically include database credentials
432 * and other information that may be needed before the ConfigFactory
433 * service can be instantiated.
435 * @note This should only be used during bootstrapping, in particular
436 * when creating the MainConfig service. Application logic should
437 * use getMainConfig() to get a Config instances.
442 public function getBootstrapConfig() {
443 return $this->getService( 'BootstrapConfig' );
448 * @return NameTableStore
450 public function getChangeTagDefStore() {
451 return $this->getService( 'ChangeTagDefStore' );
456 * @return CommentStore
458 public function getCommentStore() {
459 return $this->getService( 'CommentStore' );
464 * @return ConfigFactory
466 public function getConfigFactory() {
467 return $this->getService( 'ConfigFactory' );
472 * @return ConfigRepository
474 public function getConfigRepository() {
475 return $this->getService( 'ConfigRepository' );
480 * @return \ConfiguredReadOnlyMode
482 public function getConfiguredReadOnlyMode() {
483 return $this->getService( 'ConfiguredReadOnlyMode' );
490 public function getContentLanguage() {
491 return $this->getService( 'ContentLanguage' );
496 * @return NameTableStore
498 public function getContentModelStore() {
499 return $this->getService( 'ContentModelStore' );
506 public function getCryptHKDF() {
507 return $this->getService( 'CryptHKDF' );
512 * @deprecated since 1.32, use random_bytes()/random_int()
515 public function getCryptRand() {
516 return $this->getService( 'CryptRand' );
521 * @return LoadBalancer The main DB load balancer for the local wiki.
523 public function getDBLoadBalancer() {
524 return $this->getService( 'DBLoadBalancer' );
531 public function getDBLoadBalancerFactory() {
532 return $this->getService( 'DBLoadBalancerFactory' );
537 * @return EventRelayerGroup
539 public function getEventRelayerGroup() {
540 return $this->getService( 'EventRelayerGroup' );
545 * @return \ExternalStoreFactory
547 public function getExternalStoreFactory() {
548 return $this->getService( 'ExternalStoreFactory' );
553 * @return GenderCache
555 public function getGenderCache() {
556 return $this->getService( 'GenderCache' );
561 * @return HttpRequestFactory
563 public function getHttpRequestFactory() {
564 return $this->getService( 'HttpRequestFactory' );
569 * @return InterwikiLookup
571 public function getInterwikiLookup() {
572 return $this->getService( 'InterwikiLookup' );
579 public function getLinkCache() {
580 return $this->getService( 'LinkCache' );
584 * LinkRenderer instance that can be used
585 * if no custom options are needed
588 * @return LinkRenderer
590 public function getLinkRenderer() {
591 return $this->getService( 'LinkRenderer' );
596 * @return LinkRendererFactory
598 public function getLinkRendererFactory() {
599 return $this->getService( 'LinkRendererFactory' );
606 public function getLocalServerObjectCache() {
607 return $this->getService( 'LocalServerObjectCache' );
612 * @return MagicWordFactory
614 public function getMagicWordFactory() {
615 return $this->getService( 'MagicWordFactory' );
619 * Returns the Config object that provides configuration for MediaWiki core.
620 * This may or may not be the same object that is returned by getBootstrapConfig().
625 public function getMainConfig() {
626 return $this->getService( 'MainConfig' );
633 public function getMainObjectStash() {
634 return $this->getService( 'MainObjectStash' );
639 * @return \WANObjectCache
641 public function getMainWANObjectCache() {
642 return $this->getService( 'MainWANObjectCache' );
647 * @return MediaHandlerFactory
649 public function getMediaHandlerFactory() {
650 return $this->getService( 'MediaHandlerFactory' );
655 * @return MimeAnalyzer
657 public function getMimeAnalyzer() {
658 return $this->getService( 'MimeAnalyzer' );
663 * @return OldRevisionImporter
665 public function getOldRevisionImporter() {
666 return $this->getService( 'OldRevisionImporter' );
673 public function getParser() {
674 return $this->getService( 'Parser' );
679 * @return ParserCache
681 public function getParserCache() {
682 return $this->getService( 'ParserCache' );
687 * @return PasswordFactory
689 public function getPasswordFactory() {
690 return $this->getService( 'PasswordFactory' );
695 * @return IBufferingStatsdDataFactory
697 public function getPerDbNameStatsdDataFactory() {
698 return $this->getService( 'PerDbNameStatsdDataFactory' );
703 * @return PreferencesFactory
705 public function getPreferencesFactory() {
706 return $this->getService( 'PreferencesFactory' );
711 * @return ProxyLookup
713 public function getProxyLookup() {
714 return $this->getService( 'ProxyLookup' );
719 * @return \ReadOnlyMode
721 public function getReadOnlyMode() {
722 return $this->getService( 'ReadOnlyMode' );
727 * @return RevisionFactory
729 public function getRevisionFactory() {
730 return $this->getService( 'RevisionFactory' );
735 * @return RevisionLookup
737 public function getRevisionLookup() {
738 return $this->getService( 'RevisionLookup' );
743 * @return RevisionStore
745 public function getRevisionStore() {
746 return $this->getService( 'RevisionStore' );
751 * @return RevisionStoreFactory
753 public function getRevisionStoreFactory() {
754 return $this->getService( 'RevisionStoreFactory' );
759 * @return SearchEngine
761 public function newSearchEngine() {
762 // New engine object every time, since they keep state
763 return $this->getService( 'SearchEngineFactory' )->create();
768 * @return SearchEngineConfig
770 public function getSearchEngineConfig() {
771 return $this->getService( 'SearchEngineConfig' );
776 * @return SearchEngineFactory
778 public function getSearchEngineFactory() {
779 return $this->getService( 'SearchEngineFactory' );
784 * @return CommandFactory
786 public function getShellCommandFactory() {
787 return $this->getService( 'ShellCommandFactory' );
794 public function getSiteLookup() {
795 return $this->getService( 'SiteLookup' );
802 public function getSiteStore() {
803 return $this->getService( 'SiteStore' );
808 * @return SkinFactory
810 public function getSkinFactory() {
811 return $this->getService( 'SkinFactory' );
816 * @return NameTableStore
818 public function getSlotRoleStore() {
819 return $this->getService( 'SlotRoleStore' );
824 * @return IBufferingStatsdDataFactory
826 public function getStatsdDataFactory() {
827 return $this->getService( 'StatsdDataFactory' );
832 * @return TitleFormatter
834 public function getTitleFormatter() {
835 return $this->getService( 'TitleFormatter' );
840 * @return TitleParser
842 public function getTitleParser() {
843 return $this->getService( 'TitleParser' );
848 * @return UploadRevisionImporter
850 public function getUploadRevisionImporter() {
851 return $this->getService( 'UploadRevisionImporter' );
856 * @return VirtualRESTServiceClient
858 public function getVirtualRESTServiceClient() {
859 return $this->getService( 'VirtualRESTServiceClient' );
864 * @return WatchedItemQueryService
866 public function getWatchedItemQueryService() {
867 return $this->getService( 'WatchedItemQueryService' );
872 * @return WatchedItemStoreInterface
874 public function getWatchedItemStore() {
875 return $this->getService( 'WatchedItemStore' );
880 * @return \OldRevisionImporter
882 public function getWikiRevisionOldRevisionImporter() {
883 return $this->getService( 'OldRevisionImporter' );
888 * @return \OldRevisionImporter
890 public function getWikiRevisionOldRevisionImporterNoUpdates() {
891 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
896 * @return \UploadRevisionImporter
898 public function getWikiRevisionUploadImporter() {
899 return $this->getService( 'UploadRevisionImporter' );
902 ///////////////////////////////////////////////////////////////////////////
903 // NOTE: When adding a service getter here, don't forget to add a test
904 // case for it in MediaWikiServicesTest::provideGetters() and in
905 // MediaWikiServicesTest::provideGetService()!
906 ///////////////////////////////////////////////////////////////////////////