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