Created
June 18, 2015 10:26
-
-
Save yumu19/ca12a362b3811c2d8b1c to your computer and use it in GitHub Desktop.
ruby script to backup(export) docker container
This file contains 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
require 'clockwork' | |
include Clockwork | |
module Clockwork | |
@@rootDir = "/Users/yumu/dockerBackupDir/" | |
@@hourlyFormat = "%Y%m%d_%H%M" | |
@@dailyFormat = "%Y%m%d" | |
def getContainerNames | |
ps = `docker ps`.split("\n") | |
ps.delete_at(0) | |
names = Array.new | |
ps.each do |l| | |
names.push(l.split(/ /,0).last) | |
end | |
return names | |
end | |
def hourly | |
t = Time.now | |
yesterday = t - 60 * 60 * 24 | |
Dir.mkdir(@@rootDir) if !File.exist?(@@rootDir) | |
getContainerNames.each do |name| | |
dirPath = File.join(@@rootDir,name) | |
Dir.mkdir(dirPath) if !File.exist?(dirPath) | |
hourlyFile = t.strftime(@@hourlyFormat)+".tar" | |
hourlyFilePath = File.join(dirPath,hourlyFile) | |
dailyFile = t.strftime(@@dailyFormat)+".tar" | |
dailyFilePath = File.join(dirPath,dailyFile) | |
`docker export #{name} > #{hourlyFilePath}` | |
`cp #{hourlyFilePath} #{dailyFilePath}` | |
Dir::glob("#{dirPath}/????????_????.tar").each {|f| | |
fDateStr = f.match(%r{#{dirPath}/(.+?).tar})[1] | |
fDate = Time.strptime(fDateStr, @@hourlyFormat) | |
File.delete(f) if fDate < yesterday | |
} | |
end | |
end | |
def daily | |
today = Date.today | |
lastweek = today - 7 | |
getContainerNames.each do |name| | |
p name | |
dirPath = File.join(@@rootDir,name) | |
dailyFile = today.strftime(@@dailyFormat)+".tar" | |
dailyFilePath = File.join(dirPath,dailyFile) | |
Dir::glob("#{dirPath}/????????.tar").each {|f| | |
fDateStr = f.match(%r{#{dirPath}/(.+?).tar})[1] | |
fDate = Time.strptime(fDateStr, @@dailyFormat) | |
File.delete(f) if ((fDate < lastweek) && (fDate.day != 1)) | |
} | |
end | |
end | |
handler do |job| | |
self.send(job.to_sym) | |
end | |
every(1.hour, 'hourly') | |
every(1.day, 'daily') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment