Merge "Don't return a result of a void function"
[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 $serversCheck = [];
81 // When making changes here, remember to also specify MediaWiki-specific options
82 // for Database classes in the relevant Installer subclass.
83 // Such as MysqlInstaller::openConnection and PostgresInstaller::openConnectionWithParams.
84 if ( $lbConf['class'] === Wikimedia\Rdbms\LBFactorySimple::class ) {
85 if ( isset( $lbConf['servers'] ) ) {
86 // Server array is already explicitly configured; leave alone
87 } elseif ( is_array( $mainConfig->get( 'DBservers' ) ) ) {
88 $lbConf['servers'] = [];
89 foreach ( $mainConfig->get( 'DBservers' ) as $i => $server ) {
90 if ( $server['type'] === 'sqlite' ) {
91 $server += [ 'dbDirectory' => $mainConfig->get( 'SQLiteDataDir' ) ];
92 } elseif ( $server['type'] === 'postgres' ) {
93 $server += [
94 'port' => $mainConfig->get( 'DBport' ),
95 // Work around the reserved word usage in MediaWiki schema
96 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ]
97 ];
98 } elseif ( $server['type'] === 'mssql' ) {
99 $server += [
100 'port' => $mainConfig->get( 'DBport' ),
101 'useWindowsAuth' => $mainConfig->get( 'DBWindowsAuthentication' )
102 ];
103 }
104
105 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
106 $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
107 }
108
109 $server += [
110 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
111 'flags' => DBO_DEFAULT,
112 'sqlMode' => $mainConfig->get( 'SQLMode' ),
113 ];
114
115 $lbConf['servers'][$i] = $server;
116 }
117 } else {
118 $flags = DBO_DEFAULT;
119 $flags |= $mainConfig->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
120 $flags |= $mainConfig->get( 'DBssl' ) ? DBO_SSL : 0;
121 $flags |= $mainConfig->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
122 $server = [
123 'host' => $mainConfig->get( 'DBserver' ),
124 'user' => $mainConfig->get( 'DBuser' ),
125 'password' => $mainConfig->get( 'DBpassword' ),
126 'dbname' => $mainConfig->get( 'DBname' ),
127 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
128 'type' => $mainConfig->get( 'DBtype' ),
129 'load' => 1,
130 'flags' => $flags,
131 'sqlMode' => $mainConfig->get( 'SQLMode' ),
132 ];
133 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
134 $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
135 }
136 if ( $server['type'] === 'sqlite' ) {
137 $server[ 'dbDirectory'] = $mainConfig->get( 'SQLiteDataDir' );
138 } elseif ( $server['type'] === 'postgres' ) {
139 $server['port'] = $mainConfig->get( 'DBport' );
140 // Work around the reserved word usage in MediaWiki schema
141 $server['keywordTableMap'] = [ 'user' => 'mwuser', 'text' => 'pagecontent' ];
142 } elseif ( $server['type'] === 'mssql' ) {
143 $server['port'] = $mainConfig->get( 'DBport' );
144 $server['useWindowsAuth'] = $mainConfig->get( 'DBWindowsAuthentication' );
145 }
146 $lbConf['servers'] = [ $server ];
147 }
148 if ( !isset( $lbConf['externalClusters'] ) ) {
149 $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
150 }
151
152 $serversCheck = $lbConf['servers'];
153 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
154 if ( isset( $lbConf['serverTemplate'] ) ) {
155 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
156 $lbConf['serverTemplate']['schema'] = $mainConfig->get( 'DBmwschema' );
157 }
158 $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
159 }
160 $serversCheck = $lbConf['serverTemplate'] ?? [];
161 }
162
163 self::sanityCheckServerConfig( $serversCheck, $mainConfig );
164 $lbConf = self::applyDefaultCaching( $lbConf, $srvCace, $mainStash, $wanCache );
165
166 return $lbConf;
167 }
168
169 /**
170 * @param array $lbConf
171 * @param BagOStuff $sCache
172 * @param BagOStuff $mStash
173 * @param WANObjectCache $wCache
174 * @return array
175 */
176 private static function applyDefaultCaching(
177 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
178 ) {
179 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
180 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
181 $lbConf['srvCache'] = $sCache;
182 }
183 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
184 $lbConf['memStash'] = $mStash;
185 }
186 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
187 $lbConf['wanCache'] = $wCache;
188 }
189
190 return $lbConf;
191 }
192
193 /**
194 * @param array $servers
195 * @param Config $mainConfig
196 */
197 private static function sanityCheckServerConfig( array $servers, Config $mainConfig ) {
198 $ldDB = $mainConfig->get( 'DBname' ); // local domain DB
199 $ldTP = $mainConfig->get( 'DBprefix' ); // local domain prefix
200
201 foreach ( $servers as $server ) {
202 $type = $server['type'] ?? null;
203 $srvDB = $server['dbname'] ?? null; // server DB
204 $srvTP = $server['tablePrefix'] ?? ''; // server table prefix
205
206 if ( $type === 'mysql' ) {
207 // A DB name is not needed to connect to mysql; 'dbname' is useless.
208 // This field only defines the DB to use for unspecified DB domains.
209 if ( $srvDB !== null && $srvDB !== $ldDB ) {
210 self::reportMismatchedDBs( $srvDB, $ldDB );
211 }
212 } elseif ( $type === 'postgres' ) {
213 if ( $srvTP !== '' ) {
214 self::reportIfPrefixSet( $srvTP, $type );
215 }
216 }
217
218 if ( $srvTP !== '' && $srvTP !== $ldTP ) {
219 self::reportMismatchedPrefixes( $srvTP, $ldTP );
220 }
221 }
222 }
223
224 /**
225 * @param string $prefix Table prefix
226 * @param string $dbType Database type
227 */
228 private static function reportIfPrefixSet( $prefix, $dbType ) {
229 $e = new UnexpectedValueException(
230 "\$wgDBprefix is set to '$prefix' but the database type is '$dbType'. " .
231 "MediaWiki does not support using a table prefix with this RDBMS type."
232 );
233 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
234 exit;
235 }
236
237 /**
238 * @param string $srvDB Server config database
239 * @param string $ldDB Local DB domain database
240 */
241 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
242 $e = new UnexpectedValueException(
243 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
244 "Set \$wgDBname to the database used by this wiki project. " .
245 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
246 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
247 "use of Database::getDomainId(), and other features are not reliable when " .
248 "\$wgDBservers does not match the local wiki database/prefix."
249 );
250 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
251 exit;
252 }
253
254 /**
255 * @param string $srvTP Server config table prefix
256 * @param string $ldTP Local DB domain database
257 */
258 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
259 $e = new UnexpectedValueException(
260 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
261 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
262 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
263 "Cross-wiki database access, use of WikiMap::getCurrentWikiDbDomain(), " .
264 "use of Database::getDomainId(), and other features are not reliable when " .
265 "\$wgDBservers does not match the local wiki database/prefix."
266 );
267 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
268 exit;
269 }
270
271 /**
272 * Returns the LBFactory class to use and the load balancer configuration.
273 *
274 * @todo instead of this, use a ServiceContainer for managing the different implementations.
275 *
276 * @param array $config (e.g. $wgLBFactoryConf)
277 * @return string Class name
278 */
279 public static function getLBFactoryClass( array $config ) {
280 // For configuration backward compatibility after removing
281 // underscores from class names in MediaWiki 1.23.
282 $bcClasses = [
283 'LBFactory_Simple' => 'LBFactorySimple',
284 'LBFactory_Single' => 'LBFactorySingle',
285 'LBFactory_Multi' => 'LBFactoryMulti'
286 ];
287
288 $class = $config['class'];
289
290 if ( isset( $bcClasses[$class] ) ) {
291 $class = $bcClasses[$class];
292 wfDeprecated(
293 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
294 '1.23'
295 );
296 }
297
298 // For configuration backward compatibility after moving classes to namespaces (1.29)
299 $compat = [
300 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
301 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
302 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
303 ];
304
305 if ( isset( $compat[$class] ) ) {
306 $class = $compat[$class];
307 }
308
309 return $class;
310 }
311
312 public static function setSchemaAliases( LBFactory $lbFactory, Config $config ) {
313 if ( $config->get( 'DBtype' ) === 'mysql' ) {
314 /**
315 * When SQLite indexes were introduced in r45764, it was noted that
316 * SQLite requires index names to be unique within the whole database,
317 * not just within a schema. As discussed in CR r45819, to avoid the
318 * need for a schema change on existing installations, the indexes
319 * were implicitly mapped from the new names to the old names.
320 *
321 * This mapping can be removed if DB patches are introduced to alter
322 * the relevant tables in existing installations. Note that because
323 * this index mapping applies to table creation, even new installations
324 * of MySQL have the old names (except for installations created during
325 * a period where this mapping was inappropriately removed, see
326 * T154872).
327 */
328 $lbFactory->setIndexAliases( [
329 'ar_usertext_timestamp' => 'usertext_timestamp',
330 'un_user_id' => 'user_id',
331 'un_user_ip' => 'user_ip',
332 ] );
333 }
334 }
335
336 /**
337 * Log a database deprecation warning
338 * @param string $msg Deprecation message
339 */
340 public static function logDeprecation( $msg ) {
341 global $wgDevelopmentWarnings;
342
343 if ( isset( self::$loggedDeprecations[$msg] ) ) {
344 return;
345 }
346 self::$loggedDeprecations[$msg] = true;
347
348 if ( $wgDevelopmentWarnings ) {
349 trigger_error( $msg, E_USER_DEPRECATED );
350 }
351 wfDebugLog( 'deprecated', $msg, 'private' );
352 }
353 }