feat(HA): add cluster communication system

This commit is contained in:
Romain J 2019-12-31 00:52:17 +01:00
commit 6d078e829d
1534 changed files with 767 additions and 34363 deletions

108
cogs/cluster_manager.py Normal file
View file

@ -0,0 +1,108 @@
from datetime import datetime
import logging
import urllib.request
import discord
from aiohttp import web
from discord.ext import tasks, commands
from bot import TuxBot
log = logging.getLogger(__name__)
class Monitoring(commands.Cog):
def __init__(self, bot: TuxBot):
self.bot = bot
self.site = web.TCPSite
self.ping_clusters.start()
app = web.Application()
app.add_routes([web.get('/', self.handle)])
self.runner = web.AppRunner(app)
self.bot.loop.create_task(self.start_HTTPMonitoring_server())
def cog_unload(self):
self.ping_clusters.stop()
@tasks.loop(seconds=20.0)
async def ping_clusters(self):
for cluster in self.bot.clusters:
if cluster == 'DEFAULT':
pass
else:
cluster = self.bot.clusters[cluster]
if not cluster.get('This', False):
host = cluster.get('Host')
port = cluster.get('Port')
try:
req = urllib.request.urlopen(f"http://{host}:{port}",
timeout=2)
except Exception:
global_channel = await self.bot.fetch_channel(
661347412463321098
)
e = discord.Embed(
title=f"Cluster `{cluster.get('Name')}`",
color=discord.colour.Color.red(),
description=f"Cluster **`{cluster.get('Name')}`** with address **`http://{host}:{port}`** is down ! ",
timestamp=datetime.now()
)
e.set_thumbnail(
url='https://upload.wikimedia.org/wikipedia/commons/7/75/Erroricon404.PNG'
)
await global_channel.send(embed=e)
else:
print(req.read().decode())
@ping_clusters.before_loop
async def before_pinging(self):
await self.bot.wait_until_ready()
cluster = self.bot.cluster
host = cluster.get('Host')
port = cluster.get('Port')
global_channel = await self.bot.fetch_channel(
661347412463321098
)
e = discord.Embed(
title=f"Cluster `{cluster.get('Name')}`",
color=discord.colour.Color.green(),
description=f"Cluster **`{cluster.get('Name')}`** with address **`http://{host}:{port}`** is started ! ",
timestamp=datetime.now()
)
e.set_thumbnail(
url='https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/MW-Icon-CheckMark.svg/1024px-MW-Icon-CheckMark.svg.png'
)
await global_channel.send(embed=e)
async def start_HTTPMonitoring_server(self):
host = self.bot.cluster.get('WebPage')
port = self.bot.cluster.get('Port')
print(f"Starting HTTP Monitoring server on {host}:{port}")
await self.runner.setup()
self.site = web.TCPSite(self.runner, host, port)
await self.site.start()
async def handle(self, _):
return web.json_response(
{
'message': "I'm alive !",
'ws': self.bot.latency * 1000
}
)
def setup(bot: TuxBot):
bot.add_cog(Monitoring(bot))

View file

@ -1,45 +0,0 @@
import asyncio
import logging
import threading
from aiohttp import web
from aiohttp.web_request import Request
from discord.ext import commands
from bot import TuxBot
log = logging.getLogger(__name__)
class Monitoring(commands.Cog):
def __init__(self):
self.app = web.Application()
t = threading.Thread(
target=self.run_server,
args=(self.aiohttp_server(),)
)
t.start()
def aiohttp_server(self):
async def hi(request: Request):
return web.Response(text="I'm alive !")
self.app.add_routes([web.get('/', hi)])
runner = web.AppRunner(self.app)
return runner
@staticmethod
def run_server(runner):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(runner.setup())
site = web.TCPSite(runner, '0.0.0.0', 8080)
loop.run_until_complete(site.start())
loop.run_forever()
def setup(bot: TuxBot):
bot.add_cog(Monitoring())

View file

@ -1,15 +1,36 @@
from typing import List, Union
import configparser
class Config(configparser.RawConfigParser):
class Config(configparser.ConfigParser):
__slots__ = ('name', '_db')
def __init__(self, name):
super().__init__()
self.name = name
self._db = super()
self._db.read(self.name)
self._db.read(name)
def all(self) -> list:
return self._db.sections()
def find(self, value: str, **kwargs) \
-> Union[
List[configparser.SectionProxy], configparser.SectionProxy
]:
key = kwargs.get('key', None)
first = kwargs.get('first', False)
results = []
for name, section in self._db.items():
if key is None:
for k in section.keys():
if section.get(k) == value:
results.append(section)
if first and len(results) == 1:
return results[0]
else:
if section.get(key) == value:
results.append(section)
if first and len(results) == 1:
return results[0]
return results