elastic-monit/index.js
2024-09-11 19:26:37 +02:00

52 lines
1.5 KiB
JavaScript

const { XMLParser } = require("fast-xml-parser"),
{ Client } = require('@elastic/elasticsearch'),
config = require('./config.js'),
parser = new XMLParser({ ignoreDeclaration: true, ignorePiTags: true }),
client = new Client({ node: config.elasticnode }),
monitnodes = config.monitnodes,
username = config.username,
password = config.password,
request = async uri => {
const ac = new AbortController()
setTimeout(() => {
ac.abort()
}, 5000)
const response = await fetch(uri, {
signal: ac.signal,
keepalive: false,
timeout: config.timeout,
headers: {
Authorization: `Basic ${btoa(`${username}:${password}`)}`
}
}),
xml = await response.text()
setImmediate(() => { ac.abort() })
return xml
},
index = async (node, data) => {
await client.index({
index: config.index,
body: {
data,
node,
timestamp: new Date()
}
})
},
start = async () => {
await Promise.all(monitnodes.map(async node => {
try {
const xml = await request(`http://${node}:2812/_status?format=xml`),
json = parser.parse(xml)
await index(node, json)
} catch (e) {
console.error(e)
}
}))
setTimeout(async () => await start(), config.poll)
}
(async () => {
await start()
})()