-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapplication.py
More file actions
349 lines (302 loc) · 9.18 KB
/
application.py
File metadata and controls
349 lines (302 loc) · 9.18 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import os
import subprocess
import sys
import logging
import time
from os.path import join, dirname
from flask import Flask, jsonify, request, send_file
from flask.logging import default_handler
from datafunctions.log.log import startLog, getLogFile, tailLogFile
SCRAPER_NAME = './run_scrapers.py'
SCRAPER_NAME_PS = SCRAPER_NAME[2:]
MODEL_NAME = './run_models.py'
MODEL_NAME_PS = MODEL_NAME[2:]
LDA17_NN_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/nearest_neighbors')
LDA17_M_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/model')
LDA17_ME_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/model.expElogbeta.npy')
LDA17_MI_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/model.id2word')
LDA17_MS_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/model.state')
LDA17_ID_PATH = join(dirname(__file__), 'datafunctions/model/models/lda17_files/id2word')
startLog(getLogFile(__file__))
APP_LOG = logging.getLogger(__name__)
APP_LOG.info('Creating app...')
application = Flask(__name__)
werkzeug_logger = logging.getLogger('werkzeug')
for handler in APP_LOG.handlers:
werkzeug_logger.addHandler(handler)
application.logger.addHandler(handler)
@application.route('/')
def index():
return '''
<html><head></head><body>
Health check: <a href="/health">/health</a>
<br>
Start scrapers: <a href="/start">/start</a>
<br>
Kill scrapers: <a href="/kill">/kill</a>
<br>
Start models: <a href="/start-models">/start-models</a>
<br>
Kill models: <a href="/kill-models">/kill-models</a>
<br>
Application logs: <a href="/logs?file=application.py&lines=50">/logs?file=application.py</a>
<br>
Scraper logs: <a href="/logs?file=run_scrapers.py&lines=100">/logs?file=run_scrapers.py</a>
<br>
Model logs: <a href="/logs?file=run_models.py&lines=100">/logs?file=run_models.py</a>
</body></html>
'''
@application.route('/logs', methods=['GET'])
def logs():
"""
Gets the last n lines of a given log
"""
APP_LOG.info(f'/logs called with args {request.args}')
logfile = request.args.get('file', None)
lines = request.args.get('lines', 1000)
if logfile is None:
return('''
<pre>
Parameters:
file: The file to get logs for
Required
Usually one of either application.py or run_scrapers.py
lines: Number of lines to get
Defaults to 1000
</pre>
''')
try:
res = tailLogFile(logfile, n_lines=lines)
return (f'<pre>{res}</pre>')
except Exception as e:
return(f'Exception {type(e)} getting logs: {e}')
@application.route('/health', methods=['GET'])
def health():
"""
Prints various health info about the machine.
"""
APP_LOG.info('/health called')
outputs = {}
outputs['scrapers running'] = check_running(SCRAPER_NAME)
outputs['models running'] = check_running(MODEL_NAME)
outputs['free'] = os.popen('free -h').read()
outputs['dstat'] = os.popen('dstat -cdlimnsty 1 0').read()
outputs['top'] = os.popen('top -bn1').read()
outputs['ps'] = os.popen('ps -Afly --forest').read()
APP_LOG.info(f'Health results: {outputs}')
r = ''
for key, val in outputs.items():
r += f'''
<hr />
<h4>{key}</h4>
<pre style="white-space: pre-wrap; overflow-wrap: break-word;">{val}</pre>
'''
return r
@application.route('/kill', methods=['GET', 'POST'])
def kill():
"""
Kills the web scrapers.
"""
initial_state = check_running(SCRAPER_NAME)
running = initial_state
try:
APP_LOG.info('/kill called')
tries = 0
max_tries = 5
while running and tries < max_tries:
APP_LOG.info(f'Scraper running, attempting to kill it (try {tries + 1} of {max_tries})')
r = os.system(
f'kill $(ps -Af | grep {SCRAPER_NAME_PS} | grep -v grep | grep -oP "^[a-zA-Z\s]+[0-9]+" | grep -oP "[0-9]+")'
)
APP_LOG.info(f'Kill call exited with code: {r}')
tries += 1
running = check_running(SCRAPER_NAME)
if running:
wait_time = 2
APP_LOG.info(f'Waiting {wait_time} seconds...')
time.sleep(wait_time)
except Exception as e:
APP_LOG.warn(f'Exception while killing scrapers: {e}')
APP_LOG.warn(e, exc_info=True)
return f'''
<html><body>
<h4>initially running</h4>
<pre>{initial_state}</pre>
<hr />
<h4>scrapers running</h4>
<pre>{running}</pre>
</html></body>
'''
@application.route('/start', methods=['GET', 'POST'])
def start():
"""
Starts the web scrapers.
"""
tries = 0
result = {
'running': False,
'tries': 0,
'message': 'Unknown failure.'
}
try:
APP_LOG.info('/start called')
max_tries = 5
while not check_running(SCRAPER_NAME) and tries < max_tries:
APP_LOG.info(f'Scraper not running, attempting to start it (try {tries + 1} of {max_tries})')
start_and_disown(SCRAPER_NAME)
wait_time = 0
APP_LOG.info(f'Waiting {wait_time} seconds...')
time.sleep(wait_time)
tries += 1
if check_running(SCRAPER_NAME):
APP_LOG.info(f'Scraper running.')
if tries == 0:
result = {
'running': True,
'tries': tries,
'message': f'{SCRAPER_NAME} already running.'
}
else:
result = {
'running': True,
'tries': tries,
'message': f'{SCRAPER_NAME} started after {tries} tries.'
}
else:
result = {
'running': False,
'tries': tries,
'message': f'Failed to start {SCRAPER_NAME} after {tries} tries.'
}
# APP_LOG.info(f'run_scrapers stdout: {p.stdout.read()}')
# APP_LOG.info(f'run_scrapers stderr: {p.stderr.read()}')
APP_LOG.info(f'result: {result}')
except Exception as e:
result = {
'running': False,
'tries': tries,
'message': f'Aborting after {type(e)} exception on try {tries}: {e}'
}
APP_LOG.warn(f'result: {result}')
APP_LOG.warn(e, exc_info=True)
return jsonify(result)
@application.route('/kill-models', methods=['GET', 'POST'])
def kill_models():
"""
Kills the topic models.
"""
initial_state = check_running(MODEL_NAME)
running = initial_state
try:
APP_LOG.info('/kill-models called')
tries = 0
max_tries = 5
while running and tries < max_tries:
APP_LOG.info(f'Models running, attempting to kill it (try {tries + 1} of {max_tries})')
r = os.system(
f'kill $(ps -Af | grep {MODEL_NAME_PS} | grep -v grep | grep -oP "^[a-zA-Z\s]+[0-9]+" | grep -oP "[0-9]+")'
)
APP_LOG.info(f'Kill call exited with code: {r}')
tries += 1
running = check_running(MODEL_NAME)
if running:
wait_time = 2
APP_LOG.info(f'Waiting {wait_time} seconds...')
time.sleep(wait_time)
except Exception as e:
APP_LOG.warn(f'Exception while killing models: {e}')
APP_LOG.warn(e, exc_info=True)
return f'''
<html><body>
<h4>initially running</h4>
<pre>{initial_state}</pre>
<hr />
<h4>models running</h4>
<pre>{running}</pre>
</html></body>
'''
@application.route('/start-models', methods=['GET', 'POST'])
def start_models():
"""
Starts the topic models.
"""
tries = 0
result = {
'running': False,
'tries': 0,
'message': 'Unknown failure.'
}
try:
APP_LOG.info('/start-models called')
max_tries = 5
while not check_running(MODEL_NAME) and tries < max_tries:
APP_LOG.info(f'Models not running, attempting to start it (try {tries + 1} of {max_tries})')
start_and_disown(MODEL_NAME)
wait_time = 0
APP_LOG.info(f'Waiting {wait_time} seconds...')
time.sleep(wait_time)
tries += 1
if check_running(MODEL_NAME):
APP_LOG.info(f'Models running.')
if tries == 0:
result = {
'running': True,
'tries': tries,
'message': f'{MODEL_NAME} already running.'
}
else:
result = {
'running': True,
'tries': tries,
'message': f'{MODEL_NAME} started after {tries} tries.'
}
else:
result = {
'running': False,
'tries': tries,
'message': f'Failed to start {MODEL_NAME} after {tries} tries.'
}
APP_LOG.info(f'result: {result}')
except Exception as e:
result = {
'running': False,
'tries': tries,
'message': f'Aborting after {type(e)} exception on try {tries}: {e}'
}
APP_LOG.warn(f'result: {result}')
APP_LOG.warn(e, exc_info=True)
return jsonify(result)
@application.route('/models/lda17-nn')
def models_lda17_nn():
'''
Returns the pickled NearestNeighbors model for the LDA17 model.
'''
# At some point, this should be replaced with an autogenerated route or a static route
return send_file(LDA17_NN_PATH)
@application.route('/models/lda17-m')
def models_lda17_m():
return send_file(LDA17_M_PATH)
@application.route('/models/lda17-m.expElogbeta.npy')
def models_lda17_me():
return send_file(LDA17_ME_PATH)
@application.route('/models/lda17-m.id2word')
def models_lda17_mi():
return send_file(LDA17_MI_PATH)
@application.route('/models/lda17-m.state')
def models_lda17_ms():
return send_file(LDA17_MS_PATH)
@application.route('/models/lda17-id')
def models_lda17_id():
return send_file(LDA17_ID_PATH)
def check_running(pname):
APP_LOG.info(f'check_running called, pname: {pname}')
result = os.system(f'ps -Af | grep -v grep | grep -v log | grep {pname}')
APP_LOG.info(f'exit code: {result}')
return result == 0
def start_and_disown(pname):
with open(os.devnull, 'r+b', 0) as DEVNULL:
subprocess.Popen(['nohup', sys.executable, pname],
stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, close_fds=True, preexec_fn=os.setpgrp)
if __name__ == '__main__':
APP_LOG.info('Starting Flask dev server...')
application.run()