etcd 备份
- config.yml
days: 7
dir: /data
ca: /etc/kubernetes/ssl/ca.pem
cert: /etc/kubernetes/ssl/etcd.pem
key: /etc/kubernetes/ssl/etcd-key.pem
endpoints: https://192.168.1.1:2379
cron:
day_of_week: 3
hour: 2
minute: 30
main.py
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import os
import yaml
from apscheduler.schedulers.background import BlockingScheduler
from loguru import logger
def callEtcdctl(days, dir, ca, cert, key, endpoints):
"""
etcd备份
"""
now_day = datetime.now().strftime("%Y-%m-%d")
day_ago = datetime.today() - timedelta(days)
day_ago = day_ago.strftime("%Y-%m-%d")
file_prefix = os.path.join(dir, "snapshot.db")
print(file_prefix)
day_ago_file = file_prefix + "." + day_ago
now_day_file = file_prefix + "." + now_day
if not os.path.exists(dir):
os.makedirs(dir)
command = "export ETCDCTL_API=3;/usr/local/bin/etcdctl " + ' --cacert=' + ca + ' --cert=' + cert + ' --key=' + key + \
' --endpoints=' + '"' + endpoints + '"' \
' snapshot save ' + now_day_file
logger.info(command)
try:
os.system(command)
except Exception as e:
logger.error(e)
logger.error("备份失败!!!")
#清理 days 天前文件
if os.path.exists(day_ago_file):
os.remove(day_ago_file)
else:
logger.warning('no such file:%s' % day_ago_file) # 则返回文件不存在
def main():
basedir = os.path.dirname(os.path.abspath(__file__))
yaml_conf_file = basedir + '/config.yml'
yaml_conf = yaml.load(open(yaml_conf_file, encoding='utf-8'), Loader=yaml.FullLoader, )
day_of_week = yaml_conf["cron"]["day_of_week"]
hour = yaml_conf["cron"]["hour"]
minute = yaml_conf["cron"]["minute"]
print(day_of_week,hour,minute)
days = yaml_conf["days"]
dir = yaml_conf["dir"]
ca = yaml_conf["ca"]
key = yaml_conf["key"]
cert = yaml_conf["cert"]
endpoints = yaml_conf["endpoints"]
args_dict = {
"days": days,
"dir": dir,
"ca": ca,
"cert": cert,
"key": key,
"endpoints": endpoints
}
exit(1)
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
scheduler.add_job(callEtcdctl, 'cron', day_of_week=day_of_week, hour=hour,minute=minute, kwargs=args_dict)
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
scheduler.start() # 采用的是阻塞的方式,只有一个线程专职做调度的任务
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
if __name__ == '__main__':
main()

浙公网安备 33010602011771号