-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
326 lines (276 loc) · 13.8 KB
/
main.py
File metadata and controls
326 lines (276 loc) · 13.8 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
import os
import sys
import time
import shutil
import signal
import threading
import subprocess
import configparser
from git import Repo
from git.exc import GitCommandError
class ScriptMonitor:
def __init__(self, config_file="config.ini"):
self.config = self._load_config(config_file)
self._validate_config()
# Настройки репозитория
self.repo_url = self.config["Repository"]["url"]
self.branch = self.config.get("Repository", "branch", fallback="main")
self.script_path = self.config["Repository"]["script_path"]
self.token = self.config.get("Repository", "token")
# Настройки монитора
self.local_path = os.path.abspath(
self.config.get("Repository", "local_path", fallback="repo")
)
self.check_interval = self.config.getint(
"Monitor", "check_interval", fallback=60
)
self.max_restarts = self.config.getint("Monitor", "max_restarts", fallback=0)
# Внутренние переменные
self.process = None
self.current_commit = None
self.restart_count = 0
self.input_thread = None
self._normalize_repo_url()
# Обеспечиваем корректное завершение
signal.signal(signal.SIGINT, self._handle_signal)
signal.signal(signal.SIGTERM, self._handle_signal)
def _load_config(self, config_file):
"""Загрузка конфигурации"""
config = configparser.ConfigParser()
if not os.path.exists(config_file):
self._create_default_config(config_file)
print(
f"Создан файл конфигурации {config_file}. Настройте его и перезапустите."
)
sys.exit(1)
config.read(config_file)
return config
def _create_default_config(self, config_file):
"""Создание конфига по умолчанию"""
config = configparser.ConfigParser()
config["Repository"] = {
"url": "https://github.com/username/private-repo.git",
"script_path": "script/main.py",
"branch": "main",
"token": "your_github_token",
"local_path": "repo",
}
config["Monitor"] = {"check_interval": "60", "max_restarts": "0"}
with open(config_file, "w") as f:
config.write(f)
def _validate_config(self):
"""Проверка обязательных параметров"""
required = ["url", "script_path"]
for param in required:
if param not in self.config["Repository"]:
raise ValueError(f"Не указан обязательный параметр: {param}")
def _normalize_repo_url(self):
"""Нормализация URL с аутентификацией"""
if not self.token:
return
if "https://" in self.repo_url:
self.repo_url = self.repo_url.replace("https://", f"https://{self.token}@")
elif "git@" not in self.repo_url:
raise ValueError("Неподдерживаемый формат URL репозитория")
def _prepare_repo_dir(self):
"""Подготовка директории репозитория"""
# Always create directory if not exists
os.makedirs(self.local_path, exist_ok=True)
def _check_for_updates(self, repo):
"""Проверка наличия обновлений в удаленном репозитории"""
origin = repo.remotes.origin
origin.fetch()
local_commit = repo.head.commit.hexsha
remote_commit = repo.refs[f"origin/{self.branch}"].commit.hexsha
return local_commit != remote_commit
def _clone_repo(self):
"""Клонирование репозитория"""
print("Клонирование репозитория...")
try:
repo = Repo.clone_from(
self.repo_url, self.local_path, branch=self.branch, depth=1
)
except GitCommandError as e:
if "already exists and is not an empty directory" in str(e):
print("Обнаружены существующие файлы, используем их как рабочую директорию")
repo = Repo.init(self.local_path)
try:
origin = repo.create_remote('origin', self.repo_url)
except GitCommandError as e:
if "remote origin already exists" in str(e):
origin = repo.remote('origin')
else:
raise e
origin.fetch()
repo.git.checkout(f'origin/{self.branch}', force=True)
else:
raise e
self.current_commit = repo.head.commit.hexsha
return True
def _ensure_repo(self):
"""Обеспечение наличия актуального репозитория"""
try:
self._prepare_repo_dir()
return self._clone_repo()
except GitCommandError as e:
print(f"Ошибка Git: {e.stderr.strip()}")
if "Authentication failed" in str(e):
print("Ошибка аутентификации. Проверьте токен доступа.")
raise
def _get_script_full_path(self):
"""Получение полного пути к скрипту"""
path = os.path.join(self.local_path, self.script_path)
if not os.path.exists(path):
raise FileNotFoundError(f"Скрипт не найден: {path}")
return path
def _setup_venv(self, only_requirements=False):
"""Создание виртуального окружения и установка зависимостей"""
# Изменяем путь venv на уровень выше репозитория
venv_dir = os.path.join(os.path.dirname(self.local_path), 'venv')
requirements = os.path.join(self.local_path, 'requirements.txt')
pip_executable = os.path.join(venv_dir, 'Scripts' if os.name == 'nt' else 'bin', 'pip')
if only_requirements:
if os.path.exists(requirements):
print("Установка зависимостей из requirements.txt...")
subprocess.run([pip_executable, "install", "-r", requirements], check=True)
else:
print("Файл requirements.txt не найден.")
return
# Создание venv если не существует
if not os.path.exists(venv_dir):
print("Создание виртуального окружения...")
subprocess.run([sys.executable, "-m", "venv", venv_dir], check=True)
python_executable = os.path.join(venv_dir, 'Scripts' if os.name == 'nt' else 'bin', 'python')
# Обновление pip до последней версии
print("Обновление pip...")
subprocess.run([python_executable, "-m", "pip", "install", "--upgrade", "pip"], check=True)
# Установка gitpython в любом случае
print("Установка обязательного пакета gitpython...")
subprocess.run([pip_executable, "install", "gitpython"], check=True)
def _handle_user_input(self):
"""Обработка ввода пользователя и передача его в дочерний процесс"""
while self.process and self.process.poll() is None:
try:
user_input = input() + "\n" # Чтение ввода с новой строки
if self.process and self.process.poll() is None:
self.process.stdin.write(user_input)
self.process.stdin.flush()
except (EOFError, BrokenPipeError, OSError):
# Процесс завершился или канал закрыт
break
except Exception as e:
print(f"Ошибка при обработке ввода: {e}")
break
def _start_script(self):
"""Запуск дочернего скрипта"""
if self.process and self.process.poll() is None:
self._stop_script()
self._setup_venv(True)
script_path = self._get_script_full_path()
# Обновляем путь к venv в соответствии с новой структурой
venv_dir = os.path.join(os.path.dirname(self.local_path), 'venv')
venv_python = os.path.join(
venv_dir,
'Scripts' if os.name == 'nt' else 'bin',
'python'
)
python_exec = venv_python if os.path.exists(venv_python) else sys.executable
cmd = (
[python_exec, script_path]
if script_path.endswith(".py")
else [script_path]
)
self.process = subprocess.Popen(
cmd,
cwd=os.path.dirname(script_path),
stdout=sys.stdout,
stderr=sys.stderr,
stdin=subprocess.PIPE,
universal_newlines=True,
bufsize=1, # Построчная буферизация
text=True,
)
# Запускаем поток для обработки пользовательского ввода
self.input_thread = threading.Thread(
target=self._handle_user_input, daemon=True
)
self.input_thread.start()
print(f"Дочерний скрипт запущен (PID: {self.process.pid})")
def _stop_script(self):
"""Остановка дочернего скрипта"""
if self.process:
# Останавливаем поток ввода
if self.input_thread and self.input_thread.is_alive():
self.input_thread = None
try:
print(f"Остановка дочернего скрипта (PID: {self.process.pid})...")
self.process.stdin.close() # Закрываем stdin
self.process.terminate()
self.process.wait(timeout=5)
print("Дочерний скрипт остановлен")
except subprocess.TimeoutExpired:
print("Принудительное завершение дочернего скрипта...")
self.process.kill()
self.process.wait()
print("Дочерний скрипт принудительно завершен")
except Exception as e:
print(f"Ошибка при остановке скрипта: {e}")
finally:
self.process = None
def _check_script_status(self):
"""Проверка состояния скрипта"""
return self.process and self.process.poll() is None
def _handle_signal(self, signum, frame):
"""Обработчик сигналов завершения"""
print(f"\nПолучен сигнал {signum}, завершение...")
self._stop_script()
sys.exit(0)
def run(self):
"""Основной цикл мониторинга"""
print("\n=== Запуск монитора скриптов ===")
print(f"Репозиторий: {self.repo_url}")
print(f"Ветка: {self.branch}")
print(f"Скрипт: {self.script_path}")
print(f"Интервал проверки: {self.check_interval} сек")
print(
"Для ввода данных в дочерний скрипт просто введите текст и нажмите Enter\n"
)
try:
# Создание директории и настройка окружения перед клонированием
self._prepare_repo_dir()
self._setup_venv() # Перенесено выше инициализации репозитория
# Инициализация репозитория
repo_updated = self._ensure_repo()
self._start_script()
# Основной цикл
while True:
time.sleep(self.check_interval)
update = False
restart = False
# Проверка состояния скрипта
if not self._check_script_status():
self.restart_count += 1
if self.max_restarts > 0 and self.restart_count > self.max_restarts:
print("Достигнут лимит перезапусков. Завершение.")
break
restart = True
# Проверка обновлений репозитория
if os.path.exists(os.path.join(self.local_path, ".git")):
repo = Repo(self.local_path)
if self._check_for_updates(repo):
print("Обнаружены обновления. Обновление репозитория...")
if self._clone_repo():
update = True
if update:
print("Перезапуск скрипта после обновления...")
self._start_script()
elif restart:
print("Перезапуск дочернего скрипта...")
self._start_script()
except Exception as e:
print(f"Критическая ошибка: {str(e)}")
finally:
self._stop_script()
if __name__ == "__main__":
monitor = ScriptMonitor()
monitor.run()