10 use EventRelayerGroup
;
14 use IBufferingStatsdDataFactory
;
15 use MediaWiki\Http\HttpRequestFactory
;
16 use MediaWiki\Preferences\PreferencesFactory
;
17 use MediaWiki\Shell\CommandFactory
;
18 use MediaWiki\Storage\BlobStore
;
19 use MediaWiki\Storage\BlobStoreFactory
;
20 use MediaWiki\Storage\NameTableStore
;
21 use MediaWiki\Storage\RevisionFactory
;
22 use MediaWiki\Storage\RevisionLookup
;
23 use MediaWiki\Storage\RevisionStore
;
24 use OldRevisionImporter
;
25 use UploadRevisionImporter
;
26 use Wikimedia\Rdbms\LBFactory
;
28 use Wikimedia\Rdbms\LoadBalancer
;
29 use MediaHandlerFactory
;
30 use MediaWiki\Config\ConfigRepository
;
31 use MediaWiki\Linker\LinkRenderer
;
32 use MediaWiki\Linker\LinkRendererFactory
;
33 use MediaWiki\Services\SalvageableService
;
34 use MediaWiki\Services\ServiceContainer
;
35 use MediaWiki\Services\NoSuchServiceException
;
43 use SearchEngineConfig
;
44 use SearchEngineFactory
;
47 use WatchedItemStoreInterface
;
48 use WatchedItemQueryService
;
52 use VirtualRESTServiceClient
;
53 use MediaWiki\Interwiki\InterwikiLookup
;
56 * Service locator for MediaWiki core services.
58 * This program is free software; you can redistribute it and/or modify
59 * it under the terms of the GNU General Public License as published by
60 * the Free Software Foundation; either version 2 of the License, or
61 * (at your option) any later version.
63 * This program is distributed in the hope that it will be useful,
64 * but WITHOUT ANY WARRANTY; without even the implied warranty of
65 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
66 * GNU General Public License for more details.
68 * You should have received a copy of the GNU General Public License along
69 * with this program; if not, write to the Free Software Foundation, Inc.,
70 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
71 * http://www.gnu.org/copyleft/gpl.html
79 * MediaWikiServices is the service locator for the application scope of MediaWiki.
80 * Its implemented as a simple configurable DI container.
81 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
82 * the network of service objects that defines MediaWiki's application logic.
83 * It acts as an entry point to MediaWiki's dependency injection mechanism.
85 * Services are defined in the "wiring" array passed to the constructor,
86 * or by calling defineService().
88 * @see docs/injection.txt for an overview of using dependency injection in the
89 * MediaWiki code base.
91 class MediaWikiServices
extends ServiceContainer
{
94 * @var MediaWikiServices|null
96 private static $instance = null;
99 * Returns the global default instance of the top level service locator.
103 * The default instance is initialized using the service instantiator functions
104 * defined in ServiceWiring.php.
106 * @note This should only be called by static functions! The instance returned here
107 * should not be passed around! Objects that need access to a service should have
108 * that service injected into the constructor, never a service locator!
110 * @return MediaWikiServices
112 public static function getInstance() {
113 if ( self
::$instance === null ) {
114 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
115 // but some information from the global scope has to be injected here,
116 // even if it's just a file name or database credentials to load
117 // configuration from.
118 $bootstrapConfig = new GlobalVarConfig();
119 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
122 return self
::$instance;
126 * Replaces the global MediaWikiServices instance.
130 * @note This is for use in PHPUnit tests only!
132 * @throws MWException if called outside of PHPUnit tests.
134 * @param MediaWikiServices $services The new MediaWikiServices object.
136 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
138 public static function forceGlobalInstance( MediaWikiServices
$services ) {
139 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
140 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
143 $old = self
::getInstance();
144 self
::$instance = $services;
150 * Creates a new instance of MediaWikiServices and sets it as the global default
151 * instance. getInstance() will return a different MediaWikiServices object
152 * after every call to resetGlobalInstance().
156 * @warning This should not be used during normal operation. It is intended for use
157 * when the configuration has changed significantly since bootstrap time, e.g.
158 * during the installation process or during testing.
160 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
161 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
162 * any of the services managed by MediaWikiServices exist. If any service objects
163 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
164 * with the operation of the services managed by the new MediaWikiServices.
165 * Operating with a mix of services created by the old and the new
166 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
167 * Any class implementing LAZY LOADING is especially prone to this problem,
168 * since instances would typically retain a reference to a storage layer service.
170 * @see forceGlobalInstance()
171 * @see resetGlobalInstance()
172 * @see resetBetweenTest()
174 * @param Config|null $bootstrapConfig The Config object to be registered as the
175 * 'BootstrapConfig' service. This has to contain at least the information
176 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
177 * config of the old instance of MediaWikiServices will be re-used. If there
178 * was no previous instance, a new GlobalVarConfig object will be used to
179 * bootstrap the services.
181 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
182 * See SalvageableService for details.
184 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
185 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
188 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
189 if ( self
::$instance === null ) {
190 // no global instance yet, nothing to reset
194 self
::failIfResetNotAllowed( __METHOD__
);
196 if ( $bootstrapConfig === null ) {
197 $bootstrapConfig = self
::$instance->getBootstrapConfig();
200 $oldInstance = self
::$instance;
202 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
203 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
205 if ( $quick === 'quick' ) {
206 self
::$instance->salvage( $oldInstance );
208 $oldInstance->destroy();
213 * Salvages the state of any salvageable service instances in $other.
215 * @note $other will have been destroyed when salvage() returns.
217 * @param MediaWikiServices $other
219 private function salvage( self
$other ) {
220 foreach ( $this->getServiceNames() as $name ) {
221 // The service could be new in the new instance and not registered in the
222 // other instance (e.g. an extension that was loaded after the instantiation of
223 // the other instance. Skip this service in this case. See T143974
225 $oldService = $other->peekService( $name );
226 } catch ( NoSuchServiceException
$e ) {
230 if ( $oldService instanceof SalvageableService
) {
231 /** @var SalvageableService $newService */
232 $newService = $this->getService( $name );
233 $newService->salvage( $oldService );
241 * Creates a new MediaWikiServices instance and initializes it according to the
242 * given $bootstrapConfig. In particular, all wiring files defined in the
243 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
245 * @param Config|null $bootstrapConfig The Config object to be registered as the
246 * 'BootstrapConfig' service.
248 * @param string $loadWiring set this to 'load' to load the wiring files specified
249 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
251 * @return MediaWikiServices
252 * @throws MWException
253 * @throws \FatalError
255 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
256 $instance = new self( $bootstrapConfig );
258 // Load the default wiring from the specified files.
259 if ( $loadWiring === 'load' ) {
260 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
261 $instance->loadWiringFiles( $wiringFiles );
264 // Provide a traditional hook point to allow extensions to configure services.
265 Hooks
::run( 'MediaWikiServices', [ $instance ] );
271 * Disables all storage layer services. After calling this, any attempt to access the
272 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
277 * @warning This is intended for extreme situations only and should never be used
278 * while serving normal web requests. Legitimate use cases for this method include
279 * the installation process. Test fixtures may also use this, if the fixture relies
282 * @see resetGlobalInstance()
283 * @see resetChildProcessServices()
285 public static function disableStorageBackend() {
286 // TODO: also disable some Caches, JobQueues, etc
287 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
288 $services = self
::getInstance();
290 foreach ( $destroy as $name ) {
291 $services->disableService( $name );
294 ObjectCache
::clear();
298 * Resets any services that may have become stale after a child process
299 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
300 * to call this method from the parent process.
304 * @note This is intended for use in the context of process forking only!
306 * @see resetGlobalInstance()
307 * @see disableStorageBackend()
309 public static function resetChildProcessServices() {
310 // NOTE: for now, just reset everything. Since we don't know the interdependencies
311 // between services, we can't do this more selectively at this time.
312 self
::resetGlobalInstance();
314 // Child, reseed because there is no bug in PHP:
315 // https://bugs.php.net/bug.php?id=42465
316 mt_srand( getmypid() );
320 * Resets the given service for testing purposes.
324 * @warning This is generally unsafe! Other services may still retain references
325 * to the stale service instance, leading to failures and inconsistencies. Subclasses
326 * may use this method to reset specific services under specific instances, but
327 * it should not be exposed to application logic.
329 * @note With proper dependency injection used throughout the codebase, this method
330 * should not be needed. It is provided to allow tests that pollute global service
331 * instances to clean up.
333 * @param string $name
334 * @param bool $destroy Whether the service instance should be destroyed if it exists.
335 * When set to false, any existing service instance will effectively be detached
336 * from the container.
338 * @throws MWException if called outside of PHPUnit tests.
340 public function resetServiceForTesting( $name, $destroy = true ) {
341 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
342 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
345 $this->resetService( $name, $destroy );
349 * Convenience method that throws an exception unless it is called during a phase in which
350 * resetting of global services is allowed. In general, services should not be reset
351 * individually, since that may introduce inconsistencies.
355 * This method will throw an exception if:
357 * - self::$resetInProgress is false (to allow all services to be reset together
358 * via resetGlobalInstance)
359 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
360 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
362 * This method is intended to be used to safeguard against accidentally resetting
363 * global service instances that are not yet managed by MediaWikiServices. It is
364 * defined here in the MediaWikiServices services class to have a central place
365 * for managing service bootstrapping and resetting.
367 * @param string $method the name of the caller method, as given by __METHOD__.
369 * @throws MWException if called outside bootstrap mode.
371 * @see resetGlobalInstance()
372 * @see forceGlobalInstance()
373 * @see disableStorageBackend()
375 public static function failIfResetNotAllowed( $method ) {
376 if ( !defined( 'MW_PHPUNIT_TEST' )
377 && !defined( 'MW_PARSER_TEST' )
378 && !defined( 'MEDIAWIKI_INSTALL' )
379 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
380 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
382 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
387 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
388 * This has to contain at least the information needed to set up the 'ConfigFactory'
391 public function __construct( Config
$config ) {
392 parent
::__construct();
394 // Register the given Config object as the bootstrap config service.
395 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
400 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
403 * Returns the Config object containing the bootstrap configuration.
404 * Bootstrap configuration would typically include database credentials
405 * and other information that may be needed before the ConfigFactory
406 * service can be instantiated.
408 * @note This should only be used during bootstrapping, in particular
409 * when creating the MainConfig service. Application logic should
410 * use getMainConfig() to get a Config instances.
415 public function getBootstrapConfig() {
416 return $this->getService( 'BootstrapConfig' );
421 * @return ConfigFactory
423 public function getConfigFactory() {
424 return $this->getService( 'ConfigFactory' );
428 * Returns the Config object that provides configuration for MediaWiki core.
429 * This may or may not be the same object that is returned by getBootstrapConfig().
434 public function getMainConfig() {
435 return $this->getService( 'MainConfig' );
442 public function getSiteLookup() {
443 return $this->getService( 'SiteLookup' );
450 public function getSiteStore() {
451 return $this->getService( 'SiteStore' );
456 * @return InterwikiLookup
458 public function getInterwikiLookup() {
459 return $this->getService( 'InterwikiLookup' );
464 * @return IBufferingStatsdDataFactory
466 public function getStatsdDataFactory() {
467 return $this->getService( 'StatsdDataFactory' );
472 * @return IBufferingStatsdDataFactory
474 public function getPerDbNameStatsdDataFactory() {
475 return $this->getService( 'PerDbNameStatsdDataFactory' );
480 * @return EventRelayerGroup
482 public function getEventRelayerGroup() {
483 return $this->getService( 'EventRelayerGroup' );
488 * @return SearchEngine
490 public function newSearchEngine() {
491 // New engine object every time, since they keep state
492 return $this->getService( 'SearchEngineFactory' )->create();
497 * @return SearchEngineFactory
499 public function getSearchEngineFactory() {
500 return $this->getService( 'SearchEngineFactory' );
505 * @return SearchEngineConfig
507 public function getSearchEngineConfig() {
508 return $this->getService( 'SearchEngineConfig' );
513 * @return SkinFactory
515 public function getSkinFactory() {
516 return $this->getService( 'SkinFactory' );
523 public function getDBLoadBalancerFactory() {
524 return $this->getService( 'DBLoadBalancerFactory' );
529 * @return LoadBalancer The main DB load balancer for the local wiki.
531 public function getDBLoadBalancer() {
532 return $this->getService( 'DBLoadBalancer' );
537 * @return WatchedItemStoreInterface
539 public function getWatchedItemStore() {
540 return $this->getService( 'WatchedItemStore' );
545 * @return WatchedItemQueryService
547 public function getWatchedItemQueryService() {
548 return $this->getService( 'WatchedItemQueryService' );
553 * @deprecated since 1.32, use random_bytes()/random_int()
556 public function getCryptRand() {
557 return $this->getService( 'CryptRand' );
564 public function getCryptHKDF() {
565 return $this->getService( 'CryptHKDF' );
570 * @return MediaHandlerFactory
572 public function getMediaHandlerFactory() {
573 return $this->getService( 'MediaHandlerFactory' );
578 * @return MimeAnalyzer
580 public function getMimeAnalyzer() {
581 return $this->getService( 'MimeAnalyzer' );
586 * @return ProxyLookup
588 public function getProxyLookup() {
589 return $this->getService( 'ProxyLookup' );
596 public function getParser() {
597 return $this->getService( 'Parser' );
602 * @return ParserCache
604 public function getParserCache() {
605 return $this->getService( 'ParserCache' );
610 * @return GenderCache
612 public function getGenderCache() {
613 return $this->getService( 'GenderCache' );
620 public function getLinkCache() {
621 return $this->getService( 'LinkCache' );
626 * @return LinkRendererFactory
628 public function getLinkRendererFactory() {
629 return $this->getService( 'LinkRendererFactory' );
633 * LinkRenderer instance that can be used
634 * if no custom options are needed
637 * @return LinkRenderer
639 public function getLinkRenderer() {
640 return $this->getService( 'LinkRenderer' );
645 * @return TitleFormatter
647 public function getTitleFormatter() {
648 return $this->getService( 'TitleFormatter' );
653 * @return TitleParser
655 public function getTitleParser() {
656 return $this->getService( 'TitleParser' );
663 public function getMainObjectStash() {
664 return $this->getService( 'MainObjectStash' );
669 * @return \WANObjectCache
671 public function getMainWANObjectCache() {
672 return $this->getService( 'MainWANObjectCache' );
679 public function getLocalServerObjectCache() {
680 return $this->getService( 'LocalServerObjectCache' );
685 * @return VirtualRESTServiceClient
687 public function getVirtualRESTServiceClient() {
688 return $this->getService( 'VirtualRESTServiceClient' );
693 * @return \ConfiguredReadOnlyMode
695 public function getConfiguredReadOnlyMode() {
696 return $this->getService( 'ConfiguredReadOnlyMode' );
701 * @return \ReadOnlyMode
703 public function getReadOnlyMode() {
704 return $this->getService( 'ReadOnlyMode' );
709 * @return \UploadRevisionImporter
711 public function getWikiRevisionUploadImporter() {
712 return $this->getService( 'UploadRevisionImporter' );
717 * @return \OldRevisionImporter
719 public function getWikiRevisionOldRevisionImporter() {
720 return $this->getService( 'OldRevisionImporter' );
725 * @return \OldRevisionImporter
727 public function getWikiRevisionOldRevisionImporterNoUpdates() {
728 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
733 * @return CommandFactory
735 public function getShellCommandFactory() {
736 return $this->getService( 'ShellCommandFactory' );
741 * @return \ExternalStoreFactory
743 public function getExternalStoreFactory() {
744 return $this->getService( 'ExternalStoreFactory' );
749 * @return BlobStoreFactory
751 public function getBlobStoreFactory() {
752 return $this->getService( 'BlobStoreFactory' );
759 public function getBlobStore() {
760 return $this->getService( '_SqlBlobStore' );
765 * @return RevisionStore
767 public function getRevisionStore() {
768 return $this->getService( 'RevisionStore' );
773 * @return RevisionLookup
775 public function getRevisionLookup() {
776 return $this->getService( 'RevisionLookup' );
781 * @return RevisionFactory
783 public function getRevisionFactory() {
784 return $this->getService( 'RevisionFactory' );
789 * @return NameTableStore
791 public function getContentModelStore() {
792 return $this->getService( 'ContentModelStore' );
797 * @return NameTableStore
799 public function getSlotRoleStore() {
800 return $this->getService( 'SlotRoleStore' );
805 * @return NameTableStore
807 public function getChangeTagDefStore() {
808 return $this->getService( 'ChangeTagDefStore' );
813 * @return PreferencesFactory
815 public function getPreferencesFactory() {
816 return $this->getService( 'PreferencesFactory' );
821 * @return HttpRequestFactory
823 public function getHttpRequestFactory() {
824 return $this->getService( 'HttpRequestFactory' );
829 * @return CommentStore
831 public function getCommentStore() {
832 return $this->getService( 'CommentStore' );
837 * @return ActorMigration
839 public function getActorMigration() {
840 return $this->getService( 'ActorMigration' );
845 * @return UploadRevisionImporter
847 public function getUploadRevisionImporter() {
848 return $this->getService( 'UploadRevisionImporter' );
853 * @return OldRevisionImporter
855 public function getOldRevisionImporter() {
856 return $this->getService( 'OldRevisionImporter' );
861 * @return ConfigRepository
863 public function getConfigRepository() {
864 return $this->getService( 'ConfigRepository' );
867 ///////////////////////////////////////////////////////////////////////////
868 // NOTE: When adding a service getter here, don't forget to add a test
869 // case for it in MediaWikiServicesTest::provideGetters() and in
870 // MediaWikiServicesTest::provideGetService()!
871 ///////////////////////////////////////////////////////////////////////////