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