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