Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Agents now report gateway latency to the collector for improved health monitoring, and the `nekoagent` CLI gains a `restart-all` command.

luolei8869590f0169
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index 0b62fb5..5b5ce99 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -46,14 +46,15 @@ type reportPayload struct {
}
type heartbeatPayload struct {
- BackendID int `json:"backendId"`
- AgentID string `json:"agentId"`
- Hostname string `json:"hostname,omitempty"`
- Version string `json:"version,omitempty"`
- AgentVersion string `json:"agentVersion,omitempty"`
- ProtocolVersion int `json:"protocolVersion"`
- GatewayType string `json:"gatewayType,omitempty"`
- GatewayURL string `json:"gatewayUrl,omitempty"`
+ BackendID int `json:"backendId"`
+ AgentID string `json:"agentId"`
+ Hostname string `json:"hostname,omitempty"`
+ Version string `json:"version,omitempty"`
+ AgentVersion string `json:"agentVersion,omitempty"`
+ ProtocolVersion int `json:"protocolVersion"`
+ GatewayType string `json:"gatewayType,omitempty"`
+ GatewayURL string `json:"gatewayUrl,omitempty"`
+ GatewayLatencyMs int64 `json:"gatewayLatencyMs,omitempty"`
}
type configPayload struct {
@@ -82,8 +83,9 @@ type Runner struct {
retryBatch []domain.TrafficUpdate
retryID string
- lastConfigHash string
- lastPolicyHash string
+ lastConfigHash string
+ lastPolicyHash string
+ gatewayLatencyMs int64
}
func NewRunner(cfg config.Config) *Runner {
@@ -205,6 +207,7 @@ func (r *Runner) runCollectorLoop(ctx context.Context, wg *sync.WaitGroup) {
failures := 0
for {
+ t0 := time.Now()
snapshots, err := r.gatewayClient.Collect(ctx)
delay := r.cfg.GatewayPollInterval
if err != nil {
@@ -213,6 +216,10 @@ func (r *Runner) runCollectorLoop(ctx context.Context, wg *sync.WaitGroup) {
log.Printf("[agent:%s] collector error (%d): %v", r.cfg.AgentID, failures, err)
} else {
failures = 0
+ latencyMs := time.Since(t0).Milliseconds()
+ r.mu.Lock()
+ r.gatewayLatencyMs = latencyMs
+ r.mu.Unlock()
r.ingestSnapshots(snapshots, time.Now().UnixMilli())
}
@@ -568,15 +575,20 @@ func (r *Runner) setRetryBatch(batch []domain.TrafficUpdate, id string) {
}
func (r *Runner) sendHeartbeat(ctx context.Context) error {
+ r.mu.Lock()
+ latencyMs := r.gatewayLatencyMs
+ r.mu.Unlock()
+
payload := heartbeatPayload{
- BackendID: r.cfg.BackendID,
- AgentID: r.cfg.AgentID,
- Hostname: r.hostname,
- Version: config.AgentVersion,
- AgentVersion: config.AgentVersion,
- ProtocolVersion: config.AgentProtocolVersion,
- GatewayType: r.cfg.GatewayType,
- GatewayURL: r.cfg.GatewayEndpoint,
+ BackendID: r.cfg.BackendID,
+ AgentID: r.cfg.AgentID,
+ Hostname: r.hostname,
+ Version: config.AgentVersion,
+ AgentVersion: config.AgentVersion,
+ ProtocolVersion: config.AgentProtocolVersion,
+ GatewayType: r.cfg.GatewayType,
+ GatewayURL: r.cfg.GatewayEndpoint,
+ GatewayLatencyMs: latencyMs,
}
return r.postJSON(ctx, "/agent/heartbeat", payload)
}
diff --git a/apps/agent/nekoagent b/apps/agent/nekoagent
index 02625e7..b11b450 100755
--- a/apps/agent/nekoagent
+++ b/apps/agent/nekoagent
@@ -8,7 +8,7 @@ AGENT_BIN="${NEKO_AGENT_BIN:-$INSTALL_DIR/neko-agent}"
CONFIG_DIR="${NEKO_AGENT_CONFIG_DIR:-/etc/neko-agent}"
STATE_DIR="${NEKO_AGENT_STATE_DIR:-/var/run/neko-agent}"
AGENT_REPO="${NEKO_AGENT_REPO:-foru17/neko-master}"
-VERSION="0.2.0"
+VERSION="0.2.1"
log() {
printf '[%s] %s\n' "$PROG" "$1"
@@ -294,7 +294,8 @@ Usage:
$PROG status <name> Show instance status
$PROG logs <name> Tail logs
$PROG list List configured instances
- $PROG upgrade [version] Upgrade manager+binary globally
+ $PROG restart-all Restart all running instances
+ $PROG upgrade [version] Upgrade manager+binary and restart running instances
$PROG remove <name> Remove instance config/runtime
$PROG delete <name> Alias of remove
$PROG uninstall Uninstall nekoagent + binaries
@@ -538,7 +539,7 @@ cmd_start() {
fi
if is_running "$name"; then
log "instance '$name' already running (pid $(cat "$(pid_file "$name")"))"
- exit 0
+ return 0
fi
load_config "$name"
@@ -559,7 +560,7 @@ cmd_stop() {
if ! is_running "$name"; then
rm -f "$pf"
log "instance '$name' is not running"
- exit 0
+ return 0
fi
pid="$(cat "$pf")"
kill "$pid" >/dev/null 2>&1 || true
@@ -620,6 +621,26 @@ cmd_list() {
fi
}
+cmd_restart_all() {
+ ensure_dirs
+ restarted_any=false
+ for f in "$CONFIG_DIR"/*.env; do
+ if [ ! -e "$f" ]; then
+ continue
+ fi
+ name="$(basename "$f" .env)"
+ if is_running "$name"; then
+ log "restarting '$name'..."
+ cmd_stop "$name" || true
+ cmd_start "$name"
+ restarted_any=true
+ fi
+ done
+ if [ "$restarted_any" = false ]; then
+ log "no running instances found"
+ fi
+}
+
cmd_upgrade_global() {
version_arg="${1:-latest}"
os="$(normalize_os)"
@@ -650,26 +671,22 @@ cmd_upgrade_global() {
do_download_manager "$target_tag"
- if [ "$binary_changed" = true ]; then
- restarted_any=false
- for f in "$CONFIG_DIR"/*.env; do
- if [ ! -e "$f" ]; then
- continue
- fi
- name="$(basename "$f" .env)"
- if is_running "$name"; then
- log "restarting running instance '$name'..."
- cmd_stop "$name" || true
- cmd_start "$name"
- restarted_any=true
- fi
- done
-
- if [ "$restarted_any" = false ]; then
- log "no running instances found; binary upgraded globally"
+ restarted_any=false
+ for f in "$CONFIG_DIR"/*.env; do
+ if [ ! -e "$f" ]; then
+ continue
fi
- else
- log "binary unchanged; skipped instance restart"
+ name="$(basename "$f" .env)"
+ if is_running "$name"; then
+ log "restarting running instance '$name'..."
+ cmd_stop "$name" || true
+ cmd_start "$name"
+ restarted_any=true
+ fi
+ done
+
+ if [ "$restarted_any" = false ]; then
+ log "no running instances found; binary upgraded globally"
fi
log "upgrade complete: manager + binary at version $target_plain"
@@ -771,6 +788,9 @@ main() {
list)
cmd_list
;;
+ restart-all)
+ cmd_restart_all
+ ;;
version|-v|--version)
version
;;
diff --git a/apps/collector/src/database/repositories/config.repository.ts b/apps/collector/src/database/repositories/config.repository.ts
index 9f416e3..be4e710 100644
--- a/apps/collector/src/database/repositories/config.repository.ts
+++ b/apps/collector/src/database/repositories/config.repository.ts
@@ -237,10 +237,12 @@ export class ConfigRepository extends BaseRepository {
this.db.prepare(`DELETE FROM device_domain_stats WHERE backend_id = ?`).run(backendId);
this.db.prepare(`DELETE FROM device_ip_stats WHERE backend_id = ?`).run(backendId);
this.db.prepare(`DELETE FROM hourly_stats WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM backend_health_logs WHERE backend_id = ?`).run(backendId);
} else {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
const minuteCutoff = cutoff.toISOString().slice(0, 16) + ':00';
const hourCutoff = cutoff.toISOString().slice(0, 13) + ':00:00';
+ const healthCutoff = cutoff.toISOString().slice(0, 16);
const minuteResult = this.db.prepare(`DELETE FROM minute_stats WHERE backend_id = ? AND minute < ?`).run(backendId, minuteCutoff);
deletedConnections = minuteResult.changes;
deletedLogs = minuteResult.changes;
@@ -249,6 +251,7 @@ export class ConfigRepository extends BaseRepository {
this.db.prepare(`DELETE FROM hourly_dim_stats WHERE backend_id = ? AND hour < ?`).run(backendId, hourCutoff);
this.db.prepare(`DELETE FROM hourly_country_stats WHERE backend_id = ? AND hour < ?`).run(backendId, hourCutoff);
this.db.prepare(`DELETE FROM connection_logs WHERE backend_id = ? AND timestamp < ?`).run(backendId, cutoff.toISOString());
+ this.db.prepare(`DELETE FROM backend_health_logs WHERE backend_id = ? AND minute < ?`).run(backendId, healthCutoff);
}
} else {
if (days === 0) {
@@ -277,10 +280,12 @@ export class ConfigRepository extends BaseRepository {
this.db.prepare(`DELETE FROM device_domain_stats`).run();
this.db.prepare(`DELETE FROM device_ip_stats`).run();
this.db.prepare(`DELETE FROM hourly_stats`).run();
+ this.db.prepare(`DELETE FROM backend_health_logs`).run();
} else {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
const minuteCutoff = cutoff.toISOString().slice(0, 16) + ':00';
const hourCutoff = cutoff.toISOString().slice(0, 13) + ':00:00';
+ const healthCutoff = cutoff.toISOString().slice(0, 16);
const minuteResult = this.db.prepare(`DELETE FROM minute_stats WHERE minute < ?`).run(minuteCutoff);
deletedConnections = minuteResult.changes;
deletedLogs = minuteResult.changes;
@@ -289,6 +294,7 @@ export class ConfigRepository extends BaseRepository {
this.db.prepare(`DELETE FROM hourly_dim_stats WHERE hour < ?`).run(hourCutoff);
this.db.prepare(`DELETE FROM hourly_country_stats WHERE hour < ?`).run(hourCutoff);
this.db.prepare(`DELETE FROM connection_logs WHERE timestamp < ?`).run(cutoff.toISOString());
+ this.db.prepare(`DELETE FROM backend_health_logs WHERE minute < ?`).run(healthCutoff);
}
}
diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.ts
index 1efc36e..cf49220 100644
--- a/apps/collector/src/database/schema.ts
+++ b/apps/collector/src/database/schema.ts
@@ -377,6 +377,7 @@ export const SCHEMA = {
gateway_type TEXT,
gateway_url TEXT,
remote_ip TEXT,
+ gateway_latency_ms INTEGER,
last_seen DATETIME NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index fb82e04..3cda44e 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -83,6 +83,7 @@ type AgentHeartbeatPayload = {
version?: string;
gatewayType?: string;
gatewayUrl?: string;
+ gatewayLatencyMs?: number;
};
type AgentReportPayload = {
@@ -572,6 +573,9 @@ export async function createApp(options: AppOptions) {
const gatewayType = String(body.gatewayType || '').trim().slice(0, 16) || undefined;
const gatewayUrl = String(body.gatewayUrl || '').trim().slice(0, 512) || undefined;
const remoteIP = request.ip || request.headers['x-forwarded-for']?.toString().split(',')[0]?.trim();
+ const gatewayLatencyMs = typeof body.gatewayLatencyMs === 'number' && body.gatewayLatencyMs > 0
+ ? body.gatewayLatencyMs
+ : undefined;
db.upsertAgentHeartbeat({
backendId,
@@ -581,6 +585,7 @@ export async function createApp(options: AppOptions) {
gatewayType,
gatewayUrl,
remoteIP,
+ gatewayLatencyMs,
lastSeen: new Date().toISOString(),
});
diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.ts
index a802fb7..dc28761 100644
--- a/apps/collector/src/modules/backend/backend.service.ts
+++ b/apps/collector/src/modules/backend/backend.service.ts
@@ -119,7 +119,7 @@ export class BackendService {
console.log(`[BackendService] Health check for ${backend.name}: ${health.status}${health.message ? ` - ${health.message}` : ''}`);
}
this.healthStatus.set(backend.id, health);
- this.db.repos.health.writeHealthLog(backend.id, minute, health.status, undefined, health.message);
+ this.db.repos.health.writeHealthLog(backend.id, minute, health.status, health.latency, health.message);
continue;
}
@@ -557,6 +557,7 @@ export class BackendService {
return {
status: isOnline ? 'healthy' : 'unhealthy',
lastChecked: now,
+ latency: isOnline && heartbeat.gatewayLatencyMs ? heartbeat.gatewayLatencyMs : undefined,
message: isOnline
? `Agent ${heartbeat.agentId} online (last seen ${ageText})`
: `Agent offline (last seen ${ageText}, timeout ${timeoutText})`,
diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.ts
index db67eae..999c565 100644
--- a/apps/collector/src/modules/db/db.ts
+++ b/apps/collector/src/modules/db/db.ts
@@ -56,6 +56,7 @@ export interface AgentHeartbeat {
gatewayType?: string;
gatewayUrl?: string;
remoteIP?: string;
+ gatewayLatencyMs?: number;
lastSeen: string;
}
@@ -239,6 +240,14 @@ export class StatsDatabase {
this.db.exec(`ALTER TABLE domain_stats ADD COLUMN chains TEXT;`);
}
+ // Migration: Add gateway_latency_ms column to agent_heartbeats
+ try {
+ this.db.exec(`ALTER TABLE agent_heartbeats ADD COLUMN gateway_latency_ms INTEGER`);
+ console.log('[DB] Migration: Added gateway_latency_ms column to agent_heartbeats');
+ } catch {
+ // Column already exists
+ }
+
// Migrate connection_logs data to new aggregation tables (one-time backfill)
this.migrateConnectionLogsToAggregation();
}
@@ -1008,13 +1017,14 @@ export class StatsDatabase {
gatewayType?: string;
gatewayUrl?: string;
remoteIP?: string;
+ gatewayLatencyMs?: number;
lastSeen?: string;
}): void {
const stmt = this.db.prepare(`
INSERT INTO agent_heartbeats (
- backend_id, agent_id, hostname, version, gateway_type, gateway_url, remote_ip, last_seen, updated_at
+ backend_id, agent_id, hostname, version, gateway_type, gateway_url, remote_ip, gateway_latency_ms, last_seen, updated_at
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(backend_id) DO UPDATE SET
agent_id = excluded.agent_id,
hostname = excluded.hostname,
@@ -1022,6 +1032,7 @@ export class StatsDatabase {
gateway_type = excluded.gateway_type,
gateway_url = excluded.gateway_url,
remote_ip = excluded.remote_ip,
+ gateway_latency_ms = excluded.gateway_latency_ms,
last_seen = excluded.last_seen,
updated_at = CURRENT_TIMESTAMP
`);
@@ -1035,6 +1046,7 @@ export class StatsDatabase {
input.gatewayType || null,
input.gatewayUrl || null,
input.remoteIP || null,
+ input.gatewayLatencyMs ?? null,
lastSeen,
);
}
@@ -1049,6 +1061,7 @@ export class StatsDatabase {
gateway_type as gatewayType,
gateway_url as gatewayUrl,
remote_ip as remoteIP,
+ gateway_latency_ms as gatewayLatencyMs,
last_seen as lastSeen
FROM agent_heartbeats
WHERE backend_id = ?