-
Notifications
You must be signed in to change notification settings - Fork 121
/
main.py
122 lines (98 loc) · 3.86 KB
/
main.py
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
# std
import argparse
import logging
import signal
import subprocess
import time
from pathlib import Path
from typing import Tuple
# lib
import confuse
# project
from src.chia_log.handlers.daily_stats.stats_manager import StatsManager
from src.chia_log.log_consumer import create_log_consumer_from_config
from src.chia_log.log_handler import LogHandler
from src.util import is_win_platform
from src.notifier.keep_alive_monitor import KeepAliveMonitor
from src.notifier.notify_manager import NotifyManager
def parse_arguments() -> Tuple[argparse.ArgumentParser, argparse.Namespace]:
parser = argparse.ArgumentParser(
description="ChiaFarmWatch: Watch your crops " "with a piece in mind for the yield."
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--config", type=str, help="path to config.yaml")
group.add_argument("--version", action="store_true")
return parser, parser.parse_args()
def get_log_level(log_level: str) -> int:
if log_level == "CRITICAL":
return logging.CRITICAL
if log_level == "ERROR":
return logging.ERROR
if log_level == "WARNING":
return logging.WARNING
if log_level == "INFO":
return logging.INFO
if log_level == "DEBUG":
return logging.DEBUG
logging.warning(f"Unsupported log level: {log_level}. Fallback to INFO level.")
return logging.INFO
def init(config: confuse.core.Configuration):
log_level = get_log_level(config["log_level"].get())
logging.basicConfig(
format="[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)",
level=log_level,
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.info(f"Starting Chiadog ({version()})")
# Create log consumer based on provided configuration
chia_logs_config = config["chia_logs"]
log_consumer = create_log_consumer_from_config(chia_logs_config)
if log_consumer is None:
exit(0)
# Keep a reference here so we can stop the thread
keep_alive_monitor = KeepAliveMonitor(config=config)
# Notify manager is responsible for the lifecycle of all notifiers
notify_manager = NotifyManager(config=config, keep_alive_monitor=keep_alive_monitor)
# Stats manager accumulates stats over 24 hours and sends a summary each day
stats_manager = StatsManager(config=config["daily_stats"], notify_manager=notify_manager)
# Link stuff up in the log handler
# Pipeline: Consume -> Handle -> Notify
LogHandler(config=config, log_consumer=log_consumer, notify_manager=notify_manager, stats_manager=stats_manager)
def interrupt(signal_number, frame):
if signal_number == signal.SIGINT:
logging.info("Received interrupt. Stopping...")
log_consumer.stop()
keep_alive_monitor.stop()
stats_manager.stop()
exit(0)
signal.signal(signal.SIGINT, interrupt)
if is_win_platform():
while True:
try:
time.sleep(5)
except IOError:
pass
else:
signal.pause()
def version():
try:
command_args = ["git", "describe", "--tags"]
f = subprocess.Popen(command_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = f.communicate()
return stdout.decode(encoding="utf-8").rstrip()
except (OSError, subprocess.CalledProcessError):
return "unknown"
if __name__ == "__main__":
# Parse config and configure logger
parser, args = parse_arguments()
# init sane config defaults
source_path = Path(__file__).resolve()
source_dir = source_path.parent
config = confuse.Configuration("chiadog", __name__)
config.set_file(source_dir / "src/default_config.yaml")
# Override with given config
if args.config:
config.set_file(Path(args.config))
init(config)
elif args.version:
print(version())