From ac8b937a033cd3c45179ac30aa04300bd7b635ea Mon Sep 17 00:00:00 2001 From: John Date: Sat, 13 Nov 2021 17:09:37 +0100 Subject: [PATCH] add grace period for race in connection cleanup --- src/ebusd/network.cpp | 8 ++++++-- src/ebusd/network.h | 11 ++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/ebusd/network.cpp b/src/ebusd/network.cpp index df84aca6..6e3ba9bf 100644 --- a/src/ebusd/network.cpp +++ b/src/ebusd/network.cpp @@ -187,6 +187,7 @@ void Connection::run() { delete m_socket; m_socket = nullptr; } + time(&m_endedAt); logInfo(lf_network, "[%05d] connection closed", getID()); } @@ -339,9 +340,12 @@ void Network::run() { void Network::cleanConnections() { auto it = m_connections.begin(); + time_t endBefore; + time(&endBefore); + endBefore += 5; // after 5 seconds grace period while (it != m_connections.end()) { - if (!(*it)->isRunning()) { - Connection* connection = *it; + Connection* connection = *it; + if (connection && !connection->isRunning() && connection->endedBefore(&endBefore)) { it = m_connections.erase(it); delete connection; logDebug(lf_network, "dead connection removed - %d", m_connections.size()); diff --git a/src/ebusd/network.h b/src/ebusd/network.h index 2d6373bd..8d560a91 100644 --- a/src/ebusd/network.h +++ b/src/ebusd/network.h @@ -227,7 +227,7 @@ class Connection : public Thread { * @param netQueue the reference to the @a NetMessage @a Queue. */ Connection(TCPSocket* socket, const bool isHttp, Queue* netQueue) - : Thread(), m_isHttp(isHttp), m_socket(socket), m_netQueue(netQueue) { + : Thread(), m_isHttp(isHttp), m_socket(socket), m_netQueue(netQueue), m_endedAt(0) { m_id = ++m_ids; } @@ -253,6 +253,12 @@ class Connection : public Thread { */ int getID() { return m_id; } + /** + * Return whether this connection has ended before the specified time. + * @param time the time to check against. + * @return true when this connection has ended before the specified time. + */ + bool endedBefore(const time_t* time) const { return m_endedAt > 0 && time && m_endedAt < *time; } private: /** whether this is a HTTP connection. */ @@ -270,6 +276,9 @@ class Connection : public Thread { /** the ID of this connection. */ int m_id; + /** the time when this connected ended, or 0 if not yet. */ + time_t m_endedAt; + /** the IF of the last opened connection. */ static int m_ids; };