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