12 use IBufferingStatsdDataFactory
;
13 use MediaWiki\Http\HttpRequestFactory
;
14 use MediaWiki\Preferences\PreferencesFactory
;
15 use MediaWiki\Shell\CommandFactory
;
16 use MediaWiki\Storage\BlobStore
;
17 use MediaWiki\Storage\BlobStoreFactory
;
18 use MediaWiki\Storage\RevisionStore
;
19 use Wikimedia\Rdbms\LBFactory
;
21 use Wikimedia\Rdbms\LoadBalancer
;
22 use MediaHandlerFactory
;
23 use MediaWiki\Linker\LinkRenderer
;
24 use MediaWiki\Linker\LinkRendererFactory
;
25 use MediaWiki\Services\SalvageableService
;
26 use MediaWiki\Services\ServiceContainer
;
27 use MediaWiki\Services\NoSuchServiceException
;
35 use SearchEngineConfig
;
36 use SearchEngineFactory
;
39 use WatchedItemStoreInterface
;
40 use WatchedItemQueryService
;
44 use VirtualRESTServiceClient
;
45 use MediaWiki\Interwiki\InterwikiLookup
;
48 * Service locator for MediaWiki core services.
50 * This program is free software; you can redistribute it and/or modify
51 * it under the terms of the GNU General Public License as published by
52 * the Free Software Foundation; either version 2 of the License, or
53 * (at your option) any later version.
55 * This program is distributed in the hope that it will be useful,
56 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58 * GNU General Public License for more details.
60 * You should have received a copy of the GNU General Public License along
61 * with this program; if not, write to the Free Software Foundation, Inc.,
62 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
63 * http://www.gnu.org/copyleft/gpl.html
71 * MediaWikiServices is the service locator for the application scope of MediaWiki.
72 * Its implemented as a simple configurable DI container.
73 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
74 * the network of service objects that defines MediaWiki's application logic.
75 * It acts as an entry point to MediaWiki's dependency injection mechanism.
77 * Services are defined in the "wiring" array passed to the constructor,
78 * or by calling defineService().
80 * @see docs/injection.txt for an overview of using dependency injection in the
81 * MediaWiki code base.
83 class MediaWikiServices
extends ServiceContainer
{
86 * @var MediaWikiServices|null
88 private static $instance = null;
91 * Returns the global default instance of the top level service locator.
95 * The default instance is initialized using the service instantiator functions
96 * defined in ServiceWiring.php.
98 * @note This should only be called by static functions! The instance returned here
99 * should not be passed around! Objects that need access to a service should have
100 * that service injected into the constructor, never a service locator!
102 * @return MediaWikiServices
104 public static function getInstance() {
105 if ( self
::$instance === null ) {
106 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
107 // but some information from the global scope has to be injected here,
108 // even if it's just a file name or database credentials to load
109 // configuration from.
110 $bootstrapConfig = new GlobalVarConfig();
111 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
114 return self
::$instance;
118 * Replaces the global MediaWikiServices instance.
122 * @note This is for use in PHPUnit tests only!
124 * @throws MWException if called outside of PHPUnit tests.
126 * @param MediaWikiServices $services The new MediaWikiServices object.
128 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
130 public static function forceGlobalInstance( MediaWikiServices
$services ) {
131 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
132 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
135 $old = self
::getInstance();
136 self
::$instance = $services;
142 * Creates a new instance of MediaWikiServices and sets it as the global default
143 * instance. getInstance() will return a different MediaWikiServices object
144 * after every call to resetGlobalInstance().
148 * @warning This should not be used during normal operation. It is intended for use
149 * when the configuration has changed significantly since bootstrap time, e.g.
150 * during the installation process or during testing.
152 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
153 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
154 * any of the services managed by MediaWikiServices exist. If any service objects
155 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
156 * with the operation of the services managed by the new MediaWikiServices.
157 * Operating with a mix of services created by the old and the new
158 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
159 * Any class implementing LAZY LOADING is especially prone to this problem,
160 * since instances would typically retain a reference to a storage layer service.
162 * @see forceGlobalInstance()
163 * @see resetGlobalInstance()
164 * @see resetBetweenTest()
166 * @param Config|null $bootstrapConfig The Config object to be registered as the
167 * 'BootstrapConfig' service. This has to contain at least the information
168 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
169 * config of the old instance of MediaWikiServices will be re-used. If there
170 * was no previous instance, a new GlobalVarConfig object will be used to
171 * bootstrap the services.
173 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
174 * See SalvageableService for details.
176 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
177 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
180 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
181 if ( self
::$instance === null ) {
182 // no global instance yet, nothing to reset
186 self
::failIfResetNotAllowed( __METHOD__
);
188 if ( $bootstrapConfig === null ) {
189 $bootstrapConfig = self
::$instance->getBootstrapConfig();
192 $oldInstance = self
::$instance;
194 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
195 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
197 if ( $quick === 'quick' ) {
198 self
::$instance->salvage( $oldInstance );
200 $oldInstance->destroy();
205 * Salvages the state of any salvageable service instances in $other.
207 * @note $other will have been destroyed when salvage() returns.
209 * @param MediaWikiServices $other
211 private function salvage( self
$other ) {
212 foreach ( $this->getServiceNames() as $name ) {
213 // The service could be new in the new instance and not registered in the
214 // other instance (e.g. an extension that was loaded after the instantiation of
215 // the other instance. Skip this service in this case. See T143974
217 $oldService = $other->peekService( $name );
218 } catch ( NoSuchServiceException
$e ) {
222 if ( $oldService instanceof SalvageableService
) {
223 /** @var SalvageableService $newService */
224 $newService = $this->getService( $name );
225 $newService->salvage( $oldService );
233 * Creates a new MediaWikiServices instance and initializes it according to the
234 * given $bootstrapConfig. In particular, all wiring files defined in the
235 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
237 * @param Config|null $bootstrapConfig The Config object to be registered as the
238 * 'BootstrapConfig' service.
240 * @param string $loadWiring set this to 'load' to load the wiring files specified
241 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
243 * @return MediaWikiServices
244 * @throws MWException
245 * @throws \FatalError
247 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
248 $instance = new self( $bootstrapConfig );
250 // Load the default wiring from the specified files.
251 if ( $loadWiring === 'load' ) {
252 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
253 $instance->loadWiringFiles( $wiringFiles );
256 // Provide a traditional hook point to allow extensions to configure services.
257 Hooks
::run( 'MediaWikiServices', [ $instance ] );
263 * Disables all storage layer services. After calling this, any attempt to access the
264 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
269 * @warning This is intended for extreme situations only and should never be used
270 * while serving normal web requests. Legitimate use cases for this method include
271 * the installation process. Test fixtures may also use this, if the fixture relies
274 * @see resetGlobalInstance()
275 * @see resetChildProcessServices()
277 public static function disableStorageBackend() {
278 // TODO: also disable some Caches, JobQueues, etc
279 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
280 $services = self
::getInstance();
282 foreach ( $destroy as $name ) {
283 $services->disableService( $name );
286 ObjectCache
::clear();
290 * Resets any services that may have become stale after a child process
291 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
292 * to call this method from the parent process.
296 * @note This is intended for use in the context of process forking only!
298 * @see resetGlobalInstance()
299 * @see disableStorageBackend()
301 public static function resetChildProcessServices() {
302 // NOTE: for now, just reset everything. Since we don't know the interdependencies
303 // between services, we can't do this more selectively at this time.
304 self
::resetGlobalInstance();
306 // Child, reseed because there is no bug in PHP:
307 // https://bugs.php.net/bug.php?id=42465
308 mt_srand( getmypid() );
312 * Resets the given service for testing purposes.
316 * @warning This is generally unsafe! Other services may still retain references
317 * to the stale service instance, leading to failures and inconsistencies. Subclasses
318 * may use this method to reset specific services under specific instances, but
319 * it should not be exposed to application logic.
321 * @note With proper dependency injection used throughout the codebase, this method
322 * should not be needed. It is provided to allow tests that pollute global service
323 * instances to clean up.
325 * @param string $name
326 * @param bool $destroy Whether the service instance should be destroyed if it exists.
327 * When set to false, any existing service instance will effectively be detached
328 * from the container.
330 * @throws MWException if called outside of PHPUnit tests.
332 public function resetServiceForTesting( $name, $destroy = true ) {
333 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
334 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
337 $this->resetService( $name, $destroy );
341 * Convenience method that throws an exception unless it is called during a phase in which
342 * resetting of global services is allowed. In general, services should not be reset
343 * individually, since that may introduce inconsistencies.
347 * This method will throw an exception if:
349 * - self::$resetInProgress is false (to allow all services to be reset together
350 * via resetGlobalInstance)
351 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
352 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
354 * This method is intended to be used to safeguard against accidentally resetting
355 * global service instances that are not yet managed by MediaWikiServices. It is
356 * defined here in the MediaWikiServices services class to have a central place
357 * for managing service bootstrapping and resetting.
359 * @param string $method the name of the caller method, as given by __METHOD__.
361 * @throws MWException if called outside bootstrap mode.
363 * @see resetGlobalInstance()
364 * @see forceGlobalInstance()
365 * @see disableStorageBackend()
367 public static function failIfResetNotAllowed( $method ) {
368 if ( !defined( 'MW_PHPUNIT_TEST' )
369 && !defined( 'MW_PARSER_TEST' )
370 && !defined( 'MEDIAWIKI_INSTALL' )
371 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
372 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
374 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
379 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
380 * This has to contain at least the information needed to set up the 'ConfigFactory'
383 public function __construct( Config
$config ) {
384 parent
::__construct();
386 // Register the given Config object as the bootstrap config service.
387 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
392 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
395 * Returns the Config object containing the bootstrap configuration.
396 * Bootstrap configuration would typically include database credentials
397 * and other information that may be needed before the ConfigFactory
398 * service can be instantiated.
400 * @note This should only be used during bootstrapping, in particular
401 * when creating the MainConfig service. Application logic should
402 * use getMainConfig() to get a Config instances.
407 public function getBootstrapConfig() {
408 return $this->getService( 'BootstrapConfig' );
413 * @return ConfigFactory
415 public function getConfigFactory() {
416 return $this->getService( 'ConfigFactory' );
420 * Returns the Config object that provides configuration for MediaWiki core.
421 * This may or may not be the same object that is returned by getBootstrapConfig().
426 public function getMainConfig() {
427 return $this->getService( 'MainConfig' );
434 public function getSiteLookup() {
435 return $this->getService( 'SiteLookup' );
442 public function getSiteStore() {
443 return $this->getService( 'SiteStore' );
448 * @return InterwikiLookup
450 public function getInterwikiLookup() {
451 return $this->getService( 'InterwikiLookup' );
456 * @return IBufferingStatsdDataFactory
458 public function getStatsdDataFactory() {
459 return $this->getService( 'StatsdDataFactory' );
464 * @return EventRelayerGroup
466 public function getEventRelayerGroup() {
467 return $this->getService( 'EventRelayerGroup' );
472 * @return SearchEngine
474 public function newSearchEngine() {
475 // New engine object every time, since they keep state
476 return $this->getService( 'SearchEngineFactory' )->create();
481 * @return SearchEngineFactory
483 public function getSearchEngineFactory() {
484 return $this->getService( 'SearchEngineFactory' );
489 * @return SearchEngineConfig
491 public function getSearchEngineConfig() {
492 return $this->getService( 'SearchEngineConfig' );
497 * @return SkinFactory
499 public function getSkinFactory() {
500 return $this->getService( 'SkinFactory' );
507 public function getDBLoadBalancerFactory() {
508 return $this->getService( 'DBLoadBalancerFactory' );
513 * @return LoadBalancer The main DB load balancer for the local wiki.
515 public function getDBLoadBalancer() {
516 return $this->getService( 'DBLoadBalancer' );
521 * @return WatchedItemStoreInterface
523 public function getWatchedItemStore() {
524 return $this->getService( 'WatchedItemStore' );
529 * @return WatchedItemQueryService
531 public function getWatchedItemQueryService() {
532 return $this->getService( 'WatchedItemQueryService' );
539 public function getCryptRand() {
540 return $this->getService( 'CryptRand' );
547 public function getCryptHKDF() {
548 return $this->getService( 'CryptHKDF' );
553 * @return MediaHandlerFactory
555 public function getMediaHandlerFactory() {
556 return $this->getService( 'MediaHandlerFactory' );
561 * @return MimeAnalyzer
563 public function getMimeAnalyzer() {
564 return $this->getService( 'MimeAnalyzer' );
569 * @return ProxyLookup
571 public function getProxyLookup() {
572 return $this->getService( 'ProxyLookup' );
579 public function getParser() {
580 return $this->getService( 'Parser' );
585 * @return ParserCache
587 public function getParserCache() {
588 return $this->getService( 'ParserCache' );
593 * @return GenderCache
595 public function getGenderCache() {
596 return $this->getService( 'GenderCache' );
603 public function getLinkCache() {
604 return $this->getService( 'LinkCache' );
609 * @return LinkRendererFactory
611 public function getLinkRendererFactory() {
612 return $this->getService( 'LinkRendererFactory' );
616 * LinkRenderer instance that can be used
617 * if no custom options are needed
620 * @return LinkRenderer
622 public function getLinkRenderer() {
623 return $this->getService( 'LinkRenderer' );
628 * @return TitleFormatter
630 public function getTitleFormatter() {
631 return $this->getService( 'TitleFormatter' );
636 * @return TitleParser
638 public function getTitleParser() {
639 return $this->getService( 'TitleParser' );
646 public function getMainObjectStash() {
647 return $this->getService( 'MainObjectStash' );
652 * @return \WANObjectCache
654 public function getMainWANObjectCache() {
655 return $this->getService( 'MainWANObjectCache' );
662 public function getLocalServerObjectCache() {
663 return $this->getService( 'LocalServerObjectCache' );
668 * @return VirtualRESTServiceClient
670 public function getVirtualRESTServiceClient() {
671 return $this->getService( 'VirtualRESTServiceClient' );
676 * @return \ConfiguredReadOnlyMode
678 public function getConfiguredReadOnlyMode() {
679 return $this->getService( 'ConfiguredReadOnlyMode' );
684 * @return \ReadOnlyMode
686 public function getReadOnlyMode() {
687 return $this->getService( 'ReadOnlyMode' );
692 * @return CommandFactory
694 public function getShellCommandFactory() {
695 return $this->getService( 'ShellCommandFactory' );
700 * @return \ExternalStoreFactory
702 public function getExternalStoreFactory() {
703 return $this->getService( 'ExternalStoreFactory' );
708 * @return BlobStoreFactory
710 public function getBlobStoreFactory() {
711 return $this->getService( 'BlobStoreFactory' );
718 public function getBlobStore() {
719 return $this->getService( '_SqlBlobStore' );
724 * @return RevisionStore
726 public function getRevisionStore() {
727 return $this->getService( 'RevisionStore' );
732 * @return PreferencesFactory
734 public function getPreferencesFactory() {
735 return $this->getService( 'PreferencesFactory' );
740 * @return HttpRequestFactory
742 public function getHttpRequestFactory() {
743 return $this->getService( 'HttpRequestFactory' );
746 ///////////////////////////////////////////////////////////////////////////
747 // NOTE: When adding a service getter here, don't forget to add a test
748 // case for it in MediaWikiServicesTest::provideGetters() and in
749 // MediaWikiServicesTest::provideGetService()!
750 ///////////////////////////////////////////////////////////////////////////