Skip to content

Instantly share code, notes, and snippets.

@riethmayer
Created January 20, 2010 01:00
Show Gist options
  • Save riethmayer/281486 to your computer and use it in GitHub Desktop.
Save riethmayer/281486 to your computer and use it in GitHub Desktop.
Mongodb startup script
#!/usr/bin/env ruby -w
# mongo ;; 2010 (cc) Jan Riethmayer
# This work is licensend under a Creative Commons Attribution 3.0 license.
require 'optparse'
options = {}
optparse = OptionParser.new do|opts|
opts.banner = <<-BANNER
Usage: sudo ./mongo [options]
BANNER
options[:dbpath] = "/data/mongodb/"
opts.on( '-d', '--dbpath', 'Select DB path. Defaults to /data/mongodb/' ) do |path|
options[:dbpath] = path
end
options[:port] = "27017"
opts.on( '-p', '--port PORT', 'Listening to port 27017 by default' ) do |port|
options[:port] = port
end
options[:fork] = false
opts.on( '-f', '--fork', 'Run as daemon' ) do
options[:fork] = true
end
options[:logpath] = "/var/log/mongodb.log"
opts.on( '-l', '--logfile FILE', 'Defaults to /var/log/mongodb.log' ) do |file|
options[:logpath] = file
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
# Parse the command-line. Remember there are two forms
# of the parse method. The 'parse' method simply parses
# ARGV, while the 'parse!' method parses ARGV and removes
# any options found there, as well as any parameters for
# the options.
optparse.parse!
class Go
attr_accessor :opts
def initialize(opts)
@opts = opts
end
def start
puts "Starting on port #{@opts[:port]} with dbpath #{@opts[:dbpath]}"
puts "Running as Daemon" if @opts[:fork]
puts "Writing to logpath /var/log/mongodb.log"
path = "--dbpath #{@opts[:dbpath]}"
port = "--port #{@opts[:port]}"
log = "--logpath #{@opts[:logpath]} --logappend"
fork = "#{@opts[:fork] ? '--fork' : ''}"
params = [path, port, log, fork].join(" ")
result = %x{ ./mongodb/bin/mongod #{ params } }
puts result
end
def stop
process = %x{ ps -o pid,command ax | grep mongod }
found = false
matcher = process.scan(/(\d+).+?bin.+?mongod.+?--fork/) do |pid|
found = true
puts "Killing process #{pid}"
%x{ kill -2 #{pid} }
end
puts "No mongod process found" unless found
end
end
go = Go.new(options)
case ARGV[0]
when /start/ : go.start
when /stop/ : go.stop
else
raise ArgumentError.new("mongo (start|stop) or mongo -h for help.")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment