Script to dump memcached data

2013/07/17

Perl script to dump all the keys/values that memcached presents over its API (not totally guaranteed to be *all* the keys/values, but good enough for debugging). I used it to dump all the SimpleSAMLPHP sessions this server was storing to debug a session expiration issue.

#!/usr/bin/perl

use 5.10.0;

use Cache::Memcached;
use Data::Dumper;
use MIME::Base64;

use strict;

my $server = "localhost:11211";

my $memcached = new Cache::Memcached {
  'servers' => [ $server ],
  'debug' => 0
};

my @items = split(/\r\n/, $memcached->stats("items")->{hosts}->{$server}->{items});
my %buckets = ();
foreach my $bucket (@items) {
  $bucket =~ s/^.*:(.*):.*$/$1/ig;
  $buckets{$bucket} = 1;
}

foreach my $bucket (sort keys %buckets) {
  my @lines = split(/\r\n/, $memcached->stats("cachedump $bucket 0")->{hosts}->{$server}->{"cachedump $bucket 0"});
  foreach my $ticket (@lines) {
    $ticket =~ /^ITEM (?<item>.*) \[(?<bytes>\d+) b; (?<expire>\d+) s\]$/ig;
    printf("%s: %s bytes: expires %s (%s)\n%s\n", $+{item}, $+{bytes}, $+{expire}, scalar(gmtime($+{expire})), encode_base64($memcached->get($+{item})));
  }
}

$memcached->disconnect_all;

Comments