Upload 12 files
Browse filesFiles changed (12)
- colab_tunnel/__init__.py+85-28
- colab_tunnel/_config.py+3-2
- colab_tunnel/_diagnostics.pyAdded+237
- colab_tunnel/_logger.pyAdded+16
- colab_tunnel/_registry.pyAdded+25
- colab_tunnel/_ssh.py+114-115
- colab_tunnel/_tunnels.py+188-67
- colab_tunnel/_utils.py+419-128
- pyproject.toml+12-2
- tests/__init__.pyAdded
- tests/test_regex.pyAdded+105
- tests/test_utils.pyAdded+133
1132345678910111213141516171819202122232425262728293031323334353637384 unmodified lines4344454647484950515253545556575825596061626364656667686970713 unmodified lines7576777879808182838485868788899044454647484950515253545591925893949596979899100101102103104105106606162636410710810911011111211311411511611711811912012112212312412570126127128737475761291301311321337913413513613713813914014114286143# ./colab_tunnel/__init__.py
"""
colab-proxy — утилиты для туннелирования веб-интерфейсов в Google Colab.
colab-tunnel — утилиты для туннелирования веб-интерфейсов в Google Colab.
Быстрый старт:
from colab_tunnel import get_share_link
link = get_share_link('cloudflared', 7860)
print(link)
Запуск всех провайдеров параллельно:
from colab_tunnel import try_all
print(try_all(7860))
Бенчмарк — найти лучший провайдер прямо сейчас:
from colab_tunnel import benchmark
results = benchmark()
Добавить собственный провайдер:
from colab_tunnel import tunnel_provider
@tunnel_provider('myprovider')
def get_myprovider_url(port: int) -> str:
...
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
from ._config import WORK_FOLDER
from ._logger import logger
from ._registry import proxies_functions, tunnel_provider
from ._utils import run, download
# Импорт модулей регистрирует провайдеров через @tunnel_provider
from . import _tunnels # noqa: F401
from . import _ssh # noqa: F401
# Прямой доступ к функциям провайдеров (обратная совместимость)
from ._tunnels import (
get_tmole_url,
get_tunwg_url,4 unmodified lines get_mmar_url,
get_tunnelite_url,
get_beeceptor_url,
get_bore_url,
get_boredigital_url,
)
from ._ssh import (
get_optimistix_url,
get_srvus_url,
get_serveo_url,
get_localhostrun_url,
)
from ._diagnostics import benchmark, TunnelBenchmarkResult
__version__ = '1.1.0'
__version__ = '1.0.0'
__all__ = [
# Основной API
'get_share_link',
'try_all',
'benchmark',
'TunnelBenchmarkResult',
# Реестр (для расширения)
'proxies_functions',
'tunnel_provider',
# Провайдеры (прямой доступ)
'get_tmole_url',
'get_tunwg_url',
'get_cloudflared_url',3 unmodified lines 'get_mmar_url',
'get_tunnelite_url',
'get_beeceptor_url',
'get_bore_url',
'get_boredigital_url',
'get_optimistix_url',
'get_srvus_url',
'get_serveo_url',
'get_localhostrun_url',
# Утилиты
'download',
'run',
'WORK_FOLDER',
'logger',
]
proxies_functions: dict = {
'tmole': get_tmole_url,
'tunwg': get_tunwg_url,
'cloudflared': get_cloudflared_url,
'localt': get_localt_url,
'gradio': get_gradio_url,
'native': get_native_url,
'mmar': get_mmar_url,
'tunnelite': get_tunnelite_url,
'beeceptor': get_beeceptor_url,
}
def try_all(port: int) -> str:
"""Запускает все доступные туннели и возвращает все полученные ссылки."""
"""
Параллельно запускает все зарегистрированные провайдеры туннелей.
В отличие от benchmark(), не измеряет метрики точно, зато возвращает
все работающие ссылки в разы быстрее — за время самого медленного провайдера
вместо суммы времён всех провайдеров.
Args:
port: Локальный порт для туннелирования.
Returns:
Строка со всеми полученными ссылками в формате 'провайдер: URL'.
"""
results: list[str] = []
for name, func in proxies_functions.items():
try:
results.append(func(port))
except Exception as e:
print(f'{name}: {e}')
with ThreadPoolExecutor(max_workers=len(proxies_functions)) as executor:
futures = {
executor.submit(func, port): name
for name, func in proxies_functions.items()
}
for future in as_completed(futures):
name = futures[future]
try:
url = future.result()
results.append(f'{name}: {url}')
except Exception as e:
logger.warning(f'[try_all] {name}: {e}')
return '\n'.join(results)
def get_share_link(host: str, port: int) -> str:
"""
Получить публичную ссылку на локальный порт через указанный туннель.
Получает публичную ссылку на локальный порт через указанный туннель.
Args:
host: Имя провайдера: 'cloudflared', 'tmole', 'tunwg',
'localt', 'gradio', 'native', 'mmar', 'tunnelite',
'beeceptor' — или 'all' для всех сразу.
port: Локальный порт веб-интерфейса.
host: Имя провайдера или 'all' для параллельного запуска всех.
Доступные провайдеры: list(proxies_functions.keys()).
port: Локальный порт веб-интерфейса.
Returns:
Публичная URL-ссылка (или несколько, если host='all').
Публичная URL-ссылка (или несколько строк при host='all').
"""
if host in proxies_functions:
return proxies_functions[host](port)
if host == 'all':
return try_all(port)
available = ', '.join(proxies_functions.keys())
return f'провайдер "{host}" не найден. Доступные: {available}' return f'Провайдер "{host}" не найден. Доступные: {available}'1123545674 unmodified lines1213141516171819# ./colab_tunnel/_config.py
from os import environ
from pathlib import Path
# Переопределяется переменной окружения colab_tunnel_WORK_DIR
# Переопределяется переменной окружения TUNNEL_WORK_DIR
WORK_FOLDER = Path(environ.get('TUNNEL_WORK_DIR', '/content/.config'))
cloudflare_bin = WORK_FOLDER / 'cloudflared'4 unmodified linesmmar_bin = WORK_FOLDER / 'mmar'
tunnelite_bin = WORK_FOLDER / 'tunnelite'
beeceptor_bin = WORK_FOLDER / 'beeceptor-cli'
bore_bin = WORK_FOLDER / 'bore'
boredigital_bin = WORK_FOLDER / 'bore_digital'
colab_native_url = WORK_FOLDER / 'colab_url.txt'
links_file = WORK_FOLDER / 'links.txt'
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""
Диагностика и бенчмарк провайдеров туннелей.
Использование:
from colab_tunnel import benchmark
results = benchmark() # все провайдеры
results = benchmark(['cloudflared', 'bore']) # выборочно
"""
import os
import socket
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from requests import get as get_url
from ._logger import logger
from ._registry import proxies_functions
from ._utils import run, kill_process_by_name
@dataclass
class TunnelBenchmarkResult:
"""Результат тестирования одного провайдера."""
name: str
url: Optional[str] = None
tunnel_time: float = 0.0 # Время получения ссылки (сек)
latency: Optional[float] = None # RTT до публичного URL (сек)
success: bool = False
error: Optional[str] = None
def find_free_port() -> int:
"""Находит свободный TCP-порт в системе."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def _find_test_server_bin() -> Path:
"""
Ищет бинарник тестового сервера в следующем порядке:
1. Переменная окружения TEST_SERVER_PATH
2. ../test_server/test_server (рядом с пакетом)
3. ./test_server/test_server (текущая директория)
"""
candidates: list[Path] = []
env = os.environ.get('TEST_SERVER_PATH')
if env:
candidates.append(Path(env))
candidates += [
Path(__file__).parent.parent / 'test_server' / 'test_server',
Path.cwd() / 'test_server' / 'test_server',
]
for path in candidates:
if path.exists() and path.is_file():
return path
raise FileNotFoundError(
'Бинарник тестового сервера не найден. '
'Укажите путь через переменную окружения TEST_SERVER_PATH.'
)
def _start_test_server(server_bin: Path, port: int) -> None:
"""Запускает тестовый HTTP-сервер в daemon-режиме."""
server_bin.chmod(0o755)
run(f'"{server_bin}" -d -p {port}', timeout=10)
time.sleep(1.5) # Даём серверу время на запуск
logger.debug(f'Тестовый сервер запущен на порту {port}.')
def _stop_test_server(server_bin: Path) -> None:
"""Останавливает тестовый HTTP-сервер."""
kill_process_by_name(server_bin.name)
logger.debug('Тестовый сервер остановлен.')
def _check_url_latency(url: str, timeout: float = 15.0) -> Optional[float]:
"""
Делает GET-запрос к публичному URL и возвращает RTT.
Returns:
Время ответа в секундах, или None если URL недоступен.
"""
# Убираем строку с IPv4-паролем (если провайдер вернул её как вторую строку)
clean_url = url.split('\n')[0].strip()
try:
t = time.time()
resp = get_url(clean_url, timeout=timeout, allow_redirects=True)
elapsed = round(time.time() - t, 3)
if 200 <= resp.status_code < 400:
return elapsed
except Exception as e:
logger.debug(f'URL недоступен ({clean_url}): {e}')
return None
def _print_report(results: list[TunnelBenchmarkResult]) -> None:
"""Выводит форматированную таблицу результатов."""
W = {'name': 14, 'status': 10, 'tunnel': 14, 'latency': 12}
total_w = sum(W.values()) + 38 # 38 — ширина колонки URL
sep = '=' * total_w
print(f'\n{sep}')
print(f'{"БЕНЧМАРК ПРОВАЙДЕРОВ ТУННЕЛЕЙ":^{total_w}}')
print(sep)
print(
f'{"Провайдер":<{W["name"]}}'
f'{"Статус":<{W["status"]}}'
f'{"Туннель":<{W["tunnel"]}}'
f'{"Задержка":<{W["latency"]}}'
f'URL / Ошибка'
)
print('-' * total_w)
for r in results:
status = '✓ OK ' if r.success else '✗ FAIL'
t_str = f'{r.tunnel_time:.2f}с'
lat_str = f'{r.latency * 1000:.0f}мс' if r.latency else '—'
detail = (r.url or r.error or '').split('\n')[0]
if len(detail) > 38:
detail = detail[:35] + '…'
print(
f'{r.name:<{W["name"]}}'
f'{status:<{W["status"]}}'
f'{t_str:<{W["tunnel"]}}'
f'{lat_str:<{W["latency"]}}'
f'{detail}'
)
print(sep)
ok = [r for r in results if r.success]
print(f'Итого: {len(ok)}/{len(results)} провайдеров работают.')
if ok:
fastest = min(ok, key=lambda r: r.tunnel_time)
print(f'Быстрейший запуск : {fastest.name} ({fastest.tunnel_time:.2f}с)')
with_lat = [r for r in ok if r.latency]
if with_lat:
lowest = min(with_lat, key=lambda r: r.latency) # type: ignore[arg-type]
print(f'Минимальная задержка: {lowest.name} ({lowest.latency * 1000:.0f}мс)') # type: ignore[operator]
print()
def benchmark(
providers: list[str] | None = None,
timeout_per_provider: float = 30.0,
latency_timeout: float = 15.0,
print_report: bool = True,
) -> list[TunnelBenchmarkResult]:
"""
Последовательно тестирует провайдеров туннелей и собирает метрики.
Схема работы:
1. Находит свободный порт, запускает тестовый HTTP-сервер (бинарник
из папки test_server/).
2. Поочерёдно вызывает каждого провайдера, замеряя время запуска.
3. Проверяет доступность полученной ссылки, измеряет RTT.
4. Гарантированно останавливает тестовый сервер (блок finally).
5. Выводит форматированный отчёт.
Последовательный (не параллельный) порядок важен для точности замеров:
параллельный запуск исказил бы время за счёт конкуренции за сеть и CPU.
Args:
providers: Имена провайдеров для теста. None — все доступные.
timeout_per_provider: Таймаут ожидания ссылки от провайдера (сек).
latency_timeout: Таймаут проверки доступности URL (сек).
print_report: Вывести форматированную таблицу в конце.
Returns:
Список TunnelBenchmarkResult для каждого протестированного провайдера.
Raises:
FileNotFoundError: Бинарник тестового сервера не найден.
ValueError: Указан несуществующий провайдер.
"""
server_bin = _find_test_server_bin()
port = find_free_port()
names = providers or list(proxies_functions.keys())
unknown = [n for n in names if n not in proxies_functions]
if unknown:
raise ValueError(
f'Неизвестные провайдеры: {unknown}. '
f'Доступные: {list(proxies_functions.keys())}'
)
print(f'Бенчмарк: {len(names)} провайдеров, порт {port}.')
_start_test_server(server_bin, port)
print('Тестовый сервер запущен.\n')
results: list[TunnelBenchmarkResult] = []
try:
for name in names:
func = proxies_functions[name]
print(f'[{name:<12}] запуск...', end=' ', flush=True)
result = TunnelBenchmarkResult(name=name)
t_start = time.time()
try:
url = func(port)
result.tunnel_time = round(time.time() - t_start, 2)
result.url = url
result.success = True
print(f'OK ({result.tunnel_time:.2f}с). Проверка...', end=' ', flush=True)
result.latency = _check_url_latency(url, timeout=latency_timeout)
if result.latency:
print(f'RTT {result.latency * 1000:.0f}мс')
else:
print('URL недоступен (туннель ещё поднимается?)')
except Exception as e:
result.tunnel_time = round(time.time() - t_start, 2)
result.error = str(e)
print(f'ОШИБКА: {str(e)[:100]}')
logger.debug(f'[{name}] детали:', exc_info=True)
results.append(result)
finally:
print()
_stop_test_server(server_bin)
print('Тестовый сервер остановлен.')
if print_report:
_print_report(results)
return results12345678910111213141516"""
Централизованный логгер для библиотеки colab_tunnel.
Управление детализацией:
import logging
logging.getLogger('colab_tunnel').setLevel(logging.DEBUG)
"""
import logging
logger = logging.getLogger('colab_tunnel')
if not logger.handlers:
_handler = logging.StreamHandler()
_handler.setFormatter(logging.Formatter('[%(name)s] %(levelname)s: %(message)s'))
logger.addHandler(_handler)
logger.setLevel(logging.WARNING)12345678910111213141516171819202122232425"""
Реестр провайдеров туннелей.
Новый провайдер регистрируется декоратором:
from colab_tunnel._registry import tunnel_provider
@tunnel_provider('myprovider')
def get_myprovider_url(port: int) -> str:
...
После этого провайдер автоматически доступен через get_share_link() и try_all().
"""
from typing import Callable
# Заполняется при импорте модулей _tunnels и _ssh через декоратор @tunnel_provider
proxies_functions: dict[str, Callable[[int], str]] = {}
def tunnel_provider(name: str) -> Callable:
"""Декоратор регистрации провайдера туннеля по имени."""
def decorator(func: Callable[[int], str]) -> Callable[[int], str]:
proxies_functions[name] = func
return func
return decorator123452645677899101112111213141516171819202122232425262728293031323316171834353637383924404142284344454647483334353649505152535439555657585960616263646566676869707172434445467374495051525375767778798081828384555657858687888990915960616263646566676869707172737475767778798081828384858687888990919293949596979293949596979899100101102103104105105106107108109110111112113114115106117107108109110111112113114115116117118119120121122123124124125126127128129130131132133125135126127128129130131132133134135136137138139140141142142143144145146147148149150151143153144145146147148149150151152153154155156157158159160160161162163164165166167168169161171162163164165166167168169170171172173174175"""
Провайдеры туннелей на основе SSH.
"""
import subprocess
from atexit import register as exit_register
import os
from pathlib import Path
from re import search
from select import select
from subprocess import DEVNULL, PIPE, Popen
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired
import time
from colab_tunnel._utils import terminate_process, run
from ._logger import logger
from ._registry import tunnel_provider
from ._utils import kill_process_by_name, terminate_process, drain_process_output, read_until_pattern
# Глобальный реестр для предотвращения Garbage Collection (сборки мусора) процессов и их труб
_active_tunnels: list[Popen] = []
# Реестр активных SSH-туннелей: имя процесса → объект Popen
# dict вместо list — предотвращает накопление мёртвых процессов при повторных вызовах
_active_tunnels: dict[str, Popen] = {}
def _register_active_tunnel(name: str, process: Popen) -> None:
"""Регистрирует туннель, корректно завершая предыдущий с тем же именем."""
if name in _active_tunnels:
old = _active_tunnels[name]
try:
old.terminate()
old.wait(timeout=3)
except TimeoutExpired:
old.kill()
old.wait()
except Exception:
pass
_active_tunnels[name] = process
def ensure_ssh_key() -> None:
"""
Гарантирует наличие приватного SSH-ключа в системе.
"""
"""Гарантирует наличие ed25519 SSH-ключа. Генерирует без пароля при отсутствии."""
ssh_dir = Path.home() / '.ssh'
ssh_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
key_file = ssh_dir / 'id_ed25519'
if not key_file.exists():
import subprocess
subprocess.run(
['ssh-keygen', '-t', 'ed25519', '-N', '', '-f', str(key_file)],
stdout=DEVNULL,
stderr=DEVNULL
stderr=DEVNULL,
)
logger.debug('SSH-ключ ed25519 сгенерирован.')
def get_ssh_tunnel_url(
start_commands: list[str],
process_name: str,
url_pattern: str,
timeout: float = 15.0,
start_commands: list[str],
process_name: str,
url_pattern: str,
timeout: float = 15.0,
) -> str:
"""
Запускает SSH-процесс с открытым stdin=PIPE для поддержания соединения.
Запускает SSH-туннельный процесс и ждёт появления публичного URL.
stdin намеренно оставляется ОТКРЫТЫМ: SSH завершается при получении EOF,
что прервало бы туннель. Объект процесса сохраняется в _active_tunnels
для предотвращения сборки мусора.
Args:
start_commands: Полная команда SSH с флагами.
process_name: Идентификатор процесса (часть адреса хоста).
url_pattern: Regex для поиска URL в выводе.
timeout: Таймаут ожидания URL в секундах.
Returns:
Публичный URL туннеля.
"""
ensure_ssh_key()
kill_process_by_name(process_name)
# Завершаем старые процессы
run(f'pkill -f "{process_name}"')
# Важно: stdin=PIPE оставляем ОТКРЫТЫМ, чтобы SSH не получал EOF и не выходил
process = Popen(start_commands, stdout=PIPE, stderr=PIPE, stdin=PIPE)
stdout_raw = process.stdout.raw
stderr_raw = process.stderr.raw
# Делаем сырые дескрипторы неблокирующими
for raw_stream in (stdout_raw, stderr_raw):
try:
url, _ = read_until_pattern(
process=process,
url_pattern=url_pattern,
timeout=timeout,
read_both_streams=True, # SSH может писать URL в stdout или stderr
)
except RuntimeError:
process.terminate()
try:
os.set_blocking(raw_stream.fileno(), False)
except Exception:
pass
process.wait(timeout=3)
except TimeoutExpired:
process.kill()
process.wait()
kill_process_by_name(process_name)
raise
start_time = time.time()
buffer = b""
while time.time() - start_time < timeout:
ready_readers, _, _ = select([stdout_raw, stderr_raw], [], [], 0.1)
read_any = False
for reader in ready_readers:
try:
chunk = reader.read(1024)
if chunk:
buffer += chunk
read_any = True
except (BlockingIOError, ValueError):
pass
except Exception:
pass
decoded_text = buffer.decode('utf-8', errors='ignore')
match = search(url_pattern, decoded_text)
if match:
# Регистрируем завершение при выходе из Python
exit_register(terminate_process, process_name, process)
# Добавляем в глобальный список, чтобы сохранить процесс и stdin-трубу открытыми
_active_tunnels.append(process)
return match.group()
if not read_any and process.poll() is not None:
break
time.sleep(0.05)
process.terminate()
run(f'pkill -f "{process_name}"')
final_output = buffer.decode('utf-8', errors='ignore')
raise RuntimeError(
f'Не удалось получить SSH-ссылку за {timeout} сек. Вывод процесса:\n{final_output}'
)
drain_process_output(process)
_register_active_tunnel(process_name, process)
exit_register(terminate_process, process_name, process)
logger.debug(f'[{process_name}] SSH-туннель: {url}')
return url
# ---------------------------------------------------------------------------
# Провайдеры
# ---------------------------------------------------------------------------
@tunnel_provider('optimistix')
def get_optimistix_url(port: int) -> str:
cmd = [
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-p', '1122',
'-R', f'80:127.0.0.1:{port}',
'ssh.optimistixtunnel.com'
]
return get_ssh_tunnel_url(
start_commands=cmd,
start_commands=[
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-p', '1122',
'-R', f'80:127.0.0.1:{port}',
'ssh.optimistixtunnel.com',
],
process_name='ssh.optimistixtunnel.com',
url_pattern=r'https://\S+\.otnl\.link',
)
@tunnel_provider('srvus')
def get_srvus_url(port: int) -> str:
cmd = [
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'1:127.0.0.1:{port}',
'srv.us'
]
return get_ssh_tunnel_url(
start_commands=cmd,
start_commands=[
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'1:127.0.0.1:{port}',
'srv.us',
],
process_name='srv.us',
url_pattern=r'https://[a-z0-9]{10,}\.srv\.us/?',
)
@tunnel_provider('serveo')
def get_serveo_url(port: int) -> str:
cmd = [
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'80:127.0.0.1:{port}',
'serveo.net'
]
return get_ssh_tunnel_url(
start_commands=cmd,
start_commands=[
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'80:127.0.0.1:{port}',
'serveo.net',
],
process_name='serveo.net',
url_pattern=r'https://\S+\.serveousercontent\.com',
)
@tunnel_provider('localhostrun')
def get_localhostrun_url(port: int) -> str:
cmd = [
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'80:127.0.0.1:{port}',
'nokey@localhost.run'
]
return get_ssh_tunnel_url(
start_commands=cmd,
start_commands=[
'ssh',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=10',
'-o', 'ServerAliveCountMax=3',
'-R', f'80:127.0.0.1:{port}',
'nokey@localhost.run',
],
process_name='localhost.run',
url_pattern=r'https://(?!admin\b)[a-zA-Z0-9-]+\.(?:localhost\.run|lhr\.life)',
)
11234546783 unmodified lines12131414151617181920212218192324252627283 unmodified lines32333429353637383940414243444546474849505152535455565758596061356263646566386768697042437172737475767778798047484981828384518586535455565787598889906162919293646566949596979869707172737475767778798081828384858687888990919299100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143971441451461471481491501 unmodified line1521531541071551561571581591601611621 unmodified line1641651661181671681691701711721731741 unmodified line1761771781291791801811821831841851861871 unmodified line18919019114119219319419519619719819917 unmodified lines2172182191682202212222232241732252262271762282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682691 unmodified line2712722731862742752762772782792802812821 unmodified line2842852861982872882892902912922932942951 unmodified line297298299210300212301302303304305216217218219220221306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342# ./colab_tunnel/_tunnels.py
"""
Провайдеры туннелей на основе бинарных утилит.
"""
from atexit import register as exit_register
from pathlib import Path
from re import search
from subprocess import PIPE, Popen
from time import sleep
3 unmodified lines WORK_FOLDER,
cloudflare_bin, tmole_bin, tunwg_bin,
go_localt_bin, gradio_bin, mmar_bin,
tunnelite_bin, beeceptor_bin, links_file
tunnelite_bin, beeceptor_bin, bore_bin,
boredigital_bin, colab_native_url, links_file,
)
from ._logger import logger
from ._registry import tunnel_provider
from ._utils import (
download, unpack_archive, run,
read_until_pattern, drain_process_output,
is_process_running, terminate_process,
move_path, is_ipv4,
kill_process_by_name, terminate_process,
move_path, is_ipv4, _snapshot,
get_github_latest_release_url,
)
3 unmodified lines bin_path: Path,
start_commands: list,
read_from_stderr: bool,
lines_to_read: int,
url_pattern: str = r'https://\S+',
timeout: float = 20.0,
write_link: bool = False,
stdin_input: str | None = None,
) -> str:
"""
Универсальный запуск бинарного туннельного провайдера.
При первом вызове скачивает и устанавливает бинарник.
Использует неблокирующее чтение вывода для поиска URL.
Args:
bin_url: URL скачивания бинарника (или архива).
need_unpack: Нужно ли распаковывать архив.
bin_path: Целевой путь бинарника на диске.
start_commands: Команда запуска со всеми аргументами.
read_from_stderr: Искать URL в stderr (иначе в stdout).
url_pattern: Regex для поиска публичного URL.
timeout: Максимальное время ожидания URL (сек).
write_link: Сохранять ли ссылку в links.txt.
stdin_input: Строка для отправки в stdin процесса.
Returns:
Публичный URL туннеля.
"""
# ── Установка бинарника ──────────────────────────────────────────────
if not bin_path.exists():
files_before = {f for f in WORK_FOLDER.iterdir() if f.is_file()}
WORK_FOLDER.mkdir(parents=True, exist_ok=True)
snapshot_before = _snapshot(WORK_FOLDER)
if need_unpack:
archive = download(bin_url, save_path=WORK_FOLDER, progress=False)
unpack_archive(download(bin_url, progress=False), WORK_FOLDER, rm_archive=True)
unpack_archive(archive, WORK_FOLDER, rm_archive=True)
else:
download(bin_url, save_path=bin_path.parent, progress=False)
files_after = {f for f in WORK_FOLDER.iterdir() if f.is_file()}
new_files = list(files_after - files_before)
new_files = list(_snapshot(WORK_FOLDER) - snapshot_before)
if not new_files:
raise RuntimeError(
f'В {WORK_FOLDER} не появилось новых файлов после загрузки {bin_url}'
)
if len(new_files) == 1:
move_path(new_files[0], bin_path)
else:
elif len(new_files) > 1:
largest_file = max(new_files, key=lambda f: f.stat().st_size)
move_path(largest_file, bin_path)
# Несколько файлов (например, архив с доп. файлами) — берём наибольший
largest = max(new_files, key=lambda f: f.stat().st_size)
move_path(largest, bin_path)
for f in new_files:
if f != largest_file:
if f != largest and f.exists():
f.unlink(missing_ok=True)
else:
raise RuntimeError(
f'ошибка при определении нового файла после распаковки!\n'
f'ожидалось появление новых файлов в директории {WORK_FOLDER}'
)
bin_path.chmod(0o777)
bin_path.chmod(0o755)
logger.debug(f'Установлен бинарник: {bin_path}')
if is_process_running(bin_path.name):
run(f'pkill -f {bin_path.name}')
# ── Завершение предыдущего экземпляра ───────────────────────────────
kill_process_by_name(bin_path.name)
# Если требуется отправка ввода, открываем канал stdin
stdin_channel = PIPE if stdin_input is not None else None
process = Popen(start_commands, stdout=PIPE, stderr=PIPE, stdin=stdin_channel, text=True)
# ── Запуск процесса ──────────────────────────────────────────────────
stdin_flag = PIPE if stdin_input is not None else None
process = Popen(start_commands, stdout=PIPE, stderr=PIPE, stdin=stdin_flag)
if stdin_input is not None and process.stdin:
process.stdin.write(stdin_input)
process.stdin.flush()
stream = process.stderr if read_from_stderr else process.stdout
lines: list[str] = []
for _ in range(lines_to_read):
line = stream.readline()
if not line:
break
lines.append(line.strip())
ipv4 = next((ln for ln in lines if is_ipv4(ln)), None)
urls = [search(url_pattern, ln).group() for ln in lines if search(url_pattern, ln)]
if urls:
exit_register(terminate_process, bin_path.name, process)
if write_link:
links_file.write_text(urls[0])
return f'{urls[0]}\n пароль(IP): {ipv4}' if ipv4 else urls[0]
run(f'pkill -f {bin_path.name}')
raise RuntimeError(
f'ссылку получить не удалось, вывод работы бинарника:\n' + '\n'.join(lines)
try:
process.stdin.write(stdin_input.encode())
process.stdin.flush()
finally:
process.stdin.close() # Сигнал EOF — многие утилиты ждут его перед стартом
# ── Чтение URL из вывода ─────────────────────────────────────────────
try:
url, full_output = read_until_pattern(
process=process,
url_pattern=url_pattern,
timeout=timeout,
read_from_stderr=read_from_stderr,
)
except RuntimeError:
kill_process_by_name(bin_path.name)
try:
process.wait(timeout=3)
except Exception:
process.kill()
process.wait()
raise
# Слив вывода в фоне — предотвращает блокировку из-за переполнения пайпа
drain_process_output(process)
# Проверка наличия IPv4 в выводе (пароль/IP у некоторых провайдеров)
ipv4 = next(
(ln.strip() for ln in full_output.splitlines() if is_ipv4(ln.strip())),
None,
)
exit_register(terminate_process, bin_path.name, process)
if write_link:
try:
links_file.write_text(url)
except Exception as e:
logger.warning(f'Не удалось записать ссылку в {links_file}: {e}')
logger.debug(f'[{bin_path.name}] Туннель: {url}')
return f'{url}\n пароль(IP): {ipv4}' if ipv4 else url
# ---------------------------------------------------------------------------
# Конкретные провайдеры
# Провайдеры
# ---------------------------------------------------------------------------
@tunnel_provider('tmole')
def get_tmole_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://tunnelmole.com/downloads/tmole-linux.gz',1 unmodified line bin_path=tmole_bin,
start_commands=[str(tmole_bin), str(port)],
read_from_stderr=False,
lines_to_read=5,
timeout=20.0,
)
@tunnel_provider('tunwg')
def get_tunwg_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://github.com/ntnj/tunwg/releases/latest/download/tunwg',1 unmodified line bin_path=tunwg_bin,
start_commands=[str(tunwg_bin), f'--forward=http://127.0.0.1:{port}'],
read_from_stderr=True,
lines_to_read=2,
timeout=20.0,
)
@tunnel_provider('cloudflared')
def get_cloudflared_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64',1 unmodified line bin_path=cloudflare_bin,
start_commands=[str(cloudflare_bin), 'tunnel', '--url', f'http://127.0.0.1:{port}'],
read_from_stderr=True,
lines_to_read=6,
url_pattern=r'(?P<url>https?://\S+\.trycloudflare\.com)',
timeout=25.0,
)
@tunnel_provider('localt')
def get_localt_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://huggingface.co/prolapse/go_localt/resolve/main/go_localt',1 unmodified line bin_path=go_localt_bin,
start_commands=[str(go_localt_bin), str(port)],
read_from_stderr=False,
lines_to_read=2,
timeout=20.0,
)
@tunnel_provider('gradio')
def get_gradio_url(port: int) -> str:
max_attempts = 3
last_error: Exception | None = None17 unmodified lines bin_path=gradio_bin,
start_commands=cmd,
read_from_stderr=False,
lines_to_read=3,
timeout=20.0,
)
except Exception as e:
last_error = e
if attempt < max_attempts - 1:
print(f'попытка {attempt + 1} получить ссылку градио провалилась: {e}. пробуем ещё...')
logger.warning(f'Попытка {attempt + 1} Gradio провалилась: {e}. Повтор через 5с...')
sleep(5)
raise RuntimeError(f'после {max_attempts} попыток поднять туннель градио не удалось: {last_error}')
raise RuntimeError(f'После {max_attempts} попыток Gradio-туннель не запущен: {last_error}')
@tunnel_provider('native')
def get_native_url(port: int) -> str:
"""
Встроенный прокси Google Colab. Результат кэшируется по номеру порта.
"""
try:
from google.colab.output import eval_js # type: ignore[import]
except ImportError:
raise RuntimeError('get_native_url доступен только в среде Google Colab.')
cache_url_file = colab_native_url
cache_port_file = colab_native_url.with_suffix('.port')
if cache_url_file.exists() and cache_port_file.exists():
try:
if int(cache_port_file.read_text().strip()) == port:
cached = cache_url_file.read_text().strip()
if cached:
logger.debug(f'native URL из кэша (порт {port}): {cached}')
return cached
except Exception:
pass
url = eval_js(f'google.colab.kernel.proxyPort({port})')
try:
WORK_FOLDER.mkdir(parents=True, exist_ok=True)
cache_url_file.write_text(url)
cache_port_file.write_text(str(port))
except Exception as e:
logger.warning(f'Не удалось кэшировать native URL: {e}')
return url
@tunnel_provider('mmar')
def get_mmar_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://github.com/yusuf-musleh/mmar/releases/latest/download/mmar_Linux_x86_64.tar.gz',1 unmodified line bin_path=mmar_bin,
start_commands=[str(mmar_bin), 'client', '--local-port', str(port)],
read_from_stderr=True,
lines_to_read=10,
url_pattern=r'(?P<url>https?://\S+\.mmar\.dev)',
timeout=20.0,
)
@tunnel_provider('tunnelite')
def get_tunnelite_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://github.com/hehepiska/tunnellite-linux/releases/download/latest/tunnelite',1 unmodified line bin_path=tunnelite_bin,
start_commands=[str(tunnelite_bin), f'http://127.0.0.1:{port}'],
read_from_stderr=False,
lines_to_read=60,
url_pattern=r'(?P<url>https?://\S+\.tunnelite\.com)',
timeout=45.0, # Tunnelite стартует медленно
)
@tunnel_provider('beeceptor')
def get_beeceptor_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://cdn.beeceptor.com/downloads/cli/latest/beeceptor-cli-linux-x64.tar.gz',1 unmodified line bin_path=beeceptor_bin,
start_commands=[str(beeceptor_bin), '-p', str(port), '-y'],
read_from_stderr=False,
lines_to_read=15,
url_pattern=r'(?P<url>https?://\S+\.beeceptor\.com)',
stdin_input='\n', # Симулируем нажатие клавиши Enter для выбора первого пункта
timeout=20.0,
stdin_input='\n',
)
def get_native_url(port: int) -> str:
try:
from google.colab.output import eval_js # type: ignore[import]
except ImportError:
raise RuntimeError('get_native_url доступен только в среде Google Colab.')
return eval_js(f'google.colab.kernel.proxyPort({port})')@tunnel_provider('bore')
def get_bore_url(port: int) -> str:
# Для актуальной версии запрашиваем GitHub API, только если бинарника ещё нет
bin_url = 'https://github.com/ekzhang/bore/releases/download/v0.6.0/bore-v0.6.0-x86_64-unknown-linux-musl.tar.gz'
if not bore_bin.exists():
try:
bin_url = get_github_latest_release_url(
'ekzhang/bore',
r'bore-v[\d.]+-x86_64-unknown-linux-musl\.tar\.gz',
)
logger.debug(f'Актуальный URL bore: {bin_url}')
except Exception as e:
logger.warning(f'GitHub API недоступен, используется закреплённая версия bore: {e}')
raw = get_revproxy_url(
bin_url=bin_url,
need_unpack=True,
bin_path=bore_bin,
start_commands=[str(bore_bin), 'local', str(port), '--to', 'bore.pub'],
read_from_stderr=True, # Rust логи идут в stderr
url_pattern=r'bore\.pub:\d+',
timeout=15.0,
)
return f'http://{raw}/'
@tunnel_provider('boredigital')
def get_boredigital_url(port: int) -> str:
return get_revproxy_url(
bin_url='https://github.com/jkuri/bore/releases/latest/download/bore_linux_amd64',
need_unpack=False,
bin_path=boredigital_bin,
start_commands=[str(boredigital_bin), '-lp', str(port)],
read_from_stderr=False,
url_pattern=r'(?P<url>https://\S+\.bore\.digital)',
timeout=20.0,
)1234567891034567111213141516171819202122232425262717282930202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182833132333435363738399091404142434445464748495051525354555657585993606162633 unmodified lines6768697071727374757677787980818283848586878889106909192939495961089798110111991001011021141151161171031041051061071081091101111191121131141231241251261151161171181191201211221231241251265 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601391611621631641431651661671681691701461471711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762771532782792802812821582832842852861 unmodified line28828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640717140840941041141241341441541641741841942042142242342418242542642742814 unmodified lines4434444452034464474489 unmodified lines4584594604614622202212222232242252262272282292304634644654664674684694704714724734744754764774784794804811 unmodified line483484485238239240241242486487488489490491492493494495496497498499500501244245246247248249250251252253254255256257258259502503504505506507508509510511512513514515516517518519520521522523263524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554"""
Вспомогательные утилиты: процессы, архивы, сеть, чтение потоков.
"""
import os
import re
import select
import threading
import time
from os import name as os_name
from pathlib import Path
from re import compile, search
from shutil import move
from subprocess import PIPE, Popen, STDOUT, check_output, CalledProcessError
from sys import stdout
from time import time
from shutil import move as shutil_move
from subprocess import (
PIPE, Popen, STDOUT, TimeoutExpired,
check_output, CalledProcessError,
)
from sys import stdout as sys_stdout
from typing import TypedDict
from urllib.parse import unquote, urlparse
from requests import get as get_url, head as get_head
from requests.structures import CaseInsensitiveDict
from ._config import WORK_FOLDER, HEADERS
from ._logger import logger
# ---------------------------------------------------------------------------
# Архивы
# Типы
# ---------------------------------------------------------------------------
def determine_archive_format(filepath: str | Path) -> str | None:
filepath = Path(filepath)
zip_sig = bytes([0x50, 0x4B, 0x03, 0x04])
seven_z = bytes([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])
lzma_xz = bytes([0xFD, 0x37, 0x7A, 0x58, 0x5A])
tgz = bytes([0x1F, 0x8B])
tbz = bytes([0x42, 0x5A, 0x68])
ustar = bytes([0x75, 0x73, 0x74, 0x61, 0x72])
with filepath.open('rb') as fh:
header = fh.read(262)
if header.startswith(zip_sig):
return 'zip'
if header.startswith(seven_z) or header.startswith(lzma_xz):
return '7z'
if header.startswith(tgz):
return 'tar.gz'
if header.startswith(tbz):
return 'tar.bz2'
if header[0x101:0x101 + len(ustar)] == ustar:
return 'tar'
return None
def unpack_archive(archive_path: str | Path, dest_path: str | Path, rm_archive: bool = True) -> None:
if str(archive_path).startswith(('https://', 'http://')):
archive_path = download(archive_path, save_path=WORK_FOLDER, progress=False)
archive_path = Path(archive_path)
dest_path = Path(dest_path)
if not archive_path.exists():
raise RuntimeError(f'архив {archive_path} не найден.')
fmt = determine_archive_format(archive_path)
def _rm() -> None:
if rm_archive:
archive_path.unlink(missing_ok=True)
try:
if fmt == '7z' or archive_path.suffix == '.7z':
run(f'7z -bso0 -bd -slp -y x "{archive_path}" -o"{dest_path}"', cwd=dest_path)
elif fmt == 'tar' or archive_path.suffix == '.tar':
run(f'tar -xvpf "{archive_path}" -C "{dest_path}"', cwd=dest_path)
elif fmt in ('tar.gz', 'tar.bz2') or archive_path.suffix in ('.tar.gz', '.tar.bz2', '.tar.xz'):
result = run(f'tar -xvzpf "{archive_path}" -C "{dest_path}"', cwd=dest_path)
if result['status_code'] != 0:
run(f'gzip -d "{archive_path}"', dest_path, cwd=dest_path)
elif fmt == 'zip' or archive_path.suffix == '.zip':
run(f'unzip "{archive_path}" -d "{dest_path}"', cwd=dest_path)
else:
run(f'7z -bso0 -bd -slp -y x "{archive_path}" -o"{dest_path}"', cwd=dest_path)
_rm()
except Exception:
try:
run(f'7z -bso0 -bd -mmt4 -slp -y x "{archive_path}" -o"{dest_path}"', cwd=dest_path)
_rm()
except Exception:
raise RuntimeError(
f'формат архива {archive_path.suffix} не определён. '
f'Задайте формат вручную через determine_archive_format.'
)
class RunResult(TypedDict):
status_code: int
output: str
# ---------------------------------------------------------------------------
# Процессы
# ---------------------------------------------------------------------------
def run(command: str, cwd: str | Path | None = None, live_output: bool = False) -> dict:
process = Popen(command, shell=True, cwd=cwd, stdout=PIPE, stderr=STDOUT)
def run(
command: str,
cwd: str | Path | None = None,
live_output: bool = False,
timeout: float | None = None,
) -> RunResult:
"""
Выполняет shell-команду, возвращает код выхода и вывод.
Args:
command: Shell-команда.
cwd: Рабочая директория (None — текущая).
live_output: Выводить прогресс в реальном времени.
timeout: Таймаут в секундах (None — без ограничений).
Returns:
RunResult: {'status_code': int, 'output': str}.
При таймауте status_code == -1.
"""
_encodings = ['utf-8', 'iso-8859-5', 'windows-1251', 'cp866', 'koi8-r', 'mac_cyrillic']
_progress_pattern = r'\d+%|\d+/\d+'
_progress_re = re.compile(r'\d+%|\d+/\d+')
def _decode(data: bytes) -> str:
for enc in _encodings:3 unmodified lines continue
return data.decode('utf-8', errors='replace')
process = Popen(command, shell=True, cwd=cwd, stdout=PIPE, stderr=STDOUT)
# Режим без живого вывода: communicate() с поддержкой таймаута
if not live_output:
try:
stdout_data, _ = process.communicate(timeout=timeout)
except TimeoutExpired:
process.kill()
process.communicate()
msg = f'Таймаут ({timeout}с): {command}'
logger.warning(msg)
return RunResult(status_code=-1, output=msg)
lines = [ln.strip() for ln in _decode(stdout_data).splitlines() if ln.strip()]
return RunResult(status_code=process.returncode, output='\n'.join(lines))
# Режим живого вывода (для ручного использования, таймаут приблизительный)
final_output: list[str] = []
last_progress = ''
deadline = time.time() + timeout if timeout else None
for raw_line in iter(process.stdout.readline, b''):
for raw_line in iter(process.stdout.readline, b''): # type: ignore[union-attr]
if deadline and time.time() > deadline:
process.kill()
process.wait()
final_output.append(f'[ТАЙМАУТ после {timeout}с]')
break
line = _decode(raw_line.strip())
if search(_progress_pattern, line):
if _progress_re.search(line):
last_progress = line
if live_output:
stdout.write('\r' + line)
sys_stdout.write('\r' + line)
sys_stdout.flush()
else:
final_output.append(line)
if live_output:
stdout.write(line + '\n')
if live_output:
stdout.flush()
sys_stdout.write(line + '\n')
sys_stdout.flush()
try:
process.wait(timeout=5)
except TimeoutExpired:
process.kill()
process.wait()
process.wait()
if last_progress:
final_output.append(last_progress)
return {
'status_code': process.returncode,
'output': '\n'.join(final_output),
}
return RunResult(status_code=process.returncode, output='\n'.join(final_output))
def kill_process_by_name(name: str) -> None:
"""
Завершает процессы текущего пользователя по подстроке имени.
Ограничение по UID предотвращает случайное завершение чужих процессов.
"""
run(f'pkill -TERM -u "$(id -u)" -f "{name}" 2>/dev/null; true', timeout=5)
def is_process_running(process_name: str | Path) -> bool:5 unmodified lines
def terminate_process(process_name: str, process_obj: Popen) -> None:
"""
Корректно завершает процесс туннеля.
Сначала SIGTERM + wait(5с), при зависании — SIGKILL.
"""
for stream in (process_obj.stdout, process_obj.stderr, process_obj.stdin):
if stream:
try:
stream.close()
except Exception:
pass
try:
process_obj.terminate()
process_obj.wait(timeout=5)
except TimeoutExpired:
process_obj.kill()
process_obj.wait()
except Exception:
pass
kill_process_by_name(process_name)
def _drain_raw(raw_stream: object) -> None:
"""Сливает данные из сырого потока в никуда, предотвращая блокировку пайпа."""
try:
process_obj.stdout.close()
os.set_blocking(raw_stream.fileno(), True) # type: ignore[attr-defined]
except Exception:
pass
try:
process_obj.stderr.close()
while True:
data = raw_stream.read(4096) # type: ignore[attr-defined]
if not data:
break
except Exception:
pass
process_obj.terminate()
run(f'pkill -f {process_name}')
def drain_process_output(process: Popen) -> None:
"""
Запускает daemon-потоки для слива stdout/stderr долгоживущего процесса.
Без этого туннельный процесс заблокируется, когда системный буфер
пайпа (обычно 64 КБ) заполнится непрочитанны��и логами.
"""
for stream in (process.stdout, process.stderr):
if stream:
raw = getattr(stream, 'raw', stream)
t = threading.Thread(target=_drain_raw, args=(raw,), daemon=True)
t.start()
def read_until_pattern(
process: Popen,
url_pattern: str,
timeout: float = 20.0,
read_from_stderr: bool = False,
read_both_streams: bool = False,
) -> tuple[str, str]:
"""
Неблокирующее чтение вывода процесса до нахождения URL-паттерна.
Использует select() + os.set_blocking() вместо readline(),
что полностью исключает зависание при нехватке строк вывода.
Args:
process: Запущенный Popen с открытыми потоками PIPE.
url_pattern: Регулярное выражение для поиска URL.
timeout: Максимальное время ожидания в секундах.
read_from_stderr: Читать из stderr (иначе stdout).
read_both_streams: Читать из обоих потоков (для SSH).
Returns:
Кортеж (matched_url, full_output).
Raises:
RuntimeError: Паттерн не найден за время timeout.
"""
if read_both_streams:
active_streams = [s for s in (process.stdout, process.stderr) if s]
elif read_from_stderr:
active_streams = [process.stderr] if process.stderr else []
else:
active_streams = [process.stdout] if process.stdout else []
if not active_streams:
raise RuntimeError('Потоки вывода процесса недоступны.')
raws: list = []
for stream in active_streams:
raw = getattr(stream, 'raw', stream)
try:
os.set_blocking(raw.fileno(), False)
except Exception:
pass
raws.append(raw)
buffer = b''
deadline = time.time() + timeout
while time.time() < deadline:
try:
ready, _, _ = select.select(raws, [], [], 0.1)
except Exception:
break
for raw in ready:
try:
chunk = raw.read(4096)
if chunk:
buffer += chunk
except (BlockingIOError, ValueError):
pass
except Exception:
pass
text = buffer.decode('utf-8', errors='ignore')
match = re.search(url_pattern, text)
if match:
return match.group(), text
if process.poll() is not None:
# Процесс завершился — финальное чтение остатков
for raw in raws:
try:
remaining = raw.read(65536)
if remaining:
buffer += remaining
except Exception:
pass
text = buffer.decode('utf-8', errors='ignore')
match = re.search(url_pattern, text)
if match:
return match.group(), text
break
output_str = buffer.decode('utf-8', errors='ignore')
raise RuntimeError(f'URL не найден за {timeout} сек. Вывод процесса:\n{output_str}')
def move_path(old_path: Path | str, new_path: Path | str) -> None:
old, new = Path(old_path), Path(new_path)
if not old.exists():
raise RuntimeError(f'не найден исходный путь для перемещения: {old}')
raise RuntimeError(f'Не найден исходный путь для перемещения: {old}')
try:
old.replace(new)
except Exception:
try:
move(old, new)
shutil_move(str(old), str(new))
except Exception:
if os_name == 'posix':
run(f'mv "{old}" "{new}"')1 unmodified line run(f'move "{old}" "{new}"')
# ---------------------------------------------------------------------------
# Файлы и архивы
# ---------------------------------------------------------------------------
def _snapshot(folder: Path) -> set[Path]:
"""Рекурсивный снимок всех файлов в директории (включая вложенные папки)."""
if not folder.exists():
return set()
return {f for f in folder.rglob('*') if f.is_file()}
def determine_archive_format(filepath: str | Path) -> str | None:
"""Определяет формат архива по сигнатуре байт (magic bytes)."""
filepath = Path(filepath)
zip_sig = bytes([0x50, 0x4B, 0x03, 0x04])
seven_z = bytes([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])
lzma_xz = bytes([0xFD, 0x37, 0x7A, 0x58, 0x5A])
tgz = bytes([0x1F, 0x8B])
tbz = bytes([0x42, 0x5A, 0x68])
ustar = bytes([0x75, 0x73, 0x74, 0x61, 0x72])
with filepath.open('rb') as fh:
header = fh.read(262)
if header.startswith(zip_sig): return 'zip'
if header.startswith(seven_z): return '7z'
if header.startswith(lzma_xz): return '7z'
if header.startswith(tgz): return 'tar.gz'
if header.startswith(tbz): return 'tar.bz2'
if header[0x101:0x101 + len(ustar)] == ustar: return 'tar'
return None
def unpack_archive(
archive_path: str | Path,
dest_path: str | Path,
rm_archive: bool = True,
) -> None:
"""
Распаковывает архив в указанную директорию.
Поддерживает: tar, tar.gz, tar.bz2, tar.xz, gz (одиночный файл), zip, 7z.
При неудаче основного метода делает fallback к 7z.
Принимает URL — скачивает архив сам.
"""
if str(archive_path).startswith(('https://', 'http://')):
archive_path = download(str(archive_path), save_path=WORK_FOLDER, progress=False)
archive_path = Path(archive_path)
dest_path = Path(dest_path)
if not archive_path.exists():
raise RuntimeError(f'Архив не найден: {archive_path}')
fmt = determine_archive_format(archive_path)
dest_path.mkdir(parents=True, exist_ok=True)
def _rm() -> None:
if rm_archive:
archive_path.unlink(missing_ok=True)
def _try_7z() -> None:
result = run(
f'7z -bso0 -bd -mmt4 -slp -y x "{archive_path}" -o"{dest_path}"',
timeout=180,
)
if result['status_code'] != 0:
raise RuntimeError(
f'Не удалось распаковать {archive_path.name}.\n{result["output"]}'
)
_rm()
try:
if fmt == 'zip' or archive_path.suffix == '.zip':
r = run(f'unzip -o "{archive_path}" -d "{dest_path}"', timeout=180)
if r['status_code'] != 0:
raise RuntimeError(r['output'])
_rm()
elif fmt in ('7z',) or archive_path.suffix == '.7z':
r = run(
f'7z -bso0 -bd -slp -y x "{archive_path}" -o"{dest_path}"',
timeout=180,
)
if r['status_code'] != 0:
raise RuntimeError(r['output'])
_rm()
elif fmt in ('tar', 'tar.gz', 'tar.bz2') or archive_path.suffix in (
'.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tar.xz', '.txz', '.gz',
):
# GNU tar определяет формат сжатия автоматически через -xpf
r = run(f'tar -xpf "{archive_path}" -C "{dest_path}"', timeout=180)
if r['status_code'] != 0:
# Возможно, это одиночный gzip-файл без tar-обёртки (напр. tmole-linux.gz)
gz_r = run(f'gzip -df "{archive_path}"', timeout=60)
if gz_r['status_code'] != 0:
raise RuntimeError(
f'tar: {r["output"]}\ngzip: {gz_r["output"]}'
)
# gzip -f уже удалил .gz и создал распакованный файл на месте
return
_rm()
else:
_try_7z()
except RuntimeError as e:
logger.debug(f'Основной метод распаковки не сработал ({e}), fallback к 7z.')
_try_7z()
# ---------------------------------------------------------------------------
# Сеть
# ---------------------------------------------------------------------------
def is_ipv4(address: str) -> bool:
pattern = compile(
pattern = re.compile(
r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'
)
return bool(pattern.match(address))
def is_valid_url(url: str, custom_headers: dict | None = None) -> bool:
"""
Проверяет доступность URL (HEAD или GET запрос).
Returns:
True, если сервер вернул HTTP 2xx.
"""
req_headers = HEADERS.copy()
if custom_headers:
req_headers.update(custom_headers)
for attempt in range(2):
for _ in range(2):
try:
with get_url(url, headers=req_headers, allow_redirects=True, stream=True, timeout=10) as resp:
if 200 <= resp.status_code < 300:14 unmodified lines cd = headers.get('content-disposition')
if not cd:
return headers.get('filename')
for part in cd.split(';'):
part = part.strip()
if part.startswith('filename*='):9 unmodified lines filename: str | Path | None = None,
save_path: str | Path | None = None,
progress: bool = True,
extra_headers: dict[str, str] | None = None,
) -> Path:
extra_headers: dict | None = None
url_parts = url.replace('"', '').replace("'", '').split('--header=')
if len(url_parts) > 1:
url = url_parts[0].strip()
key, _, value = url_parts[1].partition(':')
extra_headers = {key.strip(): value.strip()}
# Проверка валидности с учетом переданных заголовков
if not is_valid_url(url, custom_headers=extra_headers):
raise RuntimeError(f'недействительная ссылка на файл или доступ ограничен: {url}')
"""
Скачивает файл по URL.
Args:
url: URL файла.
filename: Имя для сохранения (None — из заголовков или URL).
save_path: Папка сохранения (None — текущая директория).
progress: Показывать прогресс загрузки.
extra_headers: Дополнительные HTTP-заголовки.
Returns:
Path к скачанному файлу.
Raises:
RuntimeError: При ошибке сети или записи файла.
"""
save_path = Path(save_path) if save_path else Path.cwd()
save_path.mkdir(parents=True, exist_ok=True)
1 unmodified line if extra_headers:
req_headers.update(extra_headers)
with get_url(url, stream=True, allow_redirects=True, headers=req_headers) as req:
file_size = int(req.headers.get('content-length', 0))
file_name = filename or get_filename_from_headers(req.headers) or Path(urlparse(req.url).path).name
file_path = save_path / file_name
chunk_size = max(4096, file_size // 2000) if file_size else 4096
try:
resp = get_url(url, stream=True, allow_redirects=True, headers=req_headers, timeout=60)
resp.raise_for_status()
except Exception as e:
raise RuntimeError(f'Не удалось скачать файл по ссылке {url}:\n{e}')
file_size = int(resp.headers.get('content-length', 0))
raw_name = (
str(filename)
if filename
else (get_filename_from_headers(resp.headers) or Path(urlparse(resp.url).path).name)
)
file_name = Path(raw_name).name
file_path = save_path / file_name
chunk_size = max(4096, file_size // 2000) if file_size else 4096
downloaded = 0
start = time()
try:
with open(file_path, 'wb') as fp:
for chunk in req.iter_content(chunk_size=chunk_size):
if chunk:
fp.write(chunk)
if progress and file_size:
downloaded += len(chunk)
elapsed = time() - start
print(
f'\rзагрузка {file_name}: {downloaded / file_size * 100:.2f}% | {elapsed:.2f} сек.',
end='',
)
except Exception as e:
raise RuntimeError(f'не удалось загрузить файл по ссылке {url}:\n{e}')
downloaded = 0
start = time.time()
try:
with open(file_path, 'wb') as fp:
for chunk in resp.iter_content(chunk_size=chunk_size):
if chunk:
fp.write(chunk)
if progress and file_size:
downloaded += len(chunk)
elapsed = time.time() - start
print(
f'\rзагрузка {file_name}: '
f'{downloaded / file_size * 100:.2f}% | {elapsed:.2f} сек.',
end='',
)
except Exception as e:
raise RuntimeError(f'Не удалось сохранить файл из {url}:\n{e}')
if progress and file_size:
print()
logger.debug(f'Скачан: {file_path} ({file_size} байт)')
return file_path return file_path
def get_github_latest_release_url(repo: str, asset_pattern: str) -> str:
"""
Возвращает URL загрузки актуального релизного ассета с GitHub.
Args:
repo: Репозиторий в формате 'owner/repo'.
asset_pattern: Регулярное выражение для имени ассета.
Returns:
browser_download_url для найденного ассета.
Raises:
RuntimeError: Если ассет не найден или GitHub API недоступен.
"""
api_url = f'https://api.github.com/repos/{repo}/releases/latest'
resp = get_url(api_url, timeout=10)
resp.raise_for_status()
assets = resp.json().get('assets', [])
for asset in assets:
if re.search(asset_pattern, asset['name']):
return asset['browser_download_url']
available = [a['name'] for a in assets]
raise RuntimeError(
f'Ассет "{asset_pattern}" не найден в {repo}. '
f'Доступные: {available}'
)3 unmodified lines4567789102 unmodified lines131415161718192021221723242526273 unmodified lines
[project]name = "colab-tunnel"version = "1.0.0"version = "1.1.0"description = "Утилиты для туннелирования веб-интерфейсов в Google Colab"readme = "README.md"requires-python = ">=3.10"2 unmodified lines "requests",]
[project.optional-dependencies]dev = [ "pytest>=7.0", "pytest-timeout",]
[tool.setuptools.packages.find]include = ["colab_tunnel*"]include = ["colab_tunnel*"]
[tool.pytest.ini_options]testpaths = ["tests"]timeout = 30123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""
Юнит-тесты для regex-паттернов поиска URL в выводе туннельных утилит.
Тесты не требуют сети или реальных процессов.
"""
import re
import pytest
# ── Cloudflared ────────────────────────────────────────────────────────
CF_PATTERN = r'(?P<url>https?://\S+\.trycloudflare\.com)'
@pytest.mark.parametrize('text, expected', [
(
'Visit your tunnel at https://autumn-bread-1234.trycloudflare.com',
'https://autumn-bread-1234.trycloudflare.com',
),
(
'https://my-test.trycloudflare.com is ready',
'https://my-test.trycloudflare.com',
),
])
def test_cloudflared(text: str, expected: str) -> None:
m = re.search(CF_PATTERN, text)
assert m is not None, f'Паттерн не нашёл URL в: {text!r}'
assert m.group() == expected
# ── Bore ───────────────────────────────────────────────────────────────
BORE_PATTERN = r'bore\.pub:\d+'
@pytest.mark.parametrize('text, expected', [
('INFO bore::client: listening at bore.pub:12345', 'bore.pub:12345'),
('connected to bore.pub:54321 successfully', 'bore.pub:54321'),
])
def test_bore(text: str, expected: str) -> None:
m = re.search(BORE_PATTERN, text)
assert m is not None
assert m.group() == expected
# ── MMAR ───────────────────────────────────────────────────────────────
@pytest.mark.parametrize('text, expected', [
('Tunnel at https://abc123.mmar.dev', 'https://abc123.mmar.dev'),
('http://test-tunnel.mmar.dev/ active', 'http://test-tunnel.mmar.dev/'),
])
def test_mmar(text: str, expected: str) -> None:
m = re.search(r'(?P<url>https?://\S+\.mmar\.dev)', text)
assert m is not None
assert m.group() == expected
# ── Tunnelite ──────────────────────────────────────────────────────────
def test_tunnelite() -> None:
text = 'Your public URL: https://random-words.tunnelite.com'
m = re.search(r'(?P<url>https?://\S+\.tunnelite\.com)', text)
assert m is not None
assert m.group() == 'https://random-words.tunnelite.com'
# ── Beeceptor ──────────────────────────────────────────────────────────
def test_beeceptor() -> None:
text = 'Tunnel running at https://my-endpoint.beeceptor.com'
m = re.search(r'(?P<url>https?://\S+\.beeceptor\.com)', text)
assert m is not None
assert m.group() == 'https://my-endpoint.beeceptor.com'
# ── Bore Digital ───────────────────────────────────────────────────────
def test_boredigital() -> None:
text = '| https://xyz123.bore.digital | active |'
m = re.search(r'(?P<url>https://\S+\.bore\.digital)', text)
assert m is not None
assert m.group() == 'https://xyz123.bore.digital'
# ── SSH-провайдеры ─────────────────────────────────────────────────────
@pytest.mark.parametrize('pattern, text, should_match', [
# Optimistix
(r'https://\S+\.otnl\.link',
'Forwarding from https://tunnel-abc.otnl.link', True),
# srv.us — минимум 10 символов в субдомене
(r'https://[a-z0-9]{10,}\.srv\.us/?',
'https://abcdefghij.srv.us', True),
(r'https://[a-z0-9]{10,}\.srv\.us/?',
'https://short.srv.us', False),
# Serveo
(r'https://\S+\.serveousercontent\.com',
'Forwarding from https://mytunnel.serveousercontent.com', True),
# localhost.run — admin исключён
(r'https://(?!admin\b)[a-zA-Z0-9-]+\.(?:localhost\.run|lhr\.life)',
'https://abc123.localhost.run', True),
(r'https://(?!admin\b)[a-zA-Z0-9-]+\.(?:localhost\.run|lhr\.life)',
'https://admin.localhost.run', False),
(r'https://(?!admin\b)[a-zA-Z0-9-]+\.(?:localhost\.run|lhr\.life)',
'https://my-tunnel.lhr.life', True),
])
def test_ssh_patterns(pattern: str, text: str, should_match: bool) -> None:
m = re.search(pattern, text)
if should_match:
assert m is not None, f'{pattern!r} не нашёл совпадение в {text!r}'
else:
assert m is None, f'{pattern!r} не должен совпадать с {text!r}'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""
Юнит-тесты для утилитарных функций colab_tunnel._utils.
"""
import sys
import subprocess
import pytest
from colab_tunnel._utils import is_ipv4, run, read_until_pattern
# ── is_ipv4 ────────────────────────────────────────────────────────────
@pytest.mark.parametrize('addr, expected', [
('192.168.1.1', True),
('10.0.0.1', True),
('255.255.255.255', True),
('0.0.0.0', True),
('192.168.1.256', False),
('192.168.1', False),
('not-an-ip', False),
('', False),
('999.0.0.1', False),
('1.2.3.4.5', False),
])
def test_is_ipv4(addr: str, expected: bool) -> None:
assert is_ipv4(addr) is expected
# ── run() ──────────────────────────────────────────────────────────────
def test_run_captures_output() -> None:
result = run('echo hello_world')
assert result['status_code'] == 0
assert 'hello_world' in result['output']
def test_run_nonzero_exit() -> None:
result = run('sh -c "exit 42"')
assert result['status_code'] == 42
def test_run_captures_stderr() -> None:
result = run('sh -c "echo err_msg >&2"')
assert 'err_msg' in result['output']
def test_run_timeout_returns_minus_one() -> None:
result = run('sleep 60', timeout=0.3)
assert result['status_code'] == -1
assert 'Таймаут' in result['output']
# ── read_until_pattern() ───────────────────────────────────────────────
@pytest.mark.skipif(sys.platform == 'win32', reason='select() с пайпами не поддерживается на Windows')
def test_read_until_pattern_found_in_stdout() -> None:
process = subprocess.Popen(
[sys.executable, '-c',
'import sys, time; print("https://example.com"); sys.stdout.flush(); time.sleep(60)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
url, output = read_until_pattern(process, r'https://\S+', timeout=5.0)
assert url == 'https://example.com'
assert 'https://example.com' in output
finally:
process.kill()
process.wait()
@pytest.mark.skipif(sys.platform == 'win32', reason='select() с пайпами не поддерживается на Windows')
def test_read_until_pattern_found_in_stderr() -> None:
process = subprocess.Popen(
[sys.executable, '-c',
'import sys, time; sys.stderr.write("https://stderr.example.com\\n"); sys.stderr.flush(); time.sleep(60)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
url, _ = read_until_pattern(
process, r'https://\S+', timeout=5.0, read_from_stderr=True
)
assert 'https://stderr.example.com' in url
finally:
process.kill()
process.wait()
@pytest.mark.skipif(sys.platform == 'win32', reason='select() с пайпами не поддерживается на Windows')
def test_read_until_pattern_raises_on_timeout() -> None:
process = subprocess.Popen(
[sys.executable, '-c', 'import time; time.sleep(60)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
with pytest.raises(RuntimeError, match='URL не найден'):
read_until_pattern(process, r'https://\S+', timeout=0.5)
finally:
process.kill()
process.wait()
@pytest.mark.skipif(sys.platform == 'win32', reason='select() с пайпами не поддерживается на Windows')
def test_read_until_pattern_raises_when_process_exits_without_url() -> None:
process = subprocess.Popen(
[sys.executable, '-c', 'print("no url here at all")'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
with pytest.raises(RuntimeError):
read_until_pattern(process, r'https://\S+', timeout=5.0)
@pytest.mark.skipif(sys.platform == 'win32', reason='select() с пайпами не поддерживается на Windows')
def test_read_both_streams_finds_url_in_either() -> None:
"""URL в stderr должен находиться при read_both_streams=True."""
process = subprocess.Popen(
[sys.executable, '-c',
'import sys, time; sys.stderr.write("https://both.example.com\\n"); sys.stderr.flush(); time.sleep(60)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
url, _ = read_until_pattern(
process, r'https://\S+', timeout=5.0, read_both_streams=True
)
assert 'https://both.example.com' in url
finally:
process.kill()
process.wait()colab_tunnel/__init__.py+85-28
colab_tunnel/_config.py+3-2
colab_tunnel/_diagnostics.pyAdded+237
colab_tunnel/_logger.pyAdded+16
colab_tunnel/_registry.pyAdded+25
colab_tunnel/_ssh.py+114-115
colab_tunnel/_tunnels.py+188-67
colab_tunnel/_utils.py+419-128
pyproject.toml+12-2
tests/__init__.pyAdded
tests/test_regex.pyAdded+105
tests/test_utils.pyAdded+133