Skip to content

Instantly share code, notes, and snippets.

@lajunta
Created November 6, 2010 17:09
Show Gist options
  • Save lajunta/665538 to your computer and use it in GitHub Desktop.
Save lajunta/665538 to your computer and use it in GitHub Desktop.
auto backup mongo (ruby version and very concise)
#!/usr/local/ruby/bin/ruby -w
Dbpath = "/data/db" # database path
Backpath = "/data/dbbackup" # backup directory
Host = "" # mongo host to connect,empty is for local
Database = "" # database to use. empty is for all
Collection = "" # collection to use
User = ""
Passwd = ""
Now = Time.now
DATE = Now.strftime("%Y-%m-%d")
Dom = Now.mday # Day of month
Dow = Now.wday # Day of week
M = Now.month # Month of the year
W = Now.strftime("%W") # Week of the year
Doweekly = 6 # Saturday
Opt = "" #Options
if !Host.empty?
Opt = Opt << " --host #{Host}"
end
if !User.empty?
Opt = Opt << " --username #{User} --password #{Passwd}"
end
if !Database.empty?
Opt = Opt << " --db #{Database}"
end
if !Collection.empty?
Opt = Opt << " --collection #{Collection}"
end
def dbdump(bkpath)
`mongodump --out #{bkpath} #{Opt}`
end
#Create required directory
#first check backup directory exist?
if Dir[Backpath] == []
`mkdir -p #{Backpath}`
end
#check daily exist?
if Dir["#{Backpath}/daily"] == []
`mkdir -p '#{Backpath}/daily'`
end
#check weekly exist?
if Dir["#{Backpath}/weekly"] == []
`mkdir -p '#{Backpath}/weekly'`
end
#check monthly exist?
if Dir["#{Backpath}/monthly"] == []
`mkdir -p '#{Backpath}/monthly'`
end
#make monthly backup
if Dom=="1"
bkpath=Backpath+"/monthly/"+DATE+"."+M.to_s
puts "Monthly backup begin.."
dbdump bkpath
end
#make daily backup
if Dow==Doweekly
puts "Delete last week backup"
`rm -rf #{Backpath+"/weekly/*."+W.to_s+".*"}`
puts "Weekly backup begin.."
bkpath=Backpath+"/weekly/"+DATE+"."+W.to_s
dbdump bkpath
else
puts "Delete backup 7 days ago"
`rm -rf #{Backpath+"/daily/*."+Dow.to_s+".*"}`
bkpath=Backpath+"/daily/"+DATE+"."+Dow.to_s
puts "Daily backup begin..."
dbdump bkpath
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment