Skip to content

Commit

Permalink
Add error handling and address review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
shardulsrivastava committed Jan 28, 2023
1 parent b62fc3f commit f089830
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions functions-runtime/samples/ts/prometheus.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
let text = Deno.env.get("DATA");
const text = Deno.env.get("DATA")!;
let data;
if (text != "") {
data = JSON.parse(text);
if (text && text != "") {
try {
data = JSON.parse(text);
if ( !data.metrics || !data.url || !data.expected_value) {
console.log("Missing mandatory arguments.");
printUsage()
}
} catch {
console.error("Error Parsing Json => ",text)
Deno.exit(1);
}
} else {
console.log("Missing mandatory enviornment variable DATA.");
printUsage()
}

function printUsage(){
console.log("Expecting environment variable DATA in this format => DATA='{ \"url\":\"<PROMETHEUS_URL>\", \"metrics\": \"<PROMETHEUS_QUERY>\", \"expected_value\": \"<EXPECTED_VALUE>\" }\' ")
console.log("Example: export DATA='{ \"url\":\"http://localhost:9090\", \"metrics\": \"up{service=\\\"kubernetes\\\"}\", \"expected_value\": \"1\" }\' ")
Deno.exit(1);
}

function getPrometheusURL(url: string, metrics: string): string {
let dateTime = new Date().toISOString();
let hasPort = url.includes(":9090");
let hasProtocol = url.includes("http://");
const dateTime = new Date().toISOString();
const hasPort = url.includes(":9090");
const hasProtocol = url.includes("http://");
let queryURL: string = url;
if (!hasPort) {
queryURL = queryURL + ":9090";
Expand All @@ -19,15 +37,15 @@ function getPrometheusURL(url: string, metrics: string): string {
return queryURL + "/api/v1/query?query=" + metrics + "&time=" + dateTime;
}

let promtheusURL = getPrometheusURL(data.url, data.metrics);
const promtheusURL = getPrometheusURL(data.url, data.metrics);
console.log("Prometheus URL => " + promtheusURL);
let value;
try {
let jsonResponse = await fetch(promtheusURL);
let jsonData = await jsonResponse.json();
const jsonResponse = await fetch(promtheusURL);
const jsonData = await jsonResponse.json();
value = jsonData.data.result[0].value[1];
} catch (error) {
console.error("Could not fetch ");
console.error("Could not fetch data from Prometheus.\n", error);
Deno.exit(1);
}

Expand Down

0 comments on commit f089830

Please sign in to comment.