-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.py
85 lines (66 loc) · 2.98 KB
/
application.py
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
import logging
import os
from datetime import timedelta, datetime
import docker
import sentry_sdk
from dateutil.parser import parse
from flask import session
from flask_socketio import SocketIO, join_room
from sentry_sdk import capture_exception
from sentry_sdk.integrations.flask import FlaskIntegration
from timeloop import Timeloop
from core import storage
from core.services.job import CONTAINER_NAME_PREFIX
from core.telegram.client import send_daily_stats
from core.web import create_app
from helpers import time_diff_in_seconds
JOB_EXECUTION_TIME_LIMIT_SECONDS = 30 * 60 # 30 minutes
sentry_sdk.init(
dsn=os.getenv('SENTRY_DSN'),
integrations=[FlaskIntegration()]
)
# The name of this variable (as well as this file) is important for Beanstalk
application = create_app()
# Initialized cached file storage
storage.init()
# Disable information logs from socketio, including PING/PONG logs
logging.getLogger('socketio').setLevel(logging.ERROR)
logging.getLogger('engineio').setLevel(logging.ERROR)
socketio = SocketIO(application, async_mode='threading', engineio_logger=True)
tl = Timeloop()
@tl.job(interval=timedelta(minutes=5))
def kill_containers_over_time_limit():
try:
docker_client = docker.from_env()
for container in docker_client.containers.list(filters={'status': 'running'}):
if not container.name.startswith(CONTAINER_NAME_PREFIX):
continue # We only looking for containers that execute Jobs
container_start_time = parse(container.attrs['State']['StartedAt'])
running_time_seconds = time_diff_in_seconds(container_start_time.replace(tzinfo=None),
datetime.utcnow().replace(tzinfo=None))
if running_time_seconds > JOB_EXECUTION_TIME_LIMIT_SECONDS:
logging.info(f"Shutting down container {container.name} "
f"because it's running for {running_time_seconds} seconds")
container.kill()
except Exception as e:
# We don't want the periodic task to shut down if some of its executions had an Exception
logging.error(e)
capture_exception(e)
@tl.job(interval=timedelta(minutes=30))
def send_daily_stats_to_telegram():
if os.getenv('STAGE', 'local') == 'prod':
try:
if datetime.utcnow().hour == 13: # every day at 13:00 UTC
send_daily_stats()
except Exception as e:
# We don't want the periodic task to shut down if some of its executions had an Exception
logging.error(e)
capture_exception(e)
tl.start()
@socketio.on('connect', namespace='/socket')
def connected():
"""https://stackoverflow.com/questions/39423646/flask-socketio-emit-to-specific-user"""
logging.info(f"{session['profile']['email']} connected to the socket")
join_room(session['profile']['internal_user_id'])
if __name__ == '__main__':
socketio.run(application, host='0.0.0.0', port=os.environ.get('PORT', 5000))