Merge "Add rc.unpatrolled to the recentchanges API"
[lhc/web/wiklou.git] / includes / utils / UIDGenerator.php
1 <?php
2 /**
3 * This file deals with UID generation.
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 * @author Aaron Schulz
22 */
23
24 /**
25 * Class for getting statistically unique IDs
26 *
27 * @since 1.21
28 */
29 class UIDGenerator {
30 /** @var UIDGenerator */
31 protected static $instance = null;
32
33 protected $nodeId32; // string; node ID in binary (32 bits)
34 protected $nodeId48; // string; node ID in binary (48 bits)
35
36 protected $lockFile88; // string; local file path
37 protected $lockFile128; // string; local file path
38
39 /** @var Array */
40 protected $fileHandles = array(); // cache file handles
41
42 const QUICK_RAND = 1; // get randomness from fast and insecure sources
43
44 protected function __construct() {
45 $idFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid';
46 $nodeId = is_file( $idFile ) ? file_get_contents( $idFile ) : '';
47 // Try to get some ID that uniquely identifies this machine (RFC 4122)...
48 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
49 wfSuppressWarnings();
50 if ( wfIsWindows() ) {
51 // http://technet.microsoft.com/en-us/library/bb490913.aspx
52 $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
53 $line = substr( $csv, 0, strcspn( $csv, "\n" ) );
54 $info = str_getcsv( $line );
55 $nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : '';
56 } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
57 // See http://linux.die.net/man/8/ifconfig
58 $m = array();
59 preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
60 wfShellExec( '/sbin/ifconfig -a' ), $m );
61 $nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : '';
62 }
63 wfRestoreWarnings();
64 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
65 $nodeId = MWCryptRand::generateHex( 12, true );
66 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit
67 }
68 file_put_contents( $idFile, $nodeId ); // cache
69 }
70 $this->nodeId32 = wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
71 $this->nodeId48 = wfBaseConvert( $nodeId, 16, 2, 48 );
72 // If different processes run as different users, they may have different temp dirs.
73 // This is dealt with by initializing the clock sequence number and counters randomly.
74 $this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88';
75 $this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128';
76 }
77
78 /**
79 * @return UIDGenerator
80 */
81 protected static function singleton() {
82 if ( self::$instance === null ) {
83 self::$instance = new self();
84 }
85
86 return self::$instance;
87 }
88
89 /**
90 * Get a statistically unique 88-bit unsigned integer ID string.
91 * The bits of the UID are prefixed with the time (down to the millisecond).
92 *
93 * These IDs are suitable as values for the shard key of distributed data.
94 * If a column uses these as values, it should be declared UNIQUE to handle collisions.
95 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
96 * They can also be stored "DECIMAL(27) UNSIGNED" or BINARY(11) in MySQL.
97 *
98 * UID generation is serialized on each server (as the node ID is for the whole machine).
99 *
100 * @param $base integer Specifies a base other than 10
101 * @return string Number
102 * @throws MWException
103 */
104 public static function newTimestampedUID88( $base = 10 ) {
105 if ( !is_integer( $base ) || $base > 36 || $base < 2 ) {
106 throw new MWException( "Base must an integer be between 2 and 36" );
107 }
108 $gen = self::singleton();
109 $time = $gen->getTimestampAndDelay( 'lockFile88', 1, 1024 );
110
111 return wfBaseConvert( $gen->getTimestampedID88( $time ), 2, $base );
112 }
113
114 /**
115 * @param array $time (UIDGenerator::millitime(), clock sequence)
116 * @return string 88 bits
117 */
118 protected function getTimestampedID88( array $info ) {
119 list( $time, $counter ) = $info;
120 // Take the 46 MSBs of "milliseconds since epoch"
121 $id_bin = $this->millisecondsSinceEpochBinary( $time );
122 // Add a 10 bit counter resulting in 56 bits total
123 $id_bin .= str_pad( decbin( $counter ), 10, '0', STR_PAD_LEFT );
124 // Add the 32 bit node ID resulting in 88 bits total
125 $id_bin .= $this->nodeId32;
126 // Convert to a 1-27 digit integer string
127 if ( strlen( $id_bin ) !== 88 ) {
128 throw new MWException( "Detected overflow for millisecond timestamp." );
129 }
130
131 return $id_bin;
132 }
133
134 /**
135 * Get a statistically unique 128-bit unsigned integer ID string.
136 * The bits of the UID are prefixed with the time (down to the millisecond).
137 *
138 * These IDs are suitable as globally unique IDs, without any enforced uniqueness.
139 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
140 * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL.
141 *
142 * UID generation is serialized on each server (as the node ID is for the whole machine).
143 *
144 * @param $base integer Specifies a base other than 10
145 * @return string Number
146 * @throws MWException
147 */
148 public static function newTimestampedUID128( $base = 10 ) {
149 if ( !is_integer( $base ) || $base > 36 || $base < 2 ) {
150 throw new MWException( "Base must be an integer between 2 and 36" );
151 }
152 $gen = self::singleton();
153 $time = $gen->getTimestampAndDelay( 'lockFile128', 16384, 1048576 );
154
155 return wfBaseConvert( $gen->getTimestampedID128( $time ), 2, $base );
156 }
157
158 /**
159 * @param array $info (UIDGenerator::millitime(), counter, clock sequence)
160 * @return string 128 bits
161 */
162 protected function getTimestampedID128( array $info ) {
163 list( $time, $counter, $clkSeq ) = $info;
164 // Take the 46 MSBs of "milliseconds since epoch"
165 $id_bin = $this->millisecondsSinceEpochBinary( $time );
166 // Add a 20 bit counter resulting in 66 bits total
167 $id_bin .= str_pad( decbin( $counter ), 20, '0', STR_PAD_LEFT );
168 // Add a 14 bit clock sequence number resulting in 80 bits total
169 $id_bin .= str_pad( decbin( $clkSeq ), 14, '0', STR_PAD_LEFT );
170 // Add the 48 bit node ID resulting in 128 bits total
171 $id_bin .= $this->nodeId48;
172 // Convert to a 1-39 digit integer string
173 if ( strlen( $id_bin ) !== 128 ) {
174 throw new MWException( "Detected overflow for millisecond timestamp." );
175 }
176
177 return $id_bin;
178 }
179
180 /**
181 * Return an RFC4122 compliant v4 UUID
182 *
183 * @param $flags integer Bitfield (supports UIDGenerator::QUICK_RAND)
184 * @return string
185 * @throws MWException
186 */
187 public static function newUUIDv4( $flags = 0 ) {
188 $hex = ( $flags & self::QUICK_RAND )
189 ? wfRandomString( 31 )
190 : MWCryptRand::generateHex( 31 );
191
192 return sprintf( '%s-%s-%s-%s-%s',
193 // "time_low" (32 bits)
194 substr( $hex, 0, 8 ),
195 // "time_mid" (16 bits)
196 substr( $hex, 8, 4 ),
197 // "time_hi_and_version" (16 bits)
198 '4' . substr( $hex, 12, 3 ),
199 // "clk_seq_hi_res (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
200 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
201 // "node" (48 bits)
202 substr( $hex, 19, 12 )
203 );
204 }
205
206 /**
207 * Return an RFC4122 compliant v4 UUID
208 *
209 * @param $flags integer Bitfield (supports UIDGenerator::QUICK_RAND)
210 * @return string 32 hex characters with no hyphens
211 * @throws MWException
212 */
213 public static function newRawUUIDv4( $flags = 0 ) {
214 return str_replace( '-', '', self::newUUIDv4( $flags ) );
215 }
216
217 /**
218 * Get a (time,counter,clock sequence) where (time,counter) is higher
219 * than any previous (time,counter) value for the given clock sequence.
220 * This is useful for making UIDs sequential on a per-node bases.
221 *
222 * @param string $lockFile Name of a local lock file
223 * @param $clockSeqSize integer The number of possible clock sequence values
224 * @param $counterSize integer The number of possible counter values
225 * @return Array (result of UIDGenerator::millitime(), counter, clock sequence)
226 * @throws MWException
227 */
228 protected function getTimestampAndDelay( $lockFile, $clockSeqSize, $counterSize ) {
229 // Get the UID lock file handle
230 if ( isset( $this->fileHandles[$lockFile] ) ) {
231 $handle = $this->fileHandles[$lockFile];
232 } else {
233 $handle = fopen( $this->$lockFile, 'cb+' );
234 $this->fileHandles[$lockFile] = $handle ?: null; // cache
235 }
236 // Acquire the UID lock file
237 if ( $handle === false ) {
238 throw new MWException( "Could not open '{$this->$lockFile}'." );
239 } elseif ( !flock( $handle, LOCK_EX ) ) {
240 throw new MWException( "Could not acquire '{$this->$lockFile}'." );
241 }
242 // Get the current timestamp, clock sequence number, last time, and counter
243 rewind( $handle );
244 $data = explode( ' ', fgets( $handle ) ); // "<clk seq> <sec> <msec> <counter> <offset>"
245 $clockChanged = false; // clock set back significantly?
246 if ( count( $data ) == 5 ) { // last UID info already initialized
247 $clkSeq = (int)$data[0] % $clockSeqSize;
248 $prevTime = array( (int)$data[1], (int)$data[2] );
249 $offset = (int)$data[4] % $counterSize; // random counter offset
250 $counter = 0; // counter for UIDs with the same timestamp
251 // Delay until the clock reaches the time of the last ID.
252 // This detects any microtime() drift among processes.
253 $time = $this->timeWaitUntil( $prevTime );
254 if ( !$time ) { // too long to delay?
255 $clockChanged = true; // bump clock sequence number
256 $time = self::millitime();
257 } elseif ( $time == $prevTime ) {
258 // Bump the counter if there are timestamp collisions
259 $counter = (int)$data[3] % $counterSize;
260 if ( ++$counter >= $counterSize ) { // sanity (starts at 0)
261 flock( $handle, LOCK_UN ); // abort
262 throw new MWException( "Counter overflow for timestamp value." );
263 }
264 }
265 } else { // last UID info not initialized
266 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
267 $counter = 0;
268 $offset = mt_rand( 0, $counterSize - 1 );
269 $time = self::millitime();
270 }
271 // microtime() and gettimeofday() can drift from time() at least on Windows.
272 // The drift is immediate for processes running while the system clock changes.
273 // time() does not have this problem. See https://bugs.php.net/bug.php?id=42659.
274 if ( abs( time() - $time[0] ) >= 2 ) {
275 // We don't want processes using too high or low timestamps to avoid duplicate
276 // UIDs and clock sequence number churn. This process should just be restarted.
277 flock( $handle, LOCK_UN ); // abort
278 throw new MWException( "Process clock is outdated or drifted." );
279 }
280 // If microtime() is synced and a clock change was detected, then the clock went back
281 if ( $clockChanged ) {
282 // Bump the clock sequence number and also randomize the counter offset,
283 // which is useful for UIDs that do not include the clock sequence number.
284 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
285 $offset = mt_rand( 0, $counterSize - 1 );
286 trigger_error( "Clock was set back; sequence number incremented." );
287 }
288 // Update the (clock sequence number, timestamp, counter)
289 ftruncate( $handle, 0 );
290 rewind( $handle );
291 fwrite( $handle, "{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
292 fflush( $handle );
293 // Release the UID lock file
294 flock( $handle, LOCK_UN );
295
296 return array( $time, ( $counter + $offset ) % $counterSize, $clkSeq );
297 }
298
299 /**
300 * Wait till the current timestamp reaches $time and return the current
301 * timestamp. This returns false if it would have to wait more than 10ms.
302 *
303 * @param array $time Result of UIDGenerator::millitime()
304 * @return Array|bool UIDGenerator::millitime() result or false
305 */
306 protected function timeWaitUntil( array $time ) {
307 do {
308 $ct = self::millitime();
309 if ( $ct >= $time ) { // http://php.net/manual/en/language.operators.comparison.php
310 return $ct; // current timestamp is higher than $time
311 }
312 } while ( ( ( $time[0] - $ct[0] ) * 1000 + ( $time[1] - $ct[1] ) ) <= 10 );
313
314 return false;
315 }
316
317 /**
318 * @param array $time Result of UIDGenerator::millitime()
319 * @return string 46 MSBs of "milliseconds since epoch" in binary (rolls over in 4201)
320 */
321 protected function millisecondsSinceEpochBinary( array $time ) {
322 list( $sec, $msec ) = $time;
323 $ts = 1000 * $sec + $msec;
324 if ( $ts > pow( 2, 52 ) ) {
325 throw new MWException( __METHOD__ .
326 ': sorry, this function doesn\'t work after the year 144680' );
327 }
328
329 return substr( wfBaseConvert( $ts, 10, 2, 46 ), -46 );
330 }
331
332 /**
333 * @return Array (current time in seconds, milliseconds since then)
334 */
335 protected static function millitime() {
336 list( $msec, $sec ) = explode( ' ', microtime() );
337
338 return array( (int)$sec, (int)( $msec * 1000 ) );
339 }
340
341 function __destruct() {
342 array_map( 'fclose', $this->fileHandles );
343 }
344 }