Merge "Update some minor type hints"
[lhc/web/wiklou.git] / includes / db / MWLBFactory.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25 use Wikimedia\Rdbms\LBFactory;
26 use Wikimedia\Rdbms\DatabaseDomain;
27
28 /**
29 * MediaWiki-specific class for generating database load balancers
30 * @ingroup Database
31 */
32 abstract class MWLBFactory {
33
34 /** @var array Cache of already-logged deprecation messages */
35 private static $loggedDeprecations = [];
36
37 /**
38 * @param array $lbConf Config for LBFactory::__construct()
39 * @param Config $mainConfig Main config object from MediaWikiServices
40 * @param ConfiguredReadOnlyMode $readOnlyMode
41 * @param BagOStuff $srvCace
42 * @param BagOStuff $mainStash
43 * @param WANObjectCache $wanCache
44 * @return array
45 */
46 public static function applyDefaultConfig(
47 array $lbConf,
48 Config $mainConfig,
49 ConfiguredReadOnlyMode $readOnlyMode,
50 BagOStuff $srvCace,
51 BagOStuff $mainStash,
52 WANObjectCache $wanCache
53 ) {
54 global $wgCommandLineMode;
55
56 static $typesWithSchema = [ 'postgres', 'msssql' ];
57
58 $lbConf += [
59 'localDomain' => new DatabaseDomain(
60 $mainConfig->get( 'DBname' ),
61 $mainConfig->get( 'DBmwschema' ),
62 $mainConfig->get( 'DBprefix' )
63 ),
64 'profiler' => function ( $section ) {
65 return Profiler::instance()->scopedProfileIn( $section );
66 },
67 'trxProfiler' => Profiler::instance()->getTransactionProfiler(),
68 'replLogger' => LoggerFactory::getInstance( 'DBReplication' ),
69 'queryLogger' => LoggerFactory::getInstance( 'DBQuery' ),
70 'connLogger' => LoggerFactory::getInstance( 'DBConnection' ),
71 'perfLogger' => LoggerFactory::getInstance( 'DBPerformance' ),
72 'errorLogger' => [ MWExceptionHandler::class, 'logException' ],
73 'deprecationLogger' => [ static::class, 'logDeprecation' ],
74 'cliMode' => $wgCommandLineMode,
75 'hostname' => wfHostname(),
76 'readOnlyReason' => $readOnlyMode->getReason(),
77 'defaultGroup' => $mainConfig->get( 'DBDefaultGroup' ),
78 ];
79
80 // When making changes here, remember to also specify MediaWiki-specific options
81 // for Database classes in the relevant Installer subclass.
82 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
83 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
84 if ( isset( $lbConf['servers'] ) ) {
85 // Server array is already explicitly configured; leave alone
86 } elseif ( is_array( $mainConfig->get( 'DBservers' ) ) ) {
87 foreach ( $mainConfig->get( 'DBservers' ) as $i => $server ) {
88 if ( $server['type'] === 'sqlite' ) {
89 $server += [ 'dbDirectory' => $mainConfig->get( 'SQLiteDataDir' ) ];
90 } elseif ( $server['type'] === 'postgres' ) {
91 $server += [
92 'port' => $mainConfig->get( 'DBport' ),
93 // Work around the reserved word usage in MediaWiki schema
94 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
95 ];
96 } elseif ( $server['type'] === 'mssql' ) {
97 $server += [
98 'port' => $mainConfig->get( 'DBport' ),
99 'useWindowsAuth' => $mainConfig->get( 'DBWindowsAuthentication' )
100 ];
101 } elseif ( $server['type'] === 'mysql' ) {
102 // A DB name is not needed to connect to mysql; 'dbname' is useless.
103 // This field only defines the DB to use for unspecified DB domains.
104 $ldDB = $mainConfig->get( 'DBname' ); // local domain DB
105 $srvDB = $server['dbname'] ?? null; // server DB
106 if ( $srvDB !== null && $srvDB !== $ldDB ) {
107 self::reportMismatchedDBs( $srvDB, $ldDB );
108 }
109 }
110
111 $ldTP = $mainConfig->get( 'DBprefix' ); // local domain prefix
112 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
113 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
114 self::reportMismatchedPrefixes( $srvTP, $ldTP );
115 }
116
117 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
118 $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
119 }
120
121 $server += [
122 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
123 'flags' => DBO_DEFAULT,
124 'sqlMode' => $mainConfig->get( 'SQLMode' ),
125 ];
126
127 $lbConf['servers'][$i] = $server;
128 }
129 } else {
130 $flags = DBO_DEFAULT;
131 $flags |= $mainConfig->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
132 $flags |= $mainConfig->get( 'DBssl' ) ? DBO_SSL : 0;
133 $flags |= $mainConfig->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
134 $server = [
135 'host' => $mainConfig->get( 'DBserver' ),
136 'user' => $mainConfig->get( 'DBuser' ),
137 'password' => $mainConfig->get( 'DBpassword' ),
138 'dbname' => $mainConfig->get( 'DBname' ),
139 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
140 'type' => $mainConfig->get( 'DBtype' ),
141 'load' => 1,
142 'flags' => $flags,
143 'sqlMode' => $mainConfig->get( 'SQLMode' ),
144 ];
145 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
146 $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
147 }
148 if ( $server['type'] === 'sqlite' ) {
149 $server[ 'dbDirectory'] = $mainConfig->get( 'SQLiteDataDir' );
150 } elseif ( $server['type'] === 'postgres' ) {
151 $server['port'] = $mainConfig->get( 'DBport' );
152 // Work around the reserved word usage in MediaWiki schema
153 $server['keywordTableMap'] = [ 'user' => 'mwuser', 'text' => 'pagecontent' ];
154 } elseif ( $server['type'] === 'mssql' ) {
155 $server['port'] = $mainConfig->get( 'DBport' );
156 $server['useWindowsAuth'] = $mainConfig->get( 'DBWindowsAuthentication' );
157 }
158 $lbConf['servers'] = [ $server ];
159 }
160 if ( !isset( $lbConf['externalClusters'] ) ) {
161 $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
162 }
163 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
164 if ( isset( $lbConf['serverTemplate'] ) ) {
165 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
166 $lbConf['serverTemplate']['schema'] = $mainConfig->get( 'DBmwschema' );
167 }
168 $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
169 }
170 }
171
172 $lbConf = self::applyDefaultCaching( $lbConf, $srvCace, $mainStash, $wanCache );
173
174 return $lbConf;
175 }
176
177 /**
178 * @param array $lbConf
179 * @param BagOStuff $sCache
180 * @param BagOStuff $mStash
181 * @param WANObjectCache $wCache
182 * @return array
183 */
184 private static function applyDefaultCaching(
185 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
186 ) {
187 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
188 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
189 $lbConf['srvCache'] = $sCache;
190 }
191 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
192 $lbConf['memStash'] = $mStash;
193 }
194 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
195 $lbConf['wanCache'] = $wCache;
196 }
197
198 return $lbConf;
199 }
200
201 /**
202 * @param string $srvDB Server config database
203 * @param string $ldDB Local DB domain database
204 */
205 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
206 $e = new UnexpectedValueException(
207 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
208 "Set \$wgDBname to the database used by this wiki project. " .
209 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
210 "Functions like wfWikiId(), remote wiki database access, the use " .
211 "of Database::getDomainId(), and other features are not reliable when " .
212 "\$wgDBservers does not match the local wiki database/prefix."
213 );
214 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
215 exit;
216 }
217
218 /**
219 * @param string $srvTP Server config table prefix
220 * @param string $ldTP Local DB domain database
221 */
222 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
223 $e = new UnexpectedValueException(
224 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
225 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
226 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
227 "Functions like wfWikiId(), remote wiki database access, the use " .
228 "of Database::getDomainId(), and other features are not reliable when " .
229 "\$wgDBservers does not match the local wiki database/prefix."
230 );
231 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
232 exit;
233 }
234
235 /**
236 * Returns the LBFactory class to use and the load balancer configuration.
237 *
238 * @todo instead of this, use a ServiceContainer for managing the different implementations.
239 *
240 * @param array $config (e.g. $wgLBFactoryConf)
241 * @return string Class name
242 */
243 public static function getLBFactoryClass( array $config ) {
244 // For configuration backward compatibility after removing
245 // underscores from class names in MediaWiki 1.23.
246 $bcClasses = [
247 'LBFactory_Simple' => 'LBFactorySimple',
248 'LBFactory_Single' => 'LBFactorySingle',
249 'LBFactory_Multi' => 'LBFactoryMulti'
250 ];
251
252 $class = $config['class'];
253
254 if ( isset( $bcClasses[$class] ) ) {
255 $class = $bcClasses[$class];
256 wfDeprecated(
257 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
258 '1.23'
259 );
260 }
261
262 // For configuration backward compatibility after moving classes to namespaces (1.29)
263 $compat = [
264 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
265 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
266 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
267 ];
268
269 if ( isset( $compat[$class] ) ) {
270 $class = $compat[$class];
271 }
272
273 return $class;
274 }
275
276 public static function setSchemaAliases( LBFactory $lbFactory, Config $config ) {
277 if ( $config->get( 'DBtype' ) === 'mysql' ) {
278 /**
279 * When SQLite indexes were introduced in r45764, it was noted that
280 * SQLite requires index names to be unique within the whole database,
281 * not just within a schema. As discussed in CR r45819, to avoid the
282 * need for a schema change on existing installations, the indexes
283 * were implicitly mapped from the new names to the old names.
284 *
285 * This mapping can be removed if DB patches are introduced to alter
286 * the relevant tables in existing installations. Note that because
287 * this index mapping applies to table creation, even new installations
288 * of MySQL have the old names (except for installations created during
289 * a period where this mapping was inappropriately removed, see
290 * T154872).
291 */
292 $lbFactory->setIndexAliases( [
293 'ar_usertext_timestamp' => 'usertext_timestamp',
294 'un_user_id' => 'user_id',
295 'un_user_ip' => 'user_ip',
296 ] );
297 }
298 }
299
300 /**
301 * Log a database deprecation warning
302 * @param string $msg Deprecation message
303 */
304 public static function logDeprecation( $msg ) {
305 global $wgDevelopmentWarnings;
306
307 if ( isset( self::$loggedDeprecations[$msg] ) ) {
308 return;
309 }
310 self::$loggedDeprecations[$msg] = true;
311
312 if ( $wgDevelopmentWarnings ) {
313 trigger_error( $msg, E_USER_DEPRECATED );
314 }
315 wfDebugLog( 'deprecated', $msg, 'private' );
316 }
317 }