#include "ash.hpp"
|
|
/*
|
* Серверные процессы публикуют текущий SQL-оператор
|
* в слотах активности разделяемой памяти.
|
*
|
* Фоновый процесс периодически сохраняет устойчивые слоты
|
* в кольцевой буфер записей ASH. Полный текст SQL хранится
|
* отдельно в блочном кэше. При создании снимка AWR выбранные
|
* записи переносятся в постоянное историческое хранилище.
|
*/
|
|
#include <algorithm>
|
#include <array>
|
#include <cctype>
|
#include <cstddef>
|
#include <cstdint>
|
#include <exception>
|
#include <cstdio>
|
#include <cstring>
|
#include <limits>
|
#include <map>
|
#include <iterator>
|
#include <optional>
|
#include <set>
|
#include <string>
|
#include <vector>
|
|
extern "C"
|
{
|
#include "access/subtrans.h"
|
#include "access/xact.h"
|
#include "catalog/pg_authid_d.h"
|
#include "catalog/pg_type_d.h"
|
#include "commands/dbcommands.h"
|
#include "common/md5.h"
|
#include "executor/executor.h"
|
#include "executor/spi.h"
|
#include "fmgr.h"
|
#include "libpq/pqsignal.h"
|
#include "miscadmin.h"
|
#include "postmaster/bgworker.h"
|
#include "postmaster/interrupt.h"
|
#include "portability/instr_time.h"
|
#include "storage/ipc.h"
|
#include "storage/latch.h"
|
#include "storage/lwlock.h"
|
#include "storage/proc.h"
|
#include "storage/procsignal.h"
|
#include "storage/shmem.h"
|
#include "tcop/tcopprot.h"
|
#include "tcop/utility.h"
|
#include "utils/acl.h"
|
#include "utils/builtins.h"
|
#include "utils/date.h"
|
#include "utils/elog.h"
|
#include "utils/guc.h"
|
#include "utils/guc_hooks.h"
|
#include "utils/memutils.h"
|
#include "utils/ps_status.h"
|
#include "utils/rudb_ash_startup.h"
|
#include "utils/snapmgr.h"
|
#include "utils/timestamp.h"
|
#include "utils/wait_event.h"
|
}
|
|
namespace
|
{
|
constexpr uint32 kAshMagic = 0x52554442U;
|
constexpr uint32 kAshVersion = 2;
|
constexpr int kDefaultRetentionSeconds = 86400;
|
constexpr int kDefaultSampleIntervalMs = 1000;
|
constexpr uint32 kMaxModuleNameLength = NAMEDATALEN;
|
constexpr uint32 kMaxEventLength = 96;
|
constexpr uint32 kMaxStateLength = 24;
|
constexpr uint32 kSampleCapacity = 8192;
|
constexpr uint32 kSqlCacheCapacity = 1024;
|
constexpr uint32 kSqlChunkCapacity = 8192;
|
constexpr uint32 kSqlChunkPayloadLength = 256;
|
constexpr uint64 kMaxSqlTextBytes =
|
static_cast<uint64>(kSqlChunkCapacity) * kSqlChunkPayloadLength;
|
constexpr uint32 kInvalidChunkIndex = std::numeric_limits<uint32>::max();
|
constexpr uint32 kSampleSequenceCounterBits = 20;
|
constexpr uint64 kSampleSequenceCounterLimit = UINT64CONST(1) << kSampleSequenceCounterBits;
|
constexpr uint32 kWorkerLockCount = 1;
|
constexpr const char* kAshShmemName = "rudb_ash";
|
constexpr const char* kAshTrancheName = "rudb_ash";
|
constexpr const char* kHistorySampleTable = "pg_catalog.rudb_ash_history_samples";
|
constexpr const char* kHistorySqlTextTable = "pg_catalog.rudb_ash_history_sqltext";
|
constexpr const char* kAwrSnapshotTable = "pg_catalog.rudb_awr_snapshots";
|
constexpr const char* kAwrSnapshotSequence = "pg_catalog.rudb_awr_snapshot_id_seq";
|
|
struct ResolutionInfo
|
{
|
const char* name;
|
int bucket_count;
|
};
|
|
struct AshActivitySlot
|
{
|
/*
|
* Один слот соответствует одному серверному процессу.
|
* Нечётное значение `publish_seq` означает запись,
|
* чётное позволяет читателю проверить устойчивость данных.
|
*/
|
pg_atomic_uint64 generation;
|
pg_atomic_uint64 publish_seq;
|
pg_atomic_uint64 started_at;
|
pg_atomic_uint32 active;
|
uint32 wait_event_info;
|
int pid;
|
int proc_number;
|
int64 session_generation;
|
int backend_type;
|
Oid user_id;
|
Oid database_id;
|
uint32 sql_cache_slot;
|
uint64 sql_cache_generation;
|
char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
|
char module_name[kMaxModuleNameLength];
|
char application_name[kMaxModuleNameLength];
|
char state[kMaxStateLength];
|
};
|
|
struct ActivitySlotSnapshot
|
{
|
uint64 generation = 0;
|
uint64 started_at = 0;
|
uint32 active = 0;
|
uint32 wait_event_info = 0;
|
int pid = 0;
|
int proc_number = 0;
|
int64 session_generation = 0;
|
int backend_type = 0;
|
Oid user_id = InvalidOid;
|
Oid database_id = InvalidOid;
|
uint32 sql_cache_slot = kSqlCacheCapacity;
|
uint64 sql_cache_generation = 0;
|
char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
|
char module_name[kMaxModuleNameLength];
|
char application_name[kMaxModuleNameLength];
|
char state[kMaxStateLength];
|
};
|
|
struct AshSharedSample
|
{
|
/* `sample_sequence` однозначно определяет запись ASH, а
|
* `sample_generation` защищает повторное использование ячейки кольцевого буфера. */
|
uint64 sample_sequence;
|
uint64 sample_generation;
|
uint64 activity_generation;
|
TimestampTz sample_time;
|
int64 dbid;
|
int64 instance_number;
|
int64 session_id;
|
int64 session_serial;
|
int64 session_generation;
|
TimestampTz started_at;
|
int backend_type;
|
int64 snap_id;
|
Oid user_id;
|
uint32 wait_event_info;
|
bool is_awr_sample;
|
bool sql_text_complete;
|
uint32 sql_cache_slot;
|
uint64 sql_cache_generation;
|
char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
|
char module_name[kMaxModuleNameLength];
|
char application_name[kMaxModuleNameLength];
|
char state[kMaxStateLength];
|
char command_type[16];
|
};
|
|
struct AshSharedSqlTextEntry
|
{
|
/*
|
* Каталог содержит метаданные текста SQL, а сами данные
|
* размещаются в цепочке блоков. Запись нельзя вытеснять,
|
* пока её счётчик ссылок больше нуля.
|
*/
|
uint64 generation;
|
TimestampTz first_seen;
|
TimestampTz last_seen;
|
int64 dbid;
|
Oid user_id;
|
uint64 refcount;
|
uint32 head_chunk;
|
uint32 byte_length;
|
bool complete;
|
char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
|
char command_type[16];
|
};
|
|
struct AshSharedSqlTextChunk
|
{
|
/* Полный текст SQL хранится цепочкой блоков; при совпадении SQL_ID
|
* с другим текстом SQL источник возвращает пустой результат. */
|
uint32 next_chunk;
|
uint32 used_bytes;
|
char payload[kSqlChunkPayloadLength];
|
};
|
|
struct AshSharedHeader
|
{
|
uint32 magic;
|
uint32 version;
|
uint32 activity_slot_count;
|
uint32 sample_capacity;
|
uint32 sql_cache_capacity;
|
uint32 sample_interval_ms;
|
uint32 retention_seconds;
|
pid_t worker_pid;
|
uint64 sample_sequence_epoch_milliseconds;
|
uint64 next_local_sample_sequence;
|
/* Последовательность определяет запись ASH, а позиция — физическую
|
* ячейку кольцевого буфера фиксированного размера. */
|
uint64 next_ring_position;
|
uint64 next_sample_generation;
|
uint64 next_sql_cache_generation;
|
uint64 last_sample_time;
|
uint64 worker_cycles;
|
uint64 dropped_samples;
|
uint64 active_slots_seen;
|
uint64 samples_written;
|
uint64 reject_unstable_publication;
|
uint64 reject_inactive_slot;
|
uint64 reject_invalid_proc_number;
|
uint64 reject_missing_pgproc;
|
uint64 reject_pid_mismatch;
|
uint64 reject_self_pid;
|
uint64 reject_invalid_database;
|
uint64 reject_sql_cache_reference;
|
/* Список свободных блоков текста SQL изменяется под `g_ash_lock`. */
|
uint32 free_sql_chunk_head;
|
uint32 free_sql_chunk_count;
|
};
|
|
struct ReportStats
|
{
|
std::size_t sample_count_total = 0;
|
std::size_t sample_count_matched = 0;
|
std::size_t sql_text_entry_count = 0;
|
std::size_t distinct_sql_id_count_matched = 0;
|
std::optional<std::string> top_sql_id;
|
std::optional<std::string> top_wait_class;
|
};
|
|
struct MemoryArchiveCandidate
|
{
|
rudb::ash::SampleRow row;
|
uint64 sample_generation = 0;
|
uint64 activity_generation = 0;
|
uint32 sql_cache_slot = kSqlCacheCapacity;
|
uint64 sql_cache_generation = 0;
|
};
|
|
struct SharedSampleSnapshot
|
{
|
AshSharedSample sample;
|
bool sql_reference_retained = false;
|
};
|
|
struct PendingArchiveMark
|
{
|
uint64 sample_sequence = 0;
|
uint64 sample_generation = 0;
|
uint64 activity_generation = 0;
|
int64 snap_id = 0;
|
SubTransactionId subxid = InvalidSubTransactionId;
|
};
|
|
struct PendingSnapshotClearMark
|
{
|
int64 dbid = 0;
|
int64 low_snap_id = 0;
|
int64 high_snap_id = 0;
|
SubTransactionId subxid = InvalidSubTransactionId;
|
};
|
|
struct ActivityFrame
|
{
|
std::string normalized_sql;
|
std::string sql_id;
|
std::string command_type;
|
std::string state;
|
std::string module_name;
|
std::string application_name;
|
TimestampTz started_at = 0;
|
uint32 sql_cache_slot = 0;
|
uint64 sql_cache_generation = 0;
|
int nest_level = 0;
|
SubTransactionId subxid = InvalidSubTransactionId;
|
const void* owner = nullptr;
|
bool published = false;
|
};
|
|
enum class SlotReadResult
|
{
|
SampleReady,
|
Inactive,
|
UnstablePublication,
|
InvalidProcNumber,
|
MissingProc,
|
PidMismatch,
|
SelfPid,
|
InvalidDatabase
|
};
|
|
bool g_gucs_defined = false;
|
bool g_postmaster_initialized = false;
|
bool g_backend_initialized = false;
|
bool g_archive_backend_initialized = false;
|
bool g_hooks_installed = false;
|
bool g_xact_callbacks_installed = false;
|
bool g_subxact_callbacks_installed = false;
|
volatile sig_atomic_t g_worker_shutdown_requested = false;
|
int g_retention_seconds = kDefaultRetentionSeconds;
|
int g_sample_interval_ms = kDefaultSampleIntervalMs;
|
bool g_capture_enabled = false;
|
|
shmem_request_hook_type g_prev_shmem_request_hook = nullptr;
|
shmem_startup_hook_type g_prev_shmem_startup_hook = nullptr;
|
ExecutorStart_hook_type g_prev_executor_start_hook = nullptr;
|
ExecutorEnd_hook_type g_prev_executor_end_hook = nullptr;
|
ProcessUtility_hook_type g_prev_process_utility_hook = nullptr;
|
|
AshSharedHeader* g_shared = nullptr;
|
LWLock* g_ash_lock = nullptr;
|
|
std::vector<PendingArchiveMark>&
|
pending_archive_marks(void)
|
{
|
static auto* marks = new std::vector<PendingArchiveMark>();
|
return *marks;
|
}
|
|
std::vector<PendingSnapshotClearMark>&
|
pending_snapshot_clear_marks(void)
|
{
|
static auto* marks = new std::vector<PendingSnapshotClearMark>();
|
return *marks;
|
}
|
|
std::vector<ActivityFrame>&
|
activity_stack(void)
|
{
|
static auto* frames = new std::vector<ActivityFrame>();
|
return *frames;
|
}
|
|
inline uint32
|
activity_slot_count(void)
|
{
|
return static_cast<uint32>(MaxBackends + NUM_AUXILIARY_PROCS);
|
}
|
|
inline Size
|
activity_slots_size(void)
|
{
|
return mul_size(activity_slot_count(), sizeof(AshActivitySlot));
|
}
|
|
inline Size
|
sample_ring_size(void)
|
{
|
return mul_size(kSampleCapacity, sizeof(AshSharedSample));
|
}
|
|
inline Size
|
sql_cache_size(void)
|
{
|
return mul_size(kSqlCacheCapacity, sizeof(AshSharedSqlTextEntry));
|
}
|
|
inline Size
|
sql_chunk_arena_size(void)
|
{
|
return mul_size(kSqlChunkCapacity, sizeof(AshSharedSqlTextChunk));
|
}
|
|
Size
|
shared_state_size(void)
|
{
|
Size size = MAXALIGN(sizeof(AshSharedHeader));
|
size = add_size(size, activity_slots_size());
|
size = add_size(size, sample_ring_size());
|
size = add_size(size, sql_cache_size());
|
size = add_size(size, sql_chunk_arena_size());
|
return MAXALIGN(size);
|
}
|
|
inline AshActivitySlot*
|
activity_slots(void)
|
{
|
return reinterpret_cast<AshActivitySlot*>(
|
reinterpret_cast<char*>(g_shared) + MAXALIGN(sizeof(AshSharedHeader)));
|
}
|
|
inline AshSharedSample*
|
sample_ring(void)
|
{
|
return reinterpret_cast<AshSharedSample*>(
|
reinterpret_cast<char*>(activity_slots()) + activity_slots_size());
|
}
|
|
inline AshSharedSqlTextEntry*
|
sql_cache(void)
|
{
|
return reinterpret_cast<AshSharedSqlTextEntry*>(
|
reinterpret_cast<char*>(sample_ring()) + sample_ring_size());
|
}
|
|
inline AshSharedSqlTextChunk*
|
sql_chunk_arena(void)
|
{
|
return reinterpret_cast<AshSharedSqlTextChunk*>(
|
reinterpret_cast<char*>(sql_cache()) + sql_cache_size());
|
}
|
|
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<unsigned char>(value[begin])) != 0)
|
++begin;
|
|
while (end > begin && std::isspace(static_cast<unsigned char>(value[end - 1])) != 0)
|
--end;
|
|
return value.substr(begin, end - begin);
|
}
|
|
std::string
|
uppercase_ascii_copy(const std::string& value)
|
{
|
std::string result = value;
|
std::transform(result.begin(), result.end(), result.begin(),
|
[](unsigned char ch) { return static_cast<char>(std::toupper(ch)); });
|
return result;
|
}
|
|
std::string
|
xml_escape(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;
|
}
|
|
void
|
copy_cstring_field(char* dest, std::size_t capacity, const std::string& value)
|
{
|
if (capacity == 0)
|
return;
|
|
snprintf(dest, capacity, "%s", value.c_str());
|
}
|
|
void
|
copy_cstring_field(char* dest, std::size_t capacity, const char* value)
|
{
|
if (capacity == 0)
|
return;
|
|
snprintf(dest, capacity, "%s", value != nullptr ? value : "");
|
}
|
|
std::string
|
cstring_field_to_string(const char* value)
|
{
|
return value == nullptr ? std::string() : std::string(value);
|
}
|
|
bool
|
is_valid_chunk_index(uint32 chunk_index)
|
{
|
return chunk_index < kSqlChunkCapacity;
|
}
|
|
void
|
push_free_chunk(uint32 chunk_index)
|
{
|
if (!is_valid_chunk_index(chunk_index))
|
return;
|
|
AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
std::memset(&chunk, 0, sizeof(chunk));
|
if (g_shared->free_sql_chunk_count >= kSqlChunkCapacity)
|
return;
|
chunk.next_chunk = g_shared->free_sql_chunk_head;
|
g_shared->free_sql_chunk_head = chunk_index;
|
++g_shared->free_sql_chunk_count;
|
}
|
|
bool
|
free_list_contains_chunk(uint32 chunk_index)
|
{
|
uint32 current = g_shared->free_sql_chunk_head;
|
uint32 visited = 0;
|
|
while (current != kInvalidChunkIndex)
|
{
|
if (!is_valid_chunk_index(current) || visited >= kSqlChunkCapacity)
|
return false;
|
if (current == chunk_index)
|
return true;
|
|
current = sql_chunk_arena()[current].next_chunk;
|
++visited;
|
}
|
|
return false;
|
}
|
|
std::optional<uint32>
|
pop_free_chunk(void)
|
{
|
if (g_shared->free_sql_chunk_head == kInvalidChunkIndex || g_shared->free_sql_chunk_count == 0)
|
return std::nullopt;
|
|
const uint32 chunk_index = g_shared->free_sql_chunk_head;
|
if (!is_valid_chunk_index(chunk_index))
|
{
|
g_shared->free_sql_chunk_head = kInvalidChunkIndex;
|
g_shared->free_sql_chunk_count = 0;
|
return std::nullopt;
|
}
|
|
AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
g_shared->free_sql_chunk_head = chunk.next_chunk;
|
--g_shared->free_sql_chunk_count;
|
std::memset(&chunk, 0, sizeof(chunk));
|
chunk.next_chunk = kInvalidChunkIndex;
|
return chunk_index;
|
}
|
|
bool
|
read_sql_text_from_entry(const AshSharedSqlTextEntry& entry, std::string* result)
|
{
|
// Проверяем всю цепочку текущего поколения до выделения памяти,
|
// чтобы повреждённые метаданные не увеличили размер отчёта.
|
if (result == nullptr)
|
return false;
|
|
result->clear();
|
if (entry.generation == 0 || !entry.complete || entry.byte_length > kMaxSqlTextBytes)
|
return false;
|
if (entry.byte_length == 0)
|
return entry.head_chunk == kInvalidChunkIndex;
|
if (!is_valid_chunk_index(entry.head_chunk))
|
return false;
|
|
uint64 required_chunks =
|
(static_cast<uint64>(entry.byte_length) + kSqlChunkPayloadLength - 1) /
|
kSqlChunkPayloadLength;
|
if (required_chunks == 0 || required_chunks > kSqlChunkCapacity)
|
return false;
|
|
uint32 chunk_index = entry.head_chunk;
|
uint64 consumed_bytes = 0;
|
for (uint64 chunk_no = 0; chunk_no < required_chunks; ++chunk_no)
|
{
|
if (!is_valid_chunk_index(chunk_index))
|
return false;
|
|
const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
if (chunk.used_bytes > kSqlChunkPayloadLength)
|
return false;
|
if (consumed_bytes > entry.byte_length ||
|
chunk.used_bytes > entry.byte_length - consumed_bytes)
|
return false;
|
consumed_bytes += chunk.used_bytes;
|
if (chunk_no + 1 == required_chunks)
|
{
|
if (chunk.next_chunk != kInvalidChunkIndex)
|
return false;
|
}
|
else if (chunk.next_chunk == kInvalidChunkIndex)
|
return false;
|
|
chunk_index = chunk.next_chunk;
|
}
|
|
if (consumed_bytes != entry.byte_length)
|
return false;
|
|
result->reserve(entry.byte_length);
|
chunk_index = entry.head_chunk;
|
while (chunk_index != kInvalidChunkIndex)
|
{
|
const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
result->append(chunk.payload, chunk.used_bytes);
|
chunk_index = chunk.next_chunk;
|
}
|
return true;
|
}
|
|
void
|
release_chunk_chain(uint32 head_chunk)
|
{
|
// Блоки возвращаются после удаления ссылки каталога под `g_ash_lock`.
|
uint32 chunk_index = head_chunk;
|
uint32 released = 0;
|
|
while (chunk_index != kInvalidChunkIndex && released < kSqlChunkCapacity)
|
{
|
if (!is_valid_chunk_index(chunk_index))
|
return;
|
if (free_list_contains_chunk(chunk_index))
|
return;
|
|
AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
const uint32 next_chunk = chunk.next_chunk;
|
push_free_chunk(chunk_index);
|
chunk_index = next_chunk;
|
++released;
|
}
|
}
|
|
struct SqlChunkChain
|
{
|
uint32 head = kInvalidChunkIndex;
|
uint32 tail = kInvalidChunkIndex;
|
uint32 chunk_count = 0;
|
};
|
|
std::optional<SqlChunkChain>
|
allocate_chunk_chain(const std::string& sql_text)
|
{
|
// Берёт блоки из списка свободных ячеек целиком, чтобы запись
|
// каталога не указывала на неполный текст SQL.
|
SqlChunkChain chain;
|
|
if (sql_text.empty())
|
return chain;
|
if (sql_text.size() > std::numeric_limits<uint32>::max())
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("SQL text RUDB ASH превышает поддерживаемый размер")));
|
}
|
|
const std::size_t required_chunk_count =
|
(sql_text.size() / kSqlChunkPayloadLength) +
|
(sql_text.size() % kSqlChunkPayloadLength == 0 ? 0 : 1);
|
if (required_chunk_count > std::numeric_limits<uint32>::max())
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("переполнено число chunks RUDB ASH SQL text")));
|
}
|
const uint32 required_chunks = static_cast<uint32>(required_chunk_count);
|
if (required_chunks == 0 || required_chunks > g_shared->free_sql_chunk_count)
|
return std::nullopt;
|
|
for (uint32 idx = 0; idx < required_chunks; ++idx)
|
{
|
const std::optional<uint32> chunk_index = pop_free_chunk();
|
if (!chunk_index.has_value())
|
{
|
release_chunk_chain(chain.head);
|
return std::nullopt;
|
}
|
|
if (chain.head == kInvalidChunkIndex)
|
chain.head = *chunk_index;
|
else
|
sql_chunk_arena()[chain.tail].next_chunk = *chunk_index;
|
chain.tail = *chunk_index;
|
++chain.chunk_count;
|
}
|
|
std::size_t offset = 0;
|
for (uint32 chunk_index = chain.head;
|
chunk_index != kInvalidChunkIndex;
|
chunk_index = sql_chunk_arena()[chunk_index].next_chunk)
|
{
|
AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
const std::size_t used =
|
std::min<std::size_t>(sql_text.size() - offset, kSqlChunkPayloadLength);
|
std::memcpy(chunk.payload, sql_text.data() + offset, used);
|
chunk.used_bytes = static_cast<uint32>(used);
|
offset += used;
|
}
|
|
return chain;
|
}
|
|
void
|
reset_sql_text_entry(AshSharedSqlTextEntry& entry)
|
{
|
if (entry.head_chunk != kInvalidChunkIndex)
|
release_chunk_chain(entry.head_chunk);
|
|
std::memset(&entry, 0, sizeof(entry));
|
entry.head_chunk = kInvalidChunkIndex;
|
}
|
|
bool
|
sql_text_entry_matches(const AshSharedSqlTextEntry& entry, const std::string& sql_id, int64 dbid)
|
{
|
return entry.generation != 0 &&
|
entry.dbid == dbid &&
|
std::strcmp(entry.sql_id, sql_id.c_str()) == 0;
|
}
|
|
bool
|
retain_sql_text_reference_locked(uint32 slot, uint64 generation)
|
{
|
if (slot >= kSqlCacheCapacity)
|
return false;
|
|
AshSharedSqlTextEntry& entry = sql_cache()[slot];
|
if (entry.generation == generation && entry.generation != 0)
|
{
|
++entry.refcount;
|
return true;
|
}
|
|
return false;
|
}
|
|
void
|
release_sql_text_reference_locked(uint32 slot, uint64 generation)
|
{
|
if (slot >= kSqlCacheCapacity)
|
return;
|
|
AshSharedSqlTextEntry& entry = sql_cache()[slot];
|
if (entry.generation == generation && entry.generation != 0 && entry.refcount > 0)
|
--entry.refcount;
|
}
|
|
int64
|
local_dbid_impl(Oid database_id)
|
{
|
const uint64 db_oid = static_cast<uint64>(database_id == InvalidOid ? 1 : database_id);
|
return static_cast<int64>((db_oid << 32) | 1ULL);
|
}
|
|
ResolutionInfo
|
normalize_resolution(const std::string& value)
|
{
|
if (pg_strcasecmp(value.c_str(), "LOW") == 0)
|
return {"LOW", 120};
|
|
if (pg_strcasecmp(value.c_str(), "HIGH") == 0)
|
return {"HIGH", 360};
|
|
return {"MEDIUM", 180};
|
}
|
|
int64
|
ceil_div(int64 numerator, int64 denominator)
|
{
|
return denominator == 0 ? 0 : (numerator + denominator - 1) / denominator;
|
}
|
|
const char*
|
command_type_for_operation(CmdType operation)
|
{
|
switch (operation)
|
{
|
case CMD_SELECT:
|
return "SELECT";
|
case CMD_UPDATE:
|
return "UPDATE";
|
case CMD_INSERT:
|
return "INSERT";
|
case CMD_DELETE:
|
return "DELETE";
|
case CMD_UTILITY:
|
return "UTILITY";
|
default:
|
return "SQL";
|
}
|
}
|
|
std::string
|
normalize_command_type(const std::optional<std::string>& command_type)
|
{
|
if (!command_type.has_value())
|
return "SQL";
|
|
const std::string trimmed = trim_ascii_copy(*command_type);
|
return trimmed.empty() ? "SQL" : uppercase_ascii_copy(trimmed);
|
}
|
|
std::string
|
wait_class_for_info(uint32 wait_event_info)
|
{
|
const char* wait_type = pgstat_get_wait_event_type(wait_event_info);
|
|
if (wait_type == nullptr || wait_type[0] == '\0')
|
return "CPU";
|
|
if (pg_strcasecmp(wait_type, "Activity") == 0)
|
return "Idle";
|
|
return std::string(wait_type);
|
}
|
|
std::string
|
wait_event_for_info(uint32 wait_event_info)
|
{
|
const char* wait_event = pgstat_get_wait_event(wait_event_info);
|
return wait_event == nullptr ? std::string() : std::string(wait_event);
|
}
|
|
void
|
ash_worker_die(SIGNAL_ARGS)
|
{
|
int save_errno = errno;
|
g_worker_shutdown_requested = true;
|
if (MyLatch != nullptr)
|
SetLatch(MyLatch);
|
errno = save_errno;
|
}
|
|
void
|
define_gucs(void)
|
{
|
if (g_gucs_defined)
|
return;
|
|
DefineCustomBoolVariable("dbms_ash.enabled",
|
"Enable RUDB ASH runtime.",
|
"Controls publication and sampling of active statements.",
|
&g_capture_enabled,
|
false,
|
PGC_SUSET,
|
0,
|
nullptr,
|
nullptr,
|
nullptr);
|
|
DefineCustomIntVariable("dbms_ash.retention",
|
"Retention of RUDB ASH samples in seconds.",
|
"Time eligibility for ASH samples; the 8192-slot shared-memory ring can evict samples early, counted by ash_dropped_samples.",
|
&g_retention_seconds,
|
kDefaultRetentionSeconds,
|
1,
|
std::numeric_limits<int>::max(),
|
PGC_SIGHUP,
|
0,
|
nullptr,
|
nullptr,
|
nullptr);
|
|
DefineCustomIntVariable("dbms_ash.sample_interval_ms",
|
"RUDB ASH sampler interval in milliseconds.",
|
"Controls the sampling interval of the shared-memory ASH worker.",
|
&g_sample_interval_ms,
|
kDefaultSampleIntervalMs,
|
100,
|
60000,
|
PGC_POSTMASTER,
|
0,
|
nullptr,
|
nullptr,
|
nullptr);
|
|
g_gucs_defined = true;
|
}
|
|
void
|
request_shared_resources(void)
|
{
|
if (g_prev_shmem_request_hook != nullptr)
|
g_prev_shmem_request_hook();
|
|
RequestAddinShmemSpace(shared_state_size());
|
RequestNamedLWLockTranche(kAshTrancheName, kWorkerLockCount);
|
}
|
|
void
|
initialize_shared_state(bool found)
|
{
|
g_ash_lock = &GetNamedLWLockTranche(kAshTrancheName)[0].lock;
|
|
if (found)
|
return;
|
|
std::memset(g_shared, 0, shared_state_size());
|
g_shared->magic = kAshMagic;
|
g_shared->version = kAshVersion;
|
g_shared->activity_slot_count = activity_slot_count();
|
g_shared->sample_capacity = kSampleCapacity;
|
g_shared->sql_cache_capacity = kSqlCacheCapacity;
|
g_shared->sample_interval_ms = static_cast<uint32>(g_sample_interval_ms);
|
g_shared->retention_seconds = static_cast<uint32>(g_retention_seconds);
|
g_shared->worker_pid = 0;
|
g_shared->sample_sequence_epoch_milliseconds =
|
static_cast<uint64>(GetCurrentTimestamp() / INT64CONST(1000));
|
g_shared->next_local_sample_sequence = 0;
|
g_shared->next_ring_position = 0;
|
g_shared->next_sample_generation = 1;
|
g_shared->next_sql_cache_generation = 1;
|
g_shared->free_sql_chunk_head = kSqlChunkCapacity == 0 ? kInvalidChunkIndex : 0;
|
g_shared->free_sql_chunk_count = kSqlChunkCapacity;
|
|
for (uint32 idx = 0; idx < kSqlCacheCapacity; ++idx)
|
sql_cache()[idx].head_chunk = kInvalidChunkIndex;
|
|
for (uint32 idx = 0; idx < g_shared->activity_slot_count; ++idx)
|
{
|
AshActivitySlot& slot = activity_slots()[idx];
|
pg_atomic_init_u64(&slot.generation, 0);
|
pg_atomic_init_u64(&slot.publish_seq, 0);
|
pg_atomic_init_u64(&slot.started_at, 0);
|
pg_atomic_init_u32(&slot.active, 0);
|
slot.sql_cache_slot = kSqlCacheCapacity;
|
}
|
|
for (uint32 idx = 0; idx < kSqlChunkCapacity; ++idx)
|
{
|
AshSharedSqlTextChunk& chunk = sql_chunk_arena()[idx];
|
std::memset(&chunk, 0, sizeof(chunk));
|
chunk.next_chunk = idx + 1 < kSqlChunkCapacity ? idx + 1 : kInvalidChunkIndex;
|
}
|
}
|
|
void
|
startup_shared_state(void)
|
{
|
bool found = false;
|
|
if (g_prev_shmem_startup_hook != nullptr)
|
g_prev_shmem_startup_hook();
|
|
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
|
g_shared = static_cast<AshSharedHeader*>(ShmemInitStruct(kAshShmemName,
|
shared_state_size(),
|
&found));
|
initialize_shared_state(found);
|
LWLockRelease(AddinShmemInitLock);
|
}
|
|
void
|
register_worker(void)
|
{
|
/* Product background workers must stay quiescent during pg_upgrade. */
|
if (IsBinaryUpgrade)
|
return;
|
|
BackgroundWorker worker;
|
std::memset(&worker, 0, sizeof(worker));
|
|
snprintf(worker.bgw_name, BGW_MAXLEN, "RUDB ASH sampler");
|
snprintf(worker.bgw_type, BGW_MAXLEN, "RUDB ASH sampler");
|
snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
|
snprintf(worker.bgw_function_name, BGW_MAXLEN, "rudb_ash_worker_main");
|
worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
|
worker.bgw_start_time = BgWorkerStart_PostmasterStart;
|
worker.bgw_restart_time = 1;
|
worker.bgw_notify_pid = 0;
|
worker.bgw_main_arg = (Datum) 0;
|
RegisterBackgroundWorker(&worker);
|
}
|
|
void
|
ensure_shared_state_attached(void)
|
{
|
bool found = false;
|
|
if (g_shared != nullptr && g_ash_lock != nullptr)
|
return;
|
|
g_shared = static_cast<AshSharedHeader*>(ShmemInitStruct(kAshShmemName,
|
shared_state_size(),
|
&found));
|
g_ash_lock = &GetNamedLWLockTranche(kAshTrancheName)[0].lock;
|
}
|
|
struct SqlCacheRef
|
{
|
uint32 slot = kSqlCacheCapacity;
|
uint64 generation = 0;
|
bool complete = false;
|
};
|
|
SqlCacheRef
|
invalid_sql_cache_ref(void)
|
{
|
return {};
|
}
|
|
bool
|
sql_text_entry_complete_match(const AshSharedSqlTextEntry& entry, const std::string& sql_text)
|
{
|
if (!entry.complete || entry.byte_length != sql_text.size())
|
return false;
|
|
if (entry.generation == 0 || !entry.complete || entry.byte_length > kMaxSqlTextBytes)
|
return false;
|
if (entry.byte_length == 0)
|
return entry.head_chunk == kInvalidChunkIndex;
|
if (!is_valid_chunk_index(entry.head_chunk))
|
return false;
|
|
const uint64 required_chunks =
|
(static_cast<uint64>(entry.byte_length) + kSqlChunkPayloadLength - 1) /
|
kSqlChunkPayloadLength;
|
if (required_chunks == 0 || required_chunks > kSqlChunkCapacity)
|
return false;
|
|
uint32 chunk_index = entry.head_chunk;
|
std::size_t compared_bytes = 0;
|
for (uint64 chunk_no = 0; chunk_no < required_chunks; ++chunk_no)
|
{
|
if (!is_valid_chunk_index(chunk_index))
|
return false;
|
|
const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
|
if (chunk.used_bytes > kSqlChunkPayloadLength)
|
return false;
|
if (compared_bytes > sql_text.size() ||
|
chunk.used_bytes > sql_text.size() - compared_bytes)
|
return false;
|
if (std::memcmp(chunk.payload, sql_text.data() + compared_bytes, chunk.used_bytes) != 0)
|
return false;
|
compared_bytes += chunk.used_bytes;
|
if (chunk_no + 1 == required_chunks)
|
{
|
if (chunk.next_chunk != kInvalidChunkIndex)
|
return false;
|
}
|
else if (chunk.next_chunk == kInvalidChunkIndex)
|
return false;
|
|
chunk_index = chunk.next_chunk;
|
}
|
|
return compared_bytes == sql_text.size();
|
}
|
|
SqlCacheRef
|
update_sql_cache_locked(const std::string& sql_id,
|
const std::string& sql_text,
|
const std::string& command_type,
|
Oid user_id,
|
int64 dbid,
|
TimestampTz now)
|
{
|
// Повторно используется только запись без ссылок; при совпадении SQL_ID
|
// с другим текстом SQL источник возвращает пустой результат.
|
AshSharedSqlTextEntry* cache = sql_cache();
|
uint32 target = kSqlCacheCapacity;
|
uint64 oldest_generation = std::numeric_limits<uint64>::max();
|
|
for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
|
{
|
if (sql_text_entry_matches(cache[idx], sql_id, dbid))
|
{
|
if (sql_text_entry_complete_match(cache[idx], sql_text))
|
{
|
cache[idx].last_seen = now;
|
cache[idx].user_id = user_id;
|
copy_cstring_field(cache[idx].command_type, sizeof(cache[idx].command_type), command_type);
|
return {idx, cache[idx].generation, cache[idx].complete};
|
}
|
|
return invalid_sql_cache_ref();
|
}
|
|
if (cache[idx].generation == 0)
|
{
|
target = idx;
|
break;
|
}
|
|
if (cache[idx].refcount == 0 && cache[idx].generation < oldest_generation)
|
{
|
oldest_generation = cache[idx].generation;
|
target = idx;
|
}
|
}
|
|
if (target >= g_shared->sql_cache_capacity)
|
return invalid_sql_cache_ref();
|
|
AshSharedSqlTextEntry& entry = cache[target];
|
const std::optional<SqlChunkChain> chain = allocate_chunk_chain(sql_text);
|
if (!chain.has_value())
|
return invalid_sql_cache_ref();
|
|
if (entry.generation != 0 && entry.refcount != 0)
|
{
|
release_chunk_chain(chain->head);
|
return invalid_sql_cache_ref();
|
}
|
|
reset_sql_text_entry(entry);
|
|
if (g_shared->next_sql_cache_generation == std::numeric_limits<uint64>::max())
|
{
|
release_chunk_chain(chain->head);
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("переполнен счётчик поколений RUDB ASH SQL cache")));
|
}
|
entry.generation = g_shared->next_sql_cache_generation++;
|
entry.first_seen = now;
|
entry.last_seen = now;
|
entry.dbid = dbid;
|
entry.user_id = user_id;
|
entry.refcount = 0;
|
entry.complete = true;
|
entry.byte_length = static_cast<uint32>(sql_text.size());
|
entry.head_chunk = chain->head;
|
copy_cstring_field(entry.sql_id, sizeof(entry.sql_id), sql_id);
|
copy_cstring_field(entry.command_type, sizeof(entry.command_type), command_type);
|
|
return {target, entry.generation, entry.complete};
|
}
|
|
void
|
begin_slot_publication(AshActivitySlot& slot, uint64 next_generation, TimestampTz started_at)
|
{
|
pg_atomic_write_u64(&slot.publish_seq, next_generation * 2 - 1);
|
pg_memory_barrier();
|
pg_atomic_write_u64(&slot.started_at, static_cast<uint64>(started_at));
|
pg_atomic_write_u64(&slot.generation, next_generation);
|
}
|
|
void
|
finish_slot_publication(AshActivitySlot& slot, bool active)
|
{
|
pg_memory_barrier();
|
pg_atomic_write_u32(&slot.active, active ? 1U : 0U);
|
pg_atomic_write_u64(&slot.publish_seq, pg_atomic_read_u64(&slot.generation) * 2);
|
}
|
|
ActivityFrame
|
build_activity_frame(const std::string& sql_text,
|
const std::string& command_type,
|
const std::string& state)
|
{
|
ActivityFrame frame;
|
frame.normalized_sql = trim_ascii_copy(sql_text);
|
if (frame.normalized_sql.empty())
|
return frame;
|
|
frame.sql_id = rudb::ash::compute_sql_id(frame.normalized_sql);
|
frame.command_type = command_type;
|
frame.state = state;
|
frame.module_name = application_name != nullptr ? application_name : "";
|
frame.application_name = application_name != nullptr ? application_name : "";
|
frame.started_at = GetCurrentTimestamp();
|
frame.nest_level = GetCurrentTransactionNestLevel();
|
frame.subxid = GetCurrentSubTransactionId();
|
return frame;
|
}
|
|
void
|
publish_frame_locked(ActivityFrame& frame)
|
{
|
// Слот активности и ссылка на текст SQL изменяются под одной
|
// блокировкой, чтобы фоновый процесс не увидел данные разных поколений.
|
AshActivitySlot& slot = activity_slots()[MyProcNumber];
|
const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
|
const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
|
const SqlCacheRef sql_cache_ref =
|
update_sql_cache_locked(frame.sql_id,
|
frame.normalized_sql,
|
frame.command_type,
|
GetUserId(),
|
local_dbid_impl(MyDatabaseId),
|
frame.started_at);
|
const bool retained = sql_cache_ref.generation != 0 &&
|
retain_sql_text_reference_locked(sql_cache_ref.slot, sql_cache_ref.generation);
|
const SqlCacheRef published_ref = retained ? sql_cache_ref : invalid_sql_cache_ref();
|
|
const uint64 next_generation = pg_atomic_read_u64(&slot.generation) + 1;
|
begin_slot_publication(slot, next_generation, frame.started_at);
|
copy_cstring_field(slot.sql_id, sizeof(slot.sql_id), frame.sql_id);
|
copy_cstring_field(slot.module_name, sizeof(slot.module_name), frame.module_name);
|
copy_cstring_field(slot.application_name, sizeof(slot.application_name), frame.application_name);
|
copy_cstring_field(slot.state, sizeof(slot.state), frame.state);
|
slot.sql_cache_slot = published_ref.slot;
|
slot.sql_cache_generation = published_ref.generation;
|
slot.wait_event_info = MyProc->wait_event_info;
|
slot.pid = MyProcPid;
|
slot.proc_number = MyProcNumber;
|
slot.session_generation = static_cast<int64>(MyStartTimestamp);
|
slot.backend_type = static_cast<int>(MyBackendType);
|
slot.user_id = GetUserId();
|
slot.database_id = MyDatabaseId;
|
finish_slot_publication(slot, true);
|
|
if (previous_sql_cache_generation != 0)
|
release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
|
|
frame.sql_cache_slot = published_ref.slot;
|
frame.sql_cache_generation = published_ref.generation;
|
frame.published = true;
|
}
|
|
void
|
publish_frame(ActivityFrame& frame)
|
{
|
if (!g_capture_enabled || !AmRegularBackendProcess() || MyProc == nullptr ||
|
frame.normalized_sql.empty())
|
return;
|
|
ensure_shared_state_attached();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
publish_frame_locked(frame);
|
LWLockRelease(g_ash_lock);
|
}
|
|
void clear_activity(void);
|
|
void
|
restore_outer_activity(void)
|
{
|
if (!g_capture_enabled)
|
{
|
clear_activity();
|
return;
|
}
|
|
if (activity_stack().empty())
|
return;
|
|
ActivityFrame& outer = activity_stack().back();
|
if (outer.published)
|
publish_frame(outer);
|
}
|
|
void
|
finish_current_activity_frame(const void* owner)
|
{
|
if (activity_stack().empty() || activity_stack().back().owner != owner)
|
return;
|
|
activity_stack().pop_back();
|
if (activity_stack().empty())
|
clear_activity();
|
else
|
restore_outer_activity();
|
}
|
|
void
|
clear_activity_locked(void)
|
{
|
// Освобождает ссылку слота активности; ссылка записи ASH сохраняется
|
// до вытеснения из кольцевого буфера.
|
AshActivitySlot& slot = activity_slots()[MyProcNumber];
|
const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
|
const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
|
|
begin_slot_publication(slot, pg_atomic_read_u64(&slot.generation) + 1, 0);
|
slot.wait_event_info = 0;
|
slot.sql_cache_slot = kSqlCacheCapacity;
|
slot.sql_cache_generation = 0;
|
slot.pid = MyProcPid;
|
slot.proc_number = MyProcNumber;
|
slot.session_generation = static_cast<int64>(MyStartTimestamp);
|
slot.backend_type = static_cast<int>(MyBackendType);
|
slot.state[0] = '\0';
|
slot.sql_id[0] = '\0';
|
slot.module_name[0] = '\0';
|
slot.application_name[0] = '\0';
|
slot.user_id = InvalidOid;
|
slot.database_id = InvalidOid;
|
finish_slot_publication(slot, false);
|
|
if (previous_sql_cache_generation != 0)
|
release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
|
}
|
|
void
|
clear_stale_activity_locked(AshActivitySlot& slot)
|
{
|
const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
|
const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
|
|
begin_slot_publication(slot, pg_atomic_read_u64(&slot.generation) + 1, 0);
|
slot.wait_event_info = 0;
|
slot.sql_cache_slot = kSqlCacheCapacity;
|
slot.sql_cache_generation = 0;
|
slot.pid = 0;
|
slot.proc_number = -1;
|
slot.session_generation = 0;
|
slot.backend_type = 0;
|
slot.state[0] = '\0';
|
slot.sql_id[0] = '\0';
|
slot.module_name[0] = '\0';
|
slot.application_name[0] = '\0';
|
slot.user_id = InvalidOid;
|
slot.database_id = InvalidOid;
|
finish_slot_publication(slot, false);
|
|
if (previous_sql_cache_generation != 0)
|
release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
|
}
|
|
void
|
clear_activity(void)
|
{
|
if (!g_backend_initialized || !AmRegularBackendProcess() || MyProc == nullptr)
|
return;
|
|
ensure_shared_state_attached();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
clear_activity_locked();
|
LWLockRelease(g_ash_lock);
|
}
|
|
void
|
backend_shutdown(int, Datum)
|
{
|
pending_archive_marks().clear();
|
pending_snapshot_clear_marks().clear();
|
activity_stack().clear();
|
clear_activity();
|
}
|
|
bool
|
sql_cache_reference_matches(const AshSharedSample& sample, const AshSharedSqlTextEntry& entry)
|
{
|
return entry.generation == sample.sql_cache_generation &&
|
entry.dbid == sample.dbid &&
|
entry.complete &&
|
std::strcmp(entry.sql_id, sample.sql_id) == 0;
|
}
|
|
bool
|
populate_sample_sql_reference_locked(AshSharedSample* sample)
|
{
|
if (sample == nullptr || sample->sql_cache_generation == 0)
|
return false;
|
if (sample->sql_cache_slot >= g_shared->sql_cache_capacity)
|
return false;
|
|
AshSharedSqlTextEntry& entry = sql_cache()[sample->sql_cache_slot];
|
if (!sql_cache_reference_matches(*sample, entry))
|
return false;
|
if (!retain_sql_text_reference_locked(sample->sql_cache_slot, sample->sql_cache_generation))
|
return false;
|
|
sample->sql_text_complete = true;
|
return true;
|
}
|
|
SlotReadResult
|
read_published_slot(AshActivitySlot& slot, AshSharedSample* sample, TimestampTz sample_time)
|
{
|
ActivitySlotSnapshot snapshot{};
|
|
for (int attempt = 0; attempt < 3; ++attempt)
|
{
|
const uint64 begin_seq = pg_atomic_read_u64(&slot.publish_seq);
|
if ((begin_seq & 1U) != 0)
|
return SlotReadResult::UnstablePublication;
|
|
pg_memory_barrier();
|
snapshot.wait_event_info = slot.wait_event_info;
|
snapshot.pid = slot.pid;
|
snapshot.proc_number = slot.proc_number;
|
snapshot.session_generation = slot.session_generation;
|
snapshot.backend_type = slot.backend_type;
|
snapshot.user_id = slot.user_id;
|
snapshot.database_id = slot.database_id;
|
snapshot.sql_cache_slot = slot.sql_cache_slot;
|
snapshot.sql_cache_generation = slot.sql_cache_generation;
|
std::memcpy(snapshot.sql_id, slot.sql_id, sizeof(snapshot.sql_id));
|
std::memcpy(snapshot.module_name, slot.module_name, sizeof(snapshot.module_name));
|
std::memcpy(snapshot.application_name, slot.application_name, sizeof(snapshot.application_name));
|
std::memcpy(snapshot.state, slot.state, sizeof(snapshot.state));
|
snapshot.generation = pg_atomic_read_u64(&slot.generation);
|
snapshot.started_at = pg_atomic_read_u64(&slot.started_at);
|
snapshot.active = pg_atomic_read_u32(&slot.active);
|
|
pg_memory_barrier();
|
|
const uint64 end_seq = pg_atomic_read_u64(&slot.publish_seq);
|
if (begin_seq != end_seq || (end_seq & 1U) != 0)
|
continue;
|
|
if (snapshot.active == 0)
|
return SlotReadResult::Inactive;
|
if (snapshot.proc_number < 0 ||
|
static_cast<uint32>(snapshot.proc_number) >= g_shared->activity_slot_count ||
|
ProcGlobal == nullptr ||
|
static_cast<uint32>(snapshot.proc_number) >= ProcGlobal->allProcCount ||
|
snapshot.pid <= 0)
|
return SlotReadResult::InvalidProcNumber;
|
if (snapshot.database_id == InvalidOid)
|
return SlotReadResult::InvalidDatabase;
|
|
PGPROC* proc = GetPGProcByNumber(snapshot.proc_number);
|
if (proc == nullptr)
|
return SlotReadResult::MissingProc;
|
if (proc->pid != snapshot.pid)
|
return SlotReadResult::PidMismatch;
|
if (snapshot.pid == MyProcPid)
|
return SlotReadResult::SelfPid;
|
|
std::memset(sample, 0, sizeof(*sample));
|
sample->activity_generation = snapshot.generation;
|
sample->sample_time = sample_time;
|
sample->dbid = local_dbid_impl(snapshot.database_id);
|
sample->instance_number = 1;
|
sample->session_id = snapshot.pid;
|
sample->session_serial = 0;
|
sample->session_generation = snapshot.session_generation;
|
sample->started_at = static_cast<TimestampTz>(snapshot.started_at);
|
sample->backend_type = snapshot.backend_type;
|
sample->user_id = snapshot.user_id;
|
const uint32 wait_event_info = proc->wait_event_info;
|
if (proc->pid != snapshot.pid)
|
return SlotReadResult::PidMismatch;
|
sample->wait_event_info = wait_event_info;
|
sample->is_awr_sample = false;
|
sample->sql_text_complete = false;
|
sample->sql_cache_slot = snapshot.sql_cache_slot;
|
sample->sql_cache_generation = snapshot.sql_cache_generation;
|
copy_cstring_field(sample->sql_id, sizeof(sample->sql_id), snapshot.sql_id);
|
copy_cstring_field(sample->module_name, sizeof(sample->module_name), snapshot.module_name);
|
copy_cstring_field(sample->application_name, sizeof(sample->application_name), snapshot.application_name);
|
copy_cstring_field(sample->state, sizeof(sample->state), snapshot.state);
|
if (snapshot.sql_cache_generation != 0 && snapshot.sql_cache_slot < g_shared->sql_cache_capacity)
|
{
|
const AshSharedSqlTextEntry& entry = sql_cache()[snapshot.sql_cache_slot];
|
if (entry.generation == snapshot.sql_cache_generation)
|
{
|
copy_cstring_field(sample->command_type, sizeof(sample->command_type),
|
entry.command_type);
|
}
|
else
|
{
|
sample->command_type[0] = '\0';
|
++g_shared->reject_sql_cache_reference;
|
}
|
}
|
if (sample->sql_cache_generation != 0 && !populate_sample_sql_reference_locked(sample))
|
{
|
sample->sql_cache_slot = kSqlCacheCapacity;
|
sample->sql_cache_generation = 0;
|
sample->sql_text_complete = false;
|
++g_shared->reject_sql_cache_reference;
|
}
|
return SlotReadResult::SampleReady;
|
}
|
|
return SlotReadResult::UnstablePublication;
|
}
|
|
bool
|
sample_is_retained(const AshSharedSample& sample, TimestampTz sample_time)
|
{
|
if (sample.sample_sequence == 0)
|
return false;
|
|
const TimestampTz cutoff = sample_time - static_cast<TimestampTz>(g_shared->retention_seconds) * USECS_PER_SEC;
|
return sample.sample_time >= cutoff;
|
}
|
|
void
|
release_sample_sql_reference_locked(AshSharedSample& sample)
|
{
|
if (sample.sql_cache_generation != 0)
|
release_sql_text_reference_locked(sample.sql_cache_slot, sample.sql_cache_generation);
|
|
sample.sql_cache_slot = kSqlCacheCapacity;
|
sample.sql_cache_generation = 0;
|
sample.sql_text_complete = false;
|
}
|
|
void
|
clear_expired_samples_locked(TimestampTz sample_time)
|
{
|
AshSharedSample* samples = sample_ring();
|
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
AshSharedSample& sample = samples[idx];
|
if (sample.sample_sequence == 0 || sample_is_retained(sample, sample_time))
|
continue;
|
|
release_sample_sql_reference_locked(sample);
|
std::memset(&sample, 0, sizeof(sample));
|
sample.sql_cache_slot = kSqlCacheCapacity;
|
}
|
}
|
|
void
|
capture_sample_locked(AshActivitySlot& slot, TimestampTz sample_time)
|
{
|
AshSharedSample* samples = sample_ring();
|
AshSharedSample candidate{};
|
const SlotReadResult read_result = read_published_slot(slot, &candidate, sample_time);
|
switch (read_result)
|
{
|
case SlotReadResult::SampleReady:
|
++g_shared->active_slots_seen;
|
break;
|
case SlotReadResult::Inactive:
|
++g_shared->reject_inactive_slot;
|
return;
|
case SlotReadResult::UnstablePublication:
|
++g_shared->reject_unstable_publication;
|
return;
|
case SlotReadResult::InvalidProcNumber:
|
++g_shared->reject_invalid_proc_number;
|
return;
|
case SlotReadResult::MissingProc:
|
++g_shared->reject_missing_pgproc;
|
clear_stale_activity_locked(slot);
|
return;
|
case SlotReadResult::PidMismatch:
|
++g_shared->reject_pid_mismatch;
|
clear_stale_activity_locked(slot);
|
return;
|
case SlotReadResult::SelfPid:
|
++g_shared->reject_self_pid;
|
return;
|
case SlotReadResult::InvalidDatabase:
|
++g_shared->reject_invalid_database;
|
return;
|
}
|
|
uint64 epoch_milliseconds = static_cast<uint64>(sample_time / INT64CONST(1000));
|
if (epoch_milliseconds < g_shared->sample_sequence_epoch_milliseconds)
|
epoch_milliseconds = g_shared->sample_sequence_epoch_milliseconds;
|
if (epoch_milliseconds != g_shared->sample_sequence_epoch_milliseconds ||
|
g_shared->next_local_sample_sequence >= kSampleSequenceCounterLimit)
|
{
|
g_shared->sample_sequence_epoch_milliseconds = std::max(
|
epoch_milliseconds,
|
g_shared->sample_sequence_epoch_milliseconds + 1);
|
g_shared->next_local_sample_sequence = 0;
|
}
|
if (g_shared->sample_sequence_epoch_milliseconds >
|
static_cast<uint64>(PG_INT64_MAX) / kSampleSequenceCounterLimit)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("переполнен идентификатор RUDB ASH sample")));
|
}
|
const uint64 sequence_base =
|
g_shared->sample_sequence_epoch_milliseconds * kSampleSequenceCounterLimit;
|
const uint64 local_counter = g_shared->next_local_sample_sequence++;
|
if (local_counter > static_cast<uint64>(PG_INT64_MAX) - sequence_base)
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("недопустимый идентификатор RUDB ASH sample")));
|
const uint64 next_sample_sequence = sequence_base + local_counter;
|
if (next_sample_sequence == 0 || next_sample_sequence > static_cast<uint64>(PG_INT64_MAX))
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("недопустимый идентификатор RUDB ASH sample")));
|
|
if (g_shared->next_ring_position == std::numeric_limits<uint64>::max())
|
g_shared->next_ring_position = 0;
|
const uint64 ring_position = g_shared->next_ring_position++;
|
AshSharedSample& sample = samples[ring_position % g_shared->sample_capacity];
|
const bool overwritten_retained = sample_is_retained(sample, sample_time);
|
release_sample_sql_reference_locked(sample);
|
if (overwritten_retained)
|
++g_shared->dropped_samples;
|
|
std::memset(&sample, 0, sizeof(sample));
|
sample = candidate;
|
sample.sample_sequence = next_sample_sequence;
|
if (g_shared->next_sample_generation == std::numeric_limits<uint64>::max())
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("переполнен счётчик поколений RUDB ASH sample")));
|
sample.sample_generation = g_shared->next_sample_generation++;
|
g_shared->last_sample_time = static_cast<uint64>(sample_time);
|
++g_shared->samples_written;
|
}
|
|
void
|
sample_active_slots(void)
|
{
|
// Фоновый процесс фиксирует устойчивые слоты активности и сохраняет
|
// записи ASH под одной блокировкой со ссылками кольцевого буфера и кэша.
|
ensure_shared_state_attached();
|
|
const TimestampTz now = GetCurrentTimestamp();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
g_shared->sample_interval_ms = static_cast<uint32>(g_sample_interval_ms);
|
g_shared->retention_seconds = static_cast<uint32>(g_retention_seconds);
|
++g_shared->worker_cycles;
|
clear_expired_samples_locked(now);
|
|
for (uint32 idx = 0; idx < g_shared->activity_slot_count; ++idx)
|
capture_sample_locked(activity_slots()[idx], now);
|
|
LWLockRelease(g_ash_lock);
|
}
|
|
void
|
executor_start_hook(QueryDesc* queryDesc, int eflags)
|
{
|
bool frame_pushed = false;
|
if (g_capture_enabled && queryDesc != nullptr && queryDesc->sourceText != nullptr)
|
{
|
ActivityFrame frame = build_activity_frame(queryDesc->sourceText,
|
std::string(command_type_for_operation(queryDesc->operation)),
|
"ACTIVE");
|
if (!frame.normalized_sql.empty())
|
{
|
frame.owner = queryDesc;
|
activity_stack().push_back(std::move(frame));
|
publish_frame(activity_stack().back());
|
frame_pushed = true;
|
}
|
}
|
|
PG_TRY();
|
{
|
if (g_prev_executor_start_hook != nullptr)
|
g_prev_executor_start_hook(queryDesc, eflags);
|
else
|
standard_ExecutorStart(queryDesc, eflags);
|
}
|
PG_CATCH();
|
{
|
if (frame_pushed && !activity_stack().empty() &&
|
activity_stack().back().owner == queryDesc)
|
{
|
activity_stack().pop_back();
|
if (activity_stack().empty())
|
clear_activity();
|
else
|
restore_outer_activity();
|
}
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
}
|
|
void
|
executor_end_hook(QueryDesc* queryDesc)
|
{
|
// Очистка выполняется и после ERROR, чтобы слот активности не пережил
|
// владельца SQL-оператора.
|
PG_TRY();
|
{
|
if (g_prev_executor_end_hook != nullptr)
|
g_prev_executor_end_hook(queryDesc);
|
else
|
standard_ExecutorEnd(queryDesc);
|
}
|
PG_CATCH();
|
{
|
finish_current_activity_frame(queryDesc);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
|
finish_current_activity_frame(queryDesc);
|
}
|
|
void
|
process_utility_hook(PlannedStmt* pstmt,
|
const char* queryString,
|
bool readOnlyTree,
|
ProcessUtilityContext context,
|
ParamListInfo params,
|
QueryEnvironment* queryEnv,
|
DestReceiver* dest,
|
QueryCompletion* qc)
|
{
|
// Служебный SQL-оператор использует тот же срок жизни слота, что и обычный.
|
bool frame_pushed = false;
|
if (g_capture_enabled && queryString != nullptr && queryString[0] != '\0')
|
{
|
ActivityFrame frame = build_activity_frame(queryString, "UTILITY", "ACTIVE");
|
if (!frame.normalized_sql.empty())
|
{
|
frame.owner = queryString;
|
activity_stack().push_back(std::move(frame));
|
publish_frame(activity_stack().back());
|
frame_pushed = true;
|
}
|
}
|
|
PG_TRY();
|
{
|
if (g_prev_process_utility_hook != nullptr)
|
{
|
g_prev_process_utility_hook(pstmt, queryString, readOnlyTree, context,
|
params, queryEnv, dest, qc);
|
}
|
else
|
{
|
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context,
|
params, queryEnv, dest, qc);
|
}
|
}
|
PG_CATCH();
|
{
|
if (frame_pushed)
|
finish_current_activity_frame(queryString);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
|
if (frame_pushed)
|
finish_current_activity_frame(queryString);
|
}
|
|
void
|
install_backend_hooks(void)
|
{
|
if (g_hooks_installed)
|
return;
|
|
g_prev_executor_start_hook = ExecutorStart_hook;
|
ExecutorStart_hook = executor_start_hook;
|
g_prev_executor_end_hook = ExecutorEnd_hook;
|
ExecutorEnd_hook = executor_end_hook;
|
g_prev_process_utility_hook = ProcessUtility_hook;
|
ProcessUtility_hook = process_utility_hook;
|
g_hooks_installed = true;
|
}
|
|
void
|
xact_callback(XactEvent event, void*)
|
{
|
// Вставка в постоянное историческое хранилище ещё не создаёт снимок AWR:
|
// `snap_id` публикуется только после фиксации внешней транзакции.
|
if (event == XACT_EVENT_ABORT || event == XACT_EVENT_PREPARE)
|
{
|
pending_archive_marks().clear();
|
pending_snapshot_clear_marks().clear();
|
activity_stack().clear();
|
clear_activity();
|
return;
|
}
|
|
if (event != XACT_EVENT_COMMIT)
|
return;
|
|
ensure_shared_state_attached();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
for (const PendingArchiveMark& mark : pending_archive_marks())
|
{
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
AshSharedSample& sample = sample_ring()[idx];
|
if (sample.sample_sequence != mark.sample_sequence ||
|
sample.sample_generation != mark.sample_generation ||
|
sample.activity_generation != mark.activity_generation)
|
continue;
|
|
sample.is_awr_sample = true;
|
sample.snap_id = mark.snap_id;
|
break;
|
}
|
}
|
for (const PendingSnapshotClearMark& mark : pending_snapshot_clear_marks())
|
{
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
AshSharedSample& sample = sample_ring()[idx];
|
if (sample.sample_sequence == 0 ||
|
sample.dbid != mark.dbid ||
|
sample.snap_id < mark.low_snap_id ||
|
sample.snap_id > mark.high_snap_id)
|
{
|
continue;
|
}
|
|
sample.is_awr_sample = false;
|
sample.snap_id = 0;
|
}
|
}
|
LWLockRelease(g_ash_lock);
|
pending_archive_marks().clear();
|
pending_snapshot_clear_marks().clear();
|
}
|
|
void
|
subxact_callback(SubXactEvent event,
|
SubTransactionId my_subid,
|
SubTransactionId parent_subid,
|
void*)
|
{
|
if (event == SUBXACT_EVENT_ABORT_SUB)
|
{
|
auto& marks = pending_archive_marks();
|
marks.erase(std::remove_if(marks.begin(),
|
marks.end(),
|
[my_subid](const PendingArchiveMark& mark)
|
{
|
return mark.subxid == my_subid;
|
}),
|
marks.end());
|
auto& clear_marks = pending_snapshot_clear_marks();
|
clear_marks.erase(std::remove_if(clear_marks.begin(),
|
clear_marks.end(),
|
[my_subid](const PendingSnapshotClearMark& mark)
|
{
|
return mark.subxid == my_subid;
|
}),
|
clear_marks.end());
|
|
auto& frames = activity_stack();
|
frames.erase(std::remove_if(frames.begin(),
|
frames.end(),
|
[my_subid](const ActivityFrame& frame)
|
{
|
return frame.subxid == my_subid;
|
}),
|
frames.end());
|
}
|
else if (event == SUBXACT_EVENT_COMMIT_SUB)
|
{
|
for (PendingArchiveMark& mark : pending_archive_marks())
|
{
|
if (mark.subxid == my_subid)
|
mark.subxid = parent_subid;
|
}
|
for (PendingSnapshotClearMark& mark : pending_snapshot_clear_marks())
|
{
|
if (mark.subxid == my_subid)
|
mark.subxid = parent_subid;
|
}
|
|
for (ActivityFrame& frame : activity_stack())
|
{
|
if (frame.subxid == my_subid)
|
frame.subxid = parent_subid;
|
}
|
}
|
else
|
{
|
return;
|
}
|
|
if (activity_stack().empty())
|
clear_activity();
|
else
|
restore_outer_activity();
|
}
|
|
void
|
install_xact_callbacks(void)
|
{
|
if (g_xact_callbacks_installed)
|
return;
|
|
RegisterXactCallback(xact_callback, nullptr);
|
g_xact_callbacks_installed = true;
|
if (!g_subxact_callbacks_installed)
|
{
|
RegisterSubXactCallback(subxact_callback, nullptr);
|
g_subxact_callbacks_installed = true;
|
}
|
}
|
|
std::optional<TimestampTz>
|
parse_timestamp_tz(const std::optional<std::string>& value)
|
{
|
if (!value.has_value())
|
return std::nullopt;
|
|
const std::string trimmed = trim_ascii_copy(*value);
|
if (trimmed.empty())
|
return std::nullopt;
|
|
Datum parsed = DirectFunctionCall3(timestamptz_in,
|
CStringGetDatum(trimmed.c_str()),
|
ObjectIdGetDatum(InvalidOid),
|
Int32GetDatum(-1));
|
return DatumGetTimestampTz(parsed);
|
}
|
|
TimestampTz
|
compute_begin_time(const std::optional<TimestampTz>& parsed_begin_time,
|
const TimestampTz end_time,
|
int64 time_since_sec)
|
{
|
if (parsed_begin_time.has_value() && *parsed_begin_time < end_time)
|
return *parsed_begin_time;
|
|
return end_time - static_cast<TimestampTz>(time_since_sec) * USECS_PER_SEC;
|
}
|
|
bool
|
matches_instance_filter(const rudb::ash::SampleRow& entry, const rudb::ash::HistoryFilter& filter)
|
{
|
if (filter.instance_list_is_empty)
|
return false;
|
|
if (!filter.instance_filter_enabled)
|
return true;
|
|
if (filter.global_scope)
|
{
|
return std::find(filter.instance_numbers.begin(),
|
filter.instance_numbers.end(),
|
entry.instance_number) != filter.instance_numbers.end();
|
}
|
|
return filter.instance_number.has_value() && *filter.instance_number == entry.instance_number;
|
}
|
|
bool
|
matches_sample(const rudb::ash::SampleRow& entry, const rudb::ash::HistoryFilter& filter)
|
{
|
if (filter.begin_time.has_value())
|
{
|
if (filter.begin_time_exclusive ? entry.sample_time <= *filter.begin_time
|
: entry.sample_time < *filter.begin_time)
|
return false;
|
}
|
|
if (filter.end_time.has_value())
|
{
|
if (filter.end_time_exclusive ? entry.sample_time >= *filter.end_time
|
: entry.sample_time > *filter.end_time)
|
return false;
|
}
|
|
if (filter.dbid.has_value() && entry.dbid != *filter.dbid)
|
return false;
|
|
if (!matches_instance_filter(entry, filter))
|
return false;
|
|
if (filter.sql_id.has_value() && entry.sql_id != *filter.sql_id)
|
return false;
|
|
if (filter.wait_class.has_value() &&
|
pg_strcasecmp(entry.wait_class.c_str(), filter.wait_class->c_str()) != 0)
|
{
|
return false;
|
}
|
if (filter.session_id.has_value() && entry.session_id != *filter.session_id)
|
return false;
|
if (filter.module_name.has_value() && entry.module_name != *filter.module_name)
|
return false;
|
|
if (filter.begin_snap_id.has_value() && entry.snap_id <= *filter.begin_snap_id)
|
return false;
|
|
if (filter.end_snap_id.has_value() && entry.snap_id > *filter.end_snap_id)
|
return false;
|
|
if (filter.awr_only && !entry.is_awr_sample)
|
return false;
|
|
return true;
|
}
|
|
std::string
|
format_timestamp(const std::optional<TimestampTz>& value)
|
{
|
if (!value.has_value())
|
return "NULL";
|
|
char* rendered = DatumGetCString(
|
DirectFunctionCall1(timestamptz_out, TimestampTzGetDatum(*value)));
|
std::string result(rendered);
|
pfree(rendered);
|
return result;
|
}
|
|
std::string
|
format_optional_int64(const std::optional<int64>& value)
|
{
|
return value.has_value() ? std::to_string(*value) : "NULL";
|
}
|
|
std::string
|
format_optional_text(const std::optional<std::string>& value)
|
{
|
return value.has_value() ? *value : "NULL";
|
}
|
|
std::string
|
normalize_options_text(const std::optional<int64>& options)
|
{
|
return options.has_value() ? std::to_string(*options) : "NULL";
|
}
|
|
std::string
|
normalize_slot_width_text(const std::optional<int64>& slot_width)
|
{
|
if (!slot_width.has_value() || *slot_width == 0)
|
return "auto";
|
|
return std::to_string(*slot_width);
|
}
|
|
std::string
|
slot_width_effect(const std::optional<int64>& slot_width)
|
{
|
return (!slot_width.has_value() || *slot_width == 0) ? "auto" : "minimal-report-only";
|
}
|
|
std::string
|
normalize_data_src_text(const std::optional<int64>& data_src)
|
{
|
if (!data_src.has_value())
|
return "auto";
|
|
switch (*data_src)
|
{
|
case 0:
|
return "all";
|
case 1:
|
return "memory";
|
case 2:
|
return "historical";
|
case 3:
|
return "global";
|
default:
|
return std::to_string(*data_src);
|
}
|
}
|
|
ReportStats
|
collect_report_stats(const std::vector<rudb::ash::SampleRow>& samples,
|
const rudb::ash::HistoryFilter& filter)
|
{
|
ReportStats stats;
|
std::map<std::string, std::size_t> sql_id_counts;
|
std::map<std::string, std::size_t> wait_class_counts;
|
std::set<std::string> distinct_sql_ids;
|
|
stats.sample_count_total = samples.size();
|
stats.sql_text_entry_count = rudb::ash::sql_text_count();
|
|
for (const rudb::ash::SampleRow& entry : samples)
|
{
|
if (!matches_sample(entry, filter))
|
continue;
|
|
++stats.sample_count_matched;
|
|
if (!entry.sql_id.empty())
|
{
|
distinct_sql_ids.insert(entry.sql_id);
|
++sql_id_counts[entry.sql_id];
|
}
|
|
if (!entry.wait_class.empty())
|
++wait_class_counts[entry.wait_class];
|
}
|
|
stats.distinct_sql_id_count_matched = distinct_sql_ids.size();
|
|
for (const auto& entry : sql_id_counts)
|
{
|
if (!stats.top_sql_id.has_value() || entry.second > sql_id_counts[*stats.top_sql_id] ||
|
(entry.second == sql_id_counts[*stats.top_sql_id] && entry.first < *stats.top_sql_id))
|
{
|
stats.top_sql_id = entry.first;
|
}
|
}
|
|
for (const auto& entry : wait_class_counts)
|
{
|
if (!stats.top_wait_class.has_value() || entry.second > wait_class_counts[*stats.top_wait_class] ||
|
(entry.second == wait_class_counts[*stats.top_wait_class] && entry.first < *stats.top_wait_class))
|
{
|
stats.top_wait_class = entry.first;
|
}
|
}
|
|
return stats;
|
}
|
|
void
|
append_filter_summary_rows(std::vector<std::string>& rows,
|
const rudb::ash::LayerReportRequest& request,
|
const ReportStats& stats)
|
{
|
rows.push_back("dbid=" + std::to_string(request.dbid));
|
rows.push_back(request.global_scope
|
? "instance_list=" + request.normalized_instance_list
|
: "inst_num=" + std::to_string(request.inst_num.value_or(1)));
|
rows.push_back("begin_time=" + format_timestamp(request.begin_time));
|
rows.push_back("end_time=" + format_timestamp(request.end_time));
|
rows.push_back("options=" + normalize_options_text(request.options));
|
rows.push_back("options_effect=minimal-report-format");
|
rows.push_back("slot_width=" + normalize_slot_width_text(request.slot_width));
|
rows.push_back("slot_width_effect=" + slot_width_effect(request.slot_width));
|
rows.push_back("data_src=" + normalize_data_src_text(request.data_src));
|
rows.push_back("filter_sid=" + format_optional_int64(request.sid));
|
rows.push_back("filter_sql_id=" + format_optional_text(request.sql_id));
|
rows.push_back("filter_wait_class=" + format_optional_text(request.wait_class));
|
rows.push_back("filter_service_hash=" + format_optional_int64(request.service_hash));
|
rows.push_back("filter_module=" + format_optional_text(request.module));
|
rows.push_back("filter_action=" + format_optional_text(request.action));
|
rows.push_back("filter_client_id=" + format_optional_text(request.client_id));
|
rows.push_back("filter_plsql_entry=" + format_optional_text(request.plsql_entry));
|
rows.push_back("filter_container=" + format_optional_text(request.container));
|
rows.push_back(std::string("sql_id_filter_applied=") +
|
(request.sql_id.has_value() ? "true" : "false"));
|
rows.push_back(std::string("wait_class_filter_applied=") +
|
(request.wait_class.has_value() ? "true" : "false"));
|
rows.push_back("service_hash_filter_applied=false");
|
rows.push_back(std::string("module_filter_applied=") +
|
(request.module.has_value() ? "true" : "false"));
|
rows.push_back("action_filter_applied=false");
|
rows.push_back("client_id_filter_applied=false");
|
rows.push_back("plsql_entry_filter_applied=false");
|
rows.push_back("container_filter_applied=false");
|
rows.push_back("sample_count_total=" + std::to_string(stats.sample_count_total));
|
rows.push_back("sample_count_matched=" + std::to_string(stats.sample_count_matched));
|
rows.push_back("sql_text_entry_count=" + std::to_string(stats.sql_text_entry_count));
|
rows.push_back("distinct_sql_id_count_matched=" +
|
std::to_string(stats.distinct_sql_id_count_matched));
|
rows.push_back("top_sql_id=" + stats.top_sql_id.value_or("NULL"));
|
rows.push_back("top_wait_class=" + stats.top_wait_class.value_or("NULL"));
|
}
|
|
std::string
|
join_text_rows(const std::vector<std::string>& rows)
|
{
|
std::string result;
|
|
for (std::size_t idx = 0; idx < rows.size(); ++idx)
|
{
|
if (idx != 0)
|
result += "\n";
|
|
result += rows[idx];
|
}
|
|
return result;
|
}
|
|
std::vector<std::string>
|
build_report_rows(const char* title, const rudb::ash::LayerReportRequest& request)
|
{
|
rudb::ash::HistoryFilter filter;
|
filter.dbid = request.dbid;
|
filter.instance_number = request.inst_num;
|
filter.instance_numbers = request.instance_numbers;
|
filter.global_scope = request.global_scope;
|
filter.begin_time = request.begin_time;
|
filter.end_time = request.end_time;
|
filter.sql_id = request.sql_id;
|
filter.wait_class = request.wait_class;
|
filter.session_id = request.sid;
|
filter.module_name = request.module;
|
|
std::vector<rudb::ash::SampleRow> samples;
|
const int64 data_src = request.data_src.value_or(0);
|
if (data_src == 0 || data_src == 1 || data_src == 3)
|
samples = rudb::ash::collect_memory_samples(filter);
|
|
if (data_src == 0 || data_src == 2 || data_src == 3)
|
{
|
std::vector<rudb::ash::SampleRow> history = rudb::ash::collect_history_samples(filter);
|
if (history.size() > samples.max_size() - samples.size())
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("слишком много ASH samples для формирования отчёта")));
|
samples.insert(samples.end(),
|
std::make_move_iterator(history.begin()),
|
std::make_move_iterator(history.end()));
|
}
|
std::sort(samples.begin(), samples.end(),
|
[](const rudb::ash::SampleRow& left, const rudb::ash::SampleRow& right)
|
{
|
return left.sample_sequence < right.sample_sequence;
|
});
|
samples.erase(std::unique(samples.begin(), samples.end(),
|
[](const rudb::ash::SampleRow& left,
|
const rudb::ash::SampleRow& right)
|
{
|
return left.sample_sequence == right.sample_sequence;
|
}),
|
samples.end());
|
|
const ReportStats stats = collect_report_stats(samples, filter);
|
std::vector<std::string> rows = {title};
|
append_filter_summary_rows(rows, request, stats);
|
return rows;
|
}
|
|
std::string
|
build_timepicker_buckets_xml(const TimestampTz begin_time,
|
const TimestampTz end_time,
|
int bucket_count,
|
int64 bucket_interval_sec)
|
{
|
struct BucketEntry
|
{
|
int64 cpu_count = 0;
|
int64 io_count = 0;
|
int64 other_count = 0;
|
};
|
|
rudb::ash::HistoryFilter filter;
|
filter.begin_time = begin_time;
|
filter.end_time = end_time;
|
std::vector<rudb::ash::SampleRow> samples = rudb::ash::collect_memory_samples(filter);
|
std::vector<BucketEntry> buckets(static_cast<std::size_t>(bucket_count));
|
const TimestampTz bucket_interval = static_cast<TimestampTz>(bucket_interval_sec) * USECS_PER_SEC;
|
|
for (const rudb::ash::SampleRow& entry : samples)
|
{
|
if (entry.sample_time < begin_time || entry.sample_time > end_time)
|
continue;
|
|
int64 bucket_index = bucket_interval > 0 ? (entry.sample_time - begin_time) / bucket_interval : 0;
|
|
if (bucket_index < 0)
|
bucket_index = 0;
|
else if (bucket_index >= bucket_count)
|
bucket_index = bucket_count - 1;
|
|
BucketEntry& bucket = buckets[static_cast<std::size_t>(bucket_index)];
|
|
if (pg_strcasecmp(entry.wait_class.c_str(), "CPU") == 0)
|
++bucket.cpu_count;
|
else if (pg_strcasecmp(entry.wait_class.c_str(), "USER I/O") == 0 ||
|
pg_strcasecmp(entry.wait_class.c_str(), "IO") == 0)
|
++bucket.io_count;
|
else
|
++bucket.other_count;
|
}
|
|
std::string xml;
|
|
for (int bucket_index = 0; bucket_index < bucket_count; ++bucket_index)
|
{
|
const BucketEntry& bucket = buckets[static_cast<std::size_t>(bucket_index)];
|
|
if (bucket.cpu_count == 0 && bucket.io_count == 0 && bucket.other_count == 0)
|
continue;
|
|
xml += "<b n=\"";
|
xml += std::to_string(bucket_index);
|
xml += "\" c=\"";
|
xml += std::to_string(static_cast<long long>(bucket.cpu_count));
|
xml += "\" i=\"";
|
xml += std::to_string(static_cast<long long>(bucket.io_count));
|
xml += "\" o=\"";
|
xml += std::to_string(static_cast<long long>(bucket.other_count));
|
xml += "\"></b>";
|
}
|
|
return xml;
|
}
|
|
void
|
reserve_pending_archive_marks(std::size_t additional)
|
{
|
auto& marks = pending_archive_marks();
|
if (additional > marks.max_size() - marks.size())
|
throw std::length_error("pending archive marks capacity overflow");
|
|
marks.reserve(marks.size() + additional);
|
}
|
|
void
|
reserve_pending_snapshot_clear_marks(std::size_t additional)
|
{
|
auto& marks = pending_snapshot_clear_marks();
|
if (additional > marks.max_size() - marks.size())
|
throw std::length_error("pending snapshot clear marks capacity overflow");
|
|
marks.reserve(marks.size() + additional);
|
}
|
|
struct AshSpiScope
|
{
|
bool connected = false;
|
|
AshSpiScope()
|
{
|
if (SPI_connect() != SPI_OK_CONNECT)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось открыть SPI для работы с RUDB ASH history")));
|
connected = true;
|
}
|
|
~AshSpiScope()
|
{
|
close_noexcept();
|
}
|
|
void close_noexcept() noexcept
|
{
|
if (!connected)
|
return;
|
|
connected = false;
|
(void) SPI_finish();
|
}
|
|
void finish()
|
{
|
if (!connected)
|
return;
|
|
connected = false;
|
if (SPI_finish() != SPI_OK_FINISH)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось завершить SPI для работы с RUDB ASH history")));
|
}
|
};
|
|
template <typename Callback>
|
auto
|
with_ash_spi(Callback&& callback) -> decltype(callback())
|
{
|
AshSpiScope spi;
|
|
try
|
{
|
auto result = callback();
|
spi.finish();
|
return result;
|
}
|
catch (...)
|
{
|
spi.close_noexcept();
|
throw;
|
}
|
}
|
|
std::string
|
datum_text_to_string(Datum datum)
|
{
|
char* value = TextDatumGetCString(datum);
|
std::string result(value);
|
pfree(value);
|
return result;
|
}
|
|
rudb::ash::SampleRow
|
sample_from_shared(const AshSharedSample& sample)
|
{
|
rudb::ash::SampleRow row;
|
row.sample_sequence = sample.sample_sequence;
|
row.sample_time = sample.sample_time;
|
row.dbid = sample.dbid;
|
row.instance_number = sample.instance_number;
|
row.session_id = sample.session_id;
|
row.session_serial = sample.session_serial;
|
row.session_generation = sample.session_generation;
|
row.started_at = sample.started_at;
|
row.command_type = cstring_field_to_string(sample.command_type);
|
const char* backend_type = GetBackendTypeDesc(static_cast<BackendType>(sample.backend_type));
|
row.backend_type = backend_type != nullptr ? backend_type : "";
|
row.user_id = sample.user_id;
|
row.sql_id = cstring_field_to_string(sample.sql_id);
|
if (sample.sql_text_complete &&
|
sample.sql_cache_generation != 0 &&
|
sample.sql_cache_slot < g_shared->sql_cache_capacity)
|
{
|
const AshSharedSqlTextEntry& entry = sql_cache()[sample.sql_cache_slot];
|
if (sql_cache_reference_matches(sample, entry))
|
{
|
std::string sql_text;
|
if (read_sql_text_from_entry(entry, &sql_text))
|
row.sql_text = std::move(sql_text);
|
}
|
}
|
row.module_name = cstring_field_to_string(sample.module_name);
|
row.application_name = cstring_field_to_string(sample.application_name);
|
row.state = cstring_field_to_string(sample.state);
|
row.wait_class = wait_class_for_info(sample.wait_event_info);
|
row.event_name = wait_event_for_info(sample.wait_event_info);
|
row.is_awr_sample = sample.is_awr_sample;
|
row.snap_id = sample.snap_id;
|
return row;
|
}
|
|
MemoryArchiveCandidate
|
archive_candidate_from_shared(const AshSharedSample& sample)
|
{
|
MemoryArchiveCandidate candidate;
|
candidate.row = sample_from_shared(sample);
|
candidate.sample_generation = sample.sample_generation;
|
candidate.activity_generation = sample.activity_generation;
|
candidate.sql_cache_slot = sample.sql_cache_slot;
|
candidate.sql_cache_generation = sample.sql_cache_generation;
|
return candidate;
|
}
|
|
std::vector<SharedSampleSnapshot>
|
snapshot_memory_samples(void)
|
{
|
/*
|
* Под блокировкой копируются только простые поля и временно
|
* удерживаются ссылки на текст SQL. Строки создаются уже после
|
* освобождения блокировки.
|
*/
|
std::vector<SharedSampleSnapshot> snapshots(kSampleCapacity);
|
std::size_t snapshot_count = 0;
|
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
const TimestampTz retention_cutoff = GetCurrentTimestamp() -
|
static_cast<TimestampTz>(g_shared->retention_seconds) * USECS_PER_SEC;
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
const AshSharedSample& sample = sample_ring()[idx];
|
if (sample.sample_sequence == 0 || sample.sample_time < retention_cutoff)
|
continue;
|
|
SharedSampleSnapshot snapshot;
|
snapshot.sample = sample;
|
if (snapshot.sample.sql_text_complete &&
|
snapshot.sample.sql_cache_generation != 0 &&
|
snapshot.sample.sql_cache_slot < g_shared->sql_cache_capacity)
|
{
|
snapshot.sql_reference_retained = retain_sql_text_reference_locked(
|
snapshot.sample.sql_cache_slot, snapshot.sample.sql_cache_generation);
|
if (!snapshot.sql_reference_retained)
|
snapshot.sample.sql_text_complete = false;
|
}
|
snapshots[snapshot_count++] = snapshot;
|
}
|
LWLockRelease(g_ash_lock);
|
snapshots.resize(snapshot_count);
|
return snapshots;
|
}
|
|
void
|
release_snapshot_sql_references(const std::vector<SharedSampleSnapshot>& snapshots)
|
{
|
// Временные ссылки отчёта и архива освобождаются после построения строк
|
// за пределами блокировки.
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
for (const SharedSampleSnapshot& snapshot : snapshots)
|
{
|
if (snapshot.sql_reference_retained)
|
{
|
release_sql_text_reference_locked(snapshot.sample.sql_cache_slot,
|
snapshot.sample.sql_cache_generation);
|
}
|
}
|
LWLockRelease(g_ash_lock);
|
}
|
} // namespace
|
|
extern "C" void
|
rudb_ash_postmaster_init(void)
|
{
|
if (g_postmaster_initialized)
|
return;
|
|
define_gucs();
|
g_prev_shmem_request_hook = shmem_request_hook;
|
shmem_request_hook = request_shared_resources;
|
g_prev_shmem_startup_hook = shmem_startup_hook;
|
shmem_startup_hook = startup_shared_state;
|
register_worker();
|
g_postmaster_initialized = true;
|
}
|
|
extern "C" void
|
rudb_ash_backend_init(void)
|
{
|
if (g_backend_initialized)
|
return;
|
|
define_gucs();
|
ensure_shared_state_attached();
|
install_backend_hooks();
|
install_xact_callbacks();
|
before_shmem_exit(backend_shutdown, 0);
|
g_backend_initialized = true;
|
}
|
|
extern "C" void
|
rudb_ash_archive_backend_init(void)
|
{
|
if (g_archive_backend_initialized)
|
return;
|
|
define_gucs();
|
ensure_shared_state_attached();
|
install_xact_callbacks();
|
before_shmem_exit(backend_shutdown, 0);
|
g_archive_backend_initialized = true;
|
}
|
|
extern "C" PGDLLEXPORT void
|
rudb_ash_worker_main(Datum)
|
{
|
pqsignal(SIGTERM, ash_worker_die);
|
pqsignal(SIGHUP, SignalHandlerForConfigReload);
|
pqsignal(SIGUSR1, procsignal_sigusr1_handler);
|
pqsignal(SIGPIPE, PG_SIG_IGN);
|
BackgroundWorkerUnblockSignals();
|
|
ensure_shared_state_attached();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
g_shared->worker_pid = MyProcPid;
|
LWLockRelease(g_ash_lock);
|
|
instr_time next_deadline;
|
instr_time interval;
|
INSTR_TIME_SET_ZERO(interval);
|
INSTR_TIME_ADD_NANOSEC(interval,
|
static_cast<int64>(g_sample_interval_ms) * NS_PER_MS);
|
INSTR_TIME_SET_CURRENT(next_deadline);
|
INSTR_TIME_ADD(next_deadline, interval);
|
while (!g_worker_shutdown_requested)
|
{
|
instr_time current_time;
|
INSTR_TIME_SET_CURRENT(current_time);
|
instr_time remaining = next_deadline;
|
INSTR_TIME_SUBTRACT(remaining, current_time);
|
long timeout_ms = INSTR_TIME_GET_MILLISEC(remaining);
|
if (timeout_ms < 0)
|
timeout_ms = 0;
|
int rc = WaitLatch(MyLatch,
|
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
|
timeout_ms,
|
0);
|
ResetLatch(MyLatch);
|
|
if ((rc & WL_POSTMASTER_DEATH) != 0)
|
proc_exit(1);
|
|
if (ConfigReloadPending)
|
{
|
ConfigReloadPending = false;
|
ProcessConfigFile(PGC_SIGHUP);
|
}
|
|
INSTR_TIME_SET_CURRENT(current_time);
|
if (!INSTR_TIME_GT(next_deadline, current_time))
|
{
|
sample_active_slots();
|
INSTR_TIME_SET_ZERO(interval);
|
INSTR_TIME_ADD_NANOSEC(interval,
|
static_cast<int64>(g_sample_interval_ms) * NS_PER_MS);
|
INSTR_TIME_ADD(next_deadline, interval);
|
if (!INSTR_TIME_GT(next_deadline, current_time))
|
{
|
next_deadline = current_time;
|
INSTR_TIME_ADD(next_deadline, interval);
|
}
|
}
|
}
|
|
proc_exit(0);
|
}
|
|
void
|
rudb::ash::initialize(void)
|
{
|
rudb_ash_backend_init();
|
}
|
|
bool
|
rudb::ash::is_initialized(void)
|
{
|
return g_backend_initialized && g_shared != nullptr && g_ash_lock != nullptr;
|
}
|
|
std::string
|
rudb::ash::compute_sql_id(const std::string& sql_text)
|
{
|
char hexsum[MD5_DIGEST_LENGTH * 2 + 1];
|
const char* errstr = nullptr;
|
|
if (!pg_md5_hash(sql_text.data(), sql_text.size(), hexsum, &errstr))
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось вычислить RUDB ASH SQL_ID: %s",
|
errstr != nullptr ? errstr : "unknown error")));
|
}
|
|
return std::string(hexsum);
|
}
|
|
std::optional<std::string>
|
rudb::ash::lookup_sql_text(const std::string& sql_id, bool local_path, bool historical_path)
|
{
|
const std::optional<std::string> plain = find_sql_text(
|
sql_id, historical_path, local_dbid_impl(MyDatabaseId), !historical_path);
|
|
if (!plain.has_value())
|
return std::nullopt;
|
|
if (!local_path && !historical_path)
|
return std::nullopt;
|
|
return "<a><c>SQL</c><s><![CDATA[" + *plain + "]]></s></a>";
|
}
|
|
std::optional<std::string>
|
rudb::ash::find_sql_text(const std::string& sql_id,
|
bool include_historical,
|
const std::optional<int64_t>& dbid)
|
{
|
return find_sql_text(sql_id, include_historical, dbid, true);
|
}
|
|
std::optional<std::string>
|
rudb::ash::find_sql_text(const std::string& sql_id,
|
bool include_historical,
|
const std::optional<int64_t>& dbid,
|
bool include_memory)
|
{
|
ensure_shared_state_attached();
|
std::optional<std::string> memory_result;
|
|
if (include_memory)
|
{
|
uint32 retained_slot = kSqlCacheCapacity;
|
uint64 retained_generation = 0;
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
|
{
|
AshSharedSqlTextEntry& entry = sql_cache()[idx];
|
if (entry.generation != 0 &&
|
std::strcmp(entry.sql_id, sql_id.c_str()) == 0 &&
|
(!dbid.has_value() || entry.dbid == *dbid))
|
{
|
if (entry.complete &&
|
retain_sql_text_reference_locked(idx, entry.generation))
|
{
|
retained_slot = idx;
|
retained_generation = entry.generation;
|
}
|
break;
|
}
|
}
|
LWLockRelease(g_ash_lock);
|
if (retained_generation != 0)
|
{
|
try
|
{
|
const AshSharedSqlTextEntry& entry = sql_cache()[retained_slot];
|
std::string rendered;
|
if (entry.generation == retained_generation &&
|
read_sql_text_from_entry(entry, &rendered))
|
{
|
memory_result = std::move(rendered);
|
}
|
}
|
catch (...)
|
{
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
release_sql_text_reference_locked(retained_slot, retained_generation);
|
LWLockRelease(g_ash_lock);
|
throw;
|
}
|
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
release_sql_text_reference_locked(retained_slot, retained_generation);
|
LWLockRelease(g_ash_lock);
|
}
|
if (memory_result.has_value())
|
return memory_result;
|
}
|
|
if (!include_historical)
|
return std::nullopt;
|
if (!dbid.has_value())
|
return std::nullopt;
|
|
Oid argtypes[2] = {TEXTOID, INT8OID};
|
Datum values[2] = {
|
CStringGetTextDatum(sql_id.c_str()),
|
Int64GetDatum(*dbid)};
|
const char nulls[2] = {' ', ' '};
|
|
return with_ash_spi([&]() {
|
const int rc = SPI_execute_with_args(
|
"SELECT sql_text FROM pg_catalog.rudb_ash_history_sqltext "
|
"WHERE dbid = $2 AND sql_id = $1 ORDER BY last_seen DESC LIMIT 1",
|
2, argtypes, values, nulls, true, 1);
|
|
if (rc != SPI_OK_SELECT)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось получить historical SQL text")));
|
|
std::optional<std::string> result = std::nullopt;
|
if (SPI_processed == 1)
|
{
|
bool isnull = false;
|
Datum datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
char* text_value = TextDatumGetCString(datum);
|
result = std::string(text_value);
|
pfree(text_value);
|
}
|
}
|
return result;
|
});
|
}
|
|
std::string
|
rudb::ash::capture_sql_text(const std::string& sql_text,
|
const std::optional<std::string>& command_type,
|
Oid user_id)
|
{
|
const std::string normalized_sql = trim_ascii_copy(sql_text);
|
if (normalized_sql.empty())
|
return "";
|
|
const std::string sql_id = compute_sql_id(normalized_sql);
|
const std::string normalized_command_type = normalize_command_type(command_type);
|
ensure_shared_state_attached();
|
LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
|
(void) update_sql_cache_locked(sql_id,
|
normalized_sql,
|
normalized_command_type,
|
user_id,
|
local_dbid_impl(MyDatabaseId),
|
GetCurrentTimestamp());
|
LWLockRelease(g_ash_lock);
|
return sql_id;
|
}
|
|
std::string
|
rudb::ash::build_timepicker_core_xml(const TimepickerRequest& request)
|
{
|
const TimestampTz now = GetCurrentTimestamp();
|
const std::optional<TimestampTz> parsed_end_time = parse_timestamp_tz(request.end_time_utc);
|
const TimestampTz end_time = parsed_end_time.value_or(now);
|
const TimestampTz begin_time =
|
compute_begin_time(parse_timestamp_tz(request.begin_time_utc), end_time, request.time_since_sec);
|
const ResolutionInfo resolution = normalize_resolution(request.resolution);
|
const int64 effective_time_since_sec = std::max<int64>(1, ceil_div(end_time - begin_time, USECS_PER_SEC));
|
const int64 bucket_interval = std::max<int64>(
|
1, ceil_div(effective_time_since_sec, static_cast<int64>(resolution.bucket_count)));
|
|
std::string xml = "<report xml_version=\"61\">";
|
xml += "<sys_info data_source=\"LOCAL\"></sys_info>";
|
xml += "<timing time_since_sec=\"" + std::to_string(request.time_since_sec) +
|
"\" bucket_interval=\"" + std::to_string(bucket_interval) + "\"></timing>";
|
xml += "<context begin_time_utc=\"" + xml_escape(request.begin_time_utc.value_or("")) +
|
"\" end_time_utc=\"" + xml_escape(request.end_time_utc.value_or("")) +
|
"\" instance_number=\"" + std::to_string(request.instance_number.value_or(1)) +
|
"\"></context>";
|
xml += "<report_parameters show_sql=\"";
|
xml += request.show_sql ? "Y" : "N";
|
xml += "\" verbose_xml=\"";
|
xml += request.verbose_xml ? "Y" : "N";
|
xml += "\" awr_info=\"";
|
xml += request.awr_info ? "Y" : "N";
|
xml += "\" ignore_cpu_history=\"";
|
xml += request.ignore_cpu_history ? "Y" : "N";
|
xml += "\" resolution=\"";
|
xml += resolution.name;
|
xml += "\" include_bg=\"";
|
xml += request.include_bg ? "Y" : "N";
|
xml += "\" memory_only=\"";
|
xml += request.memory_only ? "Y" : "N";
|
xml += "\"></report_parameters>";
|
xml += "<cpuinfo ignore_cpu_history=\"";
|
xml += request.ignore_cpu_history ? "Y" : "N";
|
xml += "\"></cpuinfo>";
|
xml += "<timepicker bucket_count=\"" + std::to_string(resolution.bucket_count) +
|
"\" bucket_interval=\"" + std::to_string(bucket_interval) +
|
"\" last_bucket_interval=\"0\">";
|
xml += build_timepicker_buckets_xml(begin_time, end_time, resolution.bucket_count, bucket_interval);
|
xml += "</timepicker></report>";
|
return xml;
|
}
|
|
std::vector<std::string>
|
rudb::ash::report_text(const LayerReportRequest& request)
|
{
|
return build_report_rows("ASH Report", request);
|
}
|
|
std::vector<std::string>
|
rudb::ash::report_html(const LayerReportRequest& request)
|
{
|
return {
|
"<html><head><title>ASH Report</title></head><body><pre>" +
|
xml_escape(join_text_rows(report_text(request))) +
|
"</pre></body></html>"
|
};
|
}
|
|
std::vector<std::string>
|
rudb::ash::global_report_text(const LayerReportRequest& request)
|
{
|
return build_report_rows("ASH RAC Report", request);
|
}
|
|
std::vector<std::string>
|
rudb::ash::global_report_html(const LayerReportRequest& request)
|
{
|
return {
|
"<html><head><title>ASH RAC Report</title></head><body><pre>" +
|
xml_escape(join_text_rows(global_report_text(request))) +
|
"</pre></body></html>"
|
};
|
}
|
|
std::vector<rudb::ash::SampleRow>
|
rudb::ash::collect_memory_samples(const HistoryFilter& filter)
|
{
|
ensure_shared_state_attached();
|
std::vector<SampleRow> rows;
|
const std::vector<SharedSampleSnapshot> snapshots = snapshot_memory_samples();
|
|
try
|
{
|
for (const SharedSampleSnapshot& snapshot : snapshots)
|
{
|
SampleRow row = sample_from_shared(snapshot.sample);
|
if (matches_sample(row, filter))
|
rows.push_back(std::move(row));
|
}
|
}
|
catch (...)
|
{
|
release_snapshot_sql_references(snapshots);
|
throw;
|
}
|
release_snapshot_sql_references(snapshots);
|
|
std::sort(rows.begin(), rows.end(),
|
[](const SampleRow& left, const SampleRow& right)
|
{
|
return left.sample_sequence < right.sample_sequence;
|
});
|
return rows;
|
}
|
|
std::vector<MemoryArchiveCandidate>
|
collect_memory_archive_candidates(const rudb::ash::HistoryFilter& filter)
|
{
|
ensure_shared_state_attached();
|
std::vector<MemoryArchiveCandidate> rows;
|
const std::vector<SharedSampleSnapshot> snapshots = snapshot_memory_samples();
|
|
try
|
{
|
for (const SharedSampleSnapshot& snapshot : snapshots)
|
{
|
MemoryArchiveCandidate candidate = archive_candidate_from_shared(snapshot.sample);
|
if (matches_sample(candidate.row, filter))
|
rows.push_back(std::move(candidate));
|
}
|
}
|
catch (...)
|
{
|
release_snapshot_sql_references(snapshots);
|
throw;
|
}
|
release_snapshot_sql_references(snapshots);
|
|
std::sort(rows.begin(), rows.end(),
|
[](const MemoryArchiveCandidate& left, const MemoryArchiveCandidate& right)
|
{
|
return left.row.sample_sequence < right.row.sample_sequence;
|
});
|
return rows;
|
}
|
|
std::vector<rudb::ash::SampleRow>
|
rudb::ash::collect_history_samples(const HistoryFilter& filter)
|
{
|
std::string sql =
|
"SELECT s.sample_sequence, s.sample_time, s.dbid::bigint, s.instance_number::bigint,"
|
" s.session_id::bigint, s.session_serial::bigint, s.session_generation::bigint,"
|
" s.started_at, COALESCE(s.command_type, ''), COALESCE(s.backend_type, ''),"
|
" s.user_id, COALESCE(s.sql_id, ''), COALESCE(t.sql_text, ''),"
|
" COALESCE(s.module_name, ''), COALESCE(s.application_name, ''), COALESCE(s.state, ''),"
|
" COALESCE(s.wait_class, ''), COALESCE(s.event_name, ''), s.snap_id, s.is_awr_sample"
|
" FROM pg_catalog.rudb_ash_history_samples s"
|
" LEFT JOIN pg_catalog.rudb_ash_history_sqltext t"
|
" ON t.dbid = s.dbid AND t.sql_id = s.sql_id"
|
" WHERE TRUE";
|
|
std::vector<Oid> argtypes;
|
std::vector<Datum> values;
|
std::vector<char> nulls;
|
int argno = 1;
|
auto append_arg = [&](Oid type, Datum value, char null_mark) -> std::string
|
{
|
argtypes.push_back(type);
|
values.push_back(value);
|
nulls.push_back(null_mark);
|
return "$" + std::to_string(argno++);
|
};
|
|
if (filter.dbid.has_value())
|
sql += " AND s.dbid = " + append_arg(INT8OID, Int64GetDatum(*filter.dbid), ' ');
|
if (filter.instance_number.has_value())
|
sql += " AND s.instance_number = " + append_arg(INT8OID, Int64GetDatum(*filter.instance_number), ' ');
|
if (filter.begin_time.has_value())
|
sql += " AND s.sample_time >= " + append_arg(TIMESTAMPTZOID, TimestampTzGetDatum(*filter.begin_time), ' ');
|
if (filter.end_time.has_value())
|
sql += std::string(" AND s.sample_time ") +
|
(filter.end_time_exclusive ? "< " : "<= ") +
|
append_arg(TIMESTAMPTZOID, TimestampTzGetDatum(*filter.end_time), ' ');
|
if (filter.begin_snap_id.has_value())
|
sql += " AND s.snap_id > " + append_arg(INT8OID, Int64GetDatum(*filter.begin_snap_id), ' ');
|
if (filter.end_snap_id.has_value())
|
sql += " AND s.snap_id <= " + append_arg(INT8OID, Int64GetDatum(*filter.end_snap_id), ' ');
|
if (filter.sql_id.has_value())
|
sql += " AND s.sql_id = " + append_arg(TEXTOID, CStringGetTextDatum(filter.sql_id->c_str()), ' ');
|
if (filter.wait_class.has_value())
|
sql += " AND lower(s.wait_class) = lower(" +
|
append_arg(TEXTOID, CStringGetTextDatum(filter.wait_class->c_str()), ' ') + ")";
|
if (filter.session_id.has_value())
|
sql += " AND s.session_id = " + append_arg(INT8OID, Int64GetDatum(*filter.session_id), ' ');
|
if (filter.module_name.has_value())
|
sql += " AND s.module_name = " +
|
append_arg(TEXTOID, CStringGetTextDatum(filter.module_name->c_str()), ' ');
|
if (filter.awr_only)
|
sql += " AND s.is_awr_sample";
|
|
sql += " ORDER BY s.sample_sequence";
|
|
std::vector<SampleRow> rows = with_ash_spi([&]() {
|
const int rc = SPI_execute_with_args(sql.c_str(),
|
argno - 1,
|
argtypes.empty() ? nullptr : argtypes.data(),
|
values.empty() ? nullptr : values.data(),
|
nulls.empty() ? nullptr : nulls.data(),
|
true,
|
0);
|
|
if (rc != SPI_OK_SELECT)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось получить historical ASH samples")));
|
|
const uint64 processed = SPI_processed;
|
std::vector<SampleRow> result;
|
if (processed > result.max_size() ||
|
processed > std::numeric_limits<std::size_t>::max() / sizeof(SampleRow))
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
errmsg("слишком много historical ASH samples для формирования отчёта")));
|
}
|
result.reserve(static_cast<std::size_t>(processed));
|
|
for (uint64 idx = 0; idx < processed; ++idx)
|
{
|
HeapTuple tuple = SPI_tuptable->vals[idx];
|
TupleDesc tupdesc = SPI_tuptable->tupdesc;
|
bool isnull = false;
|
SampleRow row;
|
row.sample_sequence = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 1, &isnull));
|
row.sample_time = DatumGetTimestampTz(SPI_getbinval(tuple, tupdesc, 2, &isnull));
|
row.dbid = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 3, &isnull));
|
row.instance_number = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 4, &isnull));
|
row.session_id = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 5, &isnull));
|
row.session_serial = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 6, &isnull));
|
row.session_generation = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 7, &isnull));
|
Datum started_at = SPI_getbinval(tuple, tupdesc, 8, &isnull);
|
if (!isnull)
|
row.started_at = DatumGetTimestampTz(started_at);
|
row.command_type = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 9, &isnull));
|
row.backend_type = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 10, &isnull));
|
row.user_id = DatumGetObjectId(SPI_getbinval(tuple, tupdesc, 11, &isnull));
|
row.sql_id = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 12, &isnull));
|
row.sql_text = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 13, &isnull));
|
row.module_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 14, &isnull));
|
row.application_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 15, &isnull));
|
row.state = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 16, &isnull));
|
row.wait_class = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 17, &isnull));
|
row.event_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 18, &isnull));
|
row.snap_id = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 19, &isnull));
|
row.is_awr_sample = DatumGetBool(SPI_getbinval(tuple, tupdesc, 20, &isnull));
|
|
if (matches_sample(row, filter))
|
result.push_back(std::move(row));
|
}
|
|
return result;
|
});
|
|
std::sort(rows.begin(), rows.end(),
|
[](const SampleRow& left, const SampleRow& right)
|
{
|
return left.sample_sequence < right.sample_sequence;
|
});
|
return rows;
|
}
|
|
bool
|
rudb::ash::archive_snapshot(int64_t dbid,
|
int64_t instance_number,
|
int64_t snap_id,
|
TimestampTz begin_time,
|
TimestampTz end_time)
|
{
|
// Интервал архива использует (начало, конец]; метки публикует
|
// обратный вызов транзакции.
|
HistoryFilter filter;
|
filter.dbid = dbid;
|
filter.instance_number = instance_number;
|
filter.begin_time = begin_time;
|
filter.end_time = end_time;
|
filter.begin_time_exclusive = true;
|
filter.end_time_exclusive = false;
|
std::vector<MemoryArchiveCandidate> rows = collect_memory_archive_candidates(filter);
|
reserve_pending_archive_marks(rows.size());
|
|
with_ash_spi([&]() {
|
for (const MemoryArchiveCandidate& candidate : rows)
|
{
|
const SampleRow& row = candidate.row;
|
constexpr int kArchiveSampleArgCount = 18;
|
|
Oid sample_argtypes[] = {
|
INT8OID, TIMESTAMPTZOID, INT8OID, INT8OID, INT8OID, INT8OID, INT8OID, TIMESTAMPTZOID,
|
TEXTOID, TEXTOID, OIDOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, INT8OID
|
};
|
Datum sample_values[] = {
|
Int64GetDatum(static_cast<int64>(row.sample_sequence)),
|
TimestampTzGetDatum(row.sample_time),
|
Int64GetDatum(row.dbid),
|
Int64GetDatum(row.instance_number),
|
Int64GetDatum(row.session_id),
|
Int64GetDatum(row.session_serial),
|
Int64GetDatum(row.session_generation),
|
TimestampTzGetDatum(row.started_at),
|
row.command_type.empty() ? (Datum) 0 : CStringGetTextDatum(row.command_type.c_str()),
|
row.backend_type.empty() ? (Datum) 0 : CStringGetTextDatum(row.backend_type.c_str()),
|
ObjectIdGetDatum(row.user_id),
|
row.sql_id.empty() ? (Datum) 0 : CStringGetTextDatum(row.sql_id.c_str()),
|
row.module_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.module_name.c_str()),
|
row.application_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.application_name.c_str()),
|
row.state.empty() ? (Datum) 0 : CStringGetTextDatum(row.state.c_str()),
|
row.wait_class.empty() ? (Datum) 0 : CStringGetTextDatum(row.wait_class.c_str()),
|
row.event_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.event_name.c_str()),
|
Int64GetDatum(snap_id)
|
};
|
StaticAssertDecl(lengthof(sample_argtypes) == kArchiveSampleArgCount,
|
"archive sample argtypes count must stay synchronized");
|
StaticAssertDecl(lengthof(sample_values) == kArchiveSampleArgCount,
|
"archive sample values count must stay synchronized");
|
const char sample_nulls[] = {
|
' ', ' ', ' ', ' ', ' ', ' ', ' ', row.started_at == 0 ? 'n' : ' ',
|
row.command_type.empty() ? 'n' : ' ', row.backend_type.empty() ? 'n' : ' ',
|
row.user_id == InvalidOid ? 'n' : ' ',
|
row.sql_id.empty() ? 'n' : ' ',
|
row.module_name.empty() ? 'n' : ' ',
|
row.application_name.empty() ? 'n' : ' ',
|
row.state.empty() ? 'n' : ' ',
|
row.wait_class.empty() ? 'n' : ' ',
|
row.event_name.empty() ? 'n' : ' ',
|
' '
|
};
|
StaticAssertDecl(lengthof(sample_nulls) == kArchiveSampleArgCount,
|
"archive sample null flags count must stay synchronized");
|
const int sample_rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.rudb_ash_history_samples("
|
" sample_sequence, sample_time, dbid, instance_number, session_id,"
|
" session_serial, session_generation, started_at, command_type, backend_type, user_id, sql_id, module_name, application_name,"
|
" state, wait_class, event_name, snap_id, is_awr_sample)"
|
" VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, true)"
|
" ON CONFLICT (sample_sequence) DO NOTHING",
|
kArchiveSampleArgCount, sample_argtypes, sample_values, sample_nulls, false, 0);
|
if (sample_rc != SPI_OK_INSERT && sample_rc != SPI_OK_INSERT_RETURNING)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось архивировать RUDB ASH sample")));
|
|
const bool sample_inserted = SPI_processed == 1;
|
if (!row.sql_id.empty() && !row.sql_text.empty())
|
{
|
Oid sqltext_argtypes[] = {INT8OID, TEXTOID, TEXTOID, TIMESTAMPTZOID, TIMESTAMPTZOID};
|
Datum sqltext_values[] = {
|
Int64GetDatum(row.dbid),
|
CStringGetTextDatum(row.sql_id.c_str()),
|
CStringGetTextDatum(row.sql_text.c_str()),
|
TimestampTzGetDatum(row.sample_time),
|
TimestampTzGetDatum(row.sample_time)
|
};
|
const char sqltext_nulls[] = {' ', ' ', ' ', ' ', ' '};
|
const int sqltext_rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.rudb_ash_history_sqltext(dbid, sql_id, sql_text, first_seen, last_seen)"
|
" VALUES ($1, $2, $3, $4, $5)"
|
" ON CONFLICT (dbid, sql_id)"
|
" DO UPDATE SET sql_text = EXCLUDED.sql_text, last_seen = EXCLUDED.last_seen",
|
5, sqltext_argtypes, sqltext_values, sqltext_nulls, false, 0);
|
if (sqltext_rc != SPI_OK_INSERT && sqltext_rc != SPI_OK_UPDATE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось архивировать RUDB ASH SQL text")));
|
}
|
if (sample_inserted)
|
{
|
pending_archive_marks().push_back(
|
{row.sample_sequence,
|
candidate.sample_generation,
|
candidate.activity_generation,
|
snap_id,
|
GetCurrentSubTransactionId()});
|
}
|
}
|
|
return 0;
|
});
|
return true;
|
}
|
|
void
|
rudb::ash::mark_snapshot_range_pending_clear(int64_t dbid,
|
int64_t low_snap_id,
|
int64_t high_snap_id)
|
{
|
reserve_pending_snapshot_clear_marks(1);
|
pending_snapshot_clear_marks().push_back(
|
{dbid, low_snap_id, high_snap_id, GetCurrentSubTransactionId()});
|
}
|
|
void
|
rudb::ash::drop_snapshot_range(int64_t dbid, int64_t low_snap_id, int64_t high_snap_id)
|
{
|
// Метаданные снимков AWR и связанные записи ASH удаляются
|
// согласованно для одного диапазона.
|
Oid argtypes[] = {INT8OID, INT8OID, INT8OID};
|
Datum values[] = {Int64GetDatum(dbid), Int64GetDatum(low_snap_id), Int64GetDatum(high_snap_id)};
|
const char nulls[] = {' ', ' ', ' '};
|
with_ash_spi([&]() {
|
int rc = SPI_execute_with_args(
|
"DELETE FROM pg_catalog.rudb_ash_history_samples"
|
" WHERE dbid = $1 AND snap_id >= $2 AND snap_id <= $3",
|
3, argtypes, values, nulls, false, 0);
|
if (rc != SPI_OK_DELETE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось удалить RUDB ASH history samples")));
|
|
mark_snapshot_range_pending_clear(dbid, low_snap_id, high_snap_id);
|
|
rc = SPI_execute(
|
"DELETE FROM pg_catalog.rudb_ash_history_sqltext t "
|
"WHERE NOT EXISTS ("
|
" SELECT 1 FROM pg_catalog.rudb_ash_history_samples s"
|
" WHERE s.dbid = t.dbid AND s.sql_id = t.sql_id)",
|
false, 0);
|
if (rc != SPI_OK_DELETE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось удалить orphan RUDB ASH SQL texts")));
|
return 0;
|
});
|
}
|
|
void
|
rudb::ash::purge_history(int retention_seconds)
|
{
|
// Очистка удаляет постоянное историческое хранилище; кольцевой буфер
|
// в памяти ограничен независимо.
|
char* sql = psprintf(
|
"DELETE FROM %s WHERE sample_time < clock_timestamp() - make_interval(secs => %d)",
|
kHistorySampleTable,
|
retention_seconds);
|
try
|
{
|
with_ash_spi([&]() {
|
int rc = SPI_execute(sql, false, 0);
|
if (rc != SPI_OK_DELETE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось очистить RUDB ASH history")));
|
|
rc = SPI_execute(
|
"DELETE FROM pg_catalog.rudb_ash_history_sqltext t "
|
"WHERE NOT EXISTS ("
|
" SELECT 1 FROM pg_catalog.rudb_ash_history_samples s"
|
" WHERE s.dbid = t.dbid AND s.sql_id = t.sql_id)",
|
false, 0);
|
if (rc != SPI_OK_DELETE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("не удалось очистить orphan RUDB ASH SQL texts")));
|
return 0;
|
});
|
}
|
catch (...)
|
{
|
pfree(sql);
|
throw;
|
}
|
pfree(sql);
|
}
|
|
std::size_t
|
rudb::ash::sql_text_count(void)
|
{
|
ensure_shared_state_attached();
|
std::size_t count = 0;
|
|
LWLockAcquire(g_ash_lock, LW_SHARED);
|
for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
|
{
|
if (sql_cache()[idx].generation != 0)
|
++count;
|
}
|
LWLockRelease(g_ash_lock);
|
return count;
|
}
|
|
std::size_t
|
rudb::ash::sample_count(void)
|
{
|
ensure_shared_state_attached();
|
std::size_t count = 0;
|
|
LWLockAcquire(g_ash_lock, LW_SHARED);
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
if (sample_ring()[idx].sample_sequence != 0)
|
++count;
|
}
|
LWLockRelease(g_ash_lock);
|
return count;
|
}
|
|
std::string
|
rudb::ash::service_state(void)
|
{
|
ensure_shared_state_attached();
|
std::size_t sql_cache_count = 0;
|
std::size_t memory_sample_count = 0;
|
std::size_t retained_memory_sample_count = 0;
|
std::size_t current_db_memory_sample_count = 0;
|
AshSharedHeader header_snapshot{};
|
const TimestampTz retention_cutoff =
|
GetCurrentTimestamp() -
|
static_cast<TimestampTz>(g_retention_seconds) * USECS_PER_SEC;
|
const int64 current_dbid = MyDatabaseId == InvalidOid ? 0 : local_dbid_impl(MyDatabaseId);
|
|
LWLockAcquire(g_ash_lock, LW_SHARED);
|
header_snapshot = *g_shared;
|
for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
|
{
|
if (sql_cache()[idx].generation != 0)
|
++sql_cache_count;
|
}
|
for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
|
{
|
const AshSharedSample& sample = sample_ring()[idx];
|
|
if (sample.sample_sequence == 0)
|
continue;
|
|
++memory_sample_count;
|
if (sample.sample_time < retention_cutoff)
|
continue;
|
|
++retained_memory_sample_count;
|
if (current_dbid != 0 && sample.dbid == current_dbid)
|
++current_db_memory_sample_count;
|
}
|
LWLockRelease(g_ash_lock);
|
return "ash_worker_pid=" + std::to_string(header_snapshot.worker_pid) +
|
"; ash_sample_interval_ms=" + std::to_string(header_snapshot.sample_interval_ms) +
|
"; ash_retention_seconds=" + std::to_string(header_snapshot.retention_seconds) +
|
"; ash_sql_cache=" + std::to_string(sql_cache_count) +
|
"; ash_dropped_samples=" + std::to_string(header_snapshot.dropped_samples) +
|
"; ash_memory_samples=" + std::to_string(memory_sample_count) +
|
"; ash_memory_slots_used=" + std::to_string(memory_sample_count) +
|
"; ash_memory_samples_retained=" + std::to_string(retained_memory_sample_count) +
|
"; ash_memory_samples_current_db=" + std::to_string(current_db_memory_sample_count) +
|
"; ash_worker_cycles=" + std::to_string(header_snapshot.worker_cycles) +
|
"; ash_next_ring_position=" + std::to_string(header_snapshot.next_ring_position) +
|
"; ash_active_slots_seen=" + std::to_string(header_snapshot.active_slots_seen) +
|
"; ash_samples_written=" + std::to_string(header_snapshot.samples_written) +
|
"; ash_reject_unstable_publication=" + std::to_string(header_snapshot.reject_unstable_publication) +
|
"; ash_reject_inactive_slot=" + std::to_string(header_snapshot.reject_inactive_slot) +
|
"; ash_reject_invalid_proc_number=" + std::to_string(header_snapshot.reject_invalid_proc_number) +
|
"; ash_reject_missing_pgproc=" + std::to_string(header_snapshot.reject_missing_pgproc) +
|
"; ash_reject_pid_mismatch=" + std::to_string(header_snapshot.reject_pid_mismatch) +
|
"; ash_reject_self_pid=" + std::to_string(header_snapshot.reject_self_pid) +
|
"; ash_reject_invalid_database=" + std::to_string(header_snapshot.reject_invalid_database) +
|
"; ash_reject_sql_cache_reference=" + std::to_string(header_snapshot.reject_sql_cache_reference);
|
}
|
|
int
|
rudb::ash::retention_seconds(void)
|
{
|
return g_retention_seconds;
|
}
|
|
int
|
rudb::ash::sample_interval_ms(void)
|
{
|
return g_sample_interval_ms;
|
}
|
|
int64_t
|
rudb::ash::local_dbid(void)
|
{
|
return local_dbid_impl(MyDatabaseId);
|
}
|