-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathmain.py
160 lines (113 loc) · 4.35 KB
/
main.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
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
"""
Copyright (c) 2021
This file, main.py, is part of Project Alice.
Project Alice is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
authors: Psycho <https://github.com/Psychokiller1888>
philipp2310 <https://github.com/philipp2310>
retired or
inactive authors: Jierka <https://github.com/jr-k>
maxbachmann <https://github.com/maxbachmann>
Last modified: 2021.04.13 at 12:56:49 CEST
"""
import os
import subprocess
subprocess.run(['clear'])
try:
from pathlib import Path
import json
conf = json.loads(Path('debug_server.json').read_text())
if not conf['enable']:
raise Exception
import pydevd_pycharm
pydevd_pycharm.settrace(conf['server'], port=conf['port'], stdoutToServer=conf['stdout'], stderrToServer=conf['stderr'])
except:
# Do nothing, this is only for debug server, advanced stuff
pass
import logging.handlers
from datetime import datetime
from core.util.model import FileFormatting, BashFormatting
_logger = logging.getLogger('ProjectAlice')
_logger.setLevel(logging.INFO)
date = int(datetime.now().strftime('%Y%m%d'))
logsMountpoint = Path(Path(__file__).resolve().parent, 'var', 'logs')
logFileHandler = logging.FileHandler(filename=f'{logsMountpoint}/logs.log', mode='w')
rotatingHandler = logging.handlers.RotatingFileHandler(filename=f'{logsMountpoint}/{date}-logs.log', mode='a', maxBytes=100000, backupCount=20)
streamHandler = logging.StreamHandler()
logFileFormatter = FileFormatting.Formatter()
bashFormatter = BashFormatting.Formatter()
logFileHandler.setFormatter(logFileFormatter)
rotatingHandler.setFormatter(logFileFormatter)
streamHandler.setFormatter(bashFormatter)
_logger.addHandler(logFileHandler)
_logger.addHandler(rotatingHandler)
_logger.addHandler(streamHandler)
from core.Initializer import Initializer
Initializer().initProjectAlice()
import signal
import sys
import time
import traceback
# This needs access to non native python packages, cannot init before the initializer is done
from core.util.model import HtmlFormatting
from core.util.model.MqttLoggingHandler import MqttLoggingHandler
htmlFormatter = HtmlFormatting.Formatter()
mqttHandler = MqttLoggingHandler()
#mqttHandler.setFormatter(htmlFormatter)
_logger.addHandler(mqttHandler)
def exceptionListener(*exc_info): # NOSONAR
global _logger
_logger.error('[Project Alice] An unhandled exception occurred')
text = ''.join(traceback.format_exception(*exc_info))
_logger.error(f'- Traceback: {text}')
sys.excepthook = exceptionListener
from core.ProjectAlice import ProjectAlice
# noinspection PyUnusedLocal
def stopHandler(signum, frame):
global RUNNING
RUNNING = False
def restart():
global RUNNING
RUNNING = False
def restartProcess():
sys.stdout.flush()
try:
# Close everything related to ProjectAlice, allows restart without component failing
import psutil
# noinspection PyUnboundLocalVariable
process = psutil.Process(os.getpid())
for handler in process.open_files() + process.connections():
os.close(handler.fd)
except Exception as e:
print(f'[Project Alice] Failed restarting Project Alice: {e}')
python = sys.executable
os.execl(python, python, *sys.argv)
def main():
global RUNNING
RUNNING = True
signal.signal(signal.SIGINT, stopHandler)
signal.signal(signal.SIGTERM, stopHandler)
projectAlice = ProjectAlice(restartHandler=restart)
try:
while RUNNING:
time.sleep(0.1)
except KeyboardInterrupt:
_logger.info('[Project Alice] Interruption detected, preparing shutdown')
finally:
if projectAlice.isBooted:
projectAlice.onStop()
_logger.info('[Project Alice] Shutdown completed, see you soon!')
if projectAlice.restart:
time.sleep(3)
restartProcess()
RUNNING = False
if __name__ == '__main__':
main()