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