Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / utils / UIDGenerator.php
blob92415877f73b135970d78595e51f78f024e28fd8
1 <?php
2 /**
3 * This file deals with UID generation.
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.
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.
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
20 * @file
21 * @author Aaron Schulz
24 /**
25 * Class for getting statistically unique IDs
27 * @since 1.21
29 class UIDGenerator {
30 /** @var UIDGenerator */
31 protected static $instance = null;
33 protected $nodeIdFile; // string; local file path
34 protected $nodeId32; // string; node ID in binary (32 bits)
35 protected $nodeId48; // string; node ID in binary (48 bits)
37 protected $lockFile88; // string; local file path
38 protected $lockFile128; // string; local file path
40 /** @var array */
41 protected $fileHandles = array(); // cache file handles
43 const QUICK_RAND = 1; // get randomness from fast and insecure sources
44 const QUICK_VOLATILE = 2; // use an APC like in-memory counter if available
46 protected function __construct() {
47 $this->nodeIdFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid';
48 $nodeId = '';
49 if ( is_file( $this->nodeIdFile ) ) {
50 $nodeId = file_get_contents( $this->nodeIdFile );
52 // Try to get some ID that uniquely identifies this machine (RFC 4122)...
53 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
54 wfSuppressWarnings();
55 if ( wfIsWindows() ) {
56 // http://technet.microsoft.com/en-us/library/bb490913.aspx
57 $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
58 $line = substr( $csv, 0, strcspn( $csv, "\n" ) );
59 $info = str_getcsv( $line );
60 $nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : '';
61 } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
62 // See http://linux.die.net/man/8/ifconfig
63 $m = array();
64 preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
65 wfShellExec( '/sbin/ifconfig -a' ), $m );
66 $nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : '';
68 wfRestoreWarnings();
69 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
70 $nodeId = MWCryptRand::generateHex( 12, true );
71 $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit
73 file_put_contents( $this->nodeIdFile, $nodeId ); // cache
75 $this->nodeId32 = wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
76 $this->nodeId48 = wfBaseConvert( $nodeId, 16, 2, 48 );
77 // If different processes run as different users, they may have different temp dirs.
78 // This is dealt with by initializing the clock sequence number and counters randomly.
79 $this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88';
80 $this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128';
83 /**
84 * @return UIDGenerator
86 protected static function singleton() {
87 if ( self::$instance === null ) {
88 self::$instance = new self();
91 return self::$instance;
94 /**
95 * Get a statistically unique 88-bit unsigned integer ID string.
96 * The bits of the UID are prefixed with the time (down to the millisecond).
98 * These IDs are suitable as values for the shard key of distributed data.
99 * If a column uses these as values, it should be declared UNIQUE to handle collisions.
100 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
101 * They can also be stored "DECIMAL(27) UNSIGNED" or BINARY(11) in MySQL.
103 * UID generation is serialized on each server (as the node ID is for the whole machine).
105 * @param int $base Specifies a base other than 10
106 * @return string Number
107 * @throws MWException
109 public static function newTimestampedUID88( $base = 10 ) {
110 if ( !is_integer( $base ) || $base > 36 || $base < 2 ) {
111 throw new MWException( "Base must an integer be between 2 and 36" );
113 $gen = self::singleton();
114 $time = $gen->getTimestampAndDelay( 'lockFile88', 1, 1024 );
116 return wfBaseConvert( $gen->getTimestampedID88( $time ), 2, $base );
120 * @param array $info (UIDGenerator::millitime(), counter, clock sequence)
121 * @return string 88 bits
122 * @throws MWException
124 protected function getTimestampedID88( array $info ) {
125 list( $time, $counter ) = $info;
126 // Take the 46 MSBs of "milliseconds since epoch"
127 $id_bin = $this->millisecondsSinceEpochBinary( $time );
128 // Add a 10 bit counter resulting in 56 bits total
129 $id_bin .= str_pad( decbin( $counter ), 10, '0', STR_PAD_LEFT );
130 // Add the 32 bit node ID resulting in 88 bits total
131 $id_bin .= $this->nodeId32;
132 // Convert to a 1-27 digit integer string
133 if ( strlen( $id_bin ) !== 88 ) {
134 throw new MWException( "Detected overflow for millisecond timestamp." );
137 return $id_bin;
141 * Get a statistically unique 128-bit unsigned integer ID string.
142 * The bits of the UID are prefixed with the time (down to the millisecond).
144 * These IDs are suitable as globally unique IDs, without any enforced uniqueness.
145 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
146 * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL.
148 * UID generation is serialized on each server (as the node ID is for the whole machine).
150 * @param int $base Specifies a base other than 10
151 * @return string Number
152 * @throws MWException
154 public static function newTimestampedUID128( $base = 10 ) {
155 if ( !is_integer( $base ) || $base > 36 || $base < 2 ) {
156 throw new MWException( "Base must be an integer between 2 and 36" );
158 $gen = self::singleton();
159 $time = $gen->getTimestampAndDelay( 'lockFile128', 16384, 1048576 );
161 return wfBaseConvert( $gen->getTimestampedID128( $time ), 2, $base );
165 * @param array $info (UIDGenerator::millitime(), counter, clock sequence)
166 * @return string 128 bits
167 * @throws MWException
169 protected function getTimestampedID128( array $info ) {
170 list( $time, $counter, $clkSeq ) = $info;
171 // Take the 46 MSBs of "milliseconds since epoch"
172 $id_bin = $this->millisecondsSinceEpochBinary( $time );
173 // Add a 20 bit counter resulting in 66 bits total
174 $id_bin .= str_pad( decbin( $counter ), 20, '0', STR_PAD_LEFT );
175 // Add a 14 bit clock sequence number resulting in 80 bits total
176 $id_bin .= str_pad( decbin( $clkSeq ), 14, '0', STR_PAD_LEFT );
177 // Add the 48 bit node ID resulting in 128 bits total
178 $id_bin .= $this->nodeId48;
179 // Convert to a 1-39 digit integer string
180 if ( strlen( $id_bin ) !== 128 ) {
181 throw new MWException( "Detected overflow for millisecond timestamp." );
184 return $id_bin;
188 * Return an RFC4122 compliant v4 UUID
190 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
191 * @return string
192 * @throws MWException
194 public static function newUUIDv4( $flags = 0 ) {
195 $hex = ( $flags & self::QUICK_RAND )
196 ? wfRandomString( 31 )
197 : MWCryptRand::generateHex( 31 );
199 return sprintf( '%s-%s-%s-%s-%s',
200 // "time_low" (32 bits)
201 substr( $hex, 0, 8 ),
202 // "time_mid" (16 bits)
203 substr( $hex, 8, 4 ),
204 // "time_hi_and_version" (16 bits)
205 '4' . substr( $hex, 12, 3 ),
206 // "clk_seq_hi_res (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
207 dechex( 0x8 | ( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
208 // "node" (48 bits)
209 substr( $hex, 19, 12 )
214 * Return an RFC4122 compliant v4 UUID
216 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
217 * @return string 32 hex characters with no hyphens
218 * @throws MWException
220 public static function newRawUUIDv4( $flags = 0 ) {
221 return str_replace( '-', '', self::newUUIDv4( $flags ) );
225 * Return an ID that is sequential *only* for this node and bucket
227 * These IDs are suitable for per-host sequence numbers, e.g. for some packet protocols.
228 * If UIDGenerator::QUICK_VOLATILE is used the counter might reset on server restart.
230 * @param string $bucket Arbitrary bucket name (should be ASCII)
231 * @param int $bits Bit size (<=48) of resulting numbers before wrap-around
232 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
233 * @return float Integer value as float
234 * @since 1.23
236 public static function newSequentialPerNodeID( $bucket, $bits = 48, $flags = 0 ) {
237 return current( self::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
241 * Return IDs that are sequential *only* for this node and bucket
243 * @see UIDGenerator::newSequentialPerNodeID()
244 * @param string $bucket Arbitrary bucket name (should be ASCII)
245 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
246 * @param int $count Number of IDs to return (1 to 10000)
247 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
248 * @return array Ordered list of float integer values
249 * @since 1.23
251 public static function newSequentialPerNodeIDs( $bucket, $bits, $count, $flags = 0 ) {
252 $gen = self::singleton();
253 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
257 * Return IDs that are sequential *only* for this node and bucket
259 * @see UIDGenerator::newSequentialPerNodeID()
260 * @param string $bucket Arbitrary bucket name (should be ASCII)
261 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
262 * @param int $count Number of IDs to return (1 to 10000)
263 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
264 * @return array Ordered list of float integer values
265 * @throws MWException
267 protected function getSequentialPerNodeIDs( $bucket, $bits, $count, $flags ) {
268 if ( $count <= 0 ) {
269 return array(); // nothing to do
270 } elseif ( $count > 10000 ) {
271 throw new MWException( "Number of requested IDs ($count) is too high." );
272 } elseif ( $bits < 16 || $bits > 48 ) {
273 throw new MWException( "Requested bit size ($bits) is out of range." );
276 $counter = null; // post-increment persistent counter value
278 // Use APC/eAccelerator/xcache if requested, available, and not in CLI mode;
279 // Counter values would not survive accross script instances in CLI mode.
280 $cache = null;
281 if ( ( $flags & self::QUICK_VOLATILE ) && PHP_SAPI !== 'cli' ) {
282 try {
283 $cache = ObjectCache::newAccelerator( array() );
284 } catch ( Exception $e ) {
285 // not supported
288 if ( $cache ) {
289 $counter = $cache->incr( $bucket, $count );
290 if ( $counter === false ) {
291 if ( !$cache->add( $bucket, (int)$count ) ) {
292 throw new MWException( 'Unable to set value to ' . get_class( $cache ) );
294 $counter = $count;
298 // Note: use of fmod() avoids "division by zero" on 32 bit machines
299 if ( $counter === null ) {
300 $path = wfTempDir() . '/mw-' . __CLASS__ . '-' . rawurlencode( $bucket ) . '-48';
301 // Get the UID lock file handle
302 if ( isset( $this->fileHandles[$path] ) ) {
303 $handle = $this->fileHandles[$path];
304 } else {
305 $handle = fopen( $path, 'cb+' );
306 $this->fileHandles[$path] = $handle ?: null; // cache
308 // Acquire the UID lock file
309 if ( $handle === false ) {
310 throw new MWException( "Could not open '{$path}'." );
311 } elseif ( !flock( $handle, LOCK_EX ) ) {
312 fclose( $handle );
313 throw new MWException( "Could not acquire '{$path}'." );
315 // Fetch the counter value and increment it...
316 rewind( $handle );
317 $counter = floor( trim( fgets( $handle ) ) ) + $count; // fetch as float
318 // Write back the new counter value
319 ftruncate( $handle, 0 );
320 rewind( $handle );
321 fwrite( $handle, fmod( $counter, pow( 2, 48 ) ) ); // warp-around as needed
322 fflush( $handle );
323 // Release the UID lock file
324 flock( $handle, LOCK_UN );
327 $ids = array();
328 $divisor = pow( 2, $bits );
329 $currentId = floor( $counter - $count ); // pre-increment counter value
330 for ( $i = 0; $i < $count; ++$i ) {
331 $ids[] = fmod( ++$currentId, $divisor );
334 return $ids;
338 * Get a (time,counter,clock sequence) where (time,counter) is higher
339 * than any previous (time,counter) value for the given clock sequence.
340 * This is useful for making UIDs sequential on a per-node bases.
342 * @param string $lockFile Name of a local lock file
343 * @param int $clockSeqSize The number of possible clock sequence values
344 * @param int $counterSize The number of possible counter values
345 * @return array (result of UIDGenerator::millitime(), counter, clock sequence)
346 * @throws MWException
348 protected function getTimestampAndDelay( $lockFile, $clockSeqSize, $counterSize ) {
349 // Get the UID lock file handle
350 $path = $this->$lockFile;
351 if ( isset( $this->fileHandles[$path] ) ) {
352 $handle = $this->fileHandles[$path];
353 } else {
354 $handle = fopen( $path, 'cb+' );
355 $this->fileHandles[$path] = $handle ?: null; // cache
357 // Acquire the UID lock file
358 if ( $handle === false ) {
359 throw new MWException( "Could not open '{$this->$lockFile}'." );
360 } elseif ( !flock( $handle, LOCK_EX ) ) {
361 fclose( $handle );
362 throw new MWException( "Could not acquire '{$this->$lockFile}'." );
364 // Get the current timestamp, clock sequence number, last time, and counter
365 rewind( $handle );
366 $data = explode( ' ', fgets( $handle ) ); // "<clk seq> <sec> <msec> <counter> <offset>"
367 $clockChanged = false; // clock set back significantly?
368 if ( count( $data ) == 5 ) { // last UID info already initialized
369 $clkSeq = (int)$data[0] % $clockSeqSize;
370 $prevTime = array( (int)$data[1], (int)$data[2] );
371 $offset = (int)$data[4] % $counterSize; // random counter offset
372 $counter = 0; // counter for UIDs with the same timestamp
373 // Delay until the clock reaches the time of the last ID.
374 // This detects any microtime() drift among processes.
375 $time = $this->timeWaitUntil( $prevTime );
376 if ( !$time ) { // too long to delay?
377 $clockChanged = true; // bump clock sequence number
378 $time = self::millitime();
379 } elseif ( $time == $prevTime ) {
380 // Bump the counter if there are timestamp collisions
381 $counter = (int)$data[3] % $counterSize;
382 if ( ++$counter >= $counterSize ) { // sanity (starts at 0)
383 flock( $handle, LOCK_UN ); // abort
384 throw new MWException( "Counter overflow for timestamp value." );
387 } else { // last UID info not initialized
388 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
389 $counter = 0;
390 $offset = mt_rand( 0, $counterSize - 1 );
391 $time = self::millitime();
393 // microtime() and gettimeofday() can drift from time() at least on Windows.
394 // The drift is immediate for processes running while the system clock changes.
395 // time() does not have this problem. See https://bugs.php.net/bug.php?id=42659.
396 if ( abs( time() - $time[0] ) >= 2 ) {
397 // We don't want processes using too high or low timestamps to avoid duplicate
398 // UIDs and clock sequence number churn. This process should just be restarted.
399 flock( $handle, LOCK_UN ); // abort
400 throw new MWException( "Process clock is outdated or drifted." );
402 // If microtime() is synced and a clock change was detected, then the clock went back
403 if ( $clockChanged ) {
404 // Bump the clock sequence number and also randomize the counter offset,
405 // which is useful for UIDs that do not include the clock sequence number.
406 $clkSeq = ( $clkSeq + 1 ) % $clockSeqSize;
407 $offset = mt_rand( 0, $counterSize - 1 );
408 trigger_error( "Clock was set back; sequence number incremented." );
410 // Update the (clock sequence number, timestamp, counter)
411 ftruncate( $handle, 0 );
412 rewind( $handle );
413 fwrite( $handle, "{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
414 fflush( $handle );
415 // Release the UID lock file
416 flock( $handle, LOCK_UN );
418 return array( $time, ( $counter + $offset ) % $counterSize, $clkSeq );
422 * Wait till the current timestamp reaches $time and return the current
423 * timestamp. This returns false if it would have to wait more than 10ms.
425 * @param array $time Result of UIDGenerator::millitime()
426 * @return array|bool UIDGenerator::millitime() result or false
428 protected function timeWaitUntil( array $time ) {
429 do {
430 $ct = self::millitime();
431 if ( $ct >= $time ) { // http://php.net/manual/en/language.operators.comparison.php
432 return $ct; // current timestamp is higher than $time
434 } while ( ( ( $time[0] - $ct[0] ) * 1000 + ( $time[1] - $ct[1] ) ) <= 10 );
436 return false;
440 * @param array $time Result of UIDGenerator::millitime()
441 * @return string 46 MSBs of "milliseconds since epoch" in binary (rolls over in 4201)
442 * @throws MWException
444 protected function millisecondsSinceEpochBinary( array $time ) {
445 list( $sec, $msec ) = $time;
446 $ts = 1000 * $sec + $msec;
447 if ( $ts > pow( 2, 52 ) ) {
448 throw new MWException( __METHOD__ .
449 ': sorry, this function doesn\'t work after the year 144680' );
452 return substr( wfBaseConvert( $ts, 10, 2, 46 ), -46 );
456 * @return array (current time in seconds, milliseconds since then)
458 protected static function millitime() {
459 list( $msec, $sec ) = explode( ' ', microtime() );
461 return array( (int)$sec, (int)( $msec * 1000 ) );
465 * Delete all cache files that have been created.
467 * This is a cleanup method primarily meant to be used from unit tests to
468 * avoid poluting the local filesystem. If used outside of a unit test
469 * environment it should be used with caution as it may destroy state saved
470 * in the files.
472 * @see unitTestTearDown
473 * @since 1.23
475 protected function deleteCacheFiles() {
476 // Bug: 44850
477 foreach ( $this->fileHandles as $path => $handle ) {
478 if ( $handle !== null ) {
479 fclose( $handle );
481 if ( is_file( $path ) ) {
482 unlink( $path );
484 unset( $this->fileHandles[$path] );
486 if ( is_file( $this->nodeIdFile ) ) {
487 unlink( $this->nodeIdFile );
492 * Cleanup resources when tearing down after a unit test.
494 * This is a cleanup method primarily meant to be used from unit tests to
495 * avoid poluting the local filesystem. If used outside of a unit test
496 * environment it should be used with caution as it may destroy state saved
497 * in the files.
499 * @see deleteCacheFiles
500 * @since 1.23
502 public static function unitTestTearDown() {
503 // Bug: 44850
504 $gen = self::singleton();
505 $gen->deleteCacheFiles();
508 function __destruct() {
509 array_map( 'fclose', array_filter( $this->fileHandles ) );