491 lines
18 KiB
Python
491 lines
18 KiB
Python
from __future__ import annotations
|
|
|
|
import ftplib
|
|
import io
|
|
import posixpath
|
|
import socket
|
|
import stat
|
|
from collections.abc import Callable
|
|
from datetime import datetime
|
|
from decimal import Decimal
|
|
from typing import Any, TypeVar
|
|
|
|
import paramiko
|
|
import pymysql
|
|
|
|
import main
|
|
|
|
from .config import Settings
|
|
|
|
CONNECT_TIMEOUT_SECONDS = 15
|
|
TRANSFER_TIMEOUT_SECONDS = 120
|
|
FTP_UNSUPPORTED_COMMAND_CODES = ("500", "502")
|
|
INSERT_BATCH_SIZE = 1000
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
def entry(directory: str, name: str, is_dir: bool, size: int) -> dict[str, object]:
|
|
return {"name": name, "path": posixpath.join(directory, name), "is_dir": is_dir, "size": size}
|
|
|
|
|
|
class FtpStorage:
|
|
def __init__(
|
|
self,
|
|
host: str,
|
|
port: int,
|
|
username: str,
|
|
password: str,
|
|
encoding: str = "utf-8",
|
|
passive: bool = True,
|
|
factory: Callable[[], ftplib.FTP] | None = None,
|
|
) -> None:
|
|
self.host = host
|
|
self.port = port
|
|
self.username = username or "anonymous"
|
|
self.password = password
|
|
self.encoding = encoding
|
|
self.passive = passive
|
|
self.factory = factory or ftplib.FTP
|
|
self._ftp: ftplib.FTP | None = None
|
|
|
|
def list_dir(self, path: str) -> list[dict[str, object]]:
|
|
def action(ftp: ftplib.FTP) -> list[dict[str, object]]:
|
|
try:
|
|
return [
|
|
entry(path, name, facts.get("type") == "dir", _safe_int(facts.get("size", "")))
|
|
for name, facts in ftp.mlsd(path)
|
|
if name not in (".", "..") and facts.get("type", "file") not in ("cdir", "pdir")
|
|
]
|
|
except ftplib.error_perm as exc:
|
|
if str(exc)[:3] not in FTP_UNSUPPORTED_COMMAND_CODES:
|
|
raise
|
|
lines: list[str] = []
|
|
ftp.retrlines(f"LIST {path}", lines.append)
|
|
parsed = (parse_list_line(line) for line in lines)
|
|
return [entry(path, name, is_dir, size) for name, is_dir, size in (item for item in parsed if item)]
|
|
|
|
return self._call("list", path, action)
|
|
|
|
def read_bytes(self, path: str) -> bytes:
|
|
def action(ftp: ftplib.FTP) -> bytes:
|
|
buffer = io.BytesIO()
|
|
ftp.retrbinary(f"RETR {path}", buffer.write)
|
|
return buffer.getvalue()
|
|
|
|
return self._call("download", path, action)
|
|
|
|
def make_dir(self, path: str) -> None:
|
|
self._call("mkdir", path, lambda ftp: ftp.mkd(path))
|
|
|
|
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
|
|
path = posixpath.join(directory, filename)
|
|
self._call("upload", path, lambda ftp: ftp.storbinary(f"STOR {path}", io.BytesIO(payload)))
|
|
return path
|
|
|
|
def delete(self, path: str) -> None:
|
|
self._call("delete", path, lambda ftp: self._remove(ftp, path))
|
|
|
|
def close(self) -> None:
|
|
ftp, self._ftp = self._ftp, None
|
|
if ftp is None:
|
|
return
|
|
try:
|
|
ftp.quit()
|
|
except (OSError, EOFError, ftplib.Error):
|
|
try:
|
|
ftp.close()
|
|
except OSError:
|
|
pass
|
|
|
|
def _connect(self) -> ftplib.FTP:
|
|
if self._ftp is None:
|
|
ftp = self.factory()
|
|
ftp.encoding = self.encoding
|
|
try:
|
|
ftp.connect(self.host, self.port, timeout=CONNECT_TIMEOUT_SECONDS)
|
|
ftp.login(self.username, self.password)
|
|
ftp.set_pasv(self.passive)
|
|
if ftp.sock is not None:
|
|
ftp.sock.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
|
except BaseException:
|
|
try:
|
|
ftp.close()
|
|
except OSError:
|
|
pass
|
|
raise
|
|
self._ftp = ftp
|
|
return self._ftp
|
|
|
|
def _remove(self, ftp: ftplib.FTP, path: str) -> None:
|
|
children = self._children(ftp, path)
|
|
if children is None:
|
|
ftp.delete(path)
|
|
return
|
|
for name, is_dir in children:
|
|
child = posixpath.join(path, name)
|
|
if is_dir:
|
|
self._remove(ftp, child)
|
|
else:
|
|
ftp.delete(child)
|
|
ftp.rmd(path)
|
|
|
|
@staticmethod
|
|
def _children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
|
|
try:
|
|
listed = list(ftp.mlsd(path))
|
|
except ftplib.error_perm as exc:
|
|
if str(exc).startswith(FTP_UNSUPPORTED_COMMAND_CODES):
|
|
return FtpStorage._nlst_children(ftp, path)
|
|
return None
|
|
result: list[tuple[str, bool]] = []
|
|
for name, facts in listed:
|
|
if name in {".", ".."}:
|
|
continue
|
|
result.append((name, facts.get("type") == "dir"))
|
|
return result
|
|
|
|
@staticmethod
|
|
def _nlst_children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
|
|
try:
|
|
names = ftp.nlst(path)
|
|
except ftplib.error_perm:
|
|
return None
|
|
children: list[tuple[str, bool]] = []
|
|
for name in names:
|
|
base = posixpath.basename(name.rstrip("/"))
|
|
if base in {"", ".", ".."}:
|
|
continue
|
|
child = name if name.startswith("/") else posixpath.join(path, base)
|
|
try:
|
|
ftp.cwd(child)
|
|
ftp.cwd(path)
|
|
children.append((base, True))
|
|
except ftplib.error_perm:
|
|
children.append((base, False))
|
|
return children
|
|
|
|
def _call(self, operation: str, path: str, action: Callable[[ftplib.FTP], T]) -> T:
|
|
last_error: BaseException | None = None
|
|
for _ in range(2):
|
|
try:
|
|
return action(self._connect())
|
|
except ftplib.error_perm as exc:
|
|
raise main.ProcessingError(f"FTP {operation} {path} failed: {exc}") from exc
|
|
except (ftplib.Error, OSError, EOFError) as exc:
|
|
last_error = exc
|
|
self.close()
|
|
raise main.ProcessingError(f"FTP {operation} {path} failed: {last_error}")
|
|
|
|
|
|
class SftpStorage:
|
|
def __init__(self, host: str, port: int, username: str, password: str) -> None:
|
|
self.host = host
|
|
self.port = port
|
|
self.username = username
|
|
self.password = password
|
|
self._transport: paramiko.Transport | None = None
|
|
self._sftp: paramiko.SFTPClient | None = None
|
|
|
|
def list_dir(self, path: str) -> list[dict[str, object]]:
|
|
attrs = self._call("list", path, lambda sftp: sftp.listdir_attr(path))
|
|
return [entry(path, item.filename, stat.S_ISDIR(item.st_mode or 0), int(item.st_size or 0)) for item in attrs]
|
|
|
|
def read_bytes(self, path: str) -> bytes:
|
|
def action(sftp: paramiko.SFTPClient) -> bytes:
|
|
buffer = io.BytesIO()
|
|
sftp.getfo(path, buffer)
|
|
return buffer.getvalue()
|
|
|
|
return self._call("download", path, action)
|
|
|
|
def make_dir(self, path: str) -> None:
|
|
self._call("mkdir", path, lambda sftp: sftp.mkdir(path))
|
|
|
|
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
|
|
path = posixpath.join(directory, filename)
|
|
self._call("upload", path, lambda sftp: sftp.putfo(io.BytesIO(payload), path))
|
|
return path
|
|
|
|
def delete(self, path: str) -> None:
|
|
self._call("delete", path, lambda sftp: self._remove(sftp, path))
|
|
|
|
def close(self) -> None:
|
|
transport, self._transport, self._sftp = self._transport, None, None
|
|
if transport is not None:
|
|
try:
|
|
transport.close()
|
|
except (OSError, EOFError, paramiko.SSHException):
|
|
pass
|
|
|
|
def _connect(self) -> paramiko.SFTPClient:
|
|
if self._sftp is None:
|
|
sock = socket.create_connection((self.host, self.port), timeout=CONNECT_TIMEOUT_SECONDS)
|
|
transport = paramiko.Transport(sock)
|
|
try:
|
|
transport.banner_timeout = CONNECT_TIMEOUT_SECONDS
|
|
transport.connect(username=self.username, password=self.password)
|
|
sftp = paramiko.SFTPClient.from_transport(transport)
|
|
if sftp is None:
|
|
raise paramiko.SSHException("SFTP channel unavailable")
|
|
channel = sftp.get_channel()
|
|
if channel is not None:
|
|
channel.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
|
except BaseException:
|
|
transport.close()
|
|
raise
|
|
self._transport, self._sftp = transport, sftp
|
|
return self._sftp
|
|
|
|
def _remove(self, sftp: paramiko.SFTPClient, path: str) -> None:
|
|
try:
|
|
attrs = sftp.stat(path)
|
|
except FileNotFoundError:
|
|
return
|
|
if stat.S_ISDIR(attrs.st_mode or 0):
|
|
for item in sftp.listdir_attr(path):
|
|
self._remove(sftp, posixpath.join(path, item.filename))
|
|
sftp.rmdir(path)
|
|
return
|
|
sftp.remove(path)
|
|
|
|
def _call(self, operation: str, path: str, action: Callable[[paramiko.SFTPClient], T]) -> T:
|
|
last_error: BaseException | None = None
|
|
for _ in range(2):
|
|
try:
|
|
return action(self._connect())
|
|
except (FileNotFoundError, PermissionError, paramiko.AuthenticationException) as exc:
|
|
raise main.ProcessingError(f"SFTP {operation} {path} failed: {exc}") from exc
|
|
except (OSError, EOFError, paramiko.SSHException) as exc:
|
|
last_error = exc
|
|
self.close()
|
|
raise main.ProcessingError(f"SFTP {operation} {path} failed: {last_error}")
|
|
|
|
|
|
class MySqlSummaryStore:
|
|
def __init__(
|
|
self,
|
|
host: str,
|
|
port: int,
|
|
username: str,
|
|
password: str,
|
|
database: str = main.DATABASE_NAME,
|
|
table: str = main.DATABASE_TABLE,
|
|
connect: Callable[..., Any] | None = None,
|
|
) -> None:
|
|
self.host = host
|
|
self.port = port
|
|
self.username = username
|
|
self.password = password
|
|
self.database = main.sql_identifier(database, "database")
|
|
self.table = main.sql_identifier(table, "table")
|
|
self._connect = connect or pymysql.connect
|
|
self._schema_ready = False
|
|
|
|
def latest_metric_time(self) -> datetime | None:
|
|
with self._connection() as connection, connection.cursor() as cursor:
|
|
cursor.execute(f"SELECT MAX(metric_time) FROM `{self.table}`")
|
|
row = cursor.fetchone()
|
|
value = row[0] if row else None
|
|
if value is None:
|
|
return None
|
|
return value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
|
|
|
|
def replace_latest(self, rows: list[dict[str, str]]) -> dict[str, object]:
|
|
metric_time = main.batch_metric_time(rows)
|
|
main.ensure_not_newer(self.latest_metric_time(), metric_time)
|
|
params = [main.summary_row_params(row) for row in rows]
|
|
metric_text = metric_time.strftime("%Y-%m-%d %H:%M:%S")
|
|
placeholders = ", ".join(["%s"] * len(main.SUMMARY_HEADER))
|
|
insert_sql = f"INSERT INTO `{self.table}` ({', '.join(main.SUMMARY_HEADER)}) VALUES ({placeholders})"
|
|
with self._connection() as connection:
|
|
try:
|
|
with connection.cursor() as cursor:
|
|
refreshed = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time = %s", (metric_text,))
|
|
inserted = 0
|
|
for start in range(0, len(params), INSERT_BATCH_SIZE):
|
|
inserted += cursor.executemany(insert_sql, params[start : start + INSERT_BATCH_SIZE]) or 0
|
|
deleted = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time <> %s", (metric_text,))
|
|
connection.commit()
|
|
except pymysql.MySQLError as exc:
|
|
connection.rollback()
|
|
raise main.ProcessingError(f"MySQL write failed: {exc}") from exc
|
|
return {
|
|
"enabled": True,
|
|
"table": self.table,
|
|
"metric_time": metric_text,
|
|
"inserted_rows": int(inserted),
|
|
"refreshed_rows": int(refreshed),
|
|
"old_rows_deleted": int(deleted),
|
|
}
|
|
|
|
def rows_for_time(self, metric_time: datetime) -> list[dict[str, str]]:
|
|
sql = (
|
|
f"SELECT {', '.join(main.SUMMARY_HEADER)} FROM `{self.table}` "
|
|
"WHERE metric_time = %s ORDER BY cgi, cell_name"
|
|
)
|
|
with self._connection() as connection, connection.cursor() as cursor:
|
|
cursor.execute(sql, (metric_time.strftime("%Y-%m-%d %H:%M:%S"),))
|
|
records = cursor.fetchall()
|
|
return [
|
|
{column: mysql_cell(value) for column, value in zip(main.SUMMARY_HEADER, record, strict=True)}
|
|
for record in records
|
|
]
|
|
|
|
def select(self, sql: str, limit: int) -> list[dict[str, object]]:
|
|
try:
|
|
with self._connection() as connection, connection.cursor() as cursor:
|
|
cursor.execute(sql)
|
|
names = [column[0] for column in cursor.description or ()]
|
|
records = cursor.fetchmany(max(1, limit))
|
|
except pymysql.MySQLError as exc:
|
|
raise main.ProcessingError(f"MySQL query failed: {exc}") from exc
|
|
return [dict(zip(names, record, strict=True)) for record in records]
|
|
|
|
def _connection(self) -> Any:
|
|
if not self._schema_ready:
|
|
self._ensure_schema()
|
|
return _Closing(self._open(database=self.database))
|
|
|
|
def _ensure_schema(self) -> None:
|
|
connection = self._open(database=None)
|
|
try:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute(main.create_database_sql(self.database))
|
|
cursor.execute(f"USE `{self.database}`")
|
|
cursor.execute(main.create_table_sql(self.table))
|
|
cursor.execute(
|
|
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
|
|
(self.database, self.table),
|
|
)
|
|
existing = {str(row[0]) for row in cursor.fetchall()}
|
|
for statement in main.column_migration_sql(self.table, existing):
|
|
cursor.execute(statement)
|
|
connection.commit()
|
|
except pymysql.MySQLError as exc:
|
|
raise main.ProcessingError(f"MySQL schema check failed: {exc}") from exc
|
|
finally:
|
|
connection.close()
|
|
self._schema_ready = True
|
|
|
|
def _open(self, database: str | None) -> Any:
|
|
try:
|
|
return self._connect(
|
|
host=self.host,
|
|
port=self.port,
|
|
user=self.username,
|
|
password=self.password,
|
|
database=database,
|
|
charset="utf8mb4",
|
|
autocommit=False,
|
|
connect_timeout=CONNECT_TIMEOUT_SECONDS,
|
|
read_timeout=TRANSFER_TIMEOUT_SECONDS,
|
|
write_timeout=TRANSFER_TIMEOUT_SECONDS,
|
|
)
|
|
except pymysql.MySQLError as exc:
|
|
raise main.ProcessingError(f"MySQL connection failed: {exc}") from exc
|
|
|
|
|
|
class _Closing:
|
|
def __init__(self, connection: Any) -> None:
|
|
self.connection = connection
|
|
|
|
def __enter__(self) -> Any:
|
|
return self.connection
|
|
|
|
def __exit__(self, *exc_info: object) -> None:
|
|
self.connection.close()
|
|
|
|
|
|
def mysql_cell(value: object) -> str:
|
|
if isinstance(value, Decimal):
|
|
text = format(value, "f")
|
|
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
return main.normalize_cell(value)
|
|
|
|
|
|
def build_storage(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
|
if settings.storage_mode == "metrix":
|
|
assert client is not None
|
|
return main.MetrixStorage(client, settings.metrix_storage_id)
|
|
if settings.storage_mode == "sftp":
|
|
return SftpStorage(settings.remote_host, settings.remote_port, settings.remote_username, settings.remote_password)
|
|
return FtpStorage(
|
|
settings.remote_host,
|
|
settings.remote_port,
|
|
settings.remote_username,
|
|
settings.remote_password,
|
|
settings.ftp_encoding,
|
|
settings.ftp_passive,
|
|
)
|
|
|
|
|
|
def build_store(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
|
if settings.database_mode == "metrix":
|
|
assert client is not None
|
|
return main.ApiSummaryStore(client, settings.metrix_database_id, settings.database_name, settings.table_name)
|
|
return MySqlSummaryStore(
|
|
settings.mysql_host,
|
|
settings.mysql_port,
|
|
settings.mysql_username,
|
|
settings.mysql_password,
|
|
settings.database_name,
|
|
settings.table_name,
|
|
)
|
|
|
|
|
|
def build_client(settings: Settings) -> main.MetrixApiClient | None:
|
|
if not settings.uses_metrix_api():
|
|
return None
|
|
return main.MetrixApiClient(settings.metrix_url, settings.metrix_token)
|
|
|
|
|
|
def close_quietly(resource: object) -> None:
|
|
close = getattr(resource, "close", None)
|
|
if callable(close):
|
|
close()
|
|
|
|
|
|
def check_storage(settings: Settings) -> dict[str, object]:
|
|
storage = build_storage(settings, build_client(settings))
|
|
try:
|
|
source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories)
|
|
dates = source.date_directories()
|
|
return {"count": len(dates), "latest": str(dates[-1]["name"]) if dates else "-"}
|
|
finally:
|
|
close_quietly(storage)
|
|
|
|
|
|
def check_database(settings: Settings) -> dict[str, object]:
|
|
store = build_store(settings, build_client(settings))
|
|
latest = store.latest_metric_time()
|
|
return {"latest": latest.strftime("%Y-%m-%d %H:%M:%S") if latest else "-"}
|
|
|
|
|
|
def parse_list_line(line: str) -> tuple[str, bool, int] | None:
|
|
text = line.rstrip()
|
|
if not text or text.startswith("total "):
|
|
return None
|
|
if text[0] in "dl-" and len(text) >= 10:
|
|
parts = text.split(maxsplit=8)
|
|
if len(parts) < 9:
|
|
return None
|
|
name = parts[8]
|
|
if text[0] == "l" and " -> " in name:
|
|
name = name.split(" -> ", 1)[0]
|
|
if name in (".", ".."):
|
|
return None
|
|
return name, text[0] == "d", _safe_int(parts[4])
|
|
parts = text.split(maxsplit=3)
|
|
if len(parts) == 4 and parts[0].count("-") == 2:
|
|
is_dir = parts[2] == "<DIR>"
|
|
return parts[3], is_dir, 0 if is_dir else _safe_int(parts[2])
|
|
return None
|
|
|
|
|
|
def _safe_int(value: str) -> int:
|
|
try:
|
|
return int(value)
|
|
except ValueError:
|
|
return 0
|