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\RevisionFactory
;
20 use MediaWiki\Storage\RevisionLookup
;
21 use MediaWiki\Storage\RevisionStore
;
22 use Wikimedia\Rdbms\LBFactory
;
24 use Wikimedia\Rdbms\LoadBalancer
;
25 use MediaHandlerFactory
;
26 use MediaWiki\Linker\LinkRenderer
;
27 use MediaWiki\Linker\LinkRendererFactory
;
28 use MediaWiki\Services\SalvageableService
;
29 use MediaWiki\Services\ServiceContainer
;
30 use MediaWiki\Services\NoSuchServiceException
;
38 use SearchEngineConfig
;
39 use SearchEngineFactory
;
42 use WatchedItemStoreInterface
;
43 use WatchedItemQueryService
;
47 use VirtualRESTServiceClient
;
48 use MediaWiki\Interwiki\InterwikiLookup
;
51 * Service locator for MediaWiki core services.
53 * This program is free software; you can redistribute it and/or modify
54 * it under the terms of the GNU General Public License as published by
55 * the Free Software Foundation; either version 2 of the License, or
56 * (at your option) any later version.
58 * This program is distributed in the hope that it will be useful,
59 * but WITHOUT ANY WARRANTY; without even the implied warranty of
60 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
61 * GNU General Public License for more details.
63 * You should have received a copy of the GNU General Public License along
64 * with this program; if not, write to the Free Software Foundation, Inc.,
65 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
66 * http://www.gnu.org/copyleft/gpl.html
74 * MediaWikiServices is the service locator for the application scope of MediaWiki.
75 * Its implemented as a simple configurable DI container.
76 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
77 * the network of service objects that defines MediaWiki's application logic.
78 * It acts as an entry point to MediaWiki's dependency injection mechanism.
80 * Services are defined in the "wiring" array passed to the constructor,
81 * or by calling defineService().
83 * @see docs/injection.txt for an overview of using dependency injection in the
84 * MediaWiki code base.
86 class MediaWikiServices
extends ServiceContainer
{
89 * @var MediaWikiServices|null
91 private static $instance = null;
94 * Returns the global default instance of the top level service locator.
98 * The default instance is initialized using the service instantiator functions
99 * defined in ServiceWiring.php.
101 * @note This should only be called by static functions! The instance returned here
102 * should not be passed around! Objects that need access to a service should have
103 * that service injected into the constructor, never a service locator!
105 * @return MediaWikiServices
107 public static function getInstance() {
108 if ( self
::$instance === null ) {
109 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
110 // but some information from the global scope has to be injected here,
111 // even if it's just a file name or database credentials to load
112 // configuration from.
113 $bootstrapConfig = new GlobalVarConfig();
114 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
117 return self
::$instance;
121 * Replaces the global MediaWikiServices instance.
125 * @note This is for use in PHPUnit tests only!
127 * @throws MWException if called outside of PHPUnit tests.
129 * @param MediaWikiServices $services The new MediaWikiServices object.
131 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
133 public static function forceGlobalInstance( MediaWikiServices
$services ) {
134 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
135 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
138 $old = self
::getInstance();
139 self
::$instance = $services;
145 * Creates a new instance of MediaWikiServices and sets it as the global default
146 * instance. getInstance() will return a different MediaWikiServices object
147 * after every call to resetGlobalInstance().
151 * @warning This should not be used during normal operation. It is intended for use
152 * when the configuration has changed significantly since bootstrap time, e.g.
153 * during the installation process or during testing.
155 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
156 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
157 * any of the services managed by MediaWikiServices exist. If any service objects
158 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
159 * with the operation of the services managed by the new MediaWikiServices.
160 * Operating with a mix of services created by the old and the new
161 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
162 * Any class implementing LAZY LOADING is especially prone to this problem,
163 * since instances would typically retain a reference to a storage layer service.
165 * @see forceGlobalInstance()
166 * @see resetGlobalInstance()
167 * @see resetBetweenTest()
169 * @param Config|null $bootstrapConfig The Config object to be registered as the
170 * 'BootstrapConfig' service. This has to contain at least the information
171 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
172 * config of the old instance of MediaWikiServices will be re-used. If there
173 * was no previous instance, a new GlobalVarConfig object will be used to
174 * bootstrap the services.
176 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
177 * See SalvageableService for details.
179 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
180 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
183 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
184 if ( self
::$instance === null ) {
185 // no global instance yet, nothing to reset
189 self
::failIfResetNotAllowed( __METHOD__
);
191 if ( $bootstrapConfig === null ) {
192 $bootstrapConfig = self
::$instance->getBootstrapConfig();
195 $oldInstance = self
::$instance;
197 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
198 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
200 if ( $quick === 'quick' ) {
201 self
::$instance->salvage( $oldInstance );
203 $oldInstance->destroy();
208 * Salvages the state of any salvageable service instances in $other.
210 * @note $other will have been destroyed when salvage() returns.
212 * @param MediaWikiServices $other
214 private function salvage( self
$other ) {
215 foreach ( $this->getServiceNames() as $name ) {
216 // The service could be new in the new instance and not registered in the
217 // other instance (e.g. an extension that was loaded after the instantiation of
218 // the other instance. Skip this service in this case. See T143974
220 $oldService = $other->peekService( $name );
221 } catch ( NoSuchServiceException
$e ) {
225 if ( $oldService instanceof SalvageableService
) {
226 /** @var SalvageableService $newService */
227 $newService = $this->getService( $name );
228 $newService->salvage( $oldService );
236 * Creates a new MediaWikiServices instance and initializes it according to the
237 * given $bootstrapConfig. In particular, all wiring files defined in the
238 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
240 * @param Config|null $bootstrapConfig The Config object to be registered as the
241 * 'BootstrapConfig' service.
243 * @param string $loadWiring set this to 'load' to load the wiring files specified
244 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
246 * @return MediaWikiServices
247 * @throws MWException
248 * @throws \FatalError
250 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
251 $instance = new self( $bootstrapConfig );
253 // Load the default wiring from the specified files.
254 if ( $loadWiring === 'load' ) {
255 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
256 $instance->loadWiringFiles( $wiringFiles );
259 // Provide a traditional hook point to allow extensions to configure services.
260 Hooks
::run( 'MediaWikiServices', [ $instance ] );
266 * Disables all storage layer services. After calling this, any attempt to access the
267 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
272 * @warning This is intended for extreme situations only and should never be used
273 * while serving normal web requests. Legitimate use cases for this method include
274 * the installation process. Test fixtures may also use this, if the fixture relies
277 * @see resetGlobalInstance()
278 * @see resetChildProcessServices()
280 public static function disableStorageBackend() {
281 // TODO: also disable some Caches, JobQueues, etc
282 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
283 $services = self
::getInstance();
285 foreach ( $destroy as $name ) {
286 $services->disableService( $name );
289 ObjectCache
::clear();
293 * Resets any services that may have become stale after a child process
294 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
295 * to call this method from the parent process.
299 * @note This is intended for use in the context of process forking only!
301 * @see resetGlobalInstance()
302 * @see disableStorageBackend()
304 public static function resetChildProcessServices() {
305 // NOTE: for now, just reset everything. Since we don't know the interdependencies
306 // between services, we can't do this more selectively at this time.
307 self
::resetGlobalInstance();
309 // Child, reseed because there is no bug in PHP:
310 // https://bugs.php.net/bug.php?id=42465
311 mt_srand( getmypid() );
315 * Resets the given service for testing purposes.
319 * @warning This is generally unsafe! Other services may still retain references
320 * to the stale service instance, leading to failures and inconsistencies. Subclasses
321 * may use this method to reset specific services under specific instances, but
322 * it should not be exposed to application logic.
324 * @note With proper dependency injection used throughout the codebase, this method
325 * should not be needed. It is provided to allow tests that pollute global service
326 * instances to clean up.
328 * @param string $name
329 * @param bool $destroy Whether the service instance should be destroyed if it exists.
330 * When set to false, any existing service instance will effectively be detached
331 * from the container.
333 * @throws MWException if called outside of PHPUnit tests.
335 public function resetServiceForTesting( $name, $destroy = true ) {
336 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
337 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
340 $this->resetService( $name, $destroy );
344 * Convenience method that throws an exception unless it is called during a phase in which
345 * resetting of global services is allowed. In general, services should not be reset
346 * individually, since that may introduce inconsistencies.
350 * This method will throw an exception if:
352 * - self::$resetInProgress is false (to allow all services to be reset together
353 * via resetGlobalInstance)
354 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
355 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
357 * This method is intended to be used to safeguard against accidentally resetting
358 * global service instances that are not yet managed by MediaWikiServices. It is
359 * defined here in the MediaWikiServices services class to have a central place
360 * for managing service bootstrapping and resetting.
362 * @param string $method the name of the caller method, as given by __METHOD__.
364 * @throws MWException if called outside bootstrap mode.
366 * @see resetGlobalInstance()
367 * @see forceGlobalInstance()
368 * @see disableStorageBackend()
370 public static function failIfResetNotAllowed( $method ) {
371 if ( !defined( 'MW_PHPUNIT_TEST' )
372 && !defined( 'MW_PARSER_TEST' )
373 && !defined( 'MEDIAWIKI_INSTALL' )
374 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
375 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
377 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
382 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
383 * This has to contain at least the information needed to set up the 'ConfigFactory'
386 public function __construct( Config
$config ) {
387 parent
::__construct();
389 // Register the given Config object as the bootstrap config service.
390 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
395 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
398 * Returns the Config object containing the bootstrap configuration.
399 * Bootstrap configuration would typically include database credentials
400 * and other information that may be needed before the ConfigFactory
401 * service can be instantiated.
403 * @note This should only be used during bootstrapping, in particular
404 * when creating the MainConfig service. Application logic should
405 * use getMainConfig() to get a Config instances.
410 public function getBootstrapConfig() {
411 return $this->getService( 'BootstrapConfig' );
416 * @return ConfigFactory
418 public function getConfigFactory() {
419 return $this->getService( 'ConfigFactory' );
423 * Returns the Config object that provides configuration for MediaWiki core.
424 * This may or may not be the same object that is returned by getBootstrapConfig().
429 public function getMainConfig() {
430 return $this->getService( 'MainConfig' );
437 public function getSiteLookup() {
438 return $this->getService( 'SiteLookup' );
445 public function getSiteStore() {
446 return $this->getService( 'SiteStore' );
451 * @return InterwikiLookup
453 public function getInterwikiLookup() {
454 return $this->getService( 'InterwikiLookup' );
459 * @return IBufferingStatsdDataFactory
461 public function getStatsdDataFactory() {
462 return $this->getService( 'StatsdDataFactory' );
467 * @return EventRelayerGroup
469 public function getEventRelayerGroup() {
470 return $this->getService( 'EventRelayerGroup' );
475 * @return SearchEngine
477 public function newSearchEngine() {
478 // New engine object every time, since they keep state
479 return $this->getService( 'SearchEngineFactory' )->create();
484 * @return SearchEngineFactory
486 public function getSearchEngineFactory() {
487 return $this->getService( 'SearchEngineFactory' );
492 * @return SearchEngineConfig
494 public function getSearchEngineConfig() {
495 return $this->getService( 'SearchEngineConfig' );
500 * @return SkinFactory
502 public function getSkinFactory() {
503 return $this->getService( 'SkinFactory' );
510 public function getDBLoadBalancerFactory() {
511 return $this->getService( 'DBLoadBalancerFactory' );
516 * @return LoadBalancer The main DB load balancer for the local wiki.
518 public function getDBLoadBalancer() {
519 return $this->getService( 'DBLoadBalancer' );
524 * @return WatchedItemStoreInterface
526 public function getWatchedItemStore() {
527 return $this->getService( 'WatchedItemStore' );
532 * @return WatchedItemQueryService
534 public function getWatchedItemQueryService() {
535 return $this->getService( 'WatchedItemQueryService' );
542 public function getCryptRand() {
543 return $this->getService( 'CryptRand' );
550 public function getCryptHKDF() {
551 return $this->getService( 'CryptHKDF' );
556 * @return MediaHandlerFactory
558 public function getMediaHandlerFactory() {
559 return $this->getService( 'MediaHandlerFactory' );
564 * @return MimeAnalyzer
566 public function getMimeAnalyzer() {
567 return $this->getService( 'MimeAnalyzer' );
572 * @return ProxyLookup
574 public function getProxyLookup() {
575 return $this->getService( 'ProxyLookup' );
582 public function getParser() {
583 return $this->getService( 'Parser' );
588 * @return ParserCache
590 public function getParserCache() {
591 return $this->getService( 'ParserCache' );
596 * @return GenderCache
598 public function getGenderCache() {
599 return $this->getService( 'GenderCache' );
606 public function getLinkCache() {
607 return $this->getService( 'LinkCache' );
612 * @return LinkRendererFactory
614 public function getLinkRendererFactory() {
615 return $this->getService( 'LinkRendererFactory' );
619 * LinkRenderer instance that can be used
620 * if no custom options are needed
623 * @return LinkRenderer
625 public function getLinkRenderer() {
626 return $this->getService( 'LinkRenderer' );
631 * @return TitleFormatter
633 public function getTitleFormatter() {
634 return $this->getService( 'TitleFormatter' );
639 * @return TitleParser
641 public function getTitleParser() {
642 return $this->getService( 'TitleParser' );
649 public function getMainObjectStash() {
650 return $this->getService( 'MainObjectStash' );
655 * @return \WANObjectCache
657 public function getMainWANObjectCache() {
658 return $this->getService( 'MainWANObjectCache' );
665 public function getLocalServerObjectCache() {
666 return $this->getService( 'LocalServerObjectCache' );
671 * @return VirtualRESTServiceClient
673 public function getVirtualRESTServiceClient() {
674 return $this->getService( 'VirtualRESTServiceClient' );
679 * @return \ConfiguredReadOnlyMode
681 public function getConfiguredReadOnlyMode() {
682 return $this->getService( 'ConfiguredReadOnlyMode' );
687 * @return \ReadOnlyMode
689 public function getReadOnlyMode() {
690 return $this->getService( 'ReadOnlyMode' );
695 * @return \UploadRevisionImporter
697 public function getWikiRevisionUploadImporter() {
698 return $this->getService( 'UploadRevisionImporter' );
703 * @return \OldRevisionImporter
705 public function getWikiRevisionOldRevisionImporter() {
706 return $this->getService( 'OldRevisionImporter' );
711 * @return \OldRevisionImporter
713 public function getWikiRevisionOldRevisionImporterNoUpdates() {
714 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
719 * @return CommandFactory
721 public function getShellCommandFactory() {
722 return $this->getService( 'ShellCommandFactory' );
727 * @return \ExternalStoreFactory
729 public function getExternalStoreFactory() {
730 return $this->getService( 'ExternalStoreFactory' );
735 * @return BlobStoreFactory
737 public function getBlobStoreFactory() {
738 return $this->getService( 'BlobStoreFactory' );
745 public function getBlobStore() {
746 return $this->getService( '_SqlBlobStore' );
751 * @return RevisionStore
753 public function getRevisionStore() {
754 return $this->getService( 'RevisionStore' );
759 * @return RevisionLookup
761 public function getRevisionLookup() {
762 return $this->getService( 'RevisionLookup' );
767 * @return RevisionFactory
769 public function getRevisionFactory() {
770 return $this->getService( 'RevisionFactory' );
775 * @return PreferencesFactory
777 public function getPreferencesFactory() {
778 return $this->getService( 'PreferencesFactory' );
783 * @return HttpRequestFactory
785 public function getHttpRequestFactory() {
786 return $this->getService( 'HttpRequestFactory' );
791 * @return CommentStore
793 public function getCommentStore() {
794 return $this->getService( 'CommentStore' );
797 ///////////////////////////////////////////////////////////////////////////
798 // NOTE: When adding a service getter here, don't forget to add a test
799 // case for it in MediaWikiServicesTest::provideGetters() and in
800 // MediaWikiServicesTest::provideGetService()!
801 ///////////////////////////////////////////////////////////////////////////