xbot/watchdog_thread.cpp

81 lines
1.6 KiB
C++
Raw Permalink Normal View History

2023-11-25 09:22:55 -08:00
#include "watchdog_thread.hpp"
#include "connection.hpp"
#include "irc_parse_thread.hpp"
2023-11-25 20:09:20 -08:00
#include "write_irc.hpp"
#include <boost/asio/steady_timer.hpp>
2023-11-25 09:22:55 -08:00
#include <chrono>
2023-11-25 20:09:20 -08:00
#include <memory>
2023-11-25 09:22:55 -08:00
2023-11-27 14:12:20 -08:00
WatchdogThread::WatchdogThread(Connection& connection)
: connection_{connection}
, timer_{connection.get_executor()}
2024-03-03 12:27:36 -08:00
, stalled_{false}
2023-11-25 09:22:55 -08:00
{
2023-11-27 14:12:20 -08:00
}
2023-11-25 20:09:20 -08:00
2023-11-27 14:12:20 -08:00
auto WatchdogThread::on_activity() -> void
{
2024-03-03 12:27:36 -08:00
stalled_ = false;
timer_.expires_from_now(WatchdogThread::TIMEOUT);
2023-11-27 14:12:20 -08:00
}
2023-11-25 20:09:20 -08:00
2024-03-03 12:27:36 -08:00
auto WatchdogThread::start_timer()
2023-11-27 14:12:20 -08:00
{
2024-03-03 12:27:36 -08:00
timer_.async_wait([weak = weak_from_this()](auto const& error)
2023-11-25 09:22:55 -08:00
{
2023-11-27 14:12:20 -08:00
if (not error)
2023-11-25 09:22:55 -08:00
{
2023-11-27 14:12:20 -08:00
if (auto self = weak.lock())
2023-11-25 09:22:55 -08:00
{
2023-11-27 14:12:20 -08:00
self->on_timeout();
2023-11-25 09:22:55 -08:00
}
2023-11-27 14:12:20 -08:00
}
2024-03-03 12:27:36 -08:00
});
2023-11-27 14:12:20 -08:00
}
2023-11-25 20:09:20 -08:00
2023-11-27 14:12:20 -08:00
auto WatchdogThread::on_timeout() -> void
{
2024-03-03 12:27:36 -08:00
if (stalled_)
2023-11-25 20:09:20 -08:00
{
2023-11-27 14:12:20 -08:00
connection_.close();
2023-11-25 20:09:20 -08:00
}
2023-11-27 14:12:20 -08:00
else
2023-11-25 20:09:20 -08:00
{
2023-11-27 14:12:20 -08:00
send_ping(connection_, "watchdog");
2024-03-03 12:27:36 -08:00
stalled_ = true;
timer_.expires_from_now(WatchdogThread::TIMEOUT);
start_timer();
2023-11-25 20:09:20 -08:00
}
2023-11-27 14:12:20 -08:00
}
2023-11-25 20:09:20 -08:00
2023-11-27 14:12:20 -08:00
auto WatchdogThread::on_connect() -> void
{
on_activity();
2024-03-03 12:27:36 -08:00
start_timer();
2023-11-27 14:12:20 -08:00
}
2023-11-25 20:09:20 -08:00
2023-11-27 14:12:20 -08:00
auto WatchdogThread::on_disconnect() -> void
{
timer_.cancel();
}
2023-11-25 20:09:20 -08:00
2023-11-27 14:12:20 -08:00
auto WatchdogThread::start(Connection& connection) -> void
2023-11-25 20:09:20 -08:00
{
auto const thread = std::make_shared<WatchdogThread>(connection);
2023-11-26 15:32:52 -08:00
connection.add_listener<ConnectEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_connect();
});
2023-11-26 15:32:52 -08:00
connection.add_listener<DisconnectEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_disconnect();
});
2023-11-26 15:32:52 -08:00
connection.add_listener<IrcMsgEvent>([thread](auto&)
2023-11-25 20:09:20 -08:00
{
thread->on_activity();
});
2023-11-25 09:22:55 -08:00
}