Version2.0Commit
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
"""Точка входа: жизненный цикл PySpark Structured Streaming приложения."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# --- Windows: настройка Hadoop ДО импорта pyspark ---
|
||||
import os
|
||||
|
||||
if os.name == "nt": # только на Windows
|
||||
_hadoop_home = os.environ.get("HADOOP_HOME", r"C:\hadoop")
|
||||
os.environ["HADOOP_HOME"] = _hadoop_home
|
||||
os.environ["hadoop.home.dir"] = _hadoop_home
|
||||
_bin = os.path.join(_hadoop_home, "bin")
|
||||
os.environ["Path"] = _bin + os.pathsep + os.environ.get("Path", "")
|
||||
# ----------------------------------------------------
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from pyspark.sql import SparkSession
|
||||
from pyspark.sql.streaming import StreamingQuery
|
||||
|
||||
from app.config import AppConfig
|
||||
from app.monitoring.streaming_monitor import StreamingMonitor
|
||||
from app.processing.aggregator import build_aggregation
|
||||
from app.processing.parser import filter_valid_logs, parse_logs
|
||||
from app.sources.socket_source import read_socket_stream
|
||||
|
||||
logger = logging.getLogger("pyspark-log-stream")
|
||||
|
||||
|
||||
def configure_logging(level: str) -> None:
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, level, logging.INFO),
|
||||
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
)
|
||||
|
||||
|
||||
def build_spark(config: AppConfig) -> SparkSession:
|
||||
"""Создаёт SparkSession с настройками из конфигурации."""
|
||||
spark = (
|
||||
SparkSession.builder.appName(config.spark_app_name)
|
||||
.master(config.spark_master)
|
||||
.config("spark.sql.session.timeZone", config.spark_timezone)
|
||||
.config("spark.sql.streaming.metricsEnabled", "true")
|
||||
.config("spark.sql.shuffle.partitions", str(config.shuffle_partitions))
|
||||
.getOrCreate()
|
||||
)
|
||||
spark.sparkContext.setLogLevel("WARN")
|
||||
return spark
|
||||
|
||||
|
||||
def _output_mode_for(aggregation_mode: str) -> str:
|
||||
"""Сопоставление режима агрегации → outputMode Structured Streaming.
|
||||
|
||||
cumulative и status требуют complete (полная таблица на каждом батче).
|
||||
windowed работает только с append (после финализации окна watermark'ом).
|
||||
"""
|
||||
if aggregation_mode in ("cumulative", "status"):
|
||||
return "complete"
|
||||
if aggregation_mode == "windowed":
|
||||
return "append"
|
||||
raise ValueError(f"Неизвестный AGGREGATION_MODE: {aggregation_mode}")
|
||||
|
||||
|
||||
def build_query(valid_logs, config: AppConfig) -> StreamingQuery:
|
||||
"""Собирает pipeline и запускает streaming query."""
|
||||
aggregated = build_aggregation(valid_logs, config)
|
||||
output_mode = _output_mode_for(config.aggregation_mode)
|
||||
|
||||
writer = (
|
||||
aggregated.writeStream.format("console")
|
||||
.outputMode(output_mode)
|
||||
.trigger(processingTime=config.processing_time)
|
||||
.option("numRows", config.console_num_rows)
|
||||
.option("truncate", str(config.console_truncate).lower())
|
||||
.option("checkpointLocation", config.checkpoint_path)
|
||||
)
|
||||
|
||||
query = writer.start()
|
||||
logger.info(
|
||||
"StreamingQuery запущен: aggregation_mode=%s output_mode=%s trigger=%s",
|
||||
config.aggregation_mode,
|
||||
output_mode,
|
||||
config.processing_time,
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def install_signal_handlers(query: StreamingQuery) -> None:
|
||||
"""Корректное завершение по SIGINT/SIGTERM."""
|
||||
|
||||
def _handler(signum, _frame): # noqa: ANN001
|
||||
logger.info("Получен сигнал %s, останавливаю StreamingQuery...", signum)
|
||||
query.stop()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, _handler)
|
||||
signal.signal(signal.SIGTERM, _handler)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
config = AppConfig()
|
||||
configure_logging(config.log_level)
|
||||
|
||||
try:
|
||||
config.validate()
|
||||
except Exception as exc:
|
||||
logger.error("Конфигурация не прошла валидацию: %s", exc)
|
||||
return 2
|
||||
|
||||
logger.info(
|
||||
"Конфигурация: aggregation_mode=%s checkpoint_path=%s (существует=%s) "
|
||||
"socket=%s:%s shuffle_partitions=%s",
|
||||
config.aggregation_mode,
|
||||
config.checkpoint_path,
|
||||
Path(config.checkpoint_path).exists(),
|
||||
config.socket_host,
|
||||
config.socket_port,
|
||||
config.shuffle_partitions,
|
||||
)
|
||||
|
||||
spark = build_spark(config)
|
||||
|
||||
raw_stream = read_socket_stream(spark, config)
|
||||
parsed = parse_logs(raw_stream)
|
||||
valid_logs = filter_valid_logs(parsed)
|
||||
|
||||
query = build_query(valid_logs, config)
|
||||
install_signal_handlers(query)
|
||||
|
||||
monitor = StreamingMonitor(query, interval_seconds=10.0)
|
||||
try:
|
||||
monitor.run_loop()
|
||||
finally:
|
||||
if query.isActive:
|
||||
query.stop()
|
||||
spark.stop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user