Skip to content

Instantly share code, notes, and snippets.

@lajunta
Created October 23, 2013 06:54
Show Gist options
  • Save lajunta/7113740 to your computer and use it in GitHub Desktop.
Save lajunta/7113740 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#PATH=/bin:/usr/local/bin:/sbin:/usr/bin:/usr/sbin
Dbpath = "/data/mongodb" # database path
Backpath = "/backup/db" # 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
puts "Delete backup 7 days ago"
# `rm -rf #{Backpath+"/daily/*."+Dow.to_s+".*"}`
# bkpath=Backpath+"/daily/"+DATE+"."+Dow.to_s
`rm -rf #{Backpath+"/daily/"+Dow.to_s}`
bkpath=Backpath+"/daily/"+Dow.to_s
puts "Daily backup begin..."
dbdump bkpath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment