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