Change DatabaseBase => IDatabase in /db where possible
[lhc/web/wiklou.git] / includes / db / loadbalancer / LoadBalancer.php
index 1f4b993..6f136df 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * Database load balancing.
+ * Database load balancing manager
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * @file
  * @ingroup Database
  */
+use Psr\Log\LoggerInterface;
 
 /**
- * Database load balancing object
+ * Database load balancing, tracking, and transaction management object
  *
- * @todo document
  * @ingroup Database
  */
-class LoadBalancer {
+class LoadBalancer implements ILoadBalancer {
        /** @var array[] Map of (server index => server config array) */
        private $mServers;
-       /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
+       /** @var array[] Map of (local/foreignUsed/foreignFree => server index => IDatabase array) */
        private $mConns;
        /** @var array Map of (server index => weight) */
        private $mLoads;
@@ -40,21 +40,29 @@ class LoadBalancer {
        private $mAllowLagged;
        /** @var integer Seconds to spend waiting on replica DB lag to resolve */
        private $mWaitTimeout;
-       /** @var array LBFactory information */
-       private $mParentInfo;
-
        /** @var string The LoadMonitor subclass name */
        private $mLoadMonitorClass;
+
        /** @var LoadMonitor */
        private $mLoadMonitor;
        /** @var BagOStuff */
        private $srvCache;
+       /** @var BagOStuff */
+       private $memCache;
        /** @var WANObjectCache */
        private $wanCache;
        /** @var TransactionProfiler */
        protected $trxProfiler;
-
-       /** @var bool|DatabaseBase Database connection that caused a problem */
+       /** @var LoggerInterface */
+       protected $replLogger;
+       /** @var LoggerInterface */
+       protected $connLogger;
+       /** @var LoggerInterface */
+       protected $queryLogger;
+       /** @var LoggerInterface */
+       protected $perfLogger;
+
+       /** @var bool|IDatabase Database connection that caused a problem */
        private $mErrorConnection;
        /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
        private $mReadIndex;
@@ -74,6 +82,16 @@ class LoadBalancer {
        private $trxRoundId = false;
        /** @var array[] Map of (name => callable) */
        private $trxRecurringCallbacks = [];
+       /** @var string Local Domain ID and default for selectDB() calls */
+       private $localDomain;
+       /** @var string Current server name */
+       private $host;
+
+       /** @var callable Exception logger */
+       private $errorLogger;
+
+       /** @var boolean */
+       private $disabled = false;
 
        /** @var integer Warn when this many connection are held */
        const CONN_HELD_WARN_THRESHOLD = 10;
@@ -84,32 +102,17 @@ class LoadBalancer {
        /** @var integer Seconds to cache master server read-only status */
        const TTL_CACHE_READONLY = 5;
 
-       /**
-        * @var boolean
-        */
-       private $disabled = false;
-
-       /**
-        * @param array $params Array with keys:
-        *  - servers : Required. Array of server info structures.
-        *  - loadMonitor : Name of a class used to fetch server lag and load.
-        *  - readOnlyReason : Reason the master DB is read-only if so [optional]
-        *  - waitTimeout : Maximum time to wait for replicas for consistency [optional]
-        *  - srvCache : BagOStuff object [optional]
-        *  - wanCache : WANObjectCache object [optional]
-        * @throws MWException
-        */
        public function __construct( array $params ) {
                if ( !isset( $params['servers'] ) ) {
-                       throw new MWException( __CLASS__ . ': missing servers parameter' );
+                       throw new InvalidArgumentException( __CLASS__ . ': missing servers parameter' );
                }
                $this->mServers = $params['servers'];
                $this->mWaitTimeout = isset( $params['waitTimeout'] )
                        ? $params['waitTimeout']
                        : self::POS_WAIT_TIMEOUT;
+               $this->localDomain = isset( $params['localDomain'] ) ? $params['localDomain'] : '';
 
                $this->mReadIndex = -1;
-               $this->mWriteIndex = -1;
                $this->mConns = [
                        'local' => [],
                        'foreignUsed' => [],
@@ -151,6 +154,11 @@ class LoadBalancer {
                } else {
                        $this->srvCache = new EmptyBagOStuff();
                }
+               if ( isset( $params['memCache'] ) ) {
+                       $this->memCache = $params['memCache'];
+               } else {
+                       $this->memCache = new EmptyBagOStuff();
+               }
                if ( isset( $params['wanCache'] ) ) {
                        $this->wanCache = $params['wanCache'];
                } else {
@@ -161,6 +169,20 @@ class LoadBalancer {
                } else {
                        $this->trxProfiler = new TransactionProfiler();
                }
+
+               $this->errorLogger = isset( $params['errorLogger'] )
+                       ? $params['errorLogger']
+                       : function ( Exception $e ) {
+                               trigger_error( E_WARNING, $e->getMessage() );
+                       };
+
+               foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
+                       $this->$key = isset( $params[$key] ) ? $params[$key] : new \Psr\Log\NullLogger();
+               }
+
+               $this->host = isset( $params['hostname'] )
+                       ? $params['hostname']
+                       : ( gethostname() ?: 'unknown' );
        }
 
        /**
@@ -171,29 +193,21 @@ class LoadBalancer {
        private function getLoadMonitor() {
                if ( !isset( $this->mLoadMonitor ) ) {
                        $class = $this->mLoadMonitorClass;
-                       $this->mLoadMonitor = new $class( $this );
+                       $this->mLoadMonitor = new $class( $this, $this->srvCache, $this->memCache );
+                       $this->mLoadMonitor->setLogger( $this->replLogger );
                }
 
                return $this->mLoadMonitor;
        }
 
-       /**
-        * Get or set arbitrary data used by the parent object, usually an LBFactory
-        * @param mixed $x
-        * @return mixed
-        */
-       public function parentInfo( $x = null ) {
-               return wfSetVar( $this->mParentInfo, $x );
-       }
-
        /**
         * @param array $loads
-        * @param bool|string $wiki Wiki to get non-lagged for
+        * @param bool|string $domain Domain to get non-lagged for
         * @param int $maxLag Restrict the maximum allowed lag to this many seconds
         * @return bool|int|string
         */
-       private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF ) {
-               $lags = $this->getLagTimes( $wiki );
+       private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
+               $lags = $this->getLagTimes( $domain );
 
                # Unset excessively lagged servers
                foreach ( $lags as $i => $lag ) {
@@ -207,10 +221,10 @@ class LoadBalancer {
 
                                $host = $this->getServerName( $i );
                                if ( $lag === false && !is_infinite( $maxServerLag ) ) {
-                                       wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
+                                       $this->replLogger->error( "Server $host (#$i) is not replicating?" );
                                        unset( $loads[$i] );
                                } elseif ( $lag > $maxServerLag ) {
-                                       wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
+                                       $this->replLogger->warning( "Server $host (#$i) has >= $lag seconds of lag" );
                                        unset( $loads[$i] );
                                }
                        }
@@ -237,28 +251,10 @@ class LoadBalancer {
                return ArrayUtils::pickRandom( $loads );
        }
 
-       /**
-        * Get the index of the reader connection, which may be a replica DB
-        * This takes into account load ratios and lag times. It should
-        * always return a consistent index during a given invocation
-        *
-        * Side effect: opens connections to databases
-        * @param string|bool $group Query group, or false for the generic reader
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
-        * @throws MWException
-        * @return bool|int|string
-        */
-       public function getReaderIndex( $group = false, $wiki = false ) {
-               global $wgDBtype;
-
-               # @todo FIXME: For now, only go through all this for mysql databases
-               if ( $wgDBtype != 'mysql' ) {
-                       return $this->getWriterIndex();
-               }
-
+       public function getReaderIndex( $group = false, $domain = false ) {
                if ( count( $this->mServers ) == 1 ) {
                        # Skip the load balancing if there's only one server
-                       return 0;
+                       return $this->getWriterIndex();
                } elseif ( $group === false && $this->mReadIndex >= 0 ) {
                        # Shortcut if generic reader exists already
                        return $this->mReadIndex;
@@ -270,7 +266,7 @@ class LoadBalancer {
                                $nonErrorLoads = $this->mGroupLoads[$group];
                        } else {
                                # No loads for this group, return false and the caller can use some other group
-                               wfDebugLog( 'connect', __METHOD__ . ": no loads for group $group\n" );
+                               $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
 
                                return false;
                        }
@@ -279,11 +275,11 @@ class LoadBalancer {
                }
 
                if ( !count( $nonErrorLoads ) ) {
-                       throw new MWException( "Empty server array given to LoadBalancer" );
+                       throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
                }
 
-               # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
-               $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
+               # Scale the configured load ratios according to the dynamic load if supported
+               $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $domain );
 
                $laggedReplicaMode = false;
 
@@ -303,15 +299,15 @@ class LoadBalancer {
                                        # avoid lagged servers so as to avoid just blocking in that method.
                                        $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
                                        # Aim for <= 1 second of waiting (being too picky can backfire)
-                                       $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
+                                       $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
                                }
                                if ( $i === false ) {
                                        # Any server with less lag than it's 'max lag' param is preferable
-                                       $i = $this->getRandomNonLagged( $currentLoads, $wiki );
+                                       $i = $this->getRandomNonLagged( $currentLoads, $domain );
                                }
                                if ( $i === false && count( $currentLoads ) != 0 ) {
                                        # All replica DBs lagged. Switch to read-only mode
-                                       wfDebugLog( 'replication', "All replica DBs lagged. Switch to read-only mode" );
+                                       $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
                                        $i = ArrayUtils::pickRandom( $currentLoads );
                                        $laggedReplicaMode = true;
                                }
@@ -321,17 +317,17 @@ class LoadBalancer {
                                # pickRandom() returned false
                                # This is permanent and means the configuration or the load monitor
                                # wants us to return false.
-                               wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
+                               $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
 
                                return false;
                        }
 
                        $serverName = $this->getServerName( $i );
-                       wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: $serverName..." );
+                       $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
 
-                       $conn = $this->openConnection( $i, $wiki );
+                       $conn = $this->openConnection( $i, $domain );
                        if ( !$conn ) {
-                               wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
+                               $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
                                unset( $nonErrorLoads[$i] );
                                unset( $currentLoads[$i] );
                                $i = false;
@@ -340,7 +336,7 @@ class LoadBalancer {
 
                        // Decrement reference counter, we are finished with this connection.
                        // It will be incremented for the caller later.
-                       if ( $wiki !== false ) {
+                       if ( $domain !== false ) {
                                $this->reuseConnection( $conn );
                        }
 
@@ -350,7 +346,7 @@ class LoadBalancer {
 
                # If all servers were down, quit now
                if ( !count( $nonErrorLoads ) ) {
-                       wfDebugLog( 'connect', "All servers down" );
+                       $this->connLogger->error( "All servers down" );
                }
 
                if ( $i !== false ) {
@@ -367,19 +363,13 @@ class LoadBalancer {
                                }
                        }
                        $serverName = $this->getServerName( $i );
-                       wfDebugLog( 'connect', __METHOD__ .
-                               ": using server $serverName for group '$group'\n" );
+                       $this->connLogger->debug(
+                               __METHOD__ . ": using server $serverName for group '$group'" );
                }
 
                return $i;
        }
 
-       /**
-        * Set the master wait position
-        * If a DB_REPLICA connection has been opened already, waits
-        * Otherwise sets a variable telling it to wait if such a connection is opened
-        * @param DBMasterPos $pos
-        */
        public function waitFor( $pos ) {
                $this->mWaitForPos = $pos;
                $i = $this->mReadIndex;
@@ -422,12 +412,6 @@ class LoadBalancer {
                return $ok;
        }
 
-       /**
-        * Set the master wait position and wait for ALL replica DBs to catch up to it
-        * @param DBMasterPos $pos
-        * @param int $timeout Max seconds to wait; default is mWaitTimeout
-        * @return bool Success (able to connect and no timeouts reached)
-        */
        public function waitForAll( $pos, $timeout = null ) {
                $this->mWaitForPos = $pos;
                $serverCount = count( $this->mServers );
@@ -442,17 +426,10 @@ class LoadBalancer {
                return $ok;
        }
 
-       /**
-        * Get any open connection to a given server index, local or foreign
-        * Returns false if there is no connection open
-        *
-        * @param int $i
-        * @return DatabaseBase|bool False on failure
-        */
        public function getAnyOpenConnection( $i ) {
-               foreach ( $this->mConns as $conns ) {
-                       if ( !empty( $conns[$i] ) ) {
-                               return reset( $conns[$i] );
+               foreach ( $this->mConns as $connsByServer ) {
+                       if ( !empty( $connsByServer[$i] ) ) {
+                               return reset( $connsByServer[$i] );
                        }
                }
 
@@ -475,8 +452,8 @@ class LoadBalancer {
                /** @var DBMasterPos $knownReachedPos */
                $knownReachedPos = $this->srvCache->get( $key );
                if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
-                       wfDebugLog( 'replication', __METHOD__ .
-                               ": replica DB $server known to be caught up (pos >= $knownReachedPos).\n" );
+                       $this->replLogger->debug( __METHOD__ .
+                               ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
                        return true;
                }
 
@@ -484,13 +461,13 @@ class LoadBalancer {
                $conn = $this->getAnyOpenConnection( $index );
                if ( !$conn ) {
                        if ( !$open ) {
-                               wfDebugLog( 'replication', __METHOD__ . ": no connection open for $server\n" );
+                               $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
 
                                return false;
                        } else {
                                $conn = $this->openConnection( $index, '' );
                                if ( !$conn ) {
-                                       wfDebugLog( 'replication', __METHOD__ . ": failed to connect to $server\n" );
+                                       $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
 
                                        return false;
                                }
@@ -500,18 +477,17 @@ class LoadBalancer {
                        }
                }
 
-               wfDebugLog( 'replication', __METHOD__ . ": Waiting for replica DB $server to catch up...\n" );
+               $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
                $timeout = $timeout ?: $this->mWaitTimeout;
                $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
 
                if ( $result == -1 || is_null( $result ) ) {
                        // Timed out waiting for replica DB, use master instead
                        $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
-                       wfDebugLog( 'replication', "$msg\n" );
-                       wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
+                       $this->replLogger->warning( "$msg" );
                        $ok = false;
                } else {
-                       wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
+                       $this->replLogger->info( __METHOD__ . ": Done" );
                        $ok = true;
                        // Remember that the DB reached this point
                        $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
@@ -524,25 +500,14 @@ class LoadBalancer {
                return $ok;
        }
 
-       /**
-        * Get a connection by index
-        * This is the main entry point for this class.
-        *
-        * @param int $i Server index
-        * @param array|string|bool $groups Query group(s), or false for the generic reader
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
-        *
-        * @throws MWException
-        * @return DatabaseBase
-        */
-       public function getConnection( $i, $groups = [], $wiki = false ) {
+       public function getConnection( $i, $groups = [], $domain = false ) {
                if ( $i === null || $i === false ) {
-                       throw new MWException( 'Attempt to call ' . __METHOD__ .
+                       throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
                                ' with invalid server index' );
                }
 
-               if ( $wiki === wfWikiID() ) {
-                       $wiki = false;
+               if ( $domain === $this->localDomain ) {
+                       $domain = false;
                }
 
                $groups = ( $groups === false || $groups === [] )
@@ -557,7 +522,7 @@ class LoadBalancer {
                } else {
                        # Try to find an available server in any the query groups (in order)
                        foreach ( $groups as $group ) {
-                               $groupIndex = $this->getReaderIndex( $group, $wiki );
+                               $groupIndex = $this->getReaderIndex( $group, $domain );
                                if ( $groupIndex !== false ) {
                                        $i = $groupIndex;
                                        break;
@@ -571,7 +536,7 @@ class LoadBalancer {
                        # Try the general server pool if $groups are unavailable.
                        $i = in_array( false, $groups, true )
                                ? false // don't bother with this if that is what was tried above
-                               : $this->getReaderIndex( false, $wiki );
+                               : $this->getReaderIndex( false, $domain );
                        # Couldn't find a working server in getReaderIndex()?
                        if ( $i === false ) {
                                $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
@@ -581,7 +546,7 @@ class LoadBalancer {
                }
 
                # Now we have an explicit index into the servers array
-               $conn = $this->openConnection( $i, $wiki );
+               $conn = $this->openConnection( $i, $domain );
                if ( !$conn ) {
                        return $this->reportConnectionError();
                }
@@ -590,26 +555,17 @@ class LoadBalancer {
                if ( $this->connsOpened > $oldConnsOpened ) {
                        $host = $conn->getServer();
                        $dbname = $conn->getDBname();
-                       $trxProf = Profiler::instance()->getTransactionProfiler();
-                       $trxProf->recordConnection( $host, $dbname, $masterOnly );
+                       $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
                }
 
                if ( $masterOnly ) {
                        # Make master-requested DB handles inherit any read-only mode setting
-                       $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
+                       $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
                }
 
                return $conn;
        }
 
-       /**
-        * Mark a foreign connection as being available for reuse under a different
-        * DB name or prefix. This mechanism is reference-counted, and must be called
-        * the same number of times as getConnection() to work.
-        *
-        * @param DatabaseBase $conn
-        * @throws MWException
-        */
        public function reuseConnection( $conn ) {
                $serverIndex = $conn->getLBInfo( 'serverIndex' );
                $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
@@ -630,73 +586,64 @@ class LoadBalancer {
                $dbName = $conn->getDBname();
                $prefix = $conn->tablePrefix();
                if ( strval( $prefix ) !== '' ) {
-                       $wiki = "$dbName-$prefix";
+                       $domain = "$dbName-$prefix";
                } else {
-                       $wiki = $dbName;
+                       $domain = $dbName;
                }
-               if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
-                       throw new MWException( __METHOD__ . ": connection not found, has " .
+               if ( $this->mConns['foreignUsed'][$serverIndex][$domain] !== $conn ) {
+                       throw new InvalidArgumentException( __METHOD__ . ": connection not found, has " .
                                "the connection been freed already?" );
                }
                $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
                if ( $refCount <= 0 ) {
-                       $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
-                       unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
-                       wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
+                       $this->mConns['foreignFree'][$serverIndex][$domain] = $conn;
+                       unset( $this->mConns['foreignUsed'][$serverIndex][$domain] );
+                       $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
                } else {
-                       wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
+                       $this->connLogger->debug( __METHOD__ .
+                               ": reference count for $serverIndex/$domain reduced to $refCount" );
                }
        }
 
        /**
         * Get a database connection handle reference
         *
-        * The handle's methods wrap simply wrap those of a DatabaseBase handle
+        * The handle's methods wrap simply wrap those of a IDatabase handle
         *
         * @see LoadBalancer::getConnection() for parameter information
         *
         * @param int $db
         * @param array|string|bool $groups Query group(s), or false for the generic reader
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
+        * @param string|bool $domain Domain ID, or false for the current domain
         * @return DBConnRef
+        * @since 1.22
         */
-       public function getConnectionRef( $db, $groups = [], $wiki = false ) {
-               return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
+       public function getConnectionRef( $db, $groups = [], $domain = false ) {
+               return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
        }
 
        /**
         * Get a database connection handle reference without connecting yet
         *
-        * The handle's methods wrap simply wrap those of a DatabaseBase handle
+        * The handle's methods wrap simply wrap those of a IDatabase handle
         *
         * @see LoadBalancer::getConnection() for parameter information
         *
         * @param int $db
         * @param array|string|bool $groups Query group(s), or false for the generic reader
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
+        * @param string|bool $domain Domain ID, or false for the current domain
         * @return DBConnRef
+        * @since 1.22
         */
-       public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
-               return new DBConnRef( $this, [ $db, $groups, $wiki ] );
+       public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
+               $domain = ( $domain !== false ) ? $domain : $this->localDomain;
+
+               return new DBConnRef( $this, [ $db, $groups, $domain ] );
        }
 
-       /**
-        * Open a connection to the server given by the specified index
-        * Index must be an actual index into the array.
-        * If the server is already open, returns it.
-        *
-        * On error, returns false, and the connection which caused the
-        * error will be available via $this->mErrorConnection.
-        *
-        * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
-        *
-        * @param int $i Server index
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
-        * @return DatabaseBase|bool Returns false on errors
-        */
-       public function openConnection( $i, $wiki = false ) {
-               if ( $wiki !== false ) {
-                       $conn = $this->openForeignConnection( $i, $wiki );
+       public function openConnection( $i, $domain = false ) {
+               if ( $domain !== false ) {
+                       $conn = $this->openForeignConnection( $i, $domain );
                } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
                        $conn = $this->mConns['local'][$i][0];
                } else {
@@ -705,10 +652,10 @@ class LoadBalancer {
                        $conn = $this->reallyOpenConnection( $server, false );
                        $serverName = $this->getServerName( $i );
                        if ( $conn->isOpen() ) {
-                               wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
+                               $this->connLogger->debug( "Connected to database $i at '$serverName'." );
                                $this->mConns['local'][$i][0] = $conn;
                        } else {
-                               wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
+                               $this->connLogger->warning( "Failed to connect to database $i at '$serverName'." );
                                $this->mErrorConnection = $conn;
                                $conn = false;
                        }
@@ -730,7 +677,7 @@ class LoadBalancer {
         * Open a connection to a foreign DB, or return one if it is already open.
         *
         * Increments a reference count on the returned connection which locks the
-        * connection to the requested wiki. This reference count can be
+        * connection to the requested domain. This reference count can be
         * decremented by calling reuseConnection().
         *
         * If a connection is open to the appropriate server already, but with the wrong
@@ -743,38 +690,40 @@ class LoadBalancer {
         * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
         *
         * @param int $i Server index
-        * @param string $wiki Wiki ID to open
-        * @return DatabaseBase
+        * @param string $domain Domain ID to open
+        * @return IDatabase
         */
-       private function openForeignConnection( $i, $wiki ) {
-               list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
-               if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
+       private function openForeignConnection( $i, $domain ) {
+               list( $dbName, $prefix ) = explode( '-', $domain, 2 ) + [ '', '' ];
+
+               if ( isset( $this->mConns['foreignUsed'][$i][$domain] ) ) {
                        // Reuse an already-used connection
-                       $conn = $this->mConns['foreignUsed'][$i][$wiki];
-                       wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
-               } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
-                       // Reuse a free connection for the same wiki
-                       $conn = $this->mConns['foreignFree'][$i][$wiki];
-                       unset( $this->mConns['foreignFree'][$i][$wiki] );
-                       $this->mConns['foreignUsed'][$i][$wiki] = $conn;
-                       wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
+                       $conn = $this->mConns['foreignUsed'][$i][$domain];
+                       $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
+               } elseif ( isset( $this->mConns['foreignFree'][$i][$domain] ) ) {
+                       // Reuse a free connection for the same domain
+                       $conn = $this->mConns['foreignFree'][$i][$domain];
+                       unset( $this->mConns['foreignFree'][$i][$domain] );
+                       $this->mConns['foreignUsed'][$i][$domain] = $conn;
+                       $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
                } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
-                       // Reuse a connection from another wiki
+                       // Reuse a connection from another domain
                        $conn = reset( $this->mConns['foreignFree'][$i] );
-                       $oldWiki = key( $this->mConns['foreignFree'][$i] );
+                       $oldDomain = key( $this->mConns['foreignFree'][$i] );
 
                        // The empty string as a DB name means "don't care".
                        // DatabaseMysqlBase::open() already handle this on connection.
                        if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
                                $this->mLastError = "Error selecting database $dbName on server " .
-                                       $conn->getServer() . " from client host " . wfHostname() . "\n";
+                                       $conn->getServer() . " from client host {$this->host}";
                                $this->mErrorConnection = $conn;
                                $conn = false;
                        } else {
                                $conn->tablePrefix( $prefix );
-                               unset( $this->mConns['foreignFree'][$i][$oldWiki] );
-                               $this->mConns['foreignUsed'][$i][$wiki] = $conn;
-                               wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
+                               unset( $this->mConns['foreignFree'][$i][$oldDomain] );
+                               $this->mConns['foreignUsed'][$i][$domain] = $conn;
+                               $this->connLogger->debug( __METHOD__ .
+                                       ": reusing free connection from $oldDomain for $domain" );
                        }
                } else {
                        // Open a new connection
@@ -784,13 +733,13 @@ class LoadBalancer {
                        $server['foreign'] = true;
                        $conn = $this->reallyOpenConnection( $server, $dbName );
                        if ( !$conn->isOpen() ) {
-                               wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
+                               $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
                                $this->mErrorConnection = $conn;
                                $conn = false;
                        } else {
                                $conn->tablePrefix( $prefix );
-                               $this->mConns['foreignUsed'][$i][$wiki] = $conn;
-                               wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
+                               $this->mConns['foreignUsed'][$i][$domain] = $conn;
+                               $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
                        }
                }
 
@@ -825,8 +774,9 @@ class LoadBalancer {
         *
         * @param array $server
         * @param bool $dbNameOverride
+        * @return IDatabase
+        * @throws DBAccessError
         * @throws MWException
-        * @return DatabaseBase
         */
        protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
                if ( $this->disabled ) {
@@ -834,7 +784,8 @@ class LoadBalancer {
                }
 
                if ( !is_array( $server ) ) {
-                       throw new MWException( 'You must update your load-balancing configuration. ' .
+                       throw new InvalidArgumentException(
+                               'You must update your load-balancing configuration. ' .
                                'See DefaultSettings.php entry for $wgDBservers.' );
                }
 
@@ -843,17 +794,21 @@ class LoadBalancer {
                }
 
                // Let the handle know what the cluster master is (e.g. "db1052")
-               $masterName = $this->getServerName( 0 );
+               $masterName = $this->getServerName( $this->getWriterIndex() );
                $server['clusterMasterHost'] = $masterName;
 
                // Log when many connection are made on requests
                if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
-                       wfDebugLog( 'DBPerformance', __METHOD__ . ": " .
-                               "{$this->connsOpened}+ connections made (master=$masterName)\n" .
-                               wfBacktrace( true ) );
+                       $this->perfLogger->warning( __METHOD__ . ": " .
+                               "{$this->connsOpened}+ connections made (master=$masterName)" );
                }
 
-               # Create object
+               // Set loggers
+               $server['connLogger'] = $this->connLogger;
+               $server['queryLogger'] = $this->queryLogger;
+               $server['trxProfiler'] = $this->trxProfiler;
+
+               // Create a live connection object
                try {
                        $db = DatabaseBase::factory( $server['type'], $server );
                } catch ( DBConnectionError $e ) {
@@ -866,7 +821,6 @@ class LoadBalancer {
                $db->setLazyMasterHandle(
                        $this->getLazyConnectionRef( DB_MASTER, [], $db->getWikiID() )
                );
-               $db->setTransactionProfiler( $this->trxProfiler );
 
                if ( $server['serverIndex'] === $this->getWriterIndex() ) {
                        if ( $this->trxRoundId !== false ) {
@@ -893,7 +847,7 @@ class LoadBalancer {
 
                if ( !is_object( $conn ) ) {
                        // No last connection, probably due to all servers being too busy
-                       wfLogDBError(
+                       $this->connLogger->error(
                                "LB failure with no last connection. Connection error: {last_error}",
                                $context
                        );
@@ -902,7 +856,7 @@ class LoadBalancer {
                        throw new DBConnectionError( null, $this->mLastError );
                } else {
                        $context['db_server'] = $conn->getProperty( 'mServer' );
-                       wfLogDBError(
+                       $this->connLogger->warning(
                                "Connection error: {last_error} ({db_server})",
                                $context
                        );
@@ -914,49 +868,22 @@ class LoadBalancer {
                return false; /* not reached */
        }
 
-       /**
-        * @return int
-        * @since 1.26
-        */
        public function getWriterIndex() {
                return 0;
        }
 
-       /**
-        * Returns true if the specified index is a valid server index
-        *
-        * @param string $i
-        * @return bool
-        */
        public function haveIndex( $i ) {
                return array_key_exists( $i, $this->mServers );
        }
 
-       /**
-        * Returns true if the specified index is valid and has non-zero load
-        *
-        * @param string $i
-        * @return bool
-        */
        public function isNonZeroLoad( $i ) {
                return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
        }
 
-       /**
-        * Get the number of defined servers (not the number of open connections)
-        *
-        * @return int
-        */
        public function getServerCount() {
                return count( $this->mServers );
        }
 
-       /**
-        * Get the host name or IP address of the server with the specified index
-        * Prefer a readable name if available.
-        * @param string $i
-        * @return string
-        */
        public function getServerName( $i ) {
                if ( isset( $this->mServers[$i]['hostName'] ) ) {
                        $name = $this->mServers[$i]['hostName'];
@@ -969,11 +896,6 @@ class LoadBalancer {
                return ( $name != '' ) ? $name : 'localhost';
        }
 
-       /**
-        * Return the server info structure for a given index, or false if the index is invalid.
-        * @param int $i
-        * @return array|bool
-        */
        public function getServerInfo( $i ) {
                if ( isset( $this->mServers[$i] ) ) {
                        return $this->mServers[$i];
@@ -982,24 +904,14 @@ class LoadBalancer {
                }
        }
 
-       /**
-        * Sets the server info structure for the given index. Entry at index $i
-        * is created if it doesn't exist
-        * @param int $i
-        * @param array $serverInfo
-        */
        public function setServerInfo( $i, array $serverInfo ) {
                $this->mServers[$i] = $serverInfo;
        }
 
-       /**
-        * Get the current master position for chronology control purposes
-        * @return mixed
-        */
        public function getMasterPos() {
                # If this entire request was served from a replica DB without opening a connection to the
                # master (however unlikely that may be), then we can fetch the position from the replica DB.
-               $masterConn = $this->getAnyOpenConnection( 0 );
+               $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
                if ( !$masterConn ) {
                        $serverCount = count( $this->mServers );
                        for ( $i = 1; $i < $serverCount; $i++ ) {
@@ -1026,11 +938,8 @@ class LoadBalancer {
                $this->disabled = true;
        }
 
-       /**
-        * Close all open connections
-        */
        public function closeAll() {
-               $this->forEachOpenConnection( function ( DatabaseBase $conn ) {
+               $this->forEachOpenConnection( function ( IDatabase $conn ) {
                        $conn->close();
                } );
 
@@ -1042,48 +951,36 @@ class LoadBalancer {
                $this->connsOpened = 0;
        }
 
-       /**
-        * Close a connection
-        * Using this function makes sure the LoadBalancer knows the connection is closed.
-        * If you use $conn->close() directly, the load balancer won't update its state.
-        * @param DatabaseBase $conn
-        */
-       public function closeConnection( $conn ) {
-               $done = false;
-               foreach ( $this->mConns as $i1 => $conns2 ) {
-                       foreach ( $conns2 as $i2 => $conns3 ) {
-                               foreach ( $conns3 as $i3 => $candidateConn ) {
-                                       if ( $conn === $candidateConn ) {
-                                               $conn->close();
-                                               unset( $this->mConns[$i1][$i2][$i3] );
-                                               --$this->connsOpened;
-                                               $done = true;
-                                               break;
-                                       }
+       public function closeConnection( IDatabase $conn ) {
+               $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
+               foreach ( $this->mConns as $type => $connsByServer ) {
+                       if ( !isset( $connsByServer[$serverIndex] ) ) {
+                               continue;
+                       }
+
+                       foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
+                               if ( $conn === $trackedConn ) {
+                                       unset( $this->mConns[$type][$serverIndex][$i] );
+                                       --$this->connsOpened;
+                                       break 2;
                                }
                        }
                }
-               if ( !$done ) {
-                       $conn->close();
-               }
+
+               $conn->close();
        }
 
-       /**
-        * Commit transactions on all open connections
-        * @param string $fname Caller name
-        * @throws DBExpectedError
-        */
        public function commitAll( $fname = __METHOD__ ) {
                $failures = [];
 
                $restore = ( $this->trxRoundId !== false );
                $this->trxRoundId = false;
                $this->forEachOpenConnection(
-                       function ( DatabaseBase $conn ) use ( $fname, $restore, &$failures ) {
+                       function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
                                try {
                                        $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
                                } catch ( DBError $e ) {
-                                       MWExceptionHandler::logException( $e );
+                                       call_user_func( $this->errorLogger, $e );
                                        $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
                                }
                                if ( $restore && $conn->getLBInfo( 'master' ) ) {
@@ -1124,7 +1021,7 @@ class LoadBalancer {
         */
        public function approveMasterChanges( array $options ) {
                $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
-               $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $limit ) {
+               $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
                        // If atomic sections or explicit transactions are still open, some caller must have
                        // caught an exception but failed to properly rollback any changes. Detect that and
                        // throw and error (causing rollback).
@@ -1138,9 +1035,10 @@ class LoadBalancer {
                        // If this fails, then all DB transactions will be rollback back together.
                        $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
                        if ( $limit > 0 && $time > $limit ) {
-                               throw new DBTransactionError(
+                               throw new DBTransactionSizeError(
                                        $conn,
-                                       wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
+                                       "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
+                                       [ $time, $limit ]
                                );
                        }
                        // If a connection sits idle while slow queries execute on another, that connection
@@ -1183,7 +1081,7 @@ class LoadBalancer {
                                try {
                                        $conn->flushSnapshot( $fname );
                                } catch ( DBError $e ) {
-                                       MWExceptionHandler::logException( $e );
+                                       call_user_func( $this->errorLogger, $e );
                                        $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
                                }
                                $conn->setTrxEndCallbackSuppression( false );
@@ -1199,18 +1097,13 @@ class LoadBalancer {
                }
        }
 
-       /**
-        * Issue COMMIT on all master connections where writes where done
-        * @param string $fname Caller name
-        * @throws DBExpectedError
-        */
        public function commitMasterChanges( $fname = __METHOD__ ) {
                $failures = [];
 
                $restore = ( $this->trxRoundId !== false );
                $this->trxRoundId = false;
                $this->forEachOpenMasterConnection(
-                       function ( DatabaseBase $conn ) use ( $fname, $restore, &$failures ) {
+                       function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
                                try {
                                        if ( $conn->writesOrCallbacksPending() ) {
                                                $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
@@ -1218,7 +1111,7 @@ class LoadBalancer {
                                                $conn->flushSnapshot( $fname );
                                        }
                                } catch ( DBError $e ) {
-                                       MWExceptionHandler::logException( $e );
+                                       call_user_func( $this->errorLogger, $e );
                                        $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
                                }
                                if ( $restore ) {
@@ -1249,7 +1142,7 @@ class LoadBalancer {
                                // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
                                // (which finished its callbacks already). Warn and recover in this case. Let the
                                // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
-                               wfWarn( __METHOD__ . ": did not expect writes/callbacks pending." );
+                               $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
                                return;
                        } elseif ( $conn->trxLevel() ) {
                                // This happens for single-DB setups where DB_REPLICA uses the master DB,
@@ -1284,7 +1177,7 @@ class LoadBalancer {
                $restore = ( $this->trxRoundId !== false );
                $this->trxRoundId = false;
                $this->forEachOpenMasterConnection(
-                       function ( DatabaseBase $conn ) use ( $fname, $restore ) {
+                       function ( IDatabase $conn ) use ( $fname, $restore ) {
                                if ( $conn->writesOrCallbacksPending() ) {
                                        $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
                                }
@@ -1307,9 +1200,9 @@ class LoadBalancer {
        }
 
        /**
-        * @param DatabaseBase $conn
+        * @param IDatabase $conn
         */
-       private function applyTransactionRoundFlags( DatabaseBase $conn ) {
+       private function applyTransactionRoundFlags( IDatabase $conn ) {
                if ( $conn->getFlag( DBO_DEFAULT ) ) {
                        // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
                        // Force DBO_TRX even in CLI mode since a commit round is expected soon.
@@ -1321,9 +1214,9 @@ class LoadBalancer {
        }
 
        /**
-        * @param DatabaseBase $conn
+        * @param IDatabase $conn
         */
-       private function undoTransactionRoundFlags( DatabaseBase $conn ) {
+       private function undoTransactionRoundFlags( IDatabase $conn ) {
                if ( $conn->getFlag( DBO_DEFAULT ) ) {
                        $conn->restoreFlags( $conn::RESTORE_PRIOR );
                }
@@ -1336,7 +1229,7 @@ class LoadBalancer {
         * @since 1.28
         */
        public function flushReplicaSnapshots( $fname = __METHOD__ ) {
-               $this->forEachOpenReplicaConnection( function ( DatabaseBase $conn ) {
+               $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
                        $conn->flushSnapshot( __METHOD__ );
                } );
        }
@@ -1355,19 +1248,12 @@ class LoadBalancer {
         * @return bool
         */
        public function hasMasterChanges() {
-               $masterIndex = $this->getWriterIndex();
-               foreach ( $this->mConns as $conns2 ) {
-                       if ( empty( $conns2[$masterIndex] ) ) {
-                               continue;
-                       }
-                       /** @var DatabaseBase $conn */
-                       foreach ( $conns2[$masterIndex] as $conn ) {
-                               if ( $conn->writesOrCallbacksPending() ) {
-                                       return true;
-                               }
-                       }
-               }
-               return false;
+               $pending = 0;
+               $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
+                       $pending |= $conn->writesOrCallbacksPending();
+               } );
+
+               return (bool)$pending;
        }
 
        /**
@@ -1377,16 +1263,10 @@ class LoadBalancer {
         */
        public function lastMasterChangeTimestamp() {
                $lastTime = false;
-               $masterIndex = $this->getWriterIndex();
-               foreach ( $this->mConns as $conns2 ) {
-                       if ( empty( $conns2[$masterIndex] ) ) {
-                               continue;
-                       }
-                       /** @var DatabaseBase $conn */
-                       foreach ( $conns2[$masterIndex] as $conn ) {
-                               $lastTime = max( $lastTime, $conn->lastDoneWrites() );
-                       }
-               }
+               $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
+                       $lastTime = max( $lastTime, $conn->lastDoneWrites() );
+               } );
+
                return $lastTime;
        }
 
@@ -1408,37 +1288,24 @@ class LoadBalancer {
        /**
         * Get the list of callers that have pending master changes
         *
-        * @return array
+        * @return string[] List of method names
         * @since 1.27
         */
        public function pendingMasterChangeCallers() {
                $fnames = [];
-
-               $masterIndex = $this->getWriterIndex();
-               foreach ( $this->mConns as $conns2 ) {
-                       if ( empty( $conns2[$masterIndex] ) ) {
-                               continue;
-                       }
-                       /** @var DatabaseBase $conn */
-                       foreach ( $conns2[$masterIndex] as $conn ) {
-                               $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
-                       }
-               }
+               $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
+                       $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
+               } );
 
                return $fnames;
        }
 
-       /**
-        * @note This method will trigger a DB connection if not yet done
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
-        * @return bool Whether the generic connection for reads is highly "lagged"
-        */
-       public function getLaggedReplicaMode( $wiki = false ) {
+       public function getLaggedReplicaMode( $domain = false ) {
                // No-op if there is only one DB (also avoids recursion)
                if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
                        try {
                                // See if laggedReplicaMode gets set
-                               $conn = $this->getConnection( DB_REPLICA, false, $wiki );
+                               $conn = $this->getConnection( DB_REPLICA, false, $domain );
                                $this->reuseConnection( $conn );
                        } catch ( DBConnectionError $e ) {
                                // Avoid expensive re-connect attempts and failures
@@ -1451,12 +1318,12 @@ class LoadBalancer {
        }
 
        /**
-        * @param bool $wiki
+        * @param bool $domain
         * @return bool
         * @deprecated 1.28; use getLaggedReplicaMode()
         */
-       public function getLaggedSlaveMode( $wiki = false ) {
-               return $this->getLaggedReplicaMode( $wiki );
+       public function getLaggedSlaveMode( $domain = false ) {
+               return $this->getLaggedReplicaMode( $domain );
        }
 
        /**
@@ -1479,15 +1346,15 @@ class LoadBalancer {
 
        /**
         * @note This method may trigger a DB connection if not yet done
-        * @param string|bool $wiki Wiki ID, or false for the current wiki
-        * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
+        * @param string|bool $domain Domain ID, or false for the current domain
+        * @param IDatabase|null DB master connection; used to avoid loops [optional]
         * @return string|bool Reason the master is read-only or false if it is not
         * @since 1.27
         */
-       public function getReadOnlyReason( $wiki = false, DatabaseBase $conn = null ) {
+       public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
                if ( $this->readOnlyReason !== false ) {
                        return $this->readOnlyReason;
-               } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
+               } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
                        if ( $this->allReplicasDownMode ) {
                                return 'The database has been automatically locked ' .
                                        'until the replica database servers become available';
@@ -1495,7 +1362,7 @@ class LoadBalancer {
                                return 'The database has been automatically locked ' .
                                        'while the replica database servers catch up to the master.';
                        }
-               } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
+               } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
                        return 'The database master is running in read-only mode.';
                }
 
@@ -1503,21 +1370,21 @@ class LoadBalancer {
        }
 
        /**
-        * @param string $wiki Wiki ID, or false for the current wiki
-        * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
+        * @param string $domain Domain ID, or false for the current domain
+        * @param IDatabase|null DB master connectionl used to avoid loops [optional]
         * @return bool
         */
-       private function masterRunningReadOnly( $wiki, DatabaseBase $conn = null ) {
+       private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
                $cache = $this->wanCache;
                $masterServer = $this->getServerName( $this->getWriterIndex() );
 
                return (bool)$cache->getWithSetCallback(
                        $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
                        self::TTL_CACHE_READONLY,
-                       function () use ( $wiki, $conn ) {
+                       function () use ( $domain, $conn ) {
                                $this->trxProfiler->setSilenced( true );
                                try {
-                                       $dbw = $conn ?: $this->getConnection( DB_MASTER, [], $wiki );
+                                       $dbw = $conn ?: $this->getConnection( DB_MASTER, [], $domain );
                                        $readOnly = (int)$dbw->serverIsReadOnly();
                                } catch ( DBError $e ) {
                                        $readOnly = 0;
@@ -1529,11 +1396,6 @@ class LoadBalancer {
                );
        }
 
-       /**
-        * Disables/enables lag checks
-        * @param null|bool $mode
-        * @return bool
-        */
        public function allowLagged( $mode = null ) {
                if ( $mode === null ) {
                        return $this->mAllowLagged;
@@ -1543,12 +1405,9 @@ class LoadBalancer {
                return $this->mAllowLagged;
        }
 
-       /**
-        * @return bool
-        */
        public function pingAll() {
                $success = true;
-               $this->forEachOpenConnection( function ( DatabaseBase $conn ) use ( &$success ) {
+               $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
                        if ( !$conn->ping() ) {
                                $success = false;
                        }
@@ -1557,11 +1416,6 @@ class LoadBalancer {
                return $success;
        }
 
-       /**
-        * Call a function with each open connection object
-        * @param callable $callback
-        * @param array $params
-        */
        public function forEachOpenConnection( $callback, array $params = [] ) {
                foreach ( $this->mConns as $connsByServer ) {
                        foreach ( $connsByServer as $serverConns ) {
@@ -1583,7 +1437,7 @@ class LoadBalancer {
                $masterIndex = $this->getWriterIndex();
                foreach ( $this->mConns as $connsByServer ) {
                        if ( isset( $connsByServer[$masterIndex] ) ) {
-                               /** @var DatabaseBase $conn */
+                               /** @var IDatabase $conn */
                                foreach ( $connsByServer[$masterIndex] as $conn ) {
                                        $mergedParams = array_merge( [ $conn ], $params );
                                        call_user_func_array( $callback, $mergedParams );
@@ -1612,17 +1466,7 @@ class LoadBalancer {
                }
        }
 
-       /**
-        * Get the hostname and lag time of the most-lagged replica DB
-        *
-        * This is useful for maintenance scripts that need to throttle their updates.
-        * May attempt to open connections to replica DBs on the default DB. If there is
-        * no lag, the maximum lag will be reported as -1.
-        *
-        * @param bool|string $wiki Wiki ID, or false for the default database
-        * @return array ( host, max lag, index of max lagged host )
-        */
-       public function getMaxLag( $wiki = false ) {
+       public function getMaxLag( $domain = false ) {
                $maxLag = -1;
                $host = '';
                $maxIndex = 0;
@@ -1631,7 +1475,7 @@ class LoadBalancer {
                        return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
                }
 
-               $lagTimes = $this->getLagTimes( $wiki );
+               $lagTimes = $this->getLagTimes( $domain );
                foreach ( $lagTimes as $i => $lag ) {
                        if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
                                $maxLag = $lag;
@@ -1643,39 +1487,15 @@ class LoadBalancer {
                return [ $host, $maxLag, $maxIndex ];
        }
 
-       /**
-        * Get an estimate of replication lag (in seconds) for each server
-        *
-        * Results are cached for a short time in memcached/process cache
-        *
-        * Values may be "false" if replication is too broken to estimate
-        *
-        * @param string|bool $wiki
-        * @return int[] Map of (server index => float|int|bool)
-        */
-       public function getLagTimes( $wiki = false ) {
+       public function getLagTimes( $domain = false ) {
                if ( $this->getServerCount() <= 1 ) {
                        return [ 0 => 0 ]; // no replication = no lag
                }
 
                # Send the request to the load monitor
-               return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
+               return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $domain );
        }
 
-       /**
-        * Get the lag in seconds for a given connection, or zero if this load
-        * balancer does not have replication enabled.
-        *
-        * This should be used in preference to Database::getLag() in cases where
-        * replication may not be in use, since there is no way to determine if
-        * replication is in use at the connection level without running
-        * potentially restricted queries such as SHOW SLAVE STATUS. Using this
-        * function instead of Database::getLag() avoids a fatal error in this
-        * case on many installations.
-        *
-        * @param IDatabase $conn
-        * @return int|bool Returns false on error
-        */
        public function safeGetLag( IDatabase $conn ) {
                if ( $this->getServerCount() == 1 ) {
                        return 0;
@@ -1708,11 +1528,10 @@ class LoadBalancer {
                $result = $conn->masterPosWait( $pos, $timeout );
                if ( $result == -1 || is_null( $result ) ) {
                        $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
-                       wfDebugLog( 'replication', "$msg\n" );
-                       wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
+                       $this->replLogger->warning( "$msg" );
                        $ok = false;
                } else {
-                       wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
+                       $this->replLogger->info( __METHOD__ . ": Done" );
                        $ok = true;
                }
 
@@ -1723,13 +1542,14 @@ class LoadBalancer {
         * Clear the cache for slag lag delay times
         *
         * This is only used for testing
+        * @since 1.26
         */
        public function clearLagTimeCache() {
                $this->getLoadMonitor()->clearCaches();
        }
 
        /**
-        * Set a callback via DatabaseBase::setTransactionListener() on
+        * Set a callback via IDatabase::setTransactionListener() on
         * all current and future master connections of this load balancer
         *
         * @param string $name Callback name
@@ -1743,9 +1563,21 @@ class LoadBalancer {
                        unset( $this->trxRecurringCallbacks[$name] );
                }
                $this->forEachOpenMasterConnection(
-                       function ( DatabaseBase $conn ) use ( $name, $callback ) {
+                       function ( IDatabase $conn ) use ( $name, $callback ) {
                                $conn->setTransactionListener( $name, $callback );
                        }
                );
        }
+
+       /**
+        * Set a new table prefix for the existing local domain ID for testing
+        *
+        * @param string $prefix
+        * @since 1.28
+        */
+       public function setDomainPrefix( $prefix ) {
+               list( $dbName, ) = explode( '-', $this->localDomain, 2 );
+
+               $this->localDomain = "{$dbName}-{$prefix}";
+       }
 }