Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like LoadBalancer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use LoadBalancer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
30 | class LoadBalancer { |
||
31 | /** @var array[] Map of (server index => server config array) */ |
||
32 | private $mServers; |
||
33 | /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */ |
||
34 | private $mConns; |
||
35 | /** @var array Map of (server index => weight) */ |
||
36 | private $mLoads; |
||
37 | /** @var array[] Map of (group => server index => weight) */ |
||
38 | private $mGroupLoads; |
||
39 | /** @var bool Whether to disregard slave lag as a factor in slave selection */ |
||
40 | private $mAllowLagged; |
||
41 | /** @var integer Seconds to spend waiting on slave lag to resolve */ |
||
42 | private $mWaitTimeout; |
||
43 | /** @var array LBFactory information */ |
||
44 | private $mParentInfo; |
||
45 | |||
46 | /** @var string The LoadMonitor subclass name */ |
||
47 | private $mLoadMonitorClass; |
||
48 | /** @var LoadMonitor */ |
||
49 | private $mLoadMonitor; |
||
50 | /** @var BagOStuff */ |
||
51 | private $srvCache; |
||
52 | |||
53 | /** @var bool|DatabaseBase Database connection that caused a problem */ |
||
54 | private $mErrorConnection; |
||
55 | /** @var integer The generic (not query grouped) slave index (of $mServers) */ |
||
56 | private $mReadIndex; |
||
57 | /** @var bool|DBMasterPos False if not set */ |
||
58 | private $mWaitForPos; |
||
59 | /** @var bool Whether the generic reader fell back to a lagged slave */ |
||
60 | private $laggedSlaveMode = false; |
||
61 | /** @var bool Whether the generic reader fell back to a lagged slave */ |
||
62 | private $slavesDownMode = false; |
||
63 | /** @var string The last DB selection or connection error */ |
||
64 | private $mLastError = 'Unknown error'; |
||
65 | /** @var string|bool Reason the LB is read-only or false if not */ |
||
66 | private $readOnlyReason = false; |
||
67 | /** @var integer Total connections opened */ |
||
68 | private $connsOpened = 0; |
||
69 | |||
70 | /** @var TransactionProfiler */ |
||
71 | protected $trxProfiler; |
||
72 | |||
73 | /** @var integer Warn when this many connection are held */ |
||
74 | const CONN_HELD_WARN_THRESHOLD = 10; |
||
75 | /** @var integer Default 'max lag' when unspecified */ |
||
76 | const MAX_LAG = 10; |
||
77 | /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */ |
||
78 | const POS_WAIT_TIMEOUT = 10; |
||
79 | |||
80 | /** |
||
81 | * @var boolean |
||
82 | */ |
||
83 | private $disabled = false; |
||
84 | |||
85 | /** |
||
86 | * @param array $params Array with keys: |
||
87 | * - servers : Required. Array of server info structures. |
||
88 | * - loadMonitor : Name of a class used to fetch server lag and load. |
||
89 | * - readOnlyReason : Reason the master DB is read-only if so [optional] |
||
90 | * @throws MWException |
||
91 | */ |
||
92 | public function __construct( array $params ) { |
||
145 | |||
146 | /** |
||
147 | * Get a LoadMonitor instance |
||
148 | * |
||
149 | * @return LoadMonitor |
||
150 | */ |
||
151 | private function getLoadMonitor() { |
||
159 | |||
160 | /** |
||
161 | * Get or set arbitrary data used by the parent object, usually an LBFactory |
||
162 | * @param mixed $x |
||
163 | * @return mixed |
||
164 | */ |
||
165 | public function parentInfo( $x = null ) { |
||
168 | |||
169 | /** |
||
170 | * @param array $loads |
||
171 | * @param bool|string $wiki Wiki to get non-lagged for |
||
172 | * @param int $maxLag Restrict the maximum allowed lag to this many seconds |
||
173 | * @return bool|int|string |
||
174 | */ |
||
175 | private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self::MAX_LAG ) { |
||
217 | |||
218 | /** |
||
219 | * Get the index of the reader connection, which may be a slave |
||
220 | * This takes into account load ratios and lag times. It should |
||
221 | * always return a consistent index during a given invocation |
||
222 | * |
||
223 | * Side effect: opens connections to databases |
||
224 | * @param string|bool $group Query group, or false for the generic reader |
||
225 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
226 | * @throws MWException |
||
227 | * @return bool|int|string |
||
228 | */ |
||
229 | public function getReaderIndex( $group = false, $wiki = false ) { |
||
357 | |||
358 | /** |
||
359 | * Set the master wait position |
||
360 | * If a DB_SLAVE connection has been opened already, waits |
||
361 | * Otherwise sets a variable telling it to wait if such a connection is opened |
||
362 | * @param DBMasterPos $pos |
||
363 | */ |
||
364 | public function waitFor( $pos ) { |
||
375 | |||
376 | /** |
||
377 | * Set the master wait position and wait for a "generic" slave to catch up to it |
||
378 | * |
||
379 | * This can be used a faster proxy for waitForAll() |
||
380 | * |
||
381 | * @param DBMasterPos $pos |
||
382 | * @param int $timeout Max seconds to wait; default is mWaitTimeout |
||
383 | * @return bool Success (able to connect and no timeouts reached) |
||
384 | * @since 1.26 |
||
385 | */ |
||
386 | public function waitForOne( $pos, $timeout = null ) { |
||
406 | |||
407 | /** |
||
408 | * Set the master wait position and wait for ALL slaves to catch up to it |
||
409 | * @param DBMasterPos $pos |
||
410 | * @param int $timeout Max seconds to wait; default is mWaitTimeout |
||
411 | * @return bool Success (able to connect and no timeouts reached) |
||
412 | */ |
||
413 | public function waitForAll( $pos, $timeout = null ) { |
||
426 | |||
427 | /** |
||
428 | * Get any open connection to a given server index, local or foreign |
||
429 | * Returns false if there is no connection open |
||
430 | * |
||
431 | * @param int $i |
||
432 | * @return DatabaseBase|bool False on failure |
||
433 | */ |
||
434 | public function getAnyOpenConnection( $i ) { |
||
443 | |||
444 | /** |
||
445 | * Wait for a given slave to catch up to the master pos stored in $this |
||
446 | * @param int $index Server index |
||
447 | * @param bool $open Check the server even if a new connection has to be made |
||
448 | * @param int $timeout Max seconds to wait; default is mWaitTimeout |
||
449 | * @return bool |
||
450 | */ |
||
451 | protected function doWait( $index, $open = false, $timeout = null ) { |
||
508 | |||
509 | /** |
||
510 | * Get a connection by index |
||
511 | * This is the main entry point for this class. |
||
512 | * |
||
513 | * @param int $i Server index |
||
514 | * @param array|string|bool $groups Query group(s), or false for the generic reader |
||
515 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
516 | * |
||
517 | * @throws MWException |
||
518 | * @return DatabaseBase |
||
519 | */ |
||
520 | public function getConnection( $i, $groups = [], $wiki = false ) { |
||
586 | |||
587 | /** |
||
588 | * Mark a foreign connection as being available for reuse under a different |
||
589 | * DB name or prefix. This mechanism is reference-counted, and must be called |
||
590 | * the same number of times as getConnection() to work. |
||
591 | * |
||
592 | * @param DatabaseBase $conn |
||
593 | * @throws MWException |
||
594 | */ |
||
595 | public function reuseConnection( $conn ) { |
||
633 | |||
634 | /** |
||
635 | * Get a database connection handle reference |
||
636 | * |
||
637 | * The handle's methods wrap simply wrap those of a DatabaseBase handle |
||
638 | * |
||
639 | * @see LoadBalancer::getConnection() for parameter information |
||
640 | * |
||
641 | * @param int $db |
||
642 | * @param array|string|bool $groups Query group(s), or false for the generic reader |
||
643 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
644 | * @return DBConnRef |
||
645 | */ |
||
646 | public function getConnectionRef( $db, $groups = [], $wiki = false ) { |
||
649 | |||
650 | /** |
||
651 | * Get a database connection handle reference without connecting yet |
||
652 | * |
||
653 | * The handle's methods wrap simply wrap those of a DatabaseBase handle |
||
654 | * |
||
655 | * @see LoadBalancer::getConnection() for parameter information |
||
656 | * |
||
657 | * @param int $db |
||
658 | * @param array|string|bool $groups Query group(s), or false for the generic reader |
||
659 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
660 | * @return DBConnRef |
||
661 | */ |
||
662 | public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) { |
||
665 | |||
666 | /** |
||
667 | * Open a connection to the server given by the specified index |
||
668 | * Index must be an actual index into the array. |
||
669 | * If the server is already open, returns it. |
||
670 | * |
||
671 | * On error, returns false, and the connection which caused the |
||
672 | * error will be available via $this->mErrorConnection. |
||
673 | * |
||
674 | * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError. |
||
675 | * |
||
676 | * @param int $i Server index |
||
677 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
678 | * @return DatabaseBase|bool Returns false on errors |
||
679 | */ |
||
680 | public function openConnection( $i, $wiki = false ) { |
||
711 | |||
712 | /** |
||
713 | * Open a connection to a foreign DB, or return one if it is already open. |
||
714 | * |
||
715 | * Increments a reference count on the returned connection which locks the |
||
716 | * connection to the requested wiki. This reference count can be |
||
717 | * decremented by calling reuseConnection(). |
||
718 | * |
||
719 | * If a connection is open to the appropriate server already, but with the wrong |
||
720 | * database, it will be switched to the right database and returned, as long as |
||
721 | * it has been freed first with reuseConnection(). |
||
722 | * |
||
723 | * On error, returns false, and the connection which caused the |
||
724 | * error will be available via $this->mErrorConnection. |
||
725 | * |
||
726 | * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError. |
||
727 | * |
||
728 | * @param int $i Server index |
||
729 | * @param string $wiki Wiki ID to open |
||
730 | * @return DatabaseBase |
||
731 | */ |
||
732 | private function openForeignConnection( $i, $wiki ) { |
||
788 | |||
789 | /** |
||
790 | * Test if the specified index represents an open connection |
||
791 | * |
||
792 | * @param int $index Server index |
||
793 | * @access private |
||
794 | * @return bool |
||
795 | */ |
||
796 | private function isOpen( $index ) { |
||
803 | |||
804 | /** |
||
805 | * Really opens a connection. Uncached. |
||
806 | * Returns a Database object whether or not the connection was successful. |
||
807 | * @access private |
||
808 | * |
||
809 | * @param array $server |
||
810 | * @param bool $dbNameOverride |
||
811 | * @throws MWException |
||
812 | * @return DatabaseBase |
||
813 | */ |
||
814 | protected function reallyOpenConnection( $server, $dbNameOverride = false ) { |
||
856 | |||
857 | /** |
||
858 | * @throws DBConnectionError |
||
859 | * @return bool |
||
860 | */ |
||
861 | private function reportConnectionError() { |
||
890 | |||
891 | /** |
||
892 | * @return int |
||
893 | * @since 1.26 |
||
894 | */ |
||
895 | public function getWriterIndex() { |
||
898 | |||
899 | /** |
||
900 | * Returns true if the specified index is a valid server index |
||
901 | * |
||
902 | * @param string $i |
||
903 | * @return bool |
||
904 | */ |
||
905 | public function haveIndex( $i ) { |
||
908 | |||
909 | /** |
||
910 | * Returns true if the specified index is valid and has non-zero load |
||
911 | * |
||
912 | * @param string $i |
||
913 | * @return bool |
||
914 | */ |
||
915 | public function isNonZeroLoad( $i ) { |
||
918 | |||
919 | /** |
||
920 | * Get the number of defined servers (not the number of open connections) |
||
921 | * |
||
922 | * @return int |
||
923 | */ |
||
924 | public function getServerCount() { |
||
927 | |||
928 | /** |
||
929 | * Get the host name or IP address of the server with the specified index |
||
930 | * Prefer a readable name if available. |
||
931 | * @param string $i |
||
932 | * @return string |
||
933 | */ |
||
934 | public function getServerName( $i ) { |
||
945 | |||
946 | /** |
||
947 | * Return the server info structure for a given index, or false if the index is invalid. |
||
948 | * @param int $i |
||
949 | * @return array|bool |
||
950 | */ |
||
951 | public function getServerInfo( $i ) { |
||
958 | |||
959 | /** |
||
960 | * Sets the server info structure for the given index. Entry at index $i |
||
961 | * is created if it doesn't exist |
||
962 | * @param int $i |
||
963 | * @param array $serverInfo |
||
964 | */ |
||
965 | public function setServerInfo( $i, array $serverInfo ) { |
||
968 | |||
969 | /** |
||
970 | * Get the current master position for chronology control purposes |
||
971 | * @return mixed |
||
972 | */ |
||
973 | public function getMasterPos() { |
||
991 | |||
992 | /** |
||
993 | * Disable this load balancer. All connections are closed, and any attempt to |
||
994 | * open a new connection will result in a DBAccessError. |
||
995 | * |
||
996 | * @since 1.27 |
||
997 | */ |
||
998 | public function disable() { |
||
1002 | |||
1003 | /** |
||
1004 | * Close all open connections |
||
1005 | */ |
||
1006 | public function closeAll() { |
||
1018 | |||
1019 | /** |
||
1020 | * Close a connection |
||
1021 | * Using this function makes sure the LoadBalancer knows the connection is closed. |
||
1022 | * If you use $conn->close() directly, the load balancer won't update its state. |
||
1023 | * @param DatabaseBase $conn |
||
1024 | */ |
||
1025 | public function closeConnection( $conn ) { |
||
1044 | |||
1045 | /** |
||
1046 | * Commit transactions on all open connections |
||
1047 | * @param string $fname Caller name |
||
1048 | */ |
||
1049 | public function commitAll( $fname = __METHOD__ ) { |
||
1054 | |||
1055 | /** |
||
1056 | * Perform all pre-commit callbacks that remain part of the atomic transactions |
||
1057 | * and disable any post-commit callbacks until runMasterPostCommitCallbacks() |
||
1058 | * @since 1.28 |
||
1059 | */ |
||
1060 | public function runMasterPreCommitCallbacks() { |
||
1068 | |||
1069 | /** |
||
1070 | * Perform all pre-commit checks for things like replication safety |
||
1071 | * @param array $options Includes: |
||
1072 | * - maxWriteDuration : max write query duration time in seconds |
||
1073 | * @throws DBTransactionError |
||
1074 | * @since 1.28 |
||
1075 | */ |
||
1076 | public function approveMasterChanges( array $options ) { |
||
1090 | |||
1091 | /** |
||
1092 | * Issue COMMIT on all master connections where writes where done |
||
1093 | * @param string $fname Caller name |
||
1094 | */ |
||
1095 | public function commitMasterChanges( $fname = __METHOD__ ) { |
||
1102 | |||
1103 | /** |
||
1104 | * Issue all pending post-commit callbacks |
||
1105 | * @since 1.28 |
||
1106 | */ |
||
1107 | public function runMasterPostCommitCallbacks() { |
||
1113 | |||
1114 | /** |
||
1115 | * Issue ROLLBACK only on master, only if queries were done on connection |
||
1116 | * @param string $fname Caller name |
||
1117 | * @throws DBExpectedError |
||
1118 | * @since 1.23 |
||
1119 | */ |
||
1120 | public function rollbackMasterChanges( $fname = __METHOD__ ) { |
||
1146 | |||
1147 | /** |
||
1148 | * @return bool Whether a master connection is already open |
||
1149 | * @since 1.24 |
||
1150 | */ |
||
1151 | public function hasMasterConnection() { |
||
1154 | |||
1155 | /** |
||
1156 | * Determine if there are pending changes in a transaction by this thread |
||
1157 | * @since 1.23 |
||
1158 | * @return bool |
||
1159 | */ |
||
1160 | public function hasMasterChanges() { |
||
1175 | |||
1176 | /** |
||
1177 | * Get the timestamp of the latest write query done by this thread |
||
1178 | * @since 1.25 |
||
1179 | * @return float|bool UNIX timestamp or false |
||
1180 | */ |
||
1181 | View Code Duplication | public function lastMasterChangeTimestamp() { |
|
1195 | |||
1196 | /** |
||
1197 | * Check if this load balancer object had any recent or still |
||
1198 | * pending writes issued against it by this PHP thread |
||
1199 | * |
||
1200 | * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout] |
||
1201 | * @return bool |
||
1202 | * @since 1.25 |
||
1203 | */ |
||
1204 | public function hasOrMadeRecentMasterChanges( $age = null ) { |
||
1210 | |||
1211 | /** |
||
1212 | * Get the list of callers that have pending master changes |
||
1213 | * |
||
1214 | * @return array |
||
1215 | * @since 1.27 |
||
1216 | */ |
||
1217 | View Code Duplication | public function pendingMasterChangeCallers() { |
|
1233 | |||
1234 | /** |
||
1235 | * @param mixed $value |
||
1236 | * @return mixed |
||
1237 | */ |
||
1238 | public function waitTimeout( $value = null ) { |
||
1241 | |||
1242 | /** |
||
1243 | * @note This method will trigger a DB connection if not yet done |
||
1244 | * |
||
1245 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
1246 | * @return bool Whether the generic connection for reads is highly "lagged" |
||
1247 | */ |
||
1248 | public function getLaggedSlaveMode( $wiki = false ) { |
||
1264 | |||
1265 | /** |
||
1266 | * @note This method will never cause a new DB connection |
||
1267 | * @return bool Whether any generic connection used for reads was highly "lagged" |
||
1268 | * @since 1.27 |
||
1269 | */ |
||
1270 | public function laggedSlaveUsed() { |
||
1273 | |||
1274 | /** |
||
1275 | * @note This method may trigger a DB connection if not yet done |
||
1276 | * @param string|bool $wiki Wiki ID, or false for the current wiki |
||
1277 | * @return string|bool Reason the master is read-only or false if it is not |
||
1278 | * @since 1.27 |
||
1279 | */ |
||
1280 | public function getReadOnlyReason( $wiki = false ) { |
||
1295 | |||
1296 | /** |
||
1297 | * Disables/enables lag checks |
||
1298 | * @param null|bool $mode |
||
1299 | * @return bool |
||
1300 | */ |
||
1301 | public function allowLagged( $mode = null ) { |
||
1309 | |||
1310 | /** |
||
1311 | * @return bool |
||
1312 | */ |
||
1313 | public function pingAll() { |
||
1323 | |||
1324 | /** |
||
1325 | * Call a function with each open connection object |
||
1326 | * @param callable $callback |
||
1327 | * @param array $params |
||
1328 | */ |
||
1329 | public function forEachOpenConnection( $callback, array $params = [] ) { |
||
1339 | |||
1340 | /** |
||
1341 | * Call a function with each open connection object to a master |
||
1342 | * @param callable $callback |
||
1343 | * @param array $params |
||
1344 | * @since 1.28 |
||
1345 | */ |
||
1346 | public function forEachOpenMasterConnection( $callback, array $params = [] ) { |
||
1358 | |||
1359 | /** |
||
1360 | * Get the hostname and lag time of the most-lagged slave |
||
1361 | * |
||
1362 | * This is useful for maintenance scripts that need to throttle their updates. |
||
1363 | * May attempt to open connections to slaves on the default DB. If there is |
||
1364 | * no lag, the maximum lag will be reported as -1. |
||
1365 | * |
||
1366 | * @param bool|string $wiki Wiki ID, or false for the default database |
||
1367 | * @return array ( host, max lag, index of max lagged host ) |
||
1368 | */ |
||
1369 | public function getMaxLag( $wiki = false ) { |
||
1389 | |||
1390 | /** |
||
1391 | * Get an estimate of replication lag (in seconds) for each server |
||
1392 | * |
||
1393 | * Results are cached for a short time in memcached/process cache |
||
1394 | * |
||
1395 | * Values may be "false" if replication is too broken to estimate |
||
1396 | * |
||
1397 | * @param string|bool $wiki |
||
1398 | * @return int[] Map of (server index => float|int|bool) |
||
1399 | */ |
||
1400 | public function getLagTimes( $wiki = false ) { |
||
1408 | |||
1409 | /** |
||
1410 | * Get the lag in seconds for a given connection, or zero if this load |
||
1411 | * balancer does not have replication enabled. |
||
1412 | * |
||
1413 | * This should be used in preference to Database::getLag() in cases where |
||
1414 | * replication may not be in use, since there is no way to determine if |
||
1415 | * replication is in use at the connection level without running |
||
1416 | * potentially restricted queries such as SHOW SLAVE STATUS. Using this |
||
1417 | * function instead of Database::getLag() avoids a fatal error in this |
||
1418 | * case on many installations. |
||
1419 | * |
||
1420 | * @param IDatabase $conn |
||
1421 | * @return int|bool Returns false on error |
||
1422 | */ |
||
1423 | public function safeGetLag( IDatabase $conn ) { |
||
1430 | |||
1431 | /** |
||
1432 | * Wait for a slave DB to reach a specified master position |
||
1433 | * |
||
1434 | * This will connect to the master to get an accurate position if $pos is not given |
||
1435 | * |
||
1436 | * @param IDatabase $conn Slave DB |
||
1437 | * @param DBMasterPos|bool $pos Master position; default: current position |
||
1438 | * @param integer $timeout Timeout in seconds |
||
1439 | * @return bool Success |
||
1440 | * @since 1.27 |
||
1441 | */ |
||
1442 | public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) { |
||
1465 | |||
1466 | /** |
||
1467 | * Clear the cache for slag lag delay times |
||
1468 | * |
||
1469 | * This is only used for testing |
||
1470 | */ |
||
1471 | public function clearLagTimeCache() { |
||
1474 | } |
||
1475 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: