三、配置Jenkins公共Python配置文件(3/3)
运行Jenkins任务前删除nbr/src/sql/TableCreate下TomcatStarted.db和DBRefreshed.db,一般是运行任务中途失败产生的。
1.1.1 更新配置文件脚本updateConfig.py
updateConfig.py脚本文件主要是更新配置文件,svn上的配置文件不一定符合当前服务器环境,符合当前服务器环境的一般放在D盘,所以需要将配置文件复制到Jenkins指定目录。
updateConfig.py脚本
# coding=utf-8
import os
# 引用自定义的模块
from bxUtility import printInfo
from bxUtility import cover
# 需要从jenkins的环境变量读取的参数:现jenkins任务名、现使用场
CURRENT_JenkinsTask = os.getenv("CURRENT_JenkinsTask")
CURRENT_Env = os.getenv("CURRENT_Env")
# 原先使用的配置文件
ORIGINAL_MiniProgramProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/miniProgram.properties'
ORIGINAL_EnvProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/env.properties'
ORIGINAL_DBProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/db.properties'
ORIGINAL_PublicAccountProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/PublicAccount.properties'
ORIGINAL_PublicAccountTemplateProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/PublicAccountTemplate.properties'
ORIGINAL_Log4jXml = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/log4j.xml'
# 对应场现使用的配置文件
CURRENT_MiniProgramProperties = 'D:/NbrConfigFile/miniProgram.properties'
CURRENT_EnvProperties = 'D:/NbrConfigFile/env.properties'
CURRENT_DBProperties = 'D:/NbrConfigFile/db.properties'
CURRENT_PublicAccountProperties = 'D:/NbrConfigFile/PublicAccount.properties'
CURRENT_PublicAccountTemplateProperties = 'D:/NbrConfigFile/PublicAccountTemplate.properties'
CURRENT_Log4jXml = 'D:/NbrConfigFile/log4j.xml'
try:
# 替换配置文件(整个文件替换)
print ('正在替换' + CURRENT_Env + '场配置文件...');
cover(CURRENT_MiniProgramProperties, ORIGINAL_MiniProgramProperties)
cover(CURRENT_EnvProperties, ORIGINAL_EnvProperties)
cover(CURRENT_DBProperties, ORIGINAL_DBProperties)
cover(CURRENT_PublicAccountProperties, ORIGINAL_PublicAccountProperties)
cover(CURRENT_PublicAccountTemplateProperties, ORIGINAL_PublicAccountTemplateProperties)
cover(CURRENT_Log4jXml, ORIGINAL_Log4jXml)
printInfo('替换' + CURRENT_Env + '场配置文件完毕。', 0)
except Exception as e:
printInfo('出现异常:' + str(e), 1)
else:
os._exit(0)
1.1.2 公共脚本common.py
common.py脚本文件主要是关闭tomcat、删除tomcat目录下nbr(项目名)文件和ROOT文件夹,通知“小王子”脚本工具刷新数据库,重启tomcat,判断tomcat是否启动成功,调用了工具工具脚本bxUtility.py,可以在“工具脚本bxUtility.py”文章查看详细内容。
公共脚本common.py
# coding=utf-8
import os
# 引用自定义的模块
from bxUtility import printInfo
from bxUtility import cover
# 需要从jenkins的环境变量读取的参数:现jenkins任务名、现使用场
CURRENT_JenkinsTask = os.getenv("CURRENT_JenkinsTask")
CURRENT_Env = os.getenv("CURRENT_Env")
# 原先使用的配置文件
ORIGINAL_MiniProgramProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/miniProgram.properties'
ORIGINAL_EnvProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/env.properties'
ORIGINAL_DBProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/db.properties'
ORIGINAL_PublicAccountProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/PublicAccount.properties'
ORIGINAL_PublicAccountTemplateProperties = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/PublicAccountTemplate.properties'
ORIGINAL_Log4jXml = 'D:/Jenkins/workspace/' + CURRENT_JenkinsTask + '/src/main/resources/log4j.xml'
# 对应场现使用的配置文件
CURRENT_MiniProgramProperties = 'D:/NbrConfigFile/miniProgram.properties'
CURRENT_EnvProperties = 'D:/NbrConfigFile/env.properties'
CURRENT_DBProperties = 'D:/NbrConfigFile/db.properties'
CURRENT_PublicAccountProperties = 'D:/NbrConfigFile/PublicAccount.properties'
CURRENT_PublicAccountTemplateProperties = 'D:/NbrConfigFile/PublicAccountTemplate.properties'
CURRENT_Log4jXml = 'D:/NbrConfigFile/log4j.xml'
try:
# 替换配置文件(整个文件替换)
print ('正在替换' + CURRENT_Env + '场配置文件...');
cover(CURRENT_MiniProgramProperties, ORIGINAL_MiniProgramProperties)
cover(CURRENT_EnvProperties, ORIGINAL_EnvProperties)
cover(CURRENT_DBProperties, ORIGINAL_DBProperties)
cover(CURRENT_PublicAccountProperties, ORIGINAL_PublicAccountProperties)
cover(CURRENT_PublicAccountTemplateProperties, ORIGINAL_PublicAccountTemplateProperties)
cover(CURRENT_Log4jXml, ORIGINAL_Log4jXml)
printInfo('替换' + CURRENT_Env + '场配置文件完毕。', 0)
except Exception as e:
printInfo('出现异常:' + str(e), 1)
else:
os._exit(0)
1.1.3 工具脚本bxUtility.py
bxUtility.py主要封装了一些公共函数,printInfo函数打印错误信息和错误码:
printInfo函数
def printInfo(msg, errorCode):
"""
退出程序(当且仅当错误码不为0时)并打印错误码
:param msg:提示信息
:param errorCode:错误码
:return:
"""
print (msg + '错误码=' + str(errorCode));
sys.stdout.flush()
if errorCode != 0:
print('~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx')
os._exit(errorCode)
replace函数将指定文件file的某一段字符串替换成新的字符串,判断是否替换成功
def replace(file, old_str, new_str, encodingFormat, expectedReplaceCount):
"""
替换文件中的字符串
:param file:文件名
:param old_str:旧字符串
:param new_str:新字符串
:param encodingFormat:所修改文件的编码格式
:return:
"""
file_data = ""
replaceLineCount = 0
try:
with open(file, "r", encoding=encodingFormat) as f:
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
replaceLineCount += 1
file_data += line
if replaceLineCount != expectedReplaceCount:
printInfo(file + '中要被替换的字符串(' + old_str + ')意外地出现在了多处地方,将引发不可预知的问题。', 1);
with open(file, "w", encoding=encodingFormat) as f:
f.write(file_data)
except Exception as e:
printInfo('替换' + file + '中的字符串时出现异常:' + str(e), 1)
else:
printInfo('修改' + file + '成功。', 0)
cover函数用指定文件替换目标文件
def cover(current_file, original_file):
"""
:param current_file:对应场现使用的微信(公众号)配置文件
:param original_file:原先使用的微信(公众号)配置文件
"""
try:
shutil.copy(current_file, original_file)
except Exception as e:
printInfo('替换' + original_file + '时出现异常:' + str(e), 1)
else:
printInfo('替换' + original_file + '成功。', 0)
closeTomcat函数关闭tomcat
def closeTomcat(timeout):
"""
:param timeout:关闭Tomcat时的最大等待时间
"""
try:
print ('正在关闭Tomcat...');
if os.system('start D:/tomcat/bin/shutdown.bat') == 0:
waitingTime = 0
while waitingTime <= timeout: # 等待时长,单位为s(秒)
time.sleep(2) # 每隔10秒检查一次
handler = FindWindow(None, 'Tomcat')
if handler > 0:
if waitingTime >= timeout:
printInfo(str(timeout) + '秒内Tomcat未关闭,将终止python程序的运行~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx', 3)
else:
waitingTime += 2
else:
printInfo('Tomcat窗口已关闭。', 0)
break
else:
printInfo('关闭Tomcat失败。', 2)
except Exception as e:
printInfo('关闭Tomcat时出现异常:' + str(e), 1)
startTomcat函数负责通过文件通信通知”小王子”启动tomcat。向StartTomcat.db文件写入”Starting Tomcat...”通知”小王子”启动tomcat,“小王子”读取文件收到命令后,开始启动tomcat,并删除StartTomcat.db。”小王子”启动tomcat后创建TomcatStarted.db通知py脚本文件启动成功。py脚本隔一段时间访问项目首页,访问成功后删除TomcatStarted.db文件,访问失败则终止py脚本运行。
startTomcat函数
def startTomcat(timeout, url, CURRENT_SrcDirOfTableCreate):
"""
:param timeout:启动Tomcat时的最大等待时间
:param url:启动Tomcat时进行访问验证的网址
:param CURRENT_SrcDirOfTableCreate:当前使用的TableCreate源代码文件夹目录(v1.0 or v1.1)
"""
try:
print ('启动Tomcat中...');
with open(CURRENT_SrcDirOfTableCreate + '/StartTomcat.db', "a+", encoding='utf-8') as file:
file.write('Starting Tomcat...')
print ('正在等待小王子Jenkins版成功启动Tomcat...');
time.sleep(60) # 一般来说,Tomcat启动需要至少90秒,小王子内部会先等待90秒,然后创建TomcatStarted.db
waitingTime = 100
while waitingTime <= timeout: # 等待时长,单位为s(秒)
responseStatus = urllib.request.urlopen(url).code
if responseStatus == 200: # 判断访问网址时获取的状态码
if os.path.exists(CURRENT_SrcDirOfTableCreate + '/TomcatStarted.db'):
os.remove(CURRENT_SrcDirOfTableCreate + '/TomcatStarted.db')
printInfo('访问' + url + '成功,删除TomcatStarted.db成功,重启tomcat成功。', 0)
break
else:
printInfo('访问网址成功但是' + CURRENT_SrcDirOfTableCreate + '不存在TomcatStarted.db文件,将终止python程序的运行~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx', 3)
else:
if waitingTime >= timeout:
printInfo(str(timeout) + '秒内Tomcat未成功启动,将终止python程序的运行~~~~~~xxxxxxxx~~~~~~xxxxxxxx~~~~~~xxxxxxxx', 2)
else:
time.sleep(5) # 如果不想等待太长的间隔时间,可以设置此值为更短的时间(秒数),如10
waitingTime += 5
except Exception as e:
printInfo('启动Tomcat时出现异常:' + str(e), 1)
refreshDB函数通知”小王子”刷新数据库。创建RefreshDB.db文件写入“通知小王子Jenkins版刷新DB...”,“小王子”读取到文件内容后开始刷新数据库,刷新成功后创建DBRefreshed.db文件通知py脚本。py脚本知道后删除DBRefreshed.db文件。
refreshDB函数
def refreshDB(timeout, CURRENT_SrcDirOfTableCreate):
"""
:param timeout:刷新DB时的最大等待时间
:param CURRENT_SrcDirOfTableCreate:当前使用的TableCreate源代码文件夹目录(v1.0 or v1.1)
"""
try:
print ('通知小王子Jenkins版刷新DB...');
with open(CURRENT_SrcDirOfTableCreate + '/RefreshDB.db', "a+", encoding='utf-8') as file:
file.write('通知小王子Jenkins版刷新DB...')
print('正在等待小王子Jenkins版成功刷新DB...');
num = 0;
while num <= timeout: #等待2分钟
if os.path.exists(CURRENT_SrcDirOfTableCreate + '/DBRefreshed.db'):
os.remove(CURRENT_SrcDirOfTableCreate + '/DBRefreshed.db')
printInfo('删除DBRefreshed.db成功。', 0)
break
else:
time.sleep(3)
num += 3;
if num > timeout:
printInfo('小王子刷新DB超时', 3)
printInfo('小王子刷新DB成功。', 0)
except Exception as e:
printInfo('小王子刷新DB时出现异常:' + str(e), 1)
replaceLine函数替换目标文件file存在关键字keyword的行:
def replaceLine(file, keyword, newLine, encodingFormat, expectedReplaceCount):
"""
替换存在关键字的某一行
:param file:文件名
:param keyword:关键字
:param newLine:新的一行
:param encodingFormat:所修改文件的编码格式
:param expectedReplaceCount:期待的替换次数
:return:
"""
replaceLineCount = 0
try:
with open(file, 'r', encoding=encodingFormat) as fr:
lines = fr.readlines()
with open(file, "w", encoding=encodingFormat) as f:
for line in lines:
if keyword in line:
f.write(newLine)
replaceLineCount += 1
else:
f.write(line)
if replaceLineCount != expectedReplaceCount:
printInfo(file + '中要被替换的' + keyword + '所在行的替换次数为' + str(replaceLineCount) + ',不等于期待次数,将引发不可预知的问题。', 1);
except Exception as e:
printInfo('替换' + file + '中存在关键字"' + keyword + '"的一行时出现异常:' + str(e), 1)
else:
printInfo('替换' + file + '中存在关键字"' + keyword + '"的一行成功。', 0)

浙公网安备 33010602011771号