Merge "Avoid the use of IDatabase::insert() return value"
[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'] ?? null; // 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 'utf8Mode' => $mainConfig->get( 'DBmysql5' )
126 ];
127
128 $lbConf['servers'][$i] = $server;
129 }
130 } else {
131 $flags = DBO_DEFAULT;
132 $flags |= $mainConfig->get( 'DebugDumpSql' ) ? DBO_DEBUG : 0;
133 $flags |= $mainConfig->get( 'DBssl' ) ? DBO_SSL : 0;
134 $flags |= $mainConfig->get( 'DBcompress' ) ? DBO_COMPRESS : 0;
135 $server = [
136 'host' => $mainConfig->get( 'DBserver' ),
137 'user' => $mainConfig->get( 'DBuser' ),
138 'password' => $mainConfig->get( 'DBpassword' ),
139 'dbname' => $mainConfig->get( 'DBname' ),
140 'tablePrefix' => $mainConfig->get( 'DBprefix' ),
141 'type' => $mainConfig->get( 'DBtype' ),
142 'load' => 1,
143 'flags' => $flags,
144 'sqlMode' => $mainConfig->get( 'SQLMode' ),
145 'utf8Mode' => $mainConfig->get( 'DBmysql5' )
146 ];
147 if ( in_array( $server['type'], $typesWithSchema, true ) ) {
148 $server += [ 'schema' => $mainConfig->get( 'DBmwschema' ) ];
149 }
150 if ( $server['type'] === 'sqlite' ) {
151 $server[ 'dbDirectory'] = $mainConfig->get( 'SQLiteDataDir' );
152 } elseif ( $server['type'] === 'postgres' ) {
153 $server['port'] = $mainConfig->get( 'DBport' );
154 // Work around the reserved word usage in MediaWiki schema
155 $server['keywordTableMap'] = [ 'user' => 'mwuser', 'text' => 'pagecontent' ];
156 } elseif ( $server['type'] === 'mssql' ) {
157 $server['port'] = $mainConfig->get( 'DBport' );
158 $server['useWindowsAuth'] = $mainConfig->get( 'DBWindowsAuthentication' );
159 }
160 $lbConf['servers'] = [ $server ];
161 }
162 if ( !isset( $lbConf['externalClusters'] ) ) {
163 $lbConf['externalClusters'] = $mainConfig->get( 'ExternalServers' );
164 }
165 } elseif ( $lbConf['class'] === Wikimedia\Rdbms\LBFactoryMulti::class ) {
166 if ( isset( $lbConf['serverTemplate'] ) ) {
167 if ( in_array( $lbConf['serverTemplate']['type'], $typesWithSchema, true ) ) {
168 $lbConf['serverTemplate']['schema'] = $mainConfig->get( 'DBmwschema' );
169 }
170 $lbConf['serverTemplate']['sqlMode'] = $mainConfig->get( 'SQLMode' );
171 $lbConf['serverTemplate']['utf8Mode'] = $mainConfig->get( 'DBmysql5' );
172 }
173 }
174
175 $lbConf = self::applyDefaultCaching( $lbConf, $srvCace, $mainStash, $wanCache );
176
177 return $lbConf;
178 }
179
180 /**
181 * @param array $lbConf
182 * @param BagOStuff $sCache
183 * @param BagOStuff $mStash
184 * @param WANObjectCache $wCache
185 * @return array
186 */
187 private static function applyDefaultCaching(
188 array $lbConf, BagOStuff $sCache, BagOStuff $mStash, WANObjectCache $wCache
189 ) {
190 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
191 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
192 $lbConf['srvCache'] = $sCache;
193 }
194 if ( $mStash->getQoS( $mStash::ATTR_EMULATION ) > $mStash::QOS_EMULATION_SQL ) {
195 $lbConf['memStash'] = $mStash;
196 }
197 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
198 $lbConf['wanCache'] = $wCache;
199 }
200
201 return $lbConf;
202 }
203
204 /**
205 * @param string $srvDB Server config database
206 * @param string $ldDB Local DB domain database
207 */
208 private static function reportMismatchedDBs( $srvDB, $ldDB ) {
209 $e = new UnexpectedValueException(
210 "\$wgDBservers has dbname='$srvDB' but \$wgDBname='$ldDB'. " .
211 "Set \$wgDBname to the database used by this wiki project. " .
212 "There is rarely a need to set 'dbname' in \$wgDBservers. " .
213 "Functions like wfWikiId(), remote wiki database access, the use " .
214 "of Database::getDomainId(), and other features are not reliable when " .
215 "\$wgDBservers does not match the local wiki database/prefix."
216 );
217 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
218 exit;
219 }
220
221 /**
222 * @param string $srvTP Server config table prefix
223 * @param string $ldTP Local DB domain database
224 */
225 private static function reportMismatchedPrefixes( $srvTP, $ldTP ) {
226 $e = new UnexpectedValueException(
227 "\$wgDBservers has tablePrefix='$srvTP' but \$wgDBprefix='$ldTP'. " .
228 "Set \$wgDBprefix to the table prefix used by this wiki project. " .
229 "There is rarely a need to set 'tablePrefix' in \$wgDBservers. " .
230 "Functions like wfWikiId(), remote wiki database access, the use " .
231 "of Database::getDomainId(), and other features are not reliable when " .
232 "\$wgDBservers does not match the local wiki database/prefix."
233 );
234 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
235 exit;
236 }
237
238 /**
239 * Returns the LBFactory class to use and the load balancer configuration.
240 *
241 * @todo instead of this, use a ServiceContainer for managing the different implementations.
242 *
243 * @param array $config (e.g. $wgLBFactoryConf)
244 * @return string Class name
245 */
246 public static function getLBFactoryClass( array $config ) {
247 // For configuration backward compatibility after removing
248 // underscores from class names in MediaWiki 1.23.
249 $bcClasses = [
250 'LBFactory_Simple' => 'LBFactorySimple',
251 'LBFactory_Single' => 'LBFactorySingle',
252 'LBFactory_Multi' => 'LBFactoryMulti'
253 ];
254
255 $class = $config['class'];
256
257 if ( isset( $bcClasses[$class] ) ) {
258 $class = $bcClasses[$class];
259 wfDeprecated(
260 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
261 '1.23'
262 );
263 }
264
265 // For configuration backward compatibility after moving classes to namespaces (1.29)
266 $compat = [
267 'LBFactorySingle' => Wikimedia\Rdbms\LBFactorySingle::class,
268 'LBFactorySimple' => Wikimedia\Rdbms\LBFactorySimple::class,
269 'LBFactoryMulti' => Wikimedia\Rdbms\LBFactoryMulti::class
270 ];
271
272 if ( isset( $compat[$class] ) ) {
273 $class = $compat[$class];
274 }
275
276 return $class;
277 }
278
279 public static function setSchemaAliases( LBFactory $lbFactory, Config $config ) {
280 if ( $config->get( 'DBtype' ) === 'mysql' ) {
281 /**
282 * When SQLite indexes were introduced in r45764, it was noted that
283 * SQLite requires index names to be unique within the whole database,
284 * not just within a schema. As discussed in CR r45819, to avoid the
285 * need for a schema change on existing installations, the indexes
286 * were implicitly mapped from the new names to the old names.
287 *
288 * This mapping can be removed if DB patches are introduced to alter
289 * the relevant tables in existing installations. Note that because
290 * this index mapping applies to table creation, even new installations
291 * of MySQL have the old names (except for installations created during
292 * a period where this mapping was inappropriately removed, see
293 * T154872).
294 */
295 $lbFactory->setIndexAliases( [
296 'ar_usertext_timestamp' => 'usertext_timestamp',
297 'un_user_id' => 'user_id',
298 'un_user_ip' => 'user_ip',
299 ] );
300 }
301 }
302
303 /**
304 * Log a database deprecation warning
305 * @param string $msg Deprecation message
306 */
307 public static function logDeprecation( $msg ) {
308 global $wgDevelopmentWarnings;
309
310 if ( isset( self::$loggedDeprecations[$msg] ) ) {
311 return;
312 }
313 self::$loggedDeprecations[$msg] = true;
314
315 if ( $wgDevelopmentWarnings ) {
316 trigger_error( $msg, E_USER_DEPRECATED );
317 }
318 wfDebugLog( 'deprecated', $msg, 'private' );
319 }
320 }