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\Linker\LinkRenderer
;
31 use MediaWiki\Linker\LinkRendererFactory
;
32 use MediaWiki\Services\SalvageableService
;
33 use MediaWiki\Services\ServiceContainer
;
34 use MediaWiki\Services\NoSuchServiceException
;
42 use SearchEngineConfig
;
43 use SearchEngineFactory
;
46 use WatchedItemStoreInterface
;
47 use WatchedItemQueryService
;
51 use VirtualRESTServiceClient
;
52 use MediaWiki\Interwiki\InterwikiLookup
;
55 * Service locator for MediaWiki core services.
57 * This program is free software; you can redistribute it and/or modify
58 * it under the terms of the GNU General Public License as published by
59 * the Free Software Foundation; either version 2 of the License, or
60 * (at your option) any later version.
62 * This program is distributed in the hope that it will be useful,
63 * but WITHOUT ANY WARRANTY; without even the implied warranty of
64 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65 * GNU General Public License for more details.
67 * You should have received a copy of the GNU General Public License along
68 * with this program; if not, write to the Free Software Foundation, Inc.,
69 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
70 * http://www.gnu.org/copyleft/gpl.html
78 * MediaWikiServices is the service locator for the application scope of MediaWiki.
79 * Its implemented as a simple configurable DI container.
80 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
81 * the network of service objects that defines MediaWiki's application logic.
82 * It acts as an entry point to MediaWiki's dependency injection mechanism.
84 * Services are defined in the "wiring" array passed to the constructor,
85 * or by calling defineService().
87 * @see docs/injection.txt for an overview of using dependency injection in the
88 * MediaWiki code base.
90 class MediaWikiServices
extends ServiceContainer
{
93 * @var MediaWikiServices|null
95 private static $instance = null;
98 * Returns the global default instance of the top level service locator.
102 * The default instance is initialized using the service instantiator functions
103 * defined in ServiceWiring.php.
105 * @note This should only be called by static functions! The instance returned here
106 * should not be passed around! Objects that need access to a service should have
107 * that service injected into the constructor, never a service locator!
109 * @return MediaWikiServices
111 public static function getInstance() {
112 if ( self
::$instance === null ) {
113 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
114 // but some information from the global scope has to be injected here,
115 // even if it's just a file name or database credentials to load
116 // configuration from.
117 $bootstrapConfig = new GlobalVarConfig();
118 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
121 return self
::$instance;
125 * Replaces the global MediaWikiServices instance.
129 * @note This is for use in PHPUnit tests only!
131 * @throws MWException if called outside of PHPUnit tests.
133 * @param MediaWikiServices $services The new MediaWikiServices object.
135 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
137 public static function forceGlobalInstance( MediaWikiServices
$services ) {
138 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
139 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
142 $old = self
::getInstance();
143 self
::$instance = $services;
149 * Creates a new instance of MediaWikiServices and sets it as the global default
150 * instance. getInstance() will return a different MediaWikiServices object
151 * after every call to resetGlobalInstance().
155 * @warning This should not be used during normal operation. It is intended for use
156 * when the configuration has changed significantly since bootstrap time, e.g.
157 * during the installation process or during testing.
159 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
160 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
161 * any of the services managed by MediaWikiServices exist. If any service objects
162 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
163 * with the operation of the services managed by the new MediaWikiServices.
164 * Operating with a mix of services created by the old and the new
165 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
166 * Any class implementing LAZY LOADING is especially prone to this problem,
167 * since instances would typically retain a reference to a storage layer service.
169 * @see forceGlobalInstance()
170 * @see resetGlobalInstance()
171 * @see resetBetweenTest()
173 * @param Config|null $bootstrapConfig The Config object to be registered as the
174 * 'BootstrapConfig' service. This has to contain at least the information
175 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
176 * config of the old instance of MediaWikiServices will be re-used. If there
177 * was no previous instance, a new GlobalVarConfig object will be used to
178 * bootstrap the services.
180 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
181 * See SalvageableService for details.
183 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
184 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
187 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
188 if ( self
::$instance === null ) {
189 // no global instance yet, nothing to reset
193 self
::failIfResetNotAllowed( __METHOD__
);
195 if ( $bootstrapConfig === null ) {
196 $bootstrapConfig = self
::$instance->getBootstrapConfig();
199 $oldInstance = self
::$instance;
201 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
202 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
204 if ( $quick === 'quick' ) {
205 self
::$instance->salvage( $oldInstance );
207 $oldInstance->destroy();
212 * Salvages the state of any salvageable service instances in $other.
214 * @note $other will have been destroyed when salvage() returns.
216 * @param MediaWikiServices $other
218 private function salvage( self
$other ) {
219 foreach ( $this->getServiceNames() as $name ) {
220 // The service could be new in the new instance and not registered in the
221 // other instance (e.g. an extension that was loaded after the instantiation of
222 // the other instance. Skip this service in this case. See T143974
224 $oldService = $other->peekService( $name );
225 } catch ( NoSuchServiceException
$e ) {
229 if ( $oldService instanceof SalvageableService
) {
230 /** @var SalvageableService $newService */
231 $newService = $this->getService( $name );
232 $newService->salvage( $oldService );
240 * Creates a new MediaWikiServices instance and initializes it according to the
241 * given $bootstrapConfig. In particular, all wiring files defined in the
242 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
244 * @param Config|null $bootstrapConfig The Config object to be registered as the
245 * 'BootstrapConfig' service.
247 * @param string $loadWiring set this to 'load' to load the wiring files specified
248 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
250 * @return MediaWikiServices
251 * @throws MWException
252 * @throws \FatalError
254 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
255 $instance = new self( $bootstrapConfig );
257 // Load the default wiring from the specified files.
258 if ( $loadWiring === 'load' ) {
259 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
260 $instance->loadWiringFiles( $wiringFiles );
263 // Provide a traditional hook point to allow extensions to configure services.
264 Hooks
::run( 'MediaWikiServices', [ $instance ] );
270 * Disables all storage layer services. After calling this, any attempt to access the
271 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
276 * @warning This is intended for extreme situations only and should never be used
277 * while serving normal web requests. Legitimate use cases for this method include
278 * the installation process. Test fixtures may also use this, if the fixture relies
281 * @see resetGlobalInstance()
282 * @see resetChildProcessServices()
284 public static function disableStorageBackend() {
285 // TODO: also disable some Caches, JobQueues, etc
286 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
287 $services = self
::getInstance();
289 foreach ( $destroy as $name ) {
290 $services->disableService( $name );
293 ObjectCache
::clear();
297 * Resets any services that may have become stale after a child process
298 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
299 * to call this method from the parent process.
303 * @note This is intended for use in the context of process forking only!
305 * @see resetGlobalInstance()
306 * @see disableStorageBackend()
308 public static function resetChildProcessServices() {
309 // NOTE: for now, just reset everything. Since we don't know the interdependencies
310 // between services, we can't do this more selectively at this time.
311 self
::resetGlobalInstance();
313 // Child, reseed because there is no bug in PHP:
314 // https://bugs.php.net/bug.php?id=42465
315 mt_srand( getmypid() );
319 * Resets the given service for testing purposes.
323 * @warning This is generally unsafe! Other services may still retain references
324 * to the stale service instance, leading to failures and inconsistencies. Subclasses
325 * may use this method to reset specific services under specific instances, but
326 * it should not be exposed to application logic.
328 * @note With proper dependency injection used throughout the codebase, this method
329 * should not be needed. It is provided to allow tests that pollute global service
330 * instances to clean up.
332 * @param string $name
333 * @param bool $destroy Whether the service instance should be destroyed if it exists.
334 * When set to false, any existing service instance will effectively be detached
335 * from the container.
337 * @throws MWException if called outside of PHPUnit tests.
339 public function resetServiceForTesting( $name, $destroy = true ) {
340 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
341 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
344 $this->resetService( $name, $destroy );
348 * Convenience method that throws an exception unless it is called during a phase in which
349 * resetting of global services is allowed. In general, services should not be reset
350 * individually, since that may introduce inconsistencies.
354 * This method will throw an exception if:
356 * - self::$resetInProgress is false (to allow all services to be reset together
357 * via resetGlobalInstance)
358 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
359 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
361 * This method is intended to be used to safeguard against accidentally resetting
362 * global service instances that are not yet managed by MediaWikiServices. It is
363 * defined here in the MediaWikiServices services class to have a central place
364 * for managing service bootstrapping and resetting.
366 * @param string $method the name of the caller method, as given by __METHOD__.
368 * @throws MWException if called outside bootstrap mode.
370 * @see resetGlobalInstance()
371 * @see forceGlobalInstance()
372 * @see disableStorageBackend()
374 public static function failIfResetNotAllowed( $method ) {
375 if ( !defined( 'MW_PHPUNIT_TEST' )
376 && !defined( 'MW_PARSER_TEST' )
377 && !defined( 'MEDIAWIKI_INSTALL' )
378 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
379 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
381 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
386 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
387 * This has to contain at least the information needed to set up the 'ConfigFactory'
390 public function __construct( Config
$config ) {
391 parent
::__construct();
393 // Register the given Config object as the bootstrap config service.
394 $this->defineService( 'BootstrapConfig', function () use ( $config ) {
399 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
402 * Returns the Config object containing the bootstrap configuration.
403 * Bootstrap configuration would typically include database credentials
404 * and other information that may be needed before the ConfigFactory
405 * service can be instantiated.
407 * @note This should only be used during bootstrapping, in particular
408 * when creating the MainConfig service. Application logic should
409 * use getMainConfig() to get a Config instances.
414 public function getBootstrapConfig() {
415 return $this->getService( 'BootstrapConfig' );
420 * @return ConfigFactory
422 public function getConfigFactory() {
423 return $this->getService( 'ConfigFactory' );
427 * Returns the Config object that provides configuration for MediaWiki core.
428 * This may or may not be the same object that is returned by getBootstrapConfig().
433 public function getMainConfig() {
434 return $this->getService( 'MainConfig' );
441 public function getSiteLookup() {
442 return $this->getService( 'SiteLookup' );
449 public function getSiteStore() {
450 return $this->getService( 'SiteStore' );
455 * @return InterwikiLookup
457 public function getInterwikiLookup() {
458 return $this->getService( 'InterwikiLookup' );
463 * @return IBufferingStatsdDataFactory
465 public function getStatsdDataFactory() {
466 return $this->getService( 'StatsdDataFactory' );
471 * @return IBufferingStatsdDataFactory
473 public function getPerDbNameStatsdDataFactory() {
474 return $this->getService( 'PerDbNameStatsdDataFactory' );
479 * @return EventRelayerGroup
481 public function getEventRelayerGroup() {
482 return $this->getService( 'EventRelayerGroup' );
487 * @return SearchEngine
489 public function newSearchEngine() {
490 // New engine object every time, since they keep state
491 return $this->getService( 'SearchEngineFactory' )->create();
496 * @return SearchEngineFactory
498 public function getSearchEngineFactory() {
499 return $this->getService( 'SearchEngineFactory' );
504 * @return SearchEngineConfig
506 public function getSearchEngineConfig() {
507 return $this->getService( 'SearchEngineConfig' );
512 * @return SkinFactory
514 public function getSkinFactory() {
515 return $this->getService( 'SkinFactory' );
522 public function getDBLoadBalancerFactory() {
523 return $this->getService( 'DBLoadBalancerFactory' );
528 * @return LoadBalancer The main DB load balancer for the local wiki.
530 public function getDBLoadBalancer() {
531 return $this->getService( 'DBLoadBalancer' );
536 * @return WatchedItemStoreInterface
538 public function getWatchedItemStore() {
539 return $this->getService( 'WatchedItemStore' );
544 * @return WatchedItemQueryService
546 public function getWatchedItemQueryService() {
547 return $this->getService( 'WatchedItemQueryService' );
552 * @deprecated since 1.32, use random_bytes()/random_int()
555 public function getCryptRand() {
556 return $this->getService( 'CryptRand' );
563 public function getCryptHKDF() {
564 return $this->getService( 'CryptHKDF' );
569 * @return MediaHandlerFactory
571 public function getMediaHandlerFactory() {
572 return $this->getService( 'MediaHandlerFactory' );
577 * @return MimeAnalyzer
579 public function getMimeAnalyzer() {
580 return $this->getService( 'MimeAnalyzer' );
585 * @return ProxyLookup
587 public function getProxyLookup() {
588 return $this->getService( 'ProxyLookup' );
595 public function getParser() {
596 return $this->getService( 'Parser' );
601 * @return ParserCache
603 public function getParserCache() {
604 return $this->getService( 'ParserCache' );
609 * @return GenderCache
611 public function getGenderCache() {
612 return $this->getService( 'GenderCache' );
619 public function getLinkCache() {
620 return $this->getService( 'LinkCache' );
625 * @return LinkRendererFactory
627 public function getLinkRendererFactory() {
628 return $this->getService( 'LinkRendererFactory' );
632 * LinkRenderer instance that can be used
633 * if no custom options are needed
636 * @return LinkRenderer
638 public function getLinkRenderer() {
639 return $this->getService( 'LinkRenderer' );
644 * @return TitleFormatter
646 public function getTitleFormatter() {
647 return $this->getService( 'TitleFormatter' );
652 * @return TitleParser
654 public function getTitleParser() {
655 return $this->getService( 'TitleParser' );
662 public function getMainObjectStash() {
663 return $this->getService( 'MainObjectStash' );
668 * @return \WANObjectCache
670 public function getMainWANObjectCache() {
671 return $this->getService( 'MainWANObjectCache' );
678 public function getLocalServerObjectCache() {
679 return $this->getService( 'LocalServerObjectCache' );
684 * @return VirtualRESTServiceClient
686 public function getVirtualRESTServiceClient() {
687 return $this->getService( 'VirtualRESTServiceClient' );
692 * @return \ConfiguredReadOnlyMode
694 public function getConfiguredReadOnlyMode() {
695 return $this->getService( 'ConfiguredReadOnlyMode' );
700 * @return \ReadOnlyMode
702 public function getReadOnlyMode() {
703 return $this->getService( 'ReadOnlyMode' );
708 * @return \UploadRevisionImporter
710 public function getWikiRevisionUploadImporter() {
711 return $this->getService( 'UploadRevisionImporter' );
716 * @return \OldRevisionImporter
718 public function getWikiRevisionOldRevisionImporter() {
719 return $this->getService( 'OldRevisionImporter' );
724 * @return \OldRevisionImporter
726 public function getWikiRevisionOldRevisionImporterNoUpdates() {
727 return $this->getService( 'WikiRevisionOldRevisionImporterNoUpdates' );
732 * @return CommandFactory
734 public function getShellCommandFactory() {
735 return $this->getService( 'ShellCommandFactory' );
740 * @return \ExternalStoreFactory
742 public function getExternalStoreFactory() {
743 return $this->getService( 'ExternalStoreFactory' );
748 * @return BlobStoreFactory
750 public function getBlobStoreFactory() {
751 return $this->getService( 'BlobStoreFactory' );
758 public function getBlobStore() {
759 return $this->getService( '_SqlBlobStore' );
764 * @return RevisionStore
766 public function getRevisionStore() {
767 return $this->getService( 'RevisionStore' );
772 * @return RevisionLookup
774 public function getRevisionLookup() {
775 return $this->getService( 'RevisionLookup' );
780 * @return RevisionFactory
782 public function getRevisionFactory() {
783 return $this->getService( 'RevisionFactory' );
788 * @return NameTableStore
790 public function getContentModelStore() {
791 return $this->getService( 'ContentModelStore' );
796 * @return NameTableStore
798 public function getSlotRoleStore() {
799 return $this->getService( 'SlotRoleStore' );
804 * @return NameTableStore
806 public function getChangeTagDefStore() {
807 return $this->getService( 'ChangeTagDefStore' );
812 * @return PreferencesFactory
814 public function getPreferencesFactory() {
815 return $this->getService( 'PreferencesFactory' );
820 * @return HttpRequestFactory
822 public function getHttpRequestFactory() {
823 return $this->getService( 'HttpRequestFactory' );
828 * @return CommentStore
830 public function getCommentStore() {
831 return $this->getService( 'CommentStore' );
836 * @return ActorMigration
838 public function getActorMigration() {
839 return $this->getService( 'ActorMigration' );
844 * @return UploadRevisionImporter
846 public function getUploadRevisionImporter() {
847 return $this->getService( 'UploadRevisionImporter' );
852 * @return OldRevisionImporter
854 public function getOldRevisionImporter() {
855 return $this->getService( 'OldRevisionImporter' );
858 ///////////////////////////////////////////////////////////////////////////
859 // NOTE: When adding a service getter here, don't forget to add a test
860 // case for it in MediaWikiServicesTest::provideGetters() and in
861 // MediaWikiServicesTest::provideGetService()!
862 ///////////////////////////////////////////////////////////////////////////