-
-
Save noahsw/9bc71582c59cfe224007 to your computer and use it in GitHub Desktop.
Rake task to list non-expired memcache keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace :memcached do | |
| desc "List valid keys that haven't expired" | |
| task list_valid_keys: [:environment] do | |
| # List all keys stored in memcache. | |
| # Credit to Graham King at http://www.darkcoding.net/software/memcached-list-all-keys/ for the original article on how to get the data from memcache in the first place. | |
| require 'net/telnet' | |
| # overload so we don't have to worry about unmarshaling | |
| module Marshal | |
| def self.load(value) | |
| value | |
| end | |
| end | |
| headings = %w(id expires bytes cache_key) | |
| rows = [] | |
| localhost = Net::Telnet::new("Host" => "localhost", "Port" => 11211, "Timeout" => 3) | |
| matches = localhost.cmd("String" => "stats items", "Match" => /^END/).scan(/STAT items:(\d+):number (\d+)/) | |
| slabs = matches.inject([]) { |items, item| items << Hash[*['id','items'].zip(item).flatten]; items } | |
| longest_key_len = 0 | |
| total_bytes = 0 | |
| slabs.each do |slab| | |
| localhost.cmd("String" => "stats cachedump #{slab['id']} #{slab['items']}", "Match" => /^END/) do |c| | |
| matches = c.scan(/^ITEM (.+?) \[(\d+) b; (\d+) s\]$/).each do |key_data| | |
| cache_key, bytes, expires_time = key_data | |
| expires_at = Time.at(expires_time.to_i) | |
| cache_key =~ /\S?:(.+)/ # trim app name from string | |
| rails_key = $1 | |
| next unless Rails.cache.exist?(rails_key) | |
| rows << [slab['id'], expires_at, bytes, cache_key] | |
| longest_key_len = [longest_key_len,cache_key.length].max | |
| total_bytes += bytes.to_i | |
| end | |
| end | |
| end | |
| row_format = %Q(|%8s | %28s | %12s | %-#{longest_key_len}s |) | |
| puts row_format%headings | |
| rows.each{|row| puts row_format%row} | |
| puts "Entries: #{rows.count}" | |
| puts "Total bytes: #{total_bytes}" | |
| localhost.close | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment