Compare commits
4
Commits
86b520d85c
...
da9d922498
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da9d922498 | ||
|
|
6939775960 | ||
|
|
60a8b39d24 | ||
|
|
d2479b9b07 |
@@ -98,6 +98,16 @@ namespace {
|
||||
return s.substr(0, 4) + std::string(s.size() - 8, '*') + s.substr(s.size() - 4);
|
||||
}
|
||||
|
||||
// The HWID emitted when WMI returns no hardware components at all (every
|
||||
// hash field is the "absent" marker). Every PC with broken WMI produces
|
||||
// this exact string, so it identifies "WMI broken" in customer logs.
|
||||
constexpr const char* kEmptyFingerprintHWID = "ESWJJ-LEEFC-CCTBB-JSSWJ-JLEEF";
|
||||
|
||||
constexpr const char* kEmptyFingerprintWarning =
|
||||
"Hardware fingerprint is EMPTY - WMI returned no hardware components on this PC. "
|
||||
"Licensing proceeds but the license is weakly bound to this machine. "
|
||||
"Repair WMI: run 'winmgmt /verifyrepository' (then 'winmgmt /salvagerepository' if inconsistent).";
|
||||
|
||||
// SDK identifier passed to ANSLSHelper for licensing-service auth. Despite
|
||||
// the variable name "privateKey" used at call sites, this is an 11-byte
|
||||
// SDK token that identifies the ANSCENTER product to the licensing
|
||||
@@ -2166,7 +2176,7 @@ namespace ANSCENTER
|
||||
}
|
||||
void ANSLSHelper::LoadLicense(std::string licenseKey) {
|
||||
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
std::string licenseFileName = Dash2Underscore(licenseKey)+".json";
|
||||
std::string licenseFolder = GetLicenseDir();
|
||||
@@ -2812,6 +2822,9 @@ namespace ANSCENTER
|
||||
std::wstring _registrationName = String2WString(registrationName);
|
||||
std::wstring hardwareId = KeyHelper::GetCurrentHardwareId();
|
||||
std::string _hardwareId = WString2String(hardwareId);
|
||||
if (_hardwareId == kEmptyFingerprintHWID) {
|
||||
this->_logger.LogWarn("ANSLSHelper::ValidateLicenseKey", kEmptyFingerprintWarning, __FILE__, __LINE__);
|
||||
}
|
||||
bool _overrideLicenseFile = false;
|
||||
if (activationKey.empty()) {
|
||||
if (this->_license != NULL) {// get it from there
|
||||
@@ -2888,14 +2901,13 @@ namespace ANSCENTER
|
||||
|
||||
case STATUS_INVALID_HARDWARE_ID:
|
||||
_licenseKeyStatus = INVALID_HARDWARE_ID;
|
||||
activationStatusStr = "Hardware id does not match this computer. current HWID is " + _hardwareId +
|
||||
"; client HWID is " + WString2String(licensingClient.GetHardwareId()) +
|
||||
"; Current activation key is " + WString2String(_activationKey) +
|
||||
"; client Activation key is " + WString2String(licensingClient.GetActivationKey()) +
|
||||
activationStatusStr = "Local hardware fingerprint check rejected this computer (hardware changed, or WMI returned no components). Current HWID is " + _hardwareId +
|
||||
"; stored activation key is " + mask_secret(WString2String(_activationKey)) +
|
||||
"; server activation key is " + mask_secret(WString2String(licensingClient.GetActivationKey())) +
|
||||
"; URL is " + WString2String(this->_licenseServiceURL.c_str())+
|
||||
"; ProductId is " + WString2String(wProductId) +
|
||||
"; RegistrationName is " + WString2String(_registrationName) +
|
||||
"; Status is" + std::to_string(activationStatus);
|
||||
"; Status is " + std::to_string(activationStatus);
|
||||
break;
|
||||
|
||||
case STATUS_LICENSE_EXPIRED:
|
||||
@@ -2969,7 +2981,7 @@ namespace ANSCENTER
|
||||
|
||||
if (_overrideLicenseFile) {
|
||||
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
this->_license->SetLicenseKey(_licenseKey.c_str());
|
||||
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
|
||||
@@ -2996,7 +3008,7 @@ namespace ANSCENTER
|
||||
if (_overrideLicenseFile) {
|
||||
// Save license
|
||||
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
this->_license->SetLicenseKey(_licenseKey.c_str());
|
||||
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
|
||||
@@ -3026,6 +3038,9 @@ namespace ANSCENTER
|
||||
std::wstring _registrationName = String2WString(registrationName);
|
||||
std::string _hardwareId = customHWID;
|
||||
std::wstring hardwareId = String2WString(customHWID);
|
||||
if (_hardwareId == kEmptyFingerprintHWID) {
|
||||
this->_logger.LogWarn("ANSLSHelper::ValidateLicenseWithCustomHWID", kEmptyFingerprintWarning, __FILE__, __LINE__);
|
||||
}
|
||||
bool _overrideLicenseFile = false;
|
||||
if (activationKey.empty()) {
|
||||
if (this->_license != NULL) {// get it from there
|
||||
@@ -3102,14 +3117,13 @@ namespace ANSCENTER
|
||||
|
||||
case STATUS_INVALID_HARDWARE_ID:
|
||||
_licenseKeyStatus = INVALID_HARDWARE_ID;
|
||||
activationStatusStr = "Hardware id does not match this computer. current HWID is " + _hardwareId +
|
||||
"; client HWID is " + WString2String(licensingClient.GetHardwareId()) +
|
||||
"; Current activation key is " + WString2String(_activationKey) +
|
||||
"; client Activation key is " + WString2String(licensingClient.GetActivationKey()) +
|
||||
activationStatusStr = "Local hardware fingerprint check rejected this computer (hardware changed, or WMI returned no components). Current HWID is " + _hardwareId +
|
||||
"; stored activation key is " + mask_secret(WString2String(_activationKey)) +
|
||||
"; server activation key is " + mask_secret(WString2String(licensingClient.GetActivationKey())) +
|
||||
"; URL is " + WString2String(this->_licenseServiceURL.c_str()) +
|
||||
"; ProductId is " + WString2String(wProductId) +
|
||||
"; RegistrationName is " + WString2String(_registrationName) +
|
||||
"; Status is" + std::to_string(activationStatus);
|
||||
"; Status is " + std::to_string(activationStatus);
|
||||
break;
|
||||
|
||||
case STATUS_LICENSE_EXPIRED:
|
||||
@@ -3183,7 +3197,7 @@ namespace ANSCENTER
|
||||
|
||||
if (_overrideLicenseFile) {
|
||||
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
this->_license->SetLicenseKey(_licenseKey.c_str());
|
||||
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
|
||||
@@ -3210,7 +3224,7 @@ namespace ANSCENTER
|
||||
if (_overrideLicenseFile) {
|
||||
// Save license
|
||||
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
this->_license->SetLicenseKey(_licenseKey.c_str());
|
||||
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
|
||||
@@ -3496,7 +3510,7 @@ namespace ANSCENTER
|
||||
return 0; // invalid
|
||||
}
|
||||
else {
|
||||
if (!this->_license != NULL) delete this->_license;
|
||||
if (this->_license != NULL) delete this->_license;
|
||||
this->_license = new License();
|
||||
this->_license->SetLicenseKey(_licenseKey.c_str());
|
||||
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
|
||||
|
||||
@@ -337,6 +337,8 @@ const char* HardwareId::GetCurrentHardwareId()
|
||||
|
||||
bits.WriteUInt16(hash1);
|
||||
|
||||
bool uuidFound = (hash1 != h0);
|
||||
|
||||
// CPU IDs - get up to 4 for better resilience
|
||||
propList.clear();
|
||||
|
||||
@@ -351,6 +353,8 @@ const char* HardwareId::GetCurrentHardwareId()
|
||||
cpu = NormalizeHardwareString(cpu);
|
||||
}
|
||||
|
||||
int cpuCount = (int)propList.size();
|
||||
|
||||
hash1 = (propList.size() > 0) ? HashString(propList.front().c_str()) : h0;
|
||||
hash2 = (propList.size() > 1) ? HashString(propList.back().c_str()) : h0;
|
||||
|
||||
@@ -379,6 +383,8 @@ const char* HardwareId::GetCurrentHardwareId()
|
||||
}
|
||||
propList.sort();
|
||||
|
||||
int macCount = (int)propList.size();
|
||||
|
||||
// Store up to 4 MAC hashes
|
||||
auto macIter = propList.begin();
|
||||
hash1 = (propList.size() > 0 && macIter != propList.end()) ? HashString((macIter++)->c_str()) : h0;
|
||||
@@ -406,6 +412,8 @@ const char* HardwareId::GetCurrentHardwareId()
|
||||
}
|
||||
propList.sort();
|
||||
|
||||
int hddCount = (int)propList.size();
|
||||
|
||||
auto hddIter = propList.begin();
|
||||
hash1 = (propList.size() > 0 && hddIter != propList.end()) ? HashString((hddIter++)->c_str()) : h0;
|
||||
hash2 = (propList.size() > 1 && hddIter != propList.end()) ? HashString((hddIter++)->c_str()) : h0;
|
||||
@@ -432,11 +440,34 @@ const char* HardwareId::GetCurrentHardwareId()
|
||||
insertPos += 6;
|
||||
}
|
||||
|
||||
// Field-diagnosability: log the component availability once per distinct
|
||||
// result so support can tell a weak fingerprint from a healthy one
|
||||
static string lastLoggedHwid;
|
||||
if (hardwareId != lastLoggedHwid)
|
||||
{
|
||||
lastLoggedHwid = hardwareId;
|
||||
fprintf(stderr, "[anslicensing] hardware id %s (components: uuid=%s cpu=%d mac=%d hdd=%d)\n",
|
||||
hardwareId.c_str(), uuidFound ? "ok" : "none", cpuCount, macCount, hddCount);
|
||||
|
||||
if (!uuidFound && cpuCount == 0 && macCount == 0)
|
||||
fprintf(stderr, "[anslicensing] WARNING: no hardware components readable via WMI - hardware id is NOT machine-specific. "
|
||||
"Check WMI health: winmgmt /verifyrepository (then winmgmt /salvagerepository if inconsistent)\n");
|
||||
}
|
||||
|
||||
return hardwareId.c_str();
|
||||
}
|
||||
|
||||
bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
{
|
||||
// An HWID identical to the one this machine generates right now is by
|
||||
// definition this computer. The points-based matching below can score
|
||||
// under REQUIRED_POINTS on machines with an invalid SMBIOS UUID and few
|
||||
// fingerprintable components (no PCI NIC, no readable disk serial), which
|
||||
// would reject even a freshly generated local HWID.
|
||||
const char* currentHwid = GetCurrentHardwareId();
|
||||
if (currentHwid != NULL && strcmp(hwid, currentHwid) == 0)
|
||||
return true;
|
||||
|
||||
#ifdef _WIN32
|
||||
WmiHelper wmi;
|
||||
#endif
|
||||
@@ -464,8 +495,14 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
|
||||
auto buf = base32.decode(hardwareId.c_str(), hardwareId.length(), &bufLen);
|
||||
|
||||
// The field layout is 147 bits but the HWID only encodes 16 bytes; zero-pad
|
||||
// the buffer so reading the trailing (truncated) HDD fields stays in bounds
|
||||
// and yields deterministic values instead of an out-of-bounds read.
|
||||
if (buf.size() < 20)
|
||||
buf.resize(20, 0);
|
||||
|
||||
BitStream3 bits;
|
||||
bits.Attach(buf.data(), 125);
|
||||
bits.Attach(buf.data(), 160);
|
||||
unsigned char version = 0;
|
||||
|
||||
bits.Read(&version, 3);
|
||||
@@ -479,6 +516,7 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
|
||||
// Use a points-based matching system for resilience
|
||||
int matchPoints = 0;
|
||||
bool uuidMatched = false;
|
||||
const int REQUIRED_POINTS = 2; // Need at least 2 components to match
|
||||
|
||||
// Read UUID hash
|
||||
@@ -511,6 +549,7 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
}
|
||||
}
|
||||
matchPoints += 2; // UUID/Memory match gives 2 points
|
||||
uuidMatched = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -518,9 +557,11 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
#ifdef _WIN32
|
||||
wmi.GetPropertyList("SELECT * FROM Win32_ComputerSystemProduct", "UUID", &propList);
|
||||
#endif
|
||||
if (propList.size() > 0)
|
||||
// The generator hashes the last valid UUID entry, so accept a match
|
||||
// against any entry rather than only the first one
|
||||
for (list<string>::iterator iter = propList.begin(); iter != propList.end(); iter++)
|
||||
{
|
||||
string s = NormalizeHardwareString(propList.front());
|
||||
string s = NormalizeHardwareString(*iter);
|
||||
|
||||
if ((s.length() > 1)
|
||||
&& (s != "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
|
||||
@@ -529,6 +570,8 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
if (hash1 != h0 && hash1 == HashString(s.c_str()))
|
||||
{
|
||||
matchPoints += 2; // UUID match is worth 2 points (most stable)
|
||||
uuidMatched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -639,5 +682,14 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
|
||||
// - UUID (2) + MAC (1) = 3 points ✓
|
||||
// - UUID (2) + HDD (1) = 3 points ✓
|
||||
// - CPU (1) + MAC (1) + HDD (1) = 3 points ✓ (if UUID changed but hardware same)
|
||||
return matchPoints >= REQUIRED_POINTS;
|
||||
bool accepted = (matchPoints >= REQUIRED_POINTS);
|
||||
|
||||
// Only reached when the exact-string precheck missed, i.e. the stored HWID
|
||||
// differs from the one this machine generates now. Log the breakdown so a
|
||||
// status-12 rejection in the field is diagnosable from the console output.
|
||||
fprintf(stderr, "[anslicensing] hardware id fuzzy match for %s: uuid=%s cpuMatches=%d macMatches=%d hddMatches=%d -> %d point(s), %d required -> %s\n",
|
||||
hwid, uuidMatched ? "match" : "no-match", cpuMatches, macMatches, hddMatches,
|
||||
matchPoints, REQUIRED_POINTS, accepted ? "accepted" : "REJECTED");
|
||||
|
||||
return accepted;
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <cstdio>
|
||||
|
||||
#include "except.h"
|
||||
#include "template.h"
|
||||
@@ -179,6 +180,8 @@ public:
|
||||
catch (Exception * ex)
|
||||
{
|
||||
ex->Destroy();
|
||||
fprintf(stderr, "[anslicensing] activation key is %s (SetKey failed) - product needs (re)activation\n",
|
||||
activationKey.empty() ? "empty" : "malformed");
|
||||
activationStatus = STATUS_INVALID_ACTIVATION_KEY;
|
||||
if (ownActivationTemplate) delete activationTemplate;
|
||||
return false;
|
||||
@@ -186,6 +189,7 @@ public:
|
||||
|
||||
if (!validator.IsKeyValid())
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] activation key does not validate against this license key + hardware id\n");
|
||||
activationStatus = STATUS_INVALID_ACTIVATION_KEY;
|
||||
if (ownActivationTemplate) delete activationTemplate;
|
||||
return false;
|
||||
@@ -222,6 +226,7 @@ public:
|
||||
{
|
||||
if (timeValidationMethod == USE_INTERNET_TIME) // internet time was mandatory
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] could not obtain internet time (NTP) and internet time is mandatory - check network/firewall\n");
|
||||
activationStatus = STATUS_NET_ERROR;
|
||||
if (ownActivationTemplate) delete activationTemplate;
|
||||
return false;
|
||||
@@ -243,6 +248,10 @@ public:
|
||||
if (m_licenseValidityDays < 0)
|
||||
m_licenseValidityDays = 0;
|
||||
|
||||
fprintf(stderr, "[anslicensing] license expired on %04d-%02d-%02d (grace days remaining: %d)\n",
|
||||
1900 + licenseExpirationTime.tm_year, 1 + licenseExpirationTime.tm_mon, licenseExpirationTime.tm_mday,
|
||||
m_licenseValidityDays);
|
||||
|
||||
activationStatus = STATUS_LICENSE_EXPIRED;
|
||||
|
||||
if (ownActivationTemplate) delete activationTemplate;
|
||||
@@ -465,6 +474,9 @@ public:
|
||||
generator.SetValidationData("LicenseKeyValidationData", licenseKeyValidationData.data(), licenseKeyValidationDataLen * 8);
|
||||
}
|
||||
|
||||
fprintf(stderr, "[anslicensing] requesting activation key from licensing service: %s (hwid %s)\n",
|
||||
activationTemplate->GetLicensingServiceUrl(), hardwareId.c_str());
|
||||
|
||||
try {
|
||||
activationKey = generator.GenerateKey();
|
||||
}
|
||||
@@ -472,19 +484,29 @@ public:
|
||||
{
|
||||
if ((ex->GetCode() == STATUS_NET_ERROR) && (generator.GetSigningServiceStatusCode() == 406))
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] licensing service returned HTTP 406 - payment required\n");
|
||||
m_licenseValidationResult.SetPaymentRequired(true);
|
||||
ex->Destroy();
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] activation request failed (service HTTP status %d) - check network access to the licensing service\n",
|
||||
generator.GetSigningServiceStatusCode());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (ValidateActivationKey(activationTemplate.get(), false))
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] activation key acquired and validated (service HTTP status %d)\n",
|
||||
generator.GetSigningServiceStatusCode());
|
||||
activationStatus = STATUS_SUCCESS;
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] licensing service returned an activation key that does not validate for this hardware id\n");
|
||||
throw new LicensingException(STATUS_GENERIC_ERROR, "internal error - invalid returned activation key");
|
||||
}
|
||||
|
||||
m_licenseValidationResult.m_license = std::make_unique<LicenseImpl>();
|
||||
|
||||
@@ -533,8 +555,10 @@ public:
|
||||
{
|
||||
if (parentUsesWideChar)
|
||||
{
|
||||
static string hwid = w2s(GetCurrentHardwareIdW(parentLicensingClient));
|
||||
return hwid.c_str();
|
||||
// per-instance storage: a function-local static would freeze the
|
||||
// first client's HWID for the lifetime of the process
|
||||
currentHwidCache = w2s(GetCurrentHardwareIdW(parentLicensingClient));
|
||||
return currentHwidCache.c_str();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -587,6 +611,7 @@ private:
|
||||
string licenseKey;
|
||||
string activationKey;
|
||||
string hardwareId;
|
||||
string currentHwidCache;
|
||||
string licensingServiceUrl;
|
||||
|
||||
vector<unsigned char> licenseKeyValidationData;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#define _WIN32_DCOM
|
||||
#include <iostream>
|
||||
#include <cstdio>
|
||||
#include <comdef.h>
|
||||
#include <Wbemidl.h>
|
||||
#include <list>
|
||||
@@ -52,10 +53,12 @@ public:
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
if (ownCoInitialize)
|
||||
CoUninitialize();
|
||||
|
||||
throw new exception("failed to create IWbemLocator", hres);
|
||||
// Fail soft: leave wbemServices NULL so queries return empty results.
|
||||
// Throwing here would escape callers (e.g. hardware id generation)
|
||||
// that have no exception handling and crash the host application.
|
||||
ReportFailure("CoCreateInstance(IWbemLocator)", hres);
|
||||
wbemLocator = NULL;
|
||||
return;
|
||||
}
|
||||
|
||||
// Connect to the root\cimv2 namespace with the
|
||||
@@ -76,12 +79,11 @@ public:
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
ReportFailure("ConnectServer(ROOT\\CIMV2)", hres);
|
||||
wbemLocator->Release();
|
||||
|
||||
if (ownCoInitialize)
|
||||
CoUninitialize();
|
||||
|
||||
throw new exception("could not connect to WMI", hres);
|
||||
wbemLocator = NULL;
|
||||
wbemServices = NULL;
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the IWbemServices proxy so that impersonation
|
||||
@@ -99,10 +101,12 @@ public:
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
ReportFailure("CoSetProxyBlanket", hres);
|
||||
wbemServices->Release();
|
||||
wbemLocator->Release();
|
||||
if (ownCoInitialize) CoUninitialize();
|
||||
throw new exception("could not connecto to WMI", hres);
|
||||
wbemServices = NULL;
|
||||
wbemLocator = NULL;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +119,9 @@ public:
|
||||
|
||||
void GetPropertyList(const char * wqlQuery, const char * propertyName, list<string> * propList, int maxElements = 0x7FFFFFFF)
|
||||
{
|
||||
if (wbemServices == NULL)
|
||||
return; // WMI unavailable; already reported by the constructor
|
||||
|
||||
HRESULT hres;
|
||||
|
||||
// For example, query for all the running processes
|
||||
@@ -128,7 +135,8 @@ public:
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
throw new exception("WMI query failed");
|
||||
ReportFailure(wqlQuery, hres);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -141,6 +149,14 @@ public:
|
||||
hres = pEnumerator->Next(WBEM_INFINITE, 1,
|
||||
&pclsObj, &uReturn);
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
// An enumeration error is not "no more rows" — report it,
|
||||
// otherwise a broken WMI silently yields an empty fingerprint
|
||||
ReportFailure(wqlQuery, hres);
|
||||
break;
|
||||
}
|
||||
|
||||
if(0 == uReturn)
|
||||
{
|
||||
break;
|
||||
@@ -203,6 +219,12 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
static void ReportFailure(const char * what, HRESULT hres)
|
||||
{
|
||||
fprintf(stderr, "[anslicensing] WMI failure (hr=0x%08lX): %s — hardware fingerprint will be degraded\n",
|
||||
(unsigned long)hres, what);
|
||||
}
|
||||
|
||||
bool ownCoInitialize;
|
||||
IWbemServices * wbemServices;
|
||||
IWbemLocator * wbemLocator;
|
||||
|
||||
@@ -818,9 +818,10 @@ bool Engine<T>::loadNetwork(std::string trtModelPath, const std::array<float, 3>
|
||||
std::cerr << "[GpuMemGuard] REFUSING engine load on GPU "
|
||||
<< m_options.deviceIndex << ": need ~"
|
||||
<< (buffer.size() / (1024 * 1024)) << " MiB + "
|
||||
<< (ANSCENTER::GpuMemoryGuard::Margin() / (1024 * 1024))
|
||||
<< (ANSCENTER::GpuMemoryGuard::MarginFor(totalVRAM) / (1024 * 1024))
|
||||
<< " MiB margin, only " << (freeVRAM / (1024 * 1024))
|
||||
<< " MiB free. Reduce concurrent engines/cameras or batch size."
|
||||
<< " MiB free of " << (totalVRAM / (1024 * 1024))
|
||||
<< " MiB total. Reduce concurrent engines/cameras or batch size."
|
||||
<< std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -17,8 +17,15 @@
|
||||
// cooldown so callers back off instead of hammering
|
||||
// the fragile context (which is what corrupts it).
|
||||
//
|
||||
// Margin default = 768 MiB; override at runtime with env ANSCENTER_GPU_MARGIN_MB.
|
||||
// All queries operate on the CURRENT CUDA device (callers cudaSetDevice first).
|
||||
// The margin scales with the device: total/8, clamped to [192 MiB, 768 MiB].
|
||||
// A fixed margin cannot work across the fleet — 768 MiB is 3% of a 24 GiB
|
||||
// compute card but 19% of a 4 GiB display card (RTX A400), where the desktop
|
||||
// plus the ORT CUDA arena never leave that much free and admission control can
|
||||
// therefore never pass. The 768 MiB ceiling keeps every card >= 6 GiB on
|
||||
// exactly the previous margin, so only small cards change behaviour.
|
||||
// Override at runtime with env ANSCENTER_GPU_MARGIN_MB (or SetMargin); an
|
||||
// explicit override wins over scaling. All queries operate on the CURRENT CUDA
|
||||
// device (callers cudaSetDevice first).
|
||||
// ============================================================================
|
||||
#include <cuda_runtime.h>
|
||||
#include <atomic>
|
||||
@@ -32,8 +39,24 @@ namespace ANSCENTER {
|
||||
class GpuMemoryGuard {
|
||||
public:
|
||||
// ---- configuration ----------------------------------------------------
|
||||
static size_t Margin() { return s_marginBytes.load(std::memory_order_relaxed); }
|
||||
static void SetMargin(size_t b) { s_marginBytes.store(b, std::memory_order_relaxed); }
|
||||
// Effective margin for a device with 'totalB' VRAM. An explicit override
|
||||
// (env or SetMargin) wins; otherwise scale to the card.
|
||||
static size_t MarginFor(size_t totalB) {
|
||||
if (size_t ov = s_marginOverride.load(std::memory_order_relaxed)) return ov;
|
||||
size_t m = totalB / kMarginDivisor;
|
||||
if (m < kMarginMin) m = kMarginMin;
|
||||
if (m > kMarginMax) m = kMarginMax;
|
||||
return m;
|
||||
}
|
||||
// Effective margin for the CURRENT device. Prefer MarginFor() where the
|
||||
// caller already has a total from Query() — this re-queries.
|
||||
static size_t Margin() {
|
||||
size_t freeB = 0, totalB = 0;
|
||||
if (!Query(freeB, totalB)) return kMarginMax;
|
||||
return MarginFor(totalB);
|
||||
}
|
||||
// b == 0 restores device-scaled margins.
|
||||
static void SetMargin(size_t b) { s_marginOverride.store(b, std::memory_order_relaxed); }
|
||||
|
||||
// ---- (1) admission control at load ------------------------------------
|
||||
// True if 'needBytes' can be committed on the current device while keeping
|
||||
@@ -42,7 +65,7 @@ public:
|
||||
static bool CanLoad(size_t needBytes) {
|
||||
size_t freeB = 0, totalB = 0;
|
||||
if (!Query(freeB, totalB)) return true;
|
||||
return freeB >= needBytes + Margin();
|
||||
return freeB >= needBytes + MarginFor(totalB);
|
||||
}
|
||||
|
||||
// ---- (2) pressure guard at inference ----------------------------------
|
||||
@@ -52,7 +75,7 @@ public:
|
||||
if (BreakerOpen()) return true;
|
||||
size_t freeB = 0, totalB = 0;
|
||||
if (!Query(freeB, totalB)) return false;
|
||||
return freeB < Margin();
|
||||
return freeB < MarginFor(totalB);
|
||||
}
|
||||
|
||||
// ---- (3) OOM-safe alloc + circuit breaker -----------------------------
|
||||
@@ -80,16 +103,20 @@ private:
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
static size_t InitMargin() {
|
||||
// 0 = no override, use device-scaled margin.
|
||||
static size_t InitMarginOverride() {
|
||||
if (const char* e = std::getenv("ANSCENTER_GPU_MARGIN_MB")) {
|
||||
long mb = std::atol(e);
|
||||
if (mb > 0) return static_cast<size_t>(mb) * 1024ULL * 1024ULL;
|
||||
}
|
||||
return 768ULL * 1024 * 1024; // 768 MiB
|
||||
return 0;
|
||||
}
|
||||
|
||||
static constexpr int64_t kCooldownMs = 1500; // breaker cooldown after OOM
|
||||
inline static std::atomic<size_t> s_marginBytes{ InitMargin() };
|
||||
static constexpr size_t kMarginDivisor = 8; // margin = total/8 ...
|
||||
static constexpr size_t kMarginMin = 192ULL * 1024 * 1024; // ... clamped
|
||||
static constexpr size_t kMarginMax = 768ULL * 1024 * 1024; // (prev. fixed value)
|
||||
inline static std::atomic<size_t> s_marginOverride{ InitMarginOverride() };
|
||||
inline static std::atomic<int64_t> s_breakerUntilMs{ 0 };
|
||||
};
|
||||
|
||||
|
||||
@@ -17,6 +17,24 @@
|
||||
#define FR_END_TIMER(name, label)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
// Batch >1 only helps when several faces arrive in one frame, but the TRT
|
||||
// workspace grows ~linearly with maxBatchSize (~54 MiB per batch unit for
|
||||
// this model). The batch-4 profile was tuned for 8 GB GPUs; on smaller
|
||||
// cards (e.g. 4 GB RTX A400) that workspace crowds out the other engines
|
||||
// sharing the card. Below the 8 GB class, fall back to single-face
|
||||
// batches — results are identical, multi-face frames just run
|
||||
// sequentially. Threshold is 7.5 GiB because 8 GB cards report slightly
|
||||
// under 8192 MiB (~8188).
|
||||
int VramCappedBatch(int desiredBatch, int deviceIndex) {
|
||||
cudaDeviceProp prop{};
|
||||
if (cudaGetDeviceProperties(&prop, deviceIndex >= 0 ? deviceIndex : 0) != cudaSuccess)
|
||||
return desiredBatch; // can't query — keep the configured profile
|
||||
const size_t totalMiB = prop.totalGlobalMem / (1024ULL * 1024ULL);
|
||||
return (totalMiB >= 7680) ? desiredBatch : 1;
|
||||
}
|
||||
}
|
||||
|
||||
namespace ANSCENTER {
|
||||
std::string ANSFaceRecognizer::GetOpenVINODevice() {
|
||||
ov::Core core;
|
||||
@@ -97,8 +115,10 @@ namespace ANSCENTER {
|
||||
// comfortably on 8 GB GPUs while freeing ~1.5 GB VRAM vs max=32
|
||||
// — most scenes have ≤4 faces visible, so throughput cost is
|
||||
// near-zero (amortized per-face latency drops too at lower batch).
|
||||
m_options.optBatchSize = 4;
|
||||
m_options.maxBatchSize = 4;
|
||||
// VramCappedBatch drops this to 1 on sub-8 GB cards.
|
||||
const int frBatch = VramCappedBatch(4, _modelConfig.gpuDeviceIndex);
|
||||
m_options.optBatchSize = frBatch;
|
||||
m_options.maxBatchSize = frBatch;
|
||||
|
||||
m_options.maxInputHeight = GPU_FACE_HEIGHT;
|
||||
m_options.minInputHeight = GPU_FACE_HEIGHT;
|
||||
@@ -259,9 +279,10 @@ namespace ANSCENTER {
|
||||
// engine built/looked-up here has a different profile than the one
|
||||
// Initialize() expects, causing either a stale `.b32` rebuild every
|
||||
// launch (wasting 30-60s) or a load-time profile mismatch.
|
||||
// Keep in sync with lines 100-114.
|
||||
m_options.optBatchSize = 4;
|
||||
m_options.maxBatchSize = 4;
|
||||
// Keep in sync with the Initialize() block (same VramCappedBatch call).
|
||||
const int frBatch = VramCappedBatch(4, _modelConfig.gpuDeviceIndex);
|
||||
m_options.optBatchSize = frBatch;
|
||||
m_options.maxBatchSize = frBatch;
|
||||
|
||||
m_options.maxInputHeight = GPU_FACE_HEIGHT;
|
||||
m_options.minInputHeight = GPU_FACE_HEIGHT;
|
||||
@@ -490,8 +511,12 @@ namespace ANSCENTER {
|
||||
if (engineType == EngineType::NVIDIA_GPU) {
|
||||
// Initialize TensorRT engine via shared pool
|
||||
if (!m_trtEngine) {
|
||||
m_options.optBatchSize = 8;
|
||||
m_options.maxBatchSize = 32;
|
||||
// Note this path still uses the legacy 8/32 profile on 8 GB+
|
||||
// cards (a .b32 engine costs ~1.5 GB more workspace than .b4).
|
||||
// The VRAM cap only stops it from being fatal on small cards.
|
||||
const int frMaxBatch = VramCappedBatch(32, _modelConfig.gpuDeviceIndex);
|
||||
m_options.optBatchSize = (frMaxBatch < 8) ? frMaxBatch : 8;
|
||||
m_options.maxBatchSize = frMaxBatch;
|
||||
m_options.calibrationBatchSize = 8;
|
||||
m_options.deviceIndex = _modelConfig.gpuDeviceIndex;
|
||||
m_options.engineFileDir = _modelFolder;
|
||||
|
||||
Reference in New Issue
Block a user