Skip to content

Commit

Permalink
✨ add support for env var variants
Browse files Browse the repository at this point in the history
  • Loading branch information
Rohland committed Oct 26, 2024
1 parent 4d74c8e commit f83e784
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 20 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "barky",
"version": "1.1.19",
"version": "1.1.20",
"description": "A simple cloud services watchdog with digest notification support & no external dependencies",
"homepage": "https://github.com/Rohland/barky#readme",
"main": "dist/cli.js",
Expand Down
13 changes: 7 additions & 6 deletions src/evaluators/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { IApp } from "../models/app";
import { BaseEvaluator, EvaluatorType, findTriggerRulesFor, generateValueForVariable } from "./base";
import { IUniqueKey } from "../lib/key";
import { IRule } from "../models/trigger";
import { getEnvVar } from "../lib/env";

export class MySqlEvaluator extends BaseEvaluator {
constructor(config: any) {
Expand Down Expand Up @@ -152,7 +153,7 @@ async function runQuery(connection: mysql.Connection, app) {
let connections: mysql.Connection[] = [];

function configureSSLForConnection(app, config: any) {
const sslDisabledValue = process.env[`mysql-${ app.connection }-ssl-disabled`];
const sslDisabledValue = getEnvVar(`mysql-${ app.connection }-ssl-disabled`);
if (!sslDisabledValue) {
return;
}
Expand All @@ -166,11 +167,11 @@ function configureSSLForConnection(app, config: any) {

export async function getConnection(app): Promise<mysql.Connection> {
const config = {
host: process.env[`mysql-${ app.connection }-host`],
user: process.env[`mysql-${ app.connection }-user`],
password: process.env[`mysql-${ app.connection }-password`],
port: process.env[`mysql-${ app.connection }-port`],
database: process.env[`mysql-${ app.connection }-database`],
host: getEnvVar(`mysql-${ app.connection }-host`),
user: getEnvVar(`mysql-${ app.connection }-user`),
password: getEnvVar(`mysql-${ app.connection }-password`),
port: getEnvVar(`mysql-${ app.connection }-port`),
database: getEnvVar(`mysql-${ app.connection }-database`),
timezone: 'Z',
multipleStatements: true
};
Expand Down
7 changes: 4 additions & 3 deletions src/evaluators/sumo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import { IApp } from "../models/app";
import { BaseEvaluator, EvaluatorType, findTriggerRulesFor, generateValueForVariable } from "./base";
import { IUniqueKey } from "../lib/key";
import { RateLimiter } from "../lib/rate-limiter";
import { getEnvVar } from "../lib/env";

const SumoDomain = process.env["sumo-domain"] ?? "api.eu.sumologic.com";
const SumoDomain = getEnvVar("sumo-domain") ?? "api.eu.sumologic.com";
const SumoUrl = `https://${ SumoDomain }/api/v1/search/jobs`;

const JobPollMillis = 1000;
Expand Down Expand Up @@ -207,15 +208,15 @@ async function deleteJob(app, log) {
}

function getRequestConfig(tokenName): AxiosRequestConfig {
if (!process.env[tokenName]) {
if (!getEnvVar(tokenName)) {
throw new Error(`missing sumo logic env var with name '${ tokenName }'`);
}
return {
timeout: 10000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Basic ${ Buffer.from(process.env[tokenName]).toString('base64') }`
Authorization: `Basic ${ Buffer.from(getEnvVar(tokenName)).toString('base64') }`
}
};
}
Expand Down
5 changes: 3 additions & 2 deletions src/evaluators/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { BaseEvaluator, EvaluatorType } from "./base";
import { IUniqueKey } from "../lib/key";
import * as https from "node:https";
import { parsePeriodToHours } from "../lib/period-parser";
import { getEnvVar } from "../lib/env";

export class WebEvaluator extends BaseEvaluator {
constructor(config: any) {
Expand Down Expand Up @@ -241,11 +242,11 @@ export function getCustomHeaders(headers: any): any {
const value = (headers[key] ?? "").toString();
const match = value.match(/^\$(.*)$/);
if (match) {
const envVar = process.env[match[1]];
const envVar = getEnvVar(match[1]);
if (!envVar) {
log(`warning: environment variable used in custom header, '${ match[1] }' not found`)
}
headers[key] = process.env[match[1]] ?? value;
headers[key] = getEnvVar(match[1], value);
}
}
return headers;
Expand Down
39 changes: 39 additions & 0 deletions src/lib/env.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { getEnvVar } from "./env";

describe("env", () => {
describe("with null/undefined key", () => {
it("should return undefined", async () => {
expect(getEnvVar(undefined)).toBeUndefined();
expect(getEnvVar(null)).toBeUndefined();
});
});
describe("with missing value", () => {
it("should return default value", async () => {
const val1 = getEnvVar("teseting123");
expect(val1).toBeUndefined();
const val2 = getEnvVar("testing123", "default");
expect(val2).toBe("default");
});
});
describe("with value", () => {
it("should return it", async () => {
process.env["valueset"] = "123";
const val = getEnvVar("valueset");
expect(val).toBe("123");
});
});
describe("with dash in name", () => {
it("should check underscore variants", async () => {
process.env["testing_123_456"] = "value";
const val = getEnvVar("testing-123-456");
expect(val).toBe("value");
});
});
describe("with underscore in name", () => {
it("should check dash variants", async () => {
process.env["testing-a1-b2"] = "value";
const val = getEnvVar("testing_a1_b2");
expect(val).toBe("value");
});
});
});
21 changes: 21 additions & 0 deletions src/lib/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
in some environments, env vars with dashes aren't supported, or are converted to snake_case,
so check all variants of a key when attempting to retrieve it
*/
export function getEnvVar(key: string, defaultValue: any = undefined): any {
if (!key) {
return defaultValue;
}
const variants = [
key,
key.replace(/_/g, '-'),
key.replace(/-/g, '_')];
let value = defaultValue;
for (const variant of variants) {
if (process.env[variant]) {
value = process.env[variant];
break;
}
}
return value;
}
9 changes: 5 additions & 4 deletions src/lib/utility.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import * as crypto from "crypto";
import { log } from "../models/logger";
import { sleepMs } from "./sleep";
import { getEnvVar } from "./env";

Error.stackTraceLimit = Infinity;

export const DefaultLocale = process.env.LC_ALL
|| process.env.LC_MESSAGES
|| process.env.LANG
|| process.env.LANGUAGE;
export const DefaultLocale = getEnvVar("LC_ALL")
|| getEnvVar("LC_MESSAGES")
|| getEnvVar("LANG")
|| getEnvVar("LANGUAGE");
const defaultTimeZone = "Africa/Johannesburg";
let locale = correctCUTF8Locale(DefaultLocale || "en-US");
let timeZone = defaultTimeZone;
Expand Down
3 changes: 2 additions & 1 deletion src/models/channels/slack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import axios from "axios";
import { pluraliseWithS, toLocalTimeString, tryExecuteTimes } from "../../lib/utility";
import { AlertConfiguration } from "../alert_configuration";
import * as os from "os";
import { getEnvVar } from "../../lib/env";

export class SlackChannelConfig extends ChannelConfig {
public channel: string;
Expand All @@ -15,7 +16,7 @@ export class SlackChannelConfig extends ChannelConfig {
super(name, config);
this.type = ChannelType.Slack;
this.channel = config.channel;
this.token = process.env[config.token];
this.token = getEnvVar(config.token);
this.workspace = config.workspace;
}

Expand Down
7 changes: 4 additions & 3 deletions src/models/channels/sms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import axios from "axios";
import { pluraliseWithS } from "../../lib/utility";
import { ChannelConfig, ChannelType } from "./base";
import FormData from "form-data";
import { getEnvVar } from "../../lib/env";

export interface SMSContact {
name: string;
Expand Down Expand Up @@ -53,9 +54,9 @@ export class SMSChannelConfig extends ChannelConfig {
private async sendSMSToAllContacts(message: string): Promise<void> {
try {
const data = new FormData();
data.append('user', process.env["clickatell-user"]);
data.append('password', process.env["clickatell-password"]);
data.append('api_id', process.env["clickatell-key"]);
data.append('user', getEnvVar("clickatell-user"));
data.append('password', getEnvVar("clickatell-password"));
data.append('api_id', getEnvVar("clickatell-key"));
data.append('to', this.contacts.map(x => x.mobile).join(","));
data.append('text', message);
const config = {
Expand Down

0 comments on commit f83e784

Please sign in to comment.