Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
detector_stream.cpp
Go to the documentation of this file.
1#include "detector_stream.h"
2#include "pano_log.h"
3#include <algorithm>
4#include <atomic>
5#include <chrono>
6#include <condition_variable>
7#include <deque>
8#include <mutex>
9#include <unordered_set>
10
11// Events held per subscriber before new ones are dropped. A few seconds of a busy machine; the
12// detector normally drains its queue within milliseconds
13#define PANO_DETECTOR_QUEUE_MAX 16384
14
15// The detector holds one stream. A few more allow a debugging copy without letting a stuck
16// client tie up the server's threads
17#define PANO_MAX_DETECTOR_SUBSCRIBERS 4
18
20 std::mutex Lock;
21 std::condition_variable Wake;
22 std::deque<DetectorEventRecord> Queue;
23 std::unordered_set<std::string> EventNames; // empty: every event
24 bool Stopping = false;
25};
26
27static std::mutex g_SubscribersLock;
28static std::vector<std::shared_ptr<DetectorSubscriberState>> g_Subscribers;
29static bool g_Stopping = false;
30// Read without the lock so publishing costs one load while no detector is connected
31static std::atomic<size_t> g_SubscriberCount{ 0 };
32
33std::unique_ptr<DetectorSubscription> DetectorSubscription::Open(const std::vector<std::string>& eventNames)
34{
35 auto state = std::make_shared<DetectorSubscriberState>();
36 state->EventNames.insert(eventNames.begin(), eventNames.end());
37
38 std::lock_guard<std::mutex> guard(g_SubscribersLock);
39 if (g_Stopping || g_Subscribers.size() >= PANO_MAX_DETECTOR_SUBSCRIBERS) {
40 return nullptr;
41 }
42 g_Subscribers.push_back(state);
43 g_SubscriberCount = g_Subscribers.size();
44 return std::unique_ptr<DetectorSubscription>(new DetectorSubscription(state));
45}
46
47DetectorSubscription::DetectorSubscription(std::shared_ptr<DetectorSubscriberState> state)
48 : m_state(std::move(state))
49{
50}
51
53{
54 std::lock_guard<std::mutex> guard(g_SubscribersLock);
55 g_Subscribers.erase(std::remove(g_Subscribers.begin(), g_Subscribers.end(), m_state), g_Subscribers.end());
56 g_SubscriberCount = g_Subscribers.size();
57}
58
59bool DetectorSubscription::Wait(std::vector<DetectorEventRecord>& out, DWORD timeoutMs)
60{
61 out.clear();
62 std::unique_lock<std::mutex> lock(m_state->Lock);
63 m_state->Wake.wait_for(lock, std::chrono::milliseconds(timeoutMs),
64 [this] { return !m_state->Queue.empty() || m_state->Stopping; });
65 if (m_state->Stopping) {
66 return false;
67 }
68 out.assign(std::make_move_iterator(m_state->Queue.begin()), std::make_move_iterator(m_state->Queue.end()));
69 m_state->Queue.clear();
70 return true;
71}
72
73static void PublishDetectorEvent(const std::string& eventName, UINT64 sequence, const std::string& json, const FILETIME& time)
74{
75 if (g_SubscriberCount.load(std::memory_order_relaxed) == 0) {
76 return;
77 }
78
79 INT64 timestamp = ((INT64)time.dwHighDateTime << 32) | time.dwLowDateTime;
80 std::lock_guard<std::mutex> guard(g_SubscribersLock);
81 for (auto& subscriber : g_Subscribers) {
82 {
83 std::lock_guard<std::mutex> lock(subscriber->Lock);
84 if (!subscriber->EventNames.empty() && subscriber->EventNames.count(eventName) == 0) {
85 continue;
86 }
87 // A dropped event leaves a gap in the sequence, which tells the detector
88 if (subscriber->Queue.size() >= PANO_DETECTOR_QUEUE_MAX) {
89 continue;
90 }
91 subscriber->Queue.push_back({ sequence, timestamp, json });
92 }
93 subscriber->Wake.notify_one();
94 }
95}
96
97// Microseconds since 1970 when the service started (see detector_stream.h)
98static UINT64 FirstSequence()
99{
100 ULARGE_INTEGER now;
101 FILETIME time = CurrentFileTime();
102 now.LowPart = time.dwLowDateTime;
103 now.HighPart = time.dwHighDateTime;
104 const UINT64 unixEpoch = 116444736000000000ULL; // 1970-01-01 as a FILETIME
105 return (now.QuadPart - unixEpoch) / 10;
106}
107
108// Held from numbering an event until it is written and queued, so Seq increases down pano.log
109// and along each subscriber's stream
110static std::mutex g_RecordLock;
111static UINT64 g_NextSequence = FirstSequence();
112
113std::string RecordEvent(nlohmann::ordered_json& event, const FILETIME& time)
114{
115 std::lock_guard<std::mutex> guard(g_RecordLock);
116 UINT64 sequence = g_NextSequence++;
117 event["Seq"] = sequence;
118 std::string line = event.dump();
119 WriteToLogFile(line + "\n");
120 PublishDetectorEvent(event.value("Event", ""), sequence, line, time);
121 return line;
122}
123
125{
126 FILETIME now;
127 GetSystemTimeAsFileTime(&now);
128 return now;
129}
130
132{
133 std::lock_guard<std::mutex> guard(g_SubscribersLock);
134 g_Stopping = true;
135 for (auto& subscriber : g_Subscribers) {
136 {
137 std::lock_guard<std::mutex> lock(subscriber->Lock);
138 subscriber->Stopping = true;
139 }
140 subscriber->Wake.notify_all();
141 }
142}
static std::unique_ptr< DetectorSubscription > Open(const std::vector< std::string > &eventNames)
Registers a subscriber. Returns nullptr when the service is stopping or too many subscribers are conn...
DetectorSubscription(const DetectorSubscription &)=delete
bool Wait(std::vector< DetectorEventRecord > &out, DWORD timeoutMs)
Waits up to timeoutMs for events and moves the queued ones into out (which it clears first)....
void StopDetectorStreams()
Wakes every subscriber's Wait with false and refuses new subscribers, so the SubscribeEvents calls re...
#define PANO_DETECTOR_QUEUE_MAX
std::string RecordEvent(nlohmann::ordered_json &event, const FILETIME &time)
Gives event the next sequence number (appended as "Seq"), writes it to pano.log and queues it for eve...
FILETIME CurrentFileTime()
The current time as a FILETIME, for events that carry no timestamp of their own.
#define PANO_MAX_DETECTOR_SUBSCRIBERS
void WriteToLogFile(const std::string &message)
Appends a line to the event log: LOG_FOLDER\pano.log, continuing in pano1.log, pano2....
Definition pano_log.cpp:72
std::deque< DetectorEventRecord > Queue
std::unordered_set< std::string > EventNames
std::condition_variable Wake