Merge "Cache redirects from Special:Redirect"
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactoryMulti.php
1 <?php
2 /**
3 * Advanced generator of database load balancing objects for database farms.
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 namespace Wikimedia\Rdbms;
25
26 use InvalidArgumentException;
27
28 /**
29 * A multi-database, multi-master factory for Wikimedia and similar installations.
30 * Ignores the old configuration globals.
31 *
32 * @ingroup Database
33 */
34 class LBFactoryMulti extends LBFactory {
35 /** @var array A map of database names to section names */
36 private $sectionsByDB;
37
38 /**
39 * @var array A 2-d map. For each section, gives a map of server names to
40 * load ratios
41 */
42 private $sectionLoads;
43
44 /**
45 * @var array[] Server info associative array
46 * @note The host, hostName and load entries will be overridden
47 */
48 private $serverTemplate;
49
50 // Optional settings
51
52 /** @var array A 3-d map giving server load ratios for each section and group */
53 private $groupLoadsBySection = [];
54
55 /** @var array A 3-d map giving server load ratios by DB name */
56 private $groupLoadsByDB = [];
57
58 /** @var array A map of hostname to IP address */
59 private $hostsByName = [];
60
61 /** @var array A map of external storage cluster name to server load map */
62 private $externalLoads = [];
63
64 /**
65 * @var array A set of server info keys overriding serverTemplate for
66 * external storage
67 */
68 private $externalTemplateOverrides;
69
70 /**
71 * @var array A 2-d map overriding serverTemplate and
72 * externalTemplateOverrides on a server-by-server basis. Applies to both
73 * core and external storage
74 */
75 private $templateOverridesByServer;
76
77 /** @var array A 2-d map overriding the server info by section */
78 private $templateOverridesBySection;
79
80 /** @var array A 2-d map overriding the server info by external storage cluster */
81 private $templateOverridesByCluster;
82
83 /** @var array An override array for all master servers */
84 private $masterTemplateOverrides;
85
86 /**
87 * @var array|bool A map of section name to read-only message. Missing or
88 * false for read/write
89 */
90 private $readOnlyBySection = [];
91
92 /** @var array Load balancer factory configuration */
93 private $conf;
94
95 /** @var LoadBalancer[] */
96 private $mainLBs = [];
97
98 /** @var LoadBalancer[] */
99 private $extLBs = [];
100
101 /** @var string */
102 private $loadMonitorClass = 'LoadMonitor';
103
104 /** @var string */
105 private $lastDomain;
106
107 /** @var string */
108 private $lastSection;
109
110 /**
111 * @see LBFactory::__construct()
112 *
113 * Template override precedence (highest => lowest):
114 * - templateOverridesByServer
115 * - masterTemplateOverrides
116 * - templateOverridesBySection/templateOverridesByCluster
117 * - externalTemplateOverrides
118 * - serverTemplate
119 * Overrides only work on top level keys (so nested values will not be merged).
120 *
121 * Server configuration maps should be of the format Database::factory() requires.
122 * Additionally, a 'max lag' key should also be set on server maps, indicating how stale the
123 * data can be before the load balancer tries to avoid using it. The map can have 'is static'
124 * set to disable blocking replication sync checks (intended for archive servers with
125 * unchanging data).
126 *
127 * @param array $conf Parameters of LBFactory::__construct() as well as:
128 * - sectionsByDB Map of database names to section names.
129 * - sectionLoads 2-d map. For each section, gives a map of server names to
130 * load ratios. For example:
131 * [
132 * 'section1' => [
133 * 'db1' => 100,
134 * 'db2' => 100
135 * ]
136 * ]
137 * - serverTemplate Server configuration map intended for Database::factory().
138 * Note that "host", "hostName" and "load" entries will be
139 * overridden by "sectionLoads" and "hostsByName".
140 * - groupLoadsBySection 3-d map giving server load ratios for each section/group.
141 * For example:
142 * [
143 * 'section1' => [
144 * 'group1' => [
145 * 'db1' => 100,
146 * 'db2' => 100
147 * ]
148 * ]
149 * ]
150 * - groupLoadsByDB 3-d map giving server load ratios by DB name.
151 * - hostsByName Map of hostname to IP address.
152 * - externalLoads Map of external storage cluster name to server load map.
153 * - externalTemplateOverrides Set of server configuration maps overriding
154 * "serverTemplate" for external storage.
155 * - templateOverridesByServer 2-d map overriding "serverTemplate" and
156 * "externalTemplateOverrides" on a server-by-server basis.
157 * Applies to both core and external storage.
158 * - templateOverridesBySection 2-d map overriding the server configuration maps by section.
159 * - templateOverridesByCluster 2-d map overriding the server configuration maps by external
160 * storage cluster.
161 * - masterTemplateOverrides Server configuration map overrides for all master servers.
162 * - loadMonitorClass Name of the LoadMonitor class to always use.
163 * - readOnlyBySection A map of section name to read-only message.
164 * Missing or false for read/write.
165 */
166 public function __construct( array $conf ) {
167 parent::__construct( $conf );
168
169 $this->conf = $conf;
170 $required = [ 'sectionsByDB', 'sectionLoads', 'serverTemplate' ];
171 $optional = [ 'groupLoadsBySection', 'groupLoadsByDB', 'hostsByName',
172 'externalLoads', 'externalTemplateOverrides', 'templateOverridesByServer',
173 'templateOverridesByCluster', 'templateOverridesBySection', 'masterTemplateOverrides',
174 'readOnlyBySection', 'loadMonitorClass' ];
175
176 foreach ( $required as $key ) {
177 if ( !isset( $conf[$key] ) ) {
178 throw new InvalidArgumentException( __CLASS__ . ": $key is required." );
179 }
180 $this->$key = $conf[$key];
181 }
182
183 foreach ( $optional as $key ) {
184 if ( isset( $conf[$key] ) ) {
185 $this->$key = $conf[$key];
186 }
187 }
188 }
189
190 /**
191 * @param bool|string $domain
192 * @return string
193 */
194 private function getSectionForDomain( $domain = false ) {
195 if ( $this->lastDomain === $domain ) {
196 return $this->lastSection;
197 }
198 list( $dbName, ) = $this->getDBNameAndPrefix( $domain );
199 $section = $this->sectionsByDB[$dbName] ?? 'DEFAULT';
200 $this->lastSection = $section;
201 $this->lastDomain = $domain;
202
203 return $section;
204 }
205
206 /**
207 * @param bool|string $domain
208 * @return LoadBalancer
209 */
210 public function newMainLB( $domain = false ) {
211 list( $dbName, ) = $this->getDBNameAndPrefix( $domain );
212 $section = $this->getSectionForDomain( $domain );
213 $groupLoads = $this->groupLoadsByDB[$dbName] ?? [];
214
215 if ( isset( $this->groupLoadsBySection[$section] ) ) {
216 $groupLoads = array_merge_recursive(
217 $groupLoads, $this->groupLoadsBySection[$section] );
218 }
219
220 $readOnlyReason = $this->readOnlyReason;
221 // Use the LB-specific read-only reason if everything isn't already read-only
222 if ( $readOnlyReason === false && isset( $this->readOnlyBySection[$section] ) ) {
223 $readOnlyReason = $this->readOnlyBySection[$section];
224 }
225
226 $template = $this->serverTemplate;
227 if ( isset( $this->templateOverridesBySection[$section] ) ) {
228 $template = $this->templateOverridesBySection[$section] + $template;
229 }
230
231 return $this->newLoadBalancer(
232 $template,
233 $this->sectionLoads[$section],
234 $groupLoads,
235 $readOnlyReason
236 );
237 }
238
239 /**
240 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
241 * @return LoadBalancer
242 */
243 public function getMainLB( $domain = false ) {
244 $section = $this->getSectionForDomain( $domain );
245 if ( !isset( $this->mainLBs[$section] ) ) {
246 $this->mainLBs[$section] = $this->newMainLB( $domain );
247 }
248
249 return $this->mainLBs[$section];
250 }
251
252 public function newExternalLB( $cluster ) {
253 if ( !isset( $this->externalLoads[$cluster] ) ) {
254 throw new InvalidArgumentException( __METHOD__ . ": Unknown cluster \"$cluster\"" );
255 }
256 $template = $this->serverTemplate;
257 if ( $this->externalTemplateOverrides ) {
258 $template = $this->externalTemplateOverrides + $template;
259 }
260 if ( isset( $this->templateOverridesByCluster[$cluster] ) ) {
261 $template = $this->templateOverridesByCluster[$cluster] + $template;
262 }
263
264 return $this->newLoadBalancer(
265 $template,
266 $this->externalLoads[$cluster],
267 [],
268 $this->readOnlyReason
269 );
270 }
271
272 public function getExternalLB( $cluster ) {
273 if ( !isset( $this->extLBs[$cluster] ) ) {
274 $this->extLBs[$cluster] = $this->newExternalLB( $cluster );
275 }
276
277 return $this->extLBs[$cluster];
278 }
279
280 public function getAllMainLBs() {
281 $lbs = [];
282 foreach ( $this->sectionsByDB as $db => $section ) {
283 if ( !isset( $lbs[$section] ) ) {
284 $lbs[$section] = $this->getMainLB( $db );
285 }
286 }
287
288 return $lbs;
289 }
290
291 public function getAllExternalLBs() {
292 $lbs = [];
293 foreach ( $this->externalLoads as $cluster => $unused ) {
294 $lbs[$cluster] = $this->getExternalLB( $cluster );
295 }
296
297 return $lbs;
298 }
299
300 /**
301 * Make a new load balancer object based on template and load array
302 *
303 * @param array $template
304 * @param array $loads
305 * @param array $groupLoads
306 * @param string|bool $readOnlyReason
307 * @return LoadBalancer
308 */
309 private function newLoadBalancer( $template, $loads, $groupLoads, $readOnlyReason ) {
310 $lb = new LoadBalancer( array_merge(
311 $this->baseLoadBalancerParams(),
312 [
313 'servers' => $this->makeServerArray( $template, $loads, $groupLoads ),
314 'loadMonitor' => [ 'class' => $this->loadMonitorClass ],
315 'readOnlyReason' => $readOnlyReason
316 ]
317 ) );
318 $this->initLoadBalancer( $lb );
319
320 return $lb;
321 }
322
323 /**
324 * Make a server array as expected by LoadBalancer::__construct, using a template and load array
325 *
326 * @param array $template
327 * @param array $loads
328 * @param array $groupLoads
329 * @return array
330 */
331 private function makeServerArray( $template, $loads, $groupLoads ) {
332 $servers = [];
333 $master = true;
334 $groupLoadsByServer = $this->reindexGroupLoads( $groupLoads );
335 foreach ( $groupLoadsByServer as $server => $stuff ) {
336 if ( !isset( $loads[$server] ) ) {
337 $loads[$server] = 0;
338 }
339 }
340 foreach ( $loads as $serverName => $load ) {
341 $serverInfo = $template;
342 if ( $master ) {
343 $serverInfo['master'] = true;
344 if ( $this->masterTemplateOverrides ) {
345 $serverInfo = $this->masterTemplateOverrides + $serverInfo;
346 }
347 $master = false;
348 } else {
349 $serverInfo['replica'] = true;
350 }
351 if ( isset( $this->templateOverridesByServer[$serverName] ) ) {
352 $serverInfo = $this->templateOverridesByServer[$serverName] + $serverInfo;
353 }
354 if ( isset( $groupLoadsByServer[$serverName] ) ) {
355 $serverInfo['groupLoads'] = $groupLoadsByServer[$serverName];
356 }
357 $serverInfo['host'] = $this->hostsByName[$serverName] ?? $serverName;
358 $serverInfo['hostName'] = $serverName;
359 $serverInfo['load'] = $load;
360 $serverInfo += [ 'flags' => IDatabase::DBO_DEFAULT ];
361
362 $servers[] = $serverInfo;
363 }
364
365 return $servers;
366 }
367
368 /**
369 * Take a group load array indexed by group then server, and reindex it by server then group
370 * @param array $groupLoads
371 * @return array
372 */
373 private function reindexGroupLoads( $groupLoads ) {
374 $reindexed = [];
375 foreach ( $groupLoads as $group => $loads ) {
376 foreach ( $loads as $server => $load ) {
377 $reindexed[$server][$group] = $load;
378 }
379 }
380
381 return $reindexed;
382 }
383
384 /**
385 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
386 * @return array [database name, table prefix]
387 */
388 private function getDBNameAndPrefix( $domain = false ) {
389 $domain = ( $domain === false )
390 ? $this->localDomain
391 : DatabaseDomain::newFromId( $domain );
392
393 return [ $domain->getDatabase(), $domain->getTablePrefix() ];
394 }
395
396 /**
397 * Execute a function for each tracked load balancer
398 * The callback is called with the load balancer as the first parameter,
399 * and $params passed as the subsequent parameters.
400 * @param callable $callback
401 * @param array $params
402 */
403 public function forEachLB( $callback, array $params = [] ) {
404 foreach ( $this->mainLBs as $lb ) {
405 $callback( $lb, ...$params );
406 }
407 foreach ( $this->extLBs as $lb ) {
408 $callback( $lb, ...$params );
409 }
410 }
411 }