| 1 | package AnyEvent::Redis::Federated; | ||
| 2 | |||
| 3 | # An AnyEvent-based Redis client which implements timeouts, connection | ||
| 4 | # retries, multi-machine pool configuration (including consistent | ||
| 5 | # hashing), and other magic bits. | ||
| 6 | |||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use AnyEvent::Redis; | ||
| 10 | use AnyEvent; | ||
| 11 | use Set::ConsistentHash; # for hash ring logic | ||
| 12 | use Digest::MD5 qw(md5); # for hashing keys | ||
| 13 | use Scalar::Util qw(weaken); | ||
| 14 | use List::Util qw(shuffle); | ||
| 15 | |||
| 16 | our $VERSION = "0.08"; | ||
| 17 | |||
| 18 | # keep a global object cache that will contain weak references to | ||
| 19 | # objects keyed on their tag. this allows for sharing of objects | ||
| 20 | # within a given process by modules that are otherwise unaware of | ||
| 21 | # each other provided they use the same tag. | ||
| 22 | our %object_cache; | ||
| 23 | |||
| 24 | # These are all for failure handling (server down or unresponsive). | ||
| 25 | # If a connection to a given server fails, we'll retry up to | ||
| 26 | # MAX_HOST_RETRIES and then only retry once in a while. That | ||
| 27 | # interval is dictated by BASE_RETRY_INTERVAL. If that retry fails, | ||
| 28 | # we'll multiply that by RETRY_INTERVAL_MULT up to but not exceeding | ||
| 29 | # MAX_RETRY_INTERVAL. | ||
| 30 | # | ||
| 31 | # If we ever get a successful retry, we'll erase any memory of the | ||
| 32 | # failure and pretend things are just fine. | ||
| 33 | |||
| 34 | use constant MAX_HOST_RETRIES => 3; # how many in a row before we pass | ||
| 35 | use constant BASE_RETRY_INTERVAL => 2; # in seconds | ||
| 36 | use constant RETRY_INTERVAL_MULT => 2; # multiply this much each retry fail | ||
| 37 | use constant MAX_RETRY_INTERVAL => 600; # no more than this long | ||
| 38 | use constant DEFAULT_WEIGHT => 10; # for consistent hashing | ||
| 39 | use constant COMMAND_TIMEOUT => 1; # used in poll() | ||
| 40 | use constant QUERY_ALL => 0; # don't query all addresses by default | ||
| 41 | |||
| 42 | my %defaults = ( | ||
| 43 | command_timeout => COMMAND_TIMEOUT, | ||
| 44 | max_host_retries => MAX_HOST_RETRIES, | ||
| 45 | base_retry_interval => BASE_RETRY_INTERVAL, | ||
| 46 | retry_interval_mult => RETRY_INTERVAL_MULT, | ||
| 47 | max_retry_interval => MAX_RETRY_INTERVAL, | ||
| 48 | query_all => QUERY_ALL, | ||
| 49 | quiet => $ENV{QUIET}, | ||
| 50 | ); | ||
| 51 | |||
| 52 | sub new { | ||
| 53 | my $class = shift; | ||
| 54 | my $self = { @_ }; | ||
| 55 | |||
| 56 | # tag short circuit | ||
| 57 | if ($self->{tag}) { | ||
| 58 | if ($object_cache{$self->{tag}}) { | ||
| 59 | return $object_cache{$self->{tag}}; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | |||
| 63 | # basic init | ||
| 64 | while (my ($k, $v) = each %defaults) { | ||
| 65 | next if exists $self->{$k}; | ||
| 66 | $self->{$k} = $v; | ||
| 67 | } | ||
| 68 | |||
| 69 | # condvar for finishing up stuff (used in poll()) | ||
| 70 | $self->{cv} = undef; | ||
| 71 | |||
| 72 | # setup server_status tracking | ||
| 73 | $self->{server_status} = { }; | ||
| 74 | |||
| 75 | # request state | ||
| 76 | $self->{request_serial} = 0; | ||
| 77 | $self->{request_state} = { }; | ||
| 78 | |||
| 79 | # we must have configuration | ||
| 80 | if (not $self->{config}) { | ||
| 81 | die("No configuration provided. Can't instantiate Redis client"); | ||
| 82 | } | ||
| 83 | |||
| 84 | # populate node list | ||
| 85 | $self->{nodes} = [keys %{$self->{config}->{nodes}}]; | ||
| 86 | |||
| 87 | if ($self->{debug}) { | ||
| 88 | print "node list: ", join ', ', @{$self->{nodes}}; | ||
| 89 | print "\n"; | ||
| 90 | } | ||
| 91 | |||
| 92 | # setup the addresses array | ||
| 93 | foreach my $node (keys %{$self->{config}->{nodes}}) { | ||
| 94 | if ($self->{config}->{nodes}->{$node}->{addresses}) { | ||
| 95 | # shuffle the existing addresses array | ||
| 96 | @{$self->{config}->{nodes}->{$node}->{addresses}} = shuffle(@{$self->{config}->{nodes}->{$node}->{addresses}}); | ||
| 97 | # and set the first to be our targeted server | ||
| 98 | $self->{config}->{nodes}->{$node}->{address} = ${$self->{config}->{nodes}->{$node}->{addresses}}[-1]; | ||
| 99 | } | ||
| 100 | } | ||
| 101 | |||
| 102 | # setup the consistent hash | ||
| 103 | my $set = Set::ConsistentHash->new; | ||
| 104 | my @targets = map { $_, DEFAULT_WEIGHT } @{$self->{nodes}}; | ||
| 105 | $set->set_targets(@targets); | ||
| 106 | $set->set_hash_func(\&_hash); | ||
| 107 | $self->{set} = $set; | ||
| 108 | $self->{buckets} = $self->{set}->buckets; | ||
| 109 | |||
| 110 | $self->{idle_timeout} = 0 if not exists $self->{idle_timeout}; | ||
| 111 | |||
| 112 | print "config done.\n" if $self->{debug}; | ||
| 113 | bless $self, $class; | ||
| 114 | |||
| 115 | # cache it for later use | ||
| 116 | if ($self->{tag}) { | ||
| 117 | $object_cache{$self->{tag}} = $self; | ||
| 118 | weaken($object_cache{$self->{tag}}); | ||
| 119 | } | ||
| 120 | |||
| 121 | return $self; | ||
| 122 | } | ||
| 123 | |||
| 124 | sub removeNode { | ||
| 125 | my ($self, $node) = @_; | ||
| 126 | $self->{set}->modify_targets($node => 0); | ||
| 127 | $self->{buckets} = $self->{set}->buckets; | ||
| 128 | } | ||
| 129 | |||
| 130 | sub addNode { | ||
| 131 | my ($self, $name, $ref) = @_; | ||
| 132 | $self->{config}->{nodes}->{$name} = $ref; | ||
| 133 | $self->{set}->modify_targets($name => DEFAULT_WEIGHT); | ||
| 134 | $self->{buckets} = $self->{set}->buckets; | ||
| 135 | } | ||
| 136 | |||
| 137 | sub DESTROY { | ||
| 138 | } | ||
| 139 | |||
| 140 | sub _hash { | ||
| 141 | return unpack("N", md5(shift)); | ||
| 142 | } | ||
| 143 | |||
| 144 | sub commandTimeout { | ||
| 145 | my ($self, $time) = @_; | ||
| 146 | if (defined $time) { | ||
| 147 | $self->{command_timeout} = $time; | ||
| 148 | } | ||
| 149 | return $self->{command_timeout}; | ||
| 150 | } | ||
| 151 | |||
| 152 | sub queryAll { | ||
| 153 | my ($self, $val) = @_; | ||
| 154 | if (defined $val) { | ||
| 155 | $self->{query_all} = $val; | ||
| 156 | } | ||
| 157 | return $self->{query_all}; | ||
| 158 | } | ||
| 159 | |||
| 160 | sub nodeToHost { | ||
| 161 | my ($self, $node) = @_; | ||
| 162 | return $self->{config}->{nodes}->{$node}->{address}; | ||
| 163 | } | ||
| 164 | |||
| 165 | sub keyToNode { | ||
| 166 | my ($self, $key) = @_; | ||
| 167 | my $node = $self->{buckets}->[_hash($key) % 1024]; | ||
| 168 | return $node; | ||
| 169 | } | ||
| 170 | |||
| 171 | sub isServerDown { | ||
| 172 | my ($self, $server) = @_; | ||
| 173 | return 1 if $self->{server_status}{"$server:down"}; | ||
| 174 | return 0; | ||
| 175 | } | ||
| 176 | |||
| 177 | sub isServerUp { | ||
| 178 | my ($self, $server) = @_; | ||
| 179 | return 0 if $self->{server_status}{"$server:down"}; | ||
| 180 | return 1; | ||
| 181 | } | ||
| 182 | |||
| 183 | sub nextServer { | ||
| 184 | my ($self, $server, $node) = @_; | ||
| 185 | return $server unless $self->{config}->{nodes}->{$node}->{addresses}; | ||
| 186 | $self->{config}->{nodes}->{$node}->{address} = shift(@{$self->{config}->{nodes}->{$node}->{addresses}}); | ||
| 187 | push @{$self->{config}->{nodes}->{$node}->{addresses}}, $self->{config}->{nodes}->{$node}->{address}; | ||
| 188 | warn "redis server for $node changed from $server to $self->{config}->{nodes}->{$node}->{address} selected\n" if $self->{debug}; | ||
| 189 | return $self->{config}->{nodes}->{$node}->{address}; | ||
| 190 | } | ||
| 191 | |||
| 192 | ## return only on-line/up servers? | ||
| 193 | |||
| 194 | sub allServers { | ||
| 195 | my ($self, $node) = @_; | ||
| 196 | my $hosts = [ grep { $self->isServerUp($_) } @{$self->{config}->{nodes}->{$node}->{addresses}} ]; | ||
| 197 | return $hosts; | ||
| 198 | } | ||
| 199 | |||
| 200 | sub markServerUp { | ||
| 201 | my ($self, $server) = @_; | ||
| 202 | if ($self->{server_status}{"$server:down"}) { | ||
| 203 | my $down_since = localtime($self->{server_status}{"$server:down_since"}); | ||
| 204 | delete $self->{server_status}{"$server:down"}; | ||
| 205 | delete $self->{server_status}{"$server:retries"}; | ||
| 206 | delete $self->{server_status}{"$server:down_since"}; | ||
| 207 | delete $self->{server_status}{"$server:retry_pending"}; | ||
| 208 | delete $self->{server_status}{"$server:retry_interval"}; | ||
| 209 | warn "redis server $server back up (down since $down_since)\n" if $self->{debug}; | ||
| 210 | } | ||
| 211 | return 1; | ||
| 212 | } | ||
| 213 | |||
| 214 | sub markServerDown { | ||
| 215 | my ($self, $server, $delay) = @_; | ||
| 216 | $delay ||= $self->{base_retry_interval}; | ||
| 217 | warn "redis server $server seems down\n" if $self->{debug}; | ||
| 218 | |||
| 219 | # first time? | ||
| 220 | if (not $self->{server_status}{"$server:down"}) { | ||
| 221 | warn "server $server down, first time\n" if $self->{debug}; | ||
| 222 | $self->{server_status}{"$server:down"} = 1; | ||
| 223 | $self->{server_status}{"$server:retries"}++; | ||
| 224 | $self->{server_status}{"$server:down_since"} = time(); | ||
| 225 | $self->{server_status}{"$server:retry_interval"} ||= $self->{base_retry_interval}; | ||
| 226 | } | ||
| 227 | |||
| 228 | if ($self->{server_status}{"$server:retry_pending"}) { | ||
| 229 | warn "retry already pending for $server, skipping\n" if $self->{debug}; | ||
| 230 | return 1; | ||
| 231 | } | ||
| 232 | |||
| 233 | # ok, schedule the timer to re-check. this should NOT be a | ||
| 234 | # recurring timer, otherwise we end up with a bunch of pending | ||
| 235 | # retries since the "interval" is likely shorter than TCP timeout. | ||
| 236 | # eventually this will error out, in which case we'll try it again | ||
| 237 | # by calling markServerDown() after clearying retry_pending, or | ||
| 238 | # it'll work and we're good to go. | ||
| 239 | my $t; | ||
| 240 | my $r; | ||
| 241 | $t = AnyEvent->timer( | ||
| 242 | after => $delay, | ||
| 243 | cb => sub { | ||
| 244 | warn "timer callback triggered for $server" if $self->{debug}; | ||
| 245 | my ($host, $port) = split /:/, $server; | ||
| 246 | print "attempting reconnect to $server\n" if $self->{debug}; | ||
| 247 | $r = AnyEvent::Redis->new( | ||
| 248 | host => $host, | ||
| 249 | port => $port, | ||
| 250 | on_error => sub { | ||
| 251 | warn @_ unless $self->{quiet}; | ||
| 252 | $self->{server_status}{"$server:retry_pending"} = 0; | ||
| 253 | $self->markServerDown($server); # schedule another try | ||
| 254 | } | ||
| 255 | ); | ||
| 256 | |||
| 257 | $r->ping(sub{ | ||
| 258 | my $val = shift; # should be 'PONG' | ||
| 259 | if ($val ne 'PONG') { | ||
| 260 | warn "retry ping got $val instead of PONG" if $self->{debug}; | ||
| 261 | } | ||
| 262 | $self->{conn}->{$server} = $r; | ||
| 263 | $self->{server_status}{"$server:retry_pending"} = 0; | ||
| 264 | $self->markServerUp($server); | ||
| 265 | undef $t; # we need to keep a ref to the timer here so it runs at all | ||
| 266 | }); | ||
| 267 | } | ||
| 268 | ); | ||
| 269 | warn "scheduled health check of $server in $delay secs\n" if $self->{debug}; | ||
| 270 | $self->{server_status}{"$server:retry_pending"} = 1; | ||
| 271 | return 1; | ||
| 272 | } | ||
| 273 | |||
| 274 | our $AUTOLOAD; | ||
| 275 | |||
| 276 | sub AUTOLOAD { | ||
| 277 | my $self = shift; | ||
| 278 | my $call = lc $AUTOLOAD; | ||
| 279 | $call =~ s/.*:://; | ||
| 280 | print "method [$call] autoloaded\n" if $self->{debug}; | ||
| 281 | |||
| 282 | my $key = $_[0]; | ||
| 283 | my $hk = $key; | ||
| 284 | my $cb = sub { }; | ||
| 285 | |||
| 286 | if (ref $_[-1] eq 'CODE') { | ||
| 287 | $cb = pop @_; | ||
| 288 | } | ||
| 289 | |||
| 290 | # key group? | ||
| 291 | if (ref($_[0]) eq 'ARRAY') { | ||
| 292 | $hk = $_[0]->[0]; | ||
| 293 | $key = $_[0]->[1]; | ||
| 294 | $_[0] = $key; | ||
| 295 | } | ||
| 296 | |||
| 297 | my $node = $self->keyToNode($hk); | ||
| 298 | my $query_all = $self->{query_all}; | ||
| 299 | |||
| 300 | if ($call =~ s/_all$//) { | ||
| 301 | $query_all = 1; | ||
| 302 | } | ||
| 303 | |||
| 304 | ## The normal single-server case... | ||
| 305 | if (not $query_all) { | ||
| 306 | my $server = $self->nodeToHost($node); | ||
| 307 | print "server [$server] of node [$node] for key [$key] hashkey [$hk]\n" if $self->{debug}; | ||
| 308 | |||
| 309 | if ($self->isServerDown($server)) { | ||
| 310 | # try another if we can | ||
| 311 | if ($self->{config}->{nodes}->{$node}->{addresses}) { | ||
| 312 | print "server [$server] seems down\n" if $self->{debug}; | ||
| 313 | $server = $self->nextServer($server, $node); | ||
| 314 | print "trying next server in line [$server] for node [$node]\n" if $self->{debug}; | ||
| 315 | } | ||
| 316 | # bail otherwise | ||
| 317 | else { | ||
| 318 | print "server $server down. abandoning call.\n" if $self->{debug}; | ||
| 319 | $cb->(undef); | ||
| 320 | return $self; | ||
| 321 | } | ||
| 322 | } | ||
| 323 | |||
| 324 | return $self->scheduleCall($server, $call, [@_], $cb); | ||
| 325 | } | ||
| 326 | |||
| 327 | ## Need to fire this one at all up servers in the node group... | ||
| 328 | else { | ||
| 329 | my $servers = $self->allServers($node); | ||
| 330 | for my $server (@$servers) { | ||
| 331 | $self->scheduleCall($server, $call, [@_], $cb); | ||
| 332 | } | ||
| 333 | return $self; | ||
| 334 | } | ||
| 335 | } | ||
| 336 | |||
| 337 | sub poll { | ||
| 338 | my ($self) = @_; | ||
| 339 | #return if $self->{pending_requests} < 1; | ||
| 340 | return if not defined $self->{cv}; | ||
| 341 | my $rid = $self->{request_serial}; | ||
| 342 | my $timeout = $self->{command_timeout}; | ||
| 343 | |||
| 344 | my $w; | ||
| 345 | if ($timeout) { | ||
| 346 | $w = AnyEvent->signal(signal => "ALRM", cb => sub { | ||
| 347 | warn "AnyEvent::Redis::Federated::poll alarm timeout! ($rid)\n" if $self->{debug}; | ||
| 348 | |||
| 349 | # check the state of requests, marking remaining as cancelled | ||
| 350 | while (my ($rid, $state) = each %{$self->{request_state}}) { | ||
| 351 | if ($self->{request_state}->{$rid}) { | ||
| 352 | print "found pending request to cancel: $rid\n" if $self->{debug}; | ||
| 353 | $self->{request_state}->{$rid} = 0; | ||
| 354 | $self->{cv}->end; | ||
| 355 | undef $w; | ||
| 356 | } | ||
| 357 | } | ||
| 358 | }); | ||
| 359 | print "scheduling alarm timer in poll() for $timeout\n" if $self->{debug}; | ||
| 360 | alarm($timeout); | ||
| 361 | } | ||
| 362 | |||
| 363 | $self->{cv}->recv; | ||
| 364 | $self->{cv} = undef; | ||
| 365 | alarm(0); | ||
| 366 | undef $w; | ||
| 367 | } | ||
| 368 | |||
| 369 | sub scheduleCall { | ||
| 370 | my ($self, $server, $call, $args, $cb) = @_; | ||
| 371 | |||
| 372 | # have a non-idle connection already? | ||
| 373 | my $r; | ||
| 374 | if ($self->{conn}->{$server}) { | ||
| 375 | if ($self->{idle_timeout}) { | ||
| 376 | if ($self->{last_used}->{$server} > time - $self->{idle_timeout}) { | ||
| 377 | $r = $self->{conn}->{$server}; | ||
| 378 | } | ||
| 379 | } | ||
| 380 | else { | ||
| 381 | $r = $self->{conn}->{$server}; | ||
| 382 | } | ||
| 383 | } | ||
| 384 | |||
| 385 | # otherwise create a new connection | ||
| 386 | if (not defined $r) { | ||
| 387 | my ($host, $port) = split /:/, $server; | ||
| 388 | print "attempting new connection to $server\n" if $self->{debug}; | ||
| 389 | $r = AnyEvent::Redis->new( | ||
| 390 | host => $host, | ||
| 391 | port => $port, | ||
| 392 | on_error => sub { | ||
| 393 | warn @_ unless $self->{quiet}; | ||
| 394 | $self->markServerDown($server); | ||
| 395 | $self->{cv}->end; | ||
| 396 | } | ||
| 397 | ); | ||
| 398 | |||
| 399 | $self->{conn}->{$server} = $r; | ||
| 400 | } | ||
| 401 | |||
| 402 | if (not defined $self->{cv}) { | ||
| 403 | $self->{cv} = AnyEvent->condvar; | ||
| 404 | } | ||
| 405 | |||
| 406 | $self->{cv}->begin; | ||
| 407 | $self->{request_serial}++; | ||
| 408 | my $rid = $self->{request_serial}; | ||
| 409 | $self->{request_state}->{$rid} = 1; # open request; 0 is cancelled | ||
| 410 | print "scheduling request $rid: $_[0]\n" if $self->{debug}; | ||
| 411 | |||
| 412 | if ($call eq 'multi' or $call eq 'exec') { | ||
| 413 | @$args = (); # these don't really take args | ||
| 414 | } | ||
| 415 | |||
| 416 | $r->$call(@$args, sub { | ||
| 417 | if (not $self->{request_state}->{$rid}) { | ||
| 418 | print "call found request $rid cancelled\n" if $self->{debug}; | ||
| 419 | delete $self->{request_state}->{$rid}; | ||
| 420 | $self->markServerDown($server); | ||
| 421 | $cb->(undef); | ||
| 422 | return; | ||
| 423 | } | ||
| 424 | $self->{cv}->end; | ||
| 425 | $self->markServerUp($server); | ||
| 426 | $self->{last_used}->{$server} = time; | ||
| 427 | print "callback completed for request $rid\n" if $self->{debug}; | ||
| 428 | delete $self->{request_state}->{$rid}; | ||
| 429 | $cb->(shift); | ||
| 430 | }); | ||
| 431 | return $self; | ||
| 432 | } | ||
| 433 | |||
| 434 | =head1 NAME | ||
| 435 | |||
| 436 | AnyEvent::Redis::Federated - Full-featured Async Perl Redis client | ||
| 437 | |||
| 438 | =head1 SYNOPSIS | ||
| 439 | |||
| 440 | use AnyEvent::Redis::Federated; | ||
| 441 | |||
| 442 | my $r = AnyEvent::Redis::Federated->new(%opts); | ||
| 443 | |||
| 444 | # batch up requests and explicity wait for completion | ||
| 445 | $redis->set("foo$_", "bar$_") for 1..20; | ||
| 446 | $redis->poll; | ||
| 447 | |||
| 448 | # send a request with a callback | ||
| 449 | $redis->get("foo1", sub { | ||
| 450 | my $val = shift; | ||
| 451 | print "cb got: $val\n"; # should print "cb got: 1" | ||
| 452 | }); | ||
| 453 | $redis->poll; | ||
| 454 | |||
| 455 | =head1 DESCRIPTION | ||
| 456 | |||
| 457 | This is a wrapper around AnyEvent::Redis which adds timeouts, | ||
| 458 | connection retries, multi-machine cluster configuration (including | ||
| 459 | consistent hashing), node groups, and other magic bits. | ||
| 460 | |||
| 461 | =head2 HASHING AND SCALING | ||
| 462 | |||
| 463 | Keys are run through a consistent hashing algorithm to map them to | ||
| 464 | "nodes" which ultimately map to instances defined by back-end | ||
| 465 | host:port entries. For example, the C<redis_1> node may map to the | ||
| 466 | host and port C<redis1.example.com:63791>, but that'll all be | ||
| 467 | transparent to the user. | ||
| 468 | |||
| 469 | However, there are features in Redis that are handy if you know a | ||
| 470 | given set of keys lives on a single insance (a wildcard fetch like | ||
| 471 | C<KEYS gmail*>, for example). To facilitate that, you can specify a | ||
| 472 | "key group" that will be hashed insead of hashing the key. | ||
| 473 | |||
| 474 | For example: | ||
| 475 | |||
| 476 | key group: gmail | ||
| 477 | key : foo@gmail.com | ||
| 478 | |||
| 479 | key group: gmail | ||
| 480 | key : bar@gmail.com | ||
| 481 | |||
| 482 | Put another way, the key group defaults to the key for the named | ||
| 483 | operation, but if specified, is used instead as the input to the | ||
| 484 | consistent hashing function. | ||
| 485 | |||
| 486 | Using the same key group means that multiple keys end up on the same | ||
| 487 | Redis instance. To do so, simply change any key in a call to an | ||
| 488 | arrayref where item 0 is the key group and item 1 is the key. | ||
| 489 | |||
| 490 | $r->set(['gmail', 'foo@gmail.com'], 'spammer', $cb); | ||
| 491 | $r->set(['gmail', 'bar@gmail.com'], 'spammer', $cb); | ||
| 492 | |||
| 493 | Anytime a key is an arrayref, AnyEvent::Redis::Federated will assume | ||
| 494 | you're using a key group. | ||
| 495 | |||
| 496 | =head2 PERSISTENT CONNECTIONS | ||
| 497 | |||
| 498 | By default, AnyEvent::Redis::Federated will use a new connection for | ||
| 499 | each command. You can enable persistent connections by passing a | ||
| 500 | C<persistent> agrument (with a true value) in C<new()>. You will | ||
| 501 | likely also want to set a C<idle_timeout> value as well. The | ||
| 502 | idle_timeout defaults to 0 (which means no timeout). But if set to a | ||
| 503 | posistive value, that's the number of seconds that a connection is | ||
| 504 | allowed to remain idle before it is re-established. A number up to 60 | ||
| 505 | seconds is probably reasonable. | ||
| 506 | |||
| 507 | =head2 SHARED CONNECTIONS | ||
| 508 | |||
| 509 | Because creating AnyEvent::Redis::Federated objects isn't cheap (due | ||
| 510 | mainly to initializing the consistent hashing ring), there is a | ||
| 511 | mechanism for sharing a connection object among modules without prior | ||
| 512 | knowledge of each other. If you specify a C<tag> in the C<new()> | ||
| 513 | constructor and another module in the same process tries to create an | ||
| 514 | object with the same tag, it will get a reference to the one you | ||
| 515 | created. | ||
| 516 | |||
| 517 | For example, in your code: | ||
| 518 | |||
| 519 | my $redis = AnyEvent::Redis::Federated->new(tag => 'rate-limiter'); | ||
| 520 | |||
| 521 | Then in another module: | ||
| 522 | |||
| 523 | my $r = AnyEvent::Redis::Federated->new(tag => 'rate-limiter'); | ||
| 524 | |||
| 525 | Both C<$redis> and C<$r> will be references to the same object. | ||
| 526 | |||
| 527 | Since the first module to create an object with a given tag gets to | ||
| 528 | define the various retry parameters (as described in the next section), | ||
| 529 | it's worth thinking about whether or not you really want this behavior. | ||
| 530 | In many cases, you may--but not in all cases. | ||
| 531 | |||
| 532 | Tag names are used as a hash key internally and compared using Perl's | ||
| 533 | normal stringification mechanism, so you could use a full-blown object | ||
| 534 | as your tag if you wanted to do such a thing. | ||
| 535 | |||
| 536 | =head2 CONNECTION RETRIES | ||
| 537 | |||
| 538 | If a connection to a server goes down, AnyEvent::Redis::Federated will | ||
| 539 | notice and retry on subsequent calls. If the server remains down after | ||
| 540 | a configured number of tries, it will go into back-off mode, retrying | ||
| 541 | occasionally and increasing the time between retries until the server | ||
| 542 | is back on-line or the retry interval time has reached the maximum | ||
| 543 | configured vaue. | ||
| 544 | |||
| 545 | The module has some hopefully sane defaults built in, but you can | ||
| 546 | override any or all of them in your code when creating an | ||
| 547 | AnyEvent::Redis::Federated object. The following keys contol this | ||
| 548 | behvaior (defaults listed in parens for each): | ||
| 549 | |||
| 550 | * max_host_retries (3) is the number of times a server will be | ||
| 551 | re-tried before starting the back-off logic | ||
| 552 | |||
| 553 | * base_retry_interval (10) is the number of seconds between retries | ||
| 554 | when entering back-off mode | ||
| 555 | |||
| 556 | * retry_interval_mult (2) is the number we'll multiply | ||
| 557 | base_retry_interval by on each subsequent failure in back-off | ||
| 558 | mode | ||
| 559 | |||
| 560 | * max_retry_interval (600) is the number of seconds that the retry | ||
| 561 | interval will not exceed | ||
| 562 | |||
| 563 | When a server first goes down, this module will C<warn()> a message | ||
| 564 | that says "redis server $server seems down\n" where $server is the | ||
| 565 | $host:$port pair that represents the connection to the server. If | ||
| 566 | this is the first time that server has been seen down, it will | ||
| 567 | additionally C<warn()> "redis server $server down, first time\n". | ||
| 568 | |||
| 569 | If a server remainds down on subsequent retries beyond | ||
| 570 | max_host_retries, the module will C<warn()> "redis server $server | ||
| 571 | still down, backing off" to let you know that the back-off logic is | ||
| 572 | about to kick in. Each time the retry_interval is increased, it will | ||
| 573 | C<warn()> "redis server $server retry_interval now $retry_interval". | ||
| 574 | |||
| 575 | If a down server does come back up, the module will C<warn()> "redis | ||
| 576 | server $server back up (down since $down_since)\n" where $down_since | ||
| 577 | is human readable timestamp. It will also clear all internal state | ||
| 578 | about the down server. | ||
| 579 | |||
| 580 | =head2 TIMEOUTS | ||
| 581 | |||
| 582 | This module provides support for command timeouts. | ||
| 583 | |||
| 584 | The command timeout controls how long we're willing to wait for a | ||
| 585 | response to a given request made to a Redis server. Redis usually | ||
| 586 | responds VERY quickly to most requests. But if there's a temporary | ||
| 587 | network problem or something tying up the server, you may wish to fail | ||
| 588 | quickly and move on. | ||
| 589 | |||
| 590 | NOTE: these timeouts are implemented using C<alarm()>, so be careful | ||
| 591 | of also using C<alarm()> calls in your own code that could interfere. | ||
| 592 | |||
| 593 | =head2 MULTI-KEY OPERATIONS | ||
| 594 | |||
| 595 | Some operations can operate on many keys and might cross server | ||
| 596 | boundries. They are currently supported provided that you remember to | ||
| 597 | specify a hash key to ensure the all live on the same node. Example | ||
| 598 | operations are: | ||
| 599 | |||
| 600 | * mget | ||
| 601 | * sinter | ||
| 602 | * sinterstore | ||
| 603 | * sdiff | ||
| 604 | * sdiffstore | ||
| 605 | * zunionstore | ||
| 606 | |||
| 607 | Previous versions of this module listed these as unsupported commands, | ||
| 608 | but that's rather limiting. So they're supported now, provided you | ||
| 609 | know what you're doing. | ||
| 610 | |||
| 611 | =head2 METHODS | ||
| 612 | |||
| 613 | AnyEvent::Redis::Federated inherits all of the normal Redis methods. | ||
| 614 | However, you can supply a callback or AnyEvent condvar as the final | ||
| 615 | argument and it'll do the right thing: | ||
| 616 | |||
| 617 | $redis->get("foo", sub { print shift,"\n"; }); | ||
| 618 | |||
| 619 | You can also use call chaining: | ||
| 620 | |||
| 621 | $redis->set("foo", 1)->set("bar", 2)->get("foo", sub { | ||
| 622 | my $val = shift; | ||
| 623 | print "foo: $val\n"; | ||
| 624 | }); | ||
| 625 | |||
| 626 | =head2 CONFIGURATION | ||
| 627 | |||
| 628 | AnyEvent::Redis::Federated requires a configuration hash be passed | ||
| 629 | to it at instantiation time. The constructor will die() unless a | ||
| 630 | unless a 'config' option is passed to it. The configuration structure | ||
| 631 | looks like: | ||
| 632 | |||
| 633 | my $config = { | ||
| 634 | nodes => { | ||
| 635 | redis_1 => { address => 'db1:63790' }, | ||
| 636 | redis_2 => { address => 'db1:63791' }, | ||
| 637 | redis_3 => { address => 'db2:63790' }, | ||
| 638 | redis_4 => { address => 'db2:63791' }, | ||
| 639 | }, | ||
| 640 | }; | ||
| 641 | |||
| 642 | The "nodes" and "master_of" hashes are described below. | ||
| 643 | |||
| 644 | =head3 NODES | ||
| 645 | |||
| 646 | The "nodes" configuation maps an arbitrary node name to a host:port | ||
| 647 | pair. (The hostname can be replaced with an IP address.) | ||
| 648 | |||
| 649 | Node names (redis_N in the example above) are VERY important since | ||
| 650 | they are the keys used to build the consistent hashing ring. It's | ||
| 651 | generally the wrong idea to change a node name. Since node names are | ||
| 652 | mapped to a host:port pair, we can move a node from one host to | ||
| 653 | another without rehashing a bunch of keys. | ||
| 654 | |||
| 655 | There is unlikely to be a need to remove a node. | ||
| 656 | |||
| 657 | Adding nodes to a cluster is currently not well-supported, but is an | ||
| 658 | area of active development. | ||
| 659 | |||
| 660 | =head2 EVENT LOOP | ||
| 661 | |||
| 662 | Since this module wraps AnyEvent::Redis, there are two main ways you | ||
| 663 | can integrate it into your code. First, if you're using AnyEvent, it | ||
| 664 | should "just work." However, if you're not otherwise using AnyEvent, | ||
| 665 | you can still take advantage of batching up requests and waiting for | ||
| 666 | them in parallel by calling the C<poll()> method as illustrated in the | ||
| 667 | synopsis. | ||
| 668 | |||
| 669 | Calling C<poll()> asks the module to issue any pending requests and | ||
| 670 | wait for all of them to return before returning control back to your | ||
| 671 | code. | ||
| 672 | |||
| 673 | =head2 EXPORT | ||
| 674 | |||
| 675 | None. | ||
| 676 | |||
| 677 | =head2 SEE ALSO | ||
| 678 | |||
| 679 | The normal AnyEvent::Redis perl client C<perldoc AnyEvent::Redis>. | ||
| 680 | |||
| 681 | The Redis API documentation: | ||
| 682 | |||
| 683 | http://redis.io/commands | ||
| 684 | |||
| 685 | Jeremy Zawodny's blog describing craigslist's use of redis sharding: | ||
| 686 | |||
| 687 | http://blog.zawodny.com/2011/02/26/redis-sharding-at-craigslist/ | ||
| 688 | |||
| 689 | That posting described an implementation which was based on the | ||
| 690 | regular (non-async) Redis client from CPAN. This code is a port of | ||
| 691 | that to AnyEvent. | ||
| 692 | |||
| 693 | =head2 BUGS | ||
| 694 | |||
| 695 | Please report bugs as issues on github: | ||
| 696 | |||
| 697 | https://github.com/craigslist/perl-AnyEvent-Redis-Federated/issues | ||
| 698 | |||
| 699 | =head1 AUTHOR | ||
| 700 | |||
| 701 | Jeremy Zawodny, E<lt>jzawodn@craigslist.orgE<gt> | ||
| 702 | |||
| 703 | Joshua Thayer, E<lt>joshua@craigslist.orgE<gt> | ||
| 704 | |||
| 705 | Tyle Phelps, E<lt>tyler@craigslist.orgE<gt> | ||
| 706 | |||
| 707 | =head1 COPYRIGHT AND LICENSE | ||
| 708 | |||
| 709 | Copyright (C) 2009-2011 by craigslist. | ||
| 710 | |||
| 711 | This library is free software; you can redistribute it and/or modify | ||
| 712 | it under the same terms as Perl itself, either Perl version 5.10.0 or, | ||
| 713 | at your option, any later version of Perl 5 you may have available. | ||
| 714 | |||
| 715 | =cut | ||
| 716 | |||
| 717 | 1; | ||
| 718 | |||
| 719 | __END__ |