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
21 * @author Aaron Schulz
23 use Wikimedia\Assert\Assert
;
26 * Class for getting statistically unique IDs
31 /** @var UIDGenerator */
32 protected static $instance = null;
34 protected $nodeIdFile; // string; local file path
35 protected $nodeId32; // string; node ID in binary (32 bits)
36 protected $nodeId48; // string; node ID in binary (48 bits)
38 protected $lockFile88; // string; local file path
39 protected $lockFile128; // string; local file path
42 protected $fileHandles = array(); // cache file handles
44 const QUICK_RAND
= 1; // get randomness from fast and insecure sources
45 const QUICK_VOLATILE
= 2; // use an APC like in-memory counter if available
47 protected function __construct() {
48 $this->nodeIdFile
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-nodeid';
50 if ( is_file( $this->nodeIdFile
) ) {
51 $nodeId = file_get_contents( $this->nodeIdFile
);
53 // Try to get some ID that uniquely identifies this machine (RFC 4122)...
54 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
55 MediaWiki\
suppressWarnings();
56 if ( wfIsWindows() ) {
57 // http://technet.microsoft.com/en-us/library/bb490913.aspx
58 $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
59 $line = substr( $csv, 0, strcspn( $csv, "\n" ) );
60 $info = str_getcsv( $line );
61 $nodeId = isset( $info[0] ) ?
str_replace( '-', '', $info[0] ) : '';
62 } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
63 // See http://linux.die.net/man/8/ifconfig
65 preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
66 wfShellExec( '/sbin/ifconfig -a' ), $m );
67 $nodeId = isset( $m[1] ) ?
str_replace( ':', '', $m[1] ) : '';
69 MediaWiki\restoreWarnings
();
70 if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
71 $nodeId = MWCryptRand
::generateHex( 12, true );
72 $nodeId[1] = dechex( hexdec( $nodeId[1] ) |
0x1 ); // set multicast bit
74 file_put_contents( $this->nodeIdFile
, $nodeId ); // cache
76 $this->nodeId32
= wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
77 $this->nodeId48
= wfBaseConvert( $nodeId, 16, 2, 48 );
78 // If different processes run as different users, they may have different temp dirs.
79 // This is dealt with by initializing the clock sequence number and counters randomly.
80 $this->lockFile88
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-88';
81 $this->lockFile128
= wfTempDir() . '/mw-' . __CLASS__
. '-UID-128';
85 * @return UIDGenerator
87 protected static function singleton() {
88 if ( self
::$instance === null ) {
89 self
::$instance = new self();
92 return self
::$instance;
96 * Get a statistically unique 88-bit unsigned integer ID string.
97 * The bits of the UID are prefixed with the time (down to the millisecond).
99 * These IDs are suitable as values for the shard key of distributed data.
100 * If a column uses these as values, it should be declared UNIQUE to handle collisions.
101 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
102 * They can also be stored "DECIMAL(27) UNSIGNED" or BINARY(11) in MySQL.
104 * UID generation is serialized on each server (as the node ID is for the whole machine).
106 * @param int $base Specifies a base other than 10
107 * @return string Number
108 * @throws MWException
110 public static function newTimestampedUID88( $base = 10 ) {
111 Assert
::parameterType( 'integer', $base, '$base' );
112 Assert
::parameter( $base <= 36, '$base', 'must be <= 36' );
113 Assert
::parameter( $base >= 2, '$base', 'must be >= 2' );
115 $gen = self
::singleton();
116 $time = $gen->getTimestampAndDelay( 'lockFile88', 1, 1024 );
118 return wfBaseConvert( $gen->getTimestampedID88( $time ), 2, $base );
122 * @param array $info (UIDGenerator::millitime(), counter, clock sequence)
123 * @return string 88 bits
124 * @throws MWException
126 protected function getTimestampedID88( array $info ) {
127 list( $time, $counter ) = $info;
128 // Take the 46 MSBs of "milliseconds since epoch"
129 $id_bin = $this->millisecondsSinceEpochBinary( $time );
130 // Add a 10 bit counter resulting in 56 bits total
131 $id_bin .= str_pad( decbin( $counter ), 10, '0', STR_PAD_LEFT
);
132 // Add the 32 bit node ID resulting in 88 bits total
133 $id_bin .= $this->nodeId32
;
134 // Convert to a 1-27 digit integer string
135 if ( strlen( $id_bin ) !== 88 ) {
136 throw new MWException( "Detected overflow for millisecond timestamp." );
143 * Get a statistically unique 128-bit unsigned integer ID string.
144 * The bits of the UID are prefixed with the time (down to the millisecond).
146 * These IDs are suitable as globally unique IDs, without any enforced uniqueness.
147 * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast.
148 * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL.
150 * UID generation is serialized on each server (as the node ID is for the whole machine).
152 * @param int $base Specifies a base other than 10
153 * @return string Number
154 * @throws MWException
156 public static function newTimestampedUID128( $base = 10 ) {
157 Assert
::parameterType( 'integer', $base, '$base' );
158 Assert
::parameter( $base <= 36, '$base', 'must be <= 36' );
159 Assert
::parameter( $base >= 2, '$base', 'must be >= 2' );
161 $gen = self
::singleton();
162 $time = $gen->getTimestampAndDelay( 'lockFile128', 16384, 1048576 );
164 return wfBaseConvert( $gen->getTimestampedID128( $time ), 2, $base );
168 * @param array $info (UIDGenerator::millitime(), counter, clock sequence)
169 * @return string 128 bits
170 * @throws MWException
172 protected function getTimestampedID128( array $info ) {
173 list( $time, $counter, $clkSeq ) = $info;
174 // Take the 46 MSBs of "milliseconds since epoch"
175 $id_bin = $this->millisecondsSinceEpochBinary( $time );
176 // Add a 20 bit counter resulting in 66 bits total
177 $id_bin .= str_pad( decbin( $counter ), 20, '0', STR_PAD_LEFT
);
178 // Add a 14 bit clock sequence number resulting in 80 bits total
179 $id_bin .= str_pad( decbin( $clkSeq ), 14, '0', STR_PAD_LEFT
);
180 // Add the 48 bit node ID resulting in 128 bits total
181 $id_bin .= $this->nodeId48
;
182 // Convert to a 1-39 digit integer string
183 if ( strlen( $id_bin ) !== 128 ) {
184 throw new MWException( "Detected overflow for millisecond timestamp." );
191 * Return an RFC4122 compliant v4 UUID
193 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
195 * @throws MWException
197 public static function newUUIDv4( $flags = 0 ) {
198 $hex = ( $flags & self
::QUICK_RAND
)
199 ?
wfRandomString( 31 )
200 : MWCryptRand
::generateHex( 31 );
202 return sprintf( '%s-%s-%s-%s-%s',
203 // "time_low" (32 bits)
204 substr( $hex, 0, 8 ),
205 // "time_mid" (16 bits)
206 substr( $hex, 8, 4 ),
207 // "time_hi_and_version" (16 bits)
208 '4' . substr( $hex, 12, 3 ),
209 // "clk_seq_hi_res (8 bits, variant is binary 10x) and "clk_seq_low" (8 bits)
210 dechex( 0x8 |
( hexdec( $hex[15] ) & 0x3 ) ) . $hex[16] . substr( $hex, 17, 2 ),
212 substr( $hex, 19, 12 )
217 * Return an RFC4122 compliant v4 UUID
219 * @param int $flags Bitfield (supports UIDGenerator::QUICK_RAND)
220 * @return string 32 hex characters with no hyphens
221 * @throws MWException
223 public static function newRawUUIDv4( $flags = 0 ) {
224 return str_replace( '-', '', self
::newUUIDv4( $flags ) );
228 * Return an ID that is sequential *only* for this node and bucket
230 * These IDs are suitable for per-host sequence numbers, e.g. for some packet protocols.
231 * If UIDGenerator::QUICK_VOLATILE is used the counter might reset on server restart.
233 * @param string $bucket Arbitrary bucket name (should be ASCII)
234 * @param int $bits Bit size (<=48) of resulting numbers before wrap-around
235 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
236 * @return float Integer value as float
239 public static function newSequentialPerNodeID( $bucket, $bits = 48, $flags = 0 ) {
240 return current( self
::newSequentialPerNodeIDs( $bucket, $bits, 1, $flags ) );
244 * Return IDs that are sequential *only* for this node and bucket
246 * @see UIDGenerator::newSequentialPerNodeID()
247 * @param string $bucket Arbitrary bucket name (should be ASCII)
248 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
249 * @param int $count Number of IDs to return (1 to 10000)
250 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
251 * @return array Ordered list of float integer values
254 public static function newSequentialPerNodeIDs( $bucket, $bits, $count, $flags = 0 ) {
255 $gen = self
::singleton();
256 return $gen->getSequentialPerNodeIDs( $bucket, $bits, $count, $flags );
260 * Return IDs that are sequential *only* for this node and bucket
262 * @see UIDGenerator::newSequentialPerNodeID()
263 * @param string $bucket Arbitrary bucket name (should be ASCII)
264 * @param int $bits Bit size (16 to 48) of resulting numbers before wrap-around
265 * @param int $count Number of IDs to return (1 to 10000)
266 * @param int $flags (supports UIDGenerator::QUICK_VOLATILE)
267 * @return array Ordered list of float integer values
268 * @throws MWException
270 protected function getSequentialPerNodeIDs( $bucket, $bits, $count, $flags ) {
272 return array(); // nothing to do
273 } elseif ( $count > 10000 ) {
274 throw new MWException( "Number of requested IDs ($count) is too high." );
275 } elseif ( $bits < 16 ||
$bits > 48 ) {
276 throw new MWException( "Requested bit size ($bits) is out of range." );
279 $counter = null; // post-increment persistent counter value
281 // Use APC/eAccelerator/xcache if requested, available, and not in CLI mode;
282 // Counter values would not survive accross script instances in CLI mode.
284 if ( ( $flags & self
::QUICK_VOLATILE
) && PHP_SAPI
!== 'cli' ) {
285 $cache = ObjectCache
::getLocalServerInstance();
288 $counter = $cache->incr( $bucket, $count );
289 if ( $counter === false ) {
290 if ( !$cache->add( $bucket, (int)$count ) ) {
291 throw new MWException( 'Unable to set value to ' . get_class( $cache ) );
297 // Note: use of fmod() avoids "division by zero" on 32 bit machines
298 if ( $counter === null ) {
299 $path = wfTempDir() . '/mw-' . __CLASS__
. '-' . rawurlencode( $bucket ) . '-48';
300 // Get the UID lock file handle
301 if ( isset( $this->fileHandles
[$path] ) ) {
302 $handle = $this->fileHandles
[$path];
304 $handle = fopen( $path, 'cb+' );
305 $this->fileHandles
[$path] = $handle ?
: null; // cache
307 // Acquire the UID lock file
308 if ( $handle === false ) {
309 throw new MWException( "Could not open '{$path}'." );
310 } elseif ( !flock( $handle, LOCK_EX
) ) {
312 throw new MWException( "Could not acquire '{$path}'." );
314 // Fetch the counter value and increment it...
316 $counter = floor( trim( fgets( $handle ) ) ) +
$count; // fetch as float
317 // Write back the new counter value
318 ftruncate( $handle, 0 );
320 fwrite( $handle, fmod( $counter, pow( 2, 48 ) ) ); // warp-around as needed
322 // Release the UID lock file
323 flock( $handle, LOCK_UN
);
327 $divisor = pow( 2, $bits );
328 $currentId = floor( $counter - $count ); // pre-increment counter value
329 for ( $i = 0; $i < $count; ++
$i ) {
330 $ids[] = fmod( ++
$currentId, $divisor );
337 * Get a (time,counter,clock sequence) where (time,counter) is higher
338 * than any previous (time,counter) value for the given clock sequence.
339 * This is useful for making UIDs sequential on a per-node bases.
341 * @param string $lockFile Name of a local lock file
342 * @param int $clockSeqSize The number of possible clock sequence values
343 * @param int $counterSize The number of possible counter values
344 * @return array (result of UIDGenerator::millitime(), counter, clock sequence)
345 * @throws MWException
347 protected function getTimestampAndDelay( $lockFile, $clockSeqSize, $counterSize ) {
348 // Get the UID lock file handle
349 $path = $this->$lockFile;
350 if ( isset( $this->fileHandles
[$path] ) ) {
351 $handle = $this->fileHandles
[$path];
353 $handle = fopen( $path, 'cb+' );
354 $this->fileHandles
[$path] = $handle ?
: null; // cache
356 // Acquire the UID lock file
357 if ( $handle === false ) {
358 throw new MWException( "Could not open '{$this->$lockFile}'." );
359 } elseif ( !flock( $handle, LOCK_EX
) ) {
361 throw new MWException( "Could not acquire '{$this->$lockFile}'." );
363 // Get the current timestamp, clock sequence number, last time, and counter
365 $data = explode( ' ', fgets( $handle ) ); // "<clk seq> <sec> <msec> <counter> <offset>"
366 $clockChanged = false; // clock set back significantly?
367 if ( count( $data ) == 5 ) { // last UID info already initialized
368 $clkSeq = (int)$data[0] %
$clockSeqSize;
369 $prevTime = array( (int)$data[1], (int)$data[2] );
370 $offset = (int)$data[4] %
$counterSize; // random counter offset
371 $counter = 0; // counter for UIDs with the same timestamp
372 // Delay until the clock reaches the time of the last ID.
373 // This detects any microtime() drift among processes.
374 $time = $this->timeWaitUntil( $prevTime );
375 if ( !$time ) { // too long to delay?
376 $clockChanged = true; // bump clock sequence number
377 $time = self
::millitime();
378 } elseif ( $time == $prevTime ) {
379 // Bump the counter if there are timestamp collisions
380 $counter = (int)$data[3] %
$counterSize;
381 if ( ++
$counter >= $counterSize ) { // sanity (starts at 0)
382 flock( $handle, LOCK_UN
); // abort
383 throw new MWException( "Counter overflow for timestamp value." );
386 } else { // last UID info not initialized
387 $clkSeq = mt_rand( 0, $clockSeqSize - 1 );
389 $offset = mt_rand( 0, $counterSize - 1 );
390 $time = self
::millitime();
392 // microtime() and gettimeofday() can drift from time() at least on Windows.
393 // The drift is immediate for processes running while the system clock changes.
394 // time() does not have this problem. See https://bugs.php.net/bug.php?id=42659.
395 if ( abs( time() - $time[0] ) >= 2 ) {
396 // We don't want processes using too high or low timestamps to avoid duplicate
397 // UIDs and clock sequence number churn. This process should just be restarted.
398 flock( $handle, LOCK_UN
); // abort
399 throw new MWException( "Process clock is outdated or drifted." );
401 // If microtime() is synced and a clock change was detected, then the clock went back
402 if ( $clockChanged ) {
403 // Bump the clock sequence number and also randomize the counter offset,
404 // which is useful for UIDs that do not include the clock sequence number.
405 $clkSeq = ( $clkSeq +
1 ) %
$clockSeqSize;
406 $offset = mt_rand( 0, $counterSize - 1 );
407 trigger_error( "Clock was set back; sequence number incremented." );
409 // Update the (clock sequence number, timestamp, counter)
410 ftruncate( $handle, 0 );
412 fwrite( $handle, "{$clkSeq} {$time[0]} {$time[1]} {$counter} {$offset}" );
414 // Release the UID lock file
415 flock( $handle, LOCK_UN
);
417 return array( $time, ( $counter +
$offset ) %
$counterSize, $clkSeq );
421 * Wait till the current timestamp reaches $time and return the current
422 * timestamp. This returns false if it would have to wait more than 10ms.
424 * @param array $time Result of UIDGenerator::millitime()
425 * @return array|bool UIDGenerator::millitime() result or false
427 protected function timeWaitUntil( array $time ) {
429 $ct = self
::millitime();
430 if ( $ct >= $time ) { // http://php.net/manual/en/language.operators.comparison.php
431 return $ct; // current timestamp is higher than $time
433 } while ( ( ( $time[0] - $ct[0] ) * 1000 +
( $time[1] - $ct[1] ) ) <= 10 );
439 * @param array $time Result of UIDGenerator::millitime()
440 * @return string 46 MSBs of "milliseconds since epoch" in binary (rolls over in 4201)
441 * @throws MWException
443 protected function millisecondsSinceEpochBinary( array $time ) {
444 list( $sec, $msec ) = $time;
445 $ts = 1000 * $sec +
$msec;
446 if ( $ts > pow( 2, 52 ) ) {
447 throw new MWException( __METHOD__
.
448 ': sorry, this function doesn\'t work after the year 144680' );
451 return substr( wfBaseConvert( $ts, 10, 2, 46 ), -46 );
455 * @return array (current time in seconds, milliseconds since then)
457 protected static function millitime() {
458 list( $msec, $sec ) = explode( ' ', microtime() );
460 return array( (int)$sec, (int)( $msec * 1000 ) );
464 * Delete all cache files that have been created.
466 * This is a cleanup method primarily meant to be used from unit tests to
467 * avoid poluting the local filesystem. If used outside of a unit test
468 * environment it should be used with caution as it may destroy state saved
471 * @see unitTestTearDown
474 protected function deleteCacheFiles() {
476 foreach ( $this->fileHandles
as $path => $handle ) {
477 if ( $handle !== null ) {
480 if ( is_file( $path ) ) {
483 unset( $this->fileHandles
[$path] );
485 if ( is_file( $this->nodeIdFile
) ) {
486 unlink( $this->nodeIdFile
);
491 * Cleanup resources when tearing down after a unit test.
493 * This is a cleanup method primarily meant to be used from unit tests to
494 * avoid poluting the local filesystem. If used outside of a unit test
495 * environment it should be used with caution as it may destroy state saved
498 * @see deleteCacheFiles
501 public static function unitTestTearDown() {
503 $gen = self
::singleton();
504 $gen->deleteCacheFiles();
507 function __destruct() {
508 array_map( 'fclose', array_filter( $this->fileHandles
) );