Merge "Revert "Make WatchedItemStore use MediaWikiServices""
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use ApiQueryInfo;
5 use CentralIdLookup;
6 use Config;
7 use ConfigFactory;
8 use DeferredUpdates;
9 use FileBackendGroup;
10 use GlobalVarConfig;
11 use Hooks;
12 use IP;
13 use JobQueueAggregator;
14 use Language;
15 use LBFactory;
16 use LinkCache;
17 use LoadBalancer;
18 use LockManagerGroup;
19 use MagicWord;
20 use MediaHandler;
21 use MediaWiki\Services\ServiceContainer;
22 use MediaWiki\Session\SessionManager;
23 use MessageCache;
24 use MWException;
25 use MWNamespace;
26 use MWTidy;
27 use ObjectCache;
28 use RedisConnectionPool;
29 use RepoGroup;
30 use RequestContext;
31 use ResourceLoader;
32 use SiteLookup;
33 use SiteStore;
34 use SpecialPageFactory;
35 use Title;
36 use User;
37
38 /**
39 * Service locator for MediaWiki core services.
40 *
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.
45 *
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.
50 *
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
55 *
56 * @file
57 *
58 * @since 1.27
59 */
60
61 /**
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.
67 *
68 * Services are defined in the "wiring" array passed to the constructor,
69 * or by calling defineService().
70 *
71 * @see docs/injection.txt for an overview of using dependency injection in the
72 * MediaWiki code base.
73 */
74 class MediaWikiServices extends ServiceContainer {
75
76 /**
77 * @var MediaWikiServices|null
78 */
79 private static $instance = null;
80
81 /**
82 * Returns the global default instance of the top level service locator.
83 *
84 * The default instance is initialized using the service instantiator functions
85 * defined in ServiceWiring.php.
86 *
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!
90 *
91 * @return MediaWikiServices
92 */
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 );
101 }
102
103 return self::$instance;
104 }
105
106 /**
107 * Replaces the global MediaWikiServices instance.
108 *
109 * @note This is for use in PHPUnit tests only!
110 *
111 * @throws MWException if called outside of PHPUnit tests.
112 *
113 * @param MediaWikiServices $services The new MediaWikiServices object.
114 *
115 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
116 */
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.' );
120 }
121
122 $old = self::getInstance();
123 self::$instance = $services;
124
125 self::resetLegacyServices();
126
127 return $old;
128 }
129
130 /**
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().
134 *
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.
138 *
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.
148 *
149 * @see forceGlobalInstance()
150 * @see resetGlobalInstance()
151 * @see resetBetweenTest()
152 *
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.
159 *
160 * @throws MWException
161 */
162 public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
163 if ( self::$instance === null ) {
164 // no global instance yet, nothing to reset
165 return;
166 }
167
168 if ( $bootstrapConfig === null ) {
169 $bootstrapConfig = self::$instance->getBootstrapConfig();
170 }
171
172 self::$instance->destroy();
173
174 self::$instance = self::newInstance( $bootstrapConfig );
175
176 self::resetLegacyServices();
177 }
178
179 /**
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.
183 *
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
189 * "primordial".
190 *
191 * @return MediaWikiServices
192 * @throws MWException
193 */
194 private static function newInstance( Config $bootstrapConfig ) {
195 $instance = new self( $bootstrapConfig );
196
197 // Load the default wiring from the specified files.
198 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
199 $instance->loadWiringFiles( $wiringFiles );
200
201 // Provide a traditional hook point to allow extensions to configure services.
202 Hooks::run( 'MediaWikiServices', [ $instance ] );
203
204 return $instance;
205 }
206
207 /**
208 * Resets global instances of services that have not yet been ported to using
209 * MediaWikiServices to manage their default instance.
210 *
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.
214 *
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.
218 */
219 private static function resetLegacyServices() {
220 global $wgContLang, $wgUser, $wgMemc, $wgRequest;
221
222 $services = self::getInstance();
223 $config = $services->getMainConfig();
224
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
227 // removed.
228
229 User::resetIdByNameCache();
230 LinkCache::singleton()->clear();
231 Title::clearCaches();
232
233 MWTidy::destroySingleton();
234 MagicWord::clearCache();
235 SpecialPageFactory::resetList();
236 JobQueueAggregator::destroySingleton();
237 DeferredUpdates::clearPendingUpdates();
238 CentralIdLookup::resetCache();
239 MediaHandler::resetCache();
240 IP::clearCaches();
241 ResourceLoader::clearCache();
242
243 ApiQueryInfo::resetTokenCache();
244
245 RepoGroup::destroySingleton();
246
247 MessageCache::destroyInstance();
248
249 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
250 Language::$mLangObjCache = [];
251 Language::getLocalisationCache()->unloadAll();
252
253 ObjectCache::clear();
254 RedisConnectionPool::destroySingletons();
255 FileBackendGroup::destroySingleton();
256 LockManagerGroup::destroySingletons();
257
258 RequestContext::resetMain();
259 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
260
261 $wgContLang = Language::factory( $config->get( 'LanguageCode' ) );
262 $wgContLang->resetNamespaces(); # reset namespace cache
263
264 $wgMemc = ObjectCache::getLocalClusterInstance();
265 $wgUser = RequestContext::getMain()->getUser();
266
267 SessionManager::resetCache();
268
269 // Provide a hook point for extensions that need to reset global service instances.
270 Hooks::run( 'MediaWikiServices::resetLegacyServices', [ $services ] );
271 }
272
273 /**
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
276 * operation.
277 *
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
281 * on globalState.
282 *
283 * @see resetGlobalInstance()
284 * @see resetChildProcessServices()
285 */
286 public static function disableStorageBackend() {
287 // TODO: also disable some Caches, JobQueues, etc
288 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
289 $services = self::getInstance();
290
291 foreach ( $destroy as $name ) {
292 $services->disableService( $name );
293 }
294 }
295
296 /**
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.
300 *
301 * @note This is intended for use in the context of process forking only!
302 *
303 * @see resetGlobalInstance()
304 * @see disableStorageBackend()
305 */
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();
310
311 // Child, reseed because there is no bug in PHP:
312 // http://bugs.php.net/bug.php?id=42465
313 mt_srand( getmypid() );
314 }
315
316 /**
317 * Resets the given service for testing purposes.
318 *
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.
323 *
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.
327 *
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.
332 *
333 * @throws MWException if called outside of PHPUnit tests.
334 */
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.' );
338 }
339
340 $this->resetService( $name, $destroy );
341 }
342
343 /**
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).
349 *
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.
354 *
355 * @param string $method the name of the caller method, as given by __METHOD__.
356 *
357 * @throws MWException if called outside bootstrap mode.
358 *
359 * @see resetGlobalInstance()
360 * @see forceGlobalInstance()
361 * @see disableStorageBackend()
362 */
363 public static function failUnlessBootstrapping( $method ) {
364 if ( !defined( 'MW_PHPUNIT_TEST' )
365 && !defined( 'MEDIAWIKI_INSTALL' )
366 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
367 ) {
368 throw new MWException( $method . ' may only be called during bootstrapping unit tests!' );
369 }
370
371 ObjectCache::clear();
372 }
373
374 /**
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'
377 * service.
378 */
379 public function __construct( Config $config ) {
380 parent::__construct();
381
382 // Register the given Config object as the bootstrap config service.
383 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
384 return $config;
385 } );
386 }
387
388 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
389
390 /**
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.
395 *
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.
399 *
400 * @return Config
401 */
402 public function getBootstrapConfig() {
403 return $this->getService( 'BootstrapConfig' );
404 }
405
406 /**
407 * @return ConfigFactory
408 */
409 public function getConfigFactory() {
410 return $this->getService( 'ConfigFactory' );
411 }
412
413 /**
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().
416 *
417 * @return Config
418 */
419 public function getMainConfig() {
420 return $this->getService( 'MainConfig' );
421 }
422
423 /**
424 * @return SiteLookup
425 */
426 public function getSiteLookup() {
427 return $this->getService( 'SiteLookup' );
428 }
429
430 /**
431 * @return SiteStore
432 */
433 public function getSiteStore() {
434 return $this->getService( 'SiteStore' );
435 }
436
437 /**
438 * @return LBFactory
439 */
440 public function getDBLoadBalancerFactory() {
441 return $this->getService( 'DBLoadBalancerFactory' );
442 }
443
444 /**
445 * @return LoadBalancer The main DB load balancer for the local wiki.
446 */
447 public function getDBLoadBalancer() {
448 return $this->getService( 'DBLoadBalancer' );
449 }
450
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 ///////////////////////////////////////////////////////////////////////////
456
457 }