Prevent OOM
This commit is contained in:
@@ -162,7 +162,7 @@ bool PaddleOCRV5Engine::Initialize(const std::string& detModelPath,
|
||||
// Ensure this DLL's copy of Ort::Global<void>::api_ is initialized.
|
||||
// BasicOrtHandler sets it in ONNXEngine.dll, but each DLL has its own
|
||||
// inline-static copy. Without this, inference calls from ANSOCR.dll crash.
|
||||
if (Ort::Global<void>::api_ == nullptr) {
|
||||
if (Ort::detail::Global::Api() == nullptr) {
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
}
|
||||
|
||||
|
||||
@@ -761,6 +761,16 @@ namespace ANSCENTER
|
||||
float CosineSimilarity(const std::vector<float>& a, const std::vector<float>& b, bool normalized);
|
||||
};
|
||||
class ANSENGINE_API ANSODBase {
|
||||
public:
|
||||
// Explicit non-copy/non-move: _modelLoading (std::atomic) deletes the
|
||||
// implicit copy ops; spelling them out here gives ClangCL a clean
|
||||
// anchor and documents that subclasses are never copied/moved (they
|
||||
// are heap-allocated and passed by shared_ptr<...>).
|
||||
ANSODBase(const ANSODBase&) = delete;
|
||||
ANSODBase& operator=(const ANSODBase&) = delete;
|
||||
ANSODBase(ANSODBase&&) = delete;
|
||||
ANSODBase& operator=(ANSODBase&&) = delete;
|
||||
ANSODBase() = default;
|
||||
protected:
|
||||
bool _licenseValid{ false };
|
||||
bool _isInitialized{ false };
|
||||
@@ -1085,6 +1095,13 @@ namespace ANSCENTER
|
||||
std::vector<Object> RunInferenceInTrackingMode(const cv::Mat& input, const std::string& camera_id, std::vector<int> trackingObjectIds);// Get detected objects
|
||||
};
|
||||
class ANSENGINE_API ANSFDBase {
|
||||
public:
|
||||
// Explicit non-copy/non-move (see ANSODBase for rationale).
|
||||
ANSFDBase(const ANSFDBase&) = delete;
|
||||
ANSFDBase& operator=(const ANSFDBase&) = delete;
|
||||
ANSFDBase(ANSFDBase&&) = delete;
|
||||
ANSFDBase& operator=(ANSFDBase&&) = delete;
|
||||
ANSFDBase() = default;
|
||||
protected:
|
||||
bool _licenseValid{ false };
|
||||
bool _isInitialized{ false };
|
||||
|
||||
@@ -1316,7 +1316,7 @@ namespace ANSCENTER
|
||||
{
|
||||
try {
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(ANSCENTER::EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[ANSFDBase] EP ready: "<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace ANSCENTER
|
||||
inputImageShape_ = targetInputShape;
|
||||
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[ANSONNXCL] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -25,6 +25,13 @@ namespace ANSCENTER {
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
class ANSENGINE_API ANSONNXCL :public ANSODBase {
|
||||
public:
|
||||
// Explicit non-copy/non-move (see ANSONNXYOLO for dllexport rationale).
|
||||
ANSONNXCL(const ANSONNXCL&) = delete;
|
||||
ANSONNXCL& operator=(const ANSONNXCL&) = delete;
|
||||
ANSONNXCL(ANSONNXCL&&) = delete;
|
||||
ANSONNXCL& operator=(ANSONNXCL&&) = delete;
|
||||
ANSONNXCL() = default;
|
||||
|
||||
virtual bool Initialize(std::string licenseKey, ModelConfig modelConfig, const std::string& modelZipFilePath, const std::string& modelZipPassword, std::string& labelMap) override;
|
||||
virtual bool LoadModel(const std::string& modelZipFilePath, const std::string& modelZipPassword)override;
|
||||
virtual bool LoadModelFromFolder(std::string licenseKey, ModelConfig modelConfig, std::string modelName, std::string className, const std::string& modelFolder, std::string& labelMap)override;
|
||||
|
||||
@@ -692,7 +692,7 @@ namespace ANSCENTER {
|
||||
deviceId_ = deviceId;
|
||||
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[ANSONNXOBB] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -276,7 +276,7 @@ namespace ANSCENTER {
|
||||
deviceId_ = deviceId;
|
||||
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[ANSONNXPOSE] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -108,6 +108,13 @@ namespace ANSCENTER {
|
||||
// ====================================================================
|
||||
class ANSENGINE_API ANSONNXRTMPOSE : public ANSODBase {
|
||||
public:
|
||||
// Explicit non-copy/non-move (see ANSONNXYOLO for dllexport rationale).
|
||||
ANSONNXRTMPOSE(const ANSONNXRTMPOSE&) = delete;
|
||||
ANSONNXRTMPOSE& operator=(const ANSONNXRTMPOSE&) = delete;
|
||||
ANSONNXRTMPOSE(ANSONNXRTMPOSE&&) = delete;
|
||||
ANSONNXRTMPOSE& operator=(ANSONNXRTMPOSE&&) = delete;
|
||||
ANSONNXRTMPOSE() = default;
|
||||
|
||||
bool Initialize(std::string licenseKey, ModelConfig modelConfig,
|
||||
const std::string& modelZipFilePath,
|
||||
const std::string& modelZipPassword,
|
||||
|
||||
@@ -204,7 +204,7 @@ namespace ANSCENTER
|
||||
}
|
||||
|
||||
try {
|
||||
m_engine = std::make_unique<ONNXSAM3>(modelFolder, EngineType::NVIDIA_GPU);
|
||||
m_engine = std::make_unique<class ONNXSAM3>(modelFolder, EngineType::NVIDIA_GPU);
|
||||
m_tokenLength = m_engine->getTokenLength();
|
||||
|
||||
_logger.LogDebug("ANSONNXSAM3::InitEngine",
|
||||
|
||||
@@ -16,6 +16,13 @@ namespace ANSCENTER
|
||||
class ANSENGINE_API ANSONNXSAM3 : public ANSODBase
|
||||
{
|
||||
public:
|
||||
// Explicit non-copy/non-move (see ANSONNXYOLO for dllexport rationale).
|
||||
ANSONNXSAM3(const ANSONNXSAM3&) = delete;
|
||||
ANSONNXSAM3& operator=(const ANSONNXSAM3&) = delete;
|
||||
ANSONNXSAM3(ANSONNXSAM3&&) = delete;
|
||||
ANSONNXSAM3& operator=(ANSONNXSAM3&&) = delete;
|
||||
ANSONNXSAM3() = default;
|
||||
|
||||
virtual bool Initialize(std::string licenseKey, ModelConfig modelConfig,
|
||||
const std::string& modelZipFilePath, const std::string& modelZipPassword,
|
||||
std::string& labelMap) override;
|
||||
@@ -45,7 +52,10 @@ namespace ANSCENTER
|
||||
bool _fp16 = false;
|
||||
|
||||
// ONNX Runtime engine
|
||||
std::unique_ptr<ONNXSAM3> m_engine;
|
||||
// Elaborated `class ONNXSAM3` disambiguates from the
|
||||
// ANSCENTER::ModelType::ONNXSAM3 enumerator (ANSLicense.h) which
|
||||
// shares the same unqualified name in this namespace.
|
||||
std::unique_ptr<class ONNXSAM3> m_engine;
|
||||
|
||||
// Tokenizer (loaded from merges.txt)
|
||||
std::unique_ptr<ANSCLIPTokenizer> m_tokenizer;
|
||||
|
||||
@@ -273,7 +273,7 @@ namespace ANSCENTER {
|
||||
deviceId_ = deviceId;
|
||||
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[ANSONNXSEG] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -129,7 +129,7 @@ namespace ANSCENTER {
|
||||
// future ORT shape-mismatch failure (e.g. /model.12/Concat for
|
||||
// non-stride-32 inputs) points at the offending HxW directly.
|
||||
// One line per session — does not flood DebugView.
|
||||
static thread_local const ONNXYOLO* s_loggedFirst = nullptr;
|
||||
static thread_local const class ONNXYOLO* s_loggedFirst = nullptr;
|
||||
if (s_loggedFirst != this) {
|
||||
s_loggedFirst = this;
|
||||
ANS_DBG("ONNXYOLO",
|
||||
@@ -1680,7 +1680,7 @@ namespace ANSCENTER {
|
||||
"Model file does not exist: " + _modelFilePath, __FILE__, __LINE__);
|
||||
return false;
|
||||
}
|
||||
m_ortEngine = std::make_shared<ONNXYOLO>(_modelFilePath);
|
||||
m_ortEngine = std::make_shared<class ONNXYOLO>(_modelFilePath);
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
@@ -1696,7 +1696,7 @@ namespace ANSCENTER {
|
||||
"Model file does not exist: " + _modelFilePath, __FILE__, __LINE__);
|
||||
return false;
|
||||
}
|
||||
m_ortEngine = std::make_shared<ONNXYOLO>(_modelFilePath, engineType);
|
||||
m_ortEngine = std::make_shared<class ONNXYOLO>(_modelFilePath, engineType);
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
@@ -2244,7 +2244,7 @@ namespace ANSCENTER {
|
||||
int numKps;
|
||||
std::vector<std::string> classes;
|
||||
bool trackerEnabled, stabilizationEnabled;
|
||||
std::shared_ptr<ONNXYOLO> engine;
|
||||
std::shared_ptr<class ONNXYOLO> engine;
|
||||
{
|
||||
ANS_DBG("ONNXYOLO", "DetectObjects: cam=%s acquiring mutex...", camera_id.c_str());
|
||||
auto lk = TryLockWithTimeout("ANSONNXYOLO::DetectObjects");
|
||||
@@ -2446,7 +2446,7 @@ namespace ANSCENTER {
|
||||
int numKps;
|
||||
std::vector<std::string> classes;
|
||||
bool trackerEnabled, stabilizationEnabled;
|
||||
std::shared_ptr<ONNXYOLO> engine;
|
||||
std::shared_ptr<class ONNXYOLO> engine;
|
||||
{
|
||||
auto lk = TryLockWithTimeout("ANSONNXYOLO::DetectObjectsBatch");
|
||||
if (!lk.owns_lock()) return {};
|
||||
|
||||
@@ -205,6 +205,16 @@ namespace ANSCENTER {
|
||||
// ====================================================================
|
||||
class ANSENGINE_API ANSONNXYOLO : public ANSODBase {
|
||||
public:
|
||||
// Explicit non-copy/non-move. The class has atomic + shared_ptr members
|
||||
// that already implicitly delete these, but __declspec(dllexport)
|
||||
// makes ClangCL eagerly instantiate the implicit copy/move ctor
|
||||
// bodies; an explicit user-declared =delete short-circuits that.
|
||||
ANSONNXYOLO(const ANSONNXYOLO&) = delete;
|
||||
ANSONNXYOLO& operator=(const ANSONNXYOLO&) = delete;
|
||||
ANSONNXYOLO(ANSONNXYOLO&&) = delete;
|
||||
ANSONNXYOLO& operator=(ANSONNXYOLO&&) = delete;
|
||||
ANSONNXYOLO() = default;
|
||||
|
||||
bool Initialize(std::string licenseKey, ModelConfig modelConfig,
|
||||
const std::string& modelZipFilePath,
|
||||
const std::string& modelZipPassword,
|
||||
@@ -254,7 +264,10 @@ namespace ANSCENTER {
|
||||
// caught a DML E_FAIL and rebuilt the session — that was the
|
||||
// 0xc0000005 access violation observed in ANSODEngine.dll under
|
||||
// AMD/DirectML when multiple AI tasks ran in parallel.
|
||||
std::shared_ptr<ONNXYOLO> m_ortEngine;
|
||||
// Elaborated `class ONNXYOLO` disambiguates from the
|
||||
// ANSCENTER::ModelType::ONNXYOLO enumerator (ANSLicense.h) which
|
||||
// shares the same unqualified name in this namespace.
|
||||
std::shared_ptr<class ONNXYOLO> m_ortEngine;
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// DML stay-on-GPU recovery state.
|
||||
|
||||
@@ -281,7 +281,7 @@ namespace ANSCENTER {
|
||||
{
|
||||
try {
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[YOLO12OD] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -208,7 +208,7 @@ namespace ANSCENTER
|
||||
{
|
||||
try {
|
||||
const auto& ep = ANSCENTER::EPLoader::Current();
|
||||
if (Ort::Global<void>::api_ == nullptr)
|
||||
if (Ort::detail::Global::Api() == nullptr)
|
||||
Ort::InitApi(static_cast<const OrtApi*>(EPLoader::GetOrtApiRaw()));
|
||||
std::cout << "[YOLOOD] EP ready: "
|
||||
<< ANSCENTER::EPLoader::EngineTypeName(ep.type) << std::endl;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "ANSGpuFrameRegistry.h"
|
||||
#include "ANSEngineCommon.h"
|
||||
#include "ANSLicense.h" // ANS_DBG macro
|
||||
#include "GpuMemoryGuard.h"
|
||||
#include <opencv2/cudaimgproc.hpp>
|
||||
#include <opencv2/cudawarping.hpp>
|
||||
#include <opencv2/core/cuda_stream_accessor.hpp>
|
||||
@@ -168,6 +169,12 @@ namespace ANSCENTER {
|
||||
}
|
||||
|
||||
++m_cudaFailStreak;
|
||||
// (3) If this failure is a GPU OOM, open the process-wide circuit
|
||||
// breaker so every engine (FR/OD/OCR/LPR) backs off via UnderPressure()
|
||||
// before the streak reaches CUDA_FAIL_LIMIT and the context is lost.
|
||||
if (GpuMemoryGuard::IsOom(err) || GpuMemoryGuard::IsOom(pending)) {
|
||||
GpuMemoryGuard::NoteOom();
|
||||
}
|
||||
if (m_cudaFailStreak >= CUDA_FAIL_LIMIT && !m_cudaContextDead) {
|
||||
m_cudaContextDead = true;
|
||||
logger.LogFatal(std::string(tag) + "::NV12Helper",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "ANSGpuFrameRegistry.h"
|
||||
#include "NV12PreprocessHelper.h" // tl_currentGpuFrame()
|
||||
#include "Utility.h"
|
||||
#include "GpuMemoryGuard.h"
|
||||
#include <chrono>
|
||||
//#define FNS_DEBUG
|
||||
namespace ANSCENTER {
|
||||
@@ -638,6 +639,17 @@ namespace ANSCENTER {
|
||||
// Phase 2: CUDA preprocessing + inference (mutex released — pool dispatches to idle GPU slot)
|
||||
std::vector<std::vector<cv::cuda::GpuMat>> inputs;
|
||||
bool usedNV12 = false;
|
||||
|
||||
// (2) Pressure guard: if free GPU VRAM is below the safety margin (or the
|
||||
// OOM circuit breaker is open), SKIP this frame's GPU work instead of
|
||||
// allocating and triggering an OOM that permanently poisons the context.
|
||||
if (ANSCENTER::GpuMemoryGuard::UnderPressure()) {
|
||||
this->_logger.LogWarn("ANSSCRFDFD::Detect",
|
||||
"GPU under memory pressure — skipping SCRFD frame to avoid OOM",
|
||||
__FILE__, __LINE__);
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
// Clear any sticky CUDA error from transient graph-capture failures
|
||||
cudaError_t priorErr = cudaGetLastError();
|
||||
@@ -706,6 +718,14 @@ namespace ANSCENTER {
|
||||
m_nv12Helper.tickInference();
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
// (3) On a GPU OOM, open the circuit breaker so subsequent frames
|
||||
// back off (UnderPressure) instead of repeatedly faulting the
|
||||
// already-fragile CUDA context — that repetition is what corrupts it.
|
||||
const std::string msg = e.what();
|
||||
if (msg.find("out of memory") != std::string::npos ||
|
||||
msg.find("Gpu API call") != std::string::npos) {
|
||||
ANSCENTER::GpuMemoryGuard::NoteOom();
|
||||
}
|
||||
this->_logger.LogError(
|
||||
"ANSSCRFDFD::Detect",
|
||||
std::string("CUDA preprocessing failed: ") + e.what(),
|
||||
|
||||
@@ -1312,7 +1312,7 @@ namespace ANSCENTER
|
||||
return result;
|
||||
}
|
||||
// ====================================================================
|
||||
// GetANSLoggerErrorEvents
|
||||
// GetANSLoggerErrorEvents / GetANSLoggerErrorEventsSinceLastCall
|
||||
//
|
||||
// Reads every Error-level event written by the "ANSLogger" source in
|
||||
// the Application channel using the modern winevt API. Events are
|
||||
@@ -1322,14 +1322,98 @@ namespace ANSCENTER
|
||||
//
|
||||
// DebugView: filter "[EVTLOG]".
|
||||
// ====================================================================
|
||||
std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) {
|
||||
// XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE).
|
||||
// Forward direction keeps chronological insertion order so output
|
||||
// matches a fresh "oldest first" scroll through Event Viewer.
|
||||
constexpr const wchar_t* kQuery =
|
||||
L"*[System[Provider[@Name='ANSLogger'] and Level=2]]";
|
||||
|
||||
EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", kQuery,
|
||||
// ---- Watermark helpers (HKCU, no admin needed) ----------------------
|
||||
static constexpr const wchar_t* kWatermarkRegKey =
|
||||
L"Software\\ANSCENTER\\ANSUtilities\\EventLogWatermark";
|
||||
static constexpr const wchar_t* kWatermarkValueName = L"ANSLogger";
|
||||
|
||||
static uint64_t ReadAnsLoggerWatermark() {
|
||||
HKEY hKey = nullptr;
|
||||
if (RegOpenKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
|
||||
KEY_READ, &hKey) != ERROR_SUCCESS) {
|
||||
return 0;
|
||||
}
|
||||
uint64_t value = 0;
|
||||
DWORD size = sizeof(value), type = 0;
|
||||
LONG rc = RegQueryValueExW(hKey, kWatermarkValueName, nullptr,
|
||||
&type, reinterpret_cast<LPBYTE>(&value),
|
||||
&size);
|
||||
RegCloseKey(hKey);
|
||||
return (rc == ERROR_SUCCESS && type == REG_QWORD) ? value : 0;
|
||||
}
|
||||
|
||||
static void WriteAnsLoggerWatermark(uint64_t value) {
|
||||
HKEY hKey = nullptr;
|
||||
if (RegCreateKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
|
||||
nullptr, REG_OPTION_NON_VOLATILE, KEY_WRITE,
|
||||
nullptr, &hKey, nullptr) != ERROR_SUCCESS) {
|
||||
ANS_DBG("EVTLOG", "watermark RegCreateKey failed err=%lu",
|
||||
GetLastError());
|
||||
return;
|
||||
}
|
||||
LONG rc = RegSetValueExW(hKey, kWatermarkValueName, 0, REG_QWORD,
|
||||
reinterpret_cast<const BYTE*>(&value),
|
||||
sizeof(value));
|
||||
if (rc != ERROR_SUCCESS) {
|
||||
ANS_DBG("EVTLOG", "watermark RegSetValue failed err=%ld", rc);
|
||||
}
|
||||
RegCloseKey(hKey);
|
||||
}
|
||||
|
||||
// Extracts <EventRecordID>NNN</EventRecordID> from a rendered event XML.
|
||||
// Returns 0 if not present (shouldn't happen — every Windows event has one).
|
||||
static uint64_t ExtractRecordIdFromXml(const std::wstring& xml) {
|
||||
auto open = xml.find(L"<EventRecordID>");
|
||||
if (open == std::wstring::npos) return 0;
|
||||
open += 15; // length of "<EventRecordID>"
|
||||
auto close = xml.find(L"</EventRecordID>", open);
|
||||
if (close == std::wstring::npos) return 0;
|
||||
std::wstring numStr = xml.substr(open, close - open);
|
||||
return std::wcstoull(numStr.c_str(), nullptr, 10);
|
||||
}
|
||||
|
||||
// Returns the RecordID of the most recently written event in `channel`.
|
||||
// Used to detect channel clears: if our stored watermark > channelMax,
|
||||
// the channel was cleared and the new event counter restarted at 1, so
|
||||
// we must reset our watermark or risk skipping all new events.
|
||||
static uint64_t GetChannelMaxRecordId(const wchar_t* channel) {
|
||||
EVT_HANDLE hQuery = EvtQuery(nullptr, channel, nullptr,
|
||||
EvtQueryChannelPath | EvtQueryReverseDirection);
|
||||
if (!hQuery) return 0;
|
||||
|
||||
EVT_HANDLE hEvent = nullptr;
|
||||
DWORD returned = 0;
|
||||
uint64_t maxId = 0;
|
||||
if (EvtNext(hQuery, 1, &hEvent, 1000, 0, &returned) && returned > 0) {
|
||||
std::vector<wchar_t> buf(4096);
|
||||
DWORD used = 0, propCount = 0;
|
||||
BOOL ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
|
||||
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
||||
buf.data(), &used, &propCount);
|
||||
if (!ok && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
|
||||
buf.resize(used / sizeof(wchar_t) + 1);
|
||||
ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
|
||||
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
||||
buf.data(), &used, &propCount);
|
||||
}
|
||||
if (ok) maxId = ExtractRecordIdFromXml(std::wstring(buf.data()));
|
||||
EvtClose(hEvent);
|
||||
}
|
||||
EvtClose(hQuery);
|
||||
return maxId;
|
||||
}
|
||||
|
||||
// ---- Shared implementation -----------------------------------------
|
||||
// Runs `query` against the Application channel, formats events as
|
||||
// "<DD/MM/YYYY h:mm:ss tt>: <event data>\n"
|
||||
// and optionally clears the channel afterwards. If trackWatermark is
|
||||
// true, also persists the highest EventRecordID seen to HKCU on return.
|
||||
static std::string ReadAnsLoggerEventsImpl(const wchar_t* query,
|
||||
bool clearAfterRead,
|
||||
bool trackWatermark)
|
||||
{
|
||||
EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", query,
|
||||
EvtQueryChannelPath | EvtQueryForwardDirection);
|
||||
if (!hResults) {
|
||||
ANS_DBG("EVTLOG", "EvtQuery failed err=%lu", GetLastError());
|
||||
@@ -1337,6 +1421,7 @@ namespace ANSCENTER
|
||||
}
|
||||
|
||||
std::string out;
|
||||
uint64_t highestRecordId = 0;
|
||||
constexpr DWORD kBatch = 64;
|
||||
EVT_HANDLE events[kBatch];
|
||||
DWORD returned = 0;
|
||||
@@ -1367,6 +1452,15 @@ namespace ANSCENTER
|
||||
}
|
||||
std::wstring xml(buf.data());
|
||||
|
||||
// Track the highest RecordID we've seen this call so we can
|
||||
// persist it as the new watermark on exit. Done before the
|
||||
// continue-on-malformed-XML paths below so an unrenderable
|
||||
// event still advances the watermark.
|
||||
if (trackWatermark) {
|
||||
uint64_t rid = ExtractRecordIdFromXml(xml);
|
||||
if (rid > highestRecordId) highestRecordId = rid;
|
||||
}
|
||||
|
||||
// ---- TimeCreated SystemTime='2026-05-18T11:52:07.123Z' ----
|
||||
// EvtRender produces either single- or double-quoted attrs
|
||||
// depending on Windows version, so handle both.
|
||||
@@ -1462,18 +1556,89 @@ namespace ANSCENTER
|
||||
}
|
||||
EvtClose(hResults);
|
||||
|
||||
// Persist watermark BEFORE clearing — once EvtClearLog succeeds,
|
||||
// future events restart at RecordID 1, and we'd never see them
|
||||
// again if the watermark stayed at e.g. 547.
|
||||
// Special case: if clear is also going to succeed, the new
|
||||
// watermark is irrelevant (we'll reset on next call via the
|
||||
// GetChannelMaxRecordId check), so writing it here is harmless.
|
||||
if (trackWatermark && highestRecordId > 0) {
|
||||
WriteAnsLoggerWatermark(highestRecordId);
|
||||
ANS_DBG("EVTLOG", "watermark updated to %llu", highestRecordId);
|
||||
}
|
||||
|
||||
if (clearAfterRead) {
|
||||
// Clears the entire Application channel — see header warning.
|
||||
// DIAGNOSTIC: also print to stderr so callers without DebugView
|
||||
// can see what's going on. Common failure codes:
|
||||
// 5 ERROR_ACCESS_DENIED — process is not elevated
|
||||
// 1314 ERROR_PRIVILEGE_NOT_HELD — token missing SeSecurityPriv
|
||||
// 87 ERROR_INVALID_PARAMETER — channel name wrong
|
||||
if (!EvtClearLog(nullptr, L"Application", nullptr, 0)) {
|
||||
DWORD e = GetLastError();
|
||||
ANS_DBG("EVTLOG", "EvtClearLog failed err=%lu (need admin)", e);
|
||||
std::fprintf(stderr,
|
||||
"[ANSUtilities] EvtClearLog(Application) FAILED, "
|
||||
"GetLastError=%lu (5=AccessDenied, 1314=PrivNotHeld)\n", e);
|
||||
} else {
|
||||
ANS_DBG("EVTLOG", "EvtClearLog: Application channel cleared");
|
||||
std::fprintf(stderr,
|
||||
"[ANSUtilities] EvtClearLog(Application) OK\n");
|
||||
// Clear succeeded → counter resets to 1, so our watermark
|
||||
// is stale. Reset it now so the next call doesn't skip
|
||||
// legitimate new events whose RecordID < old watermark.
|
||||
if (trackWatermark) {
|
||||
WriteAnsLoggerWatermark(0);
|
||||
ANS_DBG("EVTLOG", "watermark reset to 0 after clear");
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Public: full read, no skip ------------------------------------
|
||||
std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) {
|
||||
// XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE).
|
||||
// Forward direction keeps chronological insertion order so output
|
||||
// matches a fresh "oldest first" scroll through Event Viewer.
|
||||
return ReadAnsLoggerEventsImpl(
|
||||
L"*[System[Provider[@Name='ANSLogger'] and Level=2]]",
|
||||
clearAfterRead,
|
||||
/*trackWatermark=*/false);
|
||||
}
|
||||
|
||||
// ---- Public: incremental read using HKCU watermark -----------------
|
||||
std::string ANSUtilities::GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead) {
|
||||
uint64_t watermark = ReadAnsLoggerWatermark();
|
||||
|
||||
// Channel-clear detection: if the channel's current max RecordID
|
||||
// is lower than our stored watermark, the log was cleared (by us
|
||||
// or by something else like Event Viewer's "Clear Log") and the
|
||||
// counter restarted at 1. Reset the watermark so we don't skip
|
||||
// events 1..watermark that are actually fresh.
|
||||
uint64_t channelMax = GetChannelMaxRecordId(L"Application");
|
||||
if (channelMax > 0 && watermark > channelMax) {
|
||||
ANS_DBG("EVTLOG", "watermark reset: stored=%llu channelMax=%llu "
|
||||
"(channel was cleared externally)",
|
||||
watermark, channelMax);
|
||||
watermark = 0;
|
||||
WriteAnsLoggerWatermark(0);
|
||||
}
|
||||
|
||||
// Embed the watermark in the XPath so Windows does the filtering;
|
||||
// we never see events <= watermark, which is more efficient than
|
||||
// post-filtering thousands of events on the client side.
|
||||
wchar_t queryBuf[256];
|
||||
swprintf_s(queryBuf, _countof(queryBuf),
|
||||
L"*[System[Provider[@Name='ANSLogger'] and Level=2 and "
|
||||
L"(EventRecordID>%llu)]]",
|
||||
watermark);
|
||||
ANS_DBG("EVTLOG", "GetANSLoggerErrorEventsSinceLastCall watermark=%llu",
|
||||
watermark);
|
||||
return ReadAnsLoggerEventsImpl(queryBuf, clearAfterRead,
|
||||
/*trackWatermark=*/true);
|
||||
}
|
||||
|
||||
} // namespace ANSCENTER
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -161,14 +161,40 @@ namespace ANSCENTER {
|
||||
// Time is converted to the user's local timezone and formatted
|
||||
// using LOCALE_USER_DEFAULT (matches Event Viewer's display).
|
||||
//
|
||||
// If `clearAfterRead` is true, calls EvtClearLog on the entire
|
||||
// Application channel after reading. WARNING: this wipes every
|
||||
// event from every source in the Application log, not just
|
||||
// ANSLogger entries — there is no per-event delete API in
|
||||
// Windows. Requires Administrator privileges; without elevation
|
||||
// the clear silently fails (events are still returned).
|
||||
// clearAfterRead=true behaviour:
|
||||
// * Calls EvtClearLog on the entire Application channel after
|
||||
// reading. WARNING: this wipes every event from every source
|
||||
// in the Application log, not just ANSLogger entries — there
|
||||
// is no per-event delete API in Windows.
|
||||
// * REQUIRES THE CALLING PROCESS TO BE ELEVATED (run as
|
||||
// Administrator). Without elevation, EvtClearLog returns
|
||||
// ERROR_ACCESS_DENIED (Win32 error 5) and the events remain
|
||||
// in the log. The read still succeeds either way.
|
||||
// * Failures are reported on stderr in the form
|
||||
// "[ANSUtilities] EvtClearLog(Application) FAILED, GetLastError=N"
|
||||
// and via DebugView under the "EVTLOG" tag. The C++ return
|
||||
// value does NOT signal clear success — capture stderr or
|
||||
// check Event Viewer afterwards to confirm.
|
||||
[[nodiscard]] static std::string GetANSLoggerErrorEvents(bool clearAfterRead = false);
|
||||
|
||||
// Same as GetANSLoggerErrorEvents but only returns events that
|
||||
// have NOT been returned by a previous call from this user
|
||||
// account. The highest EventRecordID seen is persisted to
|
||||
// HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
|
||||
// (REG_QWORD) and used as a Windows XPath filter
|
||||
// (EventRecordID > N) on the next call. No admin needed for the
|
||||
// skip mechanism — only for the optional clearAfterRead.
|
||||
//
|
||||
// Channel-clear handling: if Windows resets the Application
|
||||
// channel's RecordID counter (typical after EvtClearLog), this
|
||||
// function detects that the channel's current max RecordID is
|
||||
// less than the stored watermark and resets the watermark to 0
|
||||
// so no newly-written events are accidentally skipped.
|
||||
//
|
||||
// To force a re-read of all events, delete the registry value
|
||||
// above and call again.
|
||||
[[nodiscard]] static std::string GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead = false);
|
||||
|
||||
// Scan the local network for AIBOX / ANSVIS servers.
|
||||
// Runs two strategies in parallel and merges results by IP:
|
||||
// 1) UDP multicast probe to 230.50.200.150:58839 (with subnet
|
||||
@@ -398,6 +424,12 @@ extern "C" ANSULT_API int ScanANSDevicesCpp(int timeoutMs, std::string& resultJ
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle result);
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& result);
|
||||
|
||||
// Watermarked variant: only returns events not seen by previous calls.
|
||||
// Watermark is stored in HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
|
||||
// (REG_QWORD). No admin needed for the skip; only for clearAfterRead.
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCall(int clearAfterRead, LStrHandle result);
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCallCpp(int clearAfterRead, std::string& result);
|
||||
|
||||
// Unicode conversion utilities for LabVIEW
|
||||
extern "C" ANSULT_API int ANSConvertUTF8ToUTF16LE(const char* utf8Str, LStrHandle result, int includeBOM = 1);
|
||||
extern "C" ANSULT_API int ANSDecodeJsonUnicodeToUTF16LE(const char* escapedStr, LStrHandle result);
|
||||
|
||||
@@ -3093,3 +3093,42 @@ extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle
|
||||
}
|
||||
catch (...) { return -1; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GetANSLoggerErrorEventsSinceLastCall — watermark-based incremental read.
|
||||
// Stores highest EventRecordID seen in HKCU; subsequent calls return only
|
||||
// newer events. No admin needed for the skip (only for clearAfterRead).
|
||||
// ---------------------------------------------------------------------------
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCallCpp(int clearAfterRead, std::string& result) {
|
||||
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp: clearAfterRead=%d", clearAfterRead);
|
||||
try {
|
||||
result = ANSCENTER::ANSUtilities::GetANSLoggerErrorEventsSinceLastCall(clearAfterRead != 0);
|
||||
return 1;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp threw: %s", e.what());
|
||||
result.clear();
|
||||
return 0;
|
||||
}
|
||||
catch (...) {
|
||||
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp threw unknown");
|
||||
result.clear();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCall(int clearAfterRead, LStrHandle result) {
|
||||
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCall: clearAfterRead=%d", clearAfterRead);
|
||||
if (!result) return -1;
|
||||
try {
|
||||
std::string s;
|
||||
GetANSLoggerErrorEventsSinceLastCallCpp(clearAfterRead, s);
|
||||
int size = static_cast<int>(s.size());
|
||||
MgErr error = DSSetHandleSize(result, sizeof(int32) + size * sizeof(uChar));
|
||||
if (error != noErr) return -2;
|
||||
(*result)->cnt = size;
|
||||
if (size > 0) memcpy((*result)->str, s.data(), size);
|
||||
return 1;
|
||||
}
|
||||
catch (...) { return -1; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user