Documentation
¶
Overview ¶
Package metrics provides efficient metrics collection for NFTBan This collector replaces slow bash-based metrics with fast Go implementation
============================================================================= NFTBan v1.88 - Chain Presence Evidence Collector (M87-4) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_chains" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Collects chain presence for Phase 1 evidence" meta:inventory.files="internal/metrics/evidence_chains.go" meta:inventory.binaries="nft" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="root"
Collects chain presence per family. Returns ChainInfo (exists bool). =============================================================================
============================================================================= NFTBan v1.88 - Correlation Engine (M87-6) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_correlate" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Evidence correlation engine for metrics Phase 1" meta:inventory.files="internal/metrics/evidence_correlate.go" meta:inventory.binaries="" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="none"
Pure function. No exec calls. No side effects. No health derivation.
Correlation is DIAGNOSTIC only: - Cannot map to PROTECTED/DEGRADED/DOWN - Cannot influence exit codes - Cannot produce aggregate system state - Cannot be summarized as "healthy/unhealthy"
It answers: "does kernel evidence agree with validator interpretation?" =============================================================================
============================================================================= NFTBan v1.88 - Journal Evidence Collector (M88-2) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_journal" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-16" meta:description="Collects journal-based evidence for metrics" meta:inventory.files="internal/metrics/evidence_journal.go" meta:inventory.binaries="journalctl" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="root"
Collects bounded journal evidence for LoginMon activity. Uses the same journalctl strategy as the validator (A1-1 pattern): global query, bounded window, filter in code. =============================================================================
============================================================================= NFTBan v1.88 - Set Element Evidence Collector (M87-3) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_sets" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Collects set element counts for Phase 1 evidence" meta:inventory.files="internal/metrics/evidence_sets.go" meta:inventory.binaries="nft" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="root"
Collects per-set element counts using nft JSON output. Returns structured SetInfo (exists + count) per set. =============================================================================
============================================================================= NFTBan v1.89 - Evidence Snapshot Builder + Renderers ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_snapshot" meta:type="package" meta:version="1.89.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Builds and renders Phase 1 evidence snapshots" meta:inventory.files="internal/metrics/evidence_snapshot.go" meta:inventory.binaries="" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="root"
v1.89 INV-M-001/002: Evidence layer makes ZERO direct nft calls. All kernel data (counters, sets, chains) comes from the validator, which is the sole kernel-query authority.
Collect once → render many. Metrics report evidence; validator reports interpretation. =============================================================================
============================================================================= NFTBan v1.88 - Evidence Types (Phase 1 Canonical Model) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_types" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Canonical evidence types for metrics Phase 1" meta:inventory.files="internal/metrics/evidence_types.go" meta:inventory.binaries="" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="none"
Types only. No collection logic. No rendering logic. Metrics report evidence; validator reports interpretation. =============================================================================
============================================================================= NFTBan v1.88 - Validator Snapshot Bridge (M87-5) ============================================================================= SPDX-License-Identifier: MPL-2.0 meta:name="evidence_validator" meta:type="package" meta:version="1.88.0" meta:owner="Antonios Voulvoulis <contact@nftban.com>" meta:created_date="2026-04-15" meta:description="Read-only bridge to validator JSON for metrics evidence" meta:inventory.files="internal/metrics/evidence_validator.go" meta:inventory.binaries="nftban-validate" meta:inventory.env_vars="" meta:inventory.config_files="" meta:inventory.systemd_units="" meta:inventory.network="" meta:inventory.privileges="root"
Read-only bridge: calls nftban-validate --json once and extracts status, module effective states, and finding codes. Metrics MUST NOT modify validator truth. This is observation only. =============================================================================
Package metrics provides Prometheus metrics for NFTBan operations This file contains application-level metrics for ban/unban operations, feed loading, sync operations, and authentication
Index ¶
- Constants
- Variables
- func CollectChainPresence(ctx context.Context) map[string]ChainInfo
- func CollectRuleCounters()
- func CollectSetElements(ctx context.Context) map[string]SetInfo
- func CorrelateEvidence(counters map[string]CounterValue, sets map[string]SetInfo, ...) map[string]string
- func RecordAPIRequest(endpoint, method string, statusCode int, durationSec float64)
- func RecordAuthAttempt(success bool)
- func RecordAuthFailure(reason string)
- func RecordBan(source, family string)
- func RecordBanByCountry(country string)
- func RecordBanEnforcementLatency(op string, latencySec float64)
- func RecordBanError(source, errorType string)
- func RecordBanWithIP(source, family, ip string)
- func RecordDDoSDetection(attackType string)
- func RecordDDoSMitigation(action string)
- func RecordDetectionByCountry(country, module string)
- func RecordError(module, errorType string)
- func RecordEventBusDrop()
- func RecordEventGenerated(eventType string)
- func RecordEventsApplied(lane string, count int)
- func RecordFeedLastSuccess(feedName string, mtime time.Time)
- func RecordFeedLoad(feedName string, durationSec float64, success bool)
- func RecordIPCConnectionWait(waitSec float64)
- func RecordIPCRejection(reason string)
- func RecordIPCRequest(method string, success bool, latencySec float64)
- func RecordLoginmonBan(family, reason string)
- func RecordLoginmonDetection(reason, service string)
- func RecordLoginmonDetectionLatency(latencySec float64)
- func RecordLoginmonScoreAtBan(score float64)
- func RecordNFTCLI(operation string, durationSec float64, err error)
- func RecordOpQueueDrop(lane string)
- func RecordPortscanBan(family string)
- func RecordPortscanDetection(protocol string)
- func RecordReconciliationDuration(seconds float64)
- func RecordReconciliationRun()
- func RecordSuricataBan(category, family string)
- func RecordSuricataEvent(eventType string)
- func RecordSuricataProcessingLatency(latencySec float64)
- func RecordSync(operation string, durationSec float64, success bool)
- func RecordSyncIPChanges(added, removed int)
- func RecordUnban(source, family string)
- func RecordUnbanError(source, errorType string)
- func RecordUnbanWithIP(source, family, ip string)
- func RegisterWithSampler()
- func RenderHuman(snap *EvidenceSnapshot, w io.Writer)
- func RenderJSON(snap *EvidenceSnapshot) ([]byte, error)
- func SetActiveBans(family, banType string, count int)
- func SetCIDRCurrentTotal(count int)
- func SetCIDRLimitHard(limit int)
- func SetDDoSActiveMitigations(count int)
- func SetFeedIPsLoaded(feedName, family string, count float64)
- func SetIPCConnectionsActive(count int)
- func SetIPCConnectionsPeak(peak int)
- func SetIPCSemaphoreAvailable(available int)
- func SetLoginmonTrackedIPs(count int)
- func SetMemoryBudgetBytes(bytes int64)
- func SetMemoryPressureLevel(level int)
- func SetMemoryUsedPercent(percent float64)
- func SetModuleStatus(module string, enabled bool)
- func SetOpQueueUtilization(lane string, pending, capacity int64)
- func SetPermanentBansEvictable(count int)
- func SetPermanentBansProtected(count int)
- func SetPermanentBansTotal(count int)
- func SetPortAllowRules(family, protocol string, count int)
- func SetPortscanTrackedIPs(count int)
- func SetProtectionActive(active bool)
- func SetProtectionFeedsSkipped(skipped bool)
- func SetProtectionGeobanSkipped(skipped bool)
- func SetReconciliationDrift(setName string, drift float64)
- func SetReconciliationLastTimestamp(ts float64)
- func SetSchemaErrorsTotal(count int)
- func SetSchemaValidationStatus(drifted bool)
- func SetSuricataAlertsActive(count int)
- func SetSuricataEveLag(lagSeconds float64)
- func SetWhitelistOverlapCount(count int)
- func UpdateFeedStaleness(feedName string, mtime time.Time, threshold time.Duration)
- type AttackRateTracker
- type ChainInfo
- type Collector
- type ConnectionStats
- type CounterValue
- type DataFreshnessResult
- type EvidenceSnapshot
- type InterfaceStats
- type JournalEvidenceResult
- type NamedCountersResult
- type Sample
- type Sampler
- func (s *Sampler) AddSession()
- func (s *Sampler) DisableMetrics()
- func (s *Sampler) EnableMetrics()
- func (s *Sampler) GetRecentSamples(count int) []Sample
- func (s *Sampler) GetStatus() map[string]interface{}
- func (s *Sampler) IsMetricsEnabled() bool
- func (s *Sampler) Registry() *prometheus.Registry
- func (s *Sampler) RemoveSession()
- type SetInfo
- type TCPStats
- type UDPStats
- type ValidatorSnapshot
Constants ¶
const ( CorrelationMatch = "match" CorrelationExpectedLimitation = "expected_limitation" CorrelationWarning = "warning" CorrelationMismatch = "mismatch" CorrelationUnknown = "unknown" )
Correlation result values.
const DefaultFeedStaleThreshold = 48 * time.Hour
DefaultFeedStaleThreshold is the default duration after which a feed is considered stale
const EvidenceSchemaVersion = "1.88.0"
Variables ¶
var Phase1Chains = []string{
"input", "forward", "output",
"ddos_sanity", "ddos_penalty", "ddos_prefix", "ddos_protection",
"portscan_detection", "http_bot_guard",
}
Phase1Chains defines the chains checked in Phase 1.
var Phase1Sets = map[string][]string{
"ip": {
"blacklist_manual_ipv4", "blacklist_ipv4",
"http_bot_suspect", "http_bot_pending", "http_bot_allow",
"http_bot_grey", "http_bot_ban", "http_bot_emergency",
},
"ip6": {
"blacklist_manual_ipv6", "blacklist_ipv6",
"http_bot_suspect6", "http_bot_pending6", "http_bot_allow6",
"http_bot_grey6", "http_bot_ban6", "http_bot_emergency6",
},
}
Phase1Sets defines the sets collected in Phase 1.
var ValidatorBinPath = "/usr/lib/nftban/bin/nftban-validate"
ValidatorBinPath is the default validator binary path. Configurable for testing; production uses package default.
Functions ¶
func CollectChainPresence ¶ added in v1.87.0
CollectChainPresence checks which chains exist per family. Keys use stable format: "<family>:<chain_name>". If collection fails for a family, all chains in that family are marked Unknown.
func CollectRuleCounters ¶ added in v1.40.0
func CollectRuleCounters()
CollectRuleCounters extracts per-rule packet/byte counters from nftables Called from the sampler FULL tier. Tries named counters first (v1.41.0), falls back to anonymous counter extraction for backward compatibility.
func CollectSetElements ¶ added in v1.87.0
CollectSetElements returns element counts for Phase 1 sets. Keys use stable format: "<family>:<set_name>".
func CorrelateEvidence ¶ added in v1.87.0
func CorrelateEvidence( counters map[string]CounterValue, sets map[string]SetInfo, validator *ValidatorSnapshot, journal *JournalEvidenceResult, ) map[string]string
CorrelateEvidence compares kernel evidence against validator interpretation. Pure function — no exec, no side effects, no state mutation.
Inputs:
counters: from CollectNamedCounters() — may be nil sets: from CollectSetElements() — may be nil validator: from CollectValidatorSnapshot() — may be nil
Returns: module → correlation result
func RecordAPIRequest ¶
RecordAPIRequest records an API request
func RecordAuthAttempt ¶
func RecordAuthAttempt(success bool)
RecordAuthAttempt records an authentication attempt
func RecordAuthFailure ¶
func RecordAuthFailure(reason string)
RecordAuthFailure records an authentication failure with reason
func RecordBanByCountry ¶
func RecordBanByCountry(country string)
RecordBanByCountry records a ban for a specific country
func RecordBanEnforcementLatency ¶ added in v1.40.0
RecordBanEnforcementLatency records the latency of a ban enforcement operation
func RecordBanError ¶
func RecordBanError(source, errorType string)
RecordBanError records a ban operation error
func RecordBanWithIP ¶ added in v1.40.0
func RecordBanWithIP(source, family, ip string)
RecordBanWithIP records a ban and tracks start time + unique IP velocity
func RecordDDoSDetection ¶
func RecordDDoSDetection(attackType string)
RecordDDoSDetection records a DDoS attack detection
func RecordDDoSMitigation ¶
func RecordDDoSMitigation(action string)
RecordDDoSMitigation records a DDoS mitigation action
func RecordDetectionByCountry ¶
func RecordDetectionByCountry(country, module string)
RecordDetectionByCountry records a detection for a specific country and module
func RecordError ¶
func RecordError(module, errorType string)
RecordError records an error for a module
func RecordEventBusDrop ¶
func RecordEventBusDrop()
RecordEventBusDrop records a dropped event from the EventBus
func RecordEventGenerated ¶ added in v1.40.0
func RecordEventGenerated(eventType string)
RecordEventGenerated records an event published to the eventbus
func RecordEventsApplied ¶ added in v1.40.0
RecordEventsApplied records operations applied to nftables via opqueue
func RecordFeedLastSuccess ¶ added in v1.40.0
RecordFeedLastSuccess records the mtime of a successfully loaded feed file
func RecordFeedLoad ¶
RecordFeedLoad records a feed load operation with duration
func RecordIPCConnectionWait ¶
func RecordIPCConnectionWait(waitSec float64)
RecordIPCConnectionWait records time spent waiting for semaphore slot
func RecordIPCRejection ¶
func RecordIPCRejection(reason string)
RecordIPCRejection records an IPC connection rejection with reason Reasons: "at_capacity", "auth_failed", "read_error", "timeout"
func RecordIPCRequest ¶
RecordIPCRequest records an IPC request with its status
func RecordLoginmonBan ¶
func RecordLoginmonBan(family, reason string)
RecordLoginmonBan records a ban triggered by loginmon
func RecordLoginmonDetection ¶
func RecordLoginmonDetection(reason, service string)
RecordLoginmonDetection records a login failure detection
func RecordLoginmonDetectionLatency ¶
func RecordLoginmonDetectionLatency(latencySec float64)
RecordLoginmonDetectionLatency records detection processing latency
func RecordLoginmonScoreAtBan ¶
func RecordLoginmonScoreAtBan(score float64)
RecordLoginmonScoreAtBan records the score when a ban is triggered
func RecordNFTCLI ¶
RecordNFTCLI records an nft CLI command execution
func RecordOpQueueDrop ¶
func RecordOpQueueDrop(lane string)
RecordOpQueueDrop records a dropped operation due to queue backpressure lane should be "fast" (ban/unban) or "bulk" (feeds/geoban)
func RecordPortscanBan ¶
func RecordPortscanBan(family string)
RecordPortscanBan records a ban triggered by portscan detection
func RecordPortscanDetection ¶
func RecordPortscanDetection(protocol string)
RecordPortscanDetection records a port scan detection
func RecordReconciliationDuration ¶
func RecordReconciliationDuration(seconds float64)
RecordReconciliationDuration records the duration of a reconciliation cycle
func RecordReconciliationRun ¶
func RecordReconciliationRun()
RecordReconciliationRun increments the total reconciliation runs counter
func RecordSuricataBan ¶
func RecordSuricataBan(category, family string)
RecordSuricataBan records a ban triggered by Suricata alert
func RecordSuricataEvent ¶
func RecordSuricataEvent(eventType string)
RecordSuricataEvent records a Suricata event from eve.json
func RecordSuricataProcessingLatency ¶
func RecordSuricataProcessingLatency(latencySec float64)
RecordSuricataProcessingLatency records time from EVE event to ban action
func RecordSync ¶
RecordSync records a sync operation with duration
func RecordSyncIPChanges ¶
func RecordSyncIPChanges(added, removed int)
RecordSyncIPChanges records IPs added/removed during sync
func RecordUnban ¶
func RecordUnban(source, family string)
RecordUnban records a successful unban operation
func RecordUnbanError ¶
func RecordUnbanError(source, errorType string)
RecordUnbanError records an unban operation error
func RecordUnbanWithIP ¶ added in v1.40.0
func RecordUnbanWithIP(source, family, ip string)
RecordUnbanWithIP records an unban and observes ban duration if start time is known
func RegisterWithSampler ¶
func RegisterWithSampler()
RegisterWithSampler registers all nftban metrics with the global sampler's registry This should be called once during application startup
func RenderHuman ¶ added in v1.87.0
func RenderHuman(snap *EvidenceSnapshot, w io.Writer)
RenderHuman writes operator-first human-readable output.
func RenderJSON ¶ added in v1.87.0
func RenderJSON(snap *EvidenceSnapshot) ([]byte, error)
RenderJSON serializes the snapshot as canonical Phase 1 JSON.
func SetActiveBans ¶
SetActiveBans sets the current number of active bans
func SetCIDRCurrentTotal ¶
func SetCIDRCurrentTotal(count int)
SetCIDRCurrentTotal sets the current total CIDRs loaded
func SetCIDRLimitHard ¶
func SetCIDRLimitHard(limit int)
SetCIDRLimitHard sets the maximum CIDRs allowed for this server tier
func SetDDoSActiveMitigations ¶
func SetDDoSActiveMitigations(count int)
SetDDoSActiveMitigations sets the number of currently active mitigations
func SetFeedIPsLoaded ¶
SetFeedIPsLoaded sets the number of IPs loaded from a feed
func SetIPCConnectionsActive ¶
func SetIPCConnectionsActive(count int)
SetIPCConnectionsActive sets the current number of active IPC connections
func SetIPCConnectionsPeak ¶
func SetIPCConnectionsPeak(peak int)
SetIPCConnectionsPeak sets the peak concurrent connections (high water mark)
func SetIPCSemaphoreAvailable ¶
func SetIPCSemaphoreAvailable(available int)
SetIPCSemaphoreAvailable sets the number of available semaphore slots
func SetLoginmonTrackedIPs ¶
func SetLoginmonTrackedIPs(count int)
SetLoginmonTrackedIPs sets the current number of tracked IPs
func SetMemoryBudgetBytes ¶
func SetMemoryBudgetBytes(bytes int64)
SetMemoryBudgetBytes sets the configured memory budget in bytes
func SetMemoryPressureLevel ¶
func SetMemoryPressureLevel(level int)
SetMemoryPressureLevel sets the current memory pressure level Levels: 0=normal, 1=warning, 2=high, 3=critical
func SetMemoryUsedPercent ¶
func SetMemoryUsedPercent(percent float64)
SetMemoryUsedPercent sets the current memory usage as a percentage of budget
func SetModuleStatus ¶
SetModuleStatus sets the enabled status of a module
func SetOpQueueUtilization ¶
SetOpQueueUtilization sets the current queue utilization percentage pending = current pending operations, capacity = max queue size
func SetPermanentBansEvictable ¶
func SetPermanentBansEvictable(count int)
SetPermanentBansEvictable sets the number of bans eligible for cleanup
func SetPermanentBansProtected ¶
func SetPermanentBansProtected(count int)
SetPermanentBansProtected sets the number of bans marked as "never evict"
func SetPermanentBansTotal ¶
func SetPermanentBansTotal(count int)
SetPermanentBansTotal sets the total number of permanent bans tracked
func SetPortAllowRules ¶ added in v1.41.0
SetPortAllowRules sets the number of port allow rules for a family and protocol
func SetPortscanTrackedIPs ¶
func SetPortscanTrackedIPs(count int)
SetPortscanTrackedIPs sets the current number of IPs being tracked for port scanning
func SetProtectionActive ¶
func SetProtectionActive(active bool)
SetProtectionActive sets whether memory protection is currently triggered
func SetProtectionFeedsSkipped ¶
func SetProtectionFeedsSkipped(skipped bool)
SetProtectionFeedsSkipped sets whether feeds were skipped due to memory pressure
func SetProtectionGeobanSkipped ¶
func SetProtectionGeobanSkipped(skipped bool)
SetProtectionGeobanSkipped sets whether geoban was skipped due to memory pressure
func SetReconciliationDrift ¶
SetReconciliationDrift sets the drift count for a specific set
func SetReconciliationLastTimestamp ¶
func SetReconciliationLastTimestamp(ts float64)
SetReconciliationLastTimestamp sets the timestamp of the last reconciliation
func SetSchemaErrorsTotal ¶
func SetSchemaErrorsTotal(count int)
SetSchemaErrorsTotal sets the number of schema errors detected
func SetSchemaValidationStatus ¶
func SetSchemaValidationStatus(drifted bool)
SetSchemaValidationStatus sets whether schema validation passed or failed
func SetSuricataAlertsActive ¶
func SetSuricataAlertsActive(count int)
SetSuricataAlertsActive sets the number of IPs being tracked from alerts
func SetSuricataEveLag ¶
func SetSuricataEveLag(lagSeconds float64)
SetSuricataEveLag sets the EVE log freshness (seconds since last event)
func SetWhitelistOverlapCount ¶
func SetWhitelistOverlapCount(count int)
SetWhitelistOverlapCount sets the number of overlapping IPs
Types ¶
type AttackRateTracker ¶ added in v1.41.0
type AttackRateTracker struct {
// contains filtered or unexported fields
}
AttackRateTracker maintains a sliding window of attack event timestamps. Thread-safe for concurrent RecordAttack calls from EventBus subscribers.
func GetAttackRateTracker ¶ added in v1.41.0
func GetAttackRateTracker() *AttackRateTracker
GetAttackRateTracker returns the global attack rate tracker singleton
func NewAttackRateTracker ¶ added in v1.41.0
func NewAttackRateTracker(maxEntries int) *AttackRateTracker
NewAttackRateTracker creates a tracker with a 60-second sliding window. maxEntries caps memory usage under sustained attack (default: 10000).
func (*AttackRateTracker) Rate ¶ added in v1.41.0
func (t *AttackRateTracker) Rate() int
Rate returns the current number of events in the sliding window.
func (*AttackRateTracker) RecordAttack ¶ added in v1.41.0
func (t *AttackRateTracker) RecordAttack()
RecordAttack records an attack event and updates the Prometheus gauge.
func (*AttackRateTracker) RefreshGauge ¶ added in v1.41.0
func (t *AttackRateTracker) RefreshGauge()
RefreshGauge updates the Prometheus gauge with the current rate. Called from the sampler to keep the gauge fresh even without new events.
type ChainInfo ¶ added in v1.87.0
ChainInfo holds presence information for a kernel chain. Three states:
Exists=true, Unknown=false → confirmed present Exists=false, Unknown=false → confirmed absent Unknown=true → collection failure; absence not known
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
Collector efficiently gathers NFTBan metrics for Prometheus export
func NewCollector ¶
NewCollector creates a new metrics collector
type ConnectionStats ¶
type ConnectionStats struct {
TCP int
}
ConnectionStats represents connection statistics
type CounterValue ¶ added in v1.87.0
CounterValue holds a single named counter's packets and bytes.
type DataFreshnessResult ¶ added in v1.88.0
type DataFreshnessResult struct {
FeedFresh bool `json:"feed_fresh"` // feed data files < 7 days old
FeedAge string `json:"feed_age,omitempty"` // human-readable age of newest feed
GeoIPFresh bool `json:"geoip_fresh"` // GeoIP DB < 45 days old
GeoIPAge string `json:"geoip_age,omitempty"` // human-readable age
Unknown bool `json:"unknown,omitempty"` // collection failed
}
DataFreshnessResult holds freshness checks for data pipeline artifacts.
func CollectDataFreshness ¶ added in v1.88.0
func CollectDataFreshness() *DataFreshnessResult
CollectDataFreshness checks feed and GeoIP data pipeline freshness. M88-3: Feed data files in /var/lib/nftban/feeds/ — fresh if any file < 7 days M88-4: GeoIP DB at /var/lib/nftban/geoip/dbip-country-lite.mmdb — fresh if < 45 days
type EvidenceSnapshot ¶ added in v1.87.0
type EvidenceSnapshot struct {
SchemaVersion string `json:"schema_version"`
CollectedAt time.Time `json:"collected_at"`
TruthAuthority string `json:"truth_authority"`
Kernel struct {
Counters map[string]CounterValue `json:"counters"`
Sets map[string]SetInfo `json:"sets"`
Chains map[string]ChainInfo `json:"chains"`
} `json:"kernel"`
// v1.88: External evidence plane
External *JournalEvidenceResult `json:"external,omitempty"`
Freshness *DataFreshnessResult `json:"freshness,omitempty"`
Validator *ValidatorSnapshot `json:"validator"`
Correlation map[string]string `json:"correlation"`
}
EvidenceSnapshot is the canonical Phase 1 metrics model. Collected once, rendered as JSON or human-readable text.
This is NOT a truth object. Validator remains sole authority. Correlation is diagnostic only — cannot affect exit codes.
func CollectEvidenceSnapshot ¶ added in v1.87.0
func CollectEvidenceSnapshot(ctx context.Context) (*EvidenceSnapshot, error)
CollectEvidenceSnapshot gathers all Phase 1 evidence. Single entry point: collect once, render many.
v1.89 INV-M-001/002: All kernel data from validator — ZERO direct nft calls. The validator runs nft -j list ruleset (once) + per-set element queries. Evidence extracts counters, chains, and set element counts from the validator's result. Journal and data freshness are independent sources.
type InterfaceStats ¶
InterfaceStats represents network interface statistics
type JournalEvidenceResult ¶ added in v1.88.0
type JournalEvidenceResult struct {
LoginMonActive bool `json:"loginmon_active"` // recent ban/login_failed events found
LoginMonBans int `json:"loginmon_bans"` // ban event count in window
LoginMonEvents int `json:"loginmon_events"` // login_failed event count in window
Unknown bool `json:"unknown,omitempty"` // collection failed
}
JournalEvidenceResult holds journal-based evidence for metrics.
func CollectJournalEvidence ¶ added in v1.88.0
func CollectJournalEvidence(ctx context.Context) *JournalEvidenceResult
CollectJournalEvidence queries nftband journal for LoginMon activity. Bounded: 15m window, 500 line cap, 3s timeout.
type NamedCountersResult ¶ added in v1.87.0
type NamedCountersResult struct {
CollectedAt time.Time `json:"collected_at"`
Counters map[string]CounterValue `json:"counters"`
}
NamedCountersResult holds all named counters from a single collection. Keys use stable format: "<family>:<counter_name>" (e.g. "ip:input_ct_ssh_drop"). An empty Counters map is valid (no counters found, not an error). A nil result with non-nil error means collection failed.
func CollectNamedCounters ¶ added in v1.87.0
func CollectNamedCounters(ctx context.Context) (*NamedCountersResult, error)
CollectNamedCounters returns all named counters as structured evidence data. v1.87 M87-2: This is the canonical evidence collection function. Collect once → render many (JSON, human, Prometheus).
Semantics: - Empty Counters map = valid (no counters found, not an error) - Non-nil error = collection failed (command error, parse error) - Zero-valued counters are preserved (neutral, not failure)
type Sample ¶
type Sample struct {
Timestamp time.Time `json:"timestamp"`
Version string `json:"version"`
BlockedIPs int `json:"blocked_ips"`
RuleCount int `json:"rule_count"`
HealthOK bool `json:"health_ok"`
FeedsActive int `json:"feeds_active"`
NetworkRxMbps float64 `json:"network_rx_mbps"`
NetworkTxMbps float64 `json:"network_tx_mbps"`
RawData map[string]interface{} `json:"raw_data,omitempty"`
}
Sample represents a single metrics snapshot
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler manages global metrics collection
func GetSampler ¶
func GetSampler() *Sampler
GetSampler returns the global sampler instance (singleton)
func (*Sampler) AddSession ¶
func (s *Sampler) AddSession()
AddSession increments active session count and starts sampling if needed
func (*Sampler) DisableMetrics ¶
func (s *Sampler) DisableMetrics()
DisableMetrics disables continuous sampling (back to session-based logic)
func (*Sampler) EnableMetrics ¶
func (s *Sampler) EnableMetrics()
EnableMetrics enables continuous sampling (overrides session-based logic)
func (*Sampler) GetRecentSamples ¶
GetRecentSamples returns the most recent N samples
func (*Sampler) IsMetricsEnabled ¶
IsMetricsEnabled returns whether continuous metrics mode is enabled
func (*Sampler) Registry ¶
func (s *Sampler) Registry() *prometheus.Registry
Registry returns the Prometheus registry
func (*Sampler) RemoveSession ¶
func (s *Sampler) RemoveSession()
RemoveSession decrements active session count and stops sampling if needed
type SetInfo ¶ added in v1.87.0
type SetInfo struct {
Exists bool `json:"exists"`
Count int `json:"count"`
Unknown bool `json:"unknown,omitempty"`
}
SetInfo holds element count for a kernel set. Three states:
Exists=true, Count>=0, Unknown=false → collected successfully Exists=false, Count=0, Unknown=false → confirmed absent Unknown=true → collection failure/timeout/parse error; absence not known
type ValidatorSnapshot ¶ added in v1.87.0
type ValidatorSnapshot struct {
Status string `json:"status"` // protected/idle/degraded/down/unavailable
Modules map[string]string `json:"modules"` // module → effective state
Findings []string `json:"findings"` // finding codes only
Unknown bool `json:"unknown,omitempty"` // true if collection failed
}
ValidatorSnapshot holds extracted validator state for metrics enrichment. This is NOT a truth object — it is a read-only observation of validator output. Metrics cannot modify, override, or reinterpret these values.
func CollectValidatorSnapshot ¶ added in v1.87.0
func CollectValidatorSnapshot(ctx context.Context) *ValidatorSnapshot
CollectValidatorSnapshot calls nftban-validate --json and extracts status, module states, and finding codes. Returns ValidatorSnapshot with Unknown=true on any failure.
DEPRECATED (v1.89): CollectEvidenceSnapshot now calls validator.ValidateKernel() directly and uses buildValidatorSnapshot() for richer extraction. This function is retained for any standalone callers but is no longer on the evidence hot path.