Merge "Move Database and subclasses to Rdbms namespace"
[lhc/web/wiklou.git] / includes / libs / lockmanager / DBLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using DB table locks.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup LockManager
22 */
23
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\IDatabase;
26
27 /**
28 * Version of LockManager based on using named/row DB locks.
29 *
30 * This is meant for multi-wiki systems that may share files.
31 *
32 * All lock requests for a resource, identified by a hash string, will map to one bucket.
33 * Each bucket maps to one or several peer DBs, each on their own server.
34 * A majority of peer DBs must agree for a lock to be acquired.
35 *
36 * Caching is used to avoid hitting servers that are down.
37 *
38 * @ingroup LockManager
39 * @since 1.19
40 */
41 abstract class DBLockManager extends QuorumLockManager {
42 /** @var array[]|IDatabase[] Map of (DB names => server config or IDatabase) */
43 protected $dbServers; // (DB name => server config array)
44 /** @var BagOStuff */
45 protected $statusCache;
46
47 protected $lockExpiry; // integer number of seconds
48 protected $safeDelay; // integer number of seconds
49 /** @var IDatabase[] Map Database connections (DB name => Database) */
50 protected $conns = [];
51
52 /**
53 * Construct a new instance from configuration.
54 *
55 * @param array $config Parameters include:
56 * - dbServers : Associative array of DB names to server configuration.
57 * Configuration is an associative array that includes:
58 * - host : DB server name
59 * - dbname : DB name
60 * - type : DB type (mysql,postgres,...)
61 * - user : DB user
62 * - password : DB user password
63 * - tablePrefix : DB table prefix
64 * - flags : DB flags; bitfield of IDatabase::DBO_* constants
65 * - dbsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
66 * each having an odd-numbered list of DB names (peers) as values.
67 * - lockExpiry : Lock timeout (seconds) for dropped connections. [optional]
68 * This tells the DB server how long to wait before assuming
69 * connection failure and releasing all the locks for a session.
70 * - srvCache : A BagOStuff instance using APC or the like.
71 */
72 public function __construct( array $config ) {
73 parent::__construct( $config );
74
75 $this->dbServers = $config['dbServers'];
76 // Sanitize srvsByBucket config to prevent PHP errors
77 $this->srvsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
78 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
79
80 if ( isset( $config['lockExpiry'] ) ) {
81 $this->lockExpiry = $config['lockExpiry'];
82 } else {
83 $met = ini_get( 'max_execution_time' );
84 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
85 }
86 $this->safeDelay = ( $this->lockExpiry <= 0 )
87 ? 60 // pick a safe-ish number to match DB timeout default
88 : $this->lockExpiry; // cover worst case
89
90 // Tracks peers that couldn't be queried recently to avoid lengthy
91 // connection timeouts. This is useless if each bucket has one peer.
92 $this->statusCache = isset( $config['srvCache'] )
93 ? $config['srvCache']
94 : new HashBagOStuff();
95 }
96
97 /**
98 * @TODO change this code to work in one batch
99 * @param string $lockSrv
100 * @param array $pathsByType
101 * @return StatusValue
102 */
103 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
104 $status = StatusValue::newGood();
105 foreach ( $pathsByType as $type => $paths ) {
106 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
107 }
108
109 return $status;
110 }
111
112 abstract protected function doGetLocksOnServer( $lockSrv, array $paths, $type );
113
114 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
115 return StatusValue::newGood();
116 }
117
118 /**
119 * @see QuorumLockManager::isServerUp()
120 * @param string $lockSrv
121 * @return bool
122 */
123 protected function isServerUp( $lockSrv ) {
124 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
125 return false; // recent failure to connect
126 }
127 try {
128 $this->getConnection( $lockSrv );
129 } catch ( DBError $e ) {
130 $this->cacheRecordFailure( $lockSrv );
131
132 return false; // failed to connect
133 }
134
135 return true;
136 }
137
138 /**
139 * Get (or reuse) a connection to a lock DB
140 *
141 * @param string $lockDb
142 * @return IDatabase
143 * @throws DBError
144 * @throws UnexpectedValueException
145 */
146 protected function getConnection( $lockDb ) {
147 if ( !isset( $this->conns[$lockDb] ) ) {
148 if ( $this->dbServers[$lockDb] instanceof IDatabase ) {
149 // Direct injected connection hande for $lockDB
150 $db = $this->dbServers[$lockDb];
151 } elseif ( is_array( $this->dbServers[$lockDb] ) ) {
152 // Parameters to construct a new database connection
153 $config = $this->dbServers[$lockDb];
154 $db = Database::factory( $config['type'], $config );
155 } else {
156 throw new UnexpectedValueException( "No server called '$lockDb'." );
157 }
158
159 $db->clearFlag( DBO_TRX );
160 # If the connection drops, try to avoid letting the DB rollback
161 # and release the locks before the file operations are finished.
162 # This won't handle the case of DB server restarts however.
163 $options = [];
164 if ( $this->lockExpiry > 0 ) {
165 $options['connTimeout'] = $this->lockExpiry;
166 }
167 $db->setSessionOptions( $options );
168 $this->initConnection( $lockDb, $db );
169
170 $this->conns[$lockDb] = $db;
171 }
172
173 return $this->conns[$lockDb];
174 }
175
176 /**
177 * Do additional initialization for new lock DB connection
178 *
179 * @param string $lockDb
180 * @param IDatabase $db
181 * @throws DBError
182 */
183 protected function initConnection( $lockDb, IDatabase $db ) {
184 }
185
186 /**
187 * Checks if the DB has not recently had connection/query errors.
188 * This just avoids wasting time on doomed connection attempts.
189 *
190 * @param string $lockDb
191 * @return bool
192 */
193 protected function cacheCheckFailures( $lockDb ) {
194 return ( $this->safeDelay > 0 )
195 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
196 : true;
197 }
198
199 /**
200 * Log a lock request failure to the cache
201 *
202 * @param string $lockDb
203 * @return bool Success
204 */
205 protected function cacheRecordFailure( $lockDb ) {
206 return ( $this->safeDelay > 0 )
207 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
208 : true;
209 }
210
211 /**
212 * Get a cache key for recent query misses for a DB
213 *
214 * @param string $lockDb
215 * @return string
216 */
217 protected function getMissKey( $lockDb ) {
218 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
219 }
220
221 /**
222 * Make sure remaining locks get cleared for sanity
223 */
224 function __destruct() {
225 $this->releaseAllLocks();
226 foreach ( $this->conns as $db ) {
227 $db->close();
228 }
229 }
230 }