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