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