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 Wikimedia\Rdbms\LBFactory
;
26 use Wikimedia\Rdbms\LoadBalancer
;
27 use MediaHandlerFactory
;
28 use MediaWiki\Linker\LinkRenderer
;
29 use MediaWiki\Linker\LinkRendererFactory
;
30 use MediaWiki\Services\SalvageableService
;
31 use MediaWiki\Services\ServiceContainer
;
32 use MediaWiki\Services\NoSuchServiceException
;
40 use SearchEngineConfig
;
41 use SearchEngineFactory
;
44 use WatchedItemStoreInterface
;
45 use WatchedItemQueryService
;
49 use VirtualRESTServiceClient
;
50 use MediaWiki\Interwiki\InterwikiLookup
;
53 * Service locator for MediaWiki core services.
55 * This program is free software; you can redistribute it and/or modify
56 * it under the terms of the GNU General Public License as published by
57 * the Free Software Foundation; either version 2 of the License, or
58 * (at your option) any later version.
60 * This program is distributed in the hope that it will be useful,
61 * but WITHOUT ANY WARRANTY; without even the implied warranty of
62 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
63 * GNU General Public License for more details.
65 * You should have received a copy of the GNU General Public License along
66 * with this program; if not, write to the Free Software Foundation, Inc.,
67 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
68 * http://www.gnu.org/copyleft/gpl.html
76 * MediaWikiServices is the service locator for the application scope of MediaWiki.
77 * Its implemented as a simple configurable DI container.
78 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
79 * the network of service objects that defines MediaWiki's application logic.
80 * It acts as an entry point to MediaWiki's dependency injection mechanism.
82 * Services are defined in the "wiring" array passed to the constructor,
83 * or by calling defineService().
85 * @see docs/injection.txt for an overview of using dependency injection in the
86 * MediaWiki code base.
88 class MediaWikiServices
extends ServiceContainer
{
91 * @var MediaWikiServices|null
93 private static $instance = null;
96 * Returns the global default instance of the top level service locator.
100 * The default instance is initialized using the service instantiator functions
101 * defined in ServiceWiring.php.
103 * @note This should only be called by static functions! The instance returned here
104 * should not be passed around! Objects that need access to a service should have
105 * that service injected into the constructor, never a service locator!
107 * @return MediaWikiServices
109 public static function getInstance() {
110 if ( self
::$instance === null ) {
111 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
112 // but some information from the global scope has to be injected here,
113 // even if it's just a file name or database credentials to load
114 // configuration from.
115 $bootstrapConfig = new GlobalVarConfig();
116 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
119 return self
::$instance;
123 * Replaces the global MediaWikiServices instance.
127 * @note This is for use in PHPUnit tests only!
129 * @throws MWException if called outside of PHPUnit tests.
131 * @param MediaWikiServices $services The new MediaWikiServices object.
133 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
135 public static function forceGlobalInstance( MediaWikiServices
$services ) {
136 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
137 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
140 $old = self
::getInstance();
141 self
::$instance = $services;
147 * Creates a new instance of MediaWikiServices and sets it as the global default
148 * instance. getInstance() will return a different MediaWikiServices object
149 * after every call to resetGlobalInstance().
153 * @warning This should not be used during normal operation. It is intended for use
154 * when the configuration has changed significantly since bootstrap time, e.g.
155 * during the installation process or during testing.
157 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
158 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
159 * any of the services managed by MediaWikiServices exist. If any service objects
160 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
161 * with the operation of the services managed by the new MediaWikiServices.
162 * Operating with a mix of services created by the old and the new
163 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
164 * Any class implementing LAZY LOADING is especially prone to this problem,
165 * since instances would typically retain a reference to a storage layer service.
167 * @see forceGlobalInstance()
168 * @see resetGlobalInstance()
169 * @see resetBetweenTest()
171 * @param Config|null $bootstrapConfig The Config object to be registered as the
172 * 'BootstrapConfig' service. This has to contain at least the information
173 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
174 * config of the old instance of MediaWikiServices will be re-used. If there
175 * was no previous instance, a new GlobalVarConfig object will be used to
176 * bootstrap the services.
178 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
179 * See SalvageableService for details.
181 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
182 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
185 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
186 if ( self
::$instance === null ) {
187 // no global instance yet, nothing to reset
191 self
::failIfResetNotAllowed( __METHOD__
);
193 if ( $bootstrapConfig === null ) {
194 $bootstrapConfig = self
::$instance->getBootstrapConfig();
197 $oldInstance = self
::$instance;
199 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
200 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
202 if ( $quick === 'quick' ) {
203 self
::$instance->salvage( $oldInstance );
205 $oldInstance->destroy();
210 * Salvages the state of any salvageable service instances in $other.
212 * @note $other will have been destroyed when salvage() returns.
214 * @param MediaWikiServices $other
216 private function salvage( self
$other ) {
217 foreach ( $this->getServiceNames() as $name ) {
218 // The service could be new in the new instance and not registered in the
219 // other instance (e.g. an extension that was loaded after the instantiation of
220 // the other instance. Skip this service in this case. See T143974
222 $oldService = $other->peekService( $name );
223 } catch ( NoSuchServiceException
$e ) {
227 if ( $oldService instanceof SalvageableService
) {
228 /** @var SalvageableService $newService */
229 $newService = $this->getService( $name );
230 $newService->salvage( $oldService );
238 * Creates a new MediaWikiServices instance and initializes it according to the
239 * given $bootstrapConfig. In particular, all wiring files defined in the
240 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
242 * @param Config|null $bootstrapConfig The Config object to be registered as the
243 * 'BootstrapConfig' service.
245 * @param string $loadWiring set this to 'load' to load the wiring files specified
246 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
248 * @return MediaWikiServices
249 * @throws MWException
250 * @throws \FatalError
252 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
253 $instance = new self( $bootstrapConfig );
255 // Load the default wiring from the specified files.
256 if ( $loadWiring === 'load' ) {
257 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
258 $instance->loadWiringFiles( $wiringFiles );
261 // Provide a traditional hook point to allow extensions to configure services.
262 Hooks
::run( 'MediaWikiServices', [ $instance ] );
268 * Disables all storage layer services. After calling this, any attempt to access the
269 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
274 * @warning This is intended for extreme situations only and should never be used
275 * while serving normal web requests. Legitimate use cases for this method include
276 * the installation process. Test fixtures may also use this, if the fixture relies
279 * @see resetGlobalInstance()
280 * @see resetChildProcessServices()
282 public static function disableStorageBackend() {
283 // TODO: also disable some Caches, JobQueues, etc
284 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
285 $services = self
::getInstance();
287 foreach ( $destroy as $name ) {
288 $services->disableService( $name );
291 ObjectCache
::clear();
295 * Resets any services that may have become stale after a child process
296 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
297 * to call this method from the parent process.
301 * @note This is intended for use in the context of process forking only!
303 * @see resetGlobalInstance()
304 * @see disableStorageBackend()
306 public static function resetChildProcessServices() {
307 // NOTE: for now, just reset everything. Since we don't know the interdependencies
308 // between services, we can't do this more selectively at this time.
309 self
::resetGlobalInstance();
311 // Child, reseed because there is no bug in PHP:
312 // https://bugs.php.net/bug.php?id=42465
313 mt_srand( getmypid() );
317 * Resets the given service for testing purposes.
321 * @warning This is generally unsafe! Other services may still retain references
322 * to the stale service instance, leading to failures and inconsistencies. Subclasses
323 * may use this method to reset specific services under specific instances, but
324 * it should not be exposed to application logic.
326 * @note With proper dependency injection used throughout the codebase, this method
327 * should not be needed. It is provided to allow tests that pollute global service
328 * instances to clean up.
330 * @param string $name
331 * @param bool $destroy Whether the service instance should be destroyed if it exists.
332 * When set to false, any existing service instance will effectively be detached
333 * from the container.
335 * @throws MWException if called outside of PHPUnit tests.
337 public function resetServiceForTesting( $name, $destroy = true ) {
338 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
339 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
342 $this->resetService( $name, $destroy );
346 * Convenience method that throws an exception unless it is called during a phase in which
347 * resetting of global services is allowed. In general, services should not be reset
348 * individually, since that may introduce inconsistencies.
352 * This method will throw an exception if:
354 * - self::$resetInProgress is false (to allow all services to be reset together
355 * via resetGlobalInstance)
356 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
357 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
359 * This method is intended to be used to safeguard against accidentally resetting
360 * global service instances that are not yet managed by MediaWikiServices. It is
361 * defined here in the MediaWikiServices services class to have a central place
362 * for managing service bootstrapping and resetting.
364 * @param string $method the name of the caller method, as given by __METHOD__.
366 * @throws MWException if called outside bootstrap mode.
368 * @see resetGlobalInstance()
369 * @see forceGlobalInstance()
370 * @see disableStorageBackend()
372 public static function failIfResetNotAllowed( $method ) {
373 if ( !defined( 'MW_PHPUNIT_TEST' )
374 && !defined( 'MW_PARSER_TEST' )
375 && !defined( 'MEDIAWIKI_INSTALL' )
376 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
377 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
379 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
384 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
385 * This has to contain at least the information needed to set up the 'ConfigFactory'
388 public function __construct( Config
$config ) {
389 parent
::__construct();
391 // Register the given Config object as the bootstrap config service.
392 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
397 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
400 * Returns the Config object containing the bootstrap configuration.
401 * Bootstrap configuration would typically include database credentials
402 * and other information that may be needed before the ConfigFactory
403 * service can be instantiated.
405 * @note This should only be used during bootstrapping, in particular
406 * when creating the MainConfig service. Application logic should
407 * use getMainConfig() to get a Config instances.
412 public function getBootstrapConfig() {
413 return $this->getService( 'BootstrapConfig' );
418 * @return ConfigFactory
420 public function getConfigFactory() {
421 return $this->getService( 'ConfigFactory' );
425 * Returns the Config object that provides configuration for MediaWiki core.
426 * This may or may not be the same object that is returned by getBootstrapConfig().
431 public function getMainConfig() {
432 return $this->getService( 'MainConfig' );
439 public function getSiteLookup() {
440 return $this->getService( 'SiteLookup' );
447 public function getSiteStore() {
448 return $this->getService( 'SiteStore' );
453 * @return InterwikiLookup
455 public function getInterwikiLookup() {
456 return $this->getService( 'InterwikiLookup' );
461 * @return IBufferingStatsdDataFactory
463 public function getStatsdDataFactory() {
464 return $this->getService( 'StatsdDataFactory' );
469 * @return EventRelayerGroup
471 public function getEventRelayerGroup() {
472 return $this->getService( 'EventRelayerGroup' );
477 * @return SearchEngine
479 public function newSearchEngine() {
480 // New engine object every time, since they keep state
481 return $this->getService( 'SearchEngineFactory' )->create();
486 * @return SearchEngineFactory
488 public function getSearchEngineFactory() {
489 return $this->getService( 'SearchEngineFactory' );
494 * @return SearchEngineConfig
496 public function getSearchEngineConfig() {
497 return $this->getService( 'SearchEngineConfig' );
502 * @return SkinFactory
504 public function getSkinFactory() {
505 return $this->getService( 'SkinFactory' );
512 public function getDBLoadBalancerFactory() {
513 return $this->getService( 'DBLoadBalancerFactory' );
518 * @return LoadBalancer The main DB load balancer for the local wiki.
520 public function getDBLoadBalancer() {
521 return $this->getService( 'DBLoadBalancer' );
526 * @return WatchedItemStoreInterface
528 public function getWatchedItemStore() {
529 return $this->getService( 'WatchedItemStore' );
534 * @return WatchedItemQueryService
536 public function getWatchedItemQueryService() {
537 return $this->getService( 'WatchedItemQueryService' );
542 * @deprecated since 1.32, use random_bytes()/random_int()
545 public function getCryptRand() {
546 return $this->getService( 'CryptRand' );
553 public function getCryptHKDF() {
554 return $this->getService( 'CryptHKDF' );
559 * @return MediaHandlerFactory
561 public function getMediaHandlerFactory() {
562 return $this->getService( 'MediaHandlerFactory' );
567 * @return MimeAnalyzer
569 public function getMimeAnalyzer() {
570 return $this->getService( 'MimeAnalyzer' );
575 * @return ProxyLookup
577 public function getProxyLookup() {
578 return $this->getService( 'ProxyLookup' );
585 public function getParser() {
586 return $this->getService( 'Parser' );
591 * @return ParserCache
593 public function getParserCache() {
594 return $this->getService( 'ParserCache' );
599 * @return GenderCache
601 public function getGenderCache() {
602 return $this->getService( 'GenderCache' );
609 public function getLinkCache() {
610 return $this->getService( 'LinkCache' );
615 * @return LinkRendererFactory
617 public function getLinkRendererFactory() {
618 return $this->getService( 'LinkRendererFactory' );
622 * LinkRenderer instance that can be used
623 * if no custom options are needed
626 * @return LinkRenderer
628 public function getLinkRenderer() {
629 return $this->getService( 'LinkRenderer' );
634 * @return TitleFormatter
636 public function getTitleFormatter() {
637 return $this->getService( 'TitleFormatter' );
642 * @return TitleParser
644 public function getTitleParser() {
645 return $this->getService( 'TitleParser' );
652 public function getMainObjectStash() {
653 return $this->getService( 'MainObjectStash' );
658 * @return \WANObjectCache
660 public function getMainWANObjectCache() {
661 return $this->getService( 'MainWANObjectCache' );
668 public function getLocalServerObjectCache() {
669 return $this->getService( 'LocalServerObjectCache' );
674 * @return VirtualRESTServiceClient
676 public function getVirtualRESTServiceClient() {
677 return $this->getService( 'VirtualRESTServiceClient' );
682 * @return \ConfiguredReadOnlyMode
684 public function getConfiguredReadOnlyMode() {
685 return $this->getService( 'ConfiguredReadOnlyMode' );
690 * @return \ReadOnlyMode
692 public function getReadOnlyMode() {
693 return $this->getService( 'ReadOnlyMode' );
698 * @return \UploadRevisionImporter
700 public function getWikiRevisionUploadImporter() {
701 return $this->getService( 'UploadRevisionImporter' );
706 * @return \OldRevisionImporter
708 public function getWikiRevisionOldRevisionImporter() {
709 return $this->getService( 'OldRevisionImporter' );
714 * @return \OldRevisionImporter
716 public function getWikiRevisionOldRevisionImporterNoUpdates() {
717 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
722 * @return CommandFactory
724 public function getShellCommandFactory() {
725 return $this->getService( 'ShellCommandFactory' );
730 * @return \ExternalStoreFactory
732 public function getExternalStoreFactory() {
733 return $this->getService( 'ExternalStoreFactory' );
738 * @return BlobStoreFactory
740 public function getBlobStoreFactory() {
741 return $this->getService( 'BlobStoreFactory' );
748 public function getBlobStore() {
749 return $this->getService( '_SqlBlobStore' );
754 * @return RevisionStore
756 public function getRevisionStore() {
757 return $this->getService( 'RevisionStore' );
762 * @return RevisionLookup
764 public function getRevisionLookup() {
765 return $this->getService( 'RevisionLookup' );
770 * @return RevisionFactory
772 public function getRevisionFactory() {
773 return $this->getService( 'RevisionFactory' );
778 * @return NameTableStore
780 public function getContentModelStore() {
781 return $this->getService( 'ContentModelStore' );
786 * @return NameTableStore
788 public function getSlotRoleStore() {
789 return $this->getService( 'SlotRoleStore' );
794 * @return PreferencesFactory
796 public function getPreferencesFactory() {
797 return $this->getService( 'PreferencesFactory' );
802 * @return HttpRequestFactory
804 public function getHttpRequestFactory() {
805 return $this->getService( 'HttpRequestFactory' );
810 * @return CommentStore
812 public function getCommentStore() {
813 return $this->getService( 'CommentStore' );
818 * @return ActorMigration
820 public function getActorMigration() {
821 return $this->getService( 'ActorMigration' );
824 ///////////////////////////////////////////////////////////////////////////
825 // NOTE: When adding a service getter here, don't forget to add a test
826 // case for it in MediaWikiServicesTest::provideGetters() and in
827 // MediaWikiServicesTest::provideGetService()!
828 ///////////////////////////////////////////////////////////////////////////