12 use IBufferingStatsdDataFactory
;
13 use MediaWiki\Shell\CommandFactory
;
14 use Wikimedia\Rdbms\LBFactory
;
16 use Wikimedia\Rdbms\LoadBalancer
;
17 use MediaHandlerFactory
;
18 use MediaWiki\Linker\LinkRenderer
;
19 use MediaWiki\Linker\LinkRendererFactory
;
20 use MediaWiki\Services\SalvageableService
;
21 use MediaWiki\Services\ServiceContainer
;
22 use MediaWiki\Services\NoSuchServiceException
;
30 use SearchEngineConfig
;
31 use SearchEngineFactory
;
35 use WatchedItemQueryService
;
39 use VirtualRESTServiceClient
;
40 use MediaWiki\Interwiki\InterwikiLookup
;
43 * Service locator for MediaWiki core services.
45 * This program is free software; you can redistribute it and/or modify
46 * it under the terms of the GNU General Public License as published by
47 * the Free Software Foundation; either version 2 of the License, or
48 * (at your option) any later version.
50 * This program is distributed in the hope that it will be useful,
51 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
53 * GNU General Public License for more details.
55 * You should have received a copy of the GNU General Public License along
56 * with this program; if not, write to the Free Software Foundation, Inc.,
57 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
58 * http://www.gnu.org/copyleft/gpl.html
66 * MediaWikiServices is the service locator for the application scope of MediaWiki.
67 * Its implemented as a simple configurable DI container.
68 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
69 * the network of service objects that defines MediaWiki's application logic.
70 * It acts as an entry point to MediaWiki's dependency injection mechanism.
72 * Services are defined in the "wiring" array passed to the constructor,
73 * or by calling defineService().
75 * @see docs/injection.txt for an overview of using dependency injection in the
76 * MediaWiki code base.
78 class MediaWikiServices
extends ServiceContainer
{
81 * @var MediaWikiServices|null
83 private static $instance = null;
86 * Returns the global default instance of the top level service locator.
90 * The default instance is initialized using the service instantiator functions
91 * defined in ServiceWiring.php.
93 * @note This should only be called by static functions! The instance returned here
94 * should not be passed around! Objects that need access to a service should have
95 * that service injected into the constructor, never a service locator!
97 * @return MediaWikiServices
99 public static function getInstance() {
100 if ( self
::$instance === null ) {
101 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
102 // but some information from the global scope has to be injected here,
103 // even if it's just a file name or database credentials to load
104 // configuration from.
105 $bootstrapConfig = new GlobalVarConfig();
106 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
109 return self
::$instance;
113 * Replaces the global MediaWikiServices instance.
117 * @note This is for use in PHPUnit tests only!
119 * @throws MWException if called outside of PHPUnit tests.
121 * @param MediaWikiServices $services The new MediaWikiServices object.
123 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
125 public static function forceGlobalInstance( MediaWikiServices
$services ) {
126 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
127 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
130 $old = self
::getInstance();
131 self
::$instance = $services;
137 * Creates a new instance of MediaWikiServices and sets it as the global default
138 * instance. getInstance() will return a different MediaWikiServices object
139 * after every call to resetGlobalInstance().
143 * @warning This should not be used during normal operation. It is intended for use
144 * when the configuration has changed significantly since bootstrap time, e.g.
145 * during the installation process or during testing.
147 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
148 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
149 * any of the services managed by MediaWikiServices exist. If any service objects
150 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
151 * with the operation of the services managed by the new MediaWikiServices.
152 * Operating with a mix of services created by the old and the new
153 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
154 * Any class implementing LAZY LOADING is especially prone to this problem,
155 * since instances would typically retain a reference to a storage layer service.
157 * @see forceGlobalInstance()
158 * @see resetGlobalInstance()
159 * @see resetBetweenTest()
161 * @param Config|null $bootstrapConfig The Config object to be registered as the
162 * 'BootstrapConfig' service. This has to contain at least the information
163 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
164 * config of the old instance of MediaWikiServices will be re-used. If there
165 * was no previous instance, a new GlobalVarConfig object will be used to
166 * bootstrap the services.
168 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
169 * See SalvageableService for details.
171 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
172 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
175 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
176 if ( self
::$instance === null ) {
177 // no global instance yet, nothing to reset
181 self
::failIfResetNotAllowed( __METHOD__
);
183 if ( $bootstrapConfig === null ) {
184 $bootstrapConfig = self
::$instance->getBootstrapConfig();
187 $oldInstance = self
::$instance;
189 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
190 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
192 if ( $quick === 'quick' ) {
193 self
::$instance->salvage( $oldInstance );
195 $oldInstance->destroy();
200 * Salvages the state of any salvageable service instances in $other.
202 * @note $other will have been destroyed when salvage() returns.
204 * @param MediaWikiServices $other
206 private function salvage( self
$other ) {
207 foreach ( $this->getServiceNames() as $name ) {
208 // The service could be new in the new instance and not registered in the
209 // other instance (e.g. an extension that was loaded after the instantiation of
210 // the other instance. Skip this service in this case. See T143974
212 $oldService = $other->peekService( $name );
213 } catch ( NoSuchServiceException
$e ) {
217 if ( $oldService instanceof SalvageableService
) {
218 /** @var SalvageableService $newService */
219 $newService = $this->getService( $name );
220 $newService->salvage( $oldService );
228 * Creates a new MediaWikiServices instance and initializes it according to the
229 * given $bootstrapConfig. In particular, all wiring files defined in the
230 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
232 * @param Config|null $bootstrapConfig The Config object to be registered as the
233 * 'BootstrapConfig' service.
235 * @param string $loadWiring set this to 'load' to load the wiring files specified
236 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
238 * @return MediaWikiServices
239 * @throws MWException
240 * @throws \FatalError
242 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
243 $instance = new self( $bootstrapConfig );
245 // Load the default wiring from the specified files.
246 if ( $loadWiring === 'load' ) {
247 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
248 $instance->loadWiringFiles( $wiringFiles );
251 // Provide a traditional hook point to allow extensions to configure services.
252 Hooks
::run( 'MediaWikiServices', [ $instance ] );
258 * Disables all storage layer services. After calling this, any attempt to access the
259 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
264 * @warning This is intended for extreme situations only and should never be used
265 * while serving normal web requests. Legitimate use cases for this method include
266 * the installation process. Test fixtures may also use this, if the fixture relies
269 * @see resetGlobalInstance()
270 * @see resetChildProcessServices()
272 public static function disableStorageBackend() {
273 // TODO: also disable some Caches, JobQueues, etc
274 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
275 $services = self
::getInstance();
277 foreach ( $destroy as $name ) {
278 $services->disableService( $name );
281 ObjectCache
::clear();
285 * Resets any services that may have become stale after a child process
286 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
287 * to call this method from the parent process.
291 * @note This is intended for use in the context of process forking only!
293 * @see resetGlobalInstance()
294 * @see disableStorageBackend()
296 public static function resetChildProcessServices() {
297 // NOTE: for now, just reset everything. Since we don't know the interdependencies
298 // between services, we can't do this more selectively at this time.
299 self
::resetGlobalInstance();
301 // Child, reseed because there is no bug in PHP:
302 // https://bugs.php.net/bug.php?id=42465
303 mt_srand( getmypid() );
307 * Resets the given service for testing purposes.
311 * @warning This is generally unsafe! Other services may still retain references
312 * to the stale service instance, leading to failures and inconsistencies. Subclasses
313 * may use this method to reset specific services under specific instances, but
314 * it should not be exposed to application logic.
316 * @note With proper dependency injection used throughout the codebase, this method
317 * should not be needed. It is provided to allow tests that pollute global service
318 * instances to clean up.
320 * @param string $name
321 * @param bool $destroy Whether the service instance should be destroyed if it exists.
322 * When set to false, any existing service instance will effectively be detached
323 * from the container.
325 * @throws MWException if called outside of PHPUnit tests.
327 public function resetServiceForTesting( $name, $destroy = true ) {
328 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
329 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
332 $this->resetService( $name, $destroy );
336 * Convenience method that throws an exception unless it is called during a phase in which
337 * resetting of global services is allowed. In general, services should not be reset
338 * individually, since that may introduce inconsistencies.
342 * This method will throw an exception if:
344 * - self::$resetInProgress is false (to allow all services to be reset together
345 * via resetGlobalInstance)
346 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
347 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
349 * This method is intended to be used to safeguard against accidentally resetting
350 * global service instances that are not yet managed by MediaWikiServices. It is
351 * defined here in the MediaWikiServices services class to have a central place
352 * for managing service bootstrapping and resetting.
354 * @param string $method the name of the caller method, as given by __METHOD__.
356 * @throws MWException if called outside bootstrap mode.
358 * @see resetGlobalInstance()
359 * @see forceGlobalInstance()
360 * @see disableStorageBackend()
362 public static function failIfResetNotAllowed( $method ) {
363 if ( !defined( 'MW_PHPUNIT_TEST' )
364 && !defined( 'MW_PARSER_TEST' )
365 && !defined( 'MEDIAWIKI_INSTALL' )
366 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
367 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
369 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
374 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
375 * This has to contain at least the information needed to set up the 'ConfigFactory'
378 public function __construct( Config
$config ) {
379 parent
::__construct();
381 // Register the given Config object as the bootstrap config service.
382 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
387 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
390 * Returns the Config object containing the bootstrap configuration.
391 * Bootstrap configuration would typically include database credentials
392 * and other information that may be needed before the ConfigFactory
393 * service can be instantiated.
395 * @note This should only be used during bootstrapping, in particular
396 * when creating the MainConfig service. Application logic should
397 * use getMainConfig() to get a Config instances.
402 public function getBootstrapConfig() {
403 return $this->getService( 'BootstrapConfig' );
408 * @return ConfigFactory
410 public function getConfigFactory() {
411 return $this->getService( 'ConfigFactory' );
415 * Returns the Config object that provides configuration for MediaWiki core.
416 * This may or may not be the same object that is returned by getBootstrapConfig().
421 public function getMainConfig() {
422 return $this->getService( 'MainConfig' );
429 public function getSiteLookup() {
430 return $this->getService( 'SiteLookup' );
437 public function getSiteStore() {
438 return $this->getService( 'SiteStore' );
443 * @return InterwikiLookup
445 public function getInterwikiLookup() {
446 return $this->getService( 'InterwikiLookup' );
451 * @return IBufferingStatsdDataFactory
453 public function getStatsdDataFactory() {
454 return $this->getService( 'StatsdDataFactory' );
459 * @return EventRelayerGroup
461 public function getEventRelayerGroup() {
462 return $this->getService( 'EventRelayerGroup' );
467 * @return SearchEngine
469 public function newSearchEngine() {
470 // New engine object every time, since they keep state
471 return $this->getService( 'SearchEngineFactory' )->create();
476 * @return SearchEngineFactory
478 public function getSearchEngineFactory() {
479 return $this->getService( 'SearchEngineFactory' );
484 * @return SearchEngineConfig
486 public function getSearchEngineConfig() {
487 return $this->getService( 'SearchEngineConfig' );
492 * @return SkinFactory
494 public function getSkinFactory() {
495 return $this->getService( 'SkinFactory' );
502 public function getDBLoadBalancerFactory() {
503 return $this->getService( 'DBLoadBalancerFactory' );
508 * @return LoadBalancer The main DB load balancer for the local wiki.
510 public function getDBLoadBalancer() {
511 return $this->getService( 'DBLoadBalancer' );
516 * @return WatchedItemStore
518 public function getWatchedItemStore() {
519 return $this->getService( 'WatchedItemStore' );
524 * @return WatchedItemQueryService
526 public function getWatchedItemQueryService() {
527 return $this->getService( 'WatchedItemQueryService' );
534 public function getCryptRand() {
535 return $this->getService( 'CryptRand' );
542 public function getCryptHKDF() {
543 return $this->getService( 'CryptHKDF' );
548 * @return MediaHandlerFactory
550 public function getMediaHandlerFactory() {
551 return $this->getService( 'MediaHandlerFactory' );
556 * @return MimeAnalyzer
558 public function getMimeAnalyzer() {
559 return $this->getService( 'MimeAnalyzer' );
564 * @return ProxyLookup
566 public function getProxyLookup() {
567 return $this->getService( 'ProxyLookup' );
574 public function getParser() {
575 return $this->getService( 'Parser' );
580 * @return ParserCache
582 public function getParserCache() {
583 return $this->getService( 'ParserCache' );
588 * @return GenderCache
590 public function getGenderCache() {
591 return $this->getService( 'GenderCache' );
598 public function getLinkCache() {
599 return $this->getService( 'LinkCache' );
604 * @return LinkRendererFactory
606 public function getLinkRendererFactory() {
607 return $this->getService( 'LinkRendererFactory' );
611 * LinkRenderer instance that can be used
612 * if no custom options are needed
615 * @return LinkRenderer
617 public function getLinkRenderer() {
618 return $this->getService( 'LinkRenderer' );
623 * @return TitleFormatter
625 public function getTitleFormatter() {
626 return $this->getService( 'TitleFormatter' );
631 * @return TitleParser
633 public function getTitleParser() {
634 return $this->getService( 'TitleParser' );
641 public function getMainObjectStash() {
642 return $this->getService( 'MainObjectStash' );
647 * @return \WANObjectCache
649 public function getMainWANObjectCache() {
650 return $this->getService( 'MainWANObjectCache' );
657 public function getLocalServerObjectCache() {
658 return $this->getService( 'LocalServerObjectCache' );
663 * @return VirtualRESTServiceClient
665 public function getVirtualRESTServiceClient() {
666 return $this->getService( 'VirtualRESTServiceClient' );
671 * @return \ConfiguredReadOnlyMode
673 public function getConfiguredReadOnlyMode() {
674 return $this->getService( 'ConfiguredReadOnlyMode' );
679 * @return \ReadOnlyMode
681 public function getReadOnlyMode() {
682 return $this->getService( 'ReadOnlyMode' );
687 * @return CommandFactory
689 public function getShellCommandFactory() {
690 return $this->getService( 'ShellCommandFactory' );
693 ///////////////////////////////////////////////////////////////////////////
694 // NOTE: When adding a service getter here, don't forget to add a test
695 // case for it in MediaWikiServicesTest::provideGetters() and in
696 // MediaWikiServicesTest::provideGetService()!
697 ///////////////////////////////////////////////////////////////////////////