Replace some MWExceptions with natives ones in /db
[lhc/web/wiklou.git] / includes / db / loadbalancer / LoadBalancer.php
index 9ceae20..687317c 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) */
@@ -40,11 +40,9 @@ 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 */
@@ -53,6 +51,14 @@ class LoadBalancer {
        private $wanCache;
        /** @var TransactionProfiler */
        protected $trxProfiler;
+       /** @var LoggerInterface */
+       protected $replLogger;
+       /** @var LoggerInterface */
+       protected $connLogger;
+       /** @var LoggerInterface */
+       protected $queryLogger;
+       /** @var LoggerInterface */
+       protected $perfLogger;
 
        /** @var bool|DatabaseBase Database connection that caused a problem */
        private $mErrorConnection;
@@ -74,6 +80,13 @@ class LoadBalancer {
        private $trxRoundId = false;
        /** @var array[] Map of (name => callable) */
        private $trxRecurringCallbacks = [];
+       /** @var string Local Wiki ID and default for selectDB() calls */
+       private $localDomain;
+       /** @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 +97,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' => [],
@@ -161,6 +159,16 @@ 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();
+               }
        }
 
        /**
@@ -172,20 +180,12 @@ class LoadBalancer {
                if ( !isset( $this->mLoadMonitor ) ) {
                        $class = $this->mLoadMonitorClass;
                        $this->mLoadMonitor = new $class( $this );
+                       $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
@@ -207,10 +207,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 +237,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();
-               }
-
                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 +252,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,10 +261,10 @@ 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)
+               # Scale the configured load ratios according to the dynamic load if supported
                $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
 
                $laggedReplicaMode = false;
@@ -311,7 +293,7 @@ class LoadBalancer {
                                }
                                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 +303,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 );
                        if ( !$conn ) {
-                               wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
+                               $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$wiki" );
                                unset( $nonErrorLoads[$i] );
                                unset( $currentLoads[$i] );
                                $i = false;
@@ -350,7 +332,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 +349,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'\n" );
                }
 
                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 +398,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 +412,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,7 +438,7 @@ class LoadBalancer {
                /** @var DBMasterPos $knownReachedPos */
                $knownReachedPos = $this->srvCache->get( $key );
                if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
-                       wfDebugLog( 'replication', __METHOD__ .
+                       $this->replLogger->debug( __METHOD__ .
                                ": replica DB $server known to be caught up (pos >= $knownReachedPos).\n" );
                        return true;
                }
@@ -484,13 +447,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\n" );
 
                                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\n" );
 
                                        return false;
                                }
@@ -500,18 +463,18 @@ 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...\n" );
                $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\n" );
+                       $this->perfLogger->warning( "$msg:\n" . wfBacktrace( true ) );
                        $ok = false;
                } else {
-                       wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
+                       $this->replLogger->info( __METHOD__ . ": Done\n" );
                        $ok = true;
                        // Remember that the DB reached this point
                        $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
@@ -524,24 +487,13 @@ 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 ) {
                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() ) {
+               if ( $wiki === $this->localDomain ) {
                        $wiki = false;
                }
 
@@ -590,8 +542,7 @@ 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 ) {
@@ -602,14 +553,6 @@ class LoadBalancer {
                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' );
@@ -635,7 +578,7 @@ class LoadBalancer {
                        $wiki = $dbName;
                }
                if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
-                       throw new MWException( __METHOD__ . ": connection not found, has " .
+                       throw new InvalidArgumentException( __METHOD__ . ": connection not found, has " .
                                "the connection been freed already?" );
                }
                $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
@@ -659,6 +602,7 @@ class LoadBalancer {
         * @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
         * @return DBConnRef
+        * @since 1.22
         */
        public function getConnectionRef( $db, $groups = [], $wiki = false ) {
                return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
@@ -675,25 +619,14 @@ class LoadBalancer {
         * @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
         * @return DBConnRef
+        * @since 1.22
         */
        public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
+               $wiki = ( $wiki !== false ) ? $wiki : $this->localDomain;
+
                return new DBConnRef( $this, [ $db, $groups, $wiki ] );
        }
 
-       /**
-        * 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 );
@@ -705,10 +638,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;
                        }
@@ -747,7 +680,8 @@ class LoadBalancer {
         * @return DatabaseBase
         */
        private function openForeignConnection( $i, $wiki ) {
-               list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
+               list( $dbName, $prefix ) = explode( '-', $wiki, 2 ) + [ '', '' ];
+
                if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
                        // Reuse an already-used connection
                        $conn = $this->mConns['foreignUsed'][$i][$wiki];
@@ -834,7 +768,7 @@ 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 +777,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->perfLogger->warning( __METHOD__ . ": " .
                                "{$this->connsOpened}+ connections made (master=$masterName)\n" .
                                wfBacktrace( true ) );
                }
 
-               # Create object
+               // Set loggers
+               $server['connLogger'] = $this->connLogger;
+               $server['queryLogger'] = $this->queryLogger;
+
+               // Create a live connection object
                try {
                        $db = DatabaseBase::factory( $server['type'], $server );
                } catch ( DBConnectionError $e ) {
@@ -914,49 +852,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 +880,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 +888,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,9 +922,6 @@ class LoadBalancer {
                $this->disabled = true;
        }
 
-       /**
-        * Close all open connections
-        */
        public function closeAll() {
                $this->forEachOpenConnection( function ( DatabaseBase $conn ) {
                        $conn->close();
@@ -1042,37 +935,25 @@ 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 = [];
 
@@ -1083,7 +964,7 @@ class LoadBalancer {
                                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' ) ) {
@@ -1181,9 +1062,9 @@ class LoadBalancer {
                        function ( DatabaseBase $conn ) use ( $fname, &$failures ) {
                                $conn->setTrxEndCallbackSuppression( true );
                                try {
-                                       $conn->clearSnapshot( $fname );
+                                       $conn->flushSnapshot( $fname );
                                } catch ( DBError $e ) {
-                                       MWExceptionHandler::logException( $e );
+                                       call_user_func( $this->errorLogger, $e );
                                        $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
                                }
                                $conn->setTrxEndCallbackSuppression( false );
@@ -1199,11 +1080,6 @@ 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 = [];
 
@@ -1215,10 +1091,10 @@ class LoadBalancer {
                                        if ( $conn->writesOrCallbacksPending() ) {
                                                $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
                                        } elseif ( $restore ) {
-                                               $conn->clearSnapshot( $fname );
+                                               $conn->flushSnapshot( $fname );
                                        }
                                } catch ( DBError $e ) {
-                                       MWExceptionHandler::logException( $e );
+                                       call_user_func( $this->errorLogger, $e );
                                        $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
                                }
                                if ( $restore ) {
@@ -1244,9 +1120,21 @@ class LoadBalancer {
        public function runMasterPostTrxCallbacks( $type ) {
                $e = null; // first exception
                $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $type, &$e ) {
-                       $conn->clearSnapshot( __METHOD__ ); // clear no-op transactions
-
                        $conn->setTrxEndCallbackSuppression( false );
+                       if ( $conn->writesOrCallbacksPending() ) {
+                               // 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." );
+                               return;
+                       } elseif ( $conn->trxLevel() ) {
+                               // This happens for single-DB setups where DB_REPLICA uses the master DB,
+                               // thus leaving an implicit read-only transaction open at this point. It
+                               // also happens if onTransactionIdle() callbacks leave implicit transactions
+                               // open on *other* DBs (which is slightly improper). Let these COMMIT on the
+                               // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
+                               return;
+                       }
                        try {
                                $conn->runOnTransactionIdleCallbacks( $type );
                        } catch ( Exception $ex ) {
@@ -1295,9 +1183,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.
@@ -1309,9 +1197,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 );
                }
@@ -1325,7 +1213,7 @@ class LoadBalancer {
         */
        public function flushReplicaSnapshots( $fname = __METHOD__ ) {
                $this->forEachOpenReplicaConnection( function ( DatabaseBase $conn ) {
-                       $conn->clearSnapshot( __METHOD__ );
+                       $conn->flushSnapshot( __METHOD__ );
                } );
        }
 
@@ -1343,19 +1231,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->trxLevel() && $conn->writesOrCallbacksPending() ) {
-                                       return true;
-                               }
-                       }
-               }
-               return false;
+               $pending = 0;
+               $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( &$pending ) {
+                       $pending |= $conn->writesOrCallbacksPending();
+               } );
+
+               return (bool)$pending;
        }
 
        /**
@@ -1365,16 +1246,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 ( DatabaseBase $conn ) use ( &$lastTime ) {
+                       $lastTime = max( $lastTime, $conn->lastDoneWrites() );
+               } );
+
                return $lastTime;
        }
 
@@ -1396,31 +1271,18 @@ 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 ( DatabaseBase $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 ) {
                // No-op if there is only one DB (also avoids recursion)
                if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
@@ -1468,11 +1330,11 @@ 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 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( $wiki = false, IDatabase $conn = null ) {
                if ( $this->readOnlyReason !== false ) {
                        return $this->readOnlyReason;
                } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
@@ -1492,10 +1354,10 @@ 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 IDatabase|null DB master connectionl used to avoid loops [optional]
         * @return bool
         */
-       private function masterRunningReadOnly( $wiki, DatabaseBase $conn = null ) {
+       private function masterRunningReadOnly( $wiki, IDatabase $conn = null ) {
                $cache = $this->wanCache;
                $masterServer = $this->getServerName( $this->getWriterIndex() );
 
@@ -1517,11 +1379,6 @@ class LoadBalancer {
                );
        }
 
-       /**
-        * Disables/enables lag checks
-        * @param null|bool $mode
-        * @return bool
-        */
        public function allowLagged( $mode = null ) {
                if ( $mode === null ) {
                        return $this->mAllowLagged;
@@ -1531,9 +1388,6 @@ class LoadBalancer {
                return $this->mAllowLagged;
        }
 
-       /**
-        * @return bool
-        */
        public function pingAll() {
                $success = true;
                $this->forEachOpenConnection( function ( DatabaseBase $conn ) use ( &$success ) {
@@ -1545,11 +1399,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 ) {
@@ -1600,16 +1449,6 @@ 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 ) {
                $maxLag = -1;
                $host = '';
@@ -1631,16 +1470,6 @@ 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 ) {
                if ( $this->getServerCount() <= 1 ) {
                        return [ 0 => 0 ]; // no replication = no lag
@@ -1650,20 +1479,6 @@ class LoadBalancer {
                return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
        }
 
-       /**
-        * 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;
@@ -1696,11 +1511,11 @@ 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\n" );
+                       $this->perfLogger->warning( "$msg:\n" . wfBacktrace( true ) );
                        $ok = false;
                } else {
-                       wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
+                       $this->replLogger->info( __METHOD__ . ": Done\n" );
                        $ok = true;
                }
 
@@ -1711,6 +1526,7 @@ 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();
@@ -1736,4 +1552,16 @@ class LoadBalancer {
                        }
                );
        }
+
+       /**
+        * Set a new table prefix for the existing local wiki ID for testing
+        *
+        * @param string $prefix
+        * @since 1.28
+        */
+       public function setDomainPrefix( $prefix ) {
+               list( $dbName, ) = explode( '-', $this->localDomain, 2 );
+
+               $this->localDomain = "{$dbName}-{$prefix}";
+       }
 }