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