Skip to content

Commit

Permalink
⚡ perf: use persistant aiohttp session
Browse files Browse the repository at this point in the history
  • Loading branch information
Aeris1One committed Nov 14, 2023
1 parent 21a5a41 commit d2e269f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 24 deletions.
40 changes: 19 additions & 21 deletions plugins/monitoring/monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
"""
import time

# pylint: disable=unused-import
from discord.ext import tasks, commands

import aiohttp
from discord.ext import tasks, commands

from utils import Gunibot, MyContext
import core
from utils import Gunibot


async def setup(bot: Gunibot = None):
Expand All @@ -26,14 +24,15 @@ def __init__(self, bot: Gunibot):
self.logger = core.setup_logger(self.file)
self.config = core.config.get(self.file)
self.error_counter = 0
self.session = aiohttp.ClientSession()

async def cog_load(self) -> None:
if self.config["monitoring_enabled"]:
for i in range(5):
if await self.ping_monitoring():
self.logger.info("Monitoring test ping successful")
self.logger.info("Monitoring enabled")
self.loop.start()
self.loop.start() #pylint: disable=no-member
return
else:
self.logger.warning("Monitoring ping failed %s times", i + 1)
Expand All @@ -50,22 +49,21 @@ async def ping_monitoring(self):
"?status=up&msg=OK&ping=" + str(ping))

# send request
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status != 200:
self.logger.error("Monitoring ping failed with status %s", resp.status)
return False
else:
json = await resp.json()
try:
if not json["ok"]:
self.logger.error("Monitoring ping failed with error : %s", json["msg"])
return False
else:
return True
except KeyError:
self.logger.error("Monitoring ping failed")
async with self.session.get(url) as resp:
if resp.status != 200:
self.logger.error("Monitoring ping failed with status %s", resp.status)
return False
else:
json = await resp.json()
try:
if not json["ok"]:
self.logger.error("Monitoring ping failed with error : %s", json["msg"])
return False
else:
return True
except KeyError:
self.logger.error("Monitoring ping failed")
return False

@tasks.loop(seconds=20)
async def loop(self):
Expand All @@ -75,7 +73,7 @@ async def loop(self):
self.error_counter += 1
if self.error_counter >= 6:
self.logger.error("Monitoring disabled due to multiple ping failure")
self.loop.stop()
self.loop.stop() #pylint: disable=no-member

@loop.before_loop
async def before_ping_monitoring(self):
Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
psutil
aiohttp
psutil~=5.9.5
aiohttp~=3.8.5
gitpython >= 3.1.8
python-i18n
pyyaml
pyyaml~=6.0.1
emoji >= 2.0
feedparser >= 6.0
async-timeout >= 3.0
Expand Down

0 comments on commit d2e269f

Please sign in to comment.