13 use IBufferingStatsdDataFactory
;
14 use MediaWiki\Http\HttpRequestFactory
;
15 use MediaWiki\Preferences\PreferencesFactory
;
16 use MediaWiki\Shell\CommandFactory
;
17 use MediaWiki\Storage\BlobStore
;
18 use MediaWiki\Storage\BlobStoreFactory
;
19 use MediaWiki\Storage\NameTableStore
;
20 use MediaWiki\Storage\RevisionFactory
;
21 use MediaWiki\Storage\RevisionLookup
;
22 use MediaWiki\Storage\RevisionStore
;
23 use Wikimedia\Rdbms\LBFactory
;
25 use Wikimedia\Rdbms\LoadBalancer
;
26 use MediaHandlerFactory
;
27 use MediaWiki\Linker\LinkRenderer
;
28 use MediaWiki\Linker\LinkRendererFactory
;
29 use MediaWiki\Services\SalvageableService
;
30 use MediaWiki\Services\ServiceContainer
;
31 use MediaWiki\Services\NoSuchServiceException
;
39 use SearchEngineConfig
;
40 use SearchEngineFactory
;
43 use WatchedItemStoreInterface
;
44 use WatchedItemQueryService
;
48 use VirtualRESTServiceClient
;
49 use MediaWiki\Interwiki\InterwikiLookup
;
52 * Service locator for MediaWiki core services.
54 * This program is free software; you can redistribute it and/or modify
55 * it under the terms of the GNU General Public License as published by
56 * the Free Software Foundation; either version 2 of the License, or
57 * (at your option) any later version.
59 * This program is distributed in the hope that it will be useful,
60 * but WITHOUT ANY WARRANTY; without even the implied warranty of
61 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
62 * GNU General Public License for more details.
64 * You should have received a copy of the GNU General Public License along
65 * with this program; if not, write to the Free Software Foundation, Inc.,
66 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
67 * http://www.gnu.org/copyleft/gpl.html
75 * MediaWikiServices is the service locator for the application scope of MediaWiki.
76 * Its implemented as a simple configurable DI container.
77 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
78 * the network of service objects that defines MediaWiki's application logic.
79 * It acts as an entry point to MediaWiki's dependency injection mechanism.
81 * Services are defined in the "wiring" array passed to the constructor,
82 * or by calling defineService().
84 * @see docs/injection.txt for an overview of using dependency injection in the
85 * MediaWiki code base.
87 class MediaWikiServices
extends ServiceContainer
{
90 * @var MediaWikiServices|null
92 private static $instance = null;
95 * Returns the global default instance of the top level service locator.
99 * The default instance is initialized using the service instantiator functions
100 * defined in ServiceWiring.php.
102 * @note This should only be called by static functions! The instance returned here
103 * should not be passed around! Objects that need access to a service should have
104 * that service injected into the constructor, never a service locator!
106 * @return MediaWikiServices
108 public static function getInstance() {
109 if ( self
::$instance === null ) {
110 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
111 // but some information from the global scope has to be injected here,
112 // even if it's just a file name or database credentials to load
113 // configuration from.
114 $bootstrapConfig = new GlobalVarConfig();
115 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
118 return self
::$instance;
122 * Replaces the global MediaWikiServices instance.
126 * @note This is for use in PHPUnit tests only!
128 * @throws MWException if called outside of PHPUnit tests.
130 * @param MediaWikiServices $services The new MediaWikiServices object.
132 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
134 public static function forceGlobalInstance( MediaWikiServices
$services ) {
135 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
136 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
139 $old = self
::getInstance();
140 self
::$instance = $services;
146 * Creates a new instance of MediaWikiServices and sets it as the global default
147 * instance. getInstance() will return a different MediaWikiServices object
148 * after every call to resetGlobalInstance().
152 * @warning This should not be used during normal operation. It is intended for use
153 * when the configuration has changed significantly since bootstrap time, e.g.
154 * during the installation process or during testing.
156 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
157 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
158 * any of the services managed by MediaWikiServices exist. If any service objects
159 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
160 * with the operation of the services managed by the new MediaWikiServices.
161 * Operating with a mix of services created by the old and the new
162 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
163 * Any class implementing LAZY LOADING is especially prone to this problem,
164 * since instances would typically retain a reference to a storage layer service.
166 * @see forceGlobalInstance()
167 * @see resetGlobalInstance()
168 * @see resetBetweenTest()
170 * @param Config|null $bootstrapConfig The Config object to be registered as the
171 * 'BootstrapConfig' service. This has to contain at least the information
172 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
173 * config of the old instance of MediaWikiServices will be re-used. If there
174 * was no previous instance, a new GlobalVarConfig object will be used to
175 * bootstrap the services.
177 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
178 * See SalvageableService for details.
180 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
181 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
184 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
185 if ( self
::$instance === null ) {
186 // no global instance yet, nothing to reset
190 self
::failIfResetNotAllowed( __METHOD__
);
192 if ( $bootstrapConfig === null ) {
193 $bootstrapConfig = self
::$instance->getBootstrapConfig();
196 $oldInstance = self
::$instance;
198 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
199 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
201 if ( $quick === 'quick' ) {
202 self
::$instance->salvage( $oldInstance );
204 $oldInstance->destroy();
209 * Salvages the state of any salvageable service instances in $other.
211 * @note $other will have been destroyed when salvage() returns.
213 * @param MediaWikiServices $other
215 private function salvage( self
$other ) {
216 foreach ( $this->getServiceNames() as $name ) {
217 // The service could be new in the new instance and not registered in the
218 // other instance (e.g. an extension that was loaded after the instantiation of
219 // the other instance. Skip this service in this case. See T143974
221 $oldService = $other->peekService( $name );
222 } catch ( NoSuchServiceException
$e ) {
226 if ( $oldService instanceof SalvageableService
) {
227 /** @var SalvageableService $newService */
228 $newService = $this->getService( $name );
229 $newService->salvage( $oldService );
237 * Creates a new MediaWikiServices instance and initializes it according to the
238 * given $bootstrapConfig. In particular, all wiring files defined in the
239 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
241 * @param Config|null $bootstrapConfig The Config object to be registered as the
242 * 'BootstrapConfig' service.
244 * @param string $loadWiring set this to 'load' to load the wiring files specified
245 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
247 * @return MediaWikiServices
248 * @throws MWException
249 * @throws \FatalError
251 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
252 $instance = new self( $bootstrapConfig );
254 // Load the default wiring from the specified files.
255 if ( $loadWiring === 'load' ) {
256 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
257 $instance->loadWiringFiles( $wiringFiles );
260 // Provide a traditional hook point to allow extensions to configure services.
261 Hooks
::run( 'MediaWikiServices', [ $instance ] );
267 * Disables all storage layer services. After calling this, any attempt to access the
268 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
273 * @warning This is intended for extreme situations only and should never be used
274 * while serving normal web requests. Legitimate use cases for this method include
275 * the installation process. Test fixtures may also use this, if the fixture relies
278 * @see resetGlobalInstance()
279 * @see resetChildProcessServices()
281 public static function disableStorageBackend() {
282 // TODO: also disable some Caches, JobQueues, etc
283 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
284 $services = self
::getInstance();
286 foreach ( $destroy as $name ) {
287 $services->disableService( $name );
290 ObjectCache
::clear();
294 * Resets any services that may have become stale after a child process
295 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
296 * to call this method from the parent process.
300 * @note This is intended for use in the context of process forking only!
302 * @see resetGlobalInstance()
303 * @see disableStorageBackend()
305 public static function resetChildProcessServices() {
306 // NOTE: for now, just reset everything. Since we don't know the interdependencies
307 // between services, we can't do this more selectively at this time.
308 self
::resetGlobalInstance();
310 // Child, reseed because there is no bug in PHP:
311 // https://bugs.php.net/bug.php?id=42465
312 mt_srand( getmypid() );
316 * Resets the given service for testing purposes.
320 * @warning This is generally unsafe! Other services may still retain references
321 * to the stale service instance, leading to failures and inconsistencies. Subclasses
322 * may use this method to reset specific services under specific instances, but
323 * it should not be exposed to application logic.
325 * @note With proper dependency injection used throughout the codebase, this method
326 * should not be needed. It is provided to allow tests that pollute global service
327 * instances to clean up.
329 * @param string $name
330 * @param bool $destroy Whether the service instance should be destroyed if it exists.
331 * When set to false, any existing service instance will effectively be detached
332 * from the container.
334 * @throws MWException if called outside of PHPUnit tests.
336 public function resetServiceForTesting( $name, $destroy = true ) {
337 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
338 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
341 $this->resetService( $name, $destroy );
345 * Convenience method that throws an exception unless it is called during a phase in which
346 * resetting of global services is allowed. In general, services should not be reset
347 * individually, since that may introduce inconsistencies.
351 * This method will throw an exception if:
353 * - self::$resetInProgress is false (to allow all services to be reset together
354 * via resetGlobalInstance)
355 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
356 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
358 * This method is intended to be used to safeguard against accidentally resetting
359 * global service instances that are not yet managed by MediaWikiServices. It is
360 * defined here in the MediaWikiServices services class to have a central place
361 * for managing service bootstrapping and resetting.
363 * @param string $method the name of the caller method, as given by __METHOD__.
365 * @throws MWException if called outside bootstrap mode.
367 * @see resetGlobalInstance()
368 * @see forceGlobalInstance()
369 * @see disableStorageBackend()
371 public static function failIfResetNotAllowed( $method ) {
372 if ( !defined( 'MW_PHPUNIT_TEST' )
373 && !defined( 'MW_PARSER_TEST' )
374 && !defined( 'MEDIAWIKI_INSTALL' )
375 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
376 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
378 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
383 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
384 * This has to contain at least the information needed to set up the 'ConfigFactory'
387 public function __construct( Config
$config ) {
388 parent
::__construct();
390 // Register the given Config object as the bootstrap config service.
391 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
396 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
399 * Returns the Config object containing the bootstrap configuration.
400 * Bootstrap configuration would typically include database credentials
401 * and other information that may be needed before the ConfigFactory
402 * service can be instantiated.
404 * @note This should only be used during bootstrapping, in particular
405 * when creating the MainConfig service. Application logic should
406 * use getMainConfig() to get a Config instances.
411 public function getBootstrapConfig() {
412 return $this->getService( 'BootstrapConfig' );
417 * @return ConfigFactory
419 public function getConfigFactory() {
420 return $this->getService( 'ConfigFactory' );
424 * Returns the Config object that provides configuration for MediaWiki core.
425 * This may or may not be the same object that is returned by getBootstrapConfig().
430 public function getMainConfig() {
431 return $this->getService( 'MainConfig' );
438 public function getSiteLookup() {
439 return $this->getService( 'SiteLookup' );
446 public function getSiteStore() {
447 return $this->getService( 'SiteStore' );
452 * @return InterwikiLookup
454 public function getInterwikiLookup() {
455 return $this->getService( 'InterwikiLookup' );
460 * @return IBufferingStatsdDataFactory
462 public function getStatsdDataFactory() {
463 return $this->getService( 'StatsdDataFactory' );
468 * @return EventRelayerGroup
470 public function getEventRelayerGroup() {
471 return $this->getService( 'EventRelayerGroup' );
476 * @return SearchEngine
478 public function newSearchEngine() {
479 // New engine object every time, since they keep state
480 return $this->getService( 'SearchEngineFactory' )->create();
485 * @return SearchEngineFactory
487 public function getSearchEngineFactory() {
488 return $this->getService( 'SearchEngineFactory' );
493 * @return SearchEngineConfig
495 public function getSearchEngineConfig() {
496 return $this->getService( 'SearchEngineConfig' );
501 * @return SkinFactory
503 public function getSkinFactory() {
504 return $this->getService( 'SkinFactory' );
511 public function getDBLoadBalancerFactory() {
512 return $this->getService( 'DBLoadBalancerFactory' );
517 * @return LoadBalancer The main DB load balancer for the local wiki.
519 public function getDBLoadBalancer() {
520 return $this->getService( 'DBLoadBalancer' );
525 * @return WatchedItemStoreInterface
527 public function getWatchedItemStore() {
528 return $this->getService( 'WatchedItemStore' );
533 * @return WatchedItemQueryService
535 public function getWatchedItemQueryService() {
536 return $this->getService( 'WatchedItemQueryService' );
543 public function getCryptRand() {
544 return $this->getService( 'CryptRand' );
551 public function getCryptHKDF() {
552 return $this->getService( 'CryptHKDF' );
557 * @return MediaHandlerFactory
559 public function getMediaHandlerFactory() {
560 return $this->getService( 'MediaHandlerFactory' );
565 * @return MimeAnalyzer
567 public function getMimeAnalyzer() {
568 return $this->getService( 'MimeAnalyzer' );
573 * @return ProxyLookup
575 public function getProxyLookup() {
576 return $this->getService( 'ProxyLookup' );
583 public function getParser() {
584 return $this->getService( 'Parser' );
589 * @return ParserCache
591 public function getParserCache() {
592 return $this->getService( 'ParserCache' );
597 * @return GenderCache
599 public function getGenderCache() {
600 return $this->getService( 'GenderCache' );
607 public function getLinkCache() {
608 return $this->getService( 'LinkCache' );
613 * @return LinkRendererFactory
615 public function getLinkRendererFactory() {
616 return $this->getService( 'LinkRendererFactory' );
620 * LinkRenderer instance that can be used
621 * if no custom options are needed
624 * @return LinkRenderer
626 public function getLinkRenderer() {
627 return $this->getService( 'LinkRenderer' );
632 * @return TitleFormatter
634 public function getTitleFormatter() {
635 return $this->getService( 'TitleFormatter' );
640 * @return TitleParser
642 public function getTitleParser() {
643 return $this->getService( 'TitleParser' );
650 public function getMainObjectStash() {
651 return $this->getService( 'MainObjectStash' );
656 * @return \WANObjectCache
658 public function getMainWANObjectCache() {
659 return $this->getService( 'MainWANObjectCache' );
666 public function getLocalServerObjectCache() {
667 return $this->getService( 'LocalServerObjectCache' );
672 * @return VirtualRESTServiceClient
674 public function getVirtualRESTServiceClient() {
675 return $this->getService( 'VirtualRESTServiceClient' );
680 * @return \ConfiguredReadOnlyMode
682 public function getConfiguredReadOnlyMode() {
683 return $this->getService( 'ConfiguredReadOnlyMode' );
688 * @return \ReadOnlyMode
690 public function getReadOnlyMode() {
691 return $this->getService( 'ReadOnlyMode' );
696 * @return \UploadRevisionImporter
698 public function getWikiRevisionUploadImporter() {
699 return $this->getService( 'UploadRevisionImporter' );
704 * @return \OldRevisionImporter
706 public function getWikiRevisionOldRevisionImporter() {
707 return $this->getService( 'OldRevisionImporter' );
712 * @return \OldRevisionImporter
714 public function getWikiRevisionOldRevisionImporterNoUpdates() {
715 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
720 * @return CommandFactory
722 public function getShellCommandFactory() {
723 return $this->getService( 'ShellCommandFactory' );
728 * @return \ExternalStoreFactory
730 public function getExternalStoreFactory() {
731 return $this->getService( 'ExternalStoreFactory' );
736 * @return BlobStoreFactory
738 public function getBlobStoreFactory() {
739 return $this->getService( 'BlobStoreFactory' );
746 public function getBlobStore() {
747 return $this->getService( '_SqlBlobStore' );
752 * @return RevisionStore
754 public function getRevisionStore() {
755 return $this->getService( 'RevisionStore' );
760 * @return RevisionLookup
762 public function getRevisionLookup() {
763 return $this->getService( 'RevisionLookup' );
768 * @return RevisionFactory
770 public function getRevisionFactory() {
771 return $this->getService( 'RevisionFactory' );
776 * @return NameTableStore
778 public function getContentModelStore() {
779 return $this->getService( 'ContentModelStore' );
784 * @return NameTableStore
786 public function getSlotRoleStore() {
787 return $this->getService( 'SlotRoleStore' );
792 * @return PreferencesFactory
794 public function getPreferencesFactory() {
795 return $this->getService( 'PreferencesFactory' );
800 * @return HttpRequestFactory
802 public function getHttpRequestFactory() {
803 return $this->getService( 'HttpRequestFactory' );
808 * @return CommentStore
810 public function getCommentStore() {
811 return $this->getService( 'CommentStore' );
816 * @return ActorMigration
818 public function getActorMigration() {
819 return $this->getService( 'ActorMigration' );
822 ///////////////////////////////////////////////////////////////////////////
823 // NOTE: When adding a service getter here, don't forget to add a test
824 // case for it in MediaWikiServicesTest::provideGetters() and in
825 // MediaWikiServicesTest::provideGetService()!
826 ///////////////////////////////////////////////////////////////////////////