#include "dbms_ash.hpp" #include "ash.hpp" #include "awr.hpp" #include #include #include #include #include #include #include #include #include #include extern "C" { #include "executor/executor.h" #include "access/htup_details.h" #include "catalog/pg_class.h" #include "catalog/pg_proc.h" #include "common/md5.h" #include "mb/pg_wchar.h" #include "miscadmin.h" #include "tcop/tcopprot.h" #include "tcop/utility.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/guc.h" #include "utils/fmgrprotos.h" #include "utils/lsyscache.h" #include "utils/numeric.h" #include "utils/syscache.h" #include "utils/timestamp.h" } // extern "C" extern "C" { PG_FUNCTION_INFO_V1(dbms_ash_fetch_obj_name); PG_FUNCTION_INFO_V1(dbms_ash_fetch_procedure_name); PG_FUNCTION_INFO_V1(dbms_ash_sql_id); PG_FUNCTION_INFO_V1(dbms_ash_fetch_sqltext); PG_FUNCTION_INFO_V1(dbms_ash_fetch_user_name); PG_FUNCTION_INFO_V1(dbms_ash_getadditionalinfo); PG_FUNCTION_INFO_V1(dbms_ash_getawrinfo); PG_FUNCTION_INFO_V1(dbms_ash_getcpuinfo); PG_FUNCTION_INFO_V1(dbms_ash_getdata); PG_FUNCTION_INFO_V1(dbms_ash_getdatahistorical); PG_FUNCTION_INFO_V1(dbms_ash_getdatarealtime); PG_FUNCTION_INFO_V1(dbms_ash_gethistogramhistorical); PG_FUNCTION_INFO_V1(dbms_ash_gethistogramrealtime); PG_FUNCTION_INFO_V1(dbms_ash_getsqltext); PG_FUNCTION_INFO_V1(dbms_ash_gettimeformat); PG_FUNCTION_INFO_V1(dbms_ash_gettimepickerhistorical); PG_FUNCTION_INFO_V1(dbms_ash_gettimepickerrealtime); PG_FUNCTION_INFO_V1(dbms_ash_getversion); PG_FUNCTION_INFO_V1(dbms_ash_get_blocking_session_data); PG_FUNCTION_INFO_V1(dbms_ash_incrementdata); PG_FUNCTION_INFO_V1(dbms_ash_incrementhistogram); PG_FUNCTION_INFO_V1(dbms_ash_incrementtimepicker); PG_FUNCTION_INFO_V1(dbms_ash_str_to_ascii); PG_FUNCTION_INFO_V1(dbms_ash_get_version); } // extern "C" #define RUDB_DBMS_ASH_VERSION "1.0.0" namespace { struct ResolutionInfo { const char* name; int bucket_count; }; template void prune_oldest_entries(std::vector& entries, std::size_t max_entries, Accessor accessor) { if (entries.size() <= max_entries) return; std::sort(entries.begin(), entries.end(), [&](const Entry& left, const Entry& right) { return accessor(left) < accessor(right); }); entries.erase(entries.begin(), entries.begin() + static_cast::difference_type>(entries.size() - max_entries)); } std::string trim_ascii_copy(const std::string& value) { std::size_t begin = 0; std::size_t end = value.size(); while (begin < end && std::isspace(static_cast(value[begin])) != 0) ++begin; while (end > begin && std::isspace(static_cast(value[end - 1])) != 0) --end; return value.substr(begin, end - begin); } std::optional text_arg_to_string(FunctionCallInfo fcinfo, int argno) { if (PG_ARGISNULL(argno)) return std::nullopt; char* value = text_to_cstring(PG_GETARG_TEXT_PP(argno)); std::string result(value); pfree(value); return result; } std::optional number_arg_to_int64(FunctionCallInfo fcinfo, int argno) { if (PG_ARGISNULL(argno)) return std::nullopt; Numeric value = PG_GETARG_NUMERIC(argno); return DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(value))); } std::optional number_arg_to_oid(FunctionCallInfo fcinfo, int argno) { const std::optional value = number_arg_to_int64(fcinfo, argno); if (!value.has_value()) return std::nullopt; if (*value <= 0 || static_cast(*value) > std::numeric_limits::max()) return std::nullopt; return static_cast(*value); } std::optional parse_yes_no_flag_strict(const std::optional& value) { if (!value.has_value()) return std::nullopt; const std::string trimmed = trim_ascii_copy(*value); if (trimmed.empty()) return std::nullopt; if (pg_strcasecmp(trimmed.c_str(), "Y") == 0) return true; if (pg_strcasecmp(trimmed.c_str(), "N") == 0) return false; return std::nullopt; } bool parse_yes_no_flag_default(const std::optional& value, bool default_value) { const std::optional parsed = parse_yes_no_flag_strict(value); return parsed.has_value() ? *parsed : default_value; } ResolutionInfo normalize_resolution(const std::optional& value) { if (!value.has_value()) return {"MEDIUM", 180}; const std::string trimmed = trim_ascii_copy(*value); if (pg_strcasecmp(trimmed.c_str(), "LOW") == 0) return {"LOW", 120}; if (pg_strcasecmp(trimmed.c_str(), "HIGH") == 0) return {"HIGH", 360}; return {"MEDIUM", 180}; } std::string xml_escape_impl(const std::string& value) { std::string result; result.reserve(value.size()); for (const char ch : value) { switch (ch) { case '&': result += "&"; break; case '<': result += "<"; break; case '>': result += ">"; break; case '"': result += """; break; case '\'': result += "'"; break; default: result.push_back(ch); break; } } return result; } std::string dbms_ash_xml_escape_internal(const std::string& value) { return xml_escape_impl(value); } std::optional build_obj_name_xml(const std::string& qualified_name, const std::string& object_type) { return "" + dbms_ash_xml_escape_internal(qualified_name) + "" + dbms_ash_xml_escape_internal(object_type) + ""; } std::optional lookup_local_relation_xml(Oid relation_oid) { HeapTuple rel_tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relation_oid)); if (!HeapTupleIsValid(rel_tuple)) return std::nullopt; Form_pg_class rel_form = (Form_pg_class) GETSTRUCT(rel_tuple); std::optional result = std::nullopt; const char* type_name = nullptr; switch (rel_form->relkind) { case RELKIND_RELATION: type_name = "TABLE"; break; case RELKIND_INDEX: type_name = "INDEX"; break; case RELKIND_SEQUENCE: type_name = "SEQUENCE"; break; case RELKIND_VIEW: type_name = "VIEW"; break; case RELKIND_MATVIEW: type_name = "MATERIALIZED VIEW"; break; case RELKIND_FOREIGN_TABLE: type_name = "FOREIGN TABLE"; break; default: break; } if (type_name != nullptr) { char* schema_name = get_namespace_name(rel_form->relnamespace); if (schema_name != nullptr) { result = build_obj_name_xml(std::string(schema_name) + "." + NameStr(rel_form->relname), type_name); pfree(schema_name); } } ReleaseSysCache(rel_tuple); return result; } std::optional lookup_standalone_routine_name(Oid procedure_oid, int64 subprogram_id) { if (subprogram_id != 1) return std::nullopt; HeapTuple proc_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(procedure_oid)); if (!HeapTupleIsValid(proc_tuple)) return std::nullopt; Form_pg_proc proc_form = (Form_pg_proc) GETSTRUCT(proc_tuple); std::optional result = std::nullopt; if (proc_form->prokind == PROKIND_FUNCTION || proc_form->prokind == PROKIND_PROCEDURE) { char* schema_name = get_namespace_name(proc_form->pronamespace); if (schema_name != nullptr) { result = std::string(schema_name) + "." + NameStr(proc_form->proname) + "."; pfree(schema_name); } } ReleaseSysCache(proc_tuple); return result; } std::optional lookup_user_name(Oid role_oid) { if (!SearchSysCacheExists1(AUTHOID, ObjectIdGetDatum(role_oid))) return std::nullopt; char* role_name = GetUserNameFromId(role_oid, true); if (role_name == nullptr) return std::nullopt; std::string result(role_name); pfree(role_name); return result; } int64 normalize_time_since_sec(const std::optional& time_since_sec) { if (!time_since_sec.has_value() || *time_since_sec <= 0) return 86400; return *time_since_sec; } [[noreturn]] void raise_not_supported(const char* function_name) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("DBMS_ASH.%s is not supported", function_name))); pg_unreachable(); } } // namespace extern "C" void dbms_ash_init(void) { rudb_awr_init(); } Datum dbms_ash_fetch_obj_name(PG_FUNCTION_ARGS) { const std::optional object_oid = number_arg_to_oid(fcinfo, 0); const std::optional is_local = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 3)); const std::optional is_old = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 5)); if (!object_oid.has_value() || !is_local.has_value() || !is_old.has_value()) PG_RETURN_NULL(); if (*is_local) { const std::optional result = lookup_local_relation_xml(*object_oid); if (!result.has_value()) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(result->c_str())); } PG_RETURN_NULL(); } Datum dbms_ash_fetch_procedure_name(PG_FUNCTION_ARGS) { const std::optional procedure_oid = number_arg_to_oid(fcinfo, 0); const std::optional subprogram_id = number_arg_to_int64(fcinfo, 1); if (!procedure_oid.has_value() || !subprogram_id.has_value()) PG_RETURN_NULL(); const std::optional result = lookup_standalone_routine_name(*procedure_oid, *subprogram_id); if (!result.has_value()) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(result->c_str())); } Datum dbms_ash_sql_id(PG_FUNCTION_ARGS) { const std::optional sql_text = text_arg_to_string(fcinfo, 0); if (!sql_text.has_value()) PG_RETURN_NULL(); const std::string normalized_sql = trim_ascii_copy(*sql_text); if (normalized_sql.empty()) PG_RETURN_NULL(); const std::string sql_id = rudb::ash::compute_sql_id(normalized_sql); PG_RETURN_TEXT_P(cstring_to_text(sql_id.c_str())); } Datum dbms_ash_fetch_sqltext(PG_FUNCTION_ARGS) { const std::optional sql_id = text_arg_to_string(fcinfo, 0); const std::optional is_local = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 3)); const std::optional is_pdb = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 4)); const std::optional is_old = parse_yes_no_flag_strict(text_arg_to_string(fcinfo, 5)); if (!sql_id.has_value() || sql_id->empty()) PG_RETURN_NULL(); if (!is_local.has_value() || !is_pdb.has_value() || !is_old.has_value()) PG_RETURN_NULL(); const std::optional xml = rudb::ash::lookup_sql_text(*sql_id, *is_local, !*is_local && *is_old); if (!xml.has_value()) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(xml->c_str())); } Datum dbms_ash_fetch_user_name(PG_FUNCTION_ARGS) { const std::optional role_oid = number_arg_to_oid(fcinfo, 0); const std::optional con_dbid = number_arg_to_int64(fcinfo, 1); if (!role_oid.has_value() || (con_dbid.has_value() && *con_dbid < 0)) PG_RETURN_NULL(); const std::optional result = lookup_user_name(*role_oid); if (!result.has_value()) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(result->c_str())); } Datum dbms_ash_getadditionalinfo(PG_FUNCTION_ARGS) { raise_not_supported("GETADDITIONALINFO"); } Datum dbms_ash_getawrinfo(PG_FUNCTION_ARGS) { raise_not_supported("GETAWRINFO"); } Datum dbms_ash_getcpuinfo(PG_FUNCTION_ARGS) { raise_not_supported("GETCPUINFO"); } Datum dbms_ash_getdata(PG_FUNCTION_ARGS) { raise_not_supported("GETDATA"); } Datum dbms_ash_getdatahistorical(PG_FUNCTION_ARGS) { raise_not_supported("GETDATAHISTORICAL"); } Datum dbms_ash_getdatarealtime(PG_FUNCTION_ARGS) { raise_not_supported("GETDATAREALTIME"); } Datum dbms_ash_gethistogramhistorical(PG_FUNCTION_ARGS) { raise_not_supported("GETHISTOGRAMHISTORICAL"); } Datum dbms_ash_gethistogramrealtime(PG_FUNCTION_ARGS) { raise_not_supported("GETHISTOGRAMREALTIME"); } Datum dbms_ash_getsqltext(PG_FUNCTION_ARGS) { raise_not_supported("GETSQLTEXT"); } Datum dbms_ash_gettimeformat(PG_FUNCTION_ARGS) { raise_not_supported("GETTIMEFORMAT"); } Datum dbms_ash_gettimepickerhistorical(PG_FUNCTION_ARGS) { rudb::ash::TimepickerRequest request; request.begin_time_utc = text_arg_to_string(fcinfo, 1); request.end_time_utc = text_arg_to_string(fcinfo, 2); request.time_since_sec = normalize_time_since_sec(number_arg_to_int64(fcinfo, 3)); request.show_sql = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 4), false); request.verbose_xml = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 5), false); request.instance_number = number_arg_to_int64(fcinfo, 6); request.awr_info = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 7), false); request.ignore_cpu_history = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 8), false); request.resolution = normalize_resolution(text_arg_to_string(fcinfo, 9)).name; request.include_bg = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 10), false); request.memory_only = parse_yes_no_flag_default(text_arg_to_string(fcinfo, 11), false); std::string xml = rudb::ash::build_timepicker_core_xml(request); if (request.awr_info) { rudb::awr::TimepickerMetadataRequest awr_request; awr_request.include_metadata = true; awr_request.dbid = rudb::awr::local_dbid(); awr_request.retention_seconds = rudb::ash::retention_seconds(); const std::string awr_xml = rudb::awr::build_timepicker_metadata_xml(awr_request); const std::size_t insert_pos = xml.find("(utf8_input); *ptr != '\0';) { const int char_len = pg_utf_mblen(ptr); const pg_wchar codepoint = utf8_to_unicode(ptr); if (codepoint >= 0x20 && codepoint <= 0x7E) { result.push_back(static_cast(codepoint)); } else { char buffer[16]; std::snprintf(buffer, sizeof(buffer), "\\%04X", static_cast(codepoint)); result += buffer; } ptr += char_len; } if (utf8_input != input_cstr) pfree(utf8_input); pfree(input_cstr); PG_RETURN_TEXT_P(cstring_to_text(result.c_str())); } Datum dbms_ash_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_ASH_VERSION)); }