Skip to content

Commit

Permalink
Merge pull request #1785 from balena-io/enable-disable-scheduled-jobs
Browse files Browse the repository at this point in the history
Add the ability to enable/disable scheduled jobs
  • Loading branch information
Page- authored Oct 8, 2024
2 parents 8678b2e + fde280f commit dfbb69e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/infra/scheduler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import Redlock from 'redlock';
import type { ScheduledJobRun } from '../../balena-model.js';
import { captureException } from '../error-handling/index.js';
import { redis, redisRO } from '../redis/index.js';
import { DISABLED_SCHEDULED_JOBS } from '../../lib/config.js';

export type { Job } from 'node-schedule';

Expand Down Expand Up @@ -88,6 +89,7 @@ const updateJobInfoExecute = async (jobInfoKey: string, job: schedule.Job) => {
await redis.set(jobInfoKey, serializedJobInfo);
};

export const jobIds: string[] = [];
export const scheduleJob = (
jobId: string,
rule:
Expand All @@ -99,6 +101,7 @@ export const scheduleJob = (
jobFunction: JobFunction,
lockOptions?: LockSettings,
): schedule.Job => {
jobIds.push(jobId);
const ttl = lockOptions?.ttl ? lockOptions.ttl : JOB_DEFAULT_TTL;
const jobLockKey = JOB_LOCK_PREFIX + jobId;
const jobInfoKey = JOB_INFO_PREFIX + jobId;
Expand All @@ -107,6 +110,11 @@ export const scheduleJob = (
rule,
async (fireDate: Date) => {
try {
if (DISABLED_SCHEDULED_JOBS.has(jobId)) {
// If jobs are not enabled then we immediately return without taking a lock.
// This allows dynamically enabling/disabling jobs without needing to restart the API.
return;
}
const lock: Redlock.Lock = await locker.lock(jobLockKey, ttl);
const rootApi = api.resin.clone({
passthrough: { req: permissions.root },
Expand Down
11 changes: 11 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
SECONDS,
hostPortsVar,
trustProxyVar,
arrayVar,
} from '@balena/env-parsing';

// Even though we only use these when TRUST_PROXY we do not conditionally
Expand Down Expand Up @@ -486,6 +487,16 @@ export const WEBRESOURCES_CLOUDFRONT_HOST = optionalVar(
'WEBRESOURCES_CLOUDFRONT_HOST',
);

export const DISABLED_SCHEDULED_JOBS = new Set(
arrayVar('DISABLED_SCHEDULED_JOBS') ?? [],
);
export const disableScheduledJob = (jobName: string) => {
DISABLED_SCHEDULED_JOBS.add(jobName);
};
export const enableScheduledJob = (jobName: string) => {
DISABLED_SCHEDULED_JOBS.delete(jobName);
};

/**
* Splits an env var in the format of `${username}:${password}`
* into a RedisAuth object. Auth is optional, so this can return
Expand Down

0 comments on commit dfbb69e

Please sign in to comment.