#!/usr/bin/env npx zx import https from 'node:https' import path from 'node:path' const NAME = path.basename(import.meta.url) $.verbose = false const KBN_URL = process.env.KBN_URL const ES_URL = process.env.ES_URL const conn = await postURL(`${KBN_URL}/api/actions/connector`, { name: `server log for ${NAME}`, connector_type_id: '.server-log', }) console.log(`server log id: ${conn.id}`) const mtRule = await postURL(`${KBN_URL}/api/alerting/rule`, { name: NAME, rule_type_id: 'example.pattern', schedule: { interval: '3s' }, actions: [ { group: 'default', id: conn.id, params: { message: '{{alert.id}} active; flapping: {{alert.flapping}}; on run {{context.runs}} step {{context.patternIndex}}'}}, { group: 'recovered', id: conn.id, params: { message: '{{alert.id}} recovered; flapping: {{alert.flapping}}'}} ], consumer: 'alerts', notify_when: 'onActionGroupChange', // notify_when: 'onActiveAlert', // notify_when: 'onThrottleInterval', throttle: '1s', params: { patterns: { instA: ' a - a ', instB: ' - a ', instC: ' a - a - a - a - - - - - -', } } } ); console.log(`rule id: ${mtRule.id}`); // ===================================================================== /** @type { (url: string) => Promise> } */ async function getURL(url) { return sendURL(url, 'GET') } /** @type { (url: string, body: Record) => Promise> } */ async function postURL(url, body) { return sendURL(url, 'POST', body) } /** @type { (urlWithPass: string, method: string, body: Record) => Promise> } */ async function sendURL(urlWithPass, method, body) { const purl = new URL(urlWithPass) const userPass = `${purl.username}:${purl.password}` const userPassEn = Buffer.from(userPass).toString('base64') const auth = `Basic ${userPassEn}` const url = `${purl.origin}${purl.pathname}${purl.search}` const headers = { 'content-type': 'application/json', 'kbn-xsrf': 'foo', 'authorization': auth, } const fetchOptions = { method, headers } if (body) fetchOptions.body = JSON.stringify(body) if (purl.protocol === 'https:') { fetchOptions.agent = new https.Agent({ rejectUnauthorized: false }) } // console.log(`fetch('${url}', ${JSON.stringify(fetchOptions, null, 4)}`) const response = await fetch(url, fetchOptions) const object = await response.json() // console.log(`fetch(...): ${JSON.stringify(object, null, 4)}`) return object }