TcpSocketMonitor: add polling loop
TcpSocketMonitor starts a sock_diag polling thread in its ctor whose
polling interval can be controlled with setPollingInterval() and
suspendPolling().
Initially the polling thread will immediately be suspended. The polling
thread is automatically started when 1 or more physical network exists,
and automatically stopped when there is 0 physical networks.
By default the polling interval is set to 30 secs.
Also fix some code indentation issues.
Bug: 64147860
Test: tested manually, watching the result of
$ adb shell dumpsys netd tcp_socket_info
Change-Id: I7fe356a0a073ebc83486bc774a3002648e9dd457
diff --git a/server/TcpSocketMonitor.h b/server/TcpSocketMonitor.h
index 7f1501a..ec39a13 100644
--- a/server/TcpSocketMonitor.h
+++ b/server/TcpSocketMonitor.h
@@ -17,6 +17,11 @@
#ifndef TCP_SOCKET_MONITOR_H
#define TCP_SOCKET_MONITOR_H
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+
+#include <android-base/thread_annotations.h>
#include "utils/String16.h"
namespace android {
@@ -27,13 +32,35 @@
class TcpSocketMonitor {
public:
static const String16 DUMP_KEYWORD;
+ static const std::chrono::milliseconds kDefaultPollingInterval;
- TcpSocketMonitor() = default;
- ~TcpSocketMonitor() = default;
+ TcpSocketMonitor();
+ ~TcpSocketMonitor();
void dump(DumpWriter& dw);
+ void setPollingInterval(std::chrono::milliseconds duration);
+ void resumePolling();
+ void suspendPolling();
private:
+ void poll();
+ void waitForNextPoll();
+ bool isRunning();
+
+ // Lock guarding all reads and writes to member variables.
+ std::mutex mLock;
+ // Used by the polling thread for sleeping between poll operations.
+ std::condition_variable mCv;
+ // The duration of a sleep between polls. Can be updated by the instance owner for dynamically
+ // adjusting the polling rate.
+ std::chrono::milliseconds mNextSleepDurationMs GUARDED_BY(mLock);
+ // The time of the last successful poll operation.
+ std::chrono::time_point<std::chrono::steady_clock> mLastPoll GUARDED_BY(mLock);
+ // True if the polling thread should sleep until notified.
+ bool mIsSuspended GUARDED_BY(mLock);
+ // True while the polling thread should poll.
+ bool mIsRunning GUARDED_BY(mLock);
+ std::thread mPollingThread;
};
} // namespace net