-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanager.py
More file actions
138 lines (107 loc) · 3.67 KB
/
manager.py
File metadata and controls
138 lines (107 loc) · 3.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
'''
Script to manage flask servers (start/stop/restart)
NOTE: Script is currently designed to assume this file exists
in same directory as python module it wil start.
Example use:
python manager.py myApi start --port 55557 --extra "test"
'''
import argparse
import os
import subprocess
import psutil
import getpass
def is_server_running(server, port=None, report=False):
'''
Returns PID if server is currently running (on same port), else 0
'''
matches = []
current_user = getpass.getuser()
list1 = ['python', server]
if port: list1.append(port)
for proc in psutil.process_iter():
pinfo = proc.as_dict(attrs=['name', 'username', 'pid', 'cmdline'])
# if pinfo['username'] != current_user:
# continue
found = 0
for name in list1:
for cmd in pinfo['cmdline']:
if name in cmd:
found += 1
if found >= len(list1):
matches.append(pinfo)
if len(matches) == 0:
if report: print("WARN: NO MATCHING PROCESSES FOUND")
return 0
elif len(matches) > 1:
if report: print ("WARN: MULTIPLE MATCHES: \n" + str(matches))
return matches[0]['pid']
else:
if report: print ("FOUND PROCESS: " + str(matches[0]))
return matches[0]['pid']
def process_stop(pid):
'''
Use psutil to kill the process ID
'''
if pid == 0:
print(server, 'is not running')
else:
print('Killing PID', pid)
p = psutil.Process(pid)
p.terminate()
pid = 0
return pid
def process_start(pid, server, port=None, extra=None):
'''
Start the requested server
'''
if pid > 0:
print(server, 'already running with PID', pid)
else:
cmd = ['/usr/local/anaconda3-5.0.0.1/bin/python', server]
if extra:
cmd.append(extra)
if port:
cmd.append('--port')
cmd.append(port)
print(f'Starting "{server}" with the cmd:' + str(cmd))
try:
p = subprocess.Popen(cmd)
except Exception as e:
print ('Error running command: ' + str(e))
print ('Done')
#===================================== MAiN ===================================
# Define input parameters
parser = argparse.ArgumentParser(description='manager.py input parameters')
parser.add_argument('server', type=str, help='flask server module name')
parser.add_argument('command', type=str, help='start, stop, restart, check')
parser.add_argument("--port", type=str, dest="port", default=None,
help="Port to use for finding existing process and --port option to forward to app.")
parser.add_argument("--extra", type=str, dest="extra", default=None,
help="Extra arguemnts string to pass to app")
# Get input parameters
args = parser.parse_args()
server = args.server
command = args.command
port = args.port
extra = args.extra
# Verify command
assert command in ['start', 'stop', 'restart', 'check'], 'Incorrect command'
# get this script directory (assuming flask module exists here)
dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir)
# Check if server file exists
server = f'{dir}/{server}.py'
assert os.path.isfile(server), print(f'server module {server} does not exist')
# Check if server is running
pid = is_server_running(server, port)
# Do the request
if command == 'stop':
pid = process_stop(pid)
elif command == 'start':
process_start(pid, server, port=port, extra=extra)
elif command == 'restart':
pid = process_stop(pid)
process_start(pid, server, port=port, extra=extra)
elif command == 'check':
pid = is_server_running(server, port, report=True)
exit()