133 lines
3.9 KiB
Python
133 lines
3.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
from ops.mmysql import MysqlBase
|
|
from ops.mansible import AnsibleAPI
|
|
from ops.mlog import define_logger
|
|
import logging
|
|
import datetime
|
|
import os
|
|
import tarfile
|
|
import svn
|
|
import shutil
|
|
import pdb
|
|
define_logger("/data/logs/ops/deploy_keys.log")
|
|
log = logging.getLogger(__name__)
|
|
|
|
dbargs = dict()
|
|
dbargs['host'] = '10.10.3.5'
|
|
dbargs['user'] = 'ops'
|
|
dbargs['pswd'] = 'deploy2018'
|
|
dbargs['db'] = 'ywplatform'
|
|
|
|
|
|
class DeployKeys:
|
|
def __init__(self, project):
|
|
self.env='test'
|
|
self.project = project
|
|
self.svn_base = f"/data/publish/svn/{self.env}"
|
|
self.svn_paths = f"{self.svn_base}/{self.project}"
|
|
|
|
|
|
def run(self):
|
|
svn_path, ipadr = self.get_config()
|
|
if svn_path:
|
|
shutil.rmtree(svn_path)
|
|
else:
|
|
pass
|
|
os.system(f"mkdir -p {svn_path}")
|
|
key_path = f"{svn_path}/keys"
|
|
args = dict()
|
|
tar_file = self.build_svn_tar(key_path)
|
|
if tar_file:
|
|
hostfile = self.build_hostfile()
|
|
args['hostfile'] = hostfile
|
|
args['tar_file'] = tar_file
|
|
self.ansible_deploy(args)
|
|
else:
|
|
log.error(f"tar file no found with {self.project}")
|
|
|
|
|
|
def get_config(self):
|
|
sql = f"""SELECT
|
|
config_address,
|
|
run_server
|
|
FROM
|
|
`deploy_projectmanage`
|
|
WHERE
|
|
project_name="{self.project}"
|
|
and env='{self.env}'"""
|
|
|
|
mydb = MysqlBase(**dbargs)
|
|
data = mydb.query(sql)
|
|
ip_addr = list()
|
|
pdb.set_trace()
|
|
if data:
|
|
for line in data:
|
|
try:
|
|
svn_path = line[0]
|
|
ip_addr.append(line[1])
|
|
except Exception:
|
|
log.error(f"split {self.project} config failed", exc_info=True)
|
|
svn_path = None
|
|
|
|
return (svn_path, ip_addr)
|
|
|
|
|
|
def build_svn_tar(self, svn_path):
|
|
try:
|
|
log.info("svn export config start")
|
|
s = svn.remote.RemoteClient(svn_path)
|
|
s.export(self.svn_paths, force=True)
|
|
log.info("svn export config success")
|
|
except Exception:
|
|
log.error(f"get remote {self.project} svn failed", exc_info=True)
|
|
else:
|
|
log.info("tarfile {0} config to tar.gz start".format(self.project))
|
|
tar = tarfile.open(self.svn_paths + '.tar.gz', 'w:gz')
|
|
os.chdir(self.svn_paths)
|
|
for f in os.listdir(self.svn_paths):
|
|
tar.add(f)
|
|
tar.close()
|
|
|
|
# 判断是否有生成tar包
|
|
list_dir = os.listdir(self.svn_base)
|
|
tar_files = list()
|
|
for i in list_dir:
|
|
if i == "{0}.tar.gz".format(self.project) and os.path.isfile(os.path.join(self.basedir, i)):
|
|
tar_files.append(os.path.join(self.basedir, i))
|
|
if len(tar_files) == 1:
|
|
log.info("tarfile {0} config to tar.gz success".format(self.project))
|
|
return tar_files
|
|
else:
|
|
return None
|
|
|
|
|
|
def build_hostfile(self, ip_addr):
|
|
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
host_files = f"/tmp/host_{now}"
|
|
with open(host_files, 'w') as f:
|
|
for line in ip_addr:
|
|
f.writelines(line + '\n')
|
|
return host_files
|
|
|
|
def ansible_deploy(self, args):
|
|
an = AnsibleAPI(args['hostfile'])
|
|
data = {'dest_filename': 'x', 'source': 'x', 'project': 'x'}
|
|
resule = an.run_playbook('deploy_keys.yml', **data)
|
|
if not (resule['failed'] or resule['unreachable']):
|
|
log.info(f"deploy keys with {self.p} success!")
|
|
else:
|
|
log.error(f"{self.p} deploy keys failed,{resule}", exc_info=True)
|
|
|
|
|
|
def main():
|
|
import sys
|
|
project = sys.argv[1]
|
|
if not project:
|
|
raise Exception("PLS input project like loginserver_php!")
|
|
dk = DeployKeys(project)
|
|
dk.run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|