Skip to content

Cpp Data Collector

Andrei edited this page Oct 16, 2026 · 4 revisions

C++ Data Collector

The native C++ data collector (hsm::collector) is the modern, CLR-free client library for sending sensor data to an HSM server from C++. It is a header-only C++ RAII API over a stable C ABI, consumed with CMake find_package (or vendored source). This page is for a developer integrating it into an application (e.g. an aggregator).

Looking to relink an existing consumer that used the old C++/CLI DataCollectorProxy wrapper instead of writing a fresh integration? That is a different, compatibility-only path — ask the maintainers; this page covers the native API.


1. What it is

  • Library: hsm::collector (CMake project HsmCollectorNative), in src/native/collector/.
  • API: header-only C++ RAII (#include <hsm_collector/hsm_collector.hpp>) over an extern "C" ABI (hsm_collector.h) — no CLR / .NET.
  • Language / build: C++17, CMake ≥ 3.21, MSVC or Clang/GCC. The core and custom sensors are cross-platform (CI builds Windows + Linux). The built-in OS/process/disk sensors read Win32 on Windows and /proc + statvfs on Linux (call InstallLinuxMetricSources() before Start(), see §5); the network, Windows-info and service-status groups are Windows-only.
  • Current version: 0.11.1 (registry tag collector-v0.11.1). The library reports its own version as HSM_COLLECTOR_VERSION_STRING and posts it to .module/Collector version.
  • Transport: libcurl (HTTPS), enabled with the HSM_COLLECTOR_HTTP build option.
  • Errors: every failing call throws hsm::collector::Error (a std::runtime_error).

Two exported CMake targets:

  • hsm_collector::hsm_collector_cpp — the header-only C++ RAII API (link this).
  • hsm_collector::hsm_collector_core — the static core + C ABI (pulled in automatically).

2. How to get it (recommended)

The collector is a static library with transitive dependencies (libcurl + Win32 iphlpapi/pdh), so the clean way to consume it is via CMake/vcpkg, which resolves those for you.

A. vcpkg registry (recommended)

This repository is itself a vcpkg registry that serves the hsm-collector package, so a project can depend on it with no checkout of the HSM sources — the closest thing to a NuGet-style experience for C++.

  1. Add the registry to your project's vcpkg-configuration.json:
{
  "default-registry": {
    "kind": "git",
    "repository": "https://github.com/microsoft/vcpkg",
    "baseline": "<your microsoft/vcpkg baseline>"
  },
  "registries": [
    {
      "kind": "git",
      "repository": "https://github.com/SoftFx/Hierarchical-Sensor-Monitoring",
      "baseline": "<HSM repo master commit>",
      "packages": ["hsm-collector"]
    }
  ]
}

Run vcpkg x-update-baseline to fill/refresh both baselines to each registry's latest commit — no need to copy commit SHAs by hand.

  1. Declare the dependency in your vcpkg.json (http = the libcurl HTTPS transport):
{
  "dependencies": [
    { "name": "hsm-collector", "features": ["http"] }
  ]
}
  1. Configure with the vcpkg toolchain, then link in CMake:
find_package(hsm_collector CONFIG REQUIRED)
target_link_libraries(your_app PRIVATE hsm_collector::hsm_collector_cpp)

vcpkg fetches and builds hsm-collector and its dependencies (libcurl for [http], plus the Win32 iphlpapi/pdh) automatically — this is the install path CI verifies in the hsm-collector-registry lane.

B. find_package from a local install (no registry)

Install the collector to a prefix, then point your build at it:

cmake -S src/native/collector -B build/collector `
  -DCMAKE_TOOLCHAIN_FILE=<vcpkg>/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows `
  -DHSM_COLLECTOR_HTTP=ON -DHSM_COLLECTOR_INSTALL=ON
cmake --build build/collector --config Release
cmake --install build/collector --config Release --prefix <install-prefix>
# in your CMakeLists.txt (with CMAKE_PREFIX_PATH pointing at <install-prefix>)
find_package(hsm_collector CONFIG REQUIRED)
target_link_libraries(your_app PRIVATE hsm_collector::hsm_collector_cpp)

The installed hsm_collectorConfig.cmake re-resolves Threads and (when built with HTTP) CURL for you. This is the path exercised by the CI install-consume lane. Canonical consumer: examples/console/standalone/CMakeLists.txt.

C. Vendor the source + add_subdirectory

Copy or submodule src/native/collector/ into your tree and:

add_subdirectory(external/hsm_collector)
target_link_libraries(your_app PRIVATE hsm_collector::hsm_collector_cpp)

No prebuilt binaries → no MSVC-runtime/ABI matching to worry about; your build compiles the collector.

libcurl: for the HTTPS transport (HSM_COLLECTOR_HTTP=ON) the consumer must provide libcurl — easiest via vcpkg (curl:x64-windows). conan and vcpkg consumption are also supported and covered by CI (conan-consume / vcpkg-consume).


3. How to use it

Prerequisites

  • The HSM server address and its Sensor API port (default 44330).
  • A product access key (a GUID) — create it in the HSM web UI; see Access Keys. The key decides which product the data lands under.

Quick start — a complete, copy-paste project

Four files. vcpkg-configuration.json is the registry snippet from §2A above; the rest:

vcpkg.json

{
  "name": "my-app",
  "version": "0.1.0",
  "dependencies": [
    { "name": "hsm-collector", "features": ["http"] }
  ]
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.21)
project(my_app LANGUAGES CXX)

find_package(hsm_collector CONFIG REQUIRED)

add_executable(my_app main.cpp)
target_link_libraries(my_app PRIVATE hsm_collector::hsm_collector_cpp)
target_compile_features(my_app PRIVATE cxx_std_17)

main.cpp

#include <hsm_collector/hsm_collector.hpp>

#include <chrono>
#include <iostream>
#include <thread>

int main()
{
    namespace hc = hsm::collector;
    try
    {
        hc::CollectorOptions options;
        options.access_key     = "<product-access-key>";  // required — see Prerequisites
        options.server_address = "https://<hsm-host>";    // required
        options.port           = 44330;                   // Sensor API port
        options.module         = "MyApp";                 // where it appears in the tree

        hc::Collector collector(options);
        auto load = collector.CreateDoubleSensor("MyApp/load");

        collector.Start();
        for (int i = 0; i < 5; ++i)
        {
            load.AddValue(1.5 * i);
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        collector.Stop();   // flushes what's queued
    }
    catch (const hsm::collector::Error& ex)
    {
        std::cerr << "hsm collector: " << ex.what() << '\n';
        return 1;
    }
    return 0;
}

Build (vcpkg resolves hsm-collector + libcurl from the registry):

cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=<vcpkg>/scripts/buildsystems/vcpkg.cmake
cmake --build build --config Release

Run it, then open the HSM web UI: the sensor shows up in the tree under your product as MyApp/load. If nothing appears, check the access key and that the host/port are reachable — failures surface as hsm::collector::Error (see the catch above).

Walkthrough

Minimal integration (distilled from the runnable examples/console/main.cpp):

#include <hsm_collector/hsm_collector.hpp>
namespace hc = hsm::collector;

hc::CollectorOptions options;
options.access_key      = "<product-access-key>";   // required
options.server_address  = "https://<hsm-host>";     // required
options.port            = 44330;                    // Sensor API port
options.module          = "<Module>";               // node name in the tree
options.computer_name   = "<host>";

hc::Collector collector(options);

collector.SetLogger([](hc::LogLevel lvl, const std::string& msg) { /* route to your log */ });
collector.AddLifecycleListener([](hc::CollectorStatus st) { /* observe start/stop */ });

// Built-in module sensors (collector alive / version / errors + queue self-diagnostics).
collector.AddAllModuleSensors("1.0.0.0");

// A custom double sensor with a "> 100" threshold alert (fluent DSL; attach before or after Start).
auto alert = collector.CreateAlert(hc::AlertKind::Instant)
                 .If(hc::AlertProperty::Value, hc::AlertOperation::GreaterThan, "100")
                 .ThenNotify("[$product]$path $operation $target")
                 .WithIcon(hc::AlertIcon::Warning);
auto temperature = collector.CreateDoubleSensor("Example/Temperature");
temperature.AttachAlert(alert);

auto requests = collector.CreateRateSensor("Example/Requests");
auto uptime   = collector.CreateFunctionSensor("Example/UptimeTicks",
                    std::chrono::seconds(1), []() -> std::int32_t { return get_ticks(); });

collector.Start();
temperature.AddValue(93.5);
requests.AddValue(1.0);
// ... work ...
collector.Stop();   // the destructor also disposes + joins; Start/Stop throw hc::Error on failure

Wrap construction / registration in try { … } catch (const hc::Error& e) { … }.

Lifetime note: state captured by reference into a collector-owned callback (e.g. a function sensor's lambda) must outlive the Collector — the destructor joins the scheduler thread, so declare such state before the collector.


4. CollectorOptions reference

Field Meaning
access_key (required) Product access key (GUID) on the HSM server
server_address (required) e.g. https://host
port Sensor API port (default 443; the repo server uses 44330)
module, computer_name, client_name Placement/identity in the sensor tree
package_collect_period_ms Send batching period (0 → default 15000)
max_queue_size, max_values_in_package, request_timeout_ms, max_sensors Bounds (0 → managed defaults)
allow_untrusted_server_certificate, allow_plaintext_transport TLS/transport relaxations (dev only)
exception_deduplicator_window_ms, max_deduplicated_messages Error-log dedup window
extra_request_headers, on_server_directive Server-directive channel (inject headers; observe X-Hsm-Directive responses)

Any numeric 0 means "use the managed default".


5. Sensors and alerts

  • Instant sensors: CreateBool/Int/Double/String/EnumSensor(...).
  • Bar sensors: CreateIntBarSensor / CreateDoubleBarSensor (min/mean/max/count and, since 0.11.0, the population standard deviation StdDev over a period; the server draws it as a band).
  • Rate: CreateRateSensor (double).
  • Last-value: CreateLastValue{Bool,Int,Double,String}Sensor.
  • Function (pull): CreateFunctionSensor / CreateValuesFunctionSensor (int).
  • File: CreateFileSensor(...) → SendFile(path) / AddContent(string).
  • Built-in groups: AddSystemMonitoringSensors, AddProcessMonitoringSensors, AddDiskMonitoringSensors, AddAllNetworkSensors, AddCollectorMonitoringSensors, AddAllModuleSensors(version), EnableServiceStatusMonitoring(name, period) (Windows).
  • Alerts: collector.CreateAlert(kind).If(property, op, "target").ThenNotify("…").WithIcon(…) → sensor.AttachAlert(alert). Before Start() the alert rides the Start registration; attached while the collector runs (0.9.1) the sensor is re-registered at the worker's next cycle.

Registering while running, descriptions, Linux built-ins (0.9 – 0.11)

  • Sensors created after Start() are registered on the server (0.9.1). Any Create…Sensor call while the collector runs queues the registration; the worker posts it to /commands before that cycle's values, and Stop() flushes it first. Before 0.9.1 such a sensor reached the server through its values only, without metadata or alerts.
  • Description updates (0.10.0). hsm_sensor_set_description(sensor.handle(), "text") (C ABI; there is no RAII wrapper yet) replaces the registration description and re-registers the sensor with the same rules as AttachAlert. Pass "" to clear a description the server already has; NULL means "unchanged".
  • Linux built-in sensors (0.7.2). On Linux call collector.InstallLinuxMetricSources() before Start(), then the usual AddSystemMonitoringSensors() / AddProcessMonitoringSensors() / AddDiskMonitoringSensors() post live values: Total CPU (/proc/stat), Free RAM memory (/proc/meminfo MemAvailable), Free space on disk and its prediction (statvfs("/")), Process CPU / Process memory / Process thread count (/proc/self). Each reads the same OS source with the same normalization as the managed Unix sensor, so the two collectors report identical values. Off Linux the call throws hsm::collector::Error.
  • Enum sensors with full options (0.9.0). hsm_collector_create_enum_sensor_with_sensor_options registers an enum sensor with both its EnumOptions and the complete sensor-options surface.
  • Lifecycle markers (0.7.4). .module/Version and .module/Collector version post a value with a Start: … / Stop: … comment on every Start and Stop.

The full API surface is in include/hsm_collector/ (hsm_collector.hpp is the umbrella include).


6. More examples

Runnable examples under src/native/collector/examples/: console (every sensor kind, no server needed), server-monitor, windows-monitor, crypto-monitor.


7. Where to look (authoritative sources)

What Where
Full runnable usage examples/console/main.cpp
find_package consumer examples/console/standalone/CMakeLists.txt
Public API headers include/hsm_collector/
Behavior vs the old managed collector docs/native-collector-migration.md

If a call throws or a sensor doesn't appear on the server, the useful details to report are: the hsm::collector::Error message, your CollectorOptions (minus the key), and the CMake consumption mode (find_package vs add_subdirectory).

Clone this wiki locally