77 lines
2.9 KiB
JavaScript
77 lines
2.9 KiB
JavaScript
// proxy/backoneAgentFetcher.js
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Fetches active agents from BackOne API.
|
|
// Uses a two-strategy approach to handle endpoints that may timeout (Source 2).
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
const { backoneFetch, agentMap } = require('./backoneClientCore');
|
|
|
|
// Strategy 1 timeout: 15s (agent/download can be slow on small deployments)
|
|
const PRIMARY_TIMEOUT_MS = 15000;
|
|
|
|
async function fetchAgents(siteUuid = null) {
|
|
// Strategy 1: Use /assets/agents (reliable, returns id+uuid+uuid)
|
|
try {
|
|
const data = await backoneFetch('/assets/agents', {}, null, siteUuid);
|
|
if (data && Array.isArray(data) && data.length > 0) {
|
|
const list = data.map(r => ({
|
|
id: r.id || r.uuid,
|
|
uuid: r.uuid,
|
|
serial: r.uuid,
|
|
label: r.label || r.uuid,
|
|
provisioned: true,
|
|
activated: true,
|
|
last_seen_at: r.last_seen ? new Date(r.last_seen * 1000) : null,
|
|
})).filter(a => a.uuid);
|
|
|
|
// Populate agentMap (uuid → id) for downstream filter_agents usage
|
|
for (const a of list) {
|
|
if (a.uuid) agentMap[a.uuid] = a.id || a.uuid;
|
|
}
|
|
console.log(`[fetchAgents] Got ${list.length} agents from /assets/agents.`);
|
|
return list;
|
|
}
|
|
} catch (e) {
|
|
console.error('[fetchAgents] /assets/agents failed:', e.message);
|
|
}
|
|
|
|
|
|
// Strategy 2: Fallback — discover agents from /data/flows
|
|
// Useful for Source 2 where /data/stats/top/agent/download consistently times out.
|
|
console.log('[fetchAgents] Primary endpoint timeout/empty. Using flows-based agent discovery...');
|
|
try {
|
|
const flowData = await backoneFetch('/data/flows', {
|
|
settings_limit: 100,
|
|
}, null, siteUuid);
|
|
|
|
if (!flowData || !Array.isArray(flowData)) return [];
|
|
|
|
// Extract unique agent_uuids from flow records
|
|
const seen = new Set();
|
|
const agentList = [];
|
|
for (const flow of flowData) {
|
|
const uuid = flow.agent_uuid;
|
|
if (uuid && !seen.has(uuid)) {
|
|
seen.add(uuid);
|
|
agentList.push({
|
|
id: null,
|
|
uuid: uuid,
|
|
serial: uuid,
|
|
label: uuid,
|
|
provisioned: true,
|
|
activated: true,
|
|
last_seen_at: flow.last_seen_at ?? null,
|
|
});
|
|
}
|
|
}
|
|
|
|
console.log(`[fetchAgents] Fallback discovered ${agentList.length} agent(s) from flows.`);
|
|
return agentList;
|
|
} catch (e) {
|
|
console.error('[fetchAgents] Fallback also failed:', e.message);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
module.exports = { fetchAgents };
|