Merge "Skin: Avoid redirect=no for links to non-redirects"
[lhc/web/wiklou.git] / includes / libs / HashRing.php
1 <?php
2 /**
3 * Convenience class for weighted consistent hash rings.
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 */
22
23 /**
24 * Convenience class for weighted consistent hash rings
25 *
26 * This deterministically maps "keys" to a set of "locations" while avoiding clumping
27 *
28 * Each location is represented by a number of nodes on a ring proportionate to the ratio
29 * of its weight compared to the total location weight. Note positions are deterministically
30 * derived from the hash of the location name. Nodes are responsible for the portion of the
31 * ring, counter-clockwise, up until the next node. Locations are responsible for all portions
32 * of the ring that the location's nodes are responsible for.
33 *
34 * A location that is temporarily "ejected" is said to be absent from the "live" ring.
35 * If no location ejections are active, then the base ring and live ring are identical.
36 *
37 * @since 1.22
38 */
39 class HashRing implements Serializable {
40 /** @var string Hashing algorithm for hash() */
41 protected $algo;
42 /** @var int[] Non-empty (location => integer weight) */
43 protected $weightByLocation;
44 /** @var int[] Map of (location => UNIX timestamp) */
45 protected $ejectExpiryByLocation;
46
47 /** @var array[] Non-empty list of (float, node name, location name) */
48 protected $baseRing;
49 /** @var array[] Non-empty list of (float, node name, location name) */
50 protected $liveRing;
51
52 /** @var float Number of positions on the ring */
53 const RING_SIZE = 4294967296.0; // 2^32
54 /** @var integer Overall number of node groups per server */
55 const HASHES_PER_LOCATION = 40;
56 /** @var integer Number of nodes in a node group */
57 const SECTORS_PER_HASH = 4;
58
59 const KEY_POS = 0;
60 const KEY_LOCATION = 1;
61
62 /** @var int Consider all locations */
63 const RING_ALL = 0;
64 /** @var int Only consider "live" locations */
65 const RING_LIVE = 1;
66
67 /**
68 * Make a consistent hash ring given a set of locations and their weight values
69 *
70 * @param int[] $map Map of (location => weight)
71 * @param string $algo Hashing algorithm listed in hash_algos() [optional]
72 * @param int[] $ejections Map of (location => UNIX timestamp) for ejection expiries
73 * @since 1.31
74 */
75 public function __construct( array $map, $algo = 'sha1', array $ejections = [] ) {
76 $this->init( $map, $algo, $ejections );
77 }
78
79 /**
80 * @param int[] $map Map of (location => integer)
81 * @param string $algo Hashing algorithm
82 * @param int[] $ejections Map of (location => UNIX timestamp) for ejection expires
83 */
84 protected function init( array $map, $algo, array $ejections ) {
85 if ( !in_array( $algo, hash_algos(), true ) ) {
86 throw new RuntimeException( __METHOD__ . ": unsupported '$algo' hash algorithm." );
87 }
88
89 $weightByLocation = array_filter( $map );
90 if ( $weightByLocation === [] ) {
91 throw new UnexpectedValueException( "No locations with non-zero weight." );
92 } elseif ( min( $map ) < 0 ) {
93 throw new InvalidArgumentException( "Location weight cannot be negative." );
94 }
95
96 $this->algo = $algo;
97 $this->weightByLocation = $weightByLocation;
98 $this->ejectExpiryByLocation = $ejections;
99 $this->baseRing = $this->buildLocationRing( $this->weightByLocation, $this->algo );
100 }
101
102 /**
103 * Get the location of an item on the ring
104 *
105 * @param string $item
106 * @return string Location
107 * @throws UnexpectedValueException
108 */
109 final public function getLocation( $item ) {
110 return $this->getLocations( $item, 1 )[0];
111 }
112
113 /**
114 * Get the location of an item on the ring, as well as the next locations
115 *
116 * @param string $item
117 * @param int $limit Maximum number of locations to return
118 * @param int $from One of the RING_* class constants
119 * @return string[] List of locations
120 * @throws UnexpectedValueException
121 */
122 public function getLocations( $item, $limit, $from = self::RING_ALL ) {
123 if ( $from === self::RING_ALL ) {
124 $ring = $this->baseRing;
125 } elseif ( $from === self::RING_LIVE ) {
126 $ring = $this->getLiveRing();
127 } else {
128 throw new InvalidArgumentException( "Invalid ring source specified." );
129 }
130
131 // Locate this item's position on the hash ring
132 $position = $this->getItemPosition( $item );
133 $itemNodeIndex = $this->findNodeIndexForPosition( $position, $ring );
134
135 $locations = [];
136 $currentIndex = $itemNodeIndex;
137 while ( count( $locations ) < $limit ) {
138 $nodeLocation = $ring[$currentIndex][self::KEY_LOCATION];
139 if ( !in_array( $nodeLocation, $locations, true ) ) {
140 // Ignore other nodes for the same locations already added
141 $locations[] = $nodeLocation;
142 }
143 $currentIndex = $this->getNextClockwiseNodeIndex( $currentIndex, $ring );
144 if ( $currentIndex === $itemNodeIndex ) {
145 break; // all nodes visited
146 }
147 }
148
149 return $locations;
150 }
151
152 /**
153 * @param float $position
154 * @param array[] $ring Either the base or live ring
155 * @return int|null
156 */
157 private function findNodeIndexForPosition( $position, $ring ) {
158 $count = count( $ring );
159 if ( $count === 0 ) {
160 return null;
161 }
162 $lowPos = 0;
163 $highPos = $count;
164 while ( true ) {
165 $midPos = intval( ( $lowPos + $highPos ) / 2 );
166 if ( $midPos === $count ) {
167 return 0;
168 }
169 $midVal = $ring[$midPos][self::KEY_POS];
170 $midMinusOneVal = $midPos === 0 ? 0 : $ring[$midPos - 1][self::KEY_POS];
171
172 if ( $position <= $midVal && $position > $midMinusOneVal ) {
173 return $midPos;
174 }
175
176 if ( $midVal < $position ) {
177 $lowPos = $midPos + 1;
178 } else {
179 $highPos = $midPos - 1;
180 }
181
182 if ( $lowPos > $highPos ) {
183 return 0;
184 }
185 }
186 }
187
188 /**
189 * Get the map of locations to weight (does not include zero weight items)
190 *
191 * @return int[]
192 */
193 public function getLocationWeights() {
194 return $this->weightByLocation;
195 }
196
197 /**
198 * Remove a location from the "live" hash ring
199 *
200 * @param string $location
201 * @param int $ttl Seconds
202 * @return bool Whether some non-ejected locations are left
203 * @throws UnexpectedValueException
204 */
205 public function ejectFromLiveRing( $location, $ttl ) {
206 if ( !isset( $this->weightByLocation[$location] ) ) {
207 throw new UnexpectedValueException( "No location '$location' in the ring." );
208 }
209
210 $expiry = $this->getCurrentTime() + $ttl;
211 $this->ejectExpiryByLocation[$location] = $expiry;
212
213 $this->liveRing = null; // invalidate ring cache
214
215 return ( count( $this->ejectExpiryByLocation ) < count( $this->weightByLocation ) );
216 }
217
218 /**
219 * Get the location of an item on the "live" ring
220 *
221 * @param string $item
222 * @return string Location
223 * @throws UnexpectedValueException
224 */
225 final public function getLiveLocation( $item ) {
226 return $this->getLocations( $item, 1, self::RING_LIVE )[0];
227 }
228
229 /**
230 * Get the location of an item on the "live" ring, as well as the next locations
231 *
232 * @param string $item
233 * @param int $limit Maximum number of locations to return
234 * @return string[] List of locations
235 * @throws UnexpectedValueException
236 */
237 final public function getLiveLocations( $item, $limit ) {
238 return $this->getLocations( $item, $limit, self::RING_LIVE );
239 }
240
241 /**
242 * Get the map of "live" locations to weight (does not include zero weight items)
243 *
244 * @return int[]
245 * @throws UnexpectedValueException
246 */
247 public function getLiveLocationWeights() {
248 $now = $this->getCurrentTime();
249
250 return array_diff_key(
251 $this->weightByLocation,
252 array_filter(
253 $this->ejectExpiryByLocation,
254 function ( $expiry ) use ( $now ) {
255 return ( $expiry > $now );
256 }
257 )
258 );
259 }
260
261 /**
262 * @param int[] $weightByLocation
263 * @param string $algo Hashing algorithm
264 * @return array[]
265 */
266 private function buildLocationRing( array $weightByLocation, $algo ) {
267 $locationCount = count( $weightByLocation );
268 $totalWeight = array_sum( $weightByLocation );
269
270 $ring = [];
271 // Assign nodes to all locations based on location weight
272 $claimed = []; // (position as string => (node, index))
273 foreach ( $weightByLocation as $location => $weight ) {
274 $ratio = $weight / $totalWeight;
275 // There $locationCount * (HASHES_PER_LOCATION * 4) nodes available;
276 // assign a few groups of nodes to this location based on its weight.
277 $nodesQuartets = intval( $ratio * self::HASHES_PER_LOCATION * $locationCount );
278 for ( $qi = 0; $qi < $nodesQuartets; ++$qi ) {
279 // For efficiency, get 4 points per hash call and 4X node count.
280 // If $algo is MD5, then this matches that of with libketama.
281 // See https://github.com/RJ/ketama/blob/master/libketama/ketama.c
282 $positions = $this->getNodePositionQuartet( "{$location}-{$qi}" );
283 foreach ( $positions as $gi => $position ) {
284 $node = ( $qi * self::SECTORS_PER_HASH + $gi ) . "@$location";
285 $posKey = (string)$position; // large integer
286 if ( isset( $claimed[$posKey] ) ) {
287 // Disallow duplicates for sanity (name decides precedence)
288 if ( $claimed[$posKey]['node'] > $node ) {
289 continue;
290 } else {
291 unset( $ring[$claimed[$posKey]['index']] );
292 }
293 }
294 $ring[] = [
295 self::KEY_POS => $position,
296 self::KEY_LOCATION => $location
297 ];
298 $claimed[$posKey] = [ 'node' => $node, 'index' => count( $ring ) - 1 ];
299 }
300 }
301 }
302 // Sort the locations into clockwise order based on the hash ring position
303 usort( $ring, function ( $a, $b ) {
304 if ( $a[self::KEY_POS] === $b[self::KEY_POS] ) {
305 throw new UnexpectedValueException( 'Duplicate node positions.' );
306 }
307
308 return ( $a[self::KEY_POS] < $b[self::KEY_POS] ? -1 : 1 );
309 } );
310
311 return $ring;
312 }
313
314 /**
315 * @param string $item Key
316 * @return float Ring position; integral number in [0, self::RING_SIZE - 1]
317 */
318 private function getItemPosition( $item ) {
319 // If $algo is MD5, then this matches that of with libketama.
320 // See https://github.com/RJ/ketama/blob/master/libketama/ketama.c
321 $octets = substr( hash( $this->algo, (string)$item, true ), 0, 4 );
322 if ( strlen( $octets ) != 4 ) {
323 throw new UnexpectedValueException( __METHOD__ . ": {$this->algo} is < 32 bits." );
324 }
325
326 return (float)sprintf( '%u', unpack( 'V', $octets )[1] );
327 }
328
329 /**
330 * @param string $nodeGroupName
331 * @return float[] Four ring positions on [0, self::RING_SIZE - 1]
332 */
333 private function getNodePositionQuartet( $nodeGroupName ) {
334 $octets = substr( hash( $this->algo, (string)$nodeGroupName, true ), 0, 16 );
335 if ( strlen( $octets ) != 16 ) {
336 throw new UnexpectedValueException( __METHOD__ . ": {$this->algo} is < 128 bits." );
337 }
338
339 $positions = [];
340 foreach ( unpack( 'V4', $octets ) as $signed ) {
341 $positions[] = (float)sprintf( '%u', $signed );
342 }
343
344 return $positions;
345 }
346
347 /**
348 * @param int $i Valid index for a node in the ring
349 * @param array[] $ring Either the base or live ring
350 * @return int Valid index for a node in the ring
351 */
352 private function getNextClockwiseNodeIndex( $i, $ring ) {
353 if ( !isset( $ring[$i] ) ) {
354 throw new UnexpectedValueException( __METHOD__ . ": reference index is invalid." );
355 }
356
357 $next = $i + 1;
358
359 return ( $next < count( $ring ) ) ? $next : 0;
360 }
361
362 /**
363 * Get the "live" hash ring (which does not include ejected locations)
364 *
365 * @return array[]
366 * @throws UnexpectedValueException
367 */
368 protected function getLiveRing() {
369 if ( !$this->ejectExpiryByLocation ) {
370 return $this->baseRing; // nothing ejected
371 }
372
373 $now = $this->getCurrentTime();
374
375 if ( $this->liveRing === null || min( $this->ejectExpiryByLocation ) <= $now ) {
376 // Live ring needs to be regerenated...
377 $this->ejectExpiryByLocation = array_filter(
378 $this->ejectExpiryByLocation,
379 function ( $expiry ) use ( $now ) {
380 return ( $expiry > $now );
381 }
382 );
383
384 if ( count( $this->ejectExpiryByLocation ) ) {
385 // Some locations are still ejected from the ring
386 $liveRing = [];
387 foreach ( $this->baseRing as $i => $nodeInfo ) {
388 $location = $nodeInfo[self::KEY_LOCATION];
389 if ( !isset( $this->ejectExpiryByLocation[$location] ) ) {
390 $liveRing[] = $nodeInfo;
391 }
392 }
393 } else {
394 $liveRing = $this->baseRing;
395 }
396
397 $this->liveRing = $liveRing;
398 }
399
400 if ( !$this->liveRing ) {
401 throw new UnexpectedValueException( "The live ring is currently empty." );
402 }
403
404 return $this->liveRing;
405 }
406
407 /**
408 * @return int UNIX timestamp
409 */
410 protected function getCurrentTime() {
411 return time();
412 }
413
414 public function serialize() {
415 return serialize( [
416 'algorithm' => $this->algo,
417 'locations' => $this->weightByLocation,
418 'ejections' => $this->ejectExpiryByLocation
419 ] );
420 }
421
422 public function unserialize( $serialized ) {
423 $data = unserialize( $serialized );
424 if ( is_array( $data ) ) {
425 $this->init( $data['locations'], $data['algorithm'], $data['ejections'] );
426 } else {
427 throw new UnexpectedValueException( __METHOD__ . ": unable to decode JSON." );
428 }
429 }
430 }