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 ////////////////////////////////////////////////////
406 * Returns the Config object containing the bootstrap configuration.
407 * Bootstrap configuration would typically include database credentials
408 * and other information that may be needed before the ConfigFactory
409 * service can be instantiated.
411 * @note This should only be used during bootstrapping, in particular
412 * when creating the MainConfig service. Application logic should
413 * use getMainConfig() to get a Config instances.
418 public function getBootstrapConfig() {
419 return $this->getService( 'BootstrapConfig' );
424 * @return ConfigFactory
426 public function getConfigFactory() {
427 return $this->getService( 'ConfigFactory' );
431 * Returns the Config object that provides configuration for MediaWiki core.
432 * This may or may not be the same object that is returned by getBootstrapConfig().
437 public function getMainConfig() {
438 return $this->getService( 'MainConfig' );
445 public function getSiteLookup() {
446 return $this->getService( 'SiteLookup' );
453 public function getSiteStore() {
454 return $this->getService( 'SiteStore' );
459 * @return InterwikiLookup
461 public function getInterwikiLookup() {
462 return $this->getService( 'InterwikiLookup' );
467 * @return IBufferingStatsdDataFactory
469 public function getStatsdDataFactory() {
470 return $this->getService( 'StatsdDataFactory' );
475 * @return IBufferingStatsdDataFactory
477 public function getPerDbNameStatsdDataFactory() {
478 return $this->getService( 'PerDbNameStatsdDataFactory' );
483 * @return EventRelayerGroup
485 public function getEventRelayerGroup() {
486 return $this->getService( 'EventRelayerGroup' );
491 * @return SearchEngine
493 public function newSearchEngine() {
494 // New engine object every time, since they keep state
495 return $this->getService( 'SearchEngineFactory' )->create();
500 * @return SearchEngineFactory
502 public function getSearchEngineFactory() {
503 return $this->getService( 'SearchEngineFactory' );
508 * @return SearchEngineConfig
510 public function getSearchEngineConfig() {
511 return $this->getService( 'SearchEngineConfig' );
516 * @return SkinFactory
518 public function getSkinFactory() {
519 return $this->getService( 'SkinFactory' );
526 public function getDBLoadBalancerFactory() {
527 return $this->getService( 'DBLoadBalancerFactory' );
532 * @return LoadBalancer The main DB load balancer for the local wiki.
534 public function getDBLoadBalancer() {
535 return $this->getService( 'DBLoadBalancer' );
540 * @return WatchedItemStoreInterface
542 public function getWatchedItemStore() {
543 return $this->getService( 'WatchedItemStore' );
548 * @return WatchedItemQueryService
550 public function getWatchedItemQueryService() {
551 return $this->getService( 'WatchedItemQueryService' );
556 * @deprecated since 1.32, use random_bytes()/random_int()
559 public function getCryptRand() {
560 return $this->getService( 'CryptRand' );
567 public function getCryptHKDF() {
568 return $this->getService( 'CryptHKDF' );
573 * @return MediaHandlerFactory
575 public function getMediaHandlerFactory() {
576 return $this->getService( 'MediaHandlerFactory' );
581 * @return MimeAnalyzer
583 public function getMimeAnalyzer() {
584 return $this->getService( 'MimeAnalyzer' );
589 * @return ProxyLookup
591 public function getProxyLookup() {
592 return $this->getService( 'ProxyLookup' );
599 public function getParser() {
600 return $this->getService( 'Parser' );
605 * @return ParserCache
607 public function getParserCache() {
608 return $this->getService( 'ParserCache' );
613 * @return GenderCache
615 public function getGenderCache() {
616 return $this->getService( 'GenderCache' );
623 public function getLinkCache() {
624 return $this->getService( 'LinkCache' );
629 * @return LinkRendererFactory
631 public function getLinkRendererFactory() {
632 return $this->getService( 'LinkRendererFactory' );
636 * LinkRenderer instance that can be used
637 * if no custom options are needed
640 * @return LinkRenderer
642 public function getLinkRenderer() {
643 return $this->getService( 'LinkRenderer' );
648 * @return TitleFormatter
650 public function getTitleFormatter() {
651 return $this->getService( 'TitleFormatter' );
656 * @return TitleParser
658 public function getTitleParser() {
659 return $this->getService( 'TitleParser' );
666 public function getMainObjectStash() {
667 return $this->getService( 'MainObjectStash' );
672 * @return \WANObjectCache
674 public function getMainWANObjectCache() {
675 return $this->getService( 'MainWANObjectCache' );
682 public function getLocalServerObjectCache() {
683 return $this->getService( 'LocalServerObjectCache' );
688 * @return VirtualRESTServiceClient
690 public function getVirtualRESTServiceClient() {
691 return $this->getService( 'VirtualRESTServiceClient' );
696 * @return \ConfiguredReadOnlyMode
698 public function getConfiguredReadOnlyMode() {
699 return $this->getService( 'ConfiguredReadOnlyMode' );
704 * @return \ReadOnlyMode
706 public function getReadOnlyMode() {
707 return $this->getService( 'ReadOnlyMode' );
712 * @return \UploadRevisionImporter
714 public function getWikiRevisionUploadImporter() {
715 return $this->getService( 'UploadRevisionImporter' );
720 * @return \OldRevisionImporter
722 public function getWikiRevisionOldRevisionImporter() {
723 return $this->getService( 'OldRevisionImporter' );
728 * @return \OldRevisionImporter
730 public function getWikiRevisionOldRevisionImporterNoUpdates() {
731 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
736 * @return CommandFactory
738 public function getShellCommandFactory() {
739 return $this->getService( 'ShellCommandFactory' );
744 * @return \ExternalStoreFactory
746 public function getExternalStoreFactory() {
747 return $this->getService( 'ExternalStoreFactory' );
752 * @return BlobStoreFactory
754 public function getBlobStoreFactory() {
755 return $this->getService( 'BlobStoreFactory' );
762 public function getBlobStore() {
763 return $this->getService( '_SqlBlobStore' );
768 * @return RevisionStore
770 public function getRevisionStore() {
771 return $this->getService( 'RevisionStore' );
776 * @return RevisionStoreFactory
778 public function getRevisionStoreFactory() {
779 return $this->getService( 'RevisionStoreFactory' );
784 * @return RevisionLookup
786 public function getRevisionLookup() {
787 return $this->getService( 'RevisionLookup' );
792 * @return RevisionFactory
794 public function getRevisionFactory() {
795 return $this->getService( 'RevisionFactory' );
800 * @return NameTableStore
802 public function getContentModelStore() {
803 return $this->getService( 'ContentModelStore' );
808 * @return NameTableStore
810 public function getSlotRoleStore() {
811 return $this->getService( 'SlotRoleStore' );
816 * @return NameTableStore
818 public function getChangeTagDefStore() {
819 return $this->getService( 'ChangeTagDefStore' );
824 * @return PreferencesFactory
826 public function getPreferencesFactory() {
827 return $this->getService( 'PreferencesFactory' );
832 * @return HttpRequestFactory
834 public function getHttpRequestFactory() {
835 return $this->getService( 'HttpRequestFactory' );
840 * @return CommentStore
842 public function getCommentStore() {
843 return $this->getService( 'CommentStore' );
848 * @return ActorMigration
850 public function getActorMigration() {
851 return $this->getService( 'ActorMigration' );
856 * @return UploadRevisionImporter
858 public function getUploadRevisionImporter() {
859 return $this->getService( 'UploadRevisionImporter' );
864 * @return OldRevisionImporter
866 public function getOldRevisionImporter() {
867 return $this->getService( 'OldRevisionImporter' );
872 * @return ConfigRepository
874 public function getConfigRepository() {
875 return $this->getService( 'ConfigRepository' );
880 * @return MagicWordFactory
882 public function getMagicWordFactory() {
883 return $this->getService( 'MagicWordFactory' );
890 public function getContentLanguage() {
891 return $this->getService( 'ContentLanguage' );
896 * @return PasswordFactory
898 public function getPasswordFactory() {
899 return $this->getService( 'PasswordFactory' );
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 ///////////////////////////////////////////////////////////////////////////