13 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
15 use MediaHandlerFactory
;
16 use MediaWiki\Linker\LinkRenderer
;
17 use MediaWiki\Linker\LinkRendererFactory
;
18 use MediaWiki\Services\SalvageableService
;
19 use MediaWiki\Services\ServiceContainer
;
20 use MediaWiki\Services\NoSuchServiceException
;
25 use SearchEngineConfig
;
26 use SearchEngineFactory
;
30 use WatchedItemQueryService
;
34 use VirtualRESTServiceClient
;
35 use MediaWiki\Interwiki\InterwikiLookup
;
38 * Service locator for MediaWiki core services.
40 * This program is free software; you can redistribute it and/or modify
41 * it under the terms of the GNU General Public License as published by
42 * the Free Software Foundation; either version 2 of the License, or
43 * (at your option) any later version.
45 * This program is distributed in the hope that it will be useful,
46 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48 * GNU General Public License for more details.
50 * You should have received a copy of the GNU General Public License along
51 * with this program; if not, write to the Free Software Foundation, Inc.,
52 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
53 * http://www.gnu.org/copyleft/gpl.html
61 * MediaWikiServices is the service locator for the application scope of MediaWiki.
62 * Its implemented as a simple configurable DI container.
63 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
64 * the network of service objects that defines MediaWiki's application logic.
65 * It acts as an entry point to MediaWiki's dependency injection mechanism.
67 * Services are defined in the "wiring" array passed to the constructor,
68 * or by calling defineService().
70 * @see docs/injection.txt for an overview of using dependency injection in the
71 * MediaWiki code base.
73 class MediaWikiServices
extends ServiceContainer
{
76 * @var MediaWikiServices|null
78 private static $instance = null;
81 * Returns the global default instance of the top level service locator.
85 * The default instance is initialized using the service instantiator functions
86 * defined in ServiceWiring.php.
88 * @note This should only be called by static functions! The instance returned here
89 * should not be passed around! Objects that need access to a service should have
90 * that service injected into the constructor, never a service locator!
92 * @return MediaWikiServices
94 public static function getInstance() {
95 if ( self
::$instance === null ) {
96 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
97 // but some information from the global scope has to be injected here,
98 // even if it's just a file name or database credentials to load
99 // configuration from.
100 $bootstrapConfig = new GlobalVarConfig();
101 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
104 return self
::$instance;
108 * Replaces the global MediaWikiServices instance.
112 * @note This is for use in PHPUnit tests only!
114 * @throws MWException if called outside of PHPUnit tests.
116 * @param MediaWikiServices $services The new MediaWikiServices object.
118 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
120 public static function forceGlobalInstance( MediaWikiServices
$services ) {
121 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
122 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
125 $old = self
::getInstance();
126 self
::$instance = $services;
132 * Creates a new instance of MediaWikiServices and sets it as the global default
133 * instance. getInstance() will return a different MediaWikiServices object
134 * after every call to resetGlobalInstance().
138 * @warning This should not be used during normal operation. It is intended for use
139 * when the configuration has changed significantly since bootstrap time, e.g.
140 * during the installation process or during testing.
142 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
143 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
144 * any of the services managed by MediaWikiServices exist. If any service objects
145 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
146 * with the operation of the services managed by the new MediaWikiServices.
147 * Operating with a mix of services created by the old and the new
148 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
149 * Any class implementing LAZY LOADING is especially prone to this problem,
150 * since instances would typically retain a reference to a storage layer service.
152 * @see forceGlobalInstance()
153 * @see resetGlobalInstance()
154 * @see resetBetweenTest()
156 * @param Config|null $bootstrapConfig The Config object to be registered as the
157 * 'BootstrapConfig' service. This has to contain at least the information
158 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
159 * config of the old instance of MediaWikiServices will be re-used. If there
160 * was no previous instance, a new GlobalVarConfig object will be used to
161 * bootstrap the services.
163 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
164 * See SalvageableService for details.
166 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
167 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
170 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
171 if ( self
::$instance === null ) {
172 // no global instance yet, nothing to reset
176 self
::failIfResetNotAllowed( __METHOD__
);
178 if ( $bootstrapConfig === null ) {
179 $bootstrapConfig = self
::$instance->getBootstrapConfig();
182 $oldInstance = self
::$instance;
184 self
::$instance = self
::newInstance( $bootstrapConfig );
185 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
187 if ( $quick === 'quick' ) {
188 self
::$instance->salvage( $oldInstance );
190 $oldInstance->destroy();
196 * Salvages the state of any salvageable service instances in $other.
198 * @note $other will have been destroyed when salvage() returns.
200 * @param MediaWikiServices $other
202 private function salvage( self
$other ) {
203 foreach ( $this->getServiceNames() as $name ) {
204 // The service could be new in the new instance and not registered in the
205 // other instance (e.g. an extension that was loaded after the instantiation of
206 // the other instance. Skip this service in this case. See T143974
208 $oldService = $other->peekService( $name );
209 } catch ( NoSuchServiceException
$e ) {
213 if ( $oldService instanceof SalvageableService
) {
214 /** @var SalvageableService $newService */
215 $newService = $this->getService( $name );
216 $newService->salvage( $oldService );
224 * Creates a new MediaWikiServices instance and initializes it according to the
225 * given $bootstrapConfig. In particular, all wiring files defined in the
226 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
228 * @param Config|null $bootstrapConfig The Config object to be registered as the
229 * 'BootstrapConfig' service.
231 * @param string $loadWiring set this to 'load' to load the wiring files specified
232 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
234 * @return MediaWikiServices
235 * @throws MWException
236 * @throws \FatalError
238 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
239 $instance = new self( $bootstrapConfig );
241 // Load the default wiring from the specified files.
242 if ( $loadWiring === 'load' ) {
243 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
244 $instance->loadWiringFiles( $wiringFiles );
247 // Provide a traditional hook point to allow extensions to configure services.
248 Hooks
::run( 'MediaWikiServices', [ $instance ] );
254 * Disables all storage layer services. After calling this, any attempt to access the
255 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
260 * @warning This is intended for extreme situations only and should never be used
261 * while serving normal web requests. Legitimate use cases for this method include
262 * the installation process. Test fixtures may also use this, if the fixture relies
265 * @see resetGlobalInstance()
266 * @see resetChildProcessServices()
268 public static function disableStorageBackend() {
269 // TODO: also disable some Caches, JobQueues, etc
270 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
271 $services = self
::getInstance();
273 foreach ( $destroy as $name ) {
274 $services->disableService( $name );
277 ObjectCache
::clear();
281 * Resets any services that may have become stale after a child process
282 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
283 * to call this method from the parent process.
287 * @note This is intended for use in the context of process forking only!
289 * @see resetGlobalInstance()
290 * @see disableStorageBackend()
292 public static function resetChildProcessServices() {
293 // NOTE: for now, just reset everything. Since we don't know the interdependencies
294 // between services, we can't do this more selectively at this time.
295 self
::resetGlobalInstance();
297 // Child, reseed because there is no bug in PHP:
298 // http://bugs.php.net/bug.php?id=42465
299 mt_srand( getmypid() );
303 * Resets the given service for testing purposes.
307 * @warning This is generally unsafe! Other services may still retain references
308 * to the stale service instance, leading to failures and inconsistencies. Subclasses
309 * may use this method to reset specific services under specific instances, but
310 * it should not be exposed to application logic.
312 * @note With proper dependency injection used throughout the codebase, this method
313 * should not be needed. It is provided to allow tests that pollute global service
314 * instances to clean up.
316 * @param string $name
317 * @param bool $destroy Whether the service instance should be destroyed if it exists.
318 * When set to false, any existing service instance will effectively be detached
319 * from the container.
321 * @throws MWException if called outside of PHPUnit tests.
323 public function resetServiceForTesting( $name, $destroy = true ) {
324 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
325 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
328 $this->resetService( $name, $destroy );
332 * Convenience method that throws an exception unless it is called during a phase in which
333 * resetting of global services is allowed. In general, services should not be reset
334 * individually, since that may introduce inconsistencies.
338 * This method will throw an exception if:
340 * - self::$resetInProgress is false (to allow all services to be reset together
341 * via resetGlobalInstance)
342 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
343 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
345 * This method is intended to be used to safeguard against accidentally resetting
346 * global service instances that are not yet managed by MediaWikiServices. It is
347 * defined here in the MediaWikiServices services class to have a central place
348 * for managing service bootstrapping and resetting.
350 * @param string $method the name of the caller method, as given by __METHOD__.
352 * @throws MWException if called outside bootstrap mode.
354 * @see resetGlobalInstance()
355 * @see forceGlobalInstance()
356 * @see disableStorageBackend()
358 public static function failIfResetNotAllowed( $method ) {
359 if ( !defined( 'MW_PHPUNIT_TEST' )
360 && !defined( 'MW_PARSER_TEST' )
361 && !defined( 'MEDIAWIKI_INSTALL' )
362 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
363 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
365 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
370 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
371 * This has to contain at least the information needed to set up the 'ConfigFactory'
374 public function __construct( Config
$config ) {
375 parent
::__construct();
377 // Register the given Config object as the bootstrap config service.
378 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
383 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
386 * Returns the Config object containing the bootstrap configuration.
387 * Bootstrap configuration would typically include database credentials
388 * and other information that may be needed before the ConfigFactory
389 * service can be instantiated.
391 * @note This should only be used during bootstrapping, in particular
392 * when creating the MainConfig service. Application logic should
393 * use getMainConfig() to get a Config instances.
398 public function getBootstrapConfig() {
399 return $this->getService( 'BootstrapConfig' );
404 * @return ConfigFactory
406 public function getConfigFactory() {
407 return $this->getService( 'ConfigFactory' );
411 * Returns the Config object that provides configuration for MediaWiki core.
412 * This may or may not be the same object that is returned by getBootstrapConfig().
417 public function getMainConfig() {
418 return $this->getService( 'MainConfig' );
425 public function getSiteLookup() {
426 return $this->getService( 'SiteLookup' );
433 public function getSiteStore() {
434 return $this->getService( 'SiteStore' );
439 * @return InterwikiLookup
441 public function getInterwikiLookup() {
442 return $this->getService( 'InterwikiLookup' );
447 * @return StatsdDataFactory
449 public function getStatsdDataFactory() {
450 return $this->getService( 'StatsdDataFactory' );
455 * @return EventRelayerGroup
457 public function getEventRelayerGroup() {
458 return $this->getService( 'EventRelayerGroup' );
463 * @return SearchEngine
465 public function newSearchEngine() {
466 // New engine object every time, since they keep state
467 return $this->getService( 'SearchEngineFactory' )->create();
472 * @return SearchEngineFactory
474 public function getSearchEngineFactory() {
475 return $this->getService( 'SearchEngineFactory' );
480 * @return SearchEngineConfig
482 public function getSearchEngineConfig() {
483 return $this->getService( 'SearchEngineConfig' );
488 * @return SkinFactory
490 public function getSkinFactory() {
491 return $this->getService( 'SkinFactory' );
498 public function getDBLoadBalancerFactory() {
499 return $this->getService( 'DBLoadBalancerFactory' );
504 * @return LoadBalancer The main DB load balancer for the local wiki.
506 public function getDBLoadBalancer() {
507 return $this->getService( 'DBLoadBalancer' );
512 * @return WatchedItemStore
514 public function getWatchedItemStore() {
515 return $this->getService( 'WatchedItemStore' );
520 * @return WatchedItemQueryService
522 public function getWatchedItemQueryService() {
523 return $this->getService( 'WatchedItemQueryService' );
530 public function getCryptRand() {
531 return $this->getService( 'CryptRand' );
536 * @return MediaHandlerFactory
538 public function getMediaHandlerFactory() {
539 return $this->getService( 'MediaHandlerFactory' );
544 * @return ProxyLookup
546 public function getProxyLookup() {
547 return $this->getService( 'ProxyLookup' );
552 * @return GenderCache
554 public function getGenderCache() {
555 return $this->getService( 'GenderCache' );
562 public function getLinkCache() {
563 return $this->getService( 'LinkCache' );
568 * @return LinkRendererFactory
570 public function getLinkRendererFactory() {
571 return $this->getService( 'LinkRendererFactory' );
575 * LinkRenderer instance that can be used
576 * if no custom options are needed
579 * @return LinkRenderer
581 public function getLinkRenderer() {
582 return $this->getService( 'LinkRenderer' );
587 * @return TitleFormatter
589 public function getTitleFormatter() {
590 return $this->getService( 'TitleFormatter' );
595 * @return TitleParser
597 public function getTitleParser() {
598 return $this->getService( 'TitleParser' );
605 public function getMainObjectStash() {
606 return $this->getService( 'MainObjectStash' );
611 * @return \WANObjectCache
613 public function getMainWANObjectCache() {
614 return $this->getService( 'MainWANObjectCache' );
621 public function getLocalServerObjectCache() {
622 return $this->getService( 'LocalServerObjectCache' );
627 * @return VirtualRESTServiceClient
629 public function getVirtualRESTServiceClient() {
630 return $this->getService( 'VirtualRESTServiceClient' );
633 ///////////////////////////////////////////////////////////////////////////
634 // NOTE: When adding a service getter here, don't forget to add a test
635 // case for it in MediaWikiServicesTest::provideGetters() and in
636 // MediaWikiServicesTest::provideGetService()!
637 ///////////////////////////////////////////////////////////////////////////