95 lines
3.0 KiB
Python
95 lines
3.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
import requests
|
|
import logging
|
|
from ops.mansible import AnsibleAPI
|
|
from ops.mmysql import MysqlBase
|
|
import time
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
class Build_Gamelog_Config():
|
|
def __init__(self):
|
|
self.url = "https://mp.kingsome.cn/api/open/games/keys"
|
|
self.filename = "/tmp/gamelog.appkey.php"
|
|
self.dest_file = "/data/apps/gamelog_php/config/gamelog.appkey.php"
|
|
self.dest_paths = "/data/apps/gamelog_php/config/"
|
|
self.project = "gamelog_php"
|
|
|
|
def get_keys(self):
|
|
r = requests.get(self.url)
|
|
if r.status_code == requests.codes.ok:
|
|
return r.json()
|
|
else:
|
|
return None
|
|
|
|
def split_data(self, data):
|
|
out = []
|
|
if data:
|
|
try:
|
|
for line in data['gameList']:
|
|
out.append(line)
|
|
except Exception:
|
|
log.error(f"split {data} failed", exc_info=True)
|
|
return out
|
|
|
|
def build_config(self, data):
|
|
start = "<?php"
|
|
end = ");"
|
|
content = ""
|
|
if data:
|
|
for line in data:
|
|
try:
|
|
content += f"""return array(
|
|
"{line['game_id']}" => array(
|
|
'gamename' => '{line['game_name']}',
|
|
'appkey' => '{line['app_key']}',
|
|
)"""
|
|
except Exception:
|
|
log.error(f"build context failed with {line}.", exc_info=True)
|
|
with open(self.filename, 'w') as f:
|
|
f.write(f"{start}+'\n'+{content}+'\n'+{end}")
|
|
|
|
def deploy_config(self):
|
|
ip_addr = self.get_ip_addr()
|
|
hostfile = self.write_host(ip_addr)
|
|
an = AnsibleAPI(hostfile)
|
|
data = {'dest_paths': self.dest_paths, 'source': self.filename, 'dest_filename': self.dest_file}
|
|
resule = an.run_playbook('/data/git/dev_ops/ansible/playbook/publish_file2server.yml', **data)
|
|
if not (resule['failed'] or resule['unreachable']):
|
|
log.info(f"deploy success!")
|
|
return True
|
|
else:
|
|
log.error(f"deploy failed info={resule}")
|
|
return False
|
|
|
|
|
|
def get_ip_addr(self):
|
|
ip_addr = list()
|
|
sql = f"SELECT run_server FROM `deploy_projectmanage` WHERE project_name='{self.project}' AND env='prod'"
|
|
args = dict()
|
|
args['host'] = '10.10.3.5'
|
|
args['user'] = 'deploy'
|
|
args['pswd'] = 'deploy2016'
|
|
args['db'] = 'ywplatform'
|
|
mdb = MysqlBase(**args)
|
|
data = mdb.query(sql)
|
|
if data:
|
|
for line in data[0]:
|
|
ip_addr.append(line)
|
|
return ip_addr
|
|
|
|
def write_host(self, ip_addr):
|
|
host_file = "%s/host%s" % ('/tmp', time.strftime("%Y%m%d%H%M%s"))
|
|
with open(host_file, 'a+') as f:
|
|
for x in ip_addr:
|
|
f.writelines(x + '\n')
|
|
return host_file
|
|
|
|
|
|
def run(self):
|
|
keys = self.get_keys()
|
|
data = self.split_data(keys)
|
|
self.build_config(data)
|
|
self.deploy_config()
|