agentdb

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package agentdb persists agent info, structured logs, and resource metrics in a local SQLite database so they survive restarts and can be uploaded for offline investigation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MaskArgs

func MaskArgs(args []string) string

MaskArgs returns os.Args as a JSON array with sensitive flag values masked.

func MaskEnv

func MaskEnv() string

MaskEnv returns PDCP_* and AGENT_* env vars as a JSON object with sensitive values masked.

Types

type AgentInfo

type AgentInfo struct {
	AgentID      string
	AgentName    string
	AgentNetwork string
	Version      string
	OS           string
	Arch         string
	NumCPU       int
	Hostname     string
	PID          int
	NetworkInfo  NetInfo
	StartupArgs  string // masked os.Args as JSON array
	StartupEnv   string // masked key env vars as JSON object
	StartedAt    time.Time
	UpdatedAt    time.Time
}

AgentInfo holds agent identity and system information.

type InterfaceInfo

type InterfaceInfo struct {
	Name  string   `json:"name"`
	Addrs []string `json:"addrs"` // CIDR notation
}

InterfaceInfo describes a single network interface.

type LogEntry

type LogEntry struct {
	ID        int64
	Timestamp time.Time
	Line      string // full slog-formatted line
}

LogEntry is a single structured log record.

type LogFilter

type LogFilter struct {
	Since  time.Time // zero = no lower bound
	Until  time.Time // zero = no upper bound
	Offset int
	Limit  int // 0 = default 500
}

LogFilter controls which log entries are returned by QueryLogs.

type LogWriter

type LogWriter struct {
	// contains filtered or unexported fields
}

LogWriter is an async, channel-based log writer that batches inserts into single transactions.

func NewLogWriter

func NewLogWriter(store *SQLiteStore) *LogWriter

NewLogWriter creates a LogWriter backed by the given store. Call Run() in a goroutine. Call Stop() to flush and shut down.

func (*LogWriter) Run

func (w *LogWriter) Run()

Run continuously drains the channel, batching inserts into transactions. No ticker — flushes as fast as entries arrive.

func (*LogWriter) Stop

func (w *LogWriter) Stop()

Stop signals the writer to flush remaining entries and exit. Blocks until all buffered entries are written to the DB.

func (*LogWriter) Write

func (w *LogWriter) Write(entry LogEntry)

Write enqueues a log entry. Non-blocking: if the channel is full or the writer has stopped, the entry is silently dropped.

type MetricSample

type MetricSample struct {
	ID               int64
	Timestamp        time.Time
	CPUPercent       float64
	RSSMB            uint64
	HeapAllocMB      uint64
	HeapSysMB        uint64
	FDUsed           int
	FDLimit          int
	MemTotalMB       uint64
	MemAvailMB       uint64
	Goroutines       int
	ActiveWorkers    int32
	ChunkParallelism int
}

MetricSample is a single point-in-time resource measurement.

type NetInfo

type NetInfo struct {
	Interfaces   []InterfaceInfo `json:"interfaces"`
	Gateway      string          `json:"gateway"`
	DNSResolvers []string        `json:"dns_resolvers"`
	PublicIPs    []string        `json:"public_ips"`
	PrivateIPs   []string        `json:"private_ips"`
	NetworkType  string          `json:"network_type"` // "direct_public", "nat_likely", "no_external"
}

NetInfo holds local network detection results.

func DetectNetInfo

func DetectNetInfo() NetInfo

DetectNetInfo enumerates local network interfaces and classifies the network environment. It is safe to call from any goroutine; the result is a snapshot of the system at the time of the call.

type SQLiteStore

type SQLiteStore struct {
	// contains filtered or unexported fields
}

SQLiteStore implements Store backed by a local SQLite database.

func Open

func Open(dbPath string) (*SQLiteStore, error)

Open creates or opens a SQLite database at dbPath and returns an SQLiteStore.

func (*SQLiteStore) ActiveTasks

func (s *SQLiteStore) ActiveTasks(ctx context.Context) ([]Task, error)

ActiveTasks returns all tasks with status "running".

func (*SQLiteStore) CheckpointWAL

func (s *SQLiteStore) CheckpointWAL() error

CheckpointWAL forces all WAL frames into the main DB file and truncates the WAL. Call after all writers have stopped and before uploading the .db file.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the database connection.

func (*SQLiteStore) DBPath

func (s *SQLiteStore) DBPath() string

DBPath returns the filesystem path of the database file.

func (*SQLiteStore) DBSizeBytes

func (s *SQLiteStore) DBSizeBytes() (int64, error)

DBSizeBytes returns the current database file size in bytes.

func (*SQLiteStore) FinishTask

func (s *SQLiteStore) FinishTask(ctx context.Context, taskID, status string) error

FinishTask updates a task's status and sets finished_at.

func (*SQLiteStore) GetAgentInfo

func (s *SQLiteStore) GetAgentInfo(ctx context.Context) (*AgentInfo, error)

GetAgentInfo returns the current agent info, or (nil, nil) if no row exists.

func (*SQLiteStore) InsertLog

func (s *SQLiteStore) InsertLog(ctx context.Context, entry *LogEntry) error

InsertLog appends a structured log entry.

func (*SQLiteStore) InsertMetric

func (s *SQLiteStore) InsertMetric(ctx context.Context, sample *MetricSample) error

InsertMetric appends a resource metrics sample.

func (*SQLiteStore) InsertTask

func (s *SQLiteStore) InsertTask(ctx context.Context, task *Task) error

InsertTask records a new scan/enumeration task as running.

func (*SQLiteStore) QueryLogs

func (s *SQLiteStore) QueryLogs(ctx context.Context, filter LogFilter) ([]LogEntry, error)

QueryLogs returns log entries matching the filter, ordered oldest-first.

func (*SQLiteStore) QueryMetrics

func (s *SQLiteStore) QueryMetrics(ctx context.Context, since, until time.Time, limit int) ([]MetricSample, error)

QueryMetrics returns metric samples within [since, until], ordered oldest-first.

func (*SQLiteStore) RecentTasks

func (s *SQLiteStore) RecentTasks(ctx context.Context, limit int) ([]Task, error)

RecentTasks returns the most recent tasks (any status), ordered newest-first.

func (*SQLiteStore) UpsertAgentInfo

func (s *SQLiteStore) UpsertAgentInfo(ctx context.Context, info *AgentInfo) error

UpsertAgentInfo inserts or replaces the single agent_info row (id=1).

type SizeCaps

type SizeCaps struct {
	LogCapBytes    int64
	MetricCapBytes int64
}

SizeCaps holds the byte-based size limits for logs and metrics tables.

func LoadSizeCaps

func LoadSizeCaps() (SizeCaps, error)

LoadSizeCaps reads PDCP_AGENTDB_LOG_CAP_MB and PDCP_AGENTDB_METRIC_CAP_MB, defaulting to 10MB logs and 18MB metrics. Returns an error only if a value is set but not a positive integer.

type Store

type Store interface {
	// UpsertAgentInfo inserts or replaces the single agent_info row.
	UpsertAgentInfo(ctx context.Context, info *AgentInfo) error

	// GetAgentInfo returns the current agent info, or nil if not yet stored.
	GetAgentInfo(ctx context.Context) (*AgentInfo, error)

	// InsertLog appends a structured log entry.
	InsertLog(ctx context.Context, entry *LogEntry) error

	// InsertMetric appends a resource metrics sample.
	InsertMetric(ctx context.Context, sample *MetricSample) error

	// QueryLogs returns log entries matching the filter, ordered oldest-first.
	QueryLogs(ctx context.Context, filter LogFilter) ([]LogEntry, error)

	// QueryMetrics returns metric samples within the time range, ordered oldest-first.
	QueryMetrics(ctx context.Context, since, until time.Time, limit int) ([]MetricSample, error)

	// InsertTask records a new scan/enumeration task as running.
	InsertTask(ctx context.Context, task *Task) error

	// FinishTask updates a task's status and sets finished_at.
	FinishTask(ctx context.Context, taskID, status string) error

	// ActiveTasks returns tasks with status "running", newest first.
	ActiveTasks(ctx context.Context) ([]Task, error)

	// RecentTasks returns the most recent tasks (any status), newest first.
	RecentTasks(ctx context.Context, limit int) ([]Task, error)

	// DBSizeBytes returns the database file size in bytes.
	DBSizeBytes() (int64, error)

	// Close closes the database connection.
	Close() error
}

Store persists local agent observability data. Implementations must be safe for concurrent use.

type Task

type Task struct {
	ID         int64
	Type       string // "scan" or "enumeration"
	TaskID     string // scan_id or enumeration_id
	Status     string // "running", "completed", "failed"
	StartedAt  time.Time
	FinishedAt time.Time // zero if still running
}

Task tracks a scan or enumeration the agent is working on.

type Truncator

type Truncator struct {
	// contains filtered or unexported fields
}

Truncator runs a periodic maintenance loop that enforces table size caps by deleting oldest rows and reclaiming disk space via incremental vacuum.

func NewTruncator

func NewTruncator(store *SQLiteStore, logCapBytes, metCapBytes int64) *Truncator

NewTruncator creates a truncator with byte-based caps. Internally converts to row limits: logCapBytes/200, metCapBytes/150.

func (*Truncator) Run

func (t *Truncator) Run(ctx context.Context)

Run blocks until ctx is cancelled, running truncation every interval.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL