概述
数据库的备份非常非常非常重要!!!否则出问题连哭的机会有没有(欲哭无泪)今天主要是做一个mongodb的数据库备份。
1、关于备份
备份其实很简单,这里选择的是对mongodb中的某个库进行全备,例如saturn。关于备份策略,要根据实际情况来定,我们是一个小时备份一次。不废话直接上代码:
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
import time
from subprocess import call
go_time = time.strftime("%Y-%m-%d_%H")
dir_path = "/data/backup"
def db_backup(user,pwd,host,db):
call("mongodump -u {} -p {} -h {} -d {} --gzip --archive={}/saturn-{}.gz".format(user,pwd,host,db,dir_path,go_time))
if __name__ == '__main__':
db_backup("hqms","hqms123","127.0.0.1:27017","saturn")
备份的文件saturn_2018-01-17_23.gz
我把备份和删除旧文件分开了,why?写在一个里面不是很好吗,主要是两个任务的执行频率不一样,删除的任务执行频率比较低,每天执行一次既可以,否则会浪费系统资源。
并且过多的耦合总会出问题。下面贴出删除代码:
#!/usr/bin/env python
# -*-encoding: utf-8 -*-
import os
import time
cur_time = time.time()
#当天零点的时间戳
st = cur_time - cur_time%86400 + time.timezone
dir_path = "/data/backup"
#删除
def drop_file(file_dir):
for filename in os.listdir(file_dir):
if os.path.isfile(file_dir + "/" +filename):
ft = os.stat(file_dir + "/" +filename)
lt = int(ft.st_mtime)
nt = cur_time - 3600*2 #距离现在2个小时之前的时间戳
dt = st - 86400*5 #距离现在5天之前的时间戳
#delete file by hour in today
if st < lt < nt:
try:
os.remove(file_dir + "/" + filename)
time.sleep(3)
print "Deleted success" + file_dir + "/" + filename
except (SyntaxError,IOError) as error:
print error
#delete file by day
elif lt < dt:
try:
os.remove(file_dir + "/" + filename)
time.sleep(3)
print "Deleted success" + file_dir + "/" + filename
except (SyntaxError,IOError) as error:
print error
if __name__ == '__main__':
drop_file(dir_path)
说明删除的代码是python2.7版本的。
附:
python3.6版本:
#!/usr/bin/env python
import os
import time
cur_time = time.time()
#获取当天零点的时间戳
st = cur_time - cur_time%86400 + time.timezone
dir_path = "/data/backup"
#删除
def drop_file(file_dir):
for filename in os.listdir(file_dir):
if os.path.isfile(file_dir + "/" +filename):
ft = os.stat(file_dir + "/" +filename)
lt = int(ft.st_mtime)
nt = cur_time - 3600*2 #获取当天保留截止的时间戳
dt = st - 86400*5 #获取保留天数的时间戳
#delete file by hour in today
if st < lt < nt:
try:
os.remove(file_dir + "/" + filename)
time.sleep(3)
print ("Deleted success" + file_dir + "/" + filename)
except (SyntaxError,IOError) as e:
print (e)
#delete file by day
elif lt < dt:
try:
os.remove(file_dir + "/" + filename)
time.sleep(3)
print ("Deleted success" + file_dir + "/" + filename)
except (SyntaxError,IOError) as e:
print (e)
if __name__ == '__main__':
drop_file(dir_path)
2、关于策略
备份脚本是一个小时执行一次,删除脚本是每天执行一次。使用jenkins的pipeline执行,给出删除策略的pipeline:
1)create a pipeline task in jenkins
pipeline{
agent{ label 'db1'}
stages{
stage('drop old file'){
steps{
dir('/data/scripts'){
sh 'python rm_backup.py'
}
}
}
}
}
2)you must create a schedule
Build periodically
50 23 * * *