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