13 use JobQueueAggregator
;
21 use MediaWiki\Services\ServiceContainer
;
22 use MediaWiki\Session\SessionManager
;
28 use RedisConnectionPool
;
34 use SpecialPageFactory
;
39 * Service locator for MediaWiki core services.
41 * This program is free software; you can redistribute it and/or modify
42 * it under the terms of the GNU General Public License as published by
43 * the Free Software Foundation; either version 2 of the License, or
44 * (at your option) any later version.
46 * This program is distributed in the hope that it will be useful,
47 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 * GNU General Public License for more details.
51 * You should have received a copy of the GNU General Public License along
52 * with this program; if not, write to the Free Software Foundation, Inc.,
53 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
54 * http://www.gnu.org/copyleft/gpl.html
62 * MediaWikiServices is the service locator for the application scope of MediaWiki.
63 * Its implemented as a simple configurable DI container.
64 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
65 * the network of service objects that defines MediaWiki's application logic.
66 * It acts as an entry point to MediaWiki's dependency injection mechanism.
68 * Services are defined in the "wiring" array passed to the constructor,
69 * or by calling defineService().
71 * @see docs/injection.txt for an overview of using dependency injection in the
72 * MediaWiki code base.
74 class MediaWikiServices
extends ServiceContainer
{
77 * @var MediaWikiServices|null
79 private static $instance = null;
82 * Returns the global default instance of the top level service locator.
84 * The default instance is initialized using the service instantiator functions
85 * defined in ServiceWiring.php.
87 * @note This should only be called by static functions! The instance returned here
88 * should not be passed around! Objects that need access to a service should have
89 * that service injected into the constructor, never a service locator!
91 * @return MediaWikiServices
93 public static function getInstance() {
94 if ( self
::$instance === null ) {
95 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
96 // but some information from the global scope has to be injected here,
97 // even if it's just a file name or database credentials to load
98 // configuration from.
99 $bootstrapConfig = new GlobalVarConfig();
100 self
::$instance = self
::newInstance( $bootstrapConfig );
103 return self
::$instance;
107 * Replaces the global MediaWikiServices instance.
109 * @note This is for use in PHPUnit tests only!
111 * @throws MWException if called outside of PHPUnit tests.
113 * @param MediaWikiServices $services The new MediaWikiServices object.
115 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
117 public static function forceGlobalInstance( MediaWikiServices
$services ) {
118 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
119 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
122 $old = self
::getInstance();
123 self
::$instance = $services;
125 self
::resetLegacyServices();
131 * Creates a new instance of MediaWikiServices and sets it as the global default
132 * instance. getInstance() will return a different MediaWikiServices object
133 * after every call to resetGlobalServiceLocator().
135 * @warning This should not be used during normal operation. It is intended for use
136 * when the configuration has changed significantly since bootstrap time, e.g.
137 * during the installation process or during testing.
139 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
140 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
141 * any of the services managed by MediaWikiServices exist. If any service objects
142 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
143 * with the operation of the services managed by the new MediaWikiServices.
144 * Operating with a mix of services created by the old and the new
145 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
146 * Any class implementing LAZY LOADING is especially prone to this problem,
147 * since instances would typically retain a reference to a storage layer service.
149 * @see forceGlobalInstance()
150 * @see resetGlobalInstance()
151 * @see resetBetweenTest()
153 * @param Config|null $bootstrapConfig The Config object to be registered as the
154 * 'BootstrapConfig' service. This has to contain at least the information
155 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
156 * config of the old instance of MediaWikiServices will be re-used. If there
157 * was no previous instance, a new GlobalVarConfig object will be used to
158 * bootstrap the services.
160 * @throws MWException
162 public static function resetGlobalInstance( Config
$bootstrapConfig = null ) {
163 if ( self
::$instance === null ) {
164 // no global instance yet, nothing to reset
168 if ( $bootstrapConfig === null ) {
169 $bootstrapConfig = self
::$instance->getBootstrapConfig();
172 self
::$instance->destroy();
174 self
::$instance = self
::newInstance( $bootstrapConfig );
176 self
::resetLegacyServices();
180 * Creates a new MediaWikiServices instance and initializes it according to the
181 * given $bootstrapConfig. In particular, all wiring files defined in the
182 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
184 * @param Config|null $bootstrapConfig The Config object to be registered as the
185 * 'BootstrapConfig' service. This has to contain at least the information
186 * needed to set up the 'ConfigFactory' service. If not provided, any call
187 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
188 * A MediaWikiServices instance without access to configuration is called
191 * @return MediaWikiServices
192 * @throws MWException
194 private static function newInstance( Config
$bootstrapConfig ) {
195 $instance = new self( $bootstrapConfig );
197 // Load the default wiring from the specified files.
198 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
199 $instance->loadWiringFiles( $wiringFiles );
201 // Provide a traditional hook point to allow extensions to configure services.
202 Hooks
::run( 'MediaWikiServices', [ $instance ] );
208 * Resets global instances of services that have not yet been ported to using
209 * MediaWikiServices to manage their default instance.
211 * @note eventually, all global service instances are to be managed by MediaWikiServices.
212 * To emulate the effect of resetting the global service locator, we reset the individual
213 * static singletons for now.
215 * @note As long as we don't know the interdependencies between the services, the only way
216 * to reset services consistently is to reset all services at once. This should be ok since
217 * there should rarely be a need to reset all processes.
219 private static function resetLegacyServices() {
220 global $wgContLang, $wgUser, $wgMemc, $wgRequest;
222 $services = self
::getInstance();
223 $config = $services->getMainConfig();
225 // NOTE: all the services instance that get reset below should be migrated
226 // to be managed by MediaWikiServices. Eventually, this method can then be
229 User
::resetIdByNameCache();
230 LinkCache
::singleton()->clear();
231 Title
::clearCaches();
233 MWTidy
::destroySingleton();
234 MagicWord
::clearCache();
235 SpecialPageFactory
::resetList();
236 JobQueueAggregator
::destroySingleton();
237 DeferredUpdates
::clearPendingUpdates();
238 CentralIdLookup
::resetCache();
239 MediaHandler
::resetCache();
241 ResourceLoader
::clearCache();
243 ApiQueryInfo
::resetTokenCache();
245 RepoGroup
::destroySingleton();
247 MessageCache
::destroyInstance();
249 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
250 Language
::$mLangObjCache = [];
251 Language
::getLocalisationCache()->unloadAll();
253 ObjectCache
::clear();
254 RedisConnectionPool
::destroySingletons();
255 FileBackendGroup
::destroySingleton();
256 LockManagerGroup
::destroySingletons();
258 RequestContext
::resetMain();
259 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
261 $wgContLang = Language
::factory( $config->get( 'LanguageCode' ) );
262 $wgContLang->resetNamespaces(); # reset namespace cache
264 $wgMemc = ObjectCache
::getLocalClusterInstance();
265 $wgUser = RequestContext
::getMain()->getUser();
267 SessionManager
::resetCache();
269 // Provide a hook point for extensions that need to reset global service instances.
270 Hooks
::run( 'MediaWikiServices::resetLegacyServices', [ $services ] );
274 * Disables all storage layer services. After calling this, any attempt to access the
275 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
278 * @warning This is intended for extreme situations only and should never be used
279 * while serving normal web requests. Legitimate use cases for this method include
280 * the installation process. Test fixtures may also use this, if the fixture relies
283 * @see resetGlobalInstance()
284 * @see resetChildProcessServices()
286 public static function disableStorageBackend() {
287 // TODO: also disable some Caches, JobQueues, etc
288 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
289 $services = self
::getInstance();
291 foreach ( $destroy as $name ) {
292 $services->disableService( $name );
297 * Resets any services that may have become stale after a child process
298 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
299 * 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 // http://bugs.php.net/bug.php?id=42465
313 mt_srand( getmypid() );
317 * Resets the given service for testing purposes.
319 * @warning This is generally unsafe! Other services may still retain references
320 * to the stale service instance, leading to failures and inconsistencies. Subclasses
321 * may use this method to reset specific services under specific instances, but
322 * it should not be exposed to application logic.
324 * @note With proper dependency injection used throughout the codebase, this method
325 * should not be needed. It is provided to allow tests that pollute global service
326 * instances to clean up.
328 * @param string $name
329 * @param string $destroy Whether the service instance should be destroyed if it exists.
330 * When set to false, any existing service instance will effectively be detached
331 * from the container.
333 * @throws MWException if called outside of PHPUnit tests.
335 public function resetServiceForTesting( $name, $destroy = true ) {
336 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
337 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
340 $this->resetService( $name, $destroy );
344 * Convenience method that throws an exception if called outside the service bootstrapping
345 * phase as indicated by the MW_SERVICE_BOOTSTRAP_COMPLETE constant - that is, after
346 * Setup.php has called resetGlobalInstance(). Additionally, no exception is thrown if
347 * this method is called during unit testing (as indicated by MW_PHPUNIT_TEST) or
348 * during installation (as indicated by MEDIAWIKI_INSTALL).
350 * This method is intended to be used to safeguard against accidentally resetting
351 * global service instances that are not yet managed by MediaWikiServices. It is
352 * defined here in the MediaWikiServices services class to keep the knowledge about
353 * how the bootstrapping phase is managed central.
355 * @param string $method the name of the caller method, as given by __METHOD__.
357 * @throws MWException if called outside bootstrap mode.
359 * @see resetGlobalInstance()
360 * @see forceGlobalInstance()
361 * @see disableStorageBackend()
363 public static function failUnlessBootstrapping( $method ) {
364 if ( !defined( 'MW_PHPUNIT_TEST' )
365 && !defined( 'MEDIAWIKI_INSTALL' )
366 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
368 throw new MWException( $method . ' may only be called during bootstrapping unit tests!' );
371 ObjectCache
::clear();
375 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
376 * This has to contain at least the information needed to set up the 'ConfigFactory'
379 public function __construct( Config
$config ) {
380 parent
::__construct();
382 // Register the given Config object as the bootstrap config service.
383 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
388 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
391 * Returns the Config object containing the bootstrap configuration.
392 * Bootstrap configuration would typically include database credentials
393 * and other information that may be needed before the ConfigFactory
394 * service can be instantiated.
396 * @note This should only be used during bootstrapping, in particular
397 * when creating the MainConfig service. Application logic should
398 * use getMainConfig() to get a Config instances.
402 public function getBootstrapConfig() {
403 return $this->getService( 'BootstrapConfig' );
407 * @return ConfigFactory
409 public function getConfigFactory() {
410 return $this->getService( 'ConfigFactory' );
414 * Returns the Config object that provides configuration for MediaWiki core.
415 * This may or may not be the same object that is returned by getBootstrapConfig().
419 public function getMainConfig() {
420 return $this->getService( 'MainConfig' );
426 public function getSiteLookup() {
427 return $this->getService( 'SiteLookup' );
433 public function getSiteStore() {
434 return $this->getService( 'SiteStore' );
440 public function getDBLoadBalancerFactory() {
441 return $this->getService( 'DBLoadBalancerFactory' );
445 * @return LoadBalancer The main DB load balancer for the local wiki.
447 public function getDBLoadBalancer() {
448 return $this->getService( 'DBLoadBalancer' );
451 ///////////////////////////////////////////////////////////////////////////
452 // NOTE: When adding a service getter here, don't forget to add a test
453 // case for it in MediaWikiServicesTest::provideGetters() and in
454 // MediaWikiServicesTest::provideGetService()!
455 ///////////////////////////////////////////////////////////////////////////