Fix resetServiceForTesting() param type in comment
[lhc/web/wiklou.git] / includes / MediaWikiServices.php
1 <?php
2 namespace MediaWiki;
3
4 use Config;
5 use ConfigFactory;
6 use EventRelayerGroup;
7 use GenderCache;
8 use GlobalVarConfig;
9 use Hooks;
10 use LBFactory;
11 use LinkCache;
12 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
13 use LoadBalancer;
14 use MediaWiki\Services\ServiceContainer;
15 use MWException;
16 use ObjectCache;
17 use ResourceLoader;
18 use SearchEngine;
19 use SearchEngineConfig;
20 use SearchEngineFactory;
21 use SiteLookup;
22 use SiteStore;
23 use WatchedItemStore;
24 use SkinFactory;
25 use TitleFormatter;
26 use TitleParser;
27 use MediaWiki\Interwiki\InterwikiLookup;
28
29 /**
30 * Service locator for MediaWiki core services.
31 *
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 2 of the License, or
35 * (at your option) any later version.
36 *
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
41 *
42 * You should have received a copy of the GNU General Public License along
43 * with this program; if not, write to the Free Software Foundation, Inc.,
44 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
45 * http://www.gnu.org/copyleft/gpl.html
46 *
47 * @file
48 *
49 * @since 1.27
50 */
51
52 /**
53 * MediaWikiServices is the service locator for the application scope of MediaWiki.
54 * Its implemented as a simple configurable DI container.
55 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
56 * the network of service objects that defines MediaWiki's application logic.
57 * It acts as an entry point to MediaWiki's dependency injection mechanism.
58 *
59 * Services are defined in the "wiring" array passed to the constructor,
60 * or by calling defineService().
61 *
62 * @see docs/injection.txt for an overview of using dependency injection in the
63 * MediaWiki code base.
64 */
65 class MediaWikiServices extends ServiceContainer {
66
67 /**
68 * @var MediaWikiServices|null
69 */
70 private static $instance = null;
71
72 /**
73 * Returns the global default instance of the top level service locator.
74 *
75 * @since 1.27
76 *
77 * The default instance is initialized using the service instantiator functions
78 * defined in ServiceWiring.php.
79 *
80 * @note This should only be called by static functions! The instance returned here
81 * should not be passed around! Objects that need access to a service should have
82 * that service injected into the constructor, never a service locator!
83 *
84 * @return MediaWikiServices
85 */
86 public static function getInstance() {
87 if ( self::$instance === null ) {
88 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
89 // but some information from the global scope has to be injected here,
90 // even if it's just a file name or database credentials to load
91 // configuration from.
92 $bootstrapConfig = new GlobalVarConfig();
93 self::$instance = self::newInstance( $bootstrapConfig );
94 }
95
96 return self::$instance;
97 }
98
99 /**
100 * Replaces the global MediaWikiServices instance.
101 *
102 * @since 1.28
103 *
104 * @note This is for use in PHPUnit tests only!
105 *
106 * @throws MWException if called outside of PHPUnit tests.
107 *
108 * @param MediaWikiServices $services The new MediaWikiServices object.
109 *
110 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
111 */
112 public static function forceGlobalInstance( MediaWikiServices $services ) {
113 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
114 throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
115 }
116
117 $old = self::getInstance();
118 self::$instance = $services;
119
120 return $old;
121 }
122
123 /**
124 * Creates a new instance of MediaWikiServices and sets it as the global default
125 * instance. getInstance() will return a different MediaWikiServices object
126 * after every call to resetGlobalServiceLocator().
127 *
128 * @since 1.28
129 *
130 * @warning This should not be used during normal operation. It is intended for use
131 * when the configuration has changed significantly since bootstrap time, e.g.
132 * during the installation process or during testing.
133 *
134 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
135 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
136 * any of the services managed by MediaWikiServices exist. If any service objects
137 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
138 * with the operation of the services managed by the new MediaWikiServices.
139 * Operating with a mix of services created by the old and the new
140 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
141 * Any class implementing LAZY LOADING is especially prone to this problem,
142 * since instances would typically retain a reference to a storage layer service.
143 *
144 * @see forceGlobalInstance()
145 * @see resetGlobalInstance()
146 * @see resetBetweenTest()
147 *
148 * @param Config|null $bootstrapConfig The Config object to be registered as the
149 * 'BootstrapConfig' service. This has to contain at least the information
150 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
151 * config of the old instance of MediaWikiServices will be re-used. If there
152 * was no previous instance, a new GlobalVarConfig object will be used to
153 * bootstrap the services.
154 *
155 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
156 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
157 * is defined).
158 */
159 public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
160 if ( self::$instance === null ) {
161 // no global instance yet, nothing to reset
162 return;
163 }
164
165 self::failIfResetNotAllowed( __METHOD__ );
166
167 if ( $bootstrapConfig === null ) {
168 $bootstrapConfig = self::$instance->getBootstrapConfig();
169 }
170
171 self::$instance->destroy();
172
173 self::$instance = self::newInstance( $bootstrapConfig );
174 }
175
176 /**
177 * Creates a new MediaWikiServices instance and initializes it according to the
178 * given $bootstrapConfig. In particular, all wiring files defined in the
179 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
180 *
181 * @param Config|null $bootstrapConfig The Config object to be registered as the
182 * 'BootstrapConfig' service. This has to contain at least the information
183 * needed to set up the 'ConfigFactory' service. If not provided, any call
184 * to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
185 * A MediaWikiServices instance without access to configuration is called
186 * "primordial".
187 *
188 * @return MediaWikiServices
189 * @throws MWException
190 */
191 private static function newInstance( Config $bootstrapConfig ) {
192 $instance = new self( $bootstrapConfig );
193
194 // Load the default wiring from the specified files.
195 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
196 $instance->loadWiringFiles( $wiringFiles );
197
198 // Provide a traditional hook point to allow extensions to configure services.
199 Hooks::run( 'MediaWikiServices', [ $instance ] );
200
201 return $instance;
202 }
203
204 /**
205 * Disables all storage layer services. After calling this, any attempt to access the
206 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
207 * operation.
208 *
209 * @since 1.28
210 *
211 * @warning This is intended for extreme situations only and should never be used
212 * while serving normal web requests. Legitimate use cases for this method include
213 * the installation process. Test fixtures may also use this, if the fixture relies
214 * on globalState.
215 *
216 * @see resetGlobalInstance()
217 * @see resetChildProcessServices()
218 */
219 public static function disableStorageBackend() {
220 // TODO: also disable some Caches, JobQueues, etc
221 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
222 $services = self::getInstance();
223
224 foreach ( $destroy as $name ) {
225 $services->disableService( $name );
226 }
227
228 ObjectCache::clear();
229 }
230
231 /**
232 * Resets any services that may have become stale after a child process
233 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
234 * to call this method from the parent process.
235 *
236 * @since 1.28
237 *
238 * @note This is intended for use in the context of process forking only!
239 *
240 * @see resetGlobalInstance()
241 * @see disableStorageBackend()
242 */
243 public static function resetChildProcessServices() {
244 // NOTE: for now, just reset everything. Since we don't know the interdependencies
245 // between services, we can't do this more selectively at this time.
246 self::resetGlobalInstance();
247
248 // Child, reseed because there is no bug in PHP:
249 // http://bugs.php.net/bug.php?id=42465
250 mt_srand( getmypid() );
251 }
252
253 /**
254 * Resets the given service for testing purposes.
255 *
256 * @since 1.28
257 *
258 * @warning This is generally unsafe! Other services may still retain references
259 * to the stale service instance, leading to failures and inconsistencies. Subclasses
260 * may use this method to reset specific services under specific instances, but
261 * it should not be exposed to application logic.
262 *
263 * @note With proper dependency injection used throughout the codebase, this method
264 * should not be needed. It is provided to allow tests that pollute global service
265 * instances to clean up.
266 *
267 * @param string $name
268 * @param bool $destroy Whether the service instance should be destroyed if it exists.
269 * When set to false, any existing service instance will effectively be detached
270 * from the container.
271 *
272 * @throws MWException if called outside of PHPUnit tests.
273 */
274 public function resetServiceForTesting( $name, $destroy = true ) {
275 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
276 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
277 }
278
279 $this->resetService( $name, $destroy );
280 }
281
282 /**
283 * Convenience method that throws an exception unless it is called during a phase in which
284 * resetting of global services is allowed. In general, services should not be reset
285 * individually, since that may introduce inconsistencies.
286 *
287 * @since 1.28
288 *
289 * This method will throw an exception if:
290 *
291 * - self::$resetInProgress is false (to allow all services to be reset together
292 * via resetGlobalInstance)
293 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
294 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
295 *
296 * This method is intended to be used to safeguard against accidentally resetting
297 * global service instances that are not yet managed by MediaWikiServices. It is
298 * defined here in the MediaWikiServices services class to have a central place
299 * for managing service bootstrapping and resetting.
300 *
301 * @param string $method the name of the caller method, as given by __METHOD__.
302 *
303 * @throws MWException if called outside bootstrap mode.
304 *
305 * @see resetGlobalInstance()
306 * @see forceGlobalInstance()
307 * @see disableStorageBackend()
308 */
309 public static function failIfResetNotAllowed( $method ) {
310 if ( !defined( 'MW_PHPUNIT_TEST' )
311 && !defined( 'MW_PARSER_TEST' )
312 && !defined( 'MEDIAWIKI_INSTALL' )
313 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
314 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
315 ) {
316 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
317 }
318 }
319
320 /**
321 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
322 * This has to contain at least the information needed to set up the 'ConfigFactory'
323 * service.
324 */
325 public function __construct( Config $config ) {
326 parent::__construct();
327
328 // Register the given Config object as the bootstrap config service.
329 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
330 return $config;
331 } );
332 }
333
334 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
335
336 /**
337 * Returns the Config object containing the bootstrap configuration.
338 * Bootstrap configuration would typically include database credentials
339 * and other information that may be needed before the ConfigFactory
340 * service can be instantiated.
341 *
342 * @note This should only be used during bootstrapping, in particular
343 * when creating the MainConfig service. Application logic should
344 * use getMainConfig() to get a Config instances.
345 *
346 * @since 1.27
347 * @return Config
348 */
349 public function getBootstrapConfig() {
350 return $this->getService( 'BootstrapConfig' );
351 }
352
353 /**
354 * @since 1.27
355 * @return ConfigFactory
356 */
357 public function getConfigFactory() {
358 return $this->getService( 'ConfigFactory' );
359 }
360
361 /**
362 * Returns the Config object that provides configuration for MediaWiki core.
363 * This may or may not be the same object that is returned by getBootstrapConfig().
364 *
365 * @since 1.27
366 * @return Config
367 */
368 public function getMainConfig() {
369 return $this->getService( 'MainConfig' );
370 }
371
372 /**
373 * @since 1.27
374 * @return SiteLookup
375 */
376 public function getSiteLookup() {
377 return $this->getService( 'SiteLookup' );
378 }
379
380 /**
381 * @since 1.27
382 * @return SiteStore
383 */
384 public function getSiteStore() {
385 return $this->getService( 'SiteStore' );
386 }
387
388 /**
389 * @since 1.28
390 * @return InterwikiLookup
391 */
392 public function getInterwikiLookup() {
393 return $this->getService( 'InterwikiLookup' );
394 }
395
396 /**
397 * @since 1.27
398 * @return StatsdDataFactory
399 */
400 public function getStatsdDataFactory() {
401 return $this->getService( 'StatsdDataFactory' );
402 }
403
404 /**
405 * @since 1.27
406 * @return EventRelayerGroup
407 */
408 public function getEventRelayerGroup() {
409 return $this->getService( 'EventRelayerGroup' );
410 }
411
412 /**
413 * @since 1.27
414 * @return SearchEngine
415 */
416 public function newSearchEngine() {
417 // New engine object every time, since they keep state
418 return $this->getService( 'SearchEngineFactory' )->create();
419 }
420
421 /**
422 * @since 1.27
423 * @return SearchEngineFactory
424 */
425 public function getSearchEngineFactory() {
426 return $this->getService( 'SearchEngineFactory' );
427 }
428
429 /**
430 * @since 1.27
431 * @return SearchEngineConfig
432 */
433 public function getSearchEngineConfig() {
434 return $this->getService( 'SearchEngineConfig' );
435 }
436
437 /**
438 * @since 1.27
439 * @return SkinFactory
440 */
441 public function getSkinFactory() {
442 return $this->getService( 'SkinFactory' );
443 }
444
445 /**
446 * @since 1.28
447 * @return LBFactory
448 */
449 public function getDBLoadBalancerFactory() {
450 return $this->getService( 'DBLoadBalancerFactory' );
451 }
452
453 /**
454 * @since 1.28
455 * @return LoadBalancer The main DB load balancer for the local wiki.
456 */
457 public function getDBLoadBalancer() {
458 return $this->getService( 'DBLoadBalancer' );
459 }
460
461 /**
462 * @since 1.28
463 * @return WatchedItemStore
464 */
465 public function getWatchedItemStore() {
466 return $this->getService( 'WatchedItemStore' );
467 }
468
469 /**
470 * @since 1.28
471 * @return GenderCache
472 */
473 public function getGenderCache() {
474 return $this->getService( 'GenderCache' );
475 }
476
477 /**
478 * @since 1.28
479 * @return LinkCache
480 */
481 public function getLinkCache() {
482 return $this->getService( 'LinkCache' );
483 }
484
485 /**
486 * @since 1.28
487 * @return TitleFormatter
488 */
489 public function getTitleFormatter() {
490 return $this->getService( 'TitleFormatter' );
491 }
492
493 /**
494 * @since 1.28
495 * @return TitleParser
496 */
497 public function getTitleParser() {
498 return $this->getService( 'TitleParser' );
499 }
500
501 ///////////////////////////////////////////////////////////////////////////
502 // NOTE: When adding a service getter here, don't forget to add a test
503 // case for it in MediaWikiServicesTest::provideGetters() and in
504 // MediaWikiServicesTest::provideGetService()!
505 ///////////////////////////////////////////////////////////////////////////
506
507 }