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
;
46 use SearchEngineConfig
;
47 use SearchEngineFactory
;
50 use WatchedItemStoreInterface
;
51 use WatchedItemQueryService
;
55 use VirtualRESTServiceClient
;
56 use MediaWiki\Interwiki\InterwikiLookup
;
60 * Service locator for MediaWiki core services.
62 * This program is free software; you can redistribute it and/or modify
63 * it under the terms of the GNU General Public License as published by
64 * the Free Software Foundation; either version 2 of the License, or
65 * (at your option) any later version.
67 * This program is distributed in the hope that it will be useful,
68 * but WITHOUT ANY WARRANTY; without even the implied warranty of
69 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 * GNU General Public License for more details.
72 * You should have received a copy of the GNU General Public License along
73 * with this program; if not, write to the Free Software Foundation, Inc.,
74 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
75 * http://www.gnu.org/copyleft/gpl.html
83 * MediaWikiServices is the service locator for the application scope of MediaWiki.
84 * Its implemented as a simple configurable DI container.
85 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
86 * the network of service objects that defines MediaWiki's application logic.
87 * It acts as an entry point to MediaWiki's dependency injection mechanism.
89 * Services are defined in the "wiring" array passed to the constructor,
90 * or by calling defineService().
92 * @see docs/injection.txt for an overview of using dependency injection in the
93 * MediaWiki code base.
95 class MediaWikiServices
extends ServiceContainer
{
98 * @var MediaWikiServices|null
100 private static $instance = null;
103 * Returns the global default instance of the top level service locator.
107 * The default instance is initialized using the service instantiator functions
108 * defined in ServiceWiring.php.
110 * @note This should only be called by static functions! The instance returned here
111 * should not be passed around! Objects that need access to a service should have
112 * that service injected into the constructor, never a service locator!
114 * @return MediaWikiServices
116 public static function getInstance() {
117 if ( self
::$instance === null ) {
118 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
119 // but some information from the global scope has to be injected here,
120 // even if it's just a file name or database credentials to load
121 // configuration from.
122 $bootstrapConfig = new GlobalVarConfig();
123 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
126 return self
::$instance;
130 * Replaces the global MediaWikiServices instance.
134 * @note This is for use in PHPUnit tests only!
136 * @throws MWException if called outside of PHPUnit tests.
138 * @param MediaWikiServices $services The new MediaWikiServices object.
140 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
142 public static function forceGlobalInstance( MediaWikiServices
$services ) {
143 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
144 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
147 $old = self
::getInstance();
148 self
::$instance = $services;
154 * Creates a new instance of MediaWikiServices and sets it as the global default
155 * instance. getInstance() will return a different MediaWikiServices object
156 * after every call to resetGlobalInstance().
160 * @warning This should not be used during normal operation. It is intended for use
161 * when the configuration has changed significantly since bootstrap time, e.g.
162 * during the installation process or during testing.
164 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
165 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
166 * any of the services managed by MediaWikiServices exist. If any service objects
167 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
168 * with the operation of the services managed by the new MediaWikiServices.
169 * Operating with a mix of services created by the old and the new
170 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
171 * Any class implementing LAZY LOADING is especially prone to this problem,
172 * since instances would typically retain a reference to a storage layer service.
174 * @see forceGlobalInstance()
175 * @see resetGlobalInstance()
176 * @see resetBetweenTest()
178 * @param Config|null $bootstrapConfig The Config object to be registered as the
179 * 'BootstrapConfig' service. This has to contain at least the information
180 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
181 * config of the old instance of MediaWikiServices will be re-used. If there
182 * was no previous instance, a new GlobalVarConfig object will be used to
183 * bootstrap the services.
185 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
186 * See SalvageableService for details.
188 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
189 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
192 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
193 if ( self
::$instance === null ) {
194 // no global instance yet, nothing to reset
198 self
::failIfResetNotAllowed( __METHOD__
);
200 if ( $bootstrapConfig === null ) {
201 $bootstrapConfig = self
::$instance->getBootstrapConfig();
204 $oldInstance = self
::$instance;
206 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
207 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
209 if ( $quick === 'quick' ) {
210 self
::$instance->salvage( $oldInstance );
212 $oldInstance->destroy();
217 * Salvages the state of any salvageable service instances in $other.
219 * @note $other will have been destroyed when salvage() returns.
221 * @param MediaWikiServices $other
223 private function salvage( self
$other ) {
224 foreach ( $this->getServiceNames() as $name ) {
225 // The service could be new in the new instance and not registered in the
226 // other instance (e.g. an extension that was loaded after the instantiation of
227 // the other instance. Skip this service in this case. See T143974
229 $oldService = $other->peekService( $name );
230 } catch ( NoSuchServiceException
$e ) {
234 if ( $oldService instanceof SalvageableService
) {
235 /** @var SalvageableService $newService */
236 $newService = $this->getService( $name );
237 $newService->salvage( $oldService );
245 * Creates a new MediaWikiServices instance and initializes it according to the
246 * given $bootstrapConfig. In particular, all wiring files defined in the
247 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
249 * @param Config|null $bootstrapConfig The Config object to be registered as the
250 * 'BootstrapConfig' service.
252 * @param string $loadWiring set this to 'load' to load the wiring files specified
253 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
255 * @return MediaWikiServices
256 * @throws MWException
257 * @throws \FatalError
259 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
260 $instance = new self( $bootstrapConfig );
262 // Load the default wiring from the specified files.
263 if ( $loadWiring === 'load' ) {
264 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
265 $instance->loadWiringFiles( $wiringFiles );
268 // Provide a traditional hook point to allow extensions to configure services.
269 Hooks
::run( 'MediaWikiServices', [ $instance ] );
275 * Disables all storage layer services. After calling this, any attempt to access the
276 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
281 * @warning This is intended for extreme situations only and should never be used
282 * while serving normal web requests. Legitimate use cases for this method include
283 * the installation process. Test fixtures may also use this, if the fixture relies
286 * @see resetGlobalInstance()
287 * @see resetChildProcessServices()
289 public static function disableStorageBackend() {
290 // TODO: also disable some Caches, JobQueues, etc
291 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
292 $services = self
::getInstance();
294 foreach ( $destroy as $name ) {
295 $services->disableService( $name );
298 ObjectCache
::clear();
302 * Resets any services that may have become stale after a child process
303 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
304 * to call this method from the parent process.
308 * @note This is intended for use in the context of process forking only!
310 * @see resetGlobalInstance()
311 * @see disableStorageBackend()
313 public static function resetChildProcessServices() {
314 // NOTE: for now, just reset everything. Since we don't know the interdependencies
315 // between services, we can't do this more selectively at this time.
316 self
::resetGlobalInstance();
318 // Child, reseed because there is no bug in PHP:
319 // https://bugs.php.net/bug.php?id=42465
320 mt_srand( getmypid() );
324 * Resets the given service for testing purposes.
328 * @warning This is generally unsafe! Other services may still retain references
329 * to the stale service instance, leading to failures and inconsistencies. Subclasses
330 * may use this method to reset specific services under specific instances, but
331 * it should not be exposed to application logic.
333 * @note With proper dependency injection used throughout the codebase, this method
334 * should not be needed. It is provided to allow tests that pollute global service
335 * instances to clean up.
337 * @param string $name
338 * @param bool $destroy Whether the service instance should be destroyed if it exists.
339 * When set to false, any existing service instance will effectively be detached
340 * from the container.
342 * @throws MWException if called outside of PHPUnit tests.
344 public function resetServiceForTesting( $name, $destroy = true ) {
345 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
346 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
349 $this->resetService( $name, $destroy );
353 * Convenience method that throws an exception unless it is called during a phase in which
354 * resetting of global services is allowed. In general, services should not be reset
355 * individually, since that may introduce inconsistencies.
359 * This method will throw an exception if:
361 * - self::$resetInProgress is false (to allow all services to be reset together
362 * via resetGlobalInstance)
363 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
364 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
366 * This method is intended to be used to safeguard against accidentally resetting
367 * global service instances that are not yet managed by MediaWikiServices. It is
368 * defined here in the MediaWikiServices services class to have a central place
369 * for managing service bootstrapping and resetting.
371 * @param string $method the name of the caller method, as given by __METHOD__.
373 * @throws MWException if called outside bootstrap mode.
375 * @see resetGlobalInstance()
376 * @see forceGlobalInstance()
377 * @see disableStorageBackend()
379 public static function failIfResetNotAllowed( $method ) {
380 if ( !defined( 'MW_PHPUNIT_TEST' )
381 && !defined( 'MW_PARSER_TEST' )
382 && !defined( 'MEDIAWIKI_INSTALL' )
383 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
384 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
386 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
391 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
392 * This has to contain at least the information needed to set up the 'ConfigFactory'
395 public function __construct( Config
$config ) {
396 parent
::__construct();
398 // Register the given Config object as the bootstrap config service.
399 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
404 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
408 * @return ActorMigration
410 public function getActorMigration() {
411 return $this->getService( 'ActorMigration' );
418 public function getBlobStore() {
419 return $this->getService( '_SqlBlobStore' );
424 * @return BlobStoreFactory
426 public function getBlobStoreFactory() {
427 return $this->getService( 'BlobStoreFactory' );
431 * Returns the Config object containing the bootstrap configuration.
432 * Bootstrap configuration would typically include database credentials
433 * and other information that may be needed before the ConfigFactory
434 * service can be instantiated.
436 * @note This should only be used during bootstrapping, in particular
437 * when creating the MainConfig service. Application logic should
438 * use getMainConfig() to get a Config instances.
443 public function getBootstrapConfig() {
444 return $this->getService( 'BootstrapConfig' );
449 * @return NameTableStore
451 public function getChangeTagDefStore() {
452 return $this->getService( 'ChangeTagDefStore' );
457 * @return CommentStore
459 public function getCommentStore() {
460 return $this->getService( 'CommentStore' );
465 * @return ConfigFactory
467 public function getConfigFactory() {
468 return $this->getService( 'ConfigFactory' );
473 * @return ConfigRepository
475 public function getConfigRepository() {
476 return $this->getService( 'ConfigRepository' );
481 * @return \ConfiguredReadOnlyMode
483 public function getConfiguredReadOnlyMode() {
484 return $this->getService( 'ConfiguredReadOnlyMode' );
491 public function getContentLanguage() {
492 return $this->getService( 'ContentLanguage' );
497 * @return NameTableStore
499 public function getContentModelStore() {
500 return $this->getService( 'ContentModelStore' );
507 public function getCryptHKDF() {
508 return $this->getService( 'CryptHKDF' );
513 * @deprecated since 1.32, use random_bytes()/random_int()
516 public function getCryptRand() {
517 return $this->getService( 'CryptRand' );
522 * @return LoadBalancer The main DB load balancer for the local wiki.
524 public function getDBLoadBalancer() {
525 return $this->getService( 'DBLoadBalancer' );
532 public function getDBLoadBalancerFactory() {
533 return $this->getService( 'DBLoadBalancerFactory' );
538 * @return EventRelayerGroup
540 public function getEventRelayerGroup() {
541 return $this->getService( 'EventRelayerGroup' );
546 * @return \ExternalStoreFactory
548 public function getExternalStoreFactory() {
549 return $this->getService( 'ExternalStoreFactory' );
554 * @return GenderCache
556 public function getGenderCache() {
557 return $this->getService( 'GenderCache' );
562 * @return HttpRequestFactory
564 public function getHttpRequestFactory() {
565 return $this->getService( 'HttpRequestFactory' );
570 * @return InterwikiLookup
572 public function getInterwikiLookup() {
573 return $this->getService( 'InterwikiLookup' );
580 public function getLinkCache() {
581 return $this->getService( 'LinkCache' );
585 * LinkRenderer instance that can be used
586 * if no custom options are needed
589 * @return LinkRenderer
591 public function getLinkRenderer() {
592 return $this->getService( 'LinkRenderer' );
597 * @return LinkRendererFactory
599 public function getLinkRendererFactory() {
600 return $this->getService( 'LinkRendererFactory' );
607 public function getLocalServerObjectCache() {
608 return $this->getService( 'LocalServerObjectCache' );
613 * @return MagicWordFactory
615 public function getMagicWordFactory() {
616 return $this->getService( 'MagicWordFactory' );
620 * Returns the Config object that provides configuration for MediaWiki core.
621 * This may or may not be the same object that is returned by getBootstrapConfig().
626 public function getMainConfig() {
627 return $this->getService( 'MainConfig' );
634 public function getMainObjectStash() {
635 return $this->getService( 'MainObjectStash' );
640 * @return \WANObjectCache
642 public function getMainWANObjectCache() {
643 return $this->getService( 'MainWANObjectCache' );
648 * @return MediaHandlerFactory
650 public function getMediaHandlerFactory() {
651 return $this->getService( 'MediaHandlerFactory' );
656 * @return MimeAnalyzer
658 public function getMimeAnalyzer() {
659 return $this->getService( 'MimeAnalyzer' );
664 * @return OldRevisionImporter
666 public function getOldRevisionImporter() {
667 return $this->getService( 'OldRevisionImporter' );
674 public function getParser() {
675 return $this->getService( 'Parser' );
680 * @return ParserCache
682 public function getParserCache() {
683 return $this->getService( 'ParserCache' );
688 * @return ParserFactory
690 public function getParserFactory() {
691 return $this->getService( 'ParserFactory' );
696 * @return PasswordFactory
698 public function getPasswordFactory() {
699 return $this->getService( 'PasswordFactory' );
704 * @return IBufferingStatsdDataFactory
706 public function getPerDbNameStatsdDataFactory() {
707 return $this->getService( 'PerDbNameStatsdDataFactory' );
712 * @return PreferencesFactory
714 public function getPreferencesFactory() {
715 return $this->getService( 'PreferencesFactory' );
720 * @return ProxyLookup
722 public function getProxyLookup() {
723 return $this->getService( 'ProxyLookup' );
728 * @return \ReadOnlyMode
730 public function getReadOnlyMode() {
731 return $this->getService( 'ReadOnlyMode' );
736 * @return RevisionFactory
738 public function getRevisionFactory() {
739 return $this->getService( 'RevisionFactory' );
744 * @return RevisionLookup
746 public function getRevisionLookup() {
747 return $this->getService( 'RevisionLookup' );
752 * @return RevisionStore
754 public function getRevisionStore() {
755 return $this->getService( 'RevisionStore' );
760 * @return RevisionStoreFactory
762 public function getRevisionStoreFactory() {
763 return $this->getService( 'RevisionStoreFactory' );
768 * @return SearchEngine
770 public function newSearchEngine() {
771 // New engine object every time, since they keep state
772 return $this->getService( 'SearchEngineFactory' )->create();
777 * @return SearchEngineConfig
779 public function getSearchEngineConfig() {
780 return $this->getService( 'SearchEngineConfig' );
785 * @return SearchEngineFactory
787 public function getSearchEngineFactory() {
788 return $this->getService( 'SearchEngineFactory' );
793 * @return CommandFactory
795 public function getShellCommandFactory() {
796 return $this->getService( 'ShellCommandFactory' );
803 public function getSiteLookup() {
804 return $this->getService( 'SiteLookup' );
811 public function getSiteStore() {
812 return $this->getService( 'SiteStore' );
817 * @return SkinFactory
819 public function getSkinFactory() {
820 return $this->getService( 'SkinFactory' );
825 * @return NameTableStore
827 public function getSlotRoleStore() {
828 return $this->getService( 'SlotRoleStore' );
833 * @return IBufferingStatsdDataFactory
835 public function getStatsdDataFactory() {
836 return $this->getService( 'StatsdDataFactory' );
841 * @return TitleFormatter
843 public function getTitleFormatter() {
844 return $this->getService( 'TitleFormatter' );
849 * @return TitleParser
851 public function getTitleParser() {
852 return $this->getService( 'TitleParser' );
857 * @return UploadRevisionImporter
859 public function getUploadRevisionImporter() {
860 return $this->getService( 'UploadRevisionImporter' );
865 * @return VirtualRESTServiceClient
867 public function getVirtualRESTServiceClient() {
868 return $this->getService( 'VirtualRESTServiceClient' );
873 * @return WatchedItemQueryService
875 public function getWatchedItemQueryService() {
876 return $this->getService( 'WatchedItemQueryService' );
881 * @return WatchedItemStoreInterface
883 public function getWatchedItemStore() {
884 return $this->getService( 'WatchedItemStore' );
889 * @return \OldRevisionImporter
891 public function getWikiRevisionOldRevisionImporter() {
892 return $this->getService( 'OldRevisionImporter' );
897 * @return \OldRevisionImporter
899 public function getWikiRevisionOldRevisionImporterNoUpdates() {
900 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
905 * @return \UploadRevisionImporter
907 public function getWikiRevisionUploadImporter() {
908 return $this->getService( 'UploadRevisionImporter' );