为什么要写这个脚本
写脚本的目的是帮我们减少重复的工作;至于使用CI/CD工具,只能说各有各的便利之处。脚本简单明了。
此脚本应用场景
比如你有一个朋友是软件开发,又需要自己频繁上线springboot应用程序测试,那这个频繁上线的工作就可以交给这个脚本来实现啦
实现思路
使用python,把频繁上线应用这个重复操作,写成脚本。
比如:启动springboot,查询springboot进程id,杀掉进程id,启动新上线的springboot,这一流水线操作
python 获取进程id
这里使用 subprocess 模块,详细说明 subprocess — 子进程管理, 文档是中文的可以看懂
def getAppPid(app):
'''获取app的进程id
Args:
app: app name
'''
pid = None
getAppPidCmdStr = 'ps -ef |grep %s|grep -v \'grep\|%s\'' % (app, os.path.basename(__file__))
log.info("~$ %s", getAppPidCmdStr)
getAppPidCmdReturn = subprocess.Popen(getAppPidCmdStr, shell=True, stdout=subprocess.PIPE).stdout.read().splitlines()
if len(getAppPidCmdReturn) > 0:
log.info(repr(getAppPidCmdReturn[0]))
pid = getAppPidCmdReturn[0].split()[1]
if pid:
return pid.decode('utf-8')
else:
return pid
启动spring boot应用
根据获取的pid决定是否启动,启动完再查一遍pid确认是否启动成功。
def runApp(app):
linux, windows = getSecriptRunPlatform()
if windows:
# appStartCmdStr = 'java -cp application.jar com.example.App'
appStartCmdStr = 'java -jar %s' % app
subprocess.run(appStartCmdStr.split(' '))
elif linux:
pid = getAppPid(app)
if pid is not None:
log.info("App already running. pid:%s", pid)
appInfo_ = getAppInfo()
appInfo_['pid'] = pid
setAppInfo(appInfo_)
sys.exit()
# appStartCmdStr = 'java -cp application.jar com.example.App > ./log/app.log 2>&1 &'
# appStartCmdStr = 'nohup java -cp %s com.example.App > ./log/app.log 2>&1 &' % app
appStartCmdStr = 'nohup java -jar %s > /dev/null 2>&1 &' % app
log.info("~$ %s", appStartCmdStr)
subprocess.Popen(appStartCmdStr, shell=True).wait(3)
pid = getAppPid(app)
if pid:
log.info("App run successful, pid:%s", pid)
appInfo_ = getAppInfo()
appInfo_['app'] = app
appInfo_['pid'] = pid
setAppInfo(appInfo_)
else:
log.info("App run failed!")
停止spring boot应用
也是根据查询到的pid,直接kill掉对应的进程
def _stop(app):
linux, windows = getSecriptRunPlatform()
if windows:
log.info("windows app sotp not support.")
sys.exit()
appInfo = getAppInfo()
if app:
pid = getAppPid(app)
elif not appInfo['app'] == "":
pid = getAppPid(appInfo['app'])
else:
log.info("App not found.")
sys.exit()
if pid is not None:
if linux:
stopCommand = 'kill %s' % pid
log.info("~$ %s", stopCommand)
subprocess.Popen(stopCommand, shell=True).wait(3)
log.info("App stoped")
appInfo['pid'] = APP_NOT_RUN
setAppInfo(appInfo)
else:
log.info("App already stoped.")