一、 期望完成功能
# todo 1 压缩对象类型检查 [100%]
# todo 2 压缩方法编写 [100%]
# todo 3 存放目录检查及默认值设定 [100%]
# todo 4 定时压缩开关设置及前端页面接口完善
# todo 5 定时压缩 crontab 后端设置
# todo 6 周期执行前端设置及后端程序编写
# todo 7 压缩进度条展示及计算方式
# todo 8 目标主机执行命令的方式 [100%]
# todo 9 src dest排除特殊目录 [100%]
# todo 10 mysql connect timeout
# todo 11 基于 Ansible 调用远程主机命令 [100%]
# todo 12 Ansible 公共调用API实现 [100%]
# todo 13 支持.*正则表达式及文件目录判断 [100%]
二、界面设计
三、逻辑架构
《XTOOLS【运维平台】之文件OR目录压缩.png》
逻辑
用户输入压缩对象:文件或目录或带.*的正则表达式
输入目标主机的ip或hostname
检查目标主机磁盘容量
检查目标压缩目录是否为/var、/usr、/等特殊目录
点击开始压缩
成功或失败后给用户反馈
四、部分代码逻辑分享
4.1 压缩对象目录或文件判断
难点:
用户输入类型判断,可能存在的类型:
文件
目录
正则表达式
错误输入(未做判断)
歧义输入(目录未带/结尾被识别为文件)
伪代码逻辑分享
# 用户输入逻辑初次处理,做去除空格处理
src_path = form_data['srcpath'].strip()
# 用户输入处理及格式转换
def srctype_check(src_path, dest_path, dest_name, compresstype):
src_dirname = os.path.dirname(src_path)
src_basename = os.path.basename(src_path)
dest_dirname = os.path.dirname(dest_path)
files = glob.glob(src_path)
# 特殊目录不能做压缩
exclude_path = [
'/',
'/usr',
'/boot',
'/cgroup',
'/sys',
# '/tmp', # test
]
for i in exclude_path:
if src_dirname == i or dest_dirname == i:
result = {'error': "above path is not allowed"}
return result
# 判断目标目录是否存在, 如果不存在强制创建
isExists = os.path.exists(dest_dirname)
if not isExists:
os.makedirs(dest_dirname)
# 判断对象是否存在 因为涉及正则表达式,所以没有使用os.path.isdir
if len(files) == 0:
result = {'error': 'File or Directory Not Exist! PLZ Check'}
return result
# 压缩包名称检测及检查
pg_name = 'tmp' + '.' + compresstype
result = {}
if os.path.isdir(src_path):
srctype = 'd'
pg_name = src_dirname.split('/')[-1] + '.' + compresstype if dest_name == '' else dest_name
if compresstype == 'tgz':
tar_compress(src_path, dest_path, pg_name)
if compresstype == 'zip':
zip_compress(src_path, dest_path, pg_name)
else:
pg_name = src_basename + '.' + compresstype if dest_name == '' else dest_name
srctype = 'f'
# 如果len(files)>1表示用户输入的是正则表达式
if len(files) > 1:
tar_compress_one_by_one(src_path, dest_path, pg_name)
else:
tar_compress(src_path, dest_path, pg_name)
result['pg_name'] = pg_name
result['dest_path'] = dest_dirname + '/'
result['compresstype'] = compresstype
result['srctype'] = srctype
return result
sult
心得:
任何一款产品都是妥协和抗争不断对抗的最后半成品
如果你在用了一款很多看不见但能感觉到的细节的产品,这款产品付出的努力一定很多
4.2 存放目录判断
难点:
目录未加/结尾
输入的目录不存在
伪代码逻辑分享:
# 默认不输入的话使用/tmp/目录
tmp_dir = '/tmp/'
# 处理用户输入去掉/,然后手动拼接/
dest_path = tmp_dir if form_data['destpath'].strip().rstrip('/') == '' else form_data['destpath'].strip().rstrip('/') + '/'
心得:
用户输入不可预测的异常,对于写代码的人实在太痛苦了,处理这个未知的时候我想了很多,后来发现strip & rstrip 能比较轻松达成要求。