1 Star 3 Fork 2

zoutao98/python manage services script

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
services.py 7.01 KB
一键复制 编辑 原始数据 按行查看 历史
zoutao98 提交于 2022-11-21 03:56 . update services.py.
# The MIT License (MIT)
# Copyright © 2022 <copyright 邹涛>
import os
import sys
import logging
import argparse
import platform
import json
import pathlib
import traceback
import subprocess
# try:
# config_source = pathlib.Path("config.json")
# document = json.loads(config_source.read_text())
# print(document)
# finally:
# pass
# java -cp application.jar com.example.App
# nohub java -jar application.jar > /dev/numm 2>&1 &
# appStartCmd = ['java', '-cp', 'application.jar', 'com.example.App']
# 创建日志记录器
log = logging.getLogger("SAS")
log.setLevel(logging.DEBUG)
LOG_FORMAT = "%(asctime)s :" + logging.BASIC_FORMAT
# 创建log目录
# if not os.path.exists('./log/services.log'):
# os.mkdir('./log')
# 添加日志文件输出
# file_handler = logging.FileHandler('./log/services.log', 'a', encoding='utf-8')
# file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
# log.addHandler(file_handler)
# 添加日志控制台输出
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
log.addHandler(console_handler)
# app信息文件
appServicesFile = 'application.json'
# 常量
APP_NOT_RUN = 'NOT_RUN'
def getSecriptRunPlatform():
"""获取脚本运行平台"""
script_run_system = platform.system()
linux = None
windows = None
if script_run_system == 'Windows':
windows = True
elif script_run_system == 'Linux':
linux = True
return linux, windows
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
def getAppInfo():
"""获取App信息
"""
try:
appInfo = json.loads(pathlib.Path(appServicesFile).read_text())
return appInfo
except Exception as e:
log.error("%s", traceback.format_exc(limit=1))
log.error('File to load services info file.')
# 默认app信息
defaultAppServicesInfo = {"app": "", "pid": APP_NOT_RUN}
runInfoJsonStr = json.dumps(defaultAppServicesInfo, indent=4)
with open(appServicesFile, 'w') as f:
f.write(runInfoJsonStr)
log.info("Write default app services infomation to file=%s.", appServicesFile)
return defaultAppServicesInfo
def setAppInfo(appInfo):
with open(appServicesFile, 'w') as f:
f.write(json.dumps(appInfo, indent=4))
log.info("Save app run services infomation to file=%s.", appServicesFile)
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!")
def _start(app):
appInfo = getAppInfo()
if appInfo['app'] == "":
if not app:
log.error("First time run app, please input app name")
sys.exit()
appInfo['app'] = app
setAppInfo(appInfo)
runApp(app)
elif (app) and (appInfo['app'] == app):
runApp(app)
elif not app:
runApp(appInfo['app'])
elif (app) and (appInfo['app'] != app):
log.info("Run a new app, stop old app next step")
linux, windows = getSecriptRunPlatform()
if linux:
_stop(appInfo['app'])
runApp(app)
elif windows:
log.info("windows app sotp not support, so direce run app.")
runApp(app)
def _stop(app):
linux, windows = getSecriptRunPlatform()
if windows:
log.info("windows app sotp not support.")
sys.exit()
appInfo = getAppInfo()
count = 0
while True:
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:
count = count + 1
if count > 20:
stopCommand = 'kill -9 %s' % pid
else:
stopCommand = 'kill %s' % pid
log.info("~$ %s", stopCommand)
subprocess.Popen(stopCommand, shell=True).wait(3)
else:
log.info("App stoped")
appInfo['pid'] = APP_NOT_RUN
setAppInfo(appInfo)
break
def _status(app):
log.info("\n%s", json.dumps(getAppInfo(), indent=4))
def _restart(app):
log.info("restart app")
_stop(app)
_start(app)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Spring boot App services manage script.")
# parser.add_argument('-g', '--gary', action='store_true')
parser.add_argument('operation', nargs='?', help="App start, stop, restart or status",
choices=['start', 'stop', 'restart', 'status'], metavar='operation')
parser.add_argument(
'app', nargs='?', help="Spring boot app jar", metavar='app.jar')
parser.add_argument('appCmd', nargs='?',
help="Application optional command", metavar='"-xxx"')
parser.add_argument('--version', action='version', version='SAS 0.0.1')
args = parser.parse_args()
operation = args.operation
if not operation:
parser.print_help()
parser.exit()
if operation == 'start':
_start(args.app)
elif operation == 'stop':
_stop(args.app)
elif operation == 'restart':
_restart(args.app)
elif operation == 'status':
_status(args.app)
log.info("Services script finish")
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/zoutao98/services-script.git
[email protected]:zoutao98/services-script.git
zoutao98
services-script
python manage services script
main

搜索帮助