|
1 | 1 | import asyncio |
| 2 | +import logging |
2 | 3 | import sys |
3 | | -import time |
4 | 4 |
|
5 | | -import aiohttp |
6 | 5 | import psutil |
7 | 6 | import pyfiglet |
8 | 7 | from colorama import Fore |
9 | 8 |
|
10 | | -from modules import cloudflare, config, webhook, redis |
| 9 | +from modules.config import get_config, ConfigNotFoundError |
| 10 | +from modules.cloudflare import Cloudflare |
| 11 | +from modules.webhook import Webhook |
| 12 | +from modules.redis import RedisCache |
11 | 13 |
|
12 | | -config = config.Config() |
13 | | -cloudflare = cloudflare.Cloudflare() |
14 | | -webhook = webhook.Webhook() |
15 | | -redis = redis.RedisCache() |
| 14 | +logger = logging.getLogger("noattack") |
16 | 15 |
|
17 | 16 | PREFIX = f"{Fore.RED}[\033[38;5;208mNoAttack{Fore.RED}]{Fore.RESET} " |
18 | 17 |
|
19 | 18 |
|
20 | | -def get_network_speed(duration=1): |
21 | | - """ |
22 | | - Measure network speed over a given duration. |
23 | | - """ |
24 | | - io_counters_start = psutil.net_io_counters() |
| 19 | +async def get_network_speed(): |
| 20 | + """Measure incoming and outgoing traffic in MB/s over 1 second.""" |
| 21 | + snap1 = psutil.net_io_counters() |
| 22 | + await asyncio.sleep(1) |
| 23 | + snap2 = psutil.net_io_counters() |
| 24 | + recv = (snap2.bytes_recv - snap1.bytes_recv) / 1024 / 1024 |
| 25 | + sent = (snap2.bytes_sent - snap1.bytes_sent) / 1024 / 1024 |
| 26 | + return recv, sent |
25 | 27 |
|
26 | | - time.sleep(duration) |
27 | 28 |
|
28 | | - io_counters_end = psutil.net_io_counters() |
| 29 | +async def handle_zone(cloudflare, webhook, zone_id, under_attack): |
| 30 | + """Activate or deactivate Under Attack mode for a zone if the state needs to change.""" |
| 31 | + zone_name = await cloudflare.get_zone(zone_id) |
| 32 | + if zone_name is None: |
| 33 | + return |
29 | 34 |
|
30 | | - bytes_received = io_counters_end.bytes_recv - io_counters_start.bytes_recv |
31 | | - bytes_sent = io_counters_end.bytes_sent - io_counters_start.bytes_sent |
| 35 | + currently_attacking = await cloudflare.get_zone_under_attack(zone_id) |
| 36 | + if currently_attacking is None: |
| 37 | + return |
32 | 38 |
|
33 | | - mb_received_per_sec = bytes_received / duration / 1024 / 1024 |
34 | | - mb_sent_per_sec = bytes_sent / duration / 1024 / 1024 |
35 | | - return mb_received_per_sec, mb_sent_per_sec |
| 39 | + if under_attack and not currently_attacking: |
| 40 | + logger.info("Activating Under Attack Mode for %s", zone_name) |
| 41 | + if await cloudflare.set_zone_under_attack(zone_id, True): |
| 42 | + await webhook.send("Under Attack Activated", zone_name, color=0xFF0000) |
| 43 | + |
| 44 | + elif not under_attack and currently_attacking: |
| 45 | + logger.info("Deactivating Under Attack Mode for %s", zone_name) |
| 46 | + if await cloudflare.set_zone_under_attack(zone_id, False): |
| 47 | + await webhook.send("Under Attack Deactivated", zone_name, color=0x00FF00) |
36 | 48 |
|
37 | 49 |
|
38 | 50 | async def main(): |
39 | | - """ |
40 | | - Main function to monitor network speed and manage Cloudflare zones. |
41 | | - """ |
42 | | - if not config.get("CLOUDFLARE", "ZONE_IDS"): |
43 | | - print(f"{PREFIX}No Cloudflare zones found.") |
| 51 | + """Main monitoring loop.""" |
| 52 | + config = get_config() |
| 53 | + cloudflare = Cloudflare() |
| 54 | + webhook = Webhook() |
| 55 | + redis_cache = RedisCache() |
| 56 | + |
| 57 | + zone_ids = config.get("CLOUDFLARE", "ZONE_IDS") |
| 58 | + if not zone_ids: |
| 59 | + logger.critical("No zone IDs configured.") |
44 | 60 | sys.exit(1) |
45 | 61 |
|
46 | | - if await redis.check(): |
47 | | - print(f"{PREFIX}Connected to Redis.") |
48 | | - else: |
49 | | - print(f"{PREFIX}Failed to connect to Redis.") |
| 62 | + if not await redis_cache.check(): |
| 63 | + logger.critical("Cannot connect to Redis.") |
50 | 64 | sys.exit(1) |
51 | 65 |
|
52 | | - while True: |
53 | | - try: |
54 | | - if await redis.is_under_attack(): |
55 | | - print(f"{PREFIX}Under Attack mode is active.") |
56 | | - else: |
57 | | - mb_received_per_sec, mb_sent_per_sec = get_network_speed() |
58 | | - print( |
59 | | - f"{PREFIX}Received: {mb_received_per_sec:.2f} MB/s, " |
60 | | - f"Sent: {mb_sent_per_sec:.2f} MB/s" |
61 | | - ) |
62 | | - |
63 | | - if mb_received_per_sec > config.get("SETTINGS", "MAX_INCOMING_TRAFFIC_MB"): |
64 | | - print( |
65 | | - f"{PREFIX}Incoming traffic exceeded " |
66 | | - f"{config.get('SETTINGS', 'MAX_INCOMING_TRAFFIC_MB')} MB/s" |
67 | | - ) |
68 | | - |
69 | | - for zone_id in config.get("CLOUDFLARE", "ZONE_IDS"): |
70 | | - await handle_zone(zone_id, True) |
71 | | - |
72 | | - await redis.set_under_attack() |
73 | | - |
74 | | - else: |
75 | | - print(f"{PREFIX}Incoming traffic is normal.") |
76 | | - for zone_id in config.get("CLOUDFLARE", "ZONE_IDS"): |
77 | | - await handle_zone(zone_id, False) |
78 | | - |
79 | | - except (aiohttp.ClientError, ValueError) as e: |
80 | | - print(f"{PREFIX}Error encountered in main loop: {e}") |
| 66 | + check_interval = config.get("SETTINGS", "CHECK_INTERVAL") or 60 |
| 67 | + threshold = config.get("SETTINGS", "MAX_INCOMING_TRAFFIC_MB") |
| 68 | + logger.info("Started | interval: %ds | threshold: %s MB/s | zones: %d", |
| 69 | + check_interval, threshold, len(zone_ids)) |
81 | 70 |
|
82 | | - await asyncio.sleep(config.get("SETTINGS", "CHECK_INTERVAL") or 60) |
83 | | - |
84 | | - |
85 | | -async def handle_zone(zone_id, under_attack): |
86 | | - """ |
87 | | - Handle Cloudflare zone based on the traffic condition. |
88 | | - """ |
89 | 71 | try: |
90 | | - zone = await cloudflare.get_zone(zone_id) |
91 | | - zone_name = zone["result"]["name"] |
92 | | - |
93 | | - under_attack_mode = await cloudflare.get_zone_under_attack(zone_id) |
94 | | - if under_attack and under_attack_mode["result"]["value"] != "under_attack": |
95 | | - print(f"{PREFIX}Activating Under Attack Mode for {zone_name}") |
96 | | - await set_zone_under_attack(zone_id, zone_name, True) |
97 | | - elif not under_attack and under_attack_mode["result"]["value"] != "essentially_off": |
98 | | - print(f"{PREFIX}Deactivating Under Attack Mode for {zone_name}") |
99 | | - await set_zone_under_attack(zone_id, zone_name, False) |
100 | | - |
101 | | - except (aiohttp.ClientError, ValueError) as e: |
102 | | - print(f"{PREFIX}Error handling Cloudflare zone {zone_id}: {e}") |
| 72 | + while True: |
| 73 | + try: |
| 74 | + if await redis_cache.is_under_attack(): |
| 75 | + remaining = await redis_cache.ttl() |
| 76 | + logger.info("Cooldown active, %ds remaining", remaining) |
| 77 | + else: |
| 78 | + recv, sent = await get_network_speed() |
| 79 | + logger.info("Traffic – recv: %.2f MB/s sent: %.2f MB/s", recv, sent) |
103 | 80 |
|
| 81 | + if recv > threshold: |
| 82 | + logger.warning("Traffic %.2f MB/s exceeded threshold %s MB/s", |
| 83 | + recv, threshold) |
| 84 | + for zone_id in zone_ids: |
| 85 | + await handle_zone(cloudflare, webhook, zone_id, True) |
| 86 | + await redis_cache.set_under_attack() |
| 87 | + else: |
| 88 | + for zone_id in zone_ids: |
| 89 | + await handle_zone(cloudflare, webhook, zone_id, False) |
104 | 90 |
|
105 | | -async def set_zone_under_attack(zone_id, zone_name, under_attack): |
106 | | - """ |
107 | | - Set the Cloudflare zone under attack mode. |
108 | | - """ |
109 | | - if config.get("SETTINGS", "LOGGING") and config.get("SETTINGS", "WEBHOOK"): |
110 | | - await webhook.send( |
111 | | - message=f"{'Activating' if under_attack else 'Deactivating'} " |
112 | | - f"Under Attack Mode for {zone_name}", |
113 | | - color=0xFF0000 if under_attack else 0x00FF00 |
114 | | - ) |
| 91 | + except Exception as exc: # pylint: disable=broad-except |
| 92 | + logger.error("Error in main loop: %s", exc) |
115 | 93 |
|
116 | | - await cloudflare.set_zone_under_attack(zone_id, under_attack) |
| 94 | + await asyncio.sleep(max(0, check_interval - 1)) |
| 95 | + finally: |
| 96 | + await cloudflare.close() |
117 | 97 |
|
118 | 98 |
|
119 | 99 | if __name__ == "__main__": |
120 | | - print("\033[38;5;208m" + pyfiglet.figlet_format('NoAttack', font='doom') + Fore.RESET) |
| 100 | + print("\033[38;5;208m" + pyfiglet.figlet_format("NoAttack", font="doom") + Fore.RESET) |
121 | 101 |
|
122 | | - if not config.config_exists(): |
123 | | - config.create_config() |
124 | | - print(f"{PREFIX}Config file created.") |
| 102 | + try: |
| 103 | + get_config() |
| 104 | + except ConfigNotFoundError as config_error: |
| 105 | + print(f"{PREFIX}{config_error}") |
| 106 | + sys.exit(1) |
125 | 107 |
|
126 | | - print(f"{PREFIX}Config file loaded.") |
| 108 | + logging.basicConfig( |
| 109 | + level=logging.INFO, |
| 110 | + format="[%(asctime)s] [%(levelname)s] %(name)s: %(message)s", |
| 111 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 112 | + ) |
127 | 113 | asyncio.run(main()) |
0 commit comments