extern "C"
|
{
|
#include "postgres.h"
|
#include "fmgr.h"
|
#include "access/xact.h"
|
#include "catalog/pg_database.h"
|
#include "executor/spi.h"
|
#include "libpq/pqsignal.h"
|
#include "miscadmin.h"
|
#include "utils/memutils.h"
|
#include "pgstat.h"
|
#include "postmaster/bgworker.h"
|
#include "postmaster/interrupt.h"
|
#include "storage/fd.h"
|
#include "storage/ipc.h"
|
#include "storage/latch.h"
|
#include "storage/lwlock.h"
|
#include "storage/proc.h"
|
#include "storage/procarray.h"
|
#include "storage/shmem.h"
|
#include "tcop/tcopprot.h"
|
#include "utils/acl.h"
|
#include "utils/builtins.h"
|
#include "utils/datum.h"
|
#include "utils/guc.h"
|
#include "utils/snapmgr.h"
|
#include "utils/timestamp.h"
|
#include "dbms/dbms_scheduler.h"
|
}
|
|
#include <cerrno>
|
#include <cstdlib>
|
#include <cstring>
|
#include <fcntl.h>
|
#include <unistd.h>
|
|
#include "dbms_scheduler_log.h"
|
|
extern "C" void rudb_scheduler_coord_die(SIGNAL_ARGS);
|
|
namespace DbmsScheduler
|
{
|
|
static const int SLOT_MAX = 32;
|
static const int DB_LIST_MAX = 64;
|
static const int STALE_RESERVE_MS = 15000;
|
static const int ERROR_TEXT_MAX = 200;
|
|
struct ExecArg
|
{
|
Oid databaseId;
|
int32 slotIndex;
|
};
|
|
struct SchedulerSlot
|
{
|
bool inUse;
|
int32 pid;
|
Oid databaseId;
|
TimestampTz reservedAt;
|
};
|
|
struct DbLogHistoryState
|
{
|
Oid databaseId;
|
int32 lastLogHistory;
|
TimestampTz stableSince;
|
};
|
|
struct SchedulerShmem
|
{
|
slock_t mutex;
|
Latch latch;
|
SchedulerSlot slots[SLOT_MAX];
|
DbLogHistoryState dbHistory[DB_LIST_MAX];
|
};
|
|
class Coordinator
|
{
|
public:
|
static void defineGucs();
|
static void requestShmem();
|
static void startupShmem();
|
static void registerWorker();
|
static void workerMain();
|
static void executorMain(Datum arg);
|
static void failLogMain(Datum arg);
|
static bool persistFailedRun(const char *owner, const char *jobName,
|
const char *errorText);
|
static void wakeup();
|
|
private:
|
static void attach();
|
static void clearSlot(int slotIndex);
|
static int reserveSlot(Oid databaseId);
|
static bool databaseBusy(Oid databaseId);
|
static int activeSlots();
|
static void reapSlots();
|
static bool launchExecutor(Oid databaseId, int slotIndex);
|
static void releaseSlotExit(int code, Datum arg);
|
static bool claimJob(char **owner, char **jobName, char **jobAction);
|
static void syncWindows();
|
static void purgeExpiredLogs();
|
static void runClaimed(const char *owner, const char *jobName, const char *jobAction);
|
static void finishJob(const char *owner, const char *jobName, const char *status,
|
const char *errorText);
|
|
static SchedulerShmem *shared_;
|
static volatile sig_atomic_t stopRequested_;
|
|
public:
|
static shmem_request_hook_type prevRequest_;
|
static shmem_startup_hook_type prevStartup_;
|
static void requestStop();
|
};
|
|
SchedulerShmem *Coordinator::shared_ = NULL;
|
shmem_request_hook_type Coordinator::prevRequest_ = NULL;
|
shmem_startup_hook_type Coordinator::prevStartup_ = NULL;
|
volatile sig_atomic_t Coordinator::stopRequested_ = 0;
|
|
extern "C"
|
{
|
int rudb_scheduler_max_workers = 5;
|
int rudb_scheduler_coordinator_nap_ms = 1000;
|
}
|
|
void
|
Coordinator::defineGucs()
|
{
|
DefineCustomIntVariable("dbms_scheduler.max_workers",
|
"Сколько исполнителей DBMS_SCHEDULER одновременно. 0 не запускает задания по времени.",
|
NULL,
|
&rudb_scheduler_max_workers,
|
5, 0, SLOT_MAX,
|
PGC_SIGHUP, 0,
|
NULL, NULL, NULL);
|
DefineCustomIntVariable("dbms_scheduler.coordinator_nap_ms",
|
"Пауза координатора DBMS_SCHEDULER, миллисекунды.",
|
NULL,
|
&rudb_scheduler_coordinator_nap_ms,
|
1000, 100, 1000,
|
PGC_SIGHUP, 0,
|
NULL, NULL, NULL);
|
}
|
|
void
|
Coordinator::requestShmem()
|
{
|
if (prevRequest_ != NULL)
|
prevRequest_();
|
RequestAddinShmemSpace(MAXALIGN(sizeof(SchedulerShmem)));
|
}
|
|
void
|
Coordinator::startupShmem()
|
{
|
bool found = false;
|
|
if (prevStartup_ != NULL)
|
prevStartup_();
|
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
|
shared_ = (SchedulerShmem *) ShmemInitStruct("rudb scheduler",
|
sizeof(SchedulerShmem),
|
&found);
|
if (!found) {
|
MemSet(shared_, 0, sizeof(SchedulerShmem));
|
SpinLockInit(&shared_->mutex);
|
InitSharedLatch(&shared_->latch);
|
}
|
LWLockRelease(AddinShmemInitLock);
|
}
|
|
void
|
Coordinator::attach()
|
{
|
bool found = false;
|
|
if (shared_ != NULL)
|
return;
|
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
|
shared_ = (SchedulerShmem *) ShmemInitStruct("rudb scheduler",
|
sizeof(SchedulerShmem),
|
&found);
|
LWLockRelease(AddinShmemInitLock);
|
}
|
|
void
|
Coordinator::registerWorker()
|
{
|
BackgroundWorker worker;
|
|
if (IsBinaryUpgrade)
|
return;
|
memset(&worker, 0, sizeof(worker));
|
snprintf(worker.bgw_name, BGW_MAXLEN, "RUDB Scheduler coordinator");
|
snprintf(worker.bgw_type, BGW_MAXLEN, "RUDB Scheduler coordinator");
|
snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
|
snprintf(worker.bgw_function_name, BGW_MAXLEN, "rudb_scheduler_worker_main");
|
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
|
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
|
worker.bgw_restart_time = 5;
|
worker.bgw_notify_pid = 0;
|
RegisterBackgroundWorker(&worker);
|
}
|
|
void
|
Coordinator::clearSlot(int slotIndex)
|
{
|
if (shared_ == NULL || slotIndex < 0 || slotIndex >= SLOT_MAX)
|
return;
|
SpinLockAcquire(&shared_->mutex);
|
shared_->slots[slotIndex].inUse = false;
|
shared_->slots[slotIndex].pid = 0;
|
shared_->slots[slotIndex].databaseId = InvalidOid;
|
SpinLockRelease(&shared_->mutex);
|
}
|
|
void
|
Coordinator::releaseSlotExit(int code, Datum arg)
|
{
|
(void) code;
|
clearSlot(DatumGetInt32(arg));
|
}
|
|
int
|
Coordinator::reserveSlot(Oid databaseId)
|
{
|
int slotIndex = -1;
|
int i;
|
|
SpinLockAcquire(&shared_->mutex);
|
for (i = 0; i < SLOT_MAX; i++) {
|
if (!shared_->slots[i].inUse) {
|
shared_->slots[i].inUse = true;
|
shared_->slots[i].pid = 0;
|
shared_->slots[i].databaseId = databaseId;
|
shared_->slots[i].reservedAt = GetCurrentTimestamp();
|
slotIndex = i;
|
break;
|
}
|
}
|
SpinLockRelease(&shared_->mutex);
|
return slotIndex;
|
}
|
|
bool
|
Coordinator::databaseBusy(Oid databaseId)
|
{
|
bool busy = false;
|
int i;
|
|
SpinLockAcquire(&shared_->mutex);
|
for (i = 0; i < SLOT_MAX; i++) {
|
if (shared_->slots[i].inUse && shared_->slots[i].databaseId == databaseId) {
|
busy = true;
|
break;
|
}
|
}
|
SpinLockRelease(&shared_->mutex);
|
return busy;
|
}
|
|
int
|
Coordinator::activeSlots()
|
{
|
int count = 0;
|
int i;
|
|
SpinLockAcquire(&shared_->mutex);
|
for (i = 0; i < SLOT_MAX; i++) {
|
if (shared_->slots[i].inUse)
|
count++;
|
}
|
SpinLockRelease(&shared_->mutex);
|
return count;
|
}
|
|
void
|
Coordinator::reapSlots()
|
{
|
TimestampTz now = GetCurrentTimestamp();
|
int i;
|
|
SpinLockAcquire(&shared_->mutex);
|
for (i = 0; i < SLOT_MAX; i++) {
|
SchedulerSlot *slot = &shared_->slots[i];
|
bool drop = false;
|
|
if (!slot->inUse)
|
continue;
|
if (slot->pid > 0 && BackendPidGetProc(slot->pid) == NULL)
|
drop = true;
|
else if (slot->pid == 0 &&
|
TimestampDifferenceExceeds(slot->reservedAt, now, STALE_RESERVE_MS))
|
drop = true;
|
if (drop) {
|
slot->inUse = false;
|
slot->pid = 0;
|
slot->databaseId = InvalidOid;
|
}
|
}
|
SpinLockRelease(&shared_->mutex);
|
}
|
|
bool
|
Coordinator::launchExecutor(Oid databaseId, int slotIndex)
|
{
|
BackgroundWorker worker;
|
ExecArg arg;
|
BackgroundWorkerHandle *handle = NULL;
|
bool registered;
|
|
memset(&worker, 0, sizeof(worker));
|
snprintf(worker.bgw_name, BGW_MAXLEN, "RUDB Scheduler executor");
|
snprintf(worker.bgw_type, BGW_MAXLEN, "RUDB Scheduler executor");
|
snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
|
snprintf(worker.bgw_function_name, BGW_MAXLEN, "rudb_scheduler_executor_main");
|
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
|
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
|
worker.bgw_restart_time = BGW_NEVER_RESTART;
|
worker.bgw_notify_pid = 0;
|
arg.databaseId = databaseId;
|
arg.slotIndex = slotIndex;
|
memcpy(worker.bgw_extra, &arg, sizeof(arg));
|
registered = RegisterDynamicBackgroundWorker(&worker, &handle);
|
if (handle != NULL)
|
pfree(handle);
|
return registered;
|
}
|
|
void
|
Coordinator::wakeup()
|
{
|
attach();
|
if (shared_ != NULL)
|
SetLatch(&shared_->latch);
|
}
|
|
|
void
|
Coordinator::requestStop()
|
{
|
stopRequested_ = 1;
|
if (shared_ != NULL)
|
SetLatch(&shared_->latch);
|
}
|
|
void
|
Coordinator::workerMain()
|
{
|
attach();
|
if (shared_ == NULL)
|
proc_exit(1);
|
OwnLatch(&shared_->latch);
|
pqsignal(SIGTERM, rudb_scheduler_coord_die);
|
pqsignal(SIGHUP, SignalHandlerForConfigReload);
|
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
|
BackgroundWorkerUnblockSignals();
|
BackgroundWorkerInitializeConnection("postgres", NULL, 0);
|
logEventf("координатор запущен",
|
"[Status: OK, Workers: %d]",
|
rudb_scheduler_max_workers);
|
|
while (!stopRequested_) {
|
int budget;
|
Oid dbList[DB_LIST_MAX];
|
int dbCount = 0;
|
int i;
|
int rc;
|
|
logRotate();
|
CHECK_FOR_INTERRUPTS();
|
if (ConfigReloadPending) {
|
ConfigReloadPending = false;
|
ProcessConfigFile(PGC_SIGHUP);
|
}
|
ResetLatch(&shared_->latch);
|
reapSlots();
|
budget = rudb_scheduler_max_workers - activeSlots();
|
if (budget > 0) {
|
SetCurrentStatementStartTimestamp();
|
StartTransactionCommand();
|
PushActiveSnapshot(GetTransactionSnapshot());
|
if (SPI_connect() == SPI_OK_CONNECT) {
|
rc = SPI_execute(
|
"SELECT oid FROM pg_database "
|
"WHERE datallowconn AND NOT datistemplate",
|
true, 0);
|
if (rc == SPI_OK_SELECT) {
|
for (i = 0; i < (int) SPI_processed && dbCount < DB_LIST_MAX; i++) {
|
bool isnull = false;
|
Datum value = SPI_getbinval(SPI_tuptable->vals[i],
|
SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
dbList[dbCount++] = DatumGetObjectId(value);
|
}
|
}
|
SPI_finish();
|
}
|
PopActiveSnapshot();
|
CommitTransactionCommand();
|
|
for (i = 0; i < dbCount && budget > 0; i++) {
|
int slotIndex;
|
|
if (databaseBusy(dbList[i]))
|
continue;
|
slotIndex = reserveSlot(dbList[i]);
|
if (slotIndex < 0)
|
break;
|
if (!launchExecutor(dbList[i], slotIndex)) {
|
clearSlot(slotIndex);
|
logEventf("исполнитель не поставлен",
|
"[Status: FAIL, Database: %u]",
|
dbList[i]);
|
}
|
else
|
budget--;
|
}
|
}
|
rc = WaitLatch(&shared_->latch,
|
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
|
rudb_scheduler_coordinator_nap_ms,
|
0);
|
(void) rc;
|
}
|
DisownLatch(&shared_->latch);
|
proc_exit(0);
|
}
|
|
static const int64 WINDOW_OPEN_GRACE_USEC = 10 * USECS_PER_SEC;
|
static const int WINDOW_ROW_MAX = 32;
|
|
struct WindowDue
|
{
|
char *name;
|
char *repeat;
|
bool high;
|
bool active;
|
bool startNull;
|
TimestampTz anchor;
|
TimestampTz occurs;
|
int64 durationUsec;
|
};
|
|
static bool
|
windowOccurrence(const char *repeat, TimestampTz anchor, int64 usec,
|
TimestampTz now, TimestampTz *occurs)
|
{
|
TimestampTz searchAfter;
|
TimestampTz cursor;
|
int step;
|
|
if (repeat == NULL || occurs == NULL || usec <= 0)
|
return false;
|
searchAfter = now - usec;
|
if (searchAfter < anchor)
|
searchAfter = anchor - 1;
|
if (!rudb_scheduler_calendar_next(repeat, anchor, searchAfter, &cursor))
|
return false;
|
for (step = 0; step < 64; step++) {
|
TimestampTz next;
|
|
if (!rudb_scheduler_calendar_next(repeat, anchor, cursor, &next))
|
break;
|
if (next > now)
|
break;
|
cursor = next;
|
}
|
if (cursor > now)
|
return false;
|
*occurs = cursor;
|
return true;
|
}
|
|
static void
|
setCurrentOpenWindow(const char *windowName)
|
{
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
int rc;
|
|
if (windowName == NULL) {
|
SPI_execute(
|
"DELETE FROM pg_catalog.dbms_scheduler_global "
|
"WHERE lower(attribute) = 'current_open_window' "
|
" AND NOT EXISTS (SELECT 1 FROM pg_catalog.dbms_scheduler_window "
|
" WHERE active)",
|
false, 0);
|
return;
|
}
|
values[0] = CStringGetTextDatum(windowName);
|
rc = SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_scheduler_global "
|
"SET value = $1 "
|
"WHERE lower(attribute) = 'current_open_window'",
|
1, argtypes, values, nulls, false, 0);
|
if (rc == SPI_OK_UPDATE && SPI_processed == 0) {
|
SPI_execute_with_args(
|
"INSERT INTO pg_catalog.dbms_scheduler_global (attribute, value) "
|
"SELECT 'current_open_window', $1 "
|
"WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.dbms_scheduler_global "
|
" WHERE lower(attribute) = 'current_open_window')",
|
1, argtypes, values, nulls, false, 0);
|
}
|
}
|
|
void
|
Coordinator::syncWindows()
|
{
|
WindowDue due[WINDOW_ROW_MAX];
|
int count = 0;
|
int i;
|
int rc;
|
bool manual = false;
|
char *keep = NULL;
|
char *freshHigh = NULL;
|
char *freshLow = NULL;
|
char *chosen = NULL;
|
TimestampTz now;
|
MemoryContext caller = CurrentMemoryContext;
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return;
|
rc = SPI_execute(
|
"SELECT to_regclass('pg_catalog.dbms_scheduler_window') IS NOT NULL",
|
true, 1);
|
if (rc != SPI_OK_SELECT || SPI_processed != 1) {
|
SPI_finish();
|
return;
|
}
|
{
|
bool isnull = false;
|
Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
|
if (isnull || !DatumGetBool(value)) {
|
SPI_finish();
|
return;
|
}
|
}
|
rc = SPI_execute(
|
"SELECT 1 FROM pg_catalog.dbms_scheduler_window "
|
"WHERE active AND manual_duration IS NOT NULL LIMIT 1",
|
true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed > 0)
|
manual = true;
|
if (manual) {
|
SPI_finish();
|
return;
|
}
|
rc = SPI_execute(
|
"SELECT window_name, repeat_interval, start_date, duration, "
|
" window_priority, active "
|
"FROM pg_catalog.dbms_scheduler_window "
|
"WHERE enabled AND schedule_type = 'CALENDAR' "
|
" AND repeat_interval IS NOT NULL AND start_date IS NOT NULL "
|
"ORDER BY window_name",
|
true, WINDOW_ROW_MAX);
|
if (rc != SPI_OK_SELECT) {
|
SPI_finish();
|
return;
|
}
|
memset(due, 0, sizeof(due));
|
now = GetCurrentTimestamp();
|
count = (int) SPI_processed;
|
if (count > WINDOW_ROW_MAX)
|
count = WINDOW_ROW_MAX;
|
for (i = 0; i < count; i++) {
|
bool isnull = false;
|
Datum value;
|
Interval *duration;
|
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull);
|
if (isnull)
|
continue;
|
due[i].name = MemoryContextStrdup(caller, text_to_cstring(DatumGetTextPP(value)));
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull);
|
if (isnull)
|
continue;
|
due[i].repeat = MemoryContextStrdup(caller, text_to_cstring(DatumGetTextPP(value)));
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 3, &isnull);
|
due[i].startNull = isnull;
|
if (!isnull)
|
due[i].anchor = DatumGetTimestampTz(value);
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 4, &isnull);
|
if (isnull)
|
continue;
|
duration = DatumGetIntervalP(value);
|
due[i].durationUsec = duration->time + (int64) duration->day * USECS_PER_DAY;
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 5, &isnull);
|
due[i].high = !isnull && pg_strcasecmp(text_to_cstring(DatumGetTextPP(value)), "HIGH") == 0;
|
value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 6, &isnull);
|
due[i].active = !isnull && DatumGetBool(value);
|
}
|
SPI_finish();
|
for (i = 0; i < count; i++) {
|
TimestampTz occurs;
|
bool fresh;
|
|
if (due[i].name == NULL || due[i].repeat == NULL || due[i].startNull)
|
continue;
|
if (!windowOccurrence(due[i].repeat, due[i].anchor, due[i].durationUsec, now, &occurs)) {
|
if (due[i].active)
|
due[i].durationUsec = -1;
|
continue;
|
}
|
due[i].occurs = occurs;
|
if (now >= occurs + due[i].durationUsec) {
|
if (due[i].active)
|
due[i].durationUsec = -1;
|
continue;
|
}
|
fresh = (now - occurs) <= WINDOW_OPEN_GRACE_USEC;
|
if (due[i].active)
|
keep = due[i].name;
|
if (!fresh)
|
continue;
|
if (due[i].high) {
|
if (freshHigh == NULL || strcmp(due[i].name, freshHigh) < 0)
|
freshHigh = due[i].name;
|
}
|
else if (freshLow == NULL || strcmp(due[i].name, freshLow) < 0)
|
freshLow = due[i].name;
|
}
|
|
if (freshHigh != NULL) {
|
bool keepHigh = false;
|
|
for (i = 0; i < count; i++) {
|
if (keep != NULL && due[i].name != NULL && strcmp(due[i].name, keep) == 0)
|
keepHigh = due[i].high;
|
}
|
if (keep == NULL || !keepHigh)
|
chosen = freshHigh;
|
else
|
chosen = keep;
|
}
|
else if (keep != NULL)
|
chosen = keep;
|
else if (freshLow != NULL)
|
chosen = freshLow;
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return;
|
if (chosen != NULL) {
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
|
values[0] = CStringGetTextDatum(chosen);
|
SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_scheduler_window "
|
"SET active = false "
|
"WHERE active AND manual_duration IS NULL "
|
" AND lower(window_name) <> lower($1)",
|
1, argtypes, values, nulls, false, 0);
|
SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_scheduler_window "
|
"SET active = true "
|
"WHERE lower(window_name) = lower($1)",
|
1, argtypes, values, nulls, false, 0);
|
setCurrentOpenWindow(chosen);
|
{
|
bool already = false;
|
|
for (i = 0; i < count; i++) {
|
if (due[i].name != NULL && due[i].active && strcmp(due[i].name, chosen) == 0)
|
already = true;
|
}
|
if (!already)
|
logEventf("окно открыто по календарю", "[Window: %s]", chosen);
|
}
|
}
|
else {
|
SPI_execute(
|
"UPDATE pg_catalog.dbms_scheduler_window "
|
"SET active = false "
|
"WHERE active AND manual_duration IS NULL",
|
false, 0);
|
setCurrentOpenWindow(NULL);
|
}
|
SPI_finish();
|
}
|
|
void
|
Coordinator::purgeExpiredLogs()
|
{
|
int rc;
|
int32 days = 30;
|
bool ready = false;
|
TimestampTz now;
|
Oid argtypes[1] = {INT4OID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
|
if (shared_ == NULL)
|
return;
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return;
|
rc = SPI_execute(
|
"SELECT to_regclass('pg_catalog.dbms_scheduler_global') IS NOT NULL "
|
" AND to_regclass('pg_catalog.dbms_scheduler_job_run') IS NOT NULL",
|
true, 1);
|
if (rc != SPI_OK_SELECT || SPI_processed != 1) {
|
SPI_finish();
|
return;
|
}
|
{
|
bool isnull = false;
|
Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
|
if (isnull || !DatumGetBool(value)) {
|
SPI_finish();
|
return;
|
}
|
}
|
rc = SPI_execute(
|
"SELECT value FROM pg_catalog.dbms_scheduler_global "
|
"WHERE lower(attribute) = 'log_history' LIMIT 1",
|
true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1) {
|
bool isnull = false;
|
Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
|
if (!isnull) {
|
char *raw = text_to_cstring(DatumGetTextPP(value));
|
char *endp = NULL;
|
long parsed = strtol(raw, &endp, 10);
|
|
if (raw[0] != '\0' && endp != NULL && *endp == '\0'
|
&& parsed >= 0 && parsed <= 1000000)
|
days = (int32) parsed;
|
}
|
}
|
now = GetCurrentTimestamp();
|
SpinLockAcquire(&shared_->mutex);
|
{
|
int idx = -1;
|
int freeIdx = -1;
|
int i;
|
|
for (i = 0; i < DB_LIST_MAX; i++) {
|
if (shared_->dbHistory[i].databaseId == MyDatabaseId) {
|
idx = i;
|
break;
|
}
|
if (freeIdx < 0 && shared_->dbHistory[i].databaseId == InvalidOid)
|
freeIdx = i;
|
}
|
if (idx < 0 && freeIdx >= 0) {
|
idx = freeIdx;
|
shared_->dbHistory[idx].databaseId = MyDatabaseId;
|
shared_->dbHistory[idx].lastLogHistory = -1;
|
shared_->dbHistory[idx].stableSince = 0;
|
}
|
if (idx >= 0) {
|
if (shared_->dbHistory[idx].lastLogHistory != days) {
|
shared_->dbHistory[idx].lastLogHistory = days;
|
shared_->dbHistory[idx].stableSince = now;
|
ready = false;
|
} else {
|
ready = TimestampDifferenceExceeds(shared_->dbHistory[idx].stableSince, now, 2000);
|
}
|
}
|
}
|
SpinLockRelease(&shared_->mutex);
|
if (ready) {
|
values[0] = Int32GetDatum(days);
|
SPI_execute_with_args(
|
"DELETE FROM pg_catalog.dbms_scheduler_job_run "
|
"WHERE log_date < clock_timestamp() - make_interval(days => $1)",
|
1, argtypes, values, nulls, false, 0);
|
}
|
SPI_finish();
|
}
|
|
bool
|
Coordinator::claimJob(char **owner, char **jobName, char **jobAction)
|
{
|
MemoryContext caller;
|
int rc;
|
bool claimed = false;
|
|
*owner = NULL;
|
*jobName = NULL;
|
*jobAction = NULL;
|
caller = TopMemoryContext;
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return false;
|
SPI_execute(
|
"UPDATE pg_catalog.dbms_scheduler_job "
|
"SET state = 'SCHEDULED', worker_pid = NULL, "
|
" next_run_date = COALESCE(next_run_date, clock_timestamp()) "
|
"WHERE state = 'RUNNING' "
|
" AND worker_pid IS NOT NULL "
|
" AND NOT EXISTS (SELECT 1 FROM pg_stat_activity a "
|
" WHERE a.pid = worker_pid)",
|
false, 0);
|
rc = SPI_execute(
|
"UPDATE pg_catalog.dbms_scheduler_job "
|
"SET state = 'RUNNING', worker_pid = pg_backend_pid(), next_run_date = NULL "
|
"WHERE ctid = ("
|
" SELECT j.ctid FROM pg_catalog.dbms_scheduler_job j "
|
" WHERE j.state = 'SCHEDULED' "
|
" AND j.next_run_date IS NOT NULL "
|
" AND j.next_run_date <= clock_timestamp() "
|
" AND NOT EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_incompat i "
|
" JOIN pg_catalog.dbms_scheduler_incompat_member m "
|
" ON m.owner = i.owner AND m.incompatibility_name = i.incompatibility_name "
|
" WHERE i.enabled AND i.constraint_level = 'JOB_LEVEL' "
|
" AND m.object_owner = j.owner AND m.object_name = j.job_name "
|
" AND EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_incompat_member m2 "
|
" JOIN pg_catalog.dbms_scheduler_job j2 "
|
" ON j2.owner = m2.object_owner AND j2.job_name = m2.object_name "
|
" WHERE m2.owner = i.owner "
|
" AND m2.incompatibility_name = i.incompatibility_name "
|
" AND j2.state = 'RUNNING' AND j2.job_name <> j.job_name))"
|
" AND NOT EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_incompat i "
|
" JOIN pg_catalog.dbms_scheduler_incompat_member m "
|
" ON m.owner = i.owner AND m.incompatibility_name = i.incompatibility_name "
|
" WHERE i.enabled AND i.constraint_level = 'PROGRAM_LEVEL' "
|
" AND j.program_name IS NOT NULL "
|
" AND m.object_owner = j.owner AND m.object_name = j.program_name "
|
" AND EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_job j2 "
|
" JOIN pg_catalog.dbms_scheduler_incompat_member m2 "
|
" ON m2.object_owner = j2.owner AND m2.object_name = j2.program_name "
|
" WHERE m2.owner = i.owner "
|
" AND m2.incompatibility_name = i.incompatibility_name "
|
" AND j2.state = 'RUNNING' AND j2.program_name <> j.program_name))"
|
" AND NOT EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_resource_constraint c "
|
" JOIN pg_catalog.dbms_scheduler_resource r "
|
" ON r.owner = c.resource_owner AND r.resource_name = c.resource_name "
|
" WHERE c.object_owner = j.owner "
|
" AND (c.object_name = upper(j.job_name) "
|
" OR (j.program_name IS NOT NULL "
|
" AND c.object_name = upper(j.program_name))) "
|
" AND (r.status = 'BLOCKED_ALL_JOBS' "
|
" OR (r.status = 'ENFORCE_CONSTRAINTS' "
|
" AND c.units + COALESCE(("
|
" SELECT SUM(c2.units) "
|
" FROM pg_catalog.dbms_scheduler_job j2 "
|
" JOIN pg_catalog.dbms_scheduler_resource_constraint c2 "
|
" ON c2.resource_owner = r.owner "
|
" AND c2.resource_name = r.resource_name "
|
" AND c2.object_owner = j2.owner "
|
" AND (c2.object_name = upper(j2.job_name) "
|
" OR (j2.program_name IS NOT NULL "
|
" AND c2.object_name = upper(j2.program_name))) "
|
" WHERE j2.state = 'RUNNING' "
|
" AND NOT (j2.owner = j.owner AND j2.job_name = j.job_name)"
|
" ), 0) > r.units / 2))) "
|
" AND (j.schedule_name IS NULL "
|
" OR EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_schedule s "
|
" WHERE s.owner = j.owner AND s.schedule_name = j.schedule_name) "
|
" OR EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_window w "
|
" WHERE w.active "
|
" AND upper(w.window_name) = regexp_replace(upper(j.schedule_name), '^SYS\\.', '')) "
|
" OR EXISTS ("
|
" SELECT 1 FROM pg_catalog.dbms_scheduler_group g "
|
" JOIN pg_catalog.dbms_scheduler_group_member gm "
|
" ON gm.owner = g.owner AND upper(gm.group_name) = upper(g.group_name) "
|
" JOIN pg_catalog.dbms_scheduler_window w "
|
" ON gm.member_name = '\"SYS\".\"' || upper(w.window_name) || '\"' "
|
" WHERE g.owner = 'SYS' AND g.group_type = 'WINDOW' AND g.enabled "
|
" AND upper(g.group_name) = regexp_replace(upper(j.schedule_name), '^SYS\\.', '') "
|
" AND w.active)) "
|
" ORDER BY j.next_run_date "
|
" FOR UPDATE OF j SKIP LOCKED "
|
" LIMIT 1) "
|
"RETURNING owner, job_name, job_action",
|
false, 1);
|
if ((rc == SPI_OK_UPDATE_RETURNING || rc == SPI_OK_UPDATE) && SPI_processed == 1) {
|
bool isnull = false;
|
Datum value;
|
char *copied;
|
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (isnull)
|
copied = pstrdup("");
|
else
|
copied = text_to_cstring(DatumGetTextPP(value));
|
*owner = MemoryContextStrdup(caller, copied);
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
|
if (isnull)
|
copied = pstrdup("");
|
else
|
copied = text_to_cstring(DatumGetTextPP(value));
|
*jobName = MemoryContextStrdup(caller, copied);
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull);
|
if (isnull)
|
copied = pstrdup("");
|
else
|
copied = text_to_cstring(DatumGetTextPP(value));
|
*jobAction = MemoryContextStrdup(caller, copied);
|
claimed = true;
|
}
|
SPI_finish();
|
return claimed;
|
}
|
|
void
|
Coordinator::finishJob(const char *owner, const char *jobName, const char *status,
|
const char *errorText)
|
{
|
Oid argtypes[6] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, INT4OID};
|
Datum values[6];
|
char nulls[6] = {' ', ' ', ' ', ' ', 'n', ' '};
|
int rc;
|
const char *state;
|
|
if (strcmp(status, "SUCCEEDED") == 0)
|
state = "COMPLETED";
|
else if (strcmp(status, "STOPPED") == 0)
|
state = "SCHEDULED";
|
else
|
state = "BROKEN";
|
values[0] = CStringGetTextDatum(owner);
|
values[1] = CStringGetTextDatum(jobName);
|
values[2] = CStringGetTextDatum(state);
|
values[3] = CStringGetTextDatum(status);
|
values[4] = (Datum) 0;
|
values[5] = Int32GetDatum(MyProcPid);
|
if (errorText != NULL) {
|
values[4] = CStringGetTextDatum(errorText);
|
nulls[4] = ' ';
|
}
|
bool writeLog = rudb_scheduler_log_run(owner, jobName, status);
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
return;
|
rc = SPI_execute_with_args(
|
"SELECT repeat_interval, start_date, end_date "
|
"FROM pg_catalog.dbms_scheduler_job "
|
"WHERE owner = $1 AND job_name = $2",
|
2, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1) {
|
bool isnull = false;
|
Datum value;
|
char *repeat = NULL;
|
bool startNull = true;
|
bool endNull = true;
|
TimestampTz startDate = 0;
|
TimestampTz endDate = 0;
|
TimestampTz nextRun;
|
bool hasNext = false;
|
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
repeat = text_to_cstring(DatumGetTextPP(value));
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
|
if (!isnull) {
|
startNull = false;
|
startDate = DatumGetTimestampTz(value);
|
}
|
value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull);
|
if (!isnull) {
|
endNull = false;
|
endDate = DatumGetTimestampTz(value);
|
}
|
if (repeat != NULL && repeat[0] != '\0') {
|
TimestampTz anchor = startNull ? GetCurrentTimestamp() : startDate;
|
TimestampTz after = GetCurrentTimestamp();
|
TimestampTz candidate;
|
|
if (rudb_scheduler_calendar_next(repeat, anchor, after, &candidate)
|
&& (endNull || candidate <= endDate)) {
|
nextRun = candidate;
|
hasNext = true;
|
state = "SCHEDULED";
|
}
|
}
|
if (repeat != NULL)
|
pfree(repeat);
|
if (hasNext) {
|
Oid writeTypes[4] = {TEXTOID, TEXTOID, TEXTOID, TIMESTAMPTZOID};
|
Datum writeValues[4];
|
char writeNulls[4] = {' ', ' ', ' ', ' '};
|
|
writeValues[0] = values[0];
|
writeValues[1] = values[1];
|
writeValues[2] = CStringGetTextDatum(state);
|
writeValues[3] = TimestampTzGetDatum(nextRun);
|
rc = SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_scheduler_job "
|
"SET state = $3, next_run_date = $4, worker_pid = NULL "
|
"WHERE owner = $1 AND job_name = $2",
|
4, writeTypes, writeValues, writeNulls, false, 0);
|
(void) rc;
|
}
|
}
|
values[2] = CStringGetTextDatum(state);
|
rc = SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_scheduler_job "
|
"SET state = $3, worker_pid = NULL "
|
"WHERE owner = $1 AND job_name = $2 "
|
" AND (repeat_interval IS NULL OR repeat_interval = '' "
|
" OR next_run_date IS NULL)",
|
3, argtypes, values, nulls, false, 0);
|
(void) rc;
|
if (writeLog) {
|
rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.dbms_scheduler_job_run "
|
"(owner, job_name, log_date, status, error, pid) "
|
"VALUES ($1, $2, clock_timestamp(), $4, $5, $6)",
|
6, argtypes, values, nulls, false, 0);
|
(void) rc;
|
}
|
/*
|
* auto_drop по умолчанию истинен. Одноразовый PLSQL без repeat_interval и
|
* без расписания после успешного запуска координатора удаляется, строка
|
* журнала остаётся. Цепочка и задание на окно или именованное расписание
|
* остаются: их состояние после успеха уже проверяют зелёные тесты.
|
* RUN_JOB в текущем сеансе сюда не попадает. Повторяющееся и
|
* auto_drop = false остаются.
|
*/
|
if (strcmp(status, "SUCCEEDED") == 0) {
|
rc = SPI_execute_with_args(
|
"SELECT 1 FROM pg_catalog.dbms_scheduler_job "
|
"WHERE owner = $1 AND job_name = $2 AND auto_drop "
|
" AND (repeat_interval IS NULL OR repeat_interval = '') "
|
" AND schedule_name IS NULL "
|
" AND job_type <> 'CHAIN'",
|
2, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1) {
|
const char *dropSql[] = {
|
"DELETE FROM pg_catalog.dbms_scheduler_job_arg "
|
"WHERE owner = $1 AND job_name = $2",
|
"DELETE FROM pg_catalog.dbms_scheduler_job_email "
|
"WHERE owner = $1 AND job_name = $2",
|
"DELETE FROM pg_catalog.dbms_scheduler_incompat_member "
|
"WHERE object_owner = $1 AND lower(object_name) = lower($2)",
|
"DELETE FROM pg_catalog.dbms_scheduler_resource_constraint "
|
"WHERE object_owner = $1 AND lower(object_name) = lower($2)",
|
"DELETE FROM pg_catalog.dbms_scheduler_job "
|
"WHERE owner = $1 AND job_name = $2",
|
NULL
|
};
|
int s;
|
|
for (s = 0; dropSql[s] != NULL; s++) {
|
rc = SPI_execute_with_args(dropSql[s], 2, argtypes, values, nulls,
|
false, 0);
|
(void) rc;
|
}
|
}
|
}
|
SPI_finish();
|
}
|
|
void
|
Coordinator::runClaimed(const char *owner, const char *jobName, const char *jobAction)
|
{
|
Oid roleId;
|
Oid saveUser;
|
int saveSec;
|
MemoryContext oldContext;
|
ResourceOwner oldOwner;
|
volatile bool spiOpen = false;
|
volatile bool ok = false;
|
volatile bool canceled = false;
|
char *errText = NULL;
|
|
roleId = get_role_oid(owner, false);
|
GetUserIdAndSecContext(&saveUser, &saveSec);
|
SetUserIdAndSecContext(roleId, 0);
|
oldContext = CurrentMemoryContext;
|
oldOwner = CurrentResourceOwner;
|
BeginInternalSubTransaction(NULL);
|
MemoryContextSwitchTo(oldContext);
|
PG_TRY();
|
{
|
if (jobAction != NULL && jobAction[0] != '\0') {
|
int rc;
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
ereport(ERROR,
|
(errmsg("dbms_scheduler: SPI не открылся"),
|
errdetail_internal("Output: [Status: FAIL, Job: %s]", jobName)));
|
spiOpen = true;
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
char *jobType = NULL;
|
char *toRun;
|
bool isnull = false;
|
|
values[0] = CStringGetTextDatum(owner);
|
values[1] = CStringGetTextDatum(jobName);
|
rc = SPI_execute_with_args(
|
"SELECT job_type, number_of_arguments FROM pg_catalog.dbms_scheduler_job "
|
"WHERE owner = $1 AND job_name = $2",
|
2, argtypes, values, nulls, true, 1);
|
int32 nargs = 0;
|
|
if (rc == SPI_OK_SELECT && SPI_processed == 1) {
|
Datum value = SPI_getbinval(SPI_tuptable->vals[0],
|
SPI_tuptable->tupdesc, 1, &isnull);
|
|
if (!isnull)
|
jobType = TextDatumGetCString(value);
|
value = SPI_getbinval(SPI_tuptable->vals[0],
|
SPI_tuptable->tupdesc, 2, &isnull);
|
if (!isnull)
|
nargs = DatumGetInt32(value);
|
}
|
if (jobType != NULL
|
&& (strcmp(jobType, "EXECUTABLE") == 0
|
|| strcmp(jobType, "EXTERNAL_SCRIPT") == 0)) {
|
SPI_finish();
|
spiOpen = false;
|
rudb_scheduler_run_os_job(owner, jobName, jobType, jobAction);
|
toRun = NULL;
|
rc = 0;
|
} else if (jobType != NULL && strcmp(jobType, "CHAIN") == 0) {
|
SPI_finish();
|
spiOpen = false;
|
if (!executeClaimedChain(owner, jobName, jobAction)) {
|
ereport(ERROR,
|
(errcode(ERRCODE_RAISE_EXCEPTION),
|
errmsg("chain step failed")));
|
}
|
toRun = NULL;
|
rc = 0;
|
} else if (jobType != NULL && strcmp(jobType, "STORED_PROCEDURE") == 0)
|
toRun = storedProcedureSql(jobAction, owner, jobName, nargs);
|
else
|
toRun = jobActionSql(jobType, jobAction, NULL, 0);
|
if (toRun != NULL)
|
rc = SPI_execute(toRun, false, 0);
|
}
|
if (spiOpen)
|
SPI_finish();
|
spiOpen = false;
|
if (rc < 0)
|
ereport(ERROR,
|
(errmsg("dbms_scheduler: действие задания не выполнено"),
|
errdetail_internal("Output: [Status: FAIL, Job: %s, Code: %d]",
|
jobName, rc)));
|
}
|
ReleaseCurrentSubTransaction();
|
MemoryContextSwitchTo(oldContext);
|
CurrentResourceOwner = oldOwner;
|
ok = true;
|
}
|
PG_CATCH();
|
{
|
ErrorData *edata;
|
|
MemoryContextSwitchTo(oldContext);
|
edata = CopyErrorData();
|
FlushErrorState();
|
if (spiOpen)
|
SPI_finish();
|
RollbackAndReleaseCurrentSubTransaction();
|
MemoryContextSwitchTo(oldContext);
|
CurrentResourceOwner = oldOwner;
|
if (edata != NULL && edata->sqlerrcode == ERRCODE_QUERY_CANCELED)
|
canceled = true;
|
else if (edata != NULL && edata->message != NULL)
|
errText = pnstrdup(edata->message, ERROR_TEXT_MAX);
|
else
|
errText = pstrdup("job failed");
|
if (edata != NULL)
|
FreeErrorData(edata);
|
}
|
PG_END_TRY();
|
SetUserIdAndSecContext(saveUser, saveSec);
|
if (ok) {
|
finishJob(owner, jobName, "SUCCEEDED", NULL);
|
rudb_scheduler_notify_email(owner, jobName, "JOB_SUCCEEDED");
|
logEventf("исполнитель завершил задание",
|
"[Status: SUCCEEDED, Job: %s]", jobName);
|
}
|
else if (canceled) {
|
finishJob(owner, jobName, "STOPPED", NULL);
|
rudb_scheduler_notify_email(owner, jobName, "JOB_STOPPED");
|
logEventf("исполнитель остановлен",
|
"[Status: STOPPED, Job: %s]", jobName);
|
}
|
else {
|
finishJob(owner, jobName, "FAILED", errText);
|
rudb_scheduler_notify_email(owner, jobName, "JOB_FAILED");
|
logEventf("исполнитель завершил задание",
|
"[Status: FAILED, Job: %s]", jobName);
|
}
|
}
|
|
void
|
Coordinator::executorMain(Datum arg)
|
{
|
ExecArg execArg;
|
char *owner = NULL;
|
char *jobName = NULL;
|
char *jobAction = NULL;
|
bool claimed = false;
|
|
memcpy(&execArg, MyBgworkerEntry->bgw_extra, sizeof(execArg));
|
attach();
|
if (shared_ != NULL && execArg.slotIndex >= 0 && execArg.slotIndex < SLOT_MAX) {
|
SpinLockAcquire(&shared_->mutex);
|
shared_->slots[execArg.slotIndex].pid = MyProcPid;
|
SpinLockRelease(&shared_->mutex);
|
before_shmem_exit(releaseSlotExit, Int32GetDatum(execArg.slotIndex));
|
}
|
pqsignal(SIGTERM, die);
|
pqsignal(SIGINT, StatementCancelHandler);
|
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
|
pqsignal(SIGHUP, SignalHandlerForConfigReload);
|
BackgroundWorkerUnblockSignals();
|
BackgroundWorkerInitializeConnectionByOid(execArg.databaseId, InvalidOid, 0);
|
|
SetCurrentStatementStartTimestamp();
|
StartTransactionCommand();
|
PushActiveSnapshot(GetTransactionSnapshot());
|
syncWindows();
|
purgeExpiredLogs();
|
claimed = claimJob(&owner, &jobName, &jobAction);
|
PopActiveSnapshot();
|
CommitTransactionCommand();
|
if (!claimed)
|
proc_exit(0);
|
|
logEventf("координатор взял задание",
|
"[Status: RUNNING, Job: %s]", jobName);
|
SetCurrentStatementStartTimestamp();
|
StartTransactionCommand();
|
PushActiveSnapshot(GetTransactionSnapshot());
|
runClaimed(owner, jobName, jobAction);
|
PopActiveSnapshot();
|
CommitTransactionCommand();
|
if (owner != NULL)
|
pfree(owner);
|
if (jobName != NULL)
|
pfree(jobName);
|
if (jobAction != NULL)
|
pfree(jobAction);
|
proc_exit(0);
|
}
|
|
static const uint32 FAIL_FILE_MAGIC = 0x46534352;
|
static const int FAIL_NAME_MAX = NAMEDATALEN;
|
static const int FAIL_ERR_MAX = 200;
|
|
struct FailHdr
|
{
|
uint32 magic;
|
Oid databaseId;
|
int32 sessionPid;
|
int32 ownerLen;
|
int32 jobLen;
|
int32 errLen;
|
};
|
|
static bool
|
writeAll(int fd, const void *buf, size_t len)
|
{
|
const char *ptr = (const char *) buf;
|
size_t left = len;
|
|
while (left > 0) {
|
ssize_t wrote = write(fd, ptr, left);
|
|
if (wrote < 0) {
|
if (errno == EINTR)
|
continue;
|
return false;
|
}
|
if (wrote == 0)
|
return false;
|
ptr += wrote;
|
left -= (size_t) wrote;
|
}
|
return true;
|
}
|
|
static bool
|
readAll(int fd, void *buf, size_t len)
|
{
|
char *ptr = (char *) buf;
|
size_t left = len;
|
|
while (left > 0) {
|
ssize_t got = read(fd, ptr, left);
|
|
if (got < 0) {
|
if (errno == EINTR)
|
continue;
|
return false;
|
}
|
if (got == 0)
|
return false;
|
ptr += got;
|
left -= (size_t) got;
|
}
|
return true;
|
}
|
|
static bool
|
failPathOk(const char *path)
|
{
|
char prefix[MAXPGPATH];
|
size_t prefixLen;
|
|
if (DataDir == NULL || path == NULL || path[0] == '\0')
|
return false;
|
snprintf(prefix, sizeof(prefix), "%s/log/dbms_scheduler_fail_", DataDir);
|
prefixLen = strlen(prefix);
|
if (strncmp(path, prefix, prefixLen) != 0)
|
return false;
|
if (strchr(path + prefixLen, '/') != NULL)
|
return false;
|
return true;
|
}
|
|
static int
|
openFailFile(char *path, int pathSize)
|
{
|
static uint32 seq = 1;
|
char dir[MAXPGPATH];
|
int fd;
|
|
if (DataDir == NULL || DataDir[0] == '\0')
|
return -1;
|
snprintf(dir, sizeof(dir), "%s/log", DataDir);
|
snprintf(path, pathSize, "%s/dbms_scheduler_fail_%d_%u",
|
dir, MyProcPid, seq++);
|
if ((int) strlen(path) >= BGW_EXTRALEN)
|
return -1;
|
fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
|
if (fd < 0 && errno == ENOENT) {
|
if (MakePGDirectory(dir) == 0)
|
fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
|
}
|
return fd;
|
}
|
|
void
|
Coordinator::failLogMain(Datum arg)
|
{
|
char path[BGW_EXTRALEN];
|
FailHdr hdr;
|
char owner[FAIL_NAME_MAX];
|
char jobName[FAIL_NAME_MAX];
|
char errorText[FAIL_ERR_MAX];
|
MemoryContext oldContext;
|
volatile bool spiOpen = false;
|
volatile bool stacked = false;
|
volatile bool ok = false;
|
int fd;
|
|
(void) arg;
|
memset(path, 0, sizeof(path));
|
if (MyBgworkerEntry != NULL)
|
memcpy(path, MyBgworkerEntry->bgw_extra, BGW_EXTRALEN - 1);
|
pqsignal(SIGTERM, die);
|
pqsignal(SIGINT, StatementCancelHandler);
|
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
|
pqsignal(SIGHUP, SignalHandlerForConfigReload);
|
BackgroundWorkerUnblockSignals();
|
if (!failPathOk(path))
|
proc_exit(1);
|
fd = open(path, O_RDONLY);
|
if (fd < 0)
|
proc_exit(1);
|
memset(&hdr, 0, sizeof(hdr));
|
memset(owner, 0, sizeof(owner));
|
memset(jobName, 0, sizeof(jobName));
|
memset(errorText, 0, sizeof(errorText));
|
if (!readAll(fd, &hdr, sizeof(hdr))
|
|| hdr.magic != FAIL_FILE_MAGIC
|
|| hdr.ownerLen <= 0 || hdr.ownerLen >= FAIL_NAME_MAX
|
|| hdr.jobLen <= 0 || hdr.jobLen >= FAIL_NAME_MAX
|
|| hdr.errLen < 0 || hdr.errLen >= FAIL_ERR_MAX
|
|| !readAll(fd, owner, (size_t) hdr.ownerLen)
|
|| !readAll(fd, jobName, (size_t) hdr.jobLen)
|
|| (hdr.errLen > 0 && !readAll(fd, errorText, (size_t) hdr.errLen))) {
|
close(fd);
|
proc_exit(1);
|
}
|
close(fd);
|
owner[hdr.ownerLen] = '\0';
|
jobName[hdr.jobLen] = '\0';
|
if (hdr.errLen > 0)
|
errorText[hdr.errLen] = '\0';
|
|
BackgroundWorkerInitializeConnectionByOid(hdr.databaseId, InvalidOid, 0);
|
oldContext = CurrentMemoryContext;
|
PG_TRY();
|
{
|
Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, INT4OID};
|
Datum values[4];
|
char nulls[4] = {' ', ' ', 'n', ' '};
|
int rc;
|
|
SetCurrentStatementStartTimestamp();
|
StartTransactionCommand();
|
PushActiveSnapshot(GetTransactionSnapshot());
|
stacked = true;
|
if (SPI_connect() != SPI_OK_CONNECT)
|
ereport(ERROR,
|
(errmsg("dbms_scheduler: SPI не открылся"),
|
errdetail_internal("Output: [Status: FAIL]")));
|
spiOpen = true;
|
values[0] = CStringGetTextDatum(owner);
|
values[1] = CStringGetTextDatum(jobName);
|
values[2] = (Datum) 0;
|
values[3] = Int32GetDatum(hdr.sessionPid);
|
if (hdr.errLen > 0) {
|
values[2] = CStringGetTextDatum(errorText);
|
nulls[2] = ' ';
|
}
|
rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.dbms_scheduler_job_run "
|
"(owner, job_name, log_date, status, error, pid) "
|
"VALUES ($1, $2, clock_timestamp(), 'FAILED', $3, $4)",
|
4, argtypes, values, nulls, false, 0);
|
if (rc < 0)
|
ereport(ERROR,
|
(errmsg("dbms_scheduler: запись журнала не выполнена"),
|
errdetail_internal("Output: [Status: FAIL, Code: %d]", rc)));
|
SPI_finish();
|
spiOpen = false;
|
PopActiveSnapshot();
|
stacked = false;
|
CommitTransactionCommand();
|
ok = true;
|
}
|
PG_CATCH();
|
{
|
MemoryContextSwitchTo(oldContext);
|
FlushErrorState();
|
if (spiOpen)
|
SPI_finish();
|
if (stacked)
|
PopActiveSnapshot();
|
AbortCurrentTransaction();
|
ok = false;
|
}
|
PG_END_TRY();
|
if (ok)
|
unlink(path);
|
else
|
logEventf("строка журнала не записана",
|
"[Status: FAIL, Job: %s]", jobName);
|
proc_exit(ok ? 0 : 1);
|
}
|
|
bool
|
Coordinator::persistFailedRun(const char *owner, const char *jobName,
|
const char *errorText)
|
{
|
char path[MAXPGPATH];
|
FailHdr hdr;
|
BackgroundWorker worker;
|
BackgroundWorkerHandle *local = NULL;
|
BackgroundWorkerHandle *volatile saved = NULL;
|
volatile bool ok = false;
|
int fd;
|
int32 ownerLen;
|
int32 jobLen;
|
int32 errLen;
|
|
if (owner == NULL || jobName == NULL || owner[0] == '\0' || jobName[0] == '\0')
|
return false;
|
ownerLen = (int32) strlen(owner);
|
jobLen = (int32) strlen(jobName);
|
errLen = (errorText == NULL) ? 0 : (int32) strlen(errorText);
|
if (ownerLen <= 0 || ownerLen >= FAIL_NAME_MAX
|
|| jobLen <= 0 || jobLen >= FAIL_NAME_MAX)
|
return false;
|
if (errLen >= FAIL_ERR_MAX)
|
errLen = FAIL_ERR_MAX - 1;
|
fd = openFailFile(path, (int) sizeof(path));
|
if (fd < 0)
|
return false;
|
memset(&hdr, 0, sizeof(hdr));
|
hdr.magic = FAIL_FILE_MAGIC;
|
hdr.databaseId = MyDatabaseId;
|
hdr.sessionPid = MyProcPid;
|
hdr.ownerLen = ownerLen;
|
hdr.jobLen = jobLen;
|
hdr.errLen = errLen;
|
if (!writeAll(fd, &hdr, sizeof(hdr))
|
|| !writeAll(fd, owner, (size_t) ownerLen)
|
|| !writeAll(fd, jobName, (size_t) jobLen)
|
|| (errLen > 0 && !writeAll(fd, errorText, (size_t) errLen))) {
|
close(fd);
|
unlink(path);
|
return false;
|
}
|
if (close(fd) != 0) {
|
unlink(path);
|
return false;
|
}
|
|
memset(&worker, 0, sizeof(worker));
|
snprintf(worker.bgw_name, BGW_MAXLEN, "RUDB Scheduler log");
|
snprintf(worker.bgw_type, BGW_MAXLEN, "RUDB Scheduler log");
|
snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
|
snprintf(worker.bgw_function_name, BGW_MAXLEN, "rudb_scheduler_fail_log_main");
|
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
|
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
|
worker.bgw_restart_time = BGW_NEVER_RESTART;
|
worker.bgw_notify_pid = MyProcPid;
|
memcpy(worker.bgw_extra, path, strlen(path) + 1);
|
PG_TRY();
|
{
|
if (!RegisterDynamicBackgroundWorker(&worker, &local))
|
ok = false;
|
else {
|
saved = local;
|
(void) WaitForBackgroundWorkerShutdown(local);
|
ok = access(path, F_OK) != 0;
|
}
|
}
|
PG_CATCH();
|
{
|
FlushErrorState();
|
ok = false;
|
}
|
PG_END_TRY();
|
if (saved != NULL)
|
pfree(saved);
|
if (!ok)
|
unlink(path);
|
if (ok)
|
logEventf("строка журнала записана отдельно",
|
"[Status: FAILED, Job: %s]", jobName);
|
else
|
logEventf("строка журнала не записана",
|
"[Status: FAIL, Job: %s]", jobName);
|
return ok;
|
}
|
|
} // namespace DbmsScheduler
|
|
extern "C"
|
{
|
|
void
|
rudb_scheduler_coord_die(SIGNAL_ARGS)
|
{
|
DbmsScheduler::Coordinator::requestStop();
|
}
|
|
void
|
rudb_scheduler_request_shmem(void)
|
{
|
DbmsScheduler::Coordinator::requestShmem();
|
}
|
|
void
|
rudb_scheduler_startup_shmem(void)
|
{
|
DbmsScheduler::Coordinator::startupShmem();
|
}
|
|
void
|
rudb_scheduler_postmaster_init(void)
|
{
|
static bool defined = false;
|
|
if (!defined) {
|
DbmsScheduler::Coordinator::defineGucs();
|
defined = true;
|
}
|
DbmsScheduler::Coordinator::prevRequest_ = shmem_request_hook;
|
shmem_request_hook = rudb_scheduler_request_shmem;
|
DbmsScheduler::Coordinator::prevStartup_ = shmem_startup_hook;
|
shmem_startup_hook = rudb_scheduler_startup_shmem;
|
DbmsScheduler::Coordinator::registerWorker();
|
}
|
|
PGDLLEXPORT void
|
rudb_scheduler_worker_main(Datum main_arg)
|
{
|
(void) main_arg;
|
DbmsScheduler::Coordinator::workerMain();
|
}
|
|
PGDLLEXPORT void
|
rudb_scheduler_executor_main(Datum main_arg)
|
{
|
DbmsScheduler::Coordinator::executorMain(main_arg);
|
}
|
|
PGDLLEXPORT void
|
rudb_scheduler_fail_log_main(Datum main_arg)
|
{
|
DbmsScheduler::Coordinator::failLogMain(main_arg);
|
}
|
|
bool
|
rudb_scheduler_persist_failed_run(const char *owner, const char *job_name,
|
const char *error_text)
|
{
|
return DbmsScheduler::Coordinator::persistFailedRun(owner, job_name, error_text);
|
}
|
|
void
|
rudb_scheduler_wakeup(void)
|
{
|
DbmsScheduler::Coordinator::wakeup();
|
}
|
|
} // extern "C"
|