forked from mtusi2026/mtusi2026lab5
Добавить панель системы и временный внешний доступ
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grant the local operations UI to an existing messenger account."""
|
||||
import re,subprocess,sys
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
if len(sys.argv)!=2 or not re.fullmatch('[a-z0-9_]{3,32}',sys.argv[1]):raise SystemExit('Укажите логин: make operator USERNAME=n1k0der')
|
||||
result=subprocess.check_output([str(root/'scripts/compose.sh'),'exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-c',"SELECT id FROM users WHERE username='"+sys.argv[1]+"'"],cwd=root,text=True).strip()
|
||||
if not result:raise SystemExit('Сначала зарегистрируйте этот аккаунт в мессенджере')
|
||||
p=root/'.env';lines=p.read_text().splitlines() if p.exists() else []
|
||||
lines=[line for line in lines if not line.startswith('OPS_USER_ID=')];lines.append('OPS_USER_ID='+result);p.write_text('\n'.join(lines)+'\n');p.chmod(0o600)
|
||||
subprocess.run([str(root/'scripts/compose.sh'),'up','-d','--no-deps','--wait','api'],cwd=root,check=True)
|
||||
print('Панель доступна аккаунту '+sys.argv[1]+'. Перезайдите в мессенджер.')
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Manage a temporary HTTPS tunnel for this project's HTTP entry point."""
|
||||
import fcntl,os,re,shutil,signal,socket,subprocess,sys,time,urllib.request
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
STATE=ROOT/'.local';STATE.mkdir(exist_ok=True)
|
||||
PID=STATE/'share.pid';URL=STATE/'share.url';origin='http://127.0.0.1:18085'
|
||||
def running():
|
||||
if not PID.exists():return None
|
||||
try:pid=int(PID.read_text())
|
||||
except ValueError:return None
|
||||
command=subprocess.run(['ps','-p',str(pid),'-o','command='],capture_output=True,text=True).stdout
|
||||
return pid if 'cloudflared tunnel' in command and '--url '+origin in command else None
|
||||
with (STATE/'share.lock').open('w') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
pid=running()
|
||||
if '--stop' in sys.argv:
|
||||
if pid:
|
||||
os.kill(pid,signal.SIGTERM)
|
||||
for _ in range(50):
|
||||
if not running():break
|
||||
time.sleep(.1)
|
||||
else:
|
||||
try:os.kill(pid,signal.SIGKILL)
|
||||
except ProcessLookupError:pass
|
||||
PID.unlink(missing_ok=True);URL.unlink(missing_ok=True)
|
||||
print('Внешний доступ отключён. Localhost продолжает работать.');raise SystemExit
|
||||
if pid:
|
||||
print(URL.read_text().strip() if URL.exists() else 'Туннель запущен, ссылка ещё создаётся.');raise SystemExit
|
||||
binary=shutil.which('cloudflared')
|
||||
if not binary:raise SystemExit('Установите cloudflared: brew install cloudflared')
|
||||
try:urllib.request.urlopen(origin+'/health/ready',timeout=5).close()
|
||||
except Exception:raise SystemExit('Сначала запустите мессенджер: make up')
|
||||
URL.unlink(missing_ok=True)
|
||||
(STATE/'share.log').unlink(missing_ok=True)
|
||||
with (STATE/'share.log').open('w') as log:
|
||||
edge=socket.gethostbyname('region1.v2.argotunnel.com')
|
||||
process=subprocess.Popen([binary,'tunnel','--no-autoupdate','--protocol','http2','--edge',edge+':7844','--url',origin],stdout=log,stderr=subprocess.STDOUT,start_new_session=True,env={**os.environ,'GODEBUG':'netdns=cgo'})
|
||||
PID.write_text(str(process.pid));PID.chmod(0o600)
|
||||
deadline=time.monotonic()+120
|
||||
while time.monotonic()<deadline and process.poll() is None:
|
||||
text=(STATE/'share.log').read_text()
|
||||
match=re.search(r'https://[a-z0-9-]+\.trycloudflare\.com',text)
|
||||
if match:URL.write_text(match.group(0)+'\n')
|
||||
if match and 'Registered tunnel connection' in text:
|
||||
check=subprocess.run(['curl','--fail','--silent','--max-time','8',match.group(0)+'/health/ready'],capture_output=True)
|
||||
if check.returncode==0:
|
||||
print(match.group(0));print('Отключение: make stop-share');raise SystemExit
|
||||
time.sleep(.25)
|
||||
if process.poll() is None:process.terminate()
|
||||
PID.unlink(missing_ok=True)
|
||||
raise SystemExit('Не удалось получить ссылку. Подробности в .local/share.log')
|
||||
Reference in New Issue
Block a user