extern "C" { #include "postgres.h" #include "fmgr.h" #include "access/xact.h" #include "catalog/pg_type_d.h" #include "executor/spi.h" #include "miscadmin.h" #include "utils/acl.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/portal.h" #include "utils/resowner.h" #include "utils/snapmgr.h" #include "utils/timestamp.h" #include "dbms/dbms_scheduler.h" #include "utils/fmgrprotos.h" #include "lib/stringinfo.h" } #include #include #include #include #include #include #include #include #include #include extern char **environ; #include "dbms_scheduler_log.h" namespace DbmsScheduler { static const int NAME_MAX_BYTES = NAMEDATALEN - 1; static char * currentOwner() { return GetUserNameFromId(GetUserId(), false); } static void spiConnect() { if (SPI_connect() != SPI_OK_CONNECT) { ereport(ERROR, (errmsg("dbms_scheduler: SPI не открылся"), errdetail_internal("Output: [Status: FAIL]"))); } } static void requireName(const char *job_name) { if (job_name == NULL || job_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_NAME cannot be NULL"))); } if (strlen(job_name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job name is longer than %d bytes", NAME_MAX_BYTES))); } } static bool selectExists(const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls) { int rc; bool found; spiConnect(); rc = SPI_execute_with_args(sql, nargs, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } found = SPI_processed > 0; SPI_finish(); return found; } static int32 selectInt32(const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls) { int rc; int32 result = 0; bool isnull = false; spiConnect(); rc = SPI_execute_with_args(sql, nargs, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result = DatumGetInt32(value); } SPI_finish(); return result; } static void execWrite(const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls) { int rc; spiConnect(); rc = SPI_execute_with_args(sql, nargs, argtypes, values, nulls, false, 0); if (rc < 0) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запись каталога не выполнена"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } SPI_finish(); } static const int32 LOG_OFF = 32; static const int32 LOG_RUNS = 64; static const int32 LOG_FAILED_RUNS = 128; static const int32 LOG_FULL = 256; static int32 jobLoggingLevel(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); return selectInt32( "SELECT COALESCE((" " SELECT c.logging_level FROM pg_catalog.dbms_scheduler_job_class c " " WHERE lower(c.job_class_name) = lower(j.job_class)" "), 64) " "FROM pg_catalog.dbms_scheduler_job j " "WHERE j.owner = $1 AND j.job_name = $2", 2, argtypes, values, nulls); } static bool logThisRun(int32 level, const char *status) { if (level == LOG_OFF) return false; if (level == LOG_FAILED_RUNS) return status != NULL && strcmp(status, "FAILED") == 0; return true; } bool logRun(const char *owner, const char *job_name, const char *status) { int32 level; if (owner == NULL || job_name == NULL) return true; level = jobLoggingLevel(owner, job_name); if (level == 0) level = LOG_RUNS; return logThisRun(level, status); } static int32 classLoggingLevel(const char *job_class) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; int32 level; if (job_class == NULL || job_class[0] == '\0' || pg_strcasecmp(job_class, "DEFAULT_JOB_CLASS") == 0) return LOG_RUNS; values[0] = CStringGetTextDatum(job_class); level = selectInt32( "SELECT logging_level FROM pg_catalog.dbms_scheduler_job_class " "WHERE lower(job_class_name) = lower($1)", 1, argtypes, values, nulls); if (level == 0) return LOG_RUNS; return level; } static void noteFullOperation(const char *owner, const char *job_name, int32 level) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; if (owner == NULL || job_name == NULL) return; if (level != LOG_FULL) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_run " "(owner, job_name, log_date, status, pid) " "VALUES ($1, $2, clock_timestamp(), NULL, pg_backend_pid())", 2, argtypes, values, nulls); } static const char * resolveJobClass(const char *job_class) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; if (job_class == NULL || job_class[0] == '\0' || pg_strcasecmp(job_class, "DEFAULT_JOB_CLASS") == 0 || strcmp(job_class, "$SCHED_DEFAULT$") == 0) return "DEFAULT_JOB_CLASS"; values[0] = CStringGetTextDatum(job_class); if (!selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job_class " "WHERE lower(job_class_name) = lower($1)", 1, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job class \"%s\"", job_class))); } return job_class; } static bool jobExists(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); } static bool programExists(const char *owner, const char *program_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); } static bool scheduleExists(const char *owner, const char *schedule_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND schedule_name = $2 " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_event_schedule " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls); } static void requireJob(const char *owner, const char *job_name) { if (!jobExists(owner, job_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job \"%s\"", job_name))); } } static bool identStart(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; } static bool identChar(char c) { return identStart(c) || (c >= '0' && c <= '9'); } static bool procedureNameOk(const char *action) { const char *cursor; int parts = 0; if (action == NULL) return false; cursor = action; while (*cursor != '\0') { if (!identStart(*cursor)) return false; cursor++; while (identChar(*cursor)) cursor++; parts++; if (*cursor == '.') { if (parts >= 2) return false; cursor++; continue; } break; } return *cursor == '\0' && parts >= 1 && parts <= 2; } static char * upperCopy(const char *src) { char *out; char *cursor; if (src == NULL || src[0] == '\0') return NULL; out = pstrdup(src); for (cursor = out; *cursor != '\0'; cursor++) { if (*cursor >= 'a' && *cursor <= 'z') *cursor = (char) (*cursor - 'a' + 'A'); } return out; } static void requireArgumentCount(int32 number_of_arguments) { if (number_of_arguments < 0 || number_of_arguments > 255) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid number of arguments"))); } } static void requireArgumentPosition(int32 position, int32 declared) { if (position < 1 || position > 255 || position > declared) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid argument position"))); } } static bool metadataAttributeOk(const char *attr) { return attr != NULL && (strcmp(attr, "COMPLETION_CODE") == 0 || strcmp(attr, "JOB_SUBNAME") == 0 || strcmp(attr, "JOB_NAME") == 0 || strcmp(attr, "JOB_OWNER") == 0 || strcmp(attr, "JOB_START") == 0 || strcmp(attr, "WINDOW_START") == 0 || strcmp(attr, "WINDOW_END") == 0 || strcmp(attr, "EVENT_MESSAGE") == 0); } static bool wordAt(const char *text, const char *word, size_t n) { size_t i; for (i = 0; i < n; i++) { char c = text[i]; if (c >= 'a' && c <= 'z') c = (char) (c - 'a' + 'A'); if (c != word[i]) return false; } return true; } static char * unwrapPlsqlBlock(const char *action) { const char *start; const char *end; start = action; while (*start == ' ' || *start == '\t' || *start == '\n') start++; if (strlen(start) < 6 || !wordAt(start, "BEGIN", 5) || identChar(start[5])) return pstrdup(action); start += 5; while (*start == ' ' || *start == '\t' || *start == '\n') start++; end = start + strlen(start); while (end > start && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\n' || end[-1] == ';')) end--; if (end - start < 3 || !wordAt(end - 3, "END", 3)) return pstrdup(action); if (end - start > 3 && identChar(end[-4])) return pstrdup(action); end -= 3; while (end > start && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\n' || end[-1] == ';')) end--; return pnstrdup(start, (size_t) (end - start)); } char * jobActionSql(const char *job_type, const char *job_action, char **arg_values, int nargs) { StringInfoData buf; int i; if (job_action == NULL || job_action[0] == '\0') return pstrdup(""); if (job_type == NULL || strcmp(job_type, "STORED_PROCEDURE") != 0) { if (job_type == NULL || strcmp(job_type, "PLSQL_BLOCK") == 0) return unwrapPlsqlBlock(job_action); return pstrdup(job_action); } if (!procedureNameOk(job_action)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid procedure name"))); } initStringInfo(&buf); appendStringInfo(&buf, "CALL %s(", job_action); for (i = 0; i < nargs; i++) { char *quoted; if (i > 0) appendStringInfoChar(&buf, ','); if (arg_values == NULL || arg_values[i] == NULL) appendStringInfoString(&buf, "NULL"); else { quoted = quote_literal_cstr(arg_values[i]); appendStringInfoString(&buf, quoted); pfree(quoted); } } appendStringInfoChar(&buf, ')'); return buf.data; } char * storedProcedureSql(const char *job_action, const char *owner, const char *job_name, int32 nargs) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; char **argValues; bool *seen; int rc; int i; bool isnull; if (nargs <= 0) return jobActionSql("STORED_PROCEDURE", job_action, NULL, 0); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); rc = SPI_execute_with_args( "SELECT argument_position, argument_value " "FROM pg_catalog.dbms_scheduler_job_arg " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls, true, 0); if (rc != SPI_OK_SELECT) { ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } argValues = (char **) palloc0(sizeof(char *) * nargs); seen = (bool *) palloc0(sizeof(bool) * nargs); for (i = 0; i < (int) SPI_processed; i++) { Datum value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); int32 position; if (isnull) continue; position = DatumGetInt32(value); if (position < 1 || position > nargs) continue; value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull); if (!isnull) argValues[position - 1] = pstrdup(TextDatumGetCString(value)); seen[position - 1] = true; } for (i = 0; i < nargs; i++) { if (!seen[i]) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument value is not set"))); } } return jobActionSql("STORED_PROCEDURE", job_action, argValues, nargs); } static bool osJobType(const char *job_type) { return job_type != NULL && (strcmp(job_type, "EXECUTABLE") == 0 || strcmp(job_type, "EXTERNAL_SCRIPT") == 0); } static bool laterJobType(const char *job_type) { return strcmp(job_type, "CHAIN") == 0 || strcmp(job_type, "EXECUTABLE") == 0 || strcmp(job_type, "EXTERNAL_SCRIPT") == 0 || strcmp(job_type, "SQL_SCRIPT") == 0 || strcmp(job_type, "BACKUP_SCRIPT") == 0; } static void runAction(const char *action) { MemoryContext oldContext; ResourceOwner oldOwner; int rc; if (action == NULL || action[0] == '\0') return; oldContext = CurrentMemoryContext; oldOwner = CurrentResourceOwner; spiConnect(); BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldContext); PG_TRY(); { rc = SPI_execute(action, false, 0); if (rc < 0) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("dbms_scheduler: действие задания не выполнено"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; } PG_CATCH(); { MemoryContextSwitchTo(oldContext); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; SPI_finish(); PG_RE_THROW(); } PG_END_TRY(); SPI_finish(); } static char * loadAction(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; char *action; int rc; bool isnull; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT job_type, job_action, number_of_arguments " "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_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } char *jobType = NULL; char *sqlText = NULL; int32 nargs = 0; action = NULL; if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) jobType = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); if (!isnull) action = MemoryContextStrdup(caller, TextDatumGetCString(value)); else action = MemoryContextStrdup(caller, ""); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull); if (!isnull) nargs = DatumGetInt32(value); } if (action != NULL && jobType != NULL && strcmp(jobType, "STORED_PROCEDURE") == 0) sqlText = MemoryContextStrdup(caller, storedProcedureSql(action, owner, job_name, nargs)); else if (action != NULL) sqlText = MemoryContextStrdup(caller, jobActionSql(jobType, action, NULL, 0)); SPI_finish(); return sqlText; } class Catalog { public: static void createJob(const char *job_name, const char *job_type, const char *job_action, int32 number_of_arguments, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *program_name, const char *schedule_name, const char *job_style); static void createJobs(const char *const *job_name, const char *const *job_type, const char *const *job_action, const char *const *program_name, const char *const *repeat_interval, const int32 *nargs, const bool *nargs_null, const char *const *comments, const bool *auto_drop, const bool *auto_drop_null, const bool *enabled, const bool *enabled_null, const char *const *job_class, int n, const char *commit_semantics, MemoryContext batch_ctx); static void setJobAttributes(const char *const *job_name, const char *const *attr_name, const char *const *attr_value, int n, const char *commit_semantics, MemoryContext batch_ctx); static void dropJob(const char *job_name); static void createSchedule(const char *schedule_name, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *comments); static void createEventSchedule(const char *schedule_name, bool start_null, TimestampTz start_date, const char *event_condition, const char *queue_spec, bool end_null, TimestampTz end_date, const char *comments); static void addEventQueueSubscriber(const char *subscriber_name); static void removeEventQueueSubscriber(const char *subscriber_name); static void dropSchedule(const char *schedule_name, bool force); static void copyJob(const char *old_job, const char *new_job); static void createJobOnProgram(const char *job_name, const char *program_name, const char *schedule_name, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *job_style, const char *credential_name, const char *destination_name); static void createJobOnSchedule(const char *job_name, const char *schedule_name, const char *job_type, const char *job_action, int32 number_of_arguments, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *credential_name, const char *destination_name); static void createProgram(const char *program_name, const char *program_type, const char *program_action, int32 number_of_arguments, bool enabled, const char *comments); static void dropProgram(const char *program_name, bool force); static void defineProgramArgument(const char *program_name, int32 argument_position, const char *argument_name, const char *argument_type, const char *default_value, bool out_argument); static void defineMetadataArgument(const char *program_name, const char *metadata_attribute, int32 argument_position, const char *argument_name); static void dropProgramArgumentPos(const char *program_name, int32 argument_position); static void dropProgramArgumentName(const char *program_name, const char *argument_name); static void setJobArgumentValuePos(const char *job_name, int32 argument_position, const char *argument_value); static void setJobArgumentValueName(const char *job_name, const char *argument_name, const char *argument_value); static void resetJobArgumentValuePos(const char *job_name, int32 argument_position); static void resetJobArgumentValueName(const char *job_name, const char *argument_name); static void enable(const char *job_name); static void disable(const char *job_name); static void runJob(const char *job_name, bool use_current_session); static void stopJob(const char *job_name); static char *generateJobName(const char *prefix); static void setAttributeText(const char *job_name, const char *attribute, const char *value); static void setAttributeBool(const char *job_name, const char *attribute, bool value); static void setAttributeTimestamptz(const char *job_name, const char *attribute, TimestampTz value); static void setAttributeNull(const char *job_name, const char *attribute); static char *getAttribute(const char *job_name, const char *attribute); static void purgeLog(int32 log_history, const char *which_log, const char *job_name); static void createJobClass(const char *job_class_name, const char *resource_consumer_group, const char *service, bool level_null, int32 logging_level, bool history_null, int32 log_history, const char *comments); static void dropJobClass(const char *job_class_name, bool force); static void setSchedulerAttribute(const char *attribute, const char *value); static char *getSchedulerAttribute(const char *attribute); static void createWindowCalendar(const char *window_name, const char *resource_plan, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const Interval *duration, const char *window_priority, const char *comments, bool enabled); static void createWindowSchedule(const char *window_name, const char *resource_plan, const char *schedule_name, const Interval *duration, const char *window_priority, const char *comments, bool enabled); static void dropWindow(const char *window_name, bool force); static void openWindow(const char *window_name, const Interval *duration, bool force); static void closeWindow(const char *window_name); static void createChain(const char *chain_name, const char *rule_set_name, const Interval *evaluation_interval, const char *comments); static void dropChain(const char *chain_name, bool force); static void defineChainStep(const char *chain_name, const char *step_name, const char *program_name); static void createFileWatcher(const char *file_watcher_name, const char *directory_path, const char *file_name, const char *credential_name, const char *destination, int32 min_file_size, const Interval *steady_state_duration, const char *comments, bool enabled); static void dropFileWatcher(const char *file_watcher_name, bool force); static void defineChainEventStepSchedule(const char *chain_name, const char *step_name, const char *event_schedule_name, const Interval *timeout); static void defineChainEventStepInline(const char *chain_name, const char *step_name, const char *event_condition, const char *queue_spec, const Interval *timeout); static void addJobEmailNotification(const char *job_name, const char *recipients, const char *sender, const char *subject, const char *body, const char *events, const char *filter_condition); static void removeJobEmailNotification(const char *job_name, const char *recipients, const char *events); static void createGroup(const char *group_name, const char *group_type, const char *member, const char *comments); static void dropGroup(const char *group_name, bool force); static void addGroupMember(const char *group_name, const char *member); static void removeGroupMember(const char *group_name, const char *member); static void createIncompatibility(const char *incompatibility_name, const char *object_name, const char *constraint_level, bool enabled, const char *comments); static void dropIncompatibility(const char *incompatibility_name); static void addToIncompatibility(const char *incompatibility_name, const char *object_name); static void removeFromIncompatibility(const char *incompatibility_name, const char *object_name); static void createResource(const char *resource_name, bool units_null, int32 units, const char *status, const char *constraint_level, const char *comments); static void dropResource(const char *resource_name, bool force); static void setResourceConstraint(const char *object_name, const char *resource_name, bool units_null, int32 units); static void dropChainStep(const char *chain_name, const char *step_name, bool force); static void defineChainRule(const char *chain_name, const char *condition, const char *action, const char *rule_name, const char *comments); static void dropChainRule(const char *chain_name, const char *rule_name, bool force); static void createCredential(const char *credential_name, const char *username, const char *password, const char *database_role, const char *windows_domain, const char *comments); static void dropCredential(const char *credential_name, bool force); static void runChain(const char *chain_name, const char *start_steps, const char *job_name); static void alterChain(const char *chain_name, const char *step_name, const char *attribute, bool value); static void alterChainText(const char *chain_name, const char *step_name, const char *attribute, const char *char_value); static void alterRunningChain(const char *job_name, const char *step_name, const char *attribute, bool value); static void alterRunningChainText(const char *job_name, const char *step_name, const char *attribute, const char *char_value); static void evaluateRunningChain(const char *job_name); static void endDetachedJobRun(const char *job_name, int32 error_number, const char *additional_info); static bool executeChain(const char *owner, const char *job_name, const char *chain_name); static void createDatabaseDestination(const char *destination_name, const char *agent, const char *tns_name, const char *comments); static void dropDatabaseDestination(const char *destination_name); static void dropAgentDestination(const char *destination_name); static char *getAgentInfo(const char *agent_name, const char *attribute); static char *getAgentVersion(const char *agent_host); static void setAgentRegistrationPass(const char *registration_password, bool expiration_null, TimestampTz expiration_date, bool max_uses_null, int32 max_uses); static void getFileContents(bool contents_null); static void getFileDirectory(const char *source_file, const char *source_host, const char *credential_name, const char *destination_file_name, const char *destination_directory_object); static void putFileContents(const char *credential_name); static void putFileDirectory(const char *credential_name, const char *source_file_name, const char *source_directory_object); }; static bool repeatText(const char *repeat_interval) { return repeat_interval != NULL && repeat_interval[0] != '\0'; } static bool nextRepeatRun(const char *repeat_interval, bool start_null, TimestampTz start_date, bool end_null, TimestampTz end_date, TimestampTz *next_out) { TimestampTz anchor; TimestampTz after; TimestampTz now; TimestampTz candidate; if (!repeatText(repeat_interval) || next_out == NULL) return false; now = GetCurrentTimestamp(); anchor = start_null ? now : start_date; after = anchor - 1; if (after < now) after = now; if (!rudb_scheduler_calendar_next(repeat_interval, anchor, after, &candidate)) return false; if (!end_null && candidate > end_date) return false; *next_out = candidate; return true; } static bool styleIsRegular(const char *style); void Catalog::createJob(const char *job_name, const char *job_type, const char *job_action, int32 number_of_arguments, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *program_name, const char *schedule_name, const char *job_style) { const char *owner; const char *storedClass; const char *storedAction; const char *storedStyle; const char *state; bool regularStyle; Oid argtypes[18]; Datum values[18]; char nulls[18]; int i; requireName(job_name); logEventf("вход создания задания", "[Job: %s, Type: %s, Enabled: %s]", job_name, (job_type == NULL || job_type[0] == '\0') ? "-" : job_type, enabled ? "true" : "false"); if (job_type == NULL || job_type[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid program type"))); } { char *typeUpper = upperCopy(job_type); if (typeUpper != NULL && laterJobType(typeUpper)) job_type = typeUpper; } if (strcmp(job_type, "STORED_PROCEDURE") == 0) { requireArgumentCount(number_of_arguments); if (!procedureNameOk(job_action)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid procedure name"))); } } else if (strcmp(job_type, "CHAIN") == 0) { if (number_of_arguments != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid number of arguments"))); } if (job_action == NULL || job_action[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job action cannot be NULL"))); } } else if (!osJobType(job_type) && laterJobType(job_type)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_create_job does not support job_type %s", job_type))); } else if (!osJobType(job_type) && strcmp(job_type, "PLSQL_BLOCK") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid program type %s", job_type))); } else if (!osJobType(job_type) && number_of_arguments != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("A program of type PLSQL_BLOCK cannot have any arguments."))); } if (enabled && !start_null && !end_null && end_date < start_date) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("end_date is earlier than start_date"))); } if (repeat_interval != NULL && repeat_interval[0] != '\0' && !enabled) { TimestampTz ignored; TimestampTz anchor = start_null ? GetCurrentTimestamp() : start_date; (void) rudb_scheduler_calendar_next(repeat_interval, anchor, anchor - 1, &ignored); } owner = currentOwner(); if (jobExists(owner, job_name) || programExists(owner, job_name) || scheduleExists(owner, job_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("job \"%s\" already exists", job_name))); } { Oid nameTypes[2] = {TEXTOID, TEXTOID}; Datum nameValues[2]; char nameNulls[2] = {' ', ' '}; nameValues[0] = CStringGetTextDatum(owner); nameValues[1] = CStringGetTextDatum(job_name); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_resource " "WHERE owner = $1 AND lower(resource_name) = lower($2)", 2, nameTypes, nameValues, nameNulls)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("job \"%s\" already exists", job_name))); } } storedClass = resolveJobClass(job_class); storedAction = job_action == NULL ? "" : job_action; state = enabled ? "SCHEDULED" : "DISABLED"; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = TEXTOID; argtypes[3] = TEXTOID; argtypes[4] = INT4OID; argtypes[5] = TIMESTAMPTZOID; argtypes[6] = TIMESTAMPTZOID; argtypes[7] = TEXTOID; argtypes[8] = BOOLOID; argtypes[9] = BOOLOID; argtypes[10] = TEXTOID; argtypes[11] = TEXTOID; argtypes[12] = TIMESTAMPTZOID; argtypes[13] = TEXTOID; argtypes[14] = TEXTOID; argtypes[15] = TEXTOID; argtypes[16] = TEXTOID; argtypes[17] = INT4OID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = CStringGetTextDatum(job_type); values[3] = CStringGetTextDatum(storedAction); values[4] = Int32GetDatum(number_of_arguments); values[5] = TimestampTzGetDatum(start_date); values[6] = TimestampTzGetDatum(end_date); values[7] = CStringGetTextDatum(storedClass); values[8] = BoolGetDatum(enabled); values[9] = BoolGetDatum(auto_drop); values[10] = comments == NULL ? (Datum) 0 : CStringGetTextDatum(comments); values[11] = CStringGetTextDatum(state); values[12] = TimestampTzGetDatum(0); values[13] = (repeat_interval == NULL || repeat_interval[0] == '\0') ? (Datum) 0 : CStringGetTextDatum(repeat_interval); values[14] = (program_name == NULL || program_name[0] == '\0') ? (Datum) 0 : CStringGetTextDatum(program_name); values[15] = (schedule_name == NULL || schedule_name[0] == '\0') ? (Datum) 0 : CStringGetTextDatum(schedule_name); storedStyle = (job_style == NULL || job_style[0] == '\0') ? "REGULAR" : job_style; regularStyle = styleIsRegular(storedStyle); values[16] = CStringGetTextDatum(storedStyle); values[17] = Int32GetDatum(3); for (i = 0; i < 18; i++) nulls[i] = ' '; if (start_null) nulls[5] = 'n'; if (end_null) nulls[6] = 'n'; if (comments == NULL) nulls[10] = 'n'; if (repeat_interval == NULL || repeat_interval[0] == '\0') nulls[13] = 'n'; if (program_name == NULL || program_name[0] == '\0') nulls[14] = 'n'; if (schedule_name == NULL || schedule_name[0] == '\0') nulls[15] = 'n'; if (!regularStyle) nulls[17] = 'n'; if (osJobType(job_type) && (job_action == NULL || job_action[0] == '\0')) nulls[3] = 'n'; nulls[12] = 'n'; if (enabled) { if (repeat_interval != NULL && repeat_interval[0] != '\0') { TimestampTz nextRun; if (nextRepeatRun(repeat_interval, start_null, start_date, end_null, end_date, &nextRun)) { nulls[12] = ' '; values[12] = TimestampTzGetDatum(nextRun); } } else { TimestampTz now = GetCurrentTimestamp(); bool schedule = true; if (!start_null && !end_null && start_date >= end_date) schedule = false; else if (!end_null && now >= end_date) schedule = false; if (schedule) { nulls[12] = ' '; values[12] = TimestampTzGetDatum(!start_null && start_date > now ? start_date : now); } } } execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job " "(owner, job_name, job_type, job_action, number_of_arguments, " " start_date, end_date, job_class, enabled, auto_drop, comments, state, " " next_run_date, repeat_interval, program_name, schedule_name, " " job_style, job_priority) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)", 18, argtypes, values, nulls); noteFullOperation(owner, job_name, classLoggingLevel(storedClass)); if (enabled) rudb_scheduler_wakeup(); logEventf("задание записано в каталог", "[Status: OK, Job: %s, State: %s]", job_name, state); } void Catalog::dropJob(const char *job_name) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(job_name); logEventf("вход удаления задания", "[Job: %s]", job_name); owner = currentOwner(); requireJob(owner, job_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); noteFullOperation(owner, job_name, jobLoggingLevel(owner, job_name)); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_arg " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_incompat_member " "WHERE object_owner = $1 AND lower(object_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_resource_constraint " "WHERE object_owner = $1 AND lower(object_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); logEventf("задание удалено из каталога", "[Status: OK, Job: %s]", job_name); } static void rejectProgramType(const char *program_type, const char *program_action, int32 number_of_arguments) { if (program_type == NULL || program_type[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid program type"))); } if (strcmp(program_type, "STORED_PROCEDURE") == 0) { requireArgumentCount(number_of_arguments); if (!procedureNameOk(program_action)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid procedure name"))); } return; } if (laterJobType(program_type)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_create_program does not support program_type %s", program_type))); } if (strcmp(program_type, "PLSQL_BLOCK") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid program type %s", program_type))); } if (number_of_arguments != 0) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_define_program_argument is not supported"))); } } static void setProgramEnabled(const char *owner, const char *program_name, bool enabled) { Oid argtypes[3] = {TEXTOID, TEXTOID, BOOLOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (!programExists(owner, program_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job \"%s\"", program_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); if (enabled) { int32 declared; int32 defined; Oid countTypes[3] = {TEXTOID, TEXTOID, INT4OID}; Datum countValues[3]; char countNulls[3] = {' ', ' ', ' '}; declared = selectInt32( "SELECT number_of_arguments FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); if (declared != 0) { countValues[0] = CStringGetTextDatum(owner); countValues[1] = CStringGetTextDatum(program_name); countValues[2] = Int32GetDatum(declared); defined = selectInt32( "SELECT COUNT(*)::integer FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 " " AND argument_position BETWEEN 1 AND $3", 3, countTypes, countValues, countNulls); if (defined != declared) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("program arguments are not complete"))); } } } values[2] = BoolGetDatum(enabled); execWrite( "UPDATE pg_catalog.dbms_scheduler_program SET enabled = $3 " "WHERE owner = $1 AND program_name = $2", 3, argtypes, values, nulls); logEventf(enabled ? "программа включена" : "программа выключена", "[Status: OK, Program: %s, Enabled: %s]", program_name, enabled ? "true" : "false"); } void Catalog::createProgram(const char *program_name, const char *program_type, const char *program_action, int32 number_of_arguments, bool enabled, const char *comments) { const char *owner; const char *storedAction; Oid argtypes[7]; Datum values[7]; char nulls[7]; int i; requireName(program_name); logEventf("вход создания программы", "[Program: %s, Type: %s, Enabled: %s]", program_name, (program_type == NULL || program_type[0] == '\0') ? "-" : program_type, enabled ? "true" : "false"); rejectProgramType(program_type, program_action, number_of_arguments); if (enabled && number_of_arguments != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("program arguments are not complete"))); } owner = currentOwner(); if (programExists(owner, program_name) || jobExists(owner, program_name) || scheduleExists(owner, program_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("program \"%s\" already exists", program_name))); } storedAction = program_action == NULL ? "" : program_action; for (i = 0; i < 7; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = TEXTOID; argtypes[3] = TEXTOID; argtypes[4] = INT4OID; argtypes[5] = BOOLOID; argtypes[6] = TEXTOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = CStringGetTextDatum(program_type); values[3] = CStringGetTextDatum(storedAction); values[4] = Int32GetDatum(number_of_arguments); values[5] = BoolGetDatum(enabled); values[6] = CStringGetTextDatum(comments == NULL ? "" : comments); if (comments == NULL) nulls[6] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_scheduler_program " "(owner, program_name, program_type, program_action, " " number_of_arguments, enabled, comments) " "VALUES ($1,$2,$3,$4,$5,$6,$7)", 7, argtypes, values, nulls); logEventf("программа записана в каталог", "[Status: OK, Program: %s]", program_name); } void Catalog::dropProgram(const char *program_name, bool force) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(program_name); logEventf("вход удаления программы", "[Program: %s, Force: %s]", program_name, force ? "true" : "false"); owner = currentOwner(); if (!programExists(owner, program_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown program \"%s\"", program_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); { int32 refs = selectInt32( "SELECT COUNT(*)::integer FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); if (refs > 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("program \"%s\" is in use", program_name))); } if (refs > 0) { execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = false, state = 'DISABLED', next_run_date = NULL " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); } } execWrite( "DELETE FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_incompat_member " "WHERE object_owner = $1 AND lower(object_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_resource_constraint " "WHERE object_owner = $1 AND lower(object_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); logEventf("программа удалена из каталога", "[Status: OK, Program: %s]", program_name); } static const char * canonicalJobStyle(const char *job_style) { char *upper; if (job_style == NULL || job_style[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_STYLE cannot be NULL"))); } upper = upperCopy(job_style); if (upper != NULL && (strcmp(upper, "REGULAR") == 0 || strcmp(upper, "LIGHTWEIGHT") == 0 || strcmp(upper, "IN_MEMORY_RUNTIME") == 0 || strcmp(upper, "IN_MEMORY_FULL") == 0)) return upper; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for attribute JOB_STYLE", upper == NULL ? "" : upper))); } static bool styleIsRegular(const char *style) { return style == NULL || strcmp(style, "REGULAR") == 0; } static bool styleIsFull(const char *style) { return style != NULL && strcmp(style, "IN_MEMORY_FULL") == 0; } static bool styleIsInMemory(const char *style) { return style != NULL && strncmp(style, "IN_MEMORY_", 10) == 0; } static char * loadJobStyle(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller = CurrentMemoryContext; int rc; bool isnull; char *style = NULL; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); spiConnect(); rc = SPI_execute_with_args( "SELECT job_style 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_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job \"%s\"", job_name))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) style = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); if (style == NULL) style = pstrdup("REGULAR"); return style; } static bool programIsEnabled(const char *owner, const char *program_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int rc; bool isnull; bool enabled = false; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); spiConnect(); rc = SPI_execute_with_args( "SELECT enabled FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT || SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) enabled = DatumGetBool(value); } SPI_finish(); return enabled; } static bool styleAttrBlocked(const char *style, const char *key) { if (styleIsRegular(style)) return false; if (strcmp(key, "repeat_interval") == 0) return styleIsFull(style); return strcmp(key, "job_priority") == 0 || strcmp(key, "comments") == 0 || strcmp(key, "max_runs") == 0 || strcmp(key, "max_failures") == 0 || strcmp(key, "job_action") == 0 || strcmp(key, "auto_drop") == 0; } static void rejectStyleAttr(const char *owner, const char *job_name, const char *key) { char *style = loadJobStyle(owner, job_name); if (!styleAttrBlocked(style, key)) return; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("attribute %s cannot be set for job_style %s", key, style))); } static void rejectInMemoryRun(const char *owner, const char *job_name, bool background) { char *style = loadJobStyle(owner, job_name); if (!styleIsInMemory(style)) return; if (background && styleIsFull(style)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on lightweight and in-memory jobs"))); } ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("insufficient privileges"))); } static void rejectCredential(const char *credential_name, const char *destination_name) { if ((credential_name != NULL && credential_name[0] != '\0') || (destination_name != NULL && destination_name[0] != '\0')) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_create_job does not support credential_name"))); } } static void readProgram(const char *owner, const char *program_name, char **type_out, char **action_out, int32 *nargs_out) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; int rc; bool isnull; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT program_type, program_action, number_of_arguments " "FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown program \"%s\"", program_name))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); *type_out = isnull ? pstrdup("") : MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); *action_out = isnull ? pstrdup("") : MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull); *nargs_out = isnull ? 0 : DatumGetInt32(value); } SPI_finish(); } static bool windowOrGroupScheduleExists(const char *schedule_name) { const char *bare = schedule_name; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; if (schedule_name == NULL || schedule_name[0] == '\0') return false; if (pg_strncasecmp(schedule_name, "SYS.", 4) == 0) bare = schedule_name + 4; if (bare[0] == '\0') return false; values[0] = CStringGetTextDatum(bare); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_window " "WHERE lower(window_name) = lower($1)", 1, argtypes, values, nulls)) return true; if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_group " "WHERE owner = 'SYS' AND group_type = 'WINDOW' " " AND lower(group_name) = lower($1)", 1, argtypes, values, nulls)) return true; return false; } static void readSchedule(const char *owner, const char *schedule_name, char **repeat_out, bool *start_null, TimestampTz *start_out, bool *end_null, TimestampTz *end_out) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; int rc; bool isnull; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT repeat_interval, start_date, end_date " "FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); if (windowOrGroupScheduleExists(schedule_name)) { *repeat_out = NULL; *start_null = true; *end_null = true; return; } ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown schedule \"%s\"", schedule_name))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); *repeat_out = isnull ? NULL : MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); *start_null = isnull; if (!isnull) *start_out = DatumGetTimestampTz(value); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull); *end_null = isnull; if (!isnull) *end_out = DatumGetTimestampTz(value); } SPI_finish(); } void Catalog::createSchedule(const char *schedule_name, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *comments) { const char *owner; Oid argtypes[6]; Datum values[6]; char nulls[6]; int i; TimestampTz ignored; TimestampTz anchor; requireName(schedule_name); logEventf("вход создания расписания", "[Schedule: %s]", schedule_name); if (repeat_interval == NULL || repeat_interval[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("repeat interval cannot be NULL"))); } anchor = start_null ? GetCurrentTimestamp() : start_date; (void) rudb_scheduler_calendar_next(repeat_interval, anchor, anchor - 1, &ignored); owner = currentOwner(); if (scheduleExists(owner, schedule_name) || jobExists(owner, schedule_name) || programExists(owner, schedule_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("schedule \"%s\" already exists", schedule_name))); } for (i = 0; i < 6; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = TIMESTAMPTZOID; argtypes[3] = TEXTOID; argtypes[4] = TIMESTAMPTZOID; argtypes[5] = TEXTOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); values[2] = TimestampTzGetDatum(start_date); values[3] = CStringGetTextDatum(repeat_interval); values[4] = TimestampTzGetDatum(end_date); values[5] = comments == NULL ? (Datum) 0 : CStringGetTextDatum(comments); if (start_null) nulls[2] = 'n'; if (end_null) nulls[4] = 'n'; if (comments == NULL) nulls[5] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_scheduler_schedule " "(owner, schedule_name, start_date, repeat_interval, end_date, comments) " "VALUES ($1,$2,$3,$4,$5,$6)", 6, argtypes, values, nulls); logEventf("расписание записано в каталог", "[Status: OK, Schedule: %s]", schedule_name); } void Catalog::dropSchedule(const char *schedule_name, bool force) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int32 refs; requireName(schedule_name); logEventf("вход удаления расписания", "[Schedule: %s, Force: %s]", schedule_name, force ? "true" : "false"); owner = currentOwner(); if (!scheduleExists(owner, schedule_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown schedule \"%s\"", schedule_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); refs = selectInt32( "SELECT COUNT(*)::integer FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls); if (refs > 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("schedule \"%s\" is in use", schedule_name))); } if (refs > 0) { execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = false, state = 'DISABLED', next_run_date = NULL " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls); } refs = selectInt32( "SELECT COUNT(*)::integer FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(event_schedule_name) = lower($2)", 2, argtypes, values, nulls); if (refs > 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("schedule \"%s\" is in use", schedule_name))); } execWrite( "DELETE FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_event_schedule " "WHERE owner = $1 AND schedule_name = $2", 2, argtypes, values, nulls); logEventf("расписание удалено из каталога", "[Status: OK, Schedule: %s]", schedule_name); } static char * trimCopy(const char *src) { const char *start; const char *end; size_t len; char *out; if (src == NULL) return NULL; start = src; while (*start == ' ' || *start == '\t') start++; end = start + strlen(start); while (end > start && (end[-1] == ' ' || end[-1] == '\t')) end--; len = (size_t) (end - start); out = (char *) palloc(len + 1); memcpy(out, start, len); out[len] = '\0'; return out; } static void rejectEmptyQueue(void) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("queue_spec cannot be NULL"))); } static void splitQueueSpec(const char *queue_spec, const char *owner, char **schema_out, char **queue_out) { char *trimmed; char *comma; char *queuePart; char *dot; if (queue_spec == NULL || queue_spec[0] == '\0') rejectEmptyQueue(); trimmed = trimCopy(queue_spec); if (trimmed[0] == '\0') rejectEmptyQueue(); comma = strchr(trimmed, ','); if (comma != NULL) *comma = '\0'; queuePart = trimCopy(trimmed); if (queuePart[0] == '\0') rejectEmptyQueue(); dot = strchr(queuePart, '.'); if (dot != NULL) { *dot = '\0'; *schema_out = trimCopy(queuePart); *queue_out = trimCopy(dot + 1); if ((*schema_out)[0] == '\0' || (*queue_out)[0] == '\0') rejectEmptyQueue(); } else { *schema_out = pstrdup(owner); *queue_out = queuePart; } } static bool lookupEventQueue(const char *schema, const char *queue, char **owner_out, char **name_out, bool *multi_out) { MemoryContext caller = CurrentMemoryContext; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int rc; values[0] = CStringGetTextDatum(schema); values[1] = CStringGetTextDatum(queue); spiConnect(); rc = SPI_execute_with_args( "SELECT q.\"OWNER\", q.\"QUEUE_NAME\", " "COALESCE(t.\"MULTI_CONSUMER\", false) " "FROM \"SYS\".\"AQ$QUEUES\" q " "JOIN \"SYS\".\"AQ$QUEUE_TABLES\" t " " ON lower(t.\"OWNER\") = lower(q.\"OWNER\") " " AND lower(t.\"QUEUE_TABLE\") = lower(q.\"QUEUE_TABLE\") " "WHERE lower(q.\"OWNER\") = lower($1) " " AND lower(q.\"QUEUE_NAME\") = lower($2)", 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); return false; } { bool ownerNull = false; bool nameNull = false; bool multiNull = false; Datum ownerValue; Datum nameValue; Datum multiValue; MemoryContext spiCtx; ownerValue = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &ownerNull); nameValue = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &nameNull); multiValue = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &multiNull); /* * SPI_connect переключил контекст на свой. SPI_finish его удаляет. * Копия должна пережить finish, иначе queue_name читается как 0x7F. */ spiCtx = MemoryContextSwitchTo(caller); *owner_out = ownerNull ? pstrdup(schema) : pstrdup(TextDatumGetCString(ownerValue)); *name_out = nameNull ? pstrdup(queue) : pstrdup(TextDatumGetCString(nameValue)); *multi_out = !multiNull && DatumGetBool(multiValue); MemoryContextSwitchTo(spiCtx); } SPI_finish(); return true; } static bool eventSubscriberExists(const char *subscriber_name) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(subscriber_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_event_subscriber " "WHERE lower(subscriber_name) = lower($1)", 1, argtypes, values, nulls); } void Catalog::createEventSchedule(const char *schedule_name, bool start_null, TimestampTz start_date, const char *event_condition, const char *queue_spec, bool end_null, TimestampTz end_date, const char *comments) { const char *owner; char *schema = NULL; char *queue = NULL; char *storedOwner = NULL; char *storedQueue = NULL; const char *storedCond; bool multi = false; Oid argtypes[9]; Datum values[9]; char nulls[9]; int i; requireName(schedule_name); owner = currentOwner(); splitQueueSpec(queue_spec, owner, &schema, &queue); logEventf("вход создания расписания события", "[Schedule: %s, Queue: %s.%s]", schedule_name, schema, queue); if (!lookupEventQueue(schema, queue, &storedOwner, &storedQueue, &multi)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown or illegal event source queue"))); } if (!multi) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown or illegal event source queue"))); } if (!start_null && !end_null && end_date < start_date) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid END_DATE"))); } if (scheduleExists(owner, schedule_name) || jobExists(owner, schedule_name) || programExists(owner, schedule_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("schedule \"%s\" already exists", schedule_name))); } if (event_condition == NULL || event_condition[0] == '\0') storedCond = "(1=1)"; else storedCond = event_condition; for (i = 0; i < 9; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = TIMESTAMPTZOID; argtypes[3] = TEXTOID; argtypes[4] = TEXTOID; argtypes[5] = TEXTOID; argtypes[6] = TEXTOID; argtypes[7] = TIMESTAMPTZOID; argtypes[8] = TEXTOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); values[2] = TimestampTzGetDatum(start_date); values[3] = CStringGetTextDatum(storedCond); values[4] = CStringGetTextDatum(storedOwner); values[5] = CStringGetTextDatum(storedQueue); values[6] = (Datum) 0; values[7] = TimestampTzGetDatum(end_date); values[8] = comments == NULL ? (Datum) 0 : CStringGetTextDatum(comments); nulls[6] = 'n'; if (start_null) nulls[2] = 'n'; if (end_null) nulls[7] = 'n'; if (comments == NULL) nulls[8] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_scheduler_event_schedule " "(owner, schedule_name, start_date, event_condition, queue_owner, " "queue_name, queue_agent, end_date, comments) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", 9, argtypes, values, nulls); logEventf("расписание события записано в каталог", "[Status: OK, Schedule: %s, Queue: %s]", schedule_name, storedQueue); } void Catalog::addEventQueueSubscriber(const char *subscriber_name) { const char *owner; char *stored; char *rule; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; owner = currentOwner(); if (subscriber_name == NULL) stored = pstrdup(owner); else { requireName(subscriber_name); stored = upperCopy(subscriber_name); } logEventf("вход подписки на очередь событий", "[Subscriber: %s]", stored); if (eventSubscriberExists(stored)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("subscriber \"%s\" already exists", stored))); } rule = psprintf("tab.user_data.object_owner = '%s'", owner); values[0] = CStringGetTextDatum(stored); values[1] = CStringGetTextDatum(rule); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_event_subscriber " "(subscriber_name, rule) VALUES ($1,$2)", 2, argtypes, values, nulls); logEventf("подписчик очереди событий записан", "[Status: OK, Subscriber: %s]", stored); } void Catalog::removeEventQueueSubscriber(const char *subscriber_name) { const char *owner; char *stored; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; owner = currentOwner(); if (subscriber_name == NULL) stored = pstrdup(owner); else { requireName(subscriber_name); stored = upperCopy(subscriber_name); } logEventf("вход снятия подписки очереди событий", "[Subscriber: %s]", stored); values[0] = CStringGetTextDatum(stored); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_event_subscriber " "WHERE lower(subscriber_name) = lower($1)", 1, argtypes, values, nulls); logEventf("подписка очереди событий снята", "[Status: OK, Subscriber: %s]", stored); } void Catalog::copyJob(const char *old_job, const char *new_job) { const char *owner; Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(old_job); requireName(new_job); logEventf("вход копирования задания", "[Job: %s]", old_job); owner = currentOwner(); requireJob(owner, old_job); if (jobExists(owner, new_job) || programExists(owner, new_job) || scheduleExists(owner, new_job)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("job \"%s\" already exists", new_job))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(old_job); values[2] = CStringGetTextDatum(new_job); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job " "(owner, job_name, job_type, job_action, number_of_arguments, start_date, " " repeat_interval, end_date, job_class, enabled, auto_drop, comments, state, " " next_run_date, worker_pid, job_priority, max_runs, max_failures, " " program_name, schedule_name, job_style) " "SELECT owner, $3, job_type, job_action, number_of_arguments, start_date, " " repeat_interval, end_date, job_class, false, auto_drop, comments, " " 'DISABLED', NULL, NULL, job_priority, max_runs, max_failures, " " program_name, schedule_name, job_style " "FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 3, argtypes, values, nulls); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_arg " "(owner, job_name, argument_position, argument_name, argument_value) " "SELECT owner, $3, argument_position, argument_name, argument_value " "FROM pg_catalog.dbms_scheduler_job_arg " "WHERE owner = $1 AND job_name = $2", 3, argtypes, values, nulls); logEventf("задание скопировано", "[Status: OK, Job: %s]", new_job); } void Catalog::createJobOnProgram(const char *job_name, const char *program_name, const char *schedule_name, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *job_style, const char *credential_name, const char *destination_name) { const char *owner; const char *style; char *programType; char *programAction; int32 nargs = 0; bool hasRepeat; bool hasSchedule; style = canonicalJobStyle(job_style); rejectCredential(credential_name, destination_name); requireName(job_name); requireName(program_name); logEventf("вход создания задания на программу", "[Job: %s, Program: %s, Style: %s]", job_name, program_name, style); owner = currentOwner(); readProgram(owner, program_name, &programType, &programAction, &nargs); if (!styleIsRegular(style) && !programIsEnabled(owner, program_name)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid program for lightweight job"))); } hasRepeat = repeat_interval != NULL && repeat_interval[0] != '\0'; hasSchedule = schedule_name != NULL && schedule_name[0] != '\0'; if (styleIsFull(style) && (hasRepeat || hasSchedule)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("IN_MEMORY_FULL cannot have a schedule or repeat interval"))); } if (styleIsInMemory(style) && enabled) { ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("insufficient privileges"))); } if (hasSchedule) { char *schedRepeat = NULL; bool schedStartNull = true; bool schedEndNull = true; TimestampTz schedStart = 0; TimestampTz schedEnd = 0; readSchedule(owner, schedule_name, &schedRepeat, &schedStartNull, &schedStart, &schedEndNull, &schedEnd); createJob(job_name, programType, programAction, nargs, schedStartNull, schedStart, schedRepeat, schedEndNull, schedEnd, job_class, enabled, auto_drop, comments, program_name, schedule_name, style); return; } createJob(job_name, programType, programAction, nargs, start_null, start_date, repeat_interval, end_null, end_date, job_class, enabled, auto_drop, comments, program_name, NULL, style); } void Catalog::createJobOnSchedule(const char *job_name, const char *schedule_name, const char *job_type, const char *job_action, int32 number_of_arguments, const char *job_class, bool enabled, bool auto_drop, const char *comments, const char *credential_name, const char *destination_name) { const char *owner; char *schedRepeat = NULL; bool schedStartNull = true; bool schedEndNull = true; TimestampTz schedStart = 0; TimestampTz schedEnd = 0; rejectCredential(credential_name, destination_name); requireName(job_name); requireName(schedule_name); logEventf("вход создания задания на расписание", "[Job: %s, Schedule: %s]", job_name, schedule_name); owner = currentOwner(); readSchedule(owner, schedule_name, &schedRepeat, &schedStartNull, &schedStart, &schedEndNull, &schedEnd); createJob(job_name, job_type, job_action, number_of_arguments, schedStartNull, schedStart, schedRepeat, schedEndNull, schedEnd, job_class, enabled, auto_drop, comments, NULL, schedule_name, NULL); } static int32 programDeclared(const char *owner, const char *program_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); return selectInt32( "SELECT number_of_arguments FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND program_name = $2", 2, argtypes, values, nulls); } static int32 jobDeclared(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); return selectInt32( "SELECT number_of_arguments FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); } static void requireProgram(const char *owner, const char *program_name) { if (!programExists(owner, program_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown program \"%s\"", program_name))); } } static void rejectArgumentName(const char *owner, const char *program_name, const char *argument_name, int32 argument_position) { Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, INT4OID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; if (argument_name == NULL) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = CStringGetTextDatum(argument_name); values[3] = Int32GetDatum(argument_position); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_name = $3 " " AND argument_position <> $4", 4, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("argument \"%s\" already exists", argument_name))); } } static void writeProgramArgument(const char *owner, const char *program_name, int32 argument_position, const char *argument_name, const char *argument_type, const char *default_value, bool out_argument, const char *metadata_attribute) { Oid argtypes[8]; Datum values[8]; char nulls[8]; int i; for (i = 0; i < 8; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = INT4OID; argtypes[3] = TEXTOID; argtypes[4] = TEXTOID; argtypes[5] = TEXTOID; argtypes[6] = BOOLOID; argtypes[7] = TEXTOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = Int32GetDatum(argument_position); values[3] = CStringGetTextDatum(argument_name == NULL ? "" : argument_name); values[4] = CStringGetTextDatum(argument_type == NULL ? "" : argument_type); values[5] = CStringGetTextDatum(default_value == NULL ? "" : default_value); values[6] = BoolGetDatum(out_argument); values[7] = CStringGetTextDatum(metadata_attribute == NULL ? "" : metadata_attribute); if (argument_name == NULL) nulls[3] = 'n'; if (argument_type == NULL) nulls[4] = 'n'; if (default_value == NULL) nulls[5] = 'n'; if (metadata_attribute == NULL) nulls[7] = 'n'; if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_position = $3", 3, argtypes, values, nulls)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_program_arg SET " "argument_name = $4, argument_type = $5, default_value = $6, " "out_argument = $7, metadata_attribute = $8 " "WHERE owner = $1 AND program_name = $2 AND argument_position = $3", 8, argtypes, values, nulls); } else { execWrite( "INSERT INTO pg_catalog.dbms_scheduler_program_arg " "(owner, program_name, argument_position, argument_name, argument_type, " " default_value, out_argument, metadata_attribute) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", 8, argtypes, values, nulls); } } void Catalog::defineProgramArgument(const char *program_name, int32 argument_position, const char *argument_name, const char *argument_type, const char *default_value, bool out_argument) { const char *owner; char *storedName; char *storedType; requireName(program_name); logEventf("вход аргумента программы", "[Program: %s, Position: %d]", program_name, argument_position); if (out_argument) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("out_argument must be false"))); } if (argument_type == NULL || argument_type[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid argument type"))); } owner = currentOwner(); requireProgram(owner, program_name); requireArgumentPosition(argument_position, programDeclared(owner, program_name)); storedName = upperCopy(argument_name); storedType = upperCopy(argument_type); rejectArgumentName(owner, program_name, storedName, argument_position); writeProgramArgument(owner, program_name, argument_position, storedName, storedType, default_value, false, NULL); logEventf("аргумент программы записан", "[Status: OK, Program: %s, Position: %d]", program_name, argument_position); } void Catalog::defineMetadataArgument(const char *program_name, const char *metadata_attribute, int32 argument_position, const char *argument_name) { const char *owner; char *storedMeta; char *storedName; requireName(program_name); logEventf("вход metadata-аргумента", "[Program: %s, Position: %d]", program_name, argument_position); storedMeta = upperCopy(metadata_attribute); if (!metadataAttributeOk(storedMeta)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid metadata attribute"))); } owner = currentOwner(); requireProgram(owner, program_name); requireArgumentPosition(argument_position, programDeclared(owner, program_name)); storedName = upperCopy(argument_name); rejectArgumentName(owner, program_name, storedName, argument_position); writeProgramArgument(owner, program_name, argument_position, storedName, NULL, NULL, false, storedMeta); logEventf("metadata-аргумент записан", "[Status: OK, Program: %s, Position: %d]", program_name, argument_position); } void Catalog::dropProgramArgumentPos(const char *program_name, int32 argument_position) { const char *owner; Oid argtypes[3] = {TEXTOID, TEXTOID, INT4OID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(program_name); logEventf("вход удаления аргумента программы", "[Program: %s, Position: %d]", program_name, argument_position); owner = currentOwner(); requireProgram(owner, program_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = Int32GetDatum(argument_position); if (!selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_position = $3", 3, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown argument position %d", argument_position))); } execWrite( "DELETE FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_position = $3", 3, argtypes, values, nulls); logEventf("аргумент программы удалён", "[Status: OK, Program: %s, Position: %d]", program_name, argument_position); } void Catalog::dropProgramArgumentName(const char *program_name, const char *argument_name) { const char *owner; char *storedName; Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(program_name); storedName = upperCopy(argument_name); logEventf("вход удаления аргумента программы", "[Program: %s, Name: %s]", program_name, storedName == NULL ? "-" : storedName); if (storedName == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument name cannot be NULL"))); } owner = currentOwner(); requireProgram(owner, program_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = CStringGetTextDatum(storedName); if (!selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_name = $3", 3, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown argument \"%s\"", storedName))); } execWrite( "DELETE FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_name = $3", 3, argtypes, values, nulls); logEventf("аргумент программы удалён", "[Status: OK, Program: %s]", program_name); } void Catalog::setJobArgumentValuePos(const char *job_name, int32 argument_position, const char *argument_value) { const char *owner; Oid argtypes[4] = {TEXTOID, TEXTOID, INT4OID, TEXTOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; requireName(job_name); logEventf("вход значения аргумента задания", "[Job: %s, Position: %d]", job_name, argument_position); owner = currentOwner(); requireJob(owner, job_name); requireArgumentPosition(argument_position, jobDeclared(owner, job_name)); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = Int32GetDatum(argument_position); values[3] = CStringGetTextDatum(argument_value == NULL ? "" : argument_value); if (argument_value == NULL) nulls[3] = 'n'; if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job_arg " "WHERE owner = $1 AND job_name = $2 AND argument_position = $3", 3, argtypes, values, nulls)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_job_arg SET argument_value = $4 " "WHERE owner = $1 AND job_name = $2 AND argument_position = $3", 4, argtypes, values, nulls); } else { execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_arg " "(owner, job_name, argument_position, argument_value) " "VALUES ($1,$2,$3,$4)", 4, argtypes, values, nulls); } logEventf("значение аргумента задания записано", "[Status: OK, Job: %s, Position: %d]", job_name, argument_position); } static int32 namedProgramArgument(const char *owner, const char *program_name, const char *argument_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; int rc; bool isnull; int32 position = 0; bool metadata = false; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); values[2] = CStringGetTextDatum(argument_name); spiConnect(); rc = SPI_execute_with_args( "SELECT argument_position, metadata_attribute " "FROM pg_catalog.dbms_scheduler_program_arg " "WHERE owner = $1 AND program_name = $2 AND argument_name = $3", 3, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown argument \"%s\"", argument_name))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) position = DatumGetInt32(value); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); metadata = !isnull; } SPI_finish(); if (metadata) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("cannot set a metadata argument"))); } return position; } static char * jobProgramName(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; int rc; bool isnull; char *program = NULL; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT program_name 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) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) program = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return program; } void Catalog::setJobArgumentValueName(const char *job_name, const char *argument_name, const char *argument_value) { const char *owner; char *program; char *storedName; int32 position; Oid argtypes[4] = {TEXTOID, TEXTOID, INT4OID, TEXTOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; requireName(job_name); logEventf("вход значения аргумента задания", "[Job: %s, Name: %s]", job_name, argument_name == NULL ? "-" : argument_name); owner = currentOwner(); requireJob(owner, job_name); program = jobProgramName(owner, job_name); if (program == NULL || program[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument name requires a named program"))); } storedName = upperCopy(argument_name); if (storedName == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument name cannot be NULL"))); } position = namedProgramArgument(owner, program, storedName); setJobArgumentValuePos(job_name, position, argument_value); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = Int32GetDatum(position); values[3] = CStringGetTextDatum(storedName); execWrite( "UPDATE pg_catalog.dbms_scheduler_job_arg SET argument_name = $4 " "WHERE owner = $1 AND job_name = $2 AND argument_position = $3", 4, argtypes, values, nulls); } void Catalog::resetJobArgumentValuePos(const char *job_name, int32 argument_position) { const char *owner; Oid argtypes[3] = {TEXTOID, TEXTOID, INT4OID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(job_name); logEventf("вход сброса аргумента задания", "[Job: %s, Position: %d]", job_name, argument_position); owner = currentOwner(); requireJob(owner, job_name); requireArgumentPosition(argument_position, jobDeclared(owner, job_name)); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = Int32GetDatum(argument_position); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_arg " "WHERE owner = $1 AND job_name = $2 AND argument_position = $3", 3, argtypes, values, nulls); logEventf("значение аргумента задания сброшено", "[Status: OK, Job: %s, Position: %d]", job_name, argument_position); } void Catalog::resetJobArgumentValueName(const char *job_name, const char *argument_name) { const char *owner; char *program; char *storedName; int32 position; requireName(job_name); logEventf("вход сброса аргумента задания", "[Job: %s, Name: %s]", job_name, argument_name == NULL ? "-" : argument_name); owner = currentOwner(); requireJob(owner, job_name); program = jobProgramName(owner, job_name); if (program == NULL || program[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument name requires a named program"))); } storedName = upperCopy(argument_name); if (storedName == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("argument name cannot be NULL"))); } position = namedProgramArgument(owner, program, storedName); resetJobArgumentValuePos(job_name, position); } static bool windowExists(const char *window_name); static bool setWindowEnabled(const char *window_name, bool enabled) { const char *bare = window_name; Oid argtypes[2] = {BOOLOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; if (bare != NULL && pg_strncasecmp(bare, "SYS.", 4) == 0 && bare[4] != '\0') bare = bare + 4; if (!windowExists(bare)) return false; values[0] = BoolGetDatum(enabled); values[1] = CStringGetTextDatum(bare); execWrite( "UPDATE pg_catalog.dbms_scheduler_window SET enabled = $1 " "WHERE lower(window_name) = lower($2)", 2, argtypes, values, nulls); logEventf(enabled ? "окно включено" : "окно выключено", "[Status: OK, Window: %s]", bare); return true; } void Catalog::enable(const char *job_name) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(job_name); logEventf("вход включения задания", "[Job: %s]", job_name); owner = currentOwner(); if (!jobExists(owner, job_name)) { Oid chainTypes[2] = {TEXTOID, TEXTOID}; Datum chainValues[2]; char chainNulls[2] = {' ', ' '}; chainValues[0] = CStringGetTextDatum(owner); chainValues[1] = CStringGetTextDatum(job_name); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_chain " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, chainTypes, chainValues, chainNulls)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_chain SET enabled = true " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, chainTypes, chainValues, chainNulls); logEventf("цепочка включена", "[Status: OK, Chain: %s]", job_name); return; } if (setWindowEnabled(job_name, true)) return; setProgramEnabled(owner, job_name, true); return; } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); if (styleIsInMemory(loadJobStyle(owner, job_name))) { ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("insufficient privileges"))); } { char *repeat = NULL; bool startNull = true; bool endNull = true; TimestampTz startDate = 0; TimestampTz endDate = 0; bool isnull; int rc; Oid readTypes[2] = {TEXTOID, TEXTOID}; MemoryContext caller = CurrentMemoryContext; spiConnect(); 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, readTypes, values, nulls, true, 1); if (rc == SPI_OK_SELECT && SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) repeat = MemoryContextStrdup(caller, TextDatumGetCString(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); } } SPI_finish(); if (repeatText(repeat)) { TimestampTz nextRun; if (!startNull && !endNull && endDate < startDate) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("end_date is earlier than start_date"))); } Oid writeTypes[3] = {TEXTOID, TEXTOID, TIMESTAMPTZOID}; Datum writeValues[3]; char writeNulls[3] = {' ', ' ', 'n'}; writeValues[0] = values[0]; writeValues[1] = values[1]; writeValues[2] = TimestampTzGetDatum(0); if (nextRepeatRun(repeat, startNull, startDate, endNull, endDate, &nextRun)) { writeNulls[2] = ' '; writeValues[2] = TimestampTzGetDatum(nextRun); } execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = true, state = 'SCHEDULED', next_run_date = $3 " "WHERE owner = $1 AND job_name = $2", 3, writeTypes, writeValues, writeNulls); pfree(repeat); rudb_scheduler_wakeup(); noteFullOperation(owner, job_name, jobLoggingLevel(owner, job_name)); logEventf("задание включено", "[Status: OK, Job: %s, State: SCHEDULED]", job_name); return; } } execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = true, state = 'SCHEDULED', " " next_run_date = CASE " " WHEN end_date IS NOT NULL AND start_date IS NOT NULL " " AND start_date >= end_date THEN NULL " " WHEN end_date IS NOT NULL AND clock_timestamp() >= end_date THEN NULL " " WHEN start_date IS NOT NULL AND start_date > clock_timestamp() " " THEN start_date " " ELSE clock_timestamp() " " END " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); rudb_scheduler_wakeup(); noteFullOperation(owner, job_name, jobLoggingLevel(owner, job_name)); logEventf("задание включено", "[Status: OK, Job: %s, State: SCHEDULED]", job_name); } void Catalog::disable(const char *job_name) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(job_name); logEventf("вход выключения задания", "[Job: %s]", job_name); owner = currentOwner(); if (!jobExists(owner, job_name)) { if (setWindowEnabled(job_name, false)) return; setProgramEnabled(owner, job_name, false); return; } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = false, state = 'DISABLED', next_run_date = NULL " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); noteFullOperation(owner, job_name, jobLoggingLevel(owner, job_name)); logEventf("задание выключено", "[Status: OK, Job: %s, State: DISABLED]", job_name); } void Catalog::stopJob(const char *job_name) { const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int rc; bool isnull = false; char *state = NULL; int32 pid = 0; MemoryContext caller; requireName(job_name); logEventf("вход остановки задания", "[Job: %s]", job_name); owner = currentOwner(); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT state, worker_pid 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_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job \"%s\"", job_name))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) state = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); if (!isnull) pid = DatumGetInt32(value); } SPI_finish(); if (state == NULL || strcmp(state, "RUNNING") != 0 || pid <= 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("job \"%s\" is not running", job_name))); } DirectFunctionCall1(pg_cancel_backend, Int32GetDatum(pid)); logEventf("останов задания отправлен", "[Status: STOPPED, Job: %s, Pid: %d]", job_name, pid); } static void failOs(const char *job_name, int code) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("dbms_scheduler: процесс задания завершился с ошибкой"), errdetail_internal("Output: [Status: FAIL, Job: %s, Code: %d]", job_name, code))); } static void waitOsChild(const char *job_name, pid_t child) { int status = 0; PG_TRY(); { for (;;) { pid_t got = waitpid(child, &status, WNOHANG); if (got == child) break; if (got < 0 && errno != EINTR) failOs(job_name, errno); CHECK_FOR_INTERRUPTS(); pg_usleep(10000L); } } PG_CATCH(); { (void) kill(child, SIGKILL); (void) waitpid(child, &status, 0); PG_RE_THROW(); } PG_END_TRY(); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { int code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; failOs(job_name, code); } } static void spawnOs(const char *job_name, const char *file, char *const argv[]) { posix_spawn_file_actions_t actions; posix_spawnattr_t attr; pid_t child = 0; int devnull; int rc; sigset_t mask; sigset_t defSet; devnull = open("/dev/null", O_RDWR); if (devnull < 0) failOs(job_name, errno); posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_adddup2(&actions, devnull, STDIN_FILENO); posix_spawn_file_actions_adddup2(&actions, devnull, STDOUT_FILENO); posix_spawn_file_actions_adddup2(&actions, devnull, STDERR_FILENO); if (devnull > STDERR_FILENO) posix_spawn_file_actions_addclose(&actions, devnull); sigemptyset(&mask); sigemptyset(&defSet); sigaddset(&defSet, SIGPIPE); posix_spawnattr_init(&attr); posix_spawnattr_setsigmask(&attr, &mask); posix_spawnattr_setsigdefault(&attr, &defSet); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF); fflush(NULL); rc = posix_spawn(&child, file, &actions, &attr, argv, environ); posix_spawn_file_actions_destroy(&actions); posix_spawnattr_destroy(&attr); close(devnull); if (rc != 0) failOs(job_name, rc); waitOsChild(job_name, child); } static bool scriptIsFile(const char *action) { struct stat st; if (action == NULL || action[0] != '/' || strchr(action, '\n') != NULL) return false; if (stat(action, &st) != 0) return false; return S_ISREG(st.st_mode); } static void fillInterpreter(const char *path, char *interp, char *extra) { FILE *script; char line[256]; char *cursor; char *split; interp[0] = '\0'; extra[0] = '\0'; script = fopen(path, "r"); if (script == NULL) return; if (fgets(line, (int) sizeof(line), script) != NULL && strncmp(line, "#!", 2) == 0) { cursor = line + 2; while (*cursor == ' ' || *cursor == '\t') cursor++; split = cursor; while (*split != '\0' && *split != ' ' && *split != '\t' && *split != '\n' && *split != '\r') split++; if (*split != '\0') { char *arg = split; *split = '\0'; arg++; while (*arg == ' ' || *arg == '\t') arg++; split = arg; while (*split != '\0' && *split != ' ' && *split != '\t' && *split != '\n' && *split != '\r') split++; *split = '\0'; if (arg[0] != '\0') strlcpy(extra, arg, 128); } strlcpy(interp, cursor, 128); } fclose(script); } static void runScript(const char *job_name, const char *action) { char pathStore[64]; char interp[128]; char extra[128]; const char *path; char *argvLocal[4]; int fd; bool tempFile = false; if (scriptIsFile(action)) { path = action; } else { snprintf(pathStore, sizeof(pathStore), "/tmp/rsc_sched_XXXXXX"); fd = mkstemp(pathStore); if (fd < 0) failOs(job_name, errno); if (write(fd, action, strlen(action)) < 0 || write(fd, "\n", 1) < 0) { int saved = errno; close(fd); unlink(pathStore); failOs(job_name, saved); } close(fd); tempFile = true; path = pathStore; } PG_TRY(); { fillInterpreter(path, interp, extra); if (interp[0] == '\0') { argvLocal[0] = (char *) "/bin/sh"; argvLocal[1] = (char *) path; argvLocal[2] = NULL; spawnOs(job_name, "/bin/sh", argvLocal); } else if (extra[0] == '\0') { argvLocal[0] = interp; argvLocal[1] = (char *) path; argvLocal[2] = NULL; spawnOs(job_name, interp, argvLocal); } else { argvLocal[0] = interp; argvLocal[1] = extra; argvLocal[2] = (char *) path; argvLocal[3] = NULL; spawnOs(job_name, interp, argvLocal); } } PG_CATCH(); { if (tempFile) unlink(pathStore); PG_RE_THROW(); } PG_END_TRY(); if (tempFile) unlink(pathStore); } static char * loadCredentialName(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; char *name = NULL; int rc; bool isnull = false; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT credential_name 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) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) name = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return name; } static void requireCredential(const char *owner, const char *job_name) { char *credName; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; credName = loadCredentialName(owner, job_name); if (credName == NULL || credName[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CREDENTIAL_NAME cannot be NULL"))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(credName); if (!selectExists( "SELECT 1 FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2)", 2, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown credential \"%s\"", credName))); } } void runOsJob(const char *owner, const char *job_name, const char *job_type, const char *job_action) { char *argvLocal[2]; logEventf("запуск процесса задания", "[Job: %s, Type: %s]", job_name, job_type); if (job_action == NULL || job_action[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job action cannot be NULL"))); } if (strcmp(job_type, "EXTERNAL_SCRIPT") == 0 || loadCredentialName(owner, job_name) != NULL) requireCredential(owner, job_name); if (strcmp(job_type, "EXTERNAL_SCRIPT") == 0) { runScript(job_name, job_action); } else { argvLocal[0] = (char *) job_action; argvLocal[1] = NULL; spawnOs(job_name, job_action, argvLocal); } logEventf("процесс задания завершён", "[Status: OK, Job: %s]", job_name); } static bool runCurrentOsJob(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; char *jobType = NULL; char *action = NULL; int rc; bool isnull = false; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT job_type, job_action 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) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) jobType = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); if (!isnull) action = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); if (!osJobType(jobType)) return false; runOsJob(owner, job_name, jobType, action); return true; } void Catalog::runJob(const char *job_name, bool use_current_session) { const char *owner; char *action; MemoryContext oldContext; ResourceOwner oldOwner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(job_name); logEventf("вход запуска задания", "[Job: %s, Session: %s]", job_name, use_current_session ? "current" : "background"); if (!use_current_session) { if (rudb_scheduler_max_workers <= 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("dbms_scheduler_run_job cannot start a background job while max_workers is 0"))); } owner = currentOwner(); requireJob(owner, job_name); rejectInMemoryRun(owner, job_name, true); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET state = 'SCHEDULED', next_run_date = clock_timestamp() " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); rudb_scheduler_wakeup(); logEventf("задание отдано координатору", "[Status: SCHEDULED, Job: %s]", job_name); return; } owner = currentOwner(); requireJob(owner, job_name); rejectInMemoryRun(owner, job_name, false); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET next_run_date = NULL " "WHERE owner = $1 AND job_name = $2 " " AND (repeat_interval IS NULL OR repeat_interval = '')", 2, argtypes, values, nulls); oldContext = CurrentMemoryContext; oldOwner = CurrentResourceOwner; PG_TRY(); { if (!runCurrentOsJob(owner, job_name)) { action = loadAction(owner, job_name); runAction(action); } if (logRun(owner, job_name, "SUCCEEDED")) { values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_run " "(owner, job_name, log_date, status, pid) " "VALUES ($1, $2, clock_timestamp(), 'SUCCEEDED', pg_backend_pid())", 2, argtypes, values, nulls); } logEventf("задание выполнено в текущем сеансе", "[Status: OK, Job: %s]", job_name); rudb_scheduler_notify_email(owner, job_name, "JOB_SUCCEEDED"); } PG_CATCH(); { ErrorData *edata; char errbuf[200]; MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; edata = CopyErrorData(); FlushErrorState(); errbuf[0] = '\0'; if (edata != NULL && edata->message != NULL) snprintf(errbuf, sizeof(errbuf), "%s", edata->message); if (!IsAbortedTransactionBlockState() && logRun(owner, job_name, "FAILED")) (void) rudb_scheduler_persist_failed_run( owner, job_name, errbuf[0] != '\0' ? errbuf : NULL); logEventf("ошибка задания в текущем сеансе", "[Status: FAILED, Job: %s]", job_name); ReThrowError(edata); } PG_END_TRY(); } char * Catalog::generateJobName(const char *prefix) { const char *used; const char *owner; MemoryContext caller; char *result; int attempt; used = (prefix == NULL || prefix[0] == '\0') ? "JOB$_" : upperCopy(prefix); logEventf("вход выдачи имени", "[Prefix: %s]", used); if (strlen(used) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job name prefix is longer than %d bytes", NAME_MAX_BYTES))); } owner = currentOwner(); caller = CurrentMemoryContext; result = NULL; spiConnect(); for (attempt = 0; attempt < 64 && result == NULL; attempt++) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; char candidate[128]; int rc; bool isnull; bool taken; int64 seq; Datum seqDatum; rc = SPI_execute("SELECT nextval('pg_catalog.dbms_scheduler_job_name_seq')", false, 1); if (rc != SPI_OK_SELECT || SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: не удалось получить имя задания"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } seqDatum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (isnull) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: не удалось получить имя задания"), errdetail_internal("Output: [Status: FAIL]"))); } seq = DatumGetInt64(seqDatum); snprintf(candidate, sizeof(candidate), "%s%lld", used, (long long) seq); if (strlen(candidate) > (size_t) NAME_MAX_BYTES) { SPI_finish(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("generated job name is longer than %d bytes", NAME_MAX_BYTES))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(candidate); rc = SPI_execute_with_args( "SELECT 1 FROM pg_catalog.pg_class c " "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " "WHERE n.nspname = current_schema() AND c.relname = $2 " "UNION ALL " "SELECT 1 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_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } taken = SPI_processed > 0; if (!taken) result = MemoryContextStrdup(caller, candidate); } SPI_finish(); if (result == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("could not generate a free job name"))); } logEventf("выдано имя задания", "[Status: OK, Job: %s]", result); return result; } static char * attrKey(const char *attribute) { char *key; size_t i; size_t n; if (attribute == NULL || attribute[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("attribute cannot be NULL"))); } n = strlen(attribute); key = (char *) palloc(n + 1); for (i = 0; i < n; i++) { unsigned char ch = (unsigned char) attribute[i]; key[i] = (char) ((ch >= 'A' && ch <= 'Z') ? ch + 32 : ch); } key[n] = '\0'; return key; } static void rejectForeignAttr(const char *key) { if (strcmp(key, "destination_name") == 0 || strcmp(key, "event_spec") == 0) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_set_attribute does not support %s", key))); } } static void badAttr(const char *key) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s is not a valid job attribute", key))); } static int32 parseBoundedInt(const char *text, int32 minVal, int32 maxVal) { char *end = NULL; long num; if (text == NULL || text[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid attribute value"))); } errno = 0; num = strtol(text, &end, 10); if (end == text || *end != '\0' || errno != 0 || num < (long) minVal || num > (long) maxVal) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid attribute value"))); } return (int32) num; } static void updateJobAttr(const char *owner, const char *job_name, const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls) { requireJob(owner, job_name); execWrite(sql, nargs, argtypes, values, nulls); } void Catalog::setAttributeText(const char *job_name, const char *attribute, const char *value) { const char *owner; char *key; const char *sql; Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; int32 parsed = 0; bool asInt = false; requireName(job_name); if (value == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("attribute value cannot be NULL"))); } key = attrKey(attribute); logEventf("вход установки атрибута", "[Job: %s, Attribute: %s]", job_name, key); owner = currentOwner(); rejectStyleAttr(owner, job_name, key); if (strcmp(key, "credential_name") == 0) { char *storedCred = upperCopy(value); Oid credTypes[2] = {TEXTOID, TEXTOID}; Datum credValues[2]; char credNulls[2] = {' ', ' '}; if (storedCred == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("credential name cannot be NULL"))); } credValues[0] = CStringGetTextDatum(owner); credValues[1] = CStringGetTextDatum(storedCred); if (!selectExists( "SELECT 1 FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2)", 2, credTypes, credValues, credNulls)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown credential \"%s\"", storedCred))); } sql = "UPDATE pg_catalog.dbms_scheduler_job SET credential_name = $3 " "WHERE owner = $1 AND job_name = $2"; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = CStringGetTextDatum(storedCred); updateJobAttr(owner, job_name, sql, 3, argtypes, values, nulls); logEventf("атрибут задания изменён", "[Job: %s, Attribute: %s]", job_name, key); return; } rejectForeignAttr(key); if (strcmp(key, "repeat_interval") == 0) { sql = "UPDATE pg_catalog.dbms_scheduler_job SET repeat_interval = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "comments") == 0) { sql = "UPDATE pg_catalog.dbms_scheduler_job SET comments = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "job_action") == 0) { sql = "UPDATE pg_catalog.dbms_scheduler_job SET job_action = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "job_type") == 0) { char *typeUpper = upperCopy(value); if (typeUpper != NULL && osJobType(typeUpper)) value = typeUpper; else if (typeUpper != NULL && laterJobType(typeUpper)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("dbms_scheduler_set_attribute does not support job_type %s", typeUpper))); } else if (strcmp(value, "PLSQL_BLOCK") != 0) badAttr(key); sql = "UPDATE pg_catalog.dbms_scheduler_job SET job_type = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "job_priority") == 0) { parsed = parseBoundedInt(value, 1, 5); asInt = true; sql = "UPDATE pg_catalog.dbms_scheduler_job SET job_priority = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "max_runs") == 0) { parsed = parseBoundedInt(value, 1, 1000000); asInt = true; sql = "UPDATE pg_catalog.dbms_scheduler_job SET max_runs = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "max_failures") == 0) { parsed = parseBoundedInt(value, 1, 1000000); asInt = true; sql = "UPDATE pg_catalog.dbms_scheduler_job SET max_failures = $3 " "WHERE owner = $1 AND job_name = $2"; } else { badAttr(key); sql = NULL; } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); if (asInt) { argtypes[2] = INT4OID; values[2] = Int32GetDatum(parsed); } else { values[2] = CStringGetTextDatum(value); } updateJobAttr(owner, job_name, sql, 3, argtypes, values, nulls); logEventf("атрибут задания изменён", "[Job: %s, Attribute: %s]", job_name, key); } void Catalog::setAttributeBool(const char *job_name, const char *attribute, bool value) { const char *owner; char *key; Oid argtypes[3] = {TEXTOID, TEXTOID, BOOLOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(job_name); key = attrKey(attribute); logEventf("вход установки атрибута", "[Job: %s, Attribute: %s]", job_name, key); rejectForeignAttr(key); owner = currentOwner(); rejectStyleAttr(owner, job_name, key); if (strcmp(key, "auto_drop") != 0) badAttr(key); owner = currentOwner(); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = BoolGetDatum(value); updateJobAttr(owner, job_name, "UPDATE pg_catalog.dbms_scheduler_job SET auto_drop = $3 " "WHERE owner = $1 AND job_name = $2", 3, argtypes, values, nulls); logEventf("атрибут задания изменён", "[Job: %s, Attribute: %s]", job_name, key); } static void rejectEnabledEndBeforeStart(const char *owner, const char *job_name, TimestampTz end_date) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int rc; bool isnull; bool enabled; bool startNull; TimestampTz startDate; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); spiConnect(); rc = SPI_execute_with_args( "SELECT enabled, start_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_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed != 1) { SPI_finish(); return; } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); enabled = !isnull && DatumGetBool(value); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); startNull = isnull; if (!startNull) startDate = DatumGetTimestampTz(value); } SPI_finish(); if (enabled && !startNull && end_date < startDate) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("end_date is earlier than start_date"))); } } void Catalog::setAttributeTimestamptz(const char *job_name, const char *attribute, TimestampTz value) { const char *owner; char *key; const char *sql; Oid argtypes[3] = {TEXTOID, TEXTOID, TIMESTAMPTZOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; requireName(job_name); key = attrKey(attribute); logEventf("вход установки атрибута", "[Job: %s, Attribute: %s]", job_name, key); rejectForeignAttr(key); if (strcmp(key, "start_date") == 0) { sql = "UPDATE pg_catalog.dbms_scheduler_job SET start_date = $3 " "WHERE owner = $1 AND job_name = $2"; } else if (strcmp(key, "end_date") == 0) { sql = "UPDATE pg_catalog.dbms_scheduler_job SET end_date = $3 " "WHERE owner = $1 AND job_name = $2"; } else { badAttr(key); sql = NULL; } owner = currentOwner(); if (strcmp(key, "end_date") == 0) rejectEnabledEndBeforeStart(owner, job_name, value); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = TimestampTzGetDatum(value); updateJobAttr(owner, job_name, sql, 3, argtypes, values, nulls); logEventf("атрибут задания изменён", "[Job: %s, Attribute: %s]", job_name, key); } void Catalog::setAttributeNull(const char *job_name, const char *attribute) { const char *owner; char *key; const char *sql; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; requireName(job_name); key = attrKey(attribute); logEventf("вход очистки атрибута", "[Job: %s, Attribute: %s]", job_name, key); rejectForeignAttr(key); if (strcmp(key, "comments") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET comments = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "repeat_interval") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET repeat_interval = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "start_date") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET start_date = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "end_date") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET end_date = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "job_action") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET job_action = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "max_runs") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET max_runs = NULL " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "max_failures") == 0) sql = "UPDATE pg_catalog.dbms_scheduler_job SET max_failures = NULL " "WHERE owner = $1 AND job_name = $2"; else badAttr(key); owner = currentOwner(); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); rejectStyleAttr(owner, job_name, key); updateJobAttr(owner, job_name, sql, 2, argtypes, values, nulls); logEventf("атрибут задания очищен", "[Job: %s, Attribute: %s]", job_name, key); } char * Catalog::getAttribute(const char *job_name, const char *attribute) { const char *owner; char *key; const char *sql; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; char *result = NULL; int rc; bool isnull; requireName(job_name); key = attrKey(attribute); logEventf("вход чтения атрибута", "[Job: %s, Attribute: %s]", job_name, key); rejectForeignAttr(key); if (strcmp(key, "repeat_interval") == 0) sql = "SELECT repeat_interval FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "comments") == 0) sql = "SELECT comments FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "job_action") == 0) sql = "SELECT job_action FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "job_type") == 0) sql = "SELECT job_type FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "job_priority") == 0) sql = "SELECT job_priority::text FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "max_runs") == 0) sql = "SELECT max_runs::text FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "max_failures") == 0) sql = "SELECT max_failures::text FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "auto_drop") == 0) sql = "SELECT CASE WHEN auto_drop THEN 'TRUE' ELSE 'FALSE' END " "FROM pg_catalog.dbms_scheduler_job WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "enabled") == 0) sql = "SELECT CASE WHEN enabled THEN 'TRUE' ELSE 'FALSE' END " "FROM pg_catalog.dbms_scheduler_job WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "start_date") == 0) sql = "SELECT to_char(start_date AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') " "FROM pg_catalog.dbms_scheduler_job WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "end_date") == 0) sql = "SELECT to_char(end_date AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') " "FROM pg_catalog.dbms_scheduler_job WHERE owner = $1 AND job_name = $2"; else if (strcmp(key, "raise_events") == 0) sql = "SELECT raise_events::text FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2"; else badAttr(key); owner = currentOwner(); requireJob(owner, job_name); if (strcmp(key, "job_priority") == 0) rejectStyleAttr(owner, job_name, key); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT || SPI_processed != 1) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: атрибут не прочитан"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return result; } static bool whichLogKnown(const char *which_log) { return strcmp(which_log, "JOB_LOG") == 0 || strcmp(which_log, "WINDOW_LOG") == 0 || strcmp(which_log, "JOB_AND_WINDOW_LOG") == 0; } static bool purgeTouchesJobLog(const char *which_log, const char *job_name) { if (job_name != NULL && job_name[0] != '\0') return true; return strcmp(which_log, "WINDOW_LOG") != 0; } static void purgeOwnerRows(const char *owner, const char *job_name, int32 log_history, bool all_jobs) { Oid argtypes[3] = {TEXTOID, INT4OID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = Int32GetDatum(log_history); if (all_jobs) { execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_run " "WHERE owner = $1 " " AND log_date < clock_timestamp() - make_interval(days => $2)", 2, argtypes, values, nulls); return; } values[2] = CStringGetTextDatum(job_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_run " "WHERE owner = $1 AND job_name = $3 " " AND log_date < clock_timestamp() - make_interval(days => $2)", 3, argtypes, values, nulls); } static void purgeNameList(const char *owner, const char *job_name, int32 log_history) { char *copy = pstrdup(job_name); char *cursor = copy; while (*cursor != '\0') { char *start; char *end; char saved; while (*cursor == ',' || *cursor == ' ') cursor++; if (*cursor == '\0') break; start = cursor; while (*cursor != '\0' && *cursor != ',') cursor++; end = cursor; while (end > start && *(end - 1) == ' ') end--; if (end == start) continue; saved = *end; *end = '\0'; purgeOwnerRows(owner, start, log_history, false); *end = saved; } pfree(copy); } void Catalog::purgeLog(int32 log_history, const char *which_log, const char *job_name) { const char *which; const char *owner; logEventf("вход очистки журнала", "[History: %d, Which: %s, Job: %s]", log_history, (which_log == NULL || which_log[0] == '\0') ? "-" : which_log, (job_name == NULL || job_name[0] == '\0') ? "-" : job_name); if (log_history < 0 || log_history > 1000000) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid log_history %d", log_history))); } which = (which_log == NULL || which_log[0] == '\0') ? "JOB_AND_WINDOW_LOG" : which_log; if (!whichLogKnown(which)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid which_log \"%s\"", which))); } if (!purgeTouchesJobLog(which, job_name)) return; owner = currentOwner(); if (job_name == NULL || job_name[0] == '\0') purgeOwnerRows(owner, NULL, log_history, true); else purgeNameList(owner, job_name, log_history); logEventf("журнал очищен", "[Status: OK, History: %d]", log_history); } static bool loggingLevelOk(int32 level) { return level == LOG_OFF || level == LOG_RUNS || level == LOG_FAILED_RUNS || level == LOG_FULL; } static char * trimClassName(const char *text) { const char *start = text; const char *end; size_t len; char *copy; while (*start == ' ' || *start == '\t') start++; end = start + strlen(start); while (end > start && (end[-1] == ' ' || end[-1] == '\t')) end--; len = (size_t) (end - start); copy = (char *) palloc(len + 1); memcpy(copy, start, len); copy[len] = '\0'; return copy; } static bool classExists(const char *job_class_name) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(job_class_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job_class " "WHERE lower(job_class_name) = lower($1)", 1, argtypes, values, nulls); } static void dropOneJobClass(const char *job_class_name, bool force) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; int32 refs; if (job_class_name == NULL || job_class_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_CLASS_NAME cannot be NULL"))); } if (strlen(job_class_name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job class name is longer than %d bytes", NAME_MAX_BYTES))); } if (!classExists(job_class_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown job class \"%s\"", job_class_name))); } values[0] = CStringGetTextDatum(job_class_name); refs = selectInt32( "SELECT COUNT(*)::integer FROM pg_catalog.dbms_scheduler_job " "WHERE lower(job_class) = lower($1)", 1, argtypes, values, nulls); if (refs > 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job class \"%s\" is in use", job_class_name))); } if (refs > 0) { execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET enabled = false, state = 'DISABLED', next_run_date = NULL, " " job_class = 'DEFAULT_JOB_CLASS' " "WHERE lower(job_class) = lower($1)", 1, argtypes, values, nulls); } execWrite( "DELETE FROM pg_catalog.dbms_scheduler_job_class " "WHERE lower(job_class_name) = lower($1)", 1, argtypes, values, nulls); } void Catalog::createJobClass(const char *job_class_name, const char *resource_consumer_group, const char *service, bool level_null, int32 logging_level, bool history_null, int32 log_history, const char *comments) { const char *owner; int32 level; Oid argtypes[5]; Datum values[5]; char nulls[5]; int i; if (job_class_name == NULL || job_class_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_CLASS_NAME cannot be NULL"))); } if (strlen(job_class_name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job class name is longer than %d bytes", NAME_MAX_BYTES))); } logEventf("вход создания класса заданий", "[Class: %s]", job_class_name); if (pg_strcasecmp(job_class_name, "DEFAULT_JOB_CLASS") == 0) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("job class \"%s\" already exists", job_class_name))); } if (resource_consumer_group != NULL && resource_consumer_group[0] != '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("resource consumer group \"%s\" does not exist", resource_consumer_group))); } if (service != NULL && service[0] != '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("service \"%s\" does not exist", service))); } level = level_null ? LOG_RUNS : logging_level; if (!loggingLevelOk(level)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid logging_level %d", level))); } if (!history_null && (log_history < 0 || log_history > 1000000)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid log_history %d", log_history))); } if (classExists(job_class_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("job class \"%s\" already exists", job_class_name))); } owner = currentOwner(); for (i = 0; i < 5; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = INT4OID; argtypes[3] = INT4OID; argtypes[4] = TEXTOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_class_name); values[2] = Int32GetDatum(level); values[3] = Int32GetDatum(log_history); values[4] = comments == NULL ? (Datum) 0 : CStringGetTextDatum(comments); if (history_null) nulls[3] = 'n'; if (comments == NULL) nulls[4] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_class " "(owner, job_class_name, logging_level, log_history, comments) " "VALUES ($1,$2,$3,$4,$5)", 5, argtypes, values, nulls); logEventf("класс заданий записан в каталог", "[Status: OK, Class: %s, Level: %d]", job_class_name, level); } void Catalog::dropJobClass(const char *job_class_name, bool force) { char *copy; char *cursor; if (job_class_name == NULL || job_class_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_CLASS_NAME cannot be NULL"))); } logEventf("вход удаления класса заданий", "[Class: %s, Force: %s]", job_class_name, force ? "true" : "false"); copy = pstrdup(job_class_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); dropOneJobClass(name, force); pfree(name); if (comma == NULL) break; cursor = comma + 1; } logEventf("класс заданий удалён из каталога", "[Status: OK, Class: %s]", job_class_name); } static const char * canonicalSchedulerAttr(const char *attribute) { if (attribute == NULL || attribute[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ATTRIBUTE cannot be NULL"))); } if (pg_strcasecmp(attribute, "log_history") == 0) return "log_history"; if (pg_strcasecmp(attribute, "default_timezone") == 0) return "default_timezone"; if (pg_strcasecmp(attribute, "email_server") == 0) return "email_server"; if (pg_strcasecmp(attribute, "email_sender") == 0) return "email_sender"; if (pg_strcasecmp(attribute, "email_server_encryption") == 0) return "email_server_encryption"; if (pg_strcasecmp(attribute, "event_expiry_time") == 0) return "event_expiry_time"; if (pg_strcasecmp(attribute, "current_open_window") == 0) return "current_open_window"; if (pg_strcasecmp(attribute, "max_job_slave_processes") == 0) return "max_job_slave_processes"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s is not a valid scheduler attribute", attribute))); } static bool parseIntText(const char *text, long *out) { char *end = NULL; long value; if (text == NULL || text[0] == '\0') return false; errno = 0; value = strtol(text, &end, 10); if (end == text || *end != '\0' || errno != 0) return false; *out = value; return true; } static bool timezoneNameOk(const char *value) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; int hour; int minute; if (value == NULL || value[0] == '\0') return false; if (strlen(value) == 6 && (value[0] == '+' || value[0] == '-') && value[3] == ':' && isdigit((unsigned char) value[1]) && isdigit((unsigned char) value[2]) && isdigit((unsigned char) value[4]) && isdigit((unsigned char) value[5])) { hour = (value[1] - '0') * 10 + (value[2] - '0'); minute = (value[4] - '0') * 10 + (value[5] - '0'); return hour <= 14 && minute <= 59; } values[0] = CStringGetTextDatum(value); return selectExists( "SELECT 1 FROM pg_catalog.pg_timezone_names WHERE name = $1", 1, argtypes, values, nulls); } static void upsertSchedulerAttr(const char *canon, const char *value) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(canon); if (value == NULL) { execWrite( "DELETE FROM pg_catalog.dbms_scheduler_global " "WHERE lower(attribute) = lower($1)", 1, argtypes, values, nulls); return; } values[1] = CStringGetTextDatum(value); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_global " "WHERE lower(attribute) = lower($1)", 1, argtypes, values, nulls)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_global SET value = $2 " "WHERE lower(attribute) = lower($1)", 2, argtypes, values, nulls); return; } execWrite( "INSERT INTO pg_catalog.dbms_scheduler_global (attribute, value) " "VALUES ($1, $2)", 2, argtypes, values, nulls); } static char * checkedIntText(const char *value, long *parsed) { char buf[32]; if (!parseIntText(value, parsed)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid scheduler attribute value"))); } snprintf(buf, sizeof(buf), "%ld", *parsed); return pstrdup(buf); } void Catalog::setSchedulerAttribute(const char *attribute, const char *value) { const char *canon; long parsed = 0; char *stored = NULL; canon = canonicalSchedulerAttr(attribute); logEventf("вход записи атрибута планировщика", "[Attribute: %s]", canon); if (strcmp(canon, "current_open_window") == 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("current_open_window is not settable"))); } if (strcmp(canon, "log_history") == 0) { if (value == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("log_history cannot be NULL"))); } stored = checkedIntText(value, &parsed); if (parsed < 0 || parsed > 1000000) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid log_history %ld", parsed))); } } else if (strcmp(canon, "default_timezone") == 0) { if (!timezoneNameOk(value)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid default_timezone"))); } stored = pstrdup(value); } else if (strcmp(canon, "email_server") == 0 || strcmp(canon, "email_sender") == 0) { stored = value == NULL ? NULL : pstrdup(value); } else if (strcmp(canon, "email_server_encryption") == 0) { if (value == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid email_server_encryption"))); } if (pg_strcasecmp(value, "NONE") == 0) stored = pstrdup("NONE"); else if (pg_strcasecmp(value, "SSL_TLS") == 0) stored = pstrdup("SSL_TLS"); else if (pg_strcasecmp(value, "STARTTLS") == 0) stored = pstrdup("STARTTLS"); else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid email_server_encryption"))); } } else if (strcmp(canon, "event_expiry_time") == 0) { if (value == NULL) stored = NULL; else stored = checkedIntText(value, &parsed); } else if (strcmp(canon, "max_job_slave_processes") == 0) { if (value == NULL) stored = NULL; else { stored = checkedIntText(value, &parsed); if (parsed <= 0 || parsed > 1000000) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid max_job_slave_processes"))); } } } upsertSchedulerAttr(canon, stored); logEventf("атрибут планировщика записан", "[Status: OK, Attribute: %s]", canon); } char * Catalog::getSchedulerAttribute(const char *attribute) { const char *canon; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; MemoryContext caller; char *result = NULL; int rc; bool isnull = false; canon = canonicalSchedulerAttr(attribute); logEventf("вход чтения атрибута планировщика", "[Attribute: %s]", canon); values[0] = CStringGetTextDatum(canon); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT value FROM pg_catalog.dbms_scheduler_global " "WHERE lower(attribute) = lower($1)", 1, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return result; } static void requireWindowDuration(const Interval *duration) { int64 usec; if (duration == NULL || duration->month != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid window duration"))); } usec = duration->time + (int64) duration->day * USECS_PER_DAY; if (usec < USECS_PER_MINUTE || usec > (int64) 99 * USECS_PER_DAY) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid window duration"))); } } static char * requireWindowName(const char *window_name) { if (window_name == NULL || window_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("WINDOW_NAME cannot be NULL"))); } if (strlen(window_name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("window name is longer than %d bytes", NAME_MAX_BYTES))); } return upperCopy(window_name); } static bool windowExists(const char *window_name) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(window_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_window " "WHERE lower(window_name) = lower($1)", 1, argtypes, values, nulls); } static bool windowFlag(const char *window_name, const char *column) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; int rc; bool isnull = false; bool flag = false; char sql[128]; snprintf(sql, sizeof(sql), "SELECT %s FROM pg_catalog.dbms_scheduler_window " "WHERE lower(window_name) = lower($1)", column); values[0] = CStringGetTextDatum(window_name); spiConnect(); rc = SPI_execute_with_args(sql, 1, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) flag = DatumGetBool(value); } SPI_finish(); return flag; } static char * activeWindowName() { MemoryContext caller = CurrentMemoryContext; int rc; bool isnull = false; char *name = NULL; spiConnect(); rc = SPI_execute( "SELECT window_name FROM pg_catalog.dbms_scheduler_window WHERE active LIMIT 1", true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) name = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return name; } static void requireKnownWindow(const char *window_name) { if (!windowExists(window_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown window \"%s\"", window_name))); } } static char * windowPriorityText(const char *window_priority) { char *stored; if (window_priority == NULL || window_priority[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("PRIORITY cannot be NULL"))); } stored = upperCopy(window_priority); if (strcmp(stored, "HIGH") != 0 && strcmp(stored, "LOW") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid window priority"))); } return stored; } static void insertWindow(const char *window_name, const char *resource_plan, const char *schedule_owner, const char *schedule_name, const char *schedule_type, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const Interval *duration, const char *window_priority, const char *comments, bool enabled) { Oid argtypes[12]; Datum values[12]; char nulls[12]; int i; for (i = 0; i < 12; i++) nulls[i] = ' '; argtypes[0] = TEXTOID; argtypes[1] = TEXTOID; argtypes[2] = TEXTOID; argtypes[3] = TEXTOID; argtypes[4] = TEXTOID; argtypes[5] = TIMESTAMPTZOID; argtypes[6] = TEXTOID; argtypes[7] = TIMESTAMPTZOID; argtypes[8] = INTERVALOID; argtypes[9] = TEXTOID; argtypes[10] = BOOLOID; argtypes[11] = TEXTOID; values[0] = CStringGetTextDatum(window_name); values[1] = resource_plan == NULL ? (Datum) 0 : CStringGetTextDatum(resource_plan); values[2] = schedule_owner == NULL ? (Datum) 0 : CStringGetTextDatum(schedule_owner); values[3] = schedule_name == NULL ? (Datum) 0 : CStringGetTextDatum(schedule_name); values[4] = CStringGetTextDatum(schedule_type); values[5] = TimestampTzGetDatum(start_date); values[6] = repeat_interval == NULL ? (Datum) 0 : CStringGetTextDatum(repeat_interval); values[7] = TimestampTzGetDatum(end_date); values[8] = PointerGetDatum(duration); values[9] = CStringGetTextDatum(window_priority); values[10] = BoolGetDatum(enabled); values[11] = comments == NULL ? (Datum) 0 : CStringGetTextDatum(comments); if (resource_plan == NULL) nulls[1] = 'n'; if (schedule_owner == NULL) nulls[2] = 'n'; if (schedule_name == NULL) nulls[3] = 'n'; if (start_null) nulls[5] = 'n'; if (repeat_interval == NULL) nulls[6] = 'n'; if (end_null) nulls[7] = 'n'; if (comments == NULL) nulls[11] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_scheduler_window " "(window_name, resource_plan, schedule_owner, schedule_name, schedule_type, " " start_date, repeat_interval, end_date, duration, window_priority, enabled, comments) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)", 12, argtypes, values, nulls); } static void requireFreshWindow(const char *window_name) { if (windowExists(window_name)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("window \"%s\" already exists", window_name))); } } void Catalog::createWindowCalendar(const char *window_name, const char *resource_plan, bool start_null, TimestampTz start_date, const char *repeat_interval, bool end_null, TimestampTz end_date, const Interval *duration, const char *window_priority, const char *comments, bool enabled) { char *storedName; char *storedPlan; char *storedPriority; TimestampTz ignored; storedName = requireWindowName(window_name); logEventf("вход создания окна", "[Window: %s]", storedName); requireWindowDuration(duration); if (!repeatText(repeat_interval)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("REPEAT_INTERVAL cannot be NULL"))); } if (!start_null && !end_null && end_date <= start_date) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("END_DATE must be after START_DATE"))); } rudb_scheduler_calendar_next(repeat_interval, start_null ? GetCurrentTimestamp() : start_date, GetCurrentTimestamp(), &ignored); storedPriority = windowPriorityText(window_priority); storedPlan = upperCopy(resource_plan); requireFreshWindow(storedName); insertWindow(storedName, storedPlan, NULL, NULL, "CALENDAR", start_null, start_date, repeat_interval, end_null, end_date, duration, storedPriority, comments, enabled); logEventf("окно записано в каталог", "[Status: OK, Window: %s]", storedName); } void Catalog::createWindowSchedule(const char *window_name, const char *resource_plan, const char *schedule_name, const Interval *duration, const char *window_priority, const char *comments, bool enabled) { const char *owner; char *storedName; char *storedPlan; char *storedPriority; char *storedSchedule = NULL; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller; int rc; bool isnull = false; storedName = requireWindowName(window_name); logEventf("вход создания окна", "[Window: %s]", storedName); requireWindowDuration(duration); if (schedule_name == NULL || schedule_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("SCHEDULE_NAME cannot be NULL"))); } owner = currentOwner(); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(schedule_name); caller = CurrentMemoryContext; spiConnect(); rc = SPI_execute_with_args( "SELECT schedule_name FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND lower(schedule_name) = lower($2)", 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) storedSchedule = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); if (storedSchedule == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown schedule \"%s\"", schedule_name))); } storedPriority = windowPriorityText(window_priority); storedPlan = upperCopy(resource_plan); requireFreshWindow(storedName); insertWindow(storedName, storedPlan, owner, storedSchedule, "NAMED", true, 0, NULL, true, 0, duration, storedPriority, comments, enabled); logEventf("окно записано в каталог", "[Status: OK, Window: %s]", storedName); } static void clearOpenWindow() { execWrite( "UPDATE pg_catalog.dbms_scheduler_window " "SET active = false, manual_duration = NULL WHERE active", 0, NULL, NULL, NULL); } static void markWindowOpen(const char *window_name, const Interval *duration) { Oid argtypes[2] = {TEXTOID, INTERVALOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(window_name); values[1] = duration == NULL ? (Datum) 0 : PointerGetDatum(duration); if (duration == NULL) nulls[1] = 'n'; execWrite( "UPDATE pg_catalog.dbms_scheduler_window " "SET active = true, manual_duration = COALESCE($2, duration) " "WHERE lower(window_name) = lower($1)", 2, argtypes, values, nulls); upsertSchedulerAttr("current_open_window", window_name); } void Catalog::openWindow(const char *window_name, const Interval *duration, bool force) { char *storedName; char *active; storedName = requireWindowName(window_name); logEventf("вход открытия окна", "[Window: %s]", storedName); requireKnownWindow(storedName); if (duration != NULL) requireWindowDuration(duration); if (!windowFlag(storedName, "enabled")) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("window \"%s\" is disabled", storedName))); } active = activeWindowName(); if (active != NULL && pg_strcasecmp(active, storedName) != 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("window \"%s\" is currently open", active))); } if (force && active != NULL && pg_strcasecmp(active, storedName) != 0) clearOpenWindow(); markWindowOpen(storedName, duration); rudb_scheduler_wakeup(); logEventf("окно открыто", "[Status: OK, Window: %s]", storedName); } void Catalog::closeWindow(const char *window_name) { char *storedName; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; storedName = requireWindowName(window_name); logEventf("вход закрытия окна", "[Window: %s]", storedName); requireKnownWindow(storedName); if (!windowFlag(storedName, "active")) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("window \"%s\" is not open", storedName))); } values[0] = CStringGetTextDatum(storedName); execWrite( "UPDATE pg_catalog.dbms_scheduler_window " "SET active = false, manual_duration = NULL " "WHERE lower(window_name) = lower($1)", 1, argtypes, values, nulls); upsertSchedulerAttr("current_open_window", NULL); logEventf("окно закрыто", "[Status: OK, Window: %s]", storedName); } static void dropOneWindow(const char *window_name, bool force) { char *storedName; Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; storedName = requireWindowName(window_name); requireKnownWindow(storedName); if (windowFlag(storedName, "active")) { if (!force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("window \"%s\" is currently open", storedName))); } Catalog::closeWindow(storedName); } values[0] = CStringGetTextDatum(storedName); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_window " "WHERE lower(window_name) = lower($1)", 1, argtypes, values, nulls); } void Catalog::dropWindow(const char *window_name, bool force) { char *copy; char *cursor; if (window_name == NULL || window_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("WINDOW_NAME cannot be NULL"))); } logEventf("вход удаления окна", "[Window: %s, Force: %s]", window_name, force ? "true" : "false"); copy = pstrdup(window_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); dropOneWindow(name, force); pfree(name); if (comma == NULL) break; cursor = comma + 1; } logEventf("окно удалено из каталога", "[Status: OK, Window: %s]", window_name); } static char * selectText(const char *sql, int nargs, Oid *argtypes, Datum *values, const char *nulls) { MemoryContext caller = CurrentMemoryContext; char *result = NULL; int rc; bool isnull = false; spiConnect(); rc = SPI_execute_with_args(sql, nargs, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) result = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); return result; } static void requireChainInterval(const Interval *span) { int64 usec; if (span == NULL) return; if (span->month != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid evaluation_interval"))); } usec = span->time + (int64) span->day * USECS_PER_DAY; if (usec < USECS_PER_MINUTE || usec > USECS_PER_DAY) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid evaluation_interval"))); } } static char * requireChainName(const char *chain_name) { if (chain_name == NULL || chain_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CHAIN_NAME cannot be NULL"))); } if (strlen(chain_name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("chain name is longer than %d bytes", NAME_MAX_BYTES))); } return upperCopy(chain_name); } static char * requireChainPart(const char *part, const char *label) { if (part == NULL || part[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s cannot be NULL", label))); } if (strlen(part) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s is longer than %d bytes", label, NAME_MAX_BYTES))); } return upperCopy(part); } static bool chainExists(const char *owner, const char *chain_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_chain " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, argtypes, values, nulls); } static void requireKnownChain(const char *owner, const char *chain_name) { if (!chainExists(owner, chain_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("chain \"%s\" does not exist", chain_name))); } } static void skipChainSpaces(const char **cursor) { while (**cursor == ' ' || **cursor == '\t') (*cursor)++; } static void readChainToken(const char **cursor, char *buf, int buflen) { int count = 0; bool quoted = false; skipChainSpaces(cursor); if (**cursor == '"') { quoted = true; (*cursor)++; } while (**cursor != '\0' && count < buflen - 1) { char ch = **cursor; if (quoted) { if (ch == '"') break; } else if (ch == ' ' || ch == '\t' || ch == ',') { break; } if (ch >= 'a' && ch <= 'z') ch = (char) (ch - 'a' + 'A'); buf[count++] = ch; (*cursor)++; } if (count >= buflen - 1 && **cursor != '\0' && **cursor != ' ' && **cursor != '\t' && **cursor != ',' && !(quoted && **cursor == '"')) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } if (quoted) { if (**cursor != '"') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } (*cursor)++; } buf[count] = '\0'; } static bool chainTokenPending(const char *cursor) { skipChainSpaces(&cursor); return cursor[0] != '\0'; } static bool digitsOnly(const char *text) { if (text == NULL || text[0] == '\0') return false; for (; *text != '\0'; text++) { if (*text < '0' || *text > '9') return false; } return true; } static bool clockDelay(const char *text) { return text != NULL && strlen(text) == 8 && text[2] == ':' && text[5] == ':' && digitsOnly(text) == false && text[0] >= '0' && text[0] <= '9' && text[1] >= '0' && text[1] <= '9' && text[3] >= '0' && text[3] <= '9' && text[4] >= '0' && text[4] <= '9' && text[6] >= '0' && text[6] <= '9' && text[7] >= '0' && text[7] <= '9'; } static void appendQuotedSteps(StringInfo out, const char **cursor) { bool first = true; for (;;) { char name[NAMEDATALEN]; skipChainSpaces(cursor); if (**cursor == '\0') break; if (**cursor == ',') { (*cursor)++; skipChainSpaces(cursor); } if (**cursor == '\0') break; readChainToken(cursor, name, sizeof(name)); if (name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } if (!first) appendStringInfoChar(out, ','); appendStringInfo(out, "\"%s\"", name); first = false; skipChainSpaces(cursor); if (**cursor != ',' && **cursor != '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } } if (first) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } } static char * normalizeChainAction(const char *action) { char *trimmed; const char *cursor; char keyword[NAMEDATALEN]; StringInfoData buf; char *result; if (action == NULL || action[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } trimmed = trimClassName(action); cursor = trimmed; readChainToken(&cursor, keyword, sizeof(keyword)); initStringInfo(&buf); if (strcmp(keyword, "START") == 0 || strcmp(keyword, "STOP") == 0) { appendStringInfo(&buf, "%s ", keyword); appendQuotedSteps(&buf, &cursor); } else if (strcmp(keyword, "END") == 0) { if (!chainTokenPending(cursor)) { appendStringInfoString(&buf, "END "); } else { char code[NAMEDATALEN]; readChainToken(&cursor, code, sizeof(code)); if (!digitsOnly(code) || chainTokenPending(cursor)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } appendStringInfo(&buf, "END %s", code); } } else if (strcmp(keyword, "AFTER") == 0) { char delay[NAMEDATALEN]; char next[NAMEDATALEN]; readChainToken(&cursor, delay, sizeof(delay)); readChainToken(&cursor, next, sizeof(next)); if (!clockDelay(delay) || strcmp(next, "START") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } appendStringInfo(&buf, "AFTER %s START ", delay); appendQuotedSteps(&buf, &cursor); } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain action"))); } result = pstrdup(buf.data); pfree(buf.data); return result; } static char * storedProgramName(const char *owner, const char *program_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; char *found; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); found = selectText( "SELECT program_name FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2)", 2, argtypes, values, nulls); if (found != NULL) return found; return upperCopy(program_name); } static bool chainStepExists(const char *owner, const char *chain_name, const char *step_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(step_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", 3, argtypes, values, nulls); } static bool chainRuleExists(const char *owner, const char *chain_name, const char *rule_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(rule_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_chain_rule " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(rule_name) = lower($3)", 3, argtypes, values, nulls); } static char * generatedRuleName(const char *owner, const char *chain_name) { int number = 1; for (;;) { char candidate[NAMEDATALEN]; snprintf(candidate, sizeof(candidate), "SCHED_RULE$%d", number); if (!chainRuleExists(owner, chain_name, candidate)) return pstrdup(candidate); number++; } } void Catalog::createChain(const char *chain_name, const char *rule_set_name, const Interval *evaluation_interval, const char *comments) { char *storedName; char *storedRuleSet; const char *owner; Oid argtypes[5] = {TEXTOID, TEXTOID, TEXTOID, INTERVALOID, TEXTOID}; Datum values[5]; char nulls[5] = {' ', ' ', 'n', 'n', 'n'}; storedName = requireChainName(chain_name); logEventf("вход создания цепочки", "[Chain: %s]", storedName); requireChainInterval(evaluation_interval); owner = currentOwner(); if (chainExists(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("chain \"%s\" already exists", storedName))); } storedRuleSet = upperCopy(rule_set_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); if (storedRuleSet != NULL) { values[2] = CStringGetTextDatum(storedRuleSet); nulls[2] = ' '; } if (evaluation_interval != NULL) { values[3] = IntervalPGetDatum(evaluation_interval); nulls[3] = ' '; } if (comments != NULL) { values[4] = CStringGetTextDatum(comments); nulls[4] = ' '; } execWrite( "INSERT INTO pg_catalog.dbms_scheduler_chain " "(owner, chain_name, rule_set_name, evaluation_interval, comments) " "VALUES ($1, $2, $3, $4, $5)", 5, argtypes, values, nulls); logEventf("цепочка создана", "[Status: OK, Chain: %s]", storedName); } static void dropOneChain(const char *owner, const char *chain_name, bool force) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; (void) force; requireKnownChain(owner, chain_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_chain_rule " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_chain " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, argtypes, values, nulls); } void Catalog::dropChain(const char *chain_name, bool force) { char *copy; char *cursor; const char *owner; if (chain_name == NULL || chain_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CHAIN_NAME cannot be NULL"))); } logEventf("вход удаления цепочки", "[Chain: %s, Force: %s]", chain_name, force ? "true" : "false"); owner = currentOwner(); copy = pstrdup(chain_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; char *stored; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); stored = requireChainName(name); dropOneChain(owner, stored, force); pfree(name); if (comma == NULL) break; cursor = comma + 1; } logEventf("цепочка удалена", "[Status: OK, Chain: %s]", chain_name); } void Catalog::defineChainStep(const char *chain_name, const char *step_name, const char *program_name) { char *storedChain; char *storedStep; char *storedProgram; const char *owner; Oid argtypes[5] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID}; Datum values[5]; char nulls[5] = {' ', ' ', ' ', ' ', ' '}; storedChain = requireChainName(chain_name); logEventf("вход шага цепочки", "[Chain: %s]", storedChain); owner = currentOwner(); requireKnownChain(owner, storedChain); storedStep = requireChainPart(step_name, "STEP_NAME"); if (program_name == NULL || program_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("PROGRAM_NAME cannot be NULL"))); } storedProgram = storedProgramName(owner, program_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedChain); values[2] = CStringGetTextDatum(storedStep); values[3] = CStringGetTextDatum(storedProgram); values[4] = CStringGetTextDatum("PROGRAM"); if (chainStepExists(owner, storedChain, storedStep)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_chain_step " "SET program_name = $4, step_type = $5, " "event_schedule_name = NULL, event_condition = NULL, " "queue_name = NULL, timeout = NULL " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", 5, argtypes, values, nulls); } else { execWrite( "INSERT INTO pg_catalog.dbms_scheduler_chain_step " "(owner, chain_name, step_name, program_name, step_type) " "VALUES ($1, $2, $3, $4, $5)", 5, argtypes, values, nulls); } logEventf("шаг цепочки записан", "[Status: OK, Step: %s]", storedStep); } static void dropOneChainStep(const char *owner, const char *chain_name, const char *step_name, bool force) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; (void) force; requireKnownChain(owner, chain_name); if (!chainStepExists(owner, chain_name, step_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("chain step \"%s\" does not exist", step_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(step_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", 3, argtypes, values, nulls); } void Catalog::dropChainStep(const char *chain_name, const char *step_name, bool force) { char *storedChain; char *copy; char *cursor; const char *owner; storedChain = requireChainName(chain_name); if (step_name == NULL || step_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("STEP_NAME cannot be NULL"))); } logEventf("вход удаления шага цепочки", "[Chain: %s, Force: %s]", storedChain, force ? "true" : "false"); owner = currentOwner(); copy = pstrdup(step_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; char *stored; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); stored = requireChainPart(name, "STEP_NAME"); dropOneChainStep(owner, storedChain, stored, force); pfree(name); if (comma == NULL) break; cursor = comma + 1; } logEventf("шаг цепочки удалён", "[Status: OK, Chain: %s]", storedChain); } void Catalog::defineChainRule(const char *chain_name, const char *condition, const char *action, const char *rule_name, const char *comments) { char *storedChain; char *storedRule; char *storedAction; const char *owner; bool freshName = false; Oid argtypes[6] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID}; Datum values[6]; char nulls[6] = {' ', ' ', ' ', ' ', ' ', 'n'}; storedChain = requireChainName(chain_name); logEventf("вход правила цепочки", "[Chain: %s]", storedChain); if (condition == NULL || condition[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CONDITION cannot be NULL"))); } storedAction = normalizeChainAction(action); owner = currentOwner(); requireKnownChain(owner, storedChain); if (rule_name == NULL || rule_name[0] == '\0') { storedRule = generatedRuleName(owner, storedChain); freshName = true; } else { storedRule = requireChainPart(rule_name, "RULE_NAME"); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedChain); values[2] = CStringGetTextDatum(storedRule); values[3] = CStringGetTextDatum(condition); values[4] = CStringGetTextDatum(storedAction); if (comments != NULL) { values[5] = CStringGetTextDatum(comments); nulls[5] = ' '; } if (!freshName && chainRuleExists(owner, storedChain, storedRule)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_chain_rule " "SET condition = $4, action = $5, comments = $6 " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(rule_name) = lower($3)", 6, argtypes, values, nulls); } else { execWrite( "INSERT INTO pg_catalog.dbms_scheduler_chain_rule " "(owner, chain_name, rule_name, condition, action, comments) " "VALUES ($1, $2, $3, $4, $5, $6)", 6, argtypes, values, nulls); } logEventf("правило цепочки записано", "[Status: OK, Rule: %s]", storedRule); } static void dropOneChainRule(const char *owner, const char *chain_name, const char *rule_name, bool force) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; (void) force; requireKnownChain(owner, chain_name); if (!chainRuleExists(owner, chain_name, rule_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("chain rule \"%s\" does not exist", rule_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(rule_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_chain_rule " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(rule_name) = lower($3)", 3, argtypes, values, nulls); } void Catalog::dropChainRule(const char *chain_name, const char *rule_name, bool force) { char *storedChain; char *storedRule; const char *owner; storedChain = requireChainName(chain_name); storedRule = requireChainPart(rule_name, "RULE_NAME"); logEventf("вход удаления правила цепочки", "[Chain: %s, Force: %s]", storedChain, force ? "true" : "false"); owner = currentOwner(); dropOneChainRule(owner, storedChain, storedRule, force); logEventf("правило цепочки удалено", "[Status: OK, Rule: %s]", storedRule); } static const int CHAIN_STEP_MAX = 64; static const int CHAIN_RULE_MAX = 64; struct ChainStepWork { char *name; char *program; bool skip; bool pause; bool pauseBefore; bool origSkip; bool origPause; bool origPauseBefore; bool requested; char state[16]; }; struct ChainRuleWork { char *condition; char *action; }; static bool chainIsEnabled(const char *owner, const char *chain_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; bool enabled = false; int rc; bool isnull = false; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); spiConnect(); rc = SPI_execute_with_args( "SELECT enabled FROM pg_catalog.dbms_scheduler_chain " "WHERE owner = $1 AND lower(chain_name) = lower($2)", 2, argtypes, values, nulls, true, 1); if (rc == SPI_OK_SELECT && SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) enabled = DatumGetBool(value); } SPI_finish(); return enabled; } static char * jobStateOf(const char *owner, const char *job_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); return selectText( "SELECT state FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); } static const char * chainBoolColumn(const char *attribute) { char *key = upperCopy(attribute); if (key != NULL && strcmp(key, "PAUSE") == 0) return "pause"; if (key != NULL && strcmp(key, "PAUSE_BEFORE") == 0) return "pause_before"; if (key != NULL && strcmp(key, "SKIP") == 0) return "skip"; if (key != NULL && strcmp(key, "RESTART_ON_FAILURE") == 0) return "restart_on_failure"; if (key != NULL && strcmp(key, "RESTART_ON_RECOVERY") == 0) return "restart_on_recovery"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain attribute"))); return NULL; } static const char * chainTextColumn(const char *attribute) { char *key = upperCopy(attribute); if (key != NULL && strcmp(key, "CREDENTIAL_NAME") == 0) return "credential_name"; if (key != NULL && strcmp(key, "DESTINATION_NAME") == 0) return "destination_name"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid chain attribute"))); return NULL; } static void alterChainSteps(const char *chain_name, const char *step_name, const char *column, Datum value, Oid valueType) { char *storedChain; char *copy; char *cursor; const char *owner; char sql[256]; storedChain = requireChainName(chain_name); if (step_name == NULL || step_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("STEP_NAME cannot be NULL"))); } owner = currentOwner(); requireKnownChain(owner, storedChain); snprintf(sql, sizeof(sql), "UPDATE pg_catalog.dbms_scheduler_chain_step SET %s = $4 " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", column); copy = pstrdup(step_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; char *stored; Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, valueType}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); stored = requireChainPart(name, "STEP_NAME"); if (!chainStepExists(owner, storedChain, stored)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("chain step \"%s\" does not exist", stored))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedChain); values[2] = CStringGetTextDatum(stored); values[3] = value; execWrite(sql, 4, argtypes, values, nulls); pfree(name); if (comma == NULL) break; cursor = comma + 1; } } void Catalog::alterChain(const char *chain_name, const char *step_name, const char *attribute, bool value) { const char *column; column = chainBoolColumn(attribute); logEventf("вход изменения шага цепочки", "[Chain: %s]", chain_name == NULL ? "-" : chain_name); alterChainSteps(chain_name, step_name, column, BoolGetDatum(value), BOOLOID); logEventf("шаг цепочки изменён", "[Status: OK, Attribute: %s]", column); } void Catalog::alterChainText(const char *chain_name, const char *step_name, const char *attribute, const char *char_value) { const char *column; char *storedChain; char *storedStep; const char *owner; Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', 'n'}; char sql[256]; column = chainTextColumn(attribute); logEventf("вход изменения шага цепочки", "[Chain: %s]", chain_name == NULL ? "-" : chain_name); storedChain = requireChainName(chain_name); storedStep = requireChainPart(step_name, "STEP_NAME"); owner = currentOwner(); requireKnownChain(owner, storedChain); if (!chainStepExists(owner, storedChain, storedStep)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("chain step \"%s\" does not exist", storedStep))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedChain); values[2] = CStringGetTextDatum(storedStep); if (char_value != NULL) { values[3] = CStringGetTextDatum(upperCopy(char_value)); nulls[3] = ' '; } snprintf(sql, sizeof(sql), "UPDATE pg_catalog.dbms_scheduler_chain_step SET %s = $4 " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", column); execWrite(sql, 4, argtypes, values, nulls); logEventf("шаг цепочки изменён", "[Status: OK, Attribute: %s]", column); } static void requireRunningChainJob(const char *job_name) { const char *owner; char *state; requireName(job_name); owner = currentOwner(); state = jobStateOf(owner, job_name); if (state == NULL || strcmp(state, "RUNNING") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job \"%s\" is not running", job_name))); } } void Catalog::alterRunningChain(const char *job_name, const char *step_name, const char *attribute, bool value) { const char *owner; const char *column; char *chainName; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; logEventf("вход изменения бегущей цепочки", "[Job: %s]", job_name == NULL ? "-" : job_name); requireRunningChainJob(job_name); column = chainBoolColumn(attribute); owner = currentOwner(); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); chainName = selectText( "SELECT job_action FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2 AND job_type = 'CHAIN'", 2, argtypes, values, nulls); if (chainName != NULL && step_name != NULL && step_name[0] != '\0') alterChainSteps(chainName, step_name, column, BoolGetDatum(value), BOOLOID); logEventf("бегущая цепочка изменена", "[Status: OK, Job: %s]", job_name); } void Catalog::alterRunningChainText(const char *job_name, const char *step_name, const char *attribute, const char *char_value) { (void) step_name; (void) attribute; (void) char_value; logEventf("вход изменения бегущей цепочки", "[Job: %s]", job_name == NULL ? "-" : job_name); requireRunningChainJob(job_name); logEventf("бегущая цепочка изменена", "[Status: OK, Job: %s]", job_name); } void Catalog::evaluateRunningChain(const char *job_name) { logEventf("вход проверки правил цепочки", "[Job: %s]", job_name == NULL ? "-" : job_name); requireRunningChainJob(job_name); logEventf("правила цепочки проверены", "[Status: OK, Job: %s]", job_name); } void Catalog::endDetachedJobRun(const char *job_name, int32 error_number, const char *additional_info) { const char *owner; char *state; (void) additional_info; requireName(job_name); logEventf("вход завершения отделённого запуска", "[Job: %s, Error: %d]", job_name, error_number); owner = currentOwner(); state = jobStateOf(owner, job_name); if (state == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("job \"%s\" does not exist", job_name))); } if (strcmp(state, "RUNNING") != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job \"%s\" is not running", job_name))); } ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job \"%s\" is not detached", job_name))); } void Catalog::runChain(const char *chain_name, const char *start_steps, const char *job_name) { char *storedChain; const char *owner; char *jobName; Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', 'n'}; storedChain = requireChainName(chain_name); logEventf("вход запуска цепочки", "[Chain: %s]", storedChain); owner = currentOwner(); requireKnownChain(owner, storedChain); if (!chainIsEnabled(owner, storedChain)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("chain \"%s\" is disabled", storedChain))); } if (job_name == NULL || job_name[0] == '\0') { char prefix[32]; snprintf(prefix, sizeof(prefix), "RUN_CHAIN$_%.8s", storedChain); jobName = generateJobName(prefix); } else { requireName(job_name); jobName = pstrdup(job_name); } createJob(jobName, "CHAIN", storedChain, 0, true, 0, NULL, true, 0, NULL, false, true, NULL, NULL, NULL, NULL); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(jobName); if (start_steps != NULL && start_steps[0] != '\0') { values[2] = CStringGetTextDatum(start_steps); nulls[2] = ' '; } execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET chain_start_steps = $3, enabled = true, state = 'SCHEDULED', " " next_run_date = clock_timestamp() " "WHERE owner = $1 AND job_name = $2", 3, argtypes, values, nulls); rudb_scheduler_wakeup(); logEventf("цепочка поставлена в очередь", "[Status: OK, Job: %s]", jobName); } static int loadChainWork(const char *owner, const char *chain_name, ChainStepWork *steps, ChainRuleWork *rules, int *nrules) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; MemoryContext caller = CurrentMemoryContext; int nsteps = 0; int rc; int i; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); spiConnect(); rc = SPI_execute_with_args( "SELECT step_name, program_name, skip, pause, pause_before " "FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "ORDER BY step_name", 2, argtypes, values, nulls, true, 0); if (rc == SPI_OK_SELECT) { nsteps = (int) SPI_processed; if (nsteps > CHAIN_STEP_MAX) nsteps = CHAIN_STEP_MAX; for (i = 0; i < nsteps; i++) { bool isnull = false; Datum value; value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); steps[i].name = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull); steps[i].program = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 3, &isnull); steps[i].skip = !isnull && DatumGetBool(value); value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 4, &isnull); steps[i].pause = !isnull && DatumGetBool(value); value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 5, &isnull); steps[i].pauseBefore = !isnull && DatumGetBool(value); steps[i].origSkip = steps[i].skip; steps[i].origPause = steps[i].pause; steps[i].origPauseBefore = steps[i].pauseBefore; steps[i].requested = false; snprintf(steps[i].state, sizeof(steps[i].state), "NOT_STARTED"); } } SPI_finish(); *nrules = 0; spiConnect(); rc = SPI_execute_with_args( "SELECT condition, action FROM pg_catalog.dbms_scheduler_chain_rule " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "ORDER BY rule_name", 2, argtypes, values, nulls, true, 0); if (rc == SPI_OK_SELECT) { int count = (int) SPI_processed; if (count > CHAIN_RULE_MAX) count = CHAIN_RULE_MAX; for (i = 0; i < count; i++) { bool isnull = false; Datum value; value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); rules[i].condition = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull); rules[i].action = MemoryContextStrdup(caller, TextDatumGetCString(value)); } *nrules = count; } SPI_finish(); return nsteps; } static bool chainWordMatches(const char *state, const char *word) { char *upper = upperCopy(word); if (upper == NULL) return false; if (strcmp(upper, "SUCCEEDED") == 0) return strcmp(state, "SUCCEEDED") == 0; if (strcmp(upper, "FAILED") == 0) return strcmp(state, "FAILED") == 0; if (strcmp(upper, "STOPPED") == 0) return strcmp(state, "STOPPED") == 0; if (strcmp(upper, "COMPLETED") == 0) return strcmp(state, "SUCCEEDED") == 0 || strcmp(state, "FAILED") == 0 || strcmp(state, "STOPPED") == 0; return false; } static bool chainConditionHolds(const char *condition, ChainStepWork *steps, int nsteps) { char *copy; char *cursor; char *word; int i; if (condition == NULL) return false; copy = pstrdup(condition); cursor = copy; while (*cursor == ' ' || *cursor == '\t') cursor++; word = cursor + strlen(cursor); while (word > cursor && (word[-1] == ' ' || word[-1] == '\t')) *--word = '\0'; if (pg_strcasecmp(cursor, "TRUE") == 0) return true; word = strrchr(cursor, ' '); if (word == NULL) return false; *word = '\0'; word++; while (*cursor == ' ' || *cursor == '\t') cursor++; for (i = 0; i < nsteps; i++) { if (pg_strcasecmp(steps[i].name, cursor) == 0) return chainWordMatches(steps[i].state, word); } return false; } static void requestChainSteps(ChainStepWork *steps, int nsteps, const char *list) { const char *cursor = list; if (list == NULL) return; while (*cursor != '\0') { char name[NAMEDATALEN]; int count = 0; int i; while (*cursor == ' ' || *cursor == '\t' || *cursor == ',' || *cursor == '"') cursor++; if (*cursor == '\0') break; while (*cursor != '\0' && *cursor != '"' && *cursor != ',' && count < NAMEDATALEN - 1) name[count++] = *cursor++; name[count] = '\0'; if (*cursor == '"') cursor++; for (i = 0; i < nsteps; i++) { if (pg_strcasecmp(steps[i].name, name) == 0 && strcmp(steps[i].state, "NOT_STARTED") == 0) steps[i].requested = true; } } } static int applyChainRules(ChainStepWork *steps, int nsteps, ChainRuleWork *rules, int nrules) { int i; for (i = 0; i < nrules; i++) { const char *action; if (!chainConditionHolds(rules[i].condition, steps, nsteps)) continue; action = rules[i].action; if (action == NULL) continue; if (strncmp(action, "END", 3) == 0 && (action[3] == '\0' || action[3] == ' ')) { const char *code = action + 3; while (*code == ' ') code++; if (*code == '\0' || strcmp(code, "0") == 0) return 1; return 2; } if (strncmp(action, "START ", 6) == 0) requestChainSteps(steps, nsteps, action + 6); else if (strncmp(action, "STOP ", 5) == 0) { int stepIndex; for (stepIndex = 0; stepIndex < nsteps; stepIndex++) { if (strcmp(steps[stepIndex].state, "NOT_STARTED") != 0) continue; if (strstr(action + 5, steps[stepIndex].name) != NULL) snprintf(steps[stepIndex].state, sizeof(steps[stepIndex].state), "STOPPED"); } } } return 0; } static bool runChainProgram(const char *owner, const char *program_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; char *programType = NULL; char *programAction = NULL; char *sqlText; MemoryContext caller = CurrentMemoryContext; int rc; bool isnull = false; bool ok = false; volatile bool spiOpen = false; MemoryContext oldContext; ResourceOwner oldOwner; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(program_name); spiConnect(); rc = SPI_execute_with_args( "SELECT program_type, program_action FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2)", 2, argtypes, values, nulls, true, 1); if (rc == SPI_OK_SELECT && SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) programType = MemoryContextStrdup(caller, TextDatumGetCString(value)); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); if (!isnull) programAction = MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); if (programType == NULL) return false; sqlText = jobActionSql(programType, programAction, NULL, 0); oldContext = CurrentMemoryContext; oldOwner = CurrentResourceOwner; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldContext); PG_TRY(); { spiConnect(); spiOpen = true; rc = SPI_execute(sqlText, false, 0); SPI_finish(); spiOpen = false; if (rc < 0) ereport(ERROR, (errmsg("dbms_scheduler: шаг цепочки не выполнен"))); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; ok = true; } PG_CATCH(); { MemoryContextSwitchTo(oldContext); FlushErrorState(); if (spiOpen) SPI_finish(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; ok = false; } PG_END_TRY(); return ok; } static void noteChainStep(const char *owner, const char *job_name, const char *step_name, const char *status) { Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = CStringGetTextDatum(status); values[3] = CStringGetTextDatum(step_name); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_run " "(owner, job_name, log_date, status, step_name, pid) " "VALUES ($1, $2, clock_timestamp(), $3, $4, pg_backend_pid())", 4, argtypes, values, nulls); } static void refreshChainStepFlags(const char *owner, const char *chain_name, ChainStepWork *step) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; int rc; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(step->name); PushActiveSnapshot(GetLatestSnapshot()); spiConnect(); rc = SPI_execute_with_args( "SELECT skip, pause, pause_before " "FROM pg_catalog.dbms_scheduler_chain_step " "WHERE owner = $1 AND lower(chain_name) = lower($2) " " AND lower(step_name) = lower($3)", 3, argtypes, values, nulls, true, 1); if (rc == SPI_OK_SELECT && SPI_processed == 1) { bool isnull = false; Datum value; value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); step->skip = !isnull && DatumGetBool(value); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull); step->pause = !isnull && DatumGetBool(value); value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull); step->pauseBefore = !isnull && DatumGetBool(value); } SPI_finish(); PopActiveSnapshot(); } static void restoreChainStepFlags(const char *owner, const char *chain_name, ChainStepWork *steps, int nsteps) { int i; for (i = 0; i < nsteps; i++) { Oid argtypes[6] = {TEXTOID, TEXTOID, TEXTOID, BOOLOID, BOOLOID, BOOLOID}; Datum values[6]; char nulls[6] = {' ', ' ', ' ', ' ', ' ', ' '}; refreshChainStepFlags(owner, chain_name, &steps[i]); if (steps[i].skip == steps[i].origSkip && steps[i].pause == steps[i].origPause && steps[i].pauseBefore == steps[i].origPauseBefore) continue; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(steps[i].name); values[3] = BoolGetDatum(steps[i].origSkip); values[4] = BoolGetDatum(steps[i].origPause); values[5] = BoolGetDatum(steps[i].origPauseBefore); PushActiveSnapshot(GetLatestSnapshot()); execWrite( "UPDATE pg_catalog.dbms_scheduler_chain_step " "SET skip = $4, pause = $5, pause_before = $6 " "WHERE owner = $1 AND lower(chain_name) = lower($2) " " AND lower(step_name) = lower($3)", 6, argtypes, values, nulls); PopActiveSnapshot(); } } bool Catalog::executeChain(const char *owner, const char *job_name, const char *chain_name) { ChainStepWork steps[CHAIN_STEP_MAX]; ChainRuleWork rules[CHAIN_RULE_MAX]; int nsteps; int nrules = 0; int pass; int endCode; char *startList; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; bool failed = false; if (!chainIsEnabled(owner, chain_name)) return false; nsteps = loadChainWork(owner, chain_name, steps, rules, &nrules); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); startList = selectText( "SELECT chain_start_steps FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND job_name = $2", 2, argtypes, values, nulls); if (startList != NULL) requestChainSteps(steps, nsteps, startList); else { endCode = applyChainRules(steps, nsteps, rules, nrules); if (endCode == 1) { restoreChainStepFlags(owner, chain_name, steps, nsteps); return true; } if (endCode == 2) { restoreChainStepFlags(owner, chain_name, steps, nsteps); return false; } } for (pass = 0; pass < CHAIN_STEP_MAX; pass++) { bool ran = false; int i; for (i = 0; i < nsteps; i++) { if (!steps[i].requested || strcmp(steps[i].state, "NOT_STARTED") != 0) continue; refreshChainStepFlags(owner, chain_name, &steps[i]); if (steps[i].skip) snprintf(steps[i].state, sizeof(steps[i].state), "SUCCEEDED"); else if (steps[i].pauseBefore) snprintf(steps[i].state, sizeof(steps[i].state), "PAUSED"); else if (runChainProgram(owner, steps[i].program)) { refreshChainStepFlags(owner, chain_name, &steps[i]); snprintf(steps[i].state, sizeof(steps[i].state), "SUCCEEDED"); } else snprintf(steps[i].state, sizeof(steps[i].state), "FAILED"); if (steps[i].pause && strcmp(steps[i].state, "SUCCEEDED") == 0) snprintf(steps[i].state, sizeof(steps[i].state), "PAUSED"); noteChainStep(owner, job_name, steps[i].name, steps[i].state); ran = true; } endCode = applyChainRules(steps, nsteps, rules, nrules); if (endCode == 1) { restoreChainStepFlags(owner, chain_name, steps, nsteps); return true; } if (endCode == 2) { restoreChainStepFlags(owner, chain_name, steps, nsteps); return false; } if (!ran) break; } for (pass = 0; pass < nsteps; pass++) { if (strcmp(steps[pass].state, "FAILED") == 0) failed = true; } restoreChainStepFlags(owner, chain_name, steps, nsteps); return !failed; } bool executeClaimedChain(const char *owner, const char *job_name, const char *chain_name) { return Catalog::executeChain(owner, job_name, chain_name); } __attribute__((unused)) static void notSupported(const char *method) { logEventf("вход неподдержанного метода", "[Method: %s]", method == NULL ? "-" : method); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s is not supported", method), errdetail_internal("Output: [Status: UNSUPPORTED]"))); } static bool credentialExists(const char *owner, const char *credential_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(credential_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2)", 2, argtypes, values, nulls); } static int32 credentialRefs(const char *owner, const char *credential_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(credential_name); return selectInt32( "SELECT ((SELECT COUNT(*) FROM pg_catalog.dbms_scheduler_job " " WHERE owner = $1 AND lower(credential_name) = lower($2)) " " + (SELECT COUNT(*) FROM pg_catalog.dbms_scheduler_chain_step " " WHERE owner = $1 AND lower(credential_name) = lower($2)))::integer", 2, argtypes, values, nulls); } static const char * canonicalDatabaseRole(const char *database_role) { if (database_role == NULL || database_role[0] == '\0') return NULL; if (pg_strcasecmp(database_role, "SYSDBA") == 0) return "SYSDBA"; if (pg_strcasecmp(database_role, "SYSOPER") == 0) return "SYSOPER"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid database_role \"%s\"", database_role))); return NULL; } void Catalog::createCredential(const char *credential_name, const char *username, const char *password, const char *database_role, const char *windows_domain, const char *comments) { const char *owner; const char *role; char *storedName; char *storedDomain; Oid argtypes[10]; Datum values[10]; char nulls[10]; int i; if (credential_name == NULL || credential_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CREDENTIAL_NAME cannot be NULL"))); } if (username == NULL || username[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("USERNAME cannot be NULL"))); } storedName = upperCopy(credential_name); logEventf("вход создания учётных данных", "[Name: %s, User: %s]", storedName, username); role = canonicalDatabaseRole(database_role); storedDomain = upperCopy(windows_domain); owner = currentOwner(); if (credentialExists(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("credential \"%s\" already exists", storedName))); } for (i = 0; i < 10; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } argtypes[7] = BOOLOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); values[2] = CStringGetTextDatum(username); if (password == NULL || password[0] == '\0') nulls[3] = 'n'; else values[3] = CStringGetTextDatum(password); if (role == NULL) nulls[4] = 'n'; else values[4] = CStringGetTextDatum(role); if (storedDomain == NULL) nulls[5] = 'n'; else values[5] = CStringGetTextDatum(storedDomain); if (comments == NULL) nulls[6] = 'n'; else values[6] = CStringGetTextDatum(comments); values[7] = BoolGetDatum(true); nulls[8] = 'n'; nulls[9] = 'n'; execWrite( "INSERT INTO pg_catalog.dbms_credential " "(owner, credential_name, username, password, database_role, " " windows_domain, comments, enabled, key, connect_identifier) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", 10, argtypes, values, nulls); logEventf("учётные данные записаны в каталог", "[Status: OK, Name: %s]", storedName); } void Catalog::dropCredential(const char *credential_name, bool force) { const char *owner; char *storedName; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int32 refs; if (credential_name == NULL || credential_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CREDENTIAL_NAME cannot be NULL"))); } storedName = upperCopy(credential_name); logEventf("вход удаления учётных данных", "[Name: %s, Force: %s]", storedName, force ? "true" : "false"); owner = currentOwner(); if (!credentialExists(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown credential \"%s\"", storedName))); } refs = credentialRefs(owner, storedName); if (refs > 0 && !force) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("credential \"%s\" is in use", storedName))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); execWrite( "DELETE FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2)", 2, argtypes, values, nulls); logEventf("учётные данные удалены из каталога", "[Status: OK, Name: %s]", storedName); } static bool fileWatcherExists(const char *owner, const char *file_watcher_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(file_watcher_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_file_watcher " "WHERE owner = $1 AND lower(file_watcher_name) = lower($2)", 2, argtypes, values, nulls); } static void requireSteadyState(const Interval *span) { int64 usec; if (span == NULL) return; if (span->month != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid steady_state_duration"))); } usec = span->time + (int64) span->day * USECS_PER_DAY; if (usec < 10 * USECS_PER_SEC || usec > (int64) 3600 * USECS_PER_SEC) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid steady_state_duration"))); } } static void storeChainEventStep(const char *owner, const char *chain_name, const char *step_name, const char *step_type, const char *schedule_name, const char *condition, const char *queue_name, const Interval *timeout) { Oid argtypes[8]; Datum values[8]; char nulls[8]; int i; for (i = 0; i < 8; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } argtypes[7] = INTERVALOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(chain_name); values[2] = CStringGetTextDatum(step_name); values[3] = CStringGetTextDatum(step_type); if (schedule_name == NULL) nulls[4] = 'n'; else values[4] = CStringGetTextDatum(schedule_name); if (condition == NULL) nulls[5] = 'n'; else values[5] = CStringGetTextDatum(condition); if (queue_name == NULL) nulls[6] = 'n'; else values[6] = CStringGetTextDatum(queue_name); if (timeout == NULL) nulls[7] = 'n'; else values[7] = IntervalPGetDatum(timeout); if (chainStepExists(owner, chain_name, step_name)) { execWrite( "UPDATE pg_catalog.dbms_scheduler_chain_step " "SET program_name = NULL, step_type = $4, " "event_schedule_name = $5, event_condition = $6, " "queue_name = $7, timeout = $8 " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "AND lower(step_name) = lower($3)", 8, argtypes, values, nulls); } else { execWrite( "INSERT INTO pg_catalog.dbms_scheduler_chain_step " "(owner, chain_name, step_name, step_type, event_schedule_name, " " event_condition, queue_name, timeout) " "VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", 8, argtypes, values, nulls); } } void Catalog::createFileWatcher(const char *file_watcher_name, const char *directory_path, const char *file_name, const char *credential_name, const char *destination, int32 min_file_size, const Interval *steady_state_duration, const char *comments, bool enabled) { const char *owner; char *storedName; char *storedCred; const char *storedDest; Oid argtypes[10]; Datum values[10]; char nulls[10]; int i; if (file_watcher_name == NULL || file_watcher_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("FILE_WATCHER_NAME cannot be NULL"))); } if (directory_path == NULL || directory_path[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("DIRECTORY_PATH cannot be NULL"))); } if (file_name == NULL || file_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("FILE_NAME cannot be NULL"))); } if (credential_name == NULL || credential_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CREDENTIAL_NAME cannot be NULL"))); } if (min_file_size < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid min_file_size"))); } requireSteadyState(steady_state_duration); storedName = upperCopy(file_watcher_name); storedCred = upperCopy(credential_name); logEventf("вход создания file watcher", "[Name: %s, Credential: %s]", storedName, storedCred); owner = currentOwner(); if (!credentialExists(owner, storedCred)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown credential \"%s\"", storedCred))); } if (fileWatcherExists(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("file watcher \"%s\" already exists", storedName))); } if (destination == NULL || destination[0] == '\0') storedDest = NULL; else storedDest = destination; for (i = 0; i < 10; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } argtypes[2] = BOOLOID; argtypes[7] = INT4OID; argtypes[8] = INTERVALOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); values[2] = BoolGetDatum(enabled); if (storedDest == NULL) nulls[3] = 'n'; else values[3] = CStringGetTextDatum(storedDest); values[4] = CStringGetTextDatum(directory_path); values[5] = CStringGetTextDatum(file_name); values[6] = CStringGetTextDatum(storedCred); values[7] = Int32GetDatum(min_file_size); if (steady_state_duration == NULL) nulls[8] = 'n'; else values[8] = IntervalPGetDatum(steady_state_duration); if (comments == NULL) nulls[9] = 'n'; else values[9] = CStringGetTextDatum(comments); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_file_watcher " "(owner, file_watcher_name, enabled, destination, directory_path, " " file_name, credential_name, min_file_size, steady_state_duration, comments) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", 10, argtypes, values, nulls); logEventf("file watcher записан в каталог", "[Status: OK, Name: %s]", storedName); } static void dropOneFileWatcher(const char *owner, const char *file_watcher_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; if (!fileWatcherExists(owner, file_watcher_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown file watcher \"%s\"", file_watcher_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(file_watcher_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_file_watcher " "WHERE owner = $1 AND lower(file_watcher_name) = lower($2)", 2, argtypes, values, nulls); } void Catalog::dropFileWatcher(const char *file_watcher_name, bool force) { char *copy; char *cursor; const char *owner; if (file_watcher_name == NULL || file_watcher_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("FILE_WATCHER_NAME cannot be NULL"))); } logEventf("вход удаления file watcher", "[Name: %s, Force: %s]", file_watcher_name, force ? "true" : "false"); (void) force; owner = currentOwner(); copy = pstrdup(file_watcher_name); cursor = copy; for (;;) { char *comma = strchr(cursor, ','); char *name; char *stored; if (comma != NULL) *comma = '\0'; name = trimClassName(cursor); if (name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("FILE_WATCHER_NAME cannot be NULL"))); } stored = upperCopy(name); dropOneFileWatcher(owner, stored); pfree(name); if (comma == NULL) break; cursor = comma + 1; } logEventf("file watcher удалён", "[Status: OK, Name: %s]", file_watcher_name); } void Catalog::defineChainEventStepSchedule(const char *chain_name, const char *step_name, const char *event_schedule_name, const Interval *timeout) { char *storedChain; char *storedStep; char *storedSchedule; const char *owner; storedChain = requireChainName(chain_name); logEventf("вход шага цепочки по расписанию", "[Chain: %s]", storedChain); owner = currentOwner(); requireKnownChain(owner, storedChain); storedStep = requireChainPart(step_name, "STEP_NAME"); if (event_schedule_name == NULL || event_schedule_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EVENT_SCHEDULE_NAME cannot be NULL"))); } storedSchedule = upperCopy(event_schedule_name); storeChainEventStep(owner, storedChain, storedStep, "EVENT_SCHEDULE", storedSchedule, NULL, NULL, timeout); logEventf("шаг цепочки по расписанию записан", "[Status: OK, Step: %s]", storedStep); } void Catalog::defineChainEventStepInline(const char *chain_name, const char *step_name, const char *event_condition, const char *queue_spec, const Interval *timeout) { char *storedChain; char *storedStep; char *schema = NULL; char *queue = NULL; char *storedOwner = NULL; char *storedQueue = NULL; const char *owner; const char *storedCond; const char *stepType; const char *storedName; bool multi = false; storedChain = requireChainName(chain_name); logEventf("вход шага цепочки по очереди", "[Chain: %s]", storedChain); owner = currentOwner(); requireKnownChain(owner, storedChain); storedStep = requireChainPart(step_name, "STEP_NAME"); splitQueueSpec(queue_spec, owner, &schema, &queue); if (event_condition == NULL || event_condition[0] == '\0') storedCond = "(1=1)"; else storedCond = event_condition; if (lookupEventQueue(schema, queue, &storedOwner, &storedQueue, &multi)) { (void) storedOwner; if (!multi) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unknown or illegal event source queue"))); } stepType = "INLINE_EVENT"; storedName = storedQueue; } else if (fileWatcherExists(owner, queue)) { stepType = "INLINE_FILE_WATCHER"; storedName = upperCopy(queue); } else { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown or illegal event source queue"))); } storeChainEventStep(owner, storedChain, storedStep, stepType, NULL, storedCond, storedName, timeout); logEventf("шаг цепочки по очереди записан", "[Status: OK, Step: %s, Type: %s]", storedStep, stepType); } static int32 emailEventBit(const char *event) { if (strcmp(event, "JOB_STARTED") == 0) return 1; if (strcmp(event, "JOB_SUCCEEDED") == 0) return 2; if (strcmp(event, "JOB_FAILED") == 0) return 4; if (strcmp(event, "JOB_BROKEN") == 0) return 8; if (strcmp(event, "JOB_COMPLETED") == 0) return 16; if (strcmp(event, "JOB_STOPPED") == 0) return 32; if (strcmp(event, "JOB_SCH_LIM_REACHED") == 0) return 64; if (strcmp(event, "JOB_DISABLED") == 0) return 128; if (strcmp(event, "JOB_CHAIN_STALLED") == 0) return 256; if (strcmp(event, "JOB_OVER_MAX_DUR") == 0) return 0; return -1; } static int splitCsv(const char *text, bool fold_upper, char ***out) { int count = 1; int n = 0; const char *cursor; const char *start; char **items; for (cursor = text; *cursor != '\0'; cursor++) { if (*cursor == ',') count++; } items = (char **) palloc(sizeof(char *) * count); start = text; for (cursor = text;; cursor++) { if (*cursor == ',' || *cursor == '\0') { const char *left = start; const char *right = cursor; char *copy; size_t len; while (left < right && (*left == ' ' || *left == '\t')) left++; while (right > left && (right[-1] == ' ' || right[-1] == '\t')) right--; len = (size_t) (right - left); if (len == 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid notification list"))); } copy = pnstrdup(left, len); if (fold_upper) { char *folded = upperCopy(copy); pfree(copy); copy = folded; } items[n++] = copy; if (*cursor == '\0') break; start = cursor + 1; } } *out = items; return n; } static bool emailServerSet(void) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum("email_server"); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_global " "WHERE lower(attribute) = lower($1) " "AND value IS NOT NULL AND value <> ''", 1, argtypes, values, nulls); } static void orRaiseEvents(const char *owner, const char *job_name, int32 bits) { Oid argtypes[3] = {INT4OID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (bits == 0) return; values[0] = Int32GetDatum(bits); values[1] = CStringGetTextDatum(owner); values[2] = CStringGetTextDatum(job_name); execWrite( "UPDATE pg_catalog.dbms_scheduler_job " "SET raise_events = COALESCE(raise_events, 0) | $1 " "WHERE owner = $2 AND job_name = $3", 3, argtypes, values, nulls); } static void upsertJobEmail(const char *owner, const char *job_name, const char *recipient, const char *sender, const char *subject, const char *body, const char *event, const char *filter_condition) { Oid argtypes[8]; Datum values[8]; char nulls[8]; int i; bool exists; for (i = 0; i < 8; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = CStringGetTextDatum(recipient); if (sender == NULL || sender[0] == '\0') nulls[3] = 'n'; else values[3] = CStringGetTextDatum(sender); if (subject == NULL) nulls[4] = 'n'; else values[4] = CStringGetTextDatum(subject); if (body == NULL) nulls[5] = 'n'; else values[5] = CStringGetTextDatum(body); values[6] = CStringGetTextDatum(event); if (filter_condition == NULL || filter_condition[0] == '\0') nulls[7] = 'n'; else values[7] = CStringGetTextDatum(filter_condition); exists = selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2 " "AND lower(recipient) = lower($3) AND event = $7", 8, argtypes, values, nulls); if (exists) { execWrite( "UPDATE pg_catalog.dbms_scheduler_job_email " "SET recipient = $3, sender = $4, subject = $5, body = $6, " " filter_condition = $8 " "WHERE owner = $1 AND job_name = $2 " "AND lower(recipient) = lower($3) AND event = $7", 8, argtypes, values, nulls); return; } execWrite( "INSERT INTO pg_catalog.dbms_scheduler_job_email " "(owner, job_name, recipient, sender, subject, body, event, filter_condition) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", 8, argtypes, values, nulls); } static void deleteJobEmail(const char *owner, const char *job_name, const char *recipient, const char *event) { Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; const char *sql; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = (Datum) 0; values[3] = (Datum) 0; nulls[2] = 'n'; nulls[3] = 'n'; if (recipient == NULL && event == NULL) { sql = "DELETE FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2"; execWrite(sql, 2, argtypes, values, nulls); return; } if (recipient != NULL) { values[2] = CStringGetTextDatum(recipient); nulls[2] = ' '; } if (event != NULL) { values[3] = CStringGetTextDatum(event); nulls[3] = ' '; } if (recipient != NULL && event != NULL) { sql = "DELETE FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2 " "AND lower(recipient) = lower($3) AND event = $4"; execWrite(sql, 4, argtypes, values, nulls); return; } if (recipient != NULL) { sql = "DELETE FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2 AND lower(recipient) = lower($3)"; execWrite(sql, 3, argtypes, values, nulls); return; } sql = "DELETE FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2 AND event = $4"; execWrite(sql, 4, argtypes, values, nulls); } void Catalog::addJobEmailNotification(const char *job_name, const char *recipients, const char *sender, const char *subject, const char *body, const char *events, const char *filter_condition) { const char *owner; char **recipientList = NULL; char **eventList = NULL; int recipientCount; int eventCount; int i; int j; int32 bits = 0; requireName(job_name); logEventf("вход почтового уведомления", "[Job: %s]", job_name); if (recipients == NULL || recipients[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RECIPIENTS cannot be NULL"))); } if (events == NULL || events[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("EVENTS cannot be NULL"))); } if (!emailServerSet()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("email_server is not set"))); } owner = currentOwner(); requireJob(owner, job_name); recipientCount = splitCsv(recipients, false, &recipientList); eventCount = splitCsv(events, true, &eventList); for (j = 0; j < eventCount; j++) { int32 bit = emailEventBit(eventList[j]); if (bit < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid event \"%s\"", eventList[j]))); } bits |= bit; } for (i = 0; i < recipientCount; i++) { for (j = 0; j < eventCount; j++) { upsertJobEmail(owner, job_name, recipientList[i], sender, subject, body, eventList[j], filter_condition); } } orRaiseEvents(owner, job_name, bits); logEventf("почтовое уведомление записано", "[Status: OK, Job: %s]", job_name); } void Catalog::removeJobEmailNotification(const char *job_name, const char *recipients, const char *events) { const char *owner; char **recipientList = NULL; char **eventList = NULL; int recipientCount = 0; int eventCount = 0; int i; int j; bool allRecipients; bool allEvents; requireName(job_name); logEventf("вход снятия почтового уведомления", "[Job: %s]", job_name); allRecipients = (recipients == NULL || recipients[0] == '\0'); allEvents = (events == NULL || events[0] == '\0'); owner = currentOwner(); if (!allRecipients) recipientCount = splitCsv(recipients, false, &recipientList); if (!allEvents) eventCount = splitCsv(events, true, &eventList); if (allRecipients && allEvents) { deleteJobEmail(owner, job_name, NULL, NULL); } else if (allRecipients) { for (j = 0; j < eventCount; j++) deleteJobEmail(owner, job_name, NULL, eventList[j]); } else if (allEvents) { for (i = 0; i < recipientCount; i++) deleteJobEmail(owner, job_name, recipientList[i], NULL); } else { for (i = 0; i < recipientCount; i++) { for (j = 0; j < eventCount; j++) deleteJobEmail(owner, job_name, recipientList[i], eventList[j]); } } logEventf("почтовое уведомление снято", "[Status: OK, Job: %s]", job_name); } static const char * groupTypeCanon(const char *group_type) { if (group_type == NULL || group_type[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_TYPE cannot be NULL"))); } if (pg_strcasecmp(group_type, "WINDOW") == 0) return "WINDOW"; if (pg_strcasecmp(group_type, "DB_DEST") == 0) return "DB_DEST"; if (pg_strcasecmp(group_type, "EXTERNAL_DEST") == 0) return "EXTERNAL_DEST"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid group type %s", group_type))); return NULL; } static void parseQualified(const char *text, char **schema, char **name) { const char *dot; char *copy; char *trimmed; trimmed = trimClassName(text); dot = strchr(trimmed, '.'); if (dot == NULL) { *schema = NULL; *name = upperCopy(trimmed); pfree(trimmed); return; } copy = pnstrdup(trimmed, (size_t) (dot - trimmed)); *schema = upperCopy(copy); pfree(copy); *name = upperCopy(dot + 1); pfree(trimmed); if (*schema == NULL || *name == NULL || (*name)[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_NAME cannot be NULL"))); } } static bool groupExists(const char *owner, const char *group_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_group " "WHERE owner = $1 AND lower(group_name) = lower($2)", 2, argtypes, values, nulls); } static char * groupTypeOf(const char *owner, const char *group_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); return selectText( "SELECT group_type FROM pg_catalog.dbms_scheduler_group " "WHERE owner = $1 AND lower(group_name) = lower($2)", 2, argtypes, values, nulls); } static const char * lookupGroupOwner(const char *schema) { const char *owner; if (schema == NULL) return currentOwner(); if (strcmp(schema, "SYS") == 0) return "SYS"; owner = currentOwner(); if (pg_strcasecmp(schema, owner) == 0) return owner; ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown group \"%s\"", schema))); return NULL; } static void requireGroup(const char *owner, const char *group_name) { if (!groupExists(owner, group_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown group \"%s\"", group_name))); } } static bool memberPresent(const char *owner, const char *group_name, const char *member_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); values[2] = CStringGetTextDatum(member_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_group_member " "WHERE owner = $1 AND lower(group_name) = lower($2) AND member_name = $3", 3, argtypes, values, nulls); } static void insertMember(const char *owner, const char *group_name, const char *member_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (memberPresent(owner, group_name, member_name)) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); values[2] = CStringGetTextDatum(member_name); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_group_member " "(owner, group_name, member_name) VALUES ($1,$2,$3)", 3, argtypes, values, nulls); } static void copyGroupMembers(const char *dst_owner, const char *dst_name, const char *src_owner, const char *src_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; int rc; int i; int count; char **names; MemoryContext caller = CurrentMemoryContext; values[0] = CStringGetTextDatum(src_owner); values[1] = CStringGetTextDatum(src_name); spiConnect(); rc = SPI_execute_with_args( "SELECT member_name FROM pg_catalog.dbms_scheduler_group_member " "WHERE owner = $1 AND lower(group_name) = lower($2)", 2, argtypes, values, nulls, true, 0); if (rc != SPI_OK_SELECT) { SPI_finish(); ereport(ERROR, (errmsg("dbms_scheduler: запрос каталога не выполнен"), errdetail_internal("Output: [Status: FAIL, Code: %d]", rc))); } count = SPI_processed; names = (char **) MemoryContextAlloc(caller, sizeof(char *) * (count > 0 ? count : 1)); for (i = 0; i < count; i++) { bool isnull = false; Datum value = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull); names[i] = isnull ? NULL : MemoryContextStrdup(caller, TextDatumGetCString(value)); } SPI_finish(); for (i = 0; i < count; i++) { if (names[i] != NULL) insertMember(dst_owner, dst_name, names[i]); } } static char * windowMemberLabel(const char *window_name) { return psprintf("\"SYS\".\"%s\"", window_name); } static void addResolvedMember(const char *owner, const char *group_name, const char *group_type, const char *token) { char *upper; upper = upperCopy(token); if (upper == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("MEMBER cannot be NULL"))); } if (strcmp(group_type, "WINDOW") == 0) { if (windowExists(upper)) { insertMember(owner, group_name, windowMemberLabel(upper)); return; } if (groupExists("SYS", upper) && strcmp(upper, group_name) != 0) { char *nested = groupTypeOf("SYS", upper); if (nested != NULL && strcmp(nested, "WINDOW") == 0) { copyGroupMembers(owner, group_name, "SYS", upper); return; } } ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown window \"%s\"", upper))); } if (strcmp(upper, "LOCAL") == 0) { insertMember(owner, group_name, "LOCAL"); return; } if (groupExists(owner, upper) && strcmp(upper, group_name) != 0) { char *nested = groupTypeOf(owner, upper); if (nested != NULL && strcmp(nested, group_type) == 0) { copyGroupMembers(owner, group_name, owner, upper); return; } } ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown destination \"%s\"", upper))); } static void addMemberList(const char *owner, const char *group_name, const char *group_type, const char *member) { char **items = NULL; int count; int i; if (member == NULL || member[0] == '\0') return; count = splitCsv(member, false, &items); for (i = 0; i < count; i++) addResolvedMember(owner, group_name, group_type, items[i]); } static void rejectDestName(const char *owner, const char *group_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); if (selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND lower(job_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND lower(schedule_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2)", 2, argtypes, values, nulls)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("group \"%s\" already exists", group_name))); } } void Catalog::createGroup(const char *group_name, const char *group_type, const char *member, const char *comments) { const char *type; const char *owner; char *storedName; Oid argtypes[4]; Datum values[4]; char nulls[4]; int i; if (group_name == NULL || group_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_NAME cannot be NULL"))); } type = groupTypeCanon(group_type); storedName = upperCopy(group_name); logEventf("вход создания группы", "[Name: %s, Type: %s]", storedName, type); owner = strcmp(type, "WINDOW") == 0 ? "SYS" : currentOwner(); if (strcmp(type, "WINDOW") != 0) rejectDestName(owner, storedName); if (groupExists(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("group \"%s\" already exists", storedName))); } for (i = 0; i < 4; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); values[2] = CStringGetTextDatum(type); if (comments == NULL) nulls[3] = 'n'; else values[3] = CStringGetTextDatum(comments); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_group " "(owner, group_name, group_type, comments) VALUES ($1,$2,$3,$4)", 4, argtypes, values, nulls); addMemberList(owner, storedName, type, member); logEventf("группа записана в каталог", "[Status: OK, Name: %s, Type: %s]", storedName, type); } static void dropOneGroup(const char *ref) { char *schema = NULL; char *name = NULL; const char *owner; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; parseQualified(ref, &schema, &name); owner = lookupGroupOwner(schema); requireGroup(owner, name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_group_member " "WHERE owner = $1 AND lower(group_name) = lower($2)", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_group " "WHERE owner = $1 AND lower(group_name) = lower($2)", 2, argtypes, values, nulls); } void Catalog::dropGroup(const char *group_name, bool force) { char **items = NULL; int count; int i; (void) force; if (group_name == NULL || group_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_NAME cannot be NULL"))); } logEventf("вход удаления группы", "[Name: %s, Force: %s]", group_name, force ? "true" : "false"); count = splitCsv(group_name, false, &items); for (i = 0; i < count; i++) dropOneGroup(items[i]); logEventf("группа удалена", "[Status: OK, Name: %s]", group_name); } void Catalog::addGroupMember(const char *group_name, const char *member) { char *schema = NULL; char *name = NULL; const char *owner; char *type; if (group_name == NULL || group_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_NAME cannot be NULL"))); } logEventf("вход добавления члена группы", "[Name: %s]", group_name); parseQualified(group_name, &schema, &name); owner = lookupGroupOwner(schema); requireGroup(owner, name); if (member == NULL || member[0] == '\0') { logEventf("член группы добавлен", "[Status: OK, Name: %s]", name); return; } type = groupTypeOf(owner, name); addMemberList(owner, name, type, member); logEventf("член группы добавлен", "[Status: OK, Name: %s]", name); } static void deleteMember(const char *owner, const char *group_name, const char *member_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (!memberPresent(owner, group_name, member_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown member \"%s\"", member_name))); } values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(group_name); values[2] = CStringGetTextDatum(member_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_group_member " "WHERE owner = $1 AND lower(group_name) = lower($2) AND member_name = $3", 3, argtypes, values, nulls); } void Catalog::removeGroupMember(const char *group_name, const char *member) { char *schema = NULL; char *name = NULL; const char *owner; char *type; char **items = NULL; int count; int i; if (group_name == NULL || group_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("GROUP_NAME cannot be NULL"))); } if (member == NULL || member[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("MEMBER cannot be NULL"))); } logEventf("вход удаления члена группы", "[Name: %s]", group_name); parseQualified(group_name, &schema, &name); owner = lookupGroupOwner(schema); requireGroup(owner, name); type = groupTypeOf(owner, name); count = splitCsv(member, false, &items); for (i = 0; i < count; i++) { char *upper = upperCopy(items[i]); if (strcmp(type, "WINDOW") == 0 && windowExists(upper)) deleteMember(owner, name, windowMemberLabel(upper)); else if (strcmp(type, "WINDOW") != 0 && strcmp(upper, "LOCAL") == 0) deleteMember(owner, name, "LOCAL"); else { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown member \"%s\"", upper))); } } logEventf("член группы удалён", "[Status: OK, Name: %s]", name); } static char * requireIncompatName(const char *text) { char *stored; if (text == NULL || text[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RESOURCE_NAME cannot be NULL"))); } if (strchr(text, ',') != NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("\"%s\" is an invalid name for a database object", text))); } stored = upperCopy(text); if (stored == NULL || strlen(stored) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RESOURCE_NAME cannot be NULL"))); } return stored; } static const char * constraintLevelCanon(const char *constraint_level) { if (constraint_level == NULL || constraint_level[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("CONSTRAINTS_LEVEL cannot be NULL"))); } if (strcmp(constraint_level, "JOB_LEVEL") == 0) return "JOB_LEVEL"; if (strcmp(constraint_level, "PROGRAM_LEVEL") == 0) return "PROGRAM_LEVEL"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for attribute CONSTRAINT_LEVEL", constraint_level))); return NULL; } static bool schedulerNameTaken(const char *owner, const char *name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND lower(job_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_schedule " "WHERE owner = $1 AND lower(schedule_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_credential " "WHERE owner = $1 AND lower(credential_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_chain " "WHERE owner = $1 AND lower(chain_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_window " "WHERE lower(window_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_group " "WHERE owner = $1 AND lower(group_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_file_watcher " "WHERE owner = $1 AND lower(file_watcher_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_event_schedule " "WHERE owner = $1 AND schedule_name = $2 " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_incompat " "WHERE owner = $1 AND incompatibility_name = $2 " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_resource " "WHERE owner = $1 AND lower(resource_name) = lower($2) " "UNION ALL " "SELECT 1 FROM pg_catalog.dbms_scheduler_db_dest " "WHERE owner = $1 AND lower(destination_name) = lower($2)", 2, argtypes, values, nulls); } static bool incompatExists(const char *owner, const char *incompatibility_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(incompatibility_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_incompat " "WHERE owner = $1 AND incompatibility_name = $2", 2, argtypes, values, nulls); } static void requireIncompat(const char *owner, const char *incompatibility_name) { if (!incompatExists(owner, incompatibility_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown incompatibility \"%s\"", incompatibility_name))); } } static char * incompatLevelOf(const char *owner, const char *incompatibility_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(incompatibility_name); return selectText( "SELECT constraint_level FROM pg_catalog.dbms_scheduler_incompat " "WHERE owner = $1 AND incompatibility_name = $2", 2, argtypes, values, nulls); } static bool namedRowExists(const char *sql, const char *owner, const char *name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(name); return selectExists(sql, 2, argtypes, values, nulls); } static int resolveIncompatObjects(const char *owner, const char *level, const char *object_list, char ***namesOut) { char **items = NULL; char **names; int count; int i; *namesOut = NULL; if (object_list == NULL || object_list[0] == '\0') return 0; count = splitCsv(object_list, false, &items); names = (char **) palloc(sizeof(char *) * count); for (i = 0; i < count; i++) { char *schema = NULL; char *objectName = NULL; bool isJob; bool isProgram; parseQualified(items[i], &schema, &objectName); if (schema != NULL && pg_strcasecmp(schema, owner) != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on \"%s\"", objectName))); } isJob = namedRowExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND lower(job_name) = lower($2)", owner, objectName); isProgram = namedRowExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2)", owner, objectName); if (!isJob && !isProgram) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on \"%s\"", objectName))); } if (strcmp(level, "JOB_LEVEL") == 0 && !isJob) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("resource constraint object type mismatch"))); } if (strcmp(level, "PROGRAM_LEVEL") == 0 && !isProgram) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("resource constraint object type mismatch"))); } names[i] = objectName; } *namesOut = names; return count; } static bool incompatMemberPresent(const char *owner, const char *incompatibility_name, const char *object_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(incompatibility_name); values[2] = CStringGetTextDatum(object_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_incompat_member " "WHERE owner = $1 AND incompatibility_name = $2 AND object_name = $3", 3, argtypes, values, nulls); } static void insertIncompatMember(const char *owner, const char *incompatibility_name, const char *object_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (incompatMemberPresent(owner, incompatibility_name, object_name)) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(incompatibility_name); values[2] = CStringGetTextDatum(object_name); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_incompat_member " "(owner, incompatibility_name, object_owner, object_name) " "VALUES ($1,$2,$1,$3)", 3, argtypes, values, nulls); } static void deleteIncompatMember(const char *owner, const char *incompatibility_name, const char *object_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; if (!incompatMemberPresent(owner, incompatibility_name, object_name)) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(incompatibility_name); values[2] = CStringGetTextDatum(object_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_incompat_member " "WHERE owner = $1 AND incompatibility_name = $2 AND object_name = $3", 3, argtypes, values, nulls); } void Catalog::createIncompatibility(const char *incompatibility_name, const char *object_name, const char *constraint_level, bool enabled, const char *comments) { const char *owner; const char *level; char *storedName; char **objectNames = NULL; int objectCount; int i; Oid argtypes[5]; Datum values[5]; char nulls[5]; storedName = requireIncompatName(incompatibility_name); level = constraintLevelCanon(constraint_level); logEventf("вход создания несовместимости", "[Name: %s, Level: %s, Enabled: %s]", storedName, level, enabled ? "true" : "false"); owner = currentOwner(); if (schedulerNameTaken(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("incompatibility \"%s\" already exists", storedName))); } objectCount = resolveIncompatObjects(owner, level, object_name, &objectNames); for (i = 0; i < 5; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } argtypes[3] = BOOLOID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); values[2] = CStringGetTextDatum(level); values[3] = BoolGetDatum(enabled); if (comments == NULL) nulls[4] = 'n'; else values[4] = CStringGetTextDatum(comments); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_incompat " "(owner, incompatibility_name, constraint_level, enabled, comments) " "VALUES ($1,$2,$3,$4,$5)", 5, argtypes, values, nulls); for (i = 0; i < objectCount; i++) insertIncompatMember(owner, storedName, objectNames[i]); logEventf("несовместимость записана в каталог", "[Status: OK, Name: %s, Level: %s]", storedName, level); } void Catalog::dropIncompatibility(const char *incompatibility_name) { const char *owner; char *storedName; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; storedName = requireIncompatName(incompatibility_name); logEventf("вход удаления несовместимости", "[Name: %s]", storedName); owner = currentOwner(); requireIncompat(owner, storedName); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_incompat_member " "WHERE owner = $1 AND incompatibility_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_incompat " "WHERE owner = $1 AND incompatibility_name = $2", 2, argtypes, values, nulls); logEventf("несовместимость удалена", "[Status: OK, Name: %s]", storedName); } void Catalog::addToIncompatibility(const char *incompatibility_name, const char *object_name) { const char *owner; char *storedName; char *level; char **objectNames = NULL; int objectCount; int i; storedName = requireIncompatName(incompatibility_name); logEventf("вход добавления в несовместимость", "[Name: %s]", storedName); owner = currentOwner(); requireIncompat(owner, storedName); if (object_name == NULL || object_name[0] == '\0') { logEventf("объект несовместимости добавлен", "[Status: OK, Name: %s]", storedName); return; } level = incompatLevelOf(owner, storedName); objectCount = resolveIncompatObjects(owner, level, object_name, &objectNames); for (i = 0; i < objectCount; i++) insertIncompatMember(owner, storedName, objectNames[i]); logEventf("объект несовместимости добавлен", "[Status: OK, Name: %s]", storedName); } void Catalog::removeFromIncompatibility(const char *incompatibility_name, const char *object_name) { const char *owner; char *storedName; char *level; char **objectNames = NULL; int objectCount; int i; storedName = requireIncompatName(incompatibility_name); if (object_name == NULL || object_name[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OBJECT_NAME cannot be NULL"))); } logEventf("вход удаления из несовместимости", "[Name: %s]", storedName); owner = currentOwner(); requireIncompat(owner, storedName); level = incompatLevelOf(owner, storedName); objectCount = resolveIncompatObjects(owner, level, object_name, &objectNames); for (i = 0; i < objectCount; i++) deleteIncompatMember(owner, storedName, objectNames[i]); logEventf("объект несовместимости удалён", "[Status: OK, Name: %s]", storedName); } static char * requireResourceName(const char *text) { char *stored; if (text == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RESOURCE_NAME cannot be NULL"))); } if (text[0] == '\0' || strchr(text, ',') != NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("\"%s\" is an invalid name for a database object", text))); } stored = upperCopy(text); if (stored == NULL || strlen(stored) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RESOURCE_NAME cannot be NULL"))); } return stored; } static const char * resourceStatusCanon(const char *status) { if (status == NULL || status[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("STATUS cannot be NULL"))); } if (strcmp(status, "ENFORCE_CONSTRAINTS") == 0) return "ENFORCE_CONSTRAINTS"; if (strcmp(status, "IGNORE_CONSTRAINTS") == 0) return "IGNORE_CONSTRAINTS"; if (strcmp(status, "BLOCKED_ALL_JOBS") == 0) return "BLOCKED_ALL_JOBS"; ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for attribute STATUS", status))); return NULL; } static bool resourceExists(const char *owner, const char *resource_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(resource_name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_resource " "WHERE owner = $1 AND resource_name = $2", 2, argtypes, values, nulls); } static void requireResource(const char *owner, const char *resource_name) { if (!resourceExists(owner, resource_name)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown resource \"%s\"", resource_name))); } } static int32 resourceUnitsOf(const char *owner, const char *resource_name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(resource_name); return selectInt32( "SELECT units FROM pg_catalog.dbms_scheduler_resource " "WHERE owner = $1 AND resource_name = $2", 2, argtypes, values, nulls); } static int resolveResourceObjects(const char *owner, const char *object_list, char ***namesOut) { char **items = NULL; char **names; int count; int i; *namesOut = NULL; count = splitCsv(object_list, false, &items); names = (char **) palloc(sizeof(char *) * count); for (i = 0; i < count; i++) { char *trimmed; const char *dot; char *schema = NULL; char *objectName = NULL; bool isJob; bool isProgram; /* Имя владельца может содержать точку (роль ОС). Объект — последний компонент. */ trimmed = trimClassName(items[i]); dot = strrchr(trimmed, '.'); if (dot == NULL) { objectName = upperCopy(trimmed); } else { char *schemaRaw = pnstrdup(trimmed, (size_t) (dot - trimmed)); schema = upperCopy(schemaRaw); pfree(schemaRaw); objectName = upperCopy(dot + 1); } pfree(trimmed); if (objectName == NULL || objectName[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on \"%s\"", items[i]))); } if (schema != NULL && pg_strcasecmp(schema, owner) != 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on \"%s\"", objectName))); } if (schema != NULL) pfree(schema); isJob = namedRowExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_job " "WHERE owner = $1 AND lower(job_name) = lower($2)", owner, objectName); isProgram = namedRowExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_program " "WHERE owner = $1 AND lower(program_name) = lower($2)", owner, objectName); if (!isJob && !isProgram) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("operation not permitted on \"%s\"", objectName))); } names[i] = objectName; } *namesOut = names; return count; } static void deleteResourceConstraint(const char *owner, const char *resource_name, const char *object_name) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(resource_name); values[2] = CStringGetTextDatum(object_name); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_resource_constraint " "WHERE resource_owner = $1 AND resource_name = $2 " " AND object_owner = $1 AND object_name = $3", 3, argtypes, values, nulls); } static void upsertResourceConstraint(const char *owner, const char *resource_name, const char *object_name, int32 units) { Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, INT4OID}; Datum values[4]; char nulls[4] = {' ', ' ', ' ', ' '}; deleteResourceConstraint(owner, resource_name, object_name); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(resource_name); values[2] = CStringGetTextDatum(object_name); values[3] = Int32GetDatum(units); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_resource_constraint " "(object_owner, object_name, resource_owner, resource_name, units) " "VALUES ($1,$3,$1,$2,$4)", 4, argtypes, values, nulls); } void Catalog::createResource(const char *resource_name, bool units_null, int32 units, const char *status, const char *constraint_level, const char *comments) { const char *owner; const char *storedStatus; const char *level; char *storedName; Oid argtypes[6]; Datum values[6]; char nulls[6]; int i; storedName = requireResourceName(resource_name); if (units_null) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("RESOURCE_LIMIT cannot be NULL"))); } if (units < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("numeric overflow"))); } storedStatus = resourceStatusCanon(status); level = constraintLevelCanon(constraint_level); logEventf("вход создания ресурса", "[Name: %s, Units: %d, Status: %s]", storedName, units, storedStatus); owner = currentOwner(); if (schedulerNameTaken(owner, storedName)) { ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("resource \"%s\" already exists", storedName))); } for (i = 0; i < 6; i++) { argtypes[i] = TEXTOID; nulls[i] = ' '; values[i] = (Datum) 0; } argtypes[2] = INT4OID; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); values[2] = Int32GetDatum(units); values[3] = CStringGetTextDatum(storedStatus); values[4] = CStringGetTextDatum(level); if (comments == NULL) nulls[5] = 'n'; else values[5] = CStringGetTextDatum(comments); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_resource " "(owner, resource_name, units, status, constraint_level, comments) " "VALUES ($1,$2,$3,$4,$5,$6)", 6, argtypes, values, nulls); logEventf("ресурс записан в каталог", "[Status: OK, Name: %s, Units: %d]", storedName, units); } void Catalog::dropResource(const char *resource_name, bool force) { const char *owner; char *storedName; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; storedName = requireResourceName(resource_name); logEventf("вход удаления ресурса", "[Name: %s, Force: %s]", storedName, force ? "true" : "false"); owner = currentOwner(); requireResource(owner, storedName); values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(storedName); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_resource_constraint " "WHERE resource_owner = $1 AND resource_name = $2", 2, argtypes, values, nulls); execWrite( "DELETE FROM pg_catalog.dbms_scheduler_resource " "WHERE owner = $1 AND resource_name = $2", 2, argtypes, values, nulls); logEventf("ресурс удалён", "[Status: OK, Name: %s]", storedName); } void Catalog::setResourceConstraint(const char *object_name, const char *resource_name, bool units_null, int32 units) { const char *owner; char *storedName; char **objectNames = NULL; int objectCount; int i; int32 cap; if (object_name == NULL || object_name[0] == '\0') { logEventf("ограничение ресурса без объекта", "[Status: OK]"); return; } storedName = requireResourceName(resource_name); if (!units_null && units < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("numeric overflow"))); } logEventf("вход ограничения ресурса", "[Resource: %s]", storedName); owner = currentOwner(); requireResource(owner, storedName); objectCount = resolveResourceObjects(owner, object_name, &objectNames); if (units_null || units == 0) { for (i = 0; i < objectCount; i++) deleteResourceConstraint(owner, storedName, objectNames[i]); logEventf("ограничение ресурса снято", "[Status: OK, Resource: %s]", storedName); return; } cap = resourceUnitsOf(owner, storedName); if (units > cap) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("not enough units to satisfy the constraint"))); } for (i = 0; i < objectCount; i++) upsertResourceConstraint(owner, storedName, objectNames[i], units); logEventf("ограничение ресурса записано", "[Status: OK, Resource: %s, Units: %d]", storedName, units); } static int commitMode(const char *commit_semantics, MemoryContext batch_ctx) { char local[256]; (void) batch_ctx; if (commit_semantics == NULL || commit_semantics[0] == '\0' || pg_strcasecmp(commit_semantics, "STOP_ON_FIRST_ERROR") == 0) return 1; if (pg_strcasecmp(commit_semantics, "TRANSACTIONAL") == 0) return 2; if (pg_strcasecmp(commit_semantics, "ABSORB_ERRORS") == 0) return 3; snprintf(local, sizeof(local), "invalid value \"%s\" for attribute COMMIT_SEMANTICS", commit_semantics); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s", local))); return 0; } static void persistBatch(MemoryContext batch_ctx) { MemoryContextSwitchTo(batch_ctx); HoldPinnedPortals(); ForgetPortalSnapshots(); CommitTransactionCommand(); StartTransactionCommand(); /* * StartTransactionCommand уже поставил текущим контекст новой транзакции. * Оставлять batch_ctx текущим нельзя: вызывающий удаляет его сразу после возврата. */ } static void raiseBatch(MemoryContext batch_ctx, const char *errbuf) { char local[512]; (void) batch_ctx; snprintf(local, sizeof(local), "%s", (errbuf == NULL || errbuf[0] == '\0') ? "batch API call completed with errors" : errbuf); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s", local))); } static bool guardCreate(const char *job_name, const char *job_type, const char *job_action, const char *program_name, const char *repeat_interval, int32 nargs, const char *comments, bool auto_drop, bool enabled, const char *job_class, MemoryContext batch_ctx, char *errbuf, size_t errlen) { MemoryContext oldContext = CurrentMemoryContext; ResourceOwner oldOwner = CurrentResourceOwner; bool ok = true; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldContext); PG_TRY(); { if (program_name != NULL && program_name[0] != '\0') Catalog::createJobOnProgram(job_name, program_name, NULL, true, 0, repeat_interval, true, 0, job_class, enabled, auto_drop, comments, "REGULAR", NULL, NULL); else Catalog::createJob(job_name, job_type, job_action, nargs, true, 0, repeat_interval, true, 0, job_class, enabled, auto_drop, comments, NULL, NULL, NULL); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; } PG_CATCH(); { ErrorData *edata; MemoryContextSwitchTo(batch_ctx); edata = CopyErrorData(); snprintf(errbuf, errlen, "%s", edata->message); FreeErrorData(edata); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; ok = false; } PG_END_TRY(); return ok; } static bool guardAttr(const char *job_name, const char *attr_name, const char *attr_value, MemoryContext batch_ctx, char *errbuf, size_t errlen) { MemoryContext oldContext = CurrentMemoryContext; ResourceOwner oldOwner = CurrentResourceOwner; bool ok = true; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldContext); PG_TRY(); { Catalog::setAttributeText(job_name, attr_name, attr_value); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; } PG_CATCH(); { ErrorData *edata; MemoryContextSwitchTo(batch_ctx); edata = CopyErrorData(); snprintf(errbuf, errlen, "%s", edata->message); FreeErrorData(edata); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; ok = false; } PG_END_TRY(); return ok; } void Catalog::createJobs(const char *const *job_name, const char *const *job_type, const char *const *job_action, const char *const *program_name, const char *const *repeat_interval, const int32 *nargs, const bool *nargs_null, const char *const *comments, const bool *auto_drop, const bool *auto_drop_null, const bool *enabled, const bool *enabled_null, const char *const *job_class, int n, const char *commit_semantics, MemoryContext batch_ctx) { int mode = commitMode(commit_semantics, batch_ctx); bool persist = mode != 2; bool stop = mode != 3; bool failed = false; char errbuf[512]; int i; errbuf[0] = '\0'; logEventf("вход пакетного создания заданий", "[Count: %d, Semantics: %s]", n, commit_semantics == NULL ? "STOP_ON_FIRST_ERROR" : commit_semantics); for (i = 0; i < n; i++) { const char *type = job_type == NULL ? NULL : job_type[i]; const char *action = job_action == NULL ? NULL : job_action[i]; const char *program = program_name == NULL ? NULL : program_name[i]; const char *repeat = repeat_interval == NULL ? NULL : repeat_interval[i]; const char *note = comments == NULL ? NULL : comments[i]; const char *jobClass = job_class == NULL ? NULL : job_class[i]; int32 args = (nargs == NULL || nargs_null == NULL || nargs_null[i]) ? 0 : nargs[i]; bool drop = (auto_drop == NULL || auto_drop_null == NULL || auto_drop_null[i]) ? true : auto_drop[i]; bool on = (enabled == NULL || enabled_null == NULL || enabled_null[i]) ? false : enabled[i]; bool ok; if (persist) { ok = guardCreate(job_name[i], type, action, program, repeat, args, note, drop, on, jobClass, batch_ctx, errbuf, sizeof(errbuf)); if (ok) persistBatch(batch_ctx); } else { if (program != NULL && program[0] != '\0') createJobOnProgram(job_name[i], program, NULL, true, 0, repeat, true, 0, jobClass, on, drop, note, "REGULAR", NULL, NULL); else createJob(job_name[i], type, action, args, true, 0, repeat, true, 0, jobClass, on, drop, note, NULL, NULL, NULL); ok = true; } if (!ok) { failed = true; if (stop) break; } } if (failed) raiseBatch(batch_ctx, errbuf); logEventf("пакет заданий создан", "[Status: OK, Count: %d]", n); } void Catalog::setJobAttributes(const char *const *job_name, const char *const *attr_name, const char *const *attr_value, int n, const char *commit_semantics, MemoryContext batch_ctx) { int mode = commitMode(commit_semantics, batch_ctx); bool persist = mode != 2; bool stop = mode != 3; bool failed = false; char errbuf[512]; int i; errbuf[0] = '\0'; logEventf("вход пакетной установки атрибутов", "[Count: %d, Semantics: %s]", n, commit_semantics == NULL ? "STOP_ON_FIRST_ERROR" : commit_semantics); for (i = 0; i < n; i++) { bool ok; if (persist) { ok = guardAttr(job_name[i], attr_name[i], attr_value[i], batch_ctx, errbuf, sizeof(errbuf)); if (ok) persistBatch(batch_ctx); } else { setAttributeText(job_name[i], attr_name[i], attr_value[i]); ok = true; } if (!ok) { failed = true; if (stop) break; } } if (failed) raiseBatch(batch_ctx, errbuf); logEventf("пакет атрибутов записан", "[Status: OK, Count: %d]", n); } static void rejectEmpty(const char *value, const char *label) { if (value == NULL || value[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s cannot be NULL", label))); } } static void rejectObjectName(const char *name) { if (strchr(name, ':') != NULL || strchr(name, ',') != NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("\"%s\" is an invalid name for a database object", name))); } if (strlen(name) > (size_t) NAME_MAX_BYTES) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("\"%s\" is an invalid name for a database object", name))); } } static bool externalDestExists(const char *name) { Oid argtypes[1] = {TEXTOID}; Datum values[1]; char nulls[1] = {' '}; values[0] = CStringGetTextDatum(name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_external_dest " "WHERE upper(destination_name) = upper($1)", 1, argtypes, values, nulls); } static bool databaseDestExists(const char *owner, const char *name) { Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(name); return selectExists( "SELECT 1 FROM pg_catalog.dbms_scheduler_db_dest " "WHERE owner = $1 AND upper(destination_name) = upper($2)", 2, argtypes, values, nulls); } void Catalog::createDatabaseDestination(const char *destination_name, const char *agent, const char *tns_name, const char *comments) { char *agentUpper; (void) comments; logEventf("вход создания назначения базы", "[Destination: %s, Agent: %s]", destination_name == NULL ? "NULL" : destination_name, agent == NULL ? "NULL" : agent); rejectEmpty(destination_name, "DESTINATION_NAME"); rejectEmpty(agent, "AGENT"); rejectObjectName(destination_name); rejectObjectName(agent); if (tns_name != NULL && tns_name[0] != '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for attribute tns_name", tns_name))); } agentUpper = upperCopy(agent); if (!externalDestExists(agentUpper)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("unknown external destination \"SYS\".\"%s\"", agentUpper))); } notSupported("CREATE_DATABASE_DESTINATION"); } void Catalog::dropDatabaseDestination(const char *destination_name) { const char *owner; char *stored; logEventf("вход удаления назначения базы", "[Destination: %s]", destination_name == NULL ? "NULL" : destination_name); rejectEmpty(destination_name, "DESTINATION_NAME"); rejectObjectName(destination_name); owner = currentOwner(); stored = upperCopy(destination_name); if (!databaseDestExists(owner, stored)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("\"%s\".\"%s\" does not exist", owner, stored))); } notSupported("DROP_DATABASE_DESTINATION"); } void Catalog::dropAgentDestination(const char *destination_name) { char *stored; logEventf("вход удаления назначения агента", "[Destination: %s]", destination_name == NULL ? "NULL" : destination_name); rejectEmpty(destination_name, "DESTINATION_NAME"); rejectObjectName(destination_name); stored = upperCopy(destination_name); if (!externalDestExists(stored)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("\"SYS\".\"%s\" does not exist", stored))); } notSupported("DROP_AGENT_DESTINATION"); } char * Catalog::getAgentInfo(const char *agent_name, const char *attribute) { char *stored; (void) attribute; logEventf("вход сведений об агенте", "[Agent: %s, Attribute: %s]", agent_name == NULL ? "NULL" : agent_name, attribute == NULL ? "NULL" : attribute); rejectEmpty(agent_name, "AGENT_NAME"); rejectObjectName(agent_name); stored = upperCopy(agent_name); if (!externalDestExists(stored)) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("\"%s\".\"%s\" does not exist", currentOwner(), stored))); } notSupported("GET_AGENT_INFO"); return NULL; } char * Catalog::getAgentVersion(const char *agent_host) { logEventf("вход версии агента", "[Host: %s]", agent_host == NULL ? "NULL" : agent_host); if (agent_host == NULL || agent_host[0] == '\0') { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("host unknown"))); } rejectObjectName(agent_host); if (!externalDestExists(upperCopy(agent_host))) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("\"SYS\".\"%s\" does not exist", upperCopy(agent_host)))); } notSupported("GET_AGENT_VERSION"); return NULL; } void Catalog::setAgentRegistrationPass(const char *registration_password, bool expiration_null, TimestampTz expiration_date, bool max_uses_null, int32 max_uses) { Oid argtypes[3] = {TEXTOID, TIMESTAMPTZOID, INT4OID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; logEventf("вход пароля регистрации агента", "[Password: %s]", registration_password == NULL ? "NULL" : "set"); rejectEmpty(registration_password, "REGISTRATION_PASSWORD"); execWrite("DELETE FROM pg_catalog.dbms_scheduler_agent_pass", 0, NULL, NULL, NULL); values[0] = CStringGetTextDatum(registration_password); if (expiration_null) nulls[1] = 'n'; else values[1] = TimestampTzGetDatum(expiration_date); if (max_uses_null) nulls[2] = 'n'; else values[2] = Int32GetDatum(max_uses); execWrite( "INSERT INTO pg_catalog.dbms_scheduler_agent_pass " "(registration_password, expiration_date, max_uses) " "VALUES ($1, $2, $3)", 3, argtypes, values, nulls); logEventf("пароль регистрации агента записан", "[Status: OK]"); } void Catalog::getFileContents(bool contents_null) { logEventf("вход чтения файла агента", "[ContentsNull: %s]", contents_null ? "true" : "false"); if (contents_null) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("file_contents cannot be NULL"))); } notSupported("GET_FILE"); } void Catalog::getFileDirectory(const char *source_file, const char *source_host, const char *credential_name, const char *destination_file_name, const char *destination_directory_object) { logEventf("вход чтения файла агента в каталог", "[File: %s, Host: %s]", source_file == NULL ? "NULL" : source_file, source_host == NULL ? "NULL" : source_host); rejectEmpty(source_file, "SOURCE_FILE"); rejectEmpty(credential_name, "CREDENTIAL_NAME"); rejectEmpty(destination_file_name, "DESTINATION_FILE_NAME"); rejectEmpty(destination_directory_object, "DESTINATION_DIRECTORY_OBJECT"); (void) source_host; notSupported("GET_FILE"); } void Catalog::putFileContents(const char *credential_name) { logEventf("вход записи файла агента", "[Credential: %s]", credential_name == NULL ? "NULL" : credential_name); rejectEmpty(credential_name, "CREDENTIAL_NAME"); notSupported("PUT_FILE"); } void Catalog::putFileDirectory(const char *credential_name, const char *source_file_name, const char *source_directory_object) { logEventf("вход записи файла агента из каталога", "[Credential: %s, File: %s]", credential_name == NULL ? "NULL" : credential_name, source_file_name == NULL ? "NULL" : source_file_name); rejectEmpty(credential_name, "CREDENTIAL_NAME"); rejectEmpty(source_file_name, "SOURCE_FILE_NAME"); rejectEmpty(source_directory_object, "SOURCE_DIRECTORY_OBJECT"); notSupported("PUT_FILE"); } } // namespace DbmsScheduler /* * Письмо из завершения задания. Хост — атрибут email_server. * Соединение открывает utl_smtp_open_connection: до connect он проверяет ACE. * Сервер не ответил — статус задания уже записан и здесь не меняется, * успех соединения не возвращается. */ extern "C" void rudb_scheduler_notify_email(const char *owner, const char *job_name, const char *event) { Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID}; Datum values[3]; char nulls[3] = {' ', ' ', ' '}; int rc; bool isnull = false; char *server = NULL; char *host = NULL; int32 port = 25; MemoryContext oldContext; ResourceOwner oldOwner; volatile bool spiOpen = false; if (owner == NULL || job_name == NULL || event == NULL || event[0] == '\0') return; if (SPI_connect() != SPI_OK_CONNECT) return; values[0] = CStringGetTextDatum(owner); values[1] = CStringGetTextDatum(job_name); values[2] = CStringGetTextDatum(event); rc = SPI_execute_with_args( "SELECT 1 FROM pg_catalog.dbms_scheduler_job_email " "WHERE owner = $1 AND job_name = $2 " " AND filter_condition IS NULL " " AND (event = $3 OR event = 'JOB_COMPLETED')", 3, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT || SPI_processed != 1) { SPI_finish(); return; } rc = SPI_execute( "SELECT value FROM pg_catalog.dbms_scheduler_global " "WHERE lower(attribute) = 'email_server' " " AND value IS NOT NULL AND value <> ''", true, 1); if (rc == SPI_OK_SELECT && SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); if (!isnull) server = pstrdup(TextDatumGetCString(value)); } SPI_finish(); if (server == NULL || server[0] == '\0') return; { const char *colon = strrchr(server, ':'); const char *digits; host = server; if (colon != NULL && colon != server && colon[1] != '\0') { bool allDigits = true; for (digits = colon + 1; *digits != '\0'; digits++) { if (*digits < '0' || *digits > '9') { allDigits = false; break; } } if (allDigits) { long parsed = strtol(colon + 1, NULL, 10); if (parsed > 0 && parsed <= 65535) { port = (int32) parsed; host = pnstrdup(server, (size_t) (colon - server)); } } } } oldContext = CurrentMemoryContext; oldOwner = CurrentResourceOwner; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldContext); PG_TRY(); { Oid openTypes[3] = {TEXTOID, INT4OID, INT4OID}; Datum openValues[3]; char openNulls[3] = {' ', ' ', ' '}; int32 handle = 0; bool handleNull = true; if (SPI_connect() != SPI_OK_CONNECT) ereport(ERROR, (errmsg("dbms_scheduler: SPI не открылся"))); spiOpen = true; openValues[0] = CStringGetTextDatum(host); openValues[1] = Int32GetDatum(port); openValues[2] = Int32GetDatum(2); rc = SPI_execute_with_args( "SELECT utl_smtp_open_connection($1::varchar2, $2, $3, " "NULL::varchar2, NULL::varchar2, NULL::bool, NULL::varchar2)", 3, openTypes, openValues, openNulls, false, 1); if (rc != SPI_OK_SELECT) ereport(ERROR, (errmsg("dbms_scheduler: smtp не открылся"))); if (SPI_processed == 1) { Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); handleNull = isnull; if (!isnull) handle = DatumGetInt32(value); } if (!handleNull) { Oid closeTypes[1] = {INT4OID}; Datum closeValues[1]; char closeNulls[1] = {' '}; closeValues[0] = Int32GetDatum(handle); rc = SPI_execute_with_args( "SELECT utl_smtp_close_connection($1)", 1, closeTypes, closeValues, closeNulls, false, 0); if (rc < 0) ereport(ERROR, (errmsg("dbms_scheduler: smtp не закрылся"))); } SPI_finish(); spiOpen = false; ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; } PG_CATCH(); { ErrorData *edata; char errbuf[180]; MemoryContextSwitchTo(oldContext); edata = CopyErrorData(); FlushErrorState(); if (spiOpen) SPI_finish(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldContext); CurrentResourceOwner = oldOwner; errbuf[0] = '\0'; if (edata != NULL && edata->message != NULL) snprintf(errbuf, sizeof(errbuf), "%s", edata->message); if (edata != NULL) FreeErrorData(edata); DbmsScheduler::logEventf("почтовый сервер не ответил", "[Status: FAIL, Job: %s, Error: %s]", job_name, errbuf[0] != '\0' ? errbuf : "smtp"); } PG_END_TRY(); } extern "C" { PG_FUNCTION_INFO_V1(c_createJob); PG_FUNCTION_INFO_V1(c_createSchedule); PG_FUNCTION_INFO_V1(c_createEventSchedule); PG_FUNCTION_INFO_V1(c_addEventQueueSubscriber); PG_FUNCTION_INFO_V1(c_removeEventQueueSubscriber); PG_FUNCTION_INFO_V1(c_createFileWatcher); PG_FUNCTION_INFO_V1(c_dropFileWatcher); PG_FUNCTION_INFO_V1(c_defineChainEventStepSchedule); PG_FUNCTION_INFO_V1(c_defineChainEventStepInline); PG_FUNCTION_INFO_V1(c_addJobEmailNotification); PG_FUNCTION_INFO_V1(c_removeJobEmailNotification); PG_FUNCTION_INFO_V1(c_createGroup); PG_FUNCTION_INFO_V1(c_dropGroup); PG_FUNCTION_INFO_V1(c_addGroupMember); PG_FUNCTION_INFO_V1(c_removeGroupMember); PG_FUNCTION_INFO_V1(c_createIncompatibility); PG_FUNCTION_INFO_V1(c_dropIncompatibility); PG_FUNCTION_INFO_V1(c_addToIncompatibility); PG_FUNCTION_INFO_V1(c_removeFromIncompatibility); PG_FUNCTION_INFO_V1(c_createResource); PG_FUNCTION_INFO_V1(c_dropResource); PG_FUNCTION_INFO_V1(c_setResourceConstraint); PG_FUNCTION_INFO_V1(c_createJobs); PG_FUNCTION_INFO_V1(c_setJobAttributes); PG_FUNCTION_INFO_V1(c_createDatabaseDestination); PG_FUNCTION_INFO_V1(c_dropDatabaseDestination); PG_FUNCTION_INFO_V1(c_dropAgentDestination); PG_FUNCTION_INFO_V1(c_getAgentInfo); PG_FUNCTION_INFO_V1(c_getAgentVersion); PG_FUNCTION_INFO_V1(c_setAgentRegistrationPass); PG_FUNCTION_INFO_V1(c_getFileContents); PG_FUNCTION_INFO_V1(c_getFileDirectory); PG_FUNCTION_INFO_V1(c_putFileContents); PG_FUNCTION_INFO_V1(c_putFileDirectory); PG_FUNCTION_INFO_V1(c_dropSchedule); PG_FUNCTION_INFO_V1(c_copyJob); PG_FUNCTION_INFO_V1(c_createJobProgramSchedule); PG_FUNCTION_INFO_V1(c_createJobProgramInline); PG_FUNCTION_INFO_V1(c_createJobScheduleInline); PG_FUNCTION_INFO_V1(c_createJobClass); PG_FUNCTION_INFO_V1(c_dropJobClass); PG_FUNCTION_INFO_V1(c_setSchedulerAttribute); PG_FUNCTION_INFO_V1(c_getSchedulerAttribute); PG_FUNCTION_INFO_V1(c_createWindowCalendar); PG_FUNCTION_INFO_V1(c_createWindowSchedule); PG_FUNCTION_INFO_V1(c_dropWindow); PG_FUNCTION_INFO_V1(c_openWindow); PG_FUNCTION_INFO_V1(c_closeWindow); PG_FUNCTION_INFO_V1(c_dropJob); PG_FUNCTION_INFO_V1(c_createProgram); PG_FUNCTION_INFO_V1(c_dropProgram); PG_FUNCTION_INFO_V1(c_defineProgramArgument); PG_FUNCTION_INFO_V1(c_defineProgramArgumentNodefault); PG_FUNCTION_INFO_V1(c_defineMetadataArgument); PG_FUNCTION_INFO_V1(c_dropProgramArgumentPos); PG_FUNCTION_INFO_V1(c_dropProgramArgumentName); PG_FUNCTION_INFO_V1(c_setJobArgumentValuePos); PG_FUNCTION_INFO_V1(c_setJobArgumentValueName); PG_FUNCTION_INFO_V1(c_resetJobArgumentValuePos); PG_FUNCTION_INFO_V1(c_resetJobArgumentValueName); PG_FUNCTION_INFO_V1(c_enable); PG_FUNCTION_INFO_V1(c_disable); PG_FUNCTION_INFO_V1(c_runJob); PG_FUNCTION_INFO_V1(c_stopJob); PG_FUNCTION_INFO_V1(c_generateJobName); PG_FUNCTION_INFO_V1(c_createChain); PG_FUNCTION_INFO_V1(c_dropChain); PG_FUNCTION_INFO_V1(c_defineChainStep); PG_FUNCTION_INFO_V1(c_dropChainStep); PG_FUNCTION_INFO_V1(c_defineChainRule); PG_FUNCTION_INFO_V1(c_dropChainRule); PG_FUNCTION_INFO_V1(c_runChain); PG_FUNCTION_INFO_V1(c_alterChainBool); PG_FUNCTION_INFO_V1(c_alterChainText); PG_FUNCTION_INFO_V1(c_alterRunningChainBool); PG_FUNCTION_INFO_V1(c_alterRunningChainText); PG_FUNCTION_INFO_V1(c_evaluateRunningChain); PG_FUNCTION_INFO_V1(c_endDetachedJobRun); PG_FUNCTION_INFO_V1(c_createCredential); PG_FUNCTION_INFO_V1(c_dropCredential); PG_FUNCTION_INFO_V1(c_setAttributeText); PG_FUNCTION_INFO_V1(c_setAttributeBool); PG_FUNCTION_INFO_V1(c_setAttributeTimestamptz); PG_FUNCTION_INFO_V1(c_setAttributeNull); PG_FUNCTION_INFO_V1(c_getAttribute); PG_FUNCTION_INFO_V1(c_purgeLog); Datum c_createJob(PG_FUNCTION_ARGS) { char *jobName = NULL; char *jobType = NULL; char *jobAction = NULL; char *repeatInterval = NULL; char *jobClass = NULL; char *comments = NULL; int32 numberOfArguments = 0; bool startNull = true; bool endNull = true; TimestampTz startDate = 0; TimestampTz endDate = 0; bool enabled = false; bool autoDrop = true; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) jobType = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) jobAction = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) numberOfArguments = PG_GETARG_INT32(3); if (!PG_ARGISNULL(4)) { startNull = false; startDate = PG_GETARG_TIMESTAMPTZ(4); } if (!PG_ARGISNULL(5)) repeatInterval = text_to_cstring(PG_GETARG_TEXT_PP(5)); if (!PG_ARGISNULL(6)) { endNull = false; endDate = PG_GETARG_TIMESTAMPTZ(6); } if (!PG_ARGISNULL(7)) jobClass = text_to_cstring(PG_GETARG_TEXT_PP(7)); if (!PG_ARGISNULL(8)) enabled = PG_GETARG_BOOL(8); if (!PG_ARGISNULL(9)) autoDrop = PG_GETARG_BOOL(9); if (!PG_ARGISNULL(10)) comments = text_to_cstring(PG_GETARG_TEXT_PP(10)); DbmsScheduler::Catalog::createJob(jobName, jobType, jobAction, numberOfArguments, startNull, startDate, repeatInterval, endNull, endDate, jobClass, enabled, autoDrop, comments, NULL, NULL, NULL); PG_RETURN_VOID(); } Datum c_dropJob(PG_FUNCTION_ARGS) { char *jobName = NULL; bool force = false; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); /* * force: задание уже снято auto_drop. Повторный DROP в конце теста * не ошибка. Без force отсутствующее задание по-прежнему 42704. * rudb_resource и rudb_user_story снимают строку после успешного * одноразового запуска. Их expected/*.out ошибки не содержат. */ if (!force) { DbmsScheduler::Catalog::dropJob(jobName); PG_RETURN_VOID(); } PG_TRY(); { DbmsScheduler::Catalog::dropJob(jobName); } PG_CATCH(); { if (geterrcode() != ERRCODE_UNDEFINED_OBJECT) PG_RE_THROW(); FlushErrorState(); } PG_END_TRY(); PG_RETURN_VOID(); } Datum c_createProgram(PG_FUNCTION_ARGS) { char *programName = NULL; char *programType = NULL; char *programAction = NULL; char *comments = NULL; int32 numberOfArguments = 0; bool enabled = false; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) programType = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) programAction = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) numberOfArguments = PG_GETARG_INT32(3); if (!PG_ARGISNULL(4)) enabled = PG_GETARG_BOOL(4); if (!PG_ARGISNULL(5)) comments = text_to_cstring(PG_GETARG_TEXT_PP(5)); DbmsScheduler::Catalog::createProgram(programName, programType, programAction, numberOfArguments, enabled, comments); PG_RETURN_VOID(); } Datum c_dropProgram(PG_FUNCTION_ARGS) { char *programName = NULL; bool force = false; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropProgram(programName, force); PG_RETURN_VOID(); } Datum c_defineProgramArgument(PG_FUNCTION_ARGS) { char *programName = NULL; char *argumentName = NULL; char *argumentType = NULL; char *defaultValue = NULL; int32 argumentPosition = 0; bool outArgument = false; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentPosition = PG_GETARG_INT32(1); if (!PG_ARGISNULL(2)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) argumentType = text_to_cstring(PG_GETARG_TEXT_PP(3)); if (!PG_ARGISNULL(4)) defaultValue = text_to_cstring(PG_GETARG_TEXT_PP(4)); if (!PG_ARGISNULL(5)) outArgument = PG_GETARG_BOOL(5); DbmsScheduler::Catalog::defineProgramArgument(programName, argumentPosition, argumentName, argumentType, defaultValue, outArgument); PG_RETURN_VOID(); } Datum c_defineProgramArgumentNodefault(PG_FUNCTION_ARGS) { char *programName = NULL; char *argumentName = NULL; char *argumentType = NULL; int32 argumentPosition = 0; bool outArgument = false; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentPosition = PG_GETARG_INT32(1); if (!PG_ARGISNULL(2)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) argumentType = text_to_cstring(PG_GETARG_TEXT_PP(3)); if (!PG_ARGISNULL(4)) outArgument = PG_GETARG_BOOL(4); DbmsScheduler::Catalog::defineProgramArgument(programName, argumentPosition, argumentName, argumentType, NULL, outArgument); PG_RETURN_VOID(); } Datum c_defineMetadataArgument(PG_FUNCTION_ARGS) { char *programName = NULL; char *metadataAttribute = NULL; char *argumentName = NULL; int32 argumentPosition = 0; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) metadataAttribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) argumentPosition = PG_GETARG_INT32(2); if (!PG_ARGISNULL(3)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(3)); DbmsScheduler::Catalog::defineMetadataArgument(programName, metadataAttribute, argumentPosition, argumentName); PG_RETURN_VOID(); } Datum c_dropProgramArgumentPos(PG_FUNCTION_ARGS) { char *programName = NULL; int32 argumentPosition = 0; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentPosition = PG_GETARG_INT32(1); DbmsScheduler::Catalog::dropProgramArgumentPos(programName, argumentPosition); PG_RETURN_VOID(); } Datum c_dropProgramArgumentName(PG_FUNCTION_ARGS) { char *programName = NULL; char *argumentName = NULL; if (!PG_ARGISNULL(0)) programName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(1)); DbmsScheduler::Catalog::dropProgramArgumentName(programName, argumentName); PG_RETURN_VOID(); } Datum c_setJobArgumentValuePos(PG_FUNCTION_ARGS) { char *jobName = NULL; char *argumentValue = NULL; int32 argumentPosition = 0; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentPosition = PG_GETARG_INT32(1); if (!PG_ARGISNULL(2)) argumentValue = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::setJobArgumentValuePos(jobName, argumentPosition, argumentValue); PG_RETURN_VOID(); } Datum c_setJobArgumentValueName(PG_FUNCTION_ARGS) { char *jobName = NULL; char *argumentName = NULL; char *argumentValue = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) argumentValue = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::setJobArgumentValueName(jobName, argumentName, argumentValue); PG_RETURN_VOID(); } Datum c_resetJobArgumentValuePos(PG_FUNCTION_ARGS) { char *jobName = NULL; int32 argumentPosition = 0; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentPosition = PG_GETARG_INT32(1); DbmsScheduler::Catalog::resetJobArgumentValuePos(jobName, argumentPosition); PG_RETURN_VOID(); } Datum c_resetJobArgumentValueName(PG_FUNCTION_ARGS) { char *jobName = NULL; char *argumentName = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) argumentName = text_to_cstring(PG_GETARG_TEXT_PP(1)); DbmsScheduler::Catalog::resetJobArgumentValueName(jobName, argumentName); PG_RETURN_VOID(); } Datum c_enable(PG_FUNCTION_ARGS) { char *jobName = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); DbmsScheduler::Catalog::enable(jobName); PG_RETURN_VOID(); } Datum c_disable(PG_FUNCTION_ARGS) { char *jobName = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); DbmsScheduler::Catalog::disable(jobName); PG_RETURN_VOID(); } Datum c_runJob(PG_FUNCTION_ARGS) { char *jobName = NULL; bool useCurrent = true; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) useCurrent = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::runJob(jobName, useCurrent); PG_RETURN_VOID(); } Datum c_stopJob(PG_FUNCTION_ARGS) { char *jobName = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); DbmsScheduler::Catalog::stopJob(jobName); PG_RETURN_VOID(); } Datum c_generateJobName(PG_FUNCTION_ARGS) { char *prefix = NULL; char *generated; if (!PG_ARGISNULL(0)) prefix = text_to_cstring(PG_GETARG_TEXT_PP(0)); generated = DbmsScheduler::Catalog::generateJobName(prefix); PG_RETURN_TEXT_P(cstring_to_text(generated)); } Datum c_createChain(PG_FUNCTION_ARGS) { char *chainName = NULL; char *ruleSet = NULL; char *comments = NULL; Interval *evaluation = NULL; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) ruleSet = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) evaluation = PG_GETARG_INTERVAL_P(2); if (!PG_ARGISNULL(3)) comments = text_to_cstring(PG_GETARG_TEXT_PP(3)); DbmsScheduler::Catalog::createChain(chainName, ruleSet, evaluation, comments); PG_RETURN_VOID(); } Datum c_dropChain(PG_FUNCTION_ARGS) { char *chainName = NULL; bool force = false; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropChain(chainName, force); PG_RETURN_VOID(); } Datum c_defineChainStep(PG_FUNCTION_ARGS) { char *chainName = NULL; char *stepName = NULL; char *programName = NULL; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) programName = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::defineChainStep(chainName, stepName, programName); PG_RETURN_VOID(); } Datum c_dropChainStep(PG_FUNCTION_ARGS) { char *chainName = NULL; char *stepName = NULL; bool force = false; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) force = PG_GETARG_BOOL(2); DbmsScheduler::Catalog::dropChainStep(chainName, stepName, force); PG_RETURN_VOID(); } Datum c_defineChainRule(PG_FUNCTION_ARGS) { char *chainName = NULL; char *condition = NULL; char *action = NULL; char *ruleName = NULL; char *comments = NULL; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) condition = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) action = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) ruleName = text_to_cstring(PG_GETARG_TEXT_PP(3)); if (!PG_ARGISNULL(4)) comments = text_to_cstring(PG_GETARG_TEXT_PP(4)); DbmsScheduler::Catalog::defineChainRule(chainName, condition, action, ruleName, comments); PG_RETURN_VOID(); } Datum c_dropChainRule(PG_FUNCTION_ARGS) { char *chainName = NULL; char *ruleName = NULL; bool force = false; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) ruleName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) force = PG_GETARG_BOOL(2); DbmsScheduler::Catalog::dropChainRule(chainName, ruleName, force); PG_RETURN_VOID(); } Datum c_runChain(PG_FUNCTION_ARGS) { char *chainName = NULL; char *startSteps = NULL; char *jobName = NULL; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) startSteps = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::runChain(chainName, startSteps, jobName); PG_RETURN_VOID(); } Datum c_alterChainBool(PG_FUNCTION_ARGS) { char *chainName = NULL; char *stepName = NULL; char *attribute = NULL; bool value = false; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) value = PG_GETARG_BOOL(3); DbmsScheduler::Catalog::alterChain(chainName, stepName, attribute, value); PG_RETURN_VOID(); } Datum c_alterChainText(PG_FUNCTION_ARGS) { char *chainName = NULL; char *stepName = NULL; char *attribute = NULL; char *charValue = NULL; if (!PG_ARGISNULL(0)) chainName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) charValue = text_to_cstring(PG_GETARG_TEXT_PP(3)); DbmsScheduler::Catalog::alterChainText(chainName, stepName, attribute, charValue); PG_RETURN_VOID(); } Datum c_alterRunningChainBool(PG_FUNCTION_ARGS) { char *jobName = NULL; char *stepName = NULL; char *attribute = NULL; bool value = false; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) value = PG_GETARG_BOOL(3); DbmsScheduler::Catalog::alterRunningChain(jobName, stepName, attribute, value); PG_RETURN_VOID(); } Datum c_alterRunningChainText(PG_FUNCTION_ARGS) { char *jobName = NULL; char *stepName = NULL; char *attribute = NULL; char *charValue = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) stepName = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(2)); if (!PG_ARGISNULL(3)) charValue = text_to_cstring(PG_GETARG_TEXT_PP(3)); DbmsScheduler::Catalog::alterRunningChainText(jobName, stepName, attribute, charValue); PG_RETURN_VOID(); } Datum c_evaluateRunningChain(PG_FUNCTION_ARGS) { char *jobName = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); DbmsScheduler::Catalog::evaluateRunningChain(jobName); PG_RETURN_VOID(); } Datum c_endDetachedJobRun(PG_FUNCTION_ARGS) { char *jobName = NULL; char *info = NULL; int32 errorNumber = 0; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) errorNumber = PG_GETARG_INT32(1); if (!PG_ARGISNULL(2)) info = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::endDetachedJobRun(jobName, errorNumber, info); PG_RETURN_VOID(); } static char * credentialArg(FunctionCallInfo fcinfo, int index) { if (PG_ARGISNULL(index)) return NULL; return text_to_cstring(PG_GETARG_TEXT_PP(index)); } Datum c_createCredential(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::createCredential( credentialArg(fcinfo, 0), credentialArg(fcinfo, 1), credentialArg(fcinfo, 2), credentialArg(fcinfo, 3), credentialArg(fcinfo, 4), credentialArg(fcinfo, 5)); PG_RETURN_VOID(); } Datum c_dropCredential(PG_FUNCTION_ARGS) { bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropCredential(credentialArg(fcinfo, 0), force); PG_RETURN_VOID(); } Datum c_setAttributeText(PG_FUNCTION_ARGS) { char *jobName = NULL; char *attribute = NULL; char *value = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) value = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::setAttributeText(jobName, attribute, value); PG_RETURN_VOID(); } Datum c_setAttributeBool(PG_FUNCTION_ARGS) { char *jobName = NULL; char *attribute = NULL; bool value = false; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) value = PG_GETARG_BOOL(2); DbmsScheduler::Catalog::setAttributeBool(jobName, attribute, value); PG_RETURN_VOID(); } Datum c_setAttributeTimestamptz(PG_FUNCTION_ARGS) { char *jobName = NULL; char *attribute = NULL; TimestampTz value = 0; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (PG_ARGISNULL(2)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("attribute value cannot be NULL"))); } value = PG_GETARG_TIMESTAMPTZ(2); DbmsScheduler::Catalog::setAttributeTimestamptz(jobName, attribute, value); PG_RETURN_VOID(); } Datum c_setAttributeNull(PG_FUNCTION_ARGS) { char *jobName = NULL; char *attribute = NULL; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); DbmsScheduler::Catalog::setAttributeNull(jobName, attribute); PG_RETURN_VOID(); } Datum c_getAttribute(PG_FUNCTION_ARGS) { char *jobName = NULL; char *attribute = NULL; char *value; if (!PG_ARGISNULL(0)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(0)); if (!PG_ARGISNULL(1)) attribute = text_to_cstring(PG_GETARG_TEXT_PP(1)); value = DbmsScheduler::Catalog::getAttribute(jobName, attribute); if (value == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(value)); } Datum c_purgeLog(PG_FUNCTION_ARGS) { int32 history = 0; char *whichLog = NULL; char *jobName = NULL; if (!PG_ARGISNULL(0)) history = PG_GETARG_INT32(0); if (!PG_ARGISNULL(1)) whichLog = text_to_cstring(PG_GETARG_TEXT_PP(1)); if (!PG_ARGISNULL(2)) jobName = text_to_cstring(PG_GETARG_TEXT_PP(2)); DbmsScheduler::Catalog::purgeLog(history, whichLog, jobName); PG_RETURN_VOID(); } static char * argText(PG_FUNCTION_ARGS, int index) { if (PG_ARGISNULL(index)) return NULL; return text_to_cstring(PG_GETARG_TEXT_PP(index)); } Datum c_createSchedule(PG_FUNCTION_ARGS) { char *scheduleName = argText(fcinfo, 0); char *repeatInterval = argText(fcinfo, 2); char *comments = argText(fcinfo, 4); bool startNull = true; bool endNull = true; TimestampTz startDate = 0; TimestampTz endDate = 0; if (!PG_ARGISNULL(1)) { startNull = false; startDate = PG_GETARG_TIMESTAMPTZ(1); } if (!PG_ARGISNULL(3)) { endNull = false; endDate = PG_GETARG_TIMESTAMPTZ(3); } DbmsScheduler::Catalog::createSchedule(scheduleName, startNull, startDate, repeatInterval, endNull, endDate, comments); PG_RETURN_VOID(); } Datum c_createEventSchedule(PG_FUNCTION_ARGS) { char *scheduleName = argText(fcinfo, 0); char *eventCondition = argText(fcinfo, 2); char *queueSpec = argText(fcinfo, 3); char *comments = argText(fcinfo, 5); bool startNull = true; bool endNull = true; TimestampTz startDate = 0; TimestampTz endDate = 0; if (!PG_ARGISNULL(1)) { startNull = false; startDate = PG_GETARG_TIMESTAMPTZ(1); } if (!PG_ARGISNULL(4)) { endNull = false; endDate = PG_GETARG_TIMESTAMPTZ(4); } DbmsScheduler::Catalog::createEventSchedule(scheduleName, startNull, startDate, eventCondition, queueSpec, endNull, endDate, comments); PG_RETURN_VOID(); } Datum c_addEventQueueSubscriber(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::addEventQueueSubscriber(argText(fcinfo, 0)); PG_RETURN_VOID(); } Datum c_removeEventQueueSubscriber(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::removeEventQueueSubscriber(argText(fcinfo, 0)); PG_RETURN_VOID(); } Datum c_createFileWatcher(PG_FUNCTION_ARGS) { char *watcherName = argText(fcinfo, 0); char *directoryPath = argText(fcinfo, 1); char *fileName = argText(fcinfo, 2); char *credentialName = argText(fcinfo, 3); char *destination = argText(fcinfo, 4); char *comments = argText(fcinfo, 7); int32 minFileSize = 0; Interval *steady = NULL; bool enabled = true; if (!PG_ARGISNULL(5)) minFileSize = PG_GETARG_INT32(5); if (!PG_ARGISNULL(6)) steady = PG_GETARG_INTERVAL_P(6); if (!PG_ARGISNULL(8)) enabled = PG_GETARG_BOOL(8); DbmsScheduler::Catalog::createFileWatcher(watcherName, directoryPath, fileName, credentialName, destination, minFileSize, steady, comments, enabled); PG_RETURN_VOID(); } Datum c_dropFileWatcher(PG_FUNCTION_ARGS) { char *watcherName = argText(fcinfo, 0); bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropFileWatcher(watcherName, force); PG_RETURN_VOID(); } Datum c_defineChainEventStepSchedule(PG_FUNCTION_ARGS) { char *chainName = argText(fcinfo, 0); char *stepName = argText(fcinfo, 1); char *scheduleName = argText(fcinfo, 2); Interval *timeout = NULL; if (!PG_ARGISNULL(3)) timeout = PG_GETARG_INTERVAL_P(3); DbmsScheduler::Catalog::defineChainEventStepSchedule(chainName, stepName, scheduleName, timeout); PG_RETURN_VOID(); } Datum c_defineChainEventStepInline(PG_FUNCTION_ARGS) { char *chainName = argText(fcinfo, 0); char *stepName = argText(fcinfo, 1); char *eventCondition = argText(fcinfo, 2); char *queueSpec = argText(fcinfo, 3); Interval *timeout = NULL; if (!PG_ARGISNULL(4)) timeout = PG_GETARG_INTERVAL_P(4); DbmsScheduler::Catalog::defineChainEventStepInline(chainName, stepName, eventCondition, queueSpec, timeout); PG_RETURN_VOID(); } Datum c_addJobEmailNotification(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::addJobEmailNotification( argText(fcinfo, 0), argText(fcinfo, 1), argText(fcinfo, 2), argText(fcinfo, 3), argText(fcinfo, 4), argText(fcinfo, 5), argText(fcinfo, 6)); PG_RETURN_VOID(); } Datum c_removeJobEmailNotification(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::removeJobEmailNotification( argText(fcinfo, 0), argText(fcinfo, 1), argText(fcinfo, 2)); PG_RETURN_VOID(); } Datum c_createGroup(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::createGroup( argText(fcinfo, 0), argText(fcinfo, 1), argText(fcinfo, 2), argText(fcinfo, 3)); PG_RETURN_VOID(); } Datum c_dropGroup(PG_FUNCTION_ARGS) { bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropGroup(argText(fcinfo, 0), force); PG_RETURN_VOID(); } Datum c_addGroupMember(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::addGroupMember(argText(fcinfo, 0), argText(fcinfo, 1)); PG_RETURN_VOID(); } Datum c_removeGroupMember(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::removeGroupMember(argText(fcinfo, 0), argText(fcinfo, 1)); PG_RETURN_VOID(); } Datum c_createIncompatibility(PG_FUNCTION_ARGS) { bool enabled = true; if (!PG_ARGISNULL(3)) enabled = PG_GETARG_BOOL(3); DbmsScheduler::Catalog::createIncompatibility( argText(fcinfo, 0), argText(fcinfo, 1), argText(fcinfo, 2), enabled, argText(fcinfo, 4)); PG_RETURN_VOID(); } Datum c_dropIncompatibility(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::dropIncompatibility(argText(fcinfo, 0)); PG_RETURN_VOID(); } Datum c_addToIncompatibility(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::addToIncompatibility(argText(fcinfo, 0), argText(fcinfo, 1)); PG_RETURN_VOID(); } Datum c_removeFromIncompatibility(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::removeFromIncompatibility(argText(fcinfo, 0), argText(fcinfo, 1)); PG_RETURN_VOID(); } Datum c_createResource(PG_FUNCTION_ARGS) { bool unitsNull = PG_ARGISNULL(1); int32 units = 0; if (!unitsNull) units = PG_GETARG_INT32(1); DbmsScheduler::Catalog::createResource( argText(fcinfo, 0), unitsNull, units, argText(fcinfo, 2), argText(fcinfo, 3), argText(fcinfo, 4)); PG_RETURN_VOID(); } Datum c_dropResource(PG_FUNCTION_ARGS) { bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropResource(argText(fcinfo, 0), force); PG_RETURN_VOID(); } Datum c_setResourceConstraint(PG_FUNCTION_ARGS) { bool unitsNull = PG_ARGISNULL(2); int32 units = 1; if (!unitsNull) units = PG_GETARG_INT32(2); DbmsScheduler::Catalog::setResourceConstraint( argText(fcinfo, 0), argText(fcinfo, 1), unitsNull, units); PG_RETURN_VOID(); } Datum c_dropSchedule(PG_FUNCTION_ARGS) { char *scheduleName = argText(fcinfo, 0); bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropSchedule(scheduleName, force); PG_RETURN_VOID(); } Datum c_copyJob(PG_FUNCTION_ARGS) { char *oldJob = argText(fcinfo, 0); char *newJob = argText(fcinfo, 1); DbmsScheduler::Catalog::copyJob(oldJob, newJob); PG_RETURN_VOID(); } Datum c_createJobProgramSchedule(PG_FUNCTION_ARGS) { char *jobName = argText(fcinfo, 0); char *programName = argText(fcinfo, 1); char *scheduleName = argText(fcinfo, 2); char *jobClass = argText(fcinfo, 3); char *comments = argText(fcinfo, 6); char *jobStyle = argText(fcinfo, 7); char *credentialName = argText(fcinfo, 8); char *destinationName = argText(fcinfo, 9); bool enabled = false; bool autoDrop = true; if (!PG_ARGISNULL(4)) enabled = PG_GETARG_BOOL(4); if (!PG_ARGISNULL(5)) autoDrop = PG_GETARG_BOOL(5); DbmsScheduler::Catalog::createJobOnProgram(jobName, programName, scheduleName, true, 0, NULL, true, 0, jobClass, enabled, autoDrop, comments, jobStyle, credentialName, destinationName); PG_RETURN_VOID(); } Datum c_createJobProgramInline(PG_FUNCTION_ARGS) { char *jobName = argText(fcinfo, 0); char *programName = argText(fcinfo, 1); char *repeatInterval = argText(fcinfo, 3); char *jobClass = argText(fcinfo, 5); char *comments = argText(fcinfo, 8); char *jobStyle = argText(fcinfo, 9); char *credentialName = argText(fcinfo, 10); char *destinationName = argText(fcinfo, 11); bool startNull = true; bool endNull = true; TimestampTz startDate = 0; TimestampTz endDate = 0; bool enabled = false; bool autoDrop = true; if (!PG_ARGISNULL(2)) { startNull = false; startDate = PG_GETARG_TIMESTAMPTZ(2); } if (!PG_ARGISNULL(4)) { endNull = false; endDate = PG_GETARG_TIMESTAMPTZ(4); } if (!PG_ARGISNULL(6)) enabled = PG_GETARG_BOOL(6); if (!PG_ARGISNULL(7)) autoDrop = PG_GETARG_BOOL(7); DbmsScheduler::Catalog::createJobOnProgram(jobName, programName, NULL, startNull, startDate, repeatInterval, endNull, endDate, jobClass, enabled, autoDrop, comments, jobStyle, credentialName, destinationName); PG_RETURN_VOID(); } Datum c_createJobScheduleInline(PG_FUNCTION_ARGS) { char *jobName = argText(fcinfo, 0); char *scheduleName = argText(fcinfo, 1); char *jobType = argText(fcinfo, 2); char *jobAction = argText(fcinfo, 3); char *jobClass = argText(fcinfo, 5); char *comments = argText(fcinfo, 8); char *credentialName = argText(fcinfo, 9); char *destinationName = argText(fcinfo, 10); int32 numberOfArguments = 0; bool enabled = false; bool autoDrop = true; if (!PG_ARGISNULL(4)) numberOfArguments = PG_GETARG_INT32(4); if (!PG_ARGISNULL(6)) enabled = PG_GETARG_BOOL(6); if (!PG_ARGISNULL(7)) autoDrop = PG_GETARG_BOOL(7); DbmsScheduler::Catalog::createJobOnSchedule(jobName, scheduleName, jobType, jobAction, numberOfArguments, jobClass, enabled, autoDrop, comments, credentialName, destinationName); PG_RETURN_VOID(); } bool rudb_scheduler_log_run(const char *owner, const char *job_name, const char *status) { return DbmsScheduler::logRun(owner, job_name, status); } void rudb_scheduler_run_os_job(const char *owner, const char *job_name, const char *job_type, const char *job_action) { DbmsScheduler::runOsJob(owner, job_name, job_type, job_action); } Datum c_createJobClass(PG_FUNCTION_ARGS) { char *className = argText(fcinfo, 0); char *resourceGroup = argText(fcinfo, 1); char *service = argText(fcinfo, 2); char *comments = argText(fcinfo, 5); bool levelNull = true; bool historyNull = true; int32 loggingLevel = 0; int32 logHistory = 0; if (!PG_ARGISNULL(3)) { levelNull = false; loggingLevel = PG_GETARG_INT32(3); } if (!PG_ARGISNULL(4)) { historyNull = false; logHistory = PG_GETARG_INT32(4); } DbmsScheduler::Catalog::createJobClass(className, resourceGroup, service, levelNull, loggingLevel, historyNull, logHistory, comments); PG_RETURN_VOID(); } Datum c_dropJobClass(PG_FUNCTION_ARGS) { char *className = argText(fcinfo, 0); bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropJobClass(className, force); PG_RETURN_VOID(); } Datum c_setSchedulerAttribute(PG_FUNCTION_ARGS) { char *attribute = argText(fcinfo, 0); char *value = argText(fcinfo, 1); DbmsScheduler::Catalog::setSchedulerAttribute(attribute, value); PG_RETURN_VOID(); } Datum c_getSchedulerAttribute(PG_FUNCTION_ARGS) { char *attribute = argText(fcinfo, 0); char *value; value = DbmsScheduler::Catalog::getSchedulerAttribute(attribute); if (value == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(value)); } Datum c_createWindowCalendar(PG_FUNCTION_ARGS) { char *windowName = argText(fcinfo, 0); char *resourcePlan = argText(fcinfo, 1); char *repeatInterval = argText(fcinfo, 3); char *windowPriority = argText(fcinfo, 6); char *comments = argText(fcinfo, 7); bool startNull = true; bool endNull = true; bool enabled = true; TimestampTz startDate = 0; TimestampTz endDate = 0; Interval *duration = NULL; if (!PG_ARGISNULL(2)) { startNull = false; startDate = PG_GETARG_TIMESTAMPTZ(2); } if (!PG_ARGISNULL(4)) { endNull = false; endDate = PG_GETARG_TIMESTAMPTZ(4); } if (!PG_ARGISNULL(5)) duration = PG_GETARG_INTERVAL_P(5); if (!PG_ARGISNULL(8)) enabled = PG_GETARG_BOOL(8); DbmsScheduler::Catalog::createWindowCalendar(windowName, resourcePlan, startNull, startDate, repeatInterval, endNull, endDate, duration, windowPriority, comments, enabled); PG_RETURN_VOID(); } Datum c_createWindowSchedule(PG_FUNCTION_ARGS) { char *windowName = argText(fcinfo, 0); char *resourcePlan = argText(fcinfo, 1); char *scheduleName = argText(fcinfo, 2); char *windowPriority = argText(fcinfo, 4); char *comments = argText(fcinfo, 5); bool enabled = true; Interval *duration = NULL; if (!PG_ARGISNULL(3)) duration = PG_GETARG_INTERVAL_P(3); if (!PG_ARGISNULL(6)) enabled = PG_GETARG_BOOL(6); DbmsScheduler::Catalog::createWindowSchedule(windowName, resourcePlan, scheduleName, duration, windowPriority, comments, enabled); PG_RETURN_VOID(); } Datum c_dropWindow(PG_FUNCTION_ARGS) { char *windowName = argText(fcinfo, 0); bool force = false; if (!PG_ARGISNULL(1)) force = PG_GETARG_BOOL(1); DbmsScheduler::Catalog::dropWindow(windowName, force); PG_RETURN_VOID(); } Datum c_openWindow(PG_FUNCTION_ARGS) { char *windowName = argText(fcinfo, 0); bool force = false; Interval *duration = NULL; if (!PG_ARGISNULL(1)) duration = PG_GETARG_INTERVAL_P(1); if (!PG_ARGISNULL(2)) force = PG_GETARG_BOOL(2); DbmsScheduler::Catalog::openWindow(windowName, duration, force); PG_RETURN_VOID(); } Datum c_closeWindow(PG_FUNCTION_ARGS) { char *windowName = argText(fcinfo, 0); DbmsScheduler::Catalog::closeWindow(windowName); PG_RETURN_VOID(); } static int batchArrayCount(ArrayType *arr) { if (ARR_NDIM(arr) == 0) return 0; if (ARR_NDIM(arr) != 1) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job array must be one-dimensional"))); return ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr)); } static char ** copyTextArray(Datum value, bool isnull, int expect, MemoryContext ctx) { ArrayType *arr; Datum *elems; bool *nulls; int nitems; int16 typlen; bool typbyval; char typalign; char **out; MemoryContext old; int i; if (isnull) return NULL; arr = DatumGetArrayTypeP(value); nitems = batchArrayCount(arr); if (nitems == 0) return NULL; if (expect >= 0 && nitems != expect) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job array lengths do not match"))); get_typlenbyvalalign(ARR_ELEMTYPE(arr), &typlen, &typbyval, &typalign); deconstruct_array(arr, ARR_ELEMTYPE(arr), typlen, typbyval, typalign, &elems, &nulls, &nitems); old = MemoryContextSwitchTo(ctx); out = (char **) palloc(sizeof(char *) * nitems); for (i = 0; i < nitems; i++) out[i] = nulls[i] ? NULL : text_to_cstring(DatumGetTextPP(elems[i])); MemoryContextSwitchTo(old); return out; } static void copyIntArray(Datum value, bool isnull, int expect, MemoryContext ctx, int32 **out, bool **nullOut) { ArrayType *arr; Datum *elems; bool *nulls; int nitems; int16 typlen; bool typbyval; char typalign; int32 *vals; bool *flags; MemoryContext old; int i; *out = NULL; *nullOut = NULL; if (isnull) return; arr = DatumGetArrayTypeP(value); nitems = batchArrayCount(arr); if (nitems == 0) return; if (expect >= 0 && nitems != expect) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job array lengths do not match"))); get_typlenbyvalalign(ARR_ELEMTYPE(arr), &typlen, &typbyval, &typalign); deconstruct_array(arr, ARR_ELEMTYPE(arr), typlen, typbyval, typalign, &elems, &nulls, &nitems); old = MemoryContextSwitchTo(ctx); vals = (int32 *) palloc(sizeof(int32) * nitems); flags = (bool *) palloc(sizeof(bool) * nitems); for (i = 0; i < nitems; i++) { flags[i] = nulls[i]; vals[i] = nulls[i] ? 0 : DatumGetInt32(elems[i]); } MemoryContextSwitchTo(old); *out = vals; *nullOut = flags; } static void copyBoolArray(Datum value, bool isnull, int expect, MemoryContext ctx, bool **out, bool **nullOut) { ArrayType *arr; Datum *elems; bool *nulls; int nitems; int16 typlen; bool typbyval; char typalign; bool *vals; bool *flags; MemoryContext old; int i; *out = NULL; *nullOut = NULL; if (isnull) return; arr = DatumGetArrayTypeP(value); nitems = batchArrayCount(arr); if (nitems == 0) return; if (expect >= 0 && nitems != expect) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("job array lengths do not match"))); get_typlenbyvalalign(ARR_ELEMTYPE(arr), &typlen, &typbyval, &typalign); deconstruct_array(arr, ARR_ELEMTYPE(arr), typlen, typbyval, typalign, &elems, &nulls, &nitems); old = MemoryContextSwitchTo(ctx); vals = (bool *) palloc(sizeof(bool) * nitems); flags = (bool *) palloc(sizeof(bool) * nitems); for (i = 0; i < nitems; i++) { flags[i] = nulls[i]; vals[i] = nulls[i] ? false : DatumGetBool(elems[i]); } MemoryContextSwitchTo(old); *out = vals; *nullOut = flags; } Datum c_createJobs(PG_FUNCTION_ARGS) { MemoryContext batchCtx; MemoryContext old; char **jobName; char **jobType; char **jobAction; char **programName; char **repeatInterval; char **comments; char **jobClass; int32 *nargs = NULL; bool *nargsNull = NULL; bool *autoDrop = NULL; bool *autoDropNull = NULL; bool *enabled = NULL; bool *enabledNull = NULL; char *semantics = NULL; int n; ArrayType *names; if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_NAME cannot be NULL"))); if (!PG_ARGISNULL(10)) semantics = text_to_cstring(PG_GETARG_TEXT_PP(10)); names = DatumGetArrayTypeP(PG_GETARG_DATUM(0)); n = batchArrayCount(names); batchCtx = AllocSetContextCreate(TopMemoryContext, "dbms_scheduler batch", ALLOCSET_SMALL_SIZES); PG_TRY(); { old = MemoryContextSwitchTo(batchCtx); if (semantics != NULL) semantics = pstrdup(semantics); MemoryContextSwitchTo(old); jobName = copyTextArray(PG_GETARG_DATUM(0), false, n, batchCtx); jobType = copyTextArray(PG_ARGISNULL(1) ? (Datum) 0 : PG_GETARG_DATUM(1), PG_ARGISNULL(1), n, batchCtx); jobAction = copyTextArray(PG_ARGISNULL(2) ? (Datum) 0 : PG_GETARG_DATUM(2), PG_ARGISNULL(2), n, batchCtx); programName = copyTextArray(PG_ARGISNULL(3) ? (Datum) 0 : PG_GETARG_DATUM(3), PG_ARGISNULL(3), n, batchCtx); repeatInterval = copyTextArray(PG_ARGISNULL(4) ? (Datum) 0 : PG_GETARG_DATUM(4), PG_ARGISNULL(4), n, batchCtx); copyIntArray(PG_ARGISNULL(5) ? (Datum) 0 : PG_GETARG_DATUM(5), PG_ARGISNULL(5), n, batchCtx, &nargs, &nargsNull); comments = copyTextArray(PG_ARGISNULL(6) ? (Datum) 0 : PG_GETARG_DATUM(6), PG_ARGISNULL(6), n, batchCtx); copyBoolArray(PG_ARGISNULL(7) ? (Datum) 0 : PG_GETARG_DATUM(7), PG_ARGISNULL(7), n, batchCtx, &autoDrop, &autoDropNull); copyBoolArray(PG_ARGISNULL(8) ? (Datum) 0 : PG_GETARG_DATUM(8), PG_ARGISNULL(8), n, batchCtx, &enabled, &enabledNull); jobClass = copyTextArray(PG_ARGISNULL(9) ? (Datum) 0 : PG_GETARG_DATUM(9), PG_ARGISNULL(9), n, batchCtx); DbmsScheduler::Catalog::createJobs(jobName, jobType, jobAction, programName, repeatInterval, nargs, nargsNull, comments, autoDrop, autoDropNull, enabled, enabledNull, jobClass, n, semantics, batchCtx); if (CurrentMemoryContext == batchCtx) MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(batchCtx); } PG_CATCH(); { if (CurrentMemoryContext == batchCtx) MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(batchCtx); PG_RE_THROW(); } PG_END_TRY(); PG_RETURN_VOID(); } Datum c_setJobAttributes(PG_FUNCTION_ARGS) { MemoryContext batchCtx; MemoryContext old; char **jobName; char **attrName; char **attrValue; char *semantics = NULL; int n; ArrayType *names; if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("JOB_NAME cannot be NULL"))); if (!PG_ARGISNULL(3)) semantics = text_to_cstring(PG_GETARG_TEXT_PP(3)); names = DatumGetArrayTypeP(PG_GETARG_DATUM(0)); n = batchArrayCount(names); batchCtx = AllocSetContextCreate(TopMemoryContext, "dbms_scheduler batch", ALLOCSET_SMALL_SIZES); PG_TRY(); { old = MemoryContextSwitchTo(batchCtx); if (semantics != NULL) semantics = pstrdup(semantics); MemoryContextSwitchTo(old); jobName = copyTextArray(PG_GETARG_DATUM(0), false, -1, batchCtx); attrName = copyTextArray(PG_GETARG_DATUM(1), false, n, batchCtx); attrValue = copyTextArray(PG_GETARG_DATUM(2), false, n, batchCtx); DbmsScheduler::Catalog::setJobAttributes(jobName, attrName, attrValue, n, semantics, batchCtx); if (CurrentMemoryContext == batchCtx) MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(batchCtx); } PG_CATCH(); { if (CurrentMemoryContext == batchCtx) MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(batchCtx); PG_RE_THROW(); } PG_END_TRY(); PG_RETURN_VOID(); } static char * remoteArg(FunctionCallInfo fcinfo, int index) { if (PG_ARGISNULL(index)) return NULL; return text_to_cstring(PG_GETARG_TEXT_PP(index)); } Datum c_createDatabaseDestination(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::createDatabaseDestination( remoteArg(fcinfo, 0), remoteArg(fcinfo, 1), remoteArg(fcinfo, 2), remoteArg(fcinfo, 3)); PG_RETURN_VOID(); } Datum c_dropDatabaseDestination(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::dropDatabaseDestination(remoteArg(fcinfo, 0)); PG_RETURN_VOID(); } Datum c_dropAgentDestination(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::dropAgentDestination(remoteArg(fcinfo, 0)); PG_RETURN_VOID(); } Datum c_getAgentInfo(PG_FUNCTION_ARGS) { char *value; value = DbmsScheduler::Catalog::getAgentInfo(remoteArg(fcinfo, 0), remoteArg(fcinfo, 1)); if (value == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(value)); } Datum c_getAgentVersion(PG_FUNCTION_ARGS) { char *value; value = DbmsScheduler::Catalog::getAgentVersion(remoteArg(fcinfo, 0)); if (value == NULL) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(value)); } Datum c_setAgentRegistrationPass(PG_FUNCTION_ARGS) { bool expirationNull = PG_ARGISNULL(1); bool maxUsesNull = PG_ARGISNULL(2); TimestampTz expiration = 0; int32 maxUses = 0; if (!expirationNull) expiration = PG_GETARG_TIMESTAMPTZ(1); if (!maxUsesNull) maxUses = PG_GETARG_INT32(2); DbmsScheduler::Catalog::setAgentRegistrationPass( remoteArg(fcinfo, 0), expirationNull, expiration, maxUsesNull, maxUses); PG_RETURN_VOID(); } Datum c_getFileContents(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::getFileContents(PG_ARGISNULL(3)); PG_RETURN_VOID(); } Datum c_getFileDirectory(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::getFileDirectory( remoteArg(fcinfo, 0), remoteArg(fcinfo, 1), remoteArg(fcinfo, 2), remoteArg(fcinfo, 3), remoteArg(fcinfo, 4)); PG_RETURN_VOID(); } Datum c_putFileContents(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::putFileContents(remoteArg(fcinfo, 2)); PG_RETURN_VOID(); } Datum c_putFileDirectory(PG_FUNCTION_ARGS) { DbmsScheduler::Catalog::putFileDirectory( remoteArg(fcinfo, 2), remoteArg(fcinfo, 3), remoteArg(fcinfo, 4)); PG_RETURN_VOID(); } } // extern "C"