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
;
43 use SearchEngineConfig
;
44 use SearchEngineFactory
;
47 use WatchedItemStoreInterface
;
48 use WatchedItemQueryService
;
52 use VirtualRESTServiceClient
;
53 use MediaWiki\Interwiki\InterwikiLookup
;
57 * Service locator for MediaWiki core services.
59 * This program is free software; you can redistribute it and/or modify
60 * it under the terms of the GNU General Public License as published by
61 * the Free Software Foundation; either version 2 of the License, or
62 * (at your option) any later version.
64 * This program is distributed in the hope that it will be useful,
65 * but WITHOUT ANY WARRANTY; without even the implied warranty of
66 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
67 * GNU General Public License for more details.
69 * You should have received a copy of the GNU General Public License along
70 * with this program; if not, write to the Free Software Foundation, Inc.,
71 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
72 * http://www.gnu.org/copyleft/gpl.html
80 * MediaWikiServices is the service locator for the application scope of MediaWiki.
81 * Its implemented as a simple configurable DI container.
82 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
83 * the network of service objects that defines MediaWiki's application logic.
84 * It acts as an entry point to MediaWiki's dependency injection mechanism.
86 * Services are defined in the "wiring" array passed to the constructor,
87 * or by calling defineService().
89 * @see docs/injection.txt for an overview of using dependency injection in the
90 * MediaWiki code base.
92 class MediaWikiServices
extends ServiceContainer
{
95 * @var MediaWikiServices|null
97 private static $instance = null;
100 * Returns the global default instance of the top level service locator.
104 * The default instance is initialized using the service instantiator functions
105 * defined in ServiceWiring.php.
107 * @note This should only be called by static functions! The instance returned here
108 * should not be passed around! Objects that need access to a service should have
109 * that service injected into the constructor, never a service locator!
111 * @return MediaWikiServices
113 public static function getInstance() {
114 if ( self
::$instance === null ) {
115 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
116 // but some information from the global scope has to be injected here,
117 // even if it's just a file name or database credentials to load
118 // configuration from.
119 $bootstrapConfig = new GlobalVarConfig();
120 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
123 return self
::$instance;
127 * Replaces the global MediaWikiServices instance.
131 * @note This is for use in PHPUnit tests only!
133 * @throws MWException if called outside of PHPUnit tests.
135 * @param MediaWikiServices $services The new MediaWikiServices object.
137 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
139 public static function forceGlobalInstance( MediaWikiServices
$services ) {
140 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
141 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
144 $old = self
::getInstance();
145 self
::$instance = $services;
151 * Creates a new instance of MediaWikiServices and sets it as the global default
152 * instance. getInstance() will return a different MediaWikiServices object
153 * after every call to resetGlobalInstance().
157 * @warning This should not be used during normal operation. It is intended for use
158 * when the configuration has changed significantly since bootstrap time, e.g.
159 * during the installation process or during testing.
161 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
162 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
163 * any of the services managed by MediaWikiServices exist. If any service objects
164 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
165 * with the operation of the services managed by the new MediaWikiServices.
166 * Operating with a mix of services created by the old and the new
167 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
168 * Any class implementing LAZY LOADING is especially prone to this problem,
169 * since instances would typically retain a reference to a storage layer service.
171 * @see forceGlobalInstance()
172 * @see resetGlobalInstance()
173 * @see resetBetweenTest()
175 * @param Config|null $bootstrapConfig The Config object to be registered as the
176 * 'BootstrapConfig' service. This has to contain at least the information
177 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
178 * config of the old instance of MediaWikiServices will be re-used. If there
179 * was no previous instance, a new GlobalVarConfig object will be used to
180 * bootstrap the services.
182 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
183 * See SalvageableService for details.
185 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
186 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
189 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
190 if ( self
::$instance === null ) {
191 // no global instance yet, nothing to reset
195 self
::failIfResetNotAllowed( __METHOD__
);
197 if ( $bootstrapConfig === null ) {
198 $bootstrapConfig = self
::$instance->getBootstrapConfig();
201 $oldInstance = self
::$instance;
203 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
204 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
206 if ( $quick === 'quick' ) {
207 self
::$instance->salvage( $oldInstance );
209 $oldInstance->destroy();
214 * Salvages the state of any salvageable service instances in $other.
216 * @note $other will have been destroyed when salvage() returns.
218 * @param MediaWikiServices $other
220 private function salvage( self
$other ) {
221 foreach ( $this->getServiceNames() as $name ) {
222 // The service could be new in the new instance and not registered in the
223 // other instance (e.g. an extension that was loaded after the instantiation of
224 // the other instance. Skip this service in this case. See T143974
226 $oldService = $other->peekService( $name );
227 } catch ( NoSuchServiceException
$e ) {
231 if ( $oldService instanceof SalvageableService
) {
232 /** @var SalvageableService $newService */
233 $newService = $this->getService( $name );
234 $newService->salvage( $oldService );
242 * Creates a new MediaWikiServices instance and initializes it according to the
243 * given $bootstrapConfig. In particular, all wiring files defined in the
244 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
246 * @param Config|null $bootstrapConfig The Config object to be registered as the
247 * 'BootstrapConfig' service.
249 * @param string $loadWiring set this to 'load' to load the wiring files specified
250 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
252 * @return MediaWikiServices
253 * @throws MWException
254 * @throws \FatalError
256 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
257 $instance = new self( $bootstrapConfig );
259 // Load the default wiring from the specified files.
260 if ( $loadWiring === 'load' ) {
261 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
262 $instance->loadWiringFiles( $wiringFiles );
265 // Provide a traditional hook point to allow extensions to configure services.
266 Hooks
::run( 'MediaWikiServices', [ $instance ] );
272 * Disables all storage layer services. After calling this, any attempt to access the
273 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
278 * @warning This is intended for extreme situations only and should never be used
279 * while serving normal web requests. Legitimate use cases for this method include
280 * the installation process. Test fixtures may also use this, if the fixture relies
283 * @see resetGlobalInstance()
284 * @see resetChildProcessServices()
286 public static function disableStorageBackend() {
287 // TODO: also disable some Caches, JobQueues, etc
288 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
289 $services = self
::getInstance();
291 foreach ( $destroy as $name ) {
292 $services->disableService( $name );
295 ObjectCache
::clear();
299 * Resets any services that may have become stale after a child process
300 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
301 * to call this method from the parent process.
305 * @note This is intended for use in the context of process forking only!
307 * @see resetGlobalInstance()
308 * @see disableStorageBackend()
310 public static function resetChildProcessServices() {
311 // NOTE: for now, just reset everything. Since we don't know the interdependencies
312 // between services, we can't do this more selectively at this time.
313 self
::resetGlobalInstance();
315 // Child, reseed because there is no bug in PHP:
316 // https://bugs.php.net/bug.php?id=42465
317 mt_srand( getmypid() );
321 * Resets the given service for testing purposes.
325 * @warning This is generally unsafe! Other services may still retain references
326 * to the stale service instance, leading to failures and inconsistencies. Subclasses
327 * may use this method to reset specific services under specific instances, but
328 * it should not be exposed to application logic.
330 * @note With proper dependency injection used throughout the codebase, this method
331 * should not be needed. It is provided to allow tests that pollute global service
332 * instances to clean up.
334 * @param string $name
335 * @param bool $destroy Whether the service instance should be destroyed if it exists.
336 * When set to false, any existing service instance will effectively be detached
337 * from the container.
339 * @throws MWException if called outside of PHPUnit tests.
341 public function resetServiceForTesting( $name, $destroy = true ) {
342 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
343 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
346 $this->resetService( $name, $destroy );
350 * Convenience method that throws an exception unless it is called during a phase in which
351 * resetting of global services is allowed. In general, services should not be reset
352 * individually, since that may introduce inconsistencies.
356 * This method will throw an exception if:
358 * - self::$resetInProgress is false (to allow all services to be reset together
359 * via resetGlobalInstance)
360 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
361 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
363 * This method is intended to be used to safeguard against accidentally resetting
364 * global service instances that are not yet managed by MediaWikiServices. It is
365 * defined here in the MediaWikiServices services class to have a central place
366 * for managing service bootstrapping and resetting.
368 * @param string $method the name of the caller method, as given by __METHOD__.
370 * @throws MWException if called outside bootstrap mode.
372 * @see resetGlobalInstance()
373 * @see forceGlobalInstance()
374 * @see disableStorageBackend()
376 public static function failIfResetNotAllowed( $method ) {
377 if ( !defined( 'MW_PHPUNIT_TEST' )
378 && !defined( 'MW_PARSER_TEST' )
379 && !defined( 'MEDIAWIKI_INSTALL' )
380 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
381 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
383 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
388 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
389 * This has to contain at least the information needed to set up the 'ConfigFactory'
392 public function __construct( Config
$config ) {
393 parent
::__construct();
395 // Register the given Config object as the bootstrap config service.
396 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
401 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
404 * Returns the Config object containing the bootstrap configuration.
405 * Bootstrap configuration would typically include database credentials
406 * and other information that may be needed before the ConfigFactory
407 * service can be instantiated.
409 * @note This should only be used during bootstrapping, in particular
410 * when creating the MainConfig service. Application logic should
411 * use getMainConfig() to get a Config instances.
416 public function getBootstrapConfig() {
417 return $this->getService( 'BootstrapConfig' );
422 * @return ConfigFactory
424 public function getConfigFactory() {
425 return $this->getService( 'ConfigFactory' );
429 * Returns the Config object that provides configuration for MediaWiki core.
430 * This may or may not be the same object that is returned by getBootstrapConfig().
435 public function getMainConfig() {
436 return $this->getService( 'MainConfig' );
443 public function getSiteLookup() {
444 return $this->getService( 'SiteLookup' );
451 public function getSiteStore() {
452 return $this->getService( 'SiteStore' );
457 * @return InterwikiLookup
459 public function getInterwikiLookup() {
460 return $this->getService( 'InterwikiLookup' );
465 * @return IBufferingStatsdDataFactory
467 public function getStatsdDataFactory() {
468 return $this->getService( 'StatsdDataFactory' );
473 * @return IBufferingStatsdDataFactory
475 public function getPerDbNameStatsdDataFactory() {
476 return $this->getService( 'PerDbNameStatsdDataFactory' );
481 * @return EventRelayerGroup
483 public function getEventRelayerGroup() {
484 return $this->getService( 'EventRelayerGroup' );
489 * @return SearchEngine
491 public function newSearchEngine() {
492 // New engine object every time, since they keep state
493 return $this->getService( 'SearchEngineFactory' )->create();
498 * @return SearchEngineFactory
500 public function getSearchEngineFactory() {
501 return $this->getService( 'SearchEngineFactory' );
506 * @return SearchEngineConfig
508 public function getSearchEngineConfig() {
509 return $this->getService( 'SearchEngineConfig' );
514 * @return SkinFactory
516 public function getSkinFactory() {
517 return $this->getService( 'SkinFactory' );
524 public function getDBLoadBalancerFactory() {
525 return $this->getService( 'DBLoadBalancerFactory' );
530 * @return LoadBalancer The main DB load balancer for the local wiki.
532 public function getDBLoadBalancer() {
533 return $this->getService( 'DBLoadBalancer' );
538 * @return WatchedItemStoreInterface
540 public function getWatchedItemStore() {
541 return $this->getService( 'WatchedItemStore' );
546 * @return WatchedItemQueryService
548 public function getWatchedItemQueryService() {
549 return $this->getService( 'WatchedItemQueryService' );
554 * @deprecated since 1.32, use random_bytes()/random_int()
557 public function getCryptRand() {
558 return $this->getService( 'CryptRand' );
565 public function getCryptHKDF() {
566 return $this->getService( 'CryptHKDF' );
571 * @return MediaHandlerFactory
573 public function getMediaHandlerFactory() {
574 return $this->getService( 'MediaHandlerFactory' );
579 * @return MimeAnalyzer
581 public function getMimeAnalyzer() {
582 return $this->getService( 'MimeAnalyzer' );
587 * @return ProxyLookup
589 public function getProxyLookup() {
590 return $this->getService( 'ProxyLookup' );
597 public function getParser() {
598 return $this->getService( 'Parser' );
603 * @return ParserCache
605 public function getParserCache() {
606 return $this->getService( 'ParserCache' );
611 * @return GenderCache
613 public function getGenderCache() {
614 return $this->getService( 'GenderCache' );
621 public function getLinkCache() {
622 return $this->getService( 'LinkCache' );
627 * @return LinkRendererFactory
629 public function getLinkRendererFactory() {
630 return $this->getService( 'LinkRendererFactory' );
634 * LinkRenderer instance that can be used
635 * if no custom options are needed
638 * @return LinkRenderer
640 public function getLinkRenderer() {
641 return $this->getService( 'LinkRenderer' );
646 * @return TitleFormatter
648 public function getTitleFormatter() {
649 return $this->getService( 'TitleFormatter' );
654 * @return TitleParser
656 public function getTitleParser() {
657 return $this->getService( 'TitleParser' );
664 public function getMainObjectStash() {
665 return $this->getService( 'MainObjectStash' );
670 * @return \WANObjectCache
672 public function getMainWANObjectCache() {
673 return $this->getService( 'MainWANObjectCache' );
680 public function getLocalServerObjectCache() {
681 return $this->getService( 'LocalServerObjectCache' );
686 * @return VirtualRESTServiceClient
688 public function getVirtualRESTServiceClient() {
689 return $this->getService( 'VirtualRESTServiceClient' );
694 * @return \ConfiguredReadOnlyMode
696 public function getConfiguredReadOnlyMode() {
697 return $this->getService( 'ConfiguredReadOnlyMode' );
702 * @return \ReadOnlyMode
704 public function getReadOnlyMode() {
705 return $this->getService( 'ReadOnlyMode' );
710 * @return \UploadRevisionImporter
712 public function getWikiRevisionUploadImporter() {
713 return $this->getService( 'UploadRevisionImporter' );
718 * @return \OldRevisionImporter
720 public function getWikiRevisionOldRevisionImporter() {
721 return $this->getService( 'OldRevisionImporter' );
726 * @return \OldRevisionImporter
728 public function getWikiRevisionOldRevisionImporterNoUpdates() {
729 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
734 * @return CommandFactory
736 public function getShellCommandFactory() {
737 return $this->getService( 'ShellCommandFactory' );
742 * @return \ExternalStoreFactory
744 public function getExternalStoreFactory() {
745 return $this->getService( 'ExternalStoreFactory' );
750 * @return BlobStoreFactory
752 public function getBlobStoreFactory() {
753 return $this->getService( 'BlobStoreFactory' );
760 public function getBlobStore() {
761 return $this->getService( '_SqlBlobStore' );
766 * @return RevisionStore
768 public function getRevisionStore() {
769 return $this->getService( 'RevisionStore' );
774 * @return RevisionLookup
776 public function getRevisionLookup() {
777 return $this->getService( 'RevisionLookup' );
782 * @return RevisionFactory
784 public function getRevisionFactory() {
785 return $this->getService( 'RevisionFactory' );
790 * @return NameTableStore
792 public function getContentModelStore() {
793 return $this->getService( 'ContentModelStore' );
798 * @return NameTableStore
800 public function getSlotRoleStore() {
801 return $this->getService( 'SlotRoleStore' );
806 * @return NameTableStore
808 public function getChangeTagDefStore() {
809 return $this->getService( 'ChangeTagDefStore' );
814 * @return PreferencesFactory
816 public function getPreferencesFactory() {
817 return $this->getService( 'PreferencesFactory' );
822 * @return HttpRequestFactory
824 public function getHttpRequestFactory() {
825 return $this->getService( 'HttpRequestFactory' );
830 * @return CommentStore
832 public function getCommentStore() {
833 return $this->getService( 'CommentStore' );
838 * @return ActorMigration
840 public function getActorMigration() {
841 return $this->getService( 'ActorMigration' );
846 * @return UploadRevisionImporter
848 public function getUploadRevisionImporter() {
849 return $this->getService( 'UploadRevisionImporter' );
854 * @return OldRevisionImporter
856 public function getOldRevisionImporter() {
857 return $this->getService( 'OldRevisionImporter' );
862 * @return ConfigRepository
864 public function getConfigRepository() {
865 return $this->getService( 'ConfigRepository' );
870 * @return MagicWordFactory
872 public function getMagicWordFactory() {
873 return $this->getService( 'MagicWordFactory' );
876 ///////////////////////////////////////////////////////////////////////////
877 // NOTE: When adding a service getter here, don't forget to add a test
878 // case for it in MediaWikiServicesTest::provideGetters() and in
879 // MediaWikiServicesTest::provideGetService()!
880 ///////////////////////////////////////////////////////////////////////////