Skip to content

Instantly share code, notes, and snippets.

@KeesCBakker
Last active January 23, 2023 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KeesCBakker/332580bf11325b21004853a9fa95f199 to your computer and use it in GitHub Desktop.
Save KeesCBakker/332580bf11325b21004853a9fa95f199 to your computer and use it in GitHub Desktop.
Hubot Grafana Slug Support
import fetch, { Headers } from "node-fetch"
import * as p from "path"
const { HUBOT_GRAFANA_HOST, HUBOT_GRAFANA_API_KEY } = process.env
async function fetchFromGrafanaApi(path: string) {
let url = p.join(HUBOT_GRAFANA_HOST!, path)
let response = await fetch(url, {
method: "GET",
headers: new Headers({
Authorization: `Bearer ${HUBOT_GRAFANA_API_KEY}`,
"Content-Type": "application/json",
}),
})
let json = await response.json()
return json
}
{
id: 904,
uid: 'ICRkSGv4k',
title: '[Team tooling] consumer-gateway - Nginx metrics (nl.wehkamp.prod)',
uri: 'db/team-tooling-consumer-gateway-nginx-metrics-nl-wehkamp-prod',
url: '/d/ICRkSGv4k/team-tooling-consumer-gateway-nginx-metrics-nl-wehkamp-prod',
slug: '',
type: 'dash-db',
tags: [ 'nl.wehkamp', 'prod', 'tooling' ],
isStarred: false,
sortMeta: 0
}
INFO Changing "jarvis graf db team-tooling-consumer-gateway-nginx-metrics-nl-wehkamp-prod:1 now-6h now" to "jarvis graf db ICRkSGv4k:1 now-6h now".
function rewriteGrafanaCommands(robot: Hubot.Robot) {
if (!robot) throw "Argument 'robot' is empty."
robot.receiveMiddleware(async (context, next, done) => {
const text = context.response.message.text
let match = /(?:grafana|graph|graf) (?:dash|dashboard|db) ([^ :]+)/i.exec(text)
if (match) {
let dashboardId = match[1]
let uid = await getUidBySlug(dashboardId)
if (uid) {
let strToReplace = match[0]
let replacement = "graf db " + uid
let newText = text.replace(strToReplace, replacement)
robot.logger.info(`Changing "${text}" to "${newText}".`)
context.response.message.text = newText
}
}
next(done)
})
}
module.exports = (robot: Hubot.Robot) => rewriteGrafanaCommands(robot)
async function search(term: string) {
const pageSize = 5000
let page = 1
const dashboards = new Array<{ uid: string; slug: string }>()
while (true) {
let items: Array<any> = await fetchFromGrafanaApi(`/api/search?limit=${pageSize}&page=${encodeURIComponent(term)}`)
items.forEach(i =>
dashboards.push({
uid: i.uid,
slug: i.url.replace(`/d/${i.uid}/`, "")
})
)
if (items.length != pageSize) break
page++
}
return dashboards
}
export async function getUidBySlug(slug: string) {
let dashboards = await search(slug)
return dashboards.find(d => d.slug == slug)?.uid
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment