script/memcached

The inimitable Wincent recently referred to a memcached script he had written that toggled whether memcached is running or not. I thought that was a great idea so wrote my own and in the spirit of comparing dicks I thought I’d post it here.

#!/usr/bin/env ruby
 
 = ::File.expand_path(::File.dirname(__FILE__)) + '/../tmp/memcached.pid'
 
def process_id
  File.exist?() ? File.read().to_i : false
end
 
def running?
  if process_id 
    Process.kill(0, process_id) == 1 rescue false
  else
    false
  end
end
 
def start!
  print 'starting memcached ...'
  system "memcached -d -P #{} -l 127.0.0.1"
  sleep 0.5
  print "started with pid #{File.read}"
end
 
def stop!
  print 'stopping memcached ...'
  Process.kill('INT', process_id)
  sleep 0.5
  File.delete() if File.exist?()
  print 'done.'
  puts
end
 
def ensure_running
  running? ? puts('already running.') : start!
end
 
def ensure_stopped
  !running? ? puts('not running.') : stop!
end
 
def toggle
  running? ? stop! : start!
end
 
case ARGV.first
when 'start'
  ensure_running
when 'stop'
  ensure_stopped
when 'toggle'
  toggle
when 'status'
  running? ? puts('running') : puts('not running')
else
  toggle
end

I love writing these kinds of scripts in Ruby. It’s perfect for it.

Tags: ,

3 Responses to “script/memcached”

  1. Wincent Colaiuta Says:

    Let us compare, then. Here’s the script I mentioned:

    #!/usr/bin/env ruby
    require 'pathname'
     
    # memcached requires an absolute path for the -P switch
    root = (Pathname.new(__FILE__).dirname + '..').realpath
    pidfile = root + 'tmp' + 'memcached.pid'
     
    if not pidfile.exist?
      puts "memcached not running: starting"
      system 'memcached', '-d', '-P', pidfile, '-l', '127.0.0.1'
    else
      puts "memcached running: stopping"
      pid = pidfile.read.chomp
      system 'kill', pid
     
      # it appears that memcached doesn't clean up its pid file
      # unless you send it a QUIT signal (TERM, KILL, HUP don't)
      # unfortuantely, QUIT on Mac OS X causes memcached to crash
      pidfile.delete
    end

    Mine doesn’t have “start”, “stop” and “toggle” actions like yours does; its default action is to toggle.

    As for “status”, I actually have a script/status script that shows me a summary like:

    nginx: running
    memcached: running
    mysqld: running
  2. Sho Says:

    Thanks for the interesting counter-example. That’s certainly a lot cleaner than my bloated efforts. Cool, and instructive, use of pathname.

    I’m a little more paranoid in my checks there since I have been burnt a few times by assuming the existence of a pidfile means the process is actually running; perhaps as I see it run reliably a little more I’ll be more trusting.

  3. Wincent Colaiuta Says:

    Yes, know what you mean about paranoid. Evidently on the production environment I wouldn’t use such a naïve little script, but I use Monit instead.

Leave a Reply