PostgreSQL Source Code  git master
pgstat.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/twophase_rmgr.h"
#include "access/xact.h"
#include "catalog/pg_database.h"
#include "catalog/pg_proc.h"
#include "common/ip.h"
#include "executor/instrument.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/fork_process.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "storage/backendid.h"
#include "storage/dsm.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lmgr.h"
#include "storage/pg_shmem.h"
#include "storage/procsignal.h"
#include "storage/sinvaladt.h"
#include "utils/ascii.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/timestamp.h"
Include dependency graph for pgstat.c:

Go to the source code of this file.

Data Structures

struct  TabStatusArray
 
struct  TabStatHashEntry
 
struct  PgStat_SubXactStatus
 
struct  TwoPhasePgStatRecord
 

Macros

#define PGSTAT_STAT_INTERVAL
 
#define PGSTAT_RETRY_DELAY
 
#define PGSTAT_MAX_WAIT_TIME
 
#define PGSTAT_INQ_INTERVAL
 
#define PGSTAT_RESTART_INTERVAL
 
#define PGSTAT_POLL_LOOP_COUNT   (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
 
#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
 
#define PGSTAT_MIN_RCVBUF   (100 * 1024)
 
#define PGSTAT_DB_HASH_SIZE   16
 
#define PGSTAT_TAB_HASH_SIZE   512
 
#define PGSTAT_FUNCTION_HASH_SIZE   512
 
#define NumBackendStatSlots   (MaxBackends + NUM_AUXPROCTYPES)
 
#define SLRU_NUM_ELEMENTS   lengthof(slru_names)
 
#define TABSTAT_QUANTUM   100 /* we alloc this many at a time */
 
#define TESTBYTEVAL   ((char) 199)
 

Typedefs

typedef struct TabStatusArray TabStatusArray
 
typedef struct TabStatHashEntry TabStatHashEntry
 
typedef struct PgStat_SubXactStatus PgStat_SubXactStatus
 
typedef struct TwoPhasePgStatRecord TwoPhasePgStatRecord
 

Functions

NON_EXEC_STATIC void PgstatCollectorMain (int argc, char *argv[]) pg_attribute_noreturn()
 
static void pgstat_beshutdown_hook (int code, Datum arg)
 
static PgStat_StatDBEntrypgstat_get_db_entry (Oid databaseid, bool create)
 
static PgStat_StatTabEntrypgstat_get_tab_entry (PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
 
static void pgstat_write_statsfiles (bool permanent, bool allDbs)
 
static void pgstat_write_db_statsfile (PgStat_StatDBEntry *dbentry, bool permanent)
 
static HTABpgstat_read_statsfiles (Oid onlydb, bool permanent, bool deep)
 
static void pgstat_read_db_statsfile (Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent)
 
static void backend_read_statsfile (void)
 
static void pgstat_read_current_status (void)
 
static bool pgstat_write_statsfile_needed (void)
 
static bool pgstat_db_requested (Oid databaseid)
 
static int pgstat_replslot_index (const char *name, bool create_it)
 
static void pgstat_reset_replslot (int i, TimestampTz ts)
 
static void pgstat_send_tabstat (PgStat_MsgTabstat *tsmsg)
 
static void pgstat_send_funcstats (void)
 
static void pgstat_send_slru (void)
 
static HTABpgstat_collect_oids (Oid catalogid, AttrNumber anum_oid)
 
static void pgstat_send_connstats (bool disconnect, TimestampTz last_report)
 
static PgStat_TableStatusget_tabstat_entry (Oid rel_id, bool isshared)
 
static void pgstat_setup_memcxt (void)
 
static const char * pgstat_get_wait_activity (WaitEventActivity w)
 
static const char * pgstat_get_wait_client (WaitEventClient w)
 
static const char * pgstat_get_wait_ipc (WaitEventIPC w)
 
static const char * pgstat_get_wait_timeout (WaitEventTimeout w)
 
static const char * pgstat_get_wait_io (WaitEventIO w)
 
static void pgstat_setheader (PgStat_MsgHdr *hdr, StatMsgType mtype)
 
static void pgstat_send (void *msg, int len)
 
static void pgstat_recv_inquiry (PgStat_MsgInquiry *msg, int len)
 
static void pgstat_recv_tabstat (PgStat_MsgTabstat *msg, int len)
 
static void pgstat_recv_tabpurge (PgStat_MsgTabpurge *msg, int len)
 
static void pgstat_recv_dropdb (PgStat_MsgDropdb *msg, int len)
 
static void pgstat_recv_resetcounter (PgStat_MsgResetcounter *msg, int len)
 
static void pgstat_recv_resetsharedcounter (PgStat_MsgResetsharedcounter *msg, int len)
 
static void pgstat_recv_resetsinglecounter (PgStat_MsgResetsinglecounter *msg, int len)
 
static void pgstat_recv_resetslrucounter (PgStat_MsgResetslrucounter *msg, int len)
 
static void pgstat_recv_resetreplslotcounter (PgStat_MsgResetreplslotcounter *msg, int len)
 
static void pgstat_recv_autovac (PgStat_MsgAutovacStart *msg, int len)
 
static void pgstat_recv_vacuum (PgStat_MsgVacuum *msg, int len)
 
static void pgstat_recv_analyze (PgStat_MsgAnalyze *msg, int len)
 
static void pgstat_recv_archiver (PgStat_MsgArchiver *msg, int len)
 
static void pgstat_recv_bgwriter (PgStat_MsgBgWriter *msg, int len)
 
static void pgstat_recv_wal (PgStat_MsgWal *msg, int len)
 
static void pgstat_recv_slru (PgStat_MsgSLRU *msg, int len)
 
static void pgstat_recv_funcstat (PgStat_MsgFuncstat *msg, int len)
 
static void pgstat_recv_funcpurge (PgStat_MsgFuncpurge *msg, int len)
 
static void pgstat_recv_recoveryconflict (PgStat_MsgRecoveryConflict *msg, int len)
 
static void pgstat_recv_deadlock (PgStat_MsgDeadlock *msg, int len)
 
static void pgstat_recv_checksum_failure (PgStat_MsgChecksumFailure *msg, int len)
 
static void pgstat_recv_connstat (PgStat_MsgConn *msg, int len)
 
static void pgstat_recv_replslot (PgStat_MsgReplSlot *msg, int len)
 
static void pgstat_recv_tempfile (PgStat_MsgTempFile *msg, int len)
 
void pgstat_init (void)
 
static void pgstat_reset_remove_files (const char *directory)
 
void pgstat_reset_all (void)
 
int pgstat_start (void)
 
void allow_immediate_pgstat_restart (void)
 
void pgstat_report_stat (bool disconnect)
 
void pgstat_vacuum_stat (void)
 
void pgstat_drop_database (Oid databaseid)
 
void pgstat_reset_counters (void)
 
void pgstat_reset_shared_counters (const char *target)
 
void pgstat_reset_single_counter (Oid objoid, PgStat_Single_Reset_Type type)
 
void pgstat_reset_slru_counter (const char *name)
 
void pgstat_reset_replslot_counter (const char *name)
 
void pgstat_report_autovac (Oid dboid)
 
void pgstat_report_vacuum (Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
 
void pgstat_report_analyze (Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
 
void pgstat_report_recovery_conflict (int reason)
 
void pgstat_report_deadlock (void)
 
void pgstat_report_checksum_failures_in_db (Oid dboid, int failurecount)
 
void pgstat_report_checksum_failure (void)
 
void pgstat_report_tempfile (size_t filesize)
 
void pgstat_report_replslot (const char *slotname, int spilltxns, int spillcount, int spillbytes, int streamtxns, int streamcount, int streambytes)
 
void pgstat_report_replslot_drop (const char *slotname)
 
void pgstat_ping (void)
 
static void pgstat_send_inquiry (TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
 
void pgstat_init_function_usage (FunctionCallInfo fcinfo, PgStat_FunctionCallUsage *fcu)
 
PgStat_BackendFunctionEntryfind_funcstat_entry (Oid func_id)
 
void pgstat_end_function_usage (PgStat_FunctionCallUsage *fcu, bool finalize)
 
void pgstat_initstats (Relation rel)
 
PgStat_TableStatusfind_tabstat_entry (Oid rel_id)
 
static PgStat_SubXactStatusget_tabstat_stack_level (int nest_level)
 
static void add_tabstat_xact_level (PgStat_TableStatus *pgstat_info, int nest_level)
 
void pgstat_count_heap_insert (Relation rel, PgStat_Counter n)
 
void pgstat_count_heap_update (Relation rel, bool hot)
 
void pgstat_count_heap_delete (Relation rel)
 
static void pgstat_truncate_save_counters (PgStat_TableXactStatus *trans)
 
static void pgstat_truncate_restore_counters (PgStat_TableXactStatus *trans)
 
void pgstat_count_truncate (Relation rel)
 
void pgstat_update_heap_dead_tuples (Relation rel, int delta)
 
void AtEOXact_PgStat (bool isCommit, bool parallel)
 
void AtEOSubXact_PgStat (bool isCommit, int nestDepth)
 
void AtPrepare_PgStat (void)
 
void PostPrepare_PgStat (void)
 
void pgstat_twophase_postcommit (TransactionId xid, uint16 info, void *recdata, uint32 len)
 
void pgstat_twophase_postabort (TransactionId xid, uint16 info, void *recdata, uint32 len)
 
PgStat_StatDBEntrypgstat_fetch_stat_dbentry (Oid dbid)
 
PgStat_StatTabEntrypgstat_fetch_stat_tabentry (Oid relid)
 
PgStat_StatFuncEntrypgstat_fetch_stat_funcentry (Oid func_id)
 
PgBackendStatuspgstat_fetch_stat_beentry (int beid)
 
LocalPgBackendStatuspgstat_fetch_stat_local_beentry (int beid)
 
int pgstat_fetch_stat_numbackends (void)
 
PgStat_ArchiverStatspgstat_fetch_stat_archiver (void)
 
PgStat_GlobalStatspgstat_fetch_global (void)
 
PgStat_WalStatspgstat_fetch_stat_wal (void)
 
PgStat_SLRUStatspgstat_fetch_slru (void)
 
PgStat_ReplSlotStatspgstat_fetch_replslot (int *nslots_p)
 
Size BackendStatusShmemSize (void)
 
void CreateSharedBackendStatus (void)
 
void pgstat_initialize (void)
 
void pgstat_bestart (void)
 
void pgstat_report_activity (BackendState state, const char *cmd_str)
 
void pgstat_progress_start_command (ProgressCommandType cmdtype, Oid relid)
 
void pgstat_progress_update_param (int index, int64 val)
 
void pgstat_progress_update_multi_param (int nparam, const int *index, const int64 *val)
 
void pgstat_progress_end_command (void)
 
void pgstat_report_appname (const char *appname)
 
void pgstat_report_xact_timestamp (TimestampTz tstamp)
 
const char * pgstat_get_wait_event_type (uint32 wait_event_info)
 
const char * pgstat_get_wait_event (uint32 wait_event_info)
 
const char * pgstat_get_backend_current_activity (int pid, bool checkUser)
 
const char * pgstat_get_crashed_backend_activity (int pid, char *buffer, int buflen)
 
void pgstat_send_archiver (const char *xlog, bool failed)
 
void pgstat_send_bgwriter (void)
 
void pgstat_send_wal (void)
 
static void reset_dbentry_counters (PgStat_StatDBEntry *dbentry)
 
static void get_dbstat_filename (bool permanent, bool tempname, Oid databaseid, char *filename, int len)
 
static bool pgstat_read_db_statsfile_timestamp (Oid databaseid, bool permanent, TimestampTz *ts)
 
void pgstat_clear_snapshot (void)
 
char * pgstat_clip_activity (const char *raw_activity)
 
int pgstat_slru_index (const char *name)
 
const char * pgstat_slru_name (int slru_idx)
 
static PgStat_MsgSLRUslru_entry (int slru_idx)
 
void pgstat_count_slru_page_zeroed (int slru_idx)
 
void pgstat_count_slru_page_hit (int slru_idx)
 
void pgstat_count_slru_page_exists (int slru_idx)
 
void pgstat_count_slru_page_read (int slru_idx)
 
void pgstat_count_slru_page_written (int slru_idx)
 
void pgstat_count_slru_flush (int slru_idx)
 
void pgstat_count_slru_truncate (int slru_idx)
 

Variables

bool pgstat_track_activities = false
 
bool pgstat_track_counts = false
 
int pgstat_track_functions = TRACK_FUNC_OFF
 
int pgstat_track_activity_query_size = 1024
 
char * pgstat_stat_directory = NULL
 
char * pgstat_stat_filename = NULL
 
char * pgstat_stat_tmpname = NULL
 
PgStat_MsgBgWriter BgWriterStats
 
PgStat_MsgWal WalStats
 
static WalUsage prevWalUsage
 
static const char *const slru_names []
 
static PgStat_MsgSLRU SLRUStats [SLRU_NUM_ELEMENTS]
 
NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET
 
static struct sockaddr_storage pgStatAddr
 
static time_t last_pgstat_start_time
 
static bool pgStatRunningInCollector = false
 
static TabStatusArraypgStatTabList = NULL
 
static HTABpgStatTabHash = NULL
 
static HTABpgStatFunctions = NULL
 
static bool have_function_stats = false
 
static PgStat_SubXactStatuspgStatXactStack = NULL
 
static int pgStatXactCommit = 0
 
static int pgStatXactRollback = 0
 
PgStat_Counter pgStatBlockReadTime = 0
 
PgStat_Counter pgStatBlockWriteTime = 0
 
static PgStat_Counter pgStatActiveTime = 0
 
static PgStat_Counter pgStatTransactionIdleTime = 0
 
SessionEndType pgStatSessionEndCause = DISCONNECT_NORMAL
 
static MemoryContext pgStatLocalContext = NULL
 
static HTABpgStatDBHash = NULL
 
static LocalPgBackendStatuslocalBackendStatusTable = NULL
 
static int localNumBackends = 0
 
static PgStat_ArchiverStats archiverStats
 
static PgStat_GlobalStats globalStats
 
static PgStat_WalStats walStats
 
static PgStat_SLRUStats slruStats [SLRU_NUM_ELEMENTS]
 
static PgStat_ReplSlotStatsreplSlotStats
 
static int nReplSlotStats
 
static Listpending_write_requests = NIL
 
static instr_time total_func_time
 
static PgBackendStatusBackendStatusArray = NULL
 
static PgBackendStatusMyBEEntry = NULL
 
static char * BackendAppnameBuffer = NULL
 
static char * BackendClientHostnameBuffer = NULL
 
static char * BackendActivityBuffer = NULL
 
static Size BackendActivityBufferSize = 0
 

Macro Definition Documentation

◆ NumBackendStatSlots

#define NumBackendStatSlots   (MaxBackends + NUM_AUXPROCTYPES)

◆ PGSTAT_DB_HASH_SIZE

#define PGSTAT_DB_HASH_SIZE   16

Definition at line 105 of file pgstat.c.

Referenced by pgstat_read_statsfiles().

◆ PGSTAT_FUNCTION_HASH_SIZE

#define PGSTAT_FUNCTION_HASH_SIZE   512

◆ PGSTAT_INQ_INTERVAL

#define PGSTAT_INQ_INTERVAL
Value:
640 /* How often to ping the collector for a
* new file; in milliseconds. */

Definition at line 87 of file pgstat.c.

◆ PGSTAT_INQ_LOOP_COUNT

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

Definition at line 95 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_MAX_WAIT_TIME

#define PGSTAT_MAX_WAIT_TIME
Value:
10000 /* Maximum time to wait for a stats
* file update; in milliseconds. */

Definition at line 84 of file pgstat.c.

◆ PGSTAT_MIN_RCVBUF

#define PGSTAT_MIN_RCVBUF   (100 * 1024)

Definition at line 98 of file pgstat.c.

Referenced by pgstat_init().

◆ PGSTAT_POLL_LOOP_COUNT

#define PGSTAT_POLL_LOOP_COUNT   (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)

Definition at line 94 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_RESTART_INTERVAL

#define PGSTAT_RESTART_INTERVAL
Value:
60 /* How often to attempt to restart a
* failed statistics collector; in
* seconds. */

Definition at line 90 of file pgstat.c.

Referenced by pgstat_start().

◆ PGSTAT_RETRY_DELAY

#define PGSTAT_RETRY_DELAY
Value:
10 /* How long to wait between checks for a
* new file; in milliseconds. */

Definition at line 81 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_STAT_INTERVAL

#define PGSTAT_STAT_INTERVAL
Value:
500 /* Minimum time between stats file
* updates; in milliseconds. */

Definition at line 78 of file pgstat.c.

Referenced by backend_read_statsfile(), and pgstat_report_stat().

◆ PGSTAT_TAB_HASH_SIZE

#define PGSTAT_TAB_HASH_SIZE   512

Definition at line 106 of file pgstat.c.

Referenced by pgstat_collect_oids(), pgstat_read_statsfiles(), and reset_dbentry_counters().

◆ SLRU_NUM_ELEMENTS

◆ TABSTAT_QUANTUM

#define TABSTAT_QUANTUM   100 /* we alloc this many at a time */

Definition at line 204 of file pgstat.c.

Referenced by get_tabstat_entry().

◆ TESTBYTEVAL

#define TESTBYTEVAL   ((char) 199)

Referenced by pgstat_init().

Typedef Documentation

◆ PgStat_SubXactStatus

◆ TabStatHashEntry

◆ TabStatusArray

◆ TwoPhasePgStatRecord

Function Documentation

◆ add_tabstat_xact_level()

static void add_tabstat_xact_level ( PgStat_TableStatus pgstat_info,
int  nest_level 
)
static

Definition at line 2148 of file pgstat.c.

References PgStat_SubXactStatus::first, get_tabstat_stack_level(), MemoryContextAllocZero(), PgStat_TableXactStatus::nest_level, PgStat_TableXactStatus::next, PgStat_TableXactStatus::parent, TopTransactionContext, PgStat_TableStatus::trans, trans, and PgStat_TableXactStatus::upper.

Referenced by pgstat_count_heap_delete(), pgstat_count_heap_insert(), pgstat_count_heap_update(), and pgstat_count_truncate().

2149 {
2150  PgStat_SubXactStatus *xact_state;
2152 
2153  /*
2154  * If this is the first rel to be modified at the current nest level, we
2155  * first have to push a transaction stack entry.
2156  */
2157  xact_state = get_tabstat_stack_level(nest_level);
2158 
2159  /* Now make a per-table stack entry */
2160  trans = (PgStat_TableXactStatus *)
2162  sizeof(PgStat_TableXactStatus));
2163  trans->nest_level = nest_level;
2164  trans->upper = pgstat_info->trans;
2165  trans->parent = pgstat_info;
2166  trans->next = xact_state->first;
2167  xact_state->first = trans;
2168  pgstat_info->trans = trans;
2169 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_TableXactStatus * next
Definition: pgstat.h:197
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:2126
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:194
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:840
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:252
PgStat_TableStatus * parent
Definition: pgstat.h:195

◆ allow_immediate_pgstat_restart()

void allow_immediate_pgstat_restart ( void  )

Definition at line 844 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

845 {
847 }
static time_t last_pgstat_start_time
Definition: pgstat.c:189

◆ AtEOSubXact_PgStat()

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

Definition at line 2408 of file pgstat.c.

References Assert, PgStat_SubXactStatus::first, get_tabstat_stack_level(), PgStat_TableXactStatus::nest_level, PgStat_SubXactStatus::nest_level, PgStat_TableXactStatus::next, PgStat_TableXactStatus::parent, pfree(), pgstat_truncate_restore_counters(), pgstat_truncate_save_counters(), pgStatXactStack, PgStat_SubXactStatus::prev, PgStat_TableStatus::t_counts, PgStat_TableCounts::t_delta_dead_tuples, PgStat_TableCounts::t_tuples_deleted, PgStat_TableCounts::t_tuples_inserted, PgStat_TableCounts::t_tuples_updated, PgStat_TableStatus::trans, trans, PgStat_TableXactStatus::truncated, PgStat_TableXactStatus::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, PgStat_TableXactStatus::tuples_updated, and PgStat_TableXactStatus::upper.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

2409 {
2410  PgStat_SubXactStatus *xact_state;
2411 
2412  /*
2413  * Transfer transactional insert/update counts into the next higher
2414  * subtransaction state.
2415  */
2416  xact_state = pgStatXactStack;
2417  if (xact_state != NULL &&
2418  xact_state->nest_level >= nestDepth)
2419  {
2421  PgStat_TableXactStatus *next_trans;
2422 
2423  /* delink xact_state from stack immediately to simplify reuse case */
2424  pgStatXactStack = xact_state->prev;
2425 
2426  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2427  {
2428  PgStat_TableStatus *tabstat;
2429 
2430  next_trans = trans->next;
2431  Assert(trans->nest_level == nestDepth);
2432  tabstat = trans->parent;
2433  Assert(tabstat->trans == trans);
2434  if (isCommit)
2435  {
2436  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2437  {
2438  if (trans->truncated)
2439  {
2440  /* propagate the truncate status one level up */
2442  /* replace upper xact stats with ours */
2443  trans->upper->tuples_inserted = trans->tuples_inserted;
2444  trans->upper->tuples_updated = trans->tuples_updated;
2445  trans->upper->tuples_deleted = trans->tuples_deleted;
2446  }
2447  else
2448  {
2449  trans->upper->tuples_inserted += trans->tuples_inserted;
2450  trans->upper->tuples_updated += trans->tuples_updated;
2451  trans->upper->tuples_deleted += trans->tuples_deleted;
2452  }
2453  tabstat->trans = trans->upper;
2454  pfree(trans);
2455  }
2456  else
2457  {
2458  /*
2459  * When there isn't an immediate parent state, we can just
2460  * reuse the record instead of going through a
2461  * palloc/pfree pushup (this works since it's all in
2462  * TopTransactionContext anyway). We have to re-link it
2463  * into the parent level, though, and that might mean
2464  * pushing a new entry into the pgStatXactStack.
2465  */
2466  PgStat_SubXactStatus *upper_xact_state;
2467 
2468  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2469  trans->next = upper_xact_state->first;
2470  upper_xact_state->first = trans;
2471  trans->nest_level = nestDepth - 1;
2472  }
2473  }
2474  else
2475  {
2476  /*
2477  * On abort, update top-level tabstat counts, then forget the
2478  * subtransaction
2479  */
2480 
2481  /* first restore values obliterated by truncate */
2483  /* count attempted actions regardless of commit/abort */
2484  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2485  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2486  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2487  /* inserted tuples are dead, deleted tuples are unaffected */
2488  tabstat->t_counts.t_delta_dead_tuples +=
2489  trans->tuples_inserted + trans->tuples_updated;
2490  tabstat->trans = trans->upper;
2491  pfree(trans);
2492  }
2493  }
2494  pfree(xact_state);
2495  }
2496 }
PgStat_Counter tuples_updated
Definition: pgstat.h:186
struct PgStat_TableXactStatus * next
Definition: pgstat.h:197
PgStat_TableCounts t_counts
Definition: pgstat.h:176
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:2126
void pfree(void *pointer)
Definition: mcxt.c:1057
PgStat_Counter t_tuples_updated
Definition: pgstat.h:122
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2262
PgStat_Counter tuples_inserted
Definition: pgstat.h:185
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:128
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:194
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:123
PgStat_Counter tuples_deleted
Definition: pgstat.h:187
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:251
#define Assert(condition)
Definition: c.h:792
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:255
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:252
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2247
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:121
PgStat_TableStatus * parent
Definition: pgstat.h:195

◆ AtEOXact_PgStat()

void AtEOXact_PgStat ( bool  isCommit,
bool  parallel 
)

Definition at line 2321 of file pgstat.c.

References Assert, PgStat_SubXactStatus::first, PgStat_TableXactStatus::nest_level, PgStat_SubXactStatus::nest_level, PgStat_TableXactStatus::next, PgStat_TableXactStatus::parent, pgstat_clear_snapshot(), pgstat_truncate_restore_counters(), pgStatXactCommit, pgStatXactRollback, pgStatXactStack, PgStat_SubXactStatus::prev, PgStat_TableCounts::t_changed_tuples, PgStat_TableStatus::t_counts, PgStat_TableCounts::t_delta_dead_tuples, PgStat_TableCounts::t_delta_live_tuples, PgStat_TableCounts::t_truncated, PgStat_TableCounts::t_tuples_deleted, PgStat_TableCounts::t_tuples_inserted, PgStat_TableCounts::t_tuples_updated, PgStat_TableStatus::trans, trans, PgStat_TableXactStatus::truncated, PgStat_TableXactStatus::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, PgStat_TableXactStatus::tuples_updated, and PgStat_TableXactStatus::upper.

Referenced by AbortTransaction(), CommitTransaction(), and FinishPreparedTransaction().

2322 {
2323  PgStat_SubXactStatus *xact_state;
2324 
2325  /* Don't count parallel worker transaction stats */
2326  if (!parallel)
2327  {
2328  /*
2329  * Count transaction commit or abort. (We use counters, not just
2330  * bools, in case the reporting message isn't sent right away.)
2331  */
2332  if (isCommit)
2333  pgStatXactCommit++;
2334  else
2336  }
2337 
2338  /*
2339  * Transfer transactional insert/update counts into the base tabstat
2340  * entries. We don't bother to free any of the transactional state, since
2341  * it's all in TopTransactionContext and will go away anyway.
2342  */
2343  xact_state = pgStatXactStack;
2344  if (xact_state != NULL)
2345  {
2347 
2348  Assert(xact_state->nest_level == 1);
2349  Assert(xact_state->prev == NULL);
2350  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2351  {
2352  PgStat_TableStatus *tabstat;
2353 
2354  Assert(trans->nest_level == 1);
2355  Assert(trans->upper == NULL);
2356  tabstat = trans->parent;
2357  Assert(tabstat->trans == trans);
2358  /* restore pre-truncate stats (if any) in case of aborted xact */
2359  if (!isCommit)
2361  /* count attempted actions regardless of commit/abort */
2362  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2363  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2364  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2365  if (isCommit)
2366  {
2367  tabstat->t_counts.t_truncated = trans->truncated;
2368  if (trans->truncated)
2369  {
2370  /* forget live/dead stats seen by backend thus far */
2371  tabstat->t_counts.t_delta_live_tuples = 0;
2372  tabstat->t_counts.t_delta_dead_tuples = 0;
2373  }
2374  /* insert adds a live tuple, delete removes one */
2375  tabstat->t_counts.t_delta_live_tuples +=
2376  trans->tuples_inserted - trans->tuples_deleted;
2377  /* update and delete each create a dead tuple */
2378  tabstat->t_counts.t_delta_dead_tuples +=
2379  trans->tuples_updated + trans->tuples_deleted;
2380  /* insert, update, delete each count as one change event */
2381  tabstat->t_counts.t_changed_tuples +=
2382  trans->tuples_inserted + trans->tuples_updated +
2383  trans->tuples_deleted;
2384  }
2385  else
2386  {
2387  /* inserted tuples are dead, deleted tuples are unaffected */
2388  tabstat->t_counts.t_delta_dead_tuples +=
2389  trans->tuples_inserted + trans->tuples_updated;
2390  /* an aborted xact generates no changed_tuple events */
2391  }
2392  tabstat->trans = NULL;
2393  }
2394  }
2395  pgStatXactStack = NULL;
2396 
2397  /* Make sure any stats snapshot is thrown away */
2399 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:127
PgStat_Counter tuples_updated
Definition: pgstat.h:186
static int pgStatXactCommit
Definition: pgstat.c:257
struct PgStat_TableXactStatus * next
Definition: pgstat.h:197
PgStat_TableCounts t_counts
Definition: pgstat.h:176
PgStat_Counter t_tuples_updated
Definition: pgstat.h:122
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2262
static int pgStatXactRollback
Definition: pgstat.c:258
PgStat_Counter tuples_inserted
Definition: pgstat.h:185
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:128
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:194
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:123
PgStat_Counter tuples_deleted
Definition: pgstat.h:187
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:251
PgStat_Counter t_changed_tuples
Definition: pgstat.h:129
#define Assert(condition)
Definition: c.h:792
void pgstat_clear_snapshot(void)
Definition: pgstat.c:6270
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:255
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:252
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:121
PgStat_TableStatus * parent
Definition: pgstat.h:195

◆ AtPrepare_PgStat()

void AtPrepare_PgStat ( void  )

Definition at line 2507 of file pgstat.c.

References Assert, PgStat_TableXactStatus::deleted_pre_trunc, TwoPhasePgStatRecord::deleted_pre_trunc, PgStat_SubXactStatus::first, PgStat_TableXactStatus::inserted_pre_trunc, TwoPhasePgStatRecord::inserted_pre_trunc, PgStat_TableXactStatus::nest_level, PgStat_SubXactStatus::nest_level, PgStat_TableXactStatus::next, PgStat_TableXactStatus::parent, pgStatXactStack, PgStat_SubXactStatus::prev, RegisterTwoPhaseRecord(), PgStat_TableStatus::t_id, TwoPhasePgStatRecord::t_id, PgStat_TableStatus::t_shared, TwoPhasePgStatRecord::t_shared, TwoPhasePgStatRecord::t_truncated, PgStat_TableStatus::trans, trans, PgStat_TableXactStatus::truncated, PgStat_TableXactStatus::tuples_deleted, TwoPhasePgStatRecord::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, TwoPhasePgStatRecord::tuples_inserted, PgStat_TableXactStatus::tuples_updated, TwoPhasePgStatRecord::tuples_updated, TWOPHASE_RM_PGSTAT_ID, PgStat_TableXactStatus::updated_pre_trunc, TwoPhasePgStatRecord::updated_pre_trunc, and PgStat_TableXactStatus::upper.

Referenced by PrepareTransaction().

2508 {
2509  PgStat_SubXactStatus *xact_state;
2510 
2511  xact_state = pgStatXactStack;
2512  if (xact_state != NULL)
2513  {
2515 
2516  Assert(xact_state->nest_level == 1);
2517  Assert(xact_state->prev == NULL);
2518  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2519  {
2520  PgStat_TableStatus *tabstat;
2521  TwoPhasePgStatRecord record;
2522 
2523  Assert(trans->nest_level == 1);
2524  Assert(trans->upper == NULL);
2525  tabstat = trans->parent;
2526  Assert(tabstat->trans == trans);
2527 
2528  record.tuples_inserted = trans->tuples_inserted;
2529  record.tuples_updated = trans->tuples_updated;
2530  record.tuples_deleted = trans->tuples_deleted;
2531  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2532  record.updated_pre_trunc = trans->updated_pre_trunc;
2533  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2534  record.t_id = tabstat->t_id;
2535  record.t_shared = tabstat->t_shared;
2536  record.t_truncated = trans->truncated;
2537 
2539  &record, sizeof(TwoPhasePgStatRecord));
2540  }
2541  }
2542 }
PgStat_Counter tuples_updated
Definition: pgstat.h:186
struct PgStat_TableXactStatus * next
Definition: pgstat.h:197
PgStat_Counter deleted_pre_trunc
Definition: pgstat.h:191
PgStat_Counter deleted_pre_trunc
Definition: pgstat.c:273
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1181
PgStat_Counter tuples_inserted
Definition: pgstat.h:185
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:272
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:271
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:194
PgStat_Counter tuples_updated
Definition: pgstat.c:269
PgStat_Counter tuples_deleted
Definition: pgstat.h:187
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:251
#define Assert(condition)
Definition: c.h:792
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:189
PgStat_Counter tuples_inserted
Definition: pgstat.c:268
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:255
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175
PgStat_Counter tuples_deleted
Definition: pgstat.c:270
#define TWOPHASE_RM_PGSTAT_ID
Definition: twophase_rmgr.h:26
PgStat_Counter updated_pre_trunc
Definition: pgstat.h:190
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:252
PgStat_TableStatus * parent
Definition: pgstat.h:195

◆ backend_read_statsfile()

static void backend_read_statsfile ( void  )
static

Definition at line 6115 of file pgstat.c.

References Assert, CHECK_FOR_INTERRUPTS, ereport, errmsg(), GetCurrentTimestamp(), InvalidOid, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), LOG, MyDatabaseId, pfree(), pg_usleep(), PGSTAT_INQ_LOOP_COUNT, PGSTAT_POLL_LOOP_COUNT, pgstat_read_db_statsfile_timestamp(), pgstat_read_statsfiles(), PGSTAT_RETRY_DELAY, pgstat_send_inquiry(), PGSTAT_STAT_INTERVAL, pgStatRunningInCollector, pstrdup(), timestamptz_to_str(), and TimestampTzPlusMilliseconds.

Referenced by pgstat_fetch_global(), pgstat_fetch_replslot(), pgstat_fetch_slru(), pgstat_fetch_stat_archiver(), pgstat_fetch_stat_dbentry(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), pgstat_fetch_stat_wal(), and pgstat_vacuum_stat().

6116 {
6117  TimestampTz min_ts = 0;
6118  TimestampTz ref_ts = 0;
6119  Oid inquiry_db;
6120  int count;
6121 
6122  /* already read it? */
6123  if (pgStatDBHash)
6124  return;
6126 
6127  /*
6128  * In a normal backend, we check staleness of the data for our own DB, and
6129  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
6130  * check staleness of the shared-catalog data, and send InvalidOid in
6131  * inquiry messages so as not to force writing unnecessary data.
6132  */
6134  inquiry_db = InvalidOid;
6135  else
6136  inquiry_db = MyDatabaseId;
6137 
6138  /*
6139  * Loop until fresh enough stats file is available or we ran out of time.
6140  * The stats inquiry message is sent repeatedly in case collector drops
6141  * it; but not every single time, as that just swamps the collector.
6142  */
6143  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
6144  {
6145  bool ok;
6146  TimestampTz file_ts = 0;
6147  TimestampTz cur_ts;
6148 
6150 
6151  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
6152 
6153  cur_ts = GetCurrentTimestamp();
6154  /* Calculate min acceptable timestamp, if we didn't already */
6155  if (count == 0 || cur_ts < ref_ts)
6156  {
6157  /*
6158  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
6159  * msec before now. This indirectly ensures that the collector
6160  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
6161  * an autovacuum worker, however, we want a lower delay to avoid
6162  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
6163  * number of workers is low, this shouldn't be a problem).
6164  *
6165  * We don't recompute min_ts after sleeping, except in the
6166  * unlikely case that cur_ts went backwards. So we might end up
6167  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
6168  * practice that shouldn't happen, though, as long as the sleep
6169  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
6170  * tell the collector that our cutoff time is less than what we'd
6171  * actually accept.
6172  */
6173  ref_ts = cur_ts;
6175  min_ts = TimestampTzPlusMilliseconds(ref_ts,
6177  else
6178  min_ts = TimestampTzPlusMilliseconds(ref_ts,
6180  }
6181 
6182  /*
6183  * If the file timestamp is actually newer than cur_ts, we must have
6184  * had a clock glitch (system time went backwards) or there is clock
6185  * skew between our processor and the stats collector's processor.
6186  * Accept the file, but send an inquiry message anyway to make
6187  * pgstat_recv_inquiry do a sanity check on the collector's time.
6188  */
6189  if (ok && file_ts > cur_ts)
6190  {
6191  /*
6192  * A small amount of clock skew between processors isn't terribly
6193  * surprising, but a large difference is worth logging. We
6194  * arbitrarily define "large" as 1000 msec.
6195  */
6196  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
6197  {
6198  char *filetime;
6199  char *mytime;
6200 
6201  /* Copy because timestamptz_to_str returns a static buffer */
6202  filetime = pstrdup(timestamptz_to_str(file_ts));
6203  mytime = pstrdup(timestamptz_to_str(cur_ts));
6204  ereport(LOG,
6205  (errmsg("statistics collector's time %s is later than backend local time %s",
6206  filetime, mytime)));
6207  pfree(filetime);
6208  pfree(mytime);
6209  }
6210 
6211  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
6212  break;
6213  }
6214 
6215  /* Normal acceptance case: file is not older than cutoff time */
6216  if (ok && file_ts >= min_ts)
6217  break;
6218 
6219  /* Not there or too old, so kick the collector and wait a bit */
6220  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
6221  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
6222 
6223  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
6224  }
6225 
6226  if (count >= PGSTAT_POLL_LOOP_COUNT)
6227  ereport(LOG,
6228  (errmsg("using stale statistics instead of current ones "
6229  "because stats collector is not responding")));
6230 
6231  /*
6232  * Autovacuum launcher wants stats about all databases, but a shallow read
6233  * is sufficient. Regular backends want a deep read for just the tables
6234  * they can see (MyDatabaseId + shared catalogs).
6235  */
6238  else
6240 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:81
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
int64 TimestampTz
Definition: timestamp.h:39
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:95
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static bool pgStatRunningInCollector
Definition: pgstat.c:191
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PGSTAT_POLL_LOOP_COUNT
Definition: pgstat.c:94
void pg_usleep(long microsec)
Definition: signal.c:53
void pfree(void *pointer)
Definition: mcxt.c:1057
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1838
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:78
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3394
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:5499
Oid MyDatabaseId
Definition: globals.c:86
#define InvalidOid
Definition: postgres_ext.h:36
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:155
static bool pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent, TimestampTz *ts)
Definition: pgstat.c:5951
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3388
#define Assert(condition)
Definition: c.h:792
static HTAB * pgStatDBHash
Definition: pgstat.c:283
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1772

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 2928 of file pgstat.c.

References add_size(), mul_size(), NAMEDATALEN, NumBackendStatSlots, and pgstat_track_activity_query_size.

Referenced by CreateSharedMemoryAndSemaphores().

2929 {
2930  Size size;
2931 
2932  /* BackendStatusArray: */
2933  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2934  /* BackendAppnameBuffer: */
2935  size = add_size(size,
2937  /* BackendClientHostnameBuffer: */
2938  size = add_size(size,
2940  /* BackendActivityBuffer: */
2941  size = add_size(size,
2943 #ifdef USE_SSL
2944  /* BackendSslStatusBuffer: */
2945  size = add_size(size,
2947 #endif
2948 #ifdef ENABLE_GSS
2949  /* BackendGssStatusBuffer: */
2950  size = add_size(size,
2952 #endif
2953  return size;
2954 }
#define NumBackendStatSlots
Definition: pgstat.c:119
#define NAMEDATALEN
int pgstat_track_activity_query_size
Definition: pgstat.c:129
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
size_t Size
Definition: c.h:528

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

Definition at line 2961 of file pgstat.c.

References BackendActivityBuffer, BackendActivityBufferSize, BackendAppnameBuffer, BackendClientHostnameBuffer, i, MemSet, mul_size(), NAMEDATALEN, NumBackendStatSlots, pgstat_track_activity_query_size, ShmemInitStruct(), PgBackendStatus::st_activity_raw, PgBackendStatus::st_appname, PgBackendStatus::st_clienthostname, PgBackendStatus::st_gssstatus, and PgBackendStatus::st_sslstatus.

Referenced by CreateSharedMemoryAndSemaphores().

2962 {
2963  Size size;
2964  bool found;
2965  int i;
2966  char *buffer;
2967 
2968  /* Create or attach to the shared array */
2969  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2971  ShmemInitStruct("Backend Status Array", size, &found);
2972 
2973  if (!found)
2974  {
2975  /*
2976  * We're the first - initialize.
2977  */
2978  MemSet(BackendStatusArray, 0, size);
2979  }
2980 
2981  /* Create or attach to the shared appname buffer */
2983  BackendAppnameBuffer = (char *)
2984  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2985 
2986  if (!found)
2987  {
2988  MemSet(BackendAppnameBuffer, 0, size);
2989 
2990  /* Initialize st_appname pointers. */
2991  buffer = BackendAppnameBuffer;
2992  for (i = 0; i < NumBackendStatSlots; i++)
2993  {
2994  BackendStatusArray[i].st_appname = buffer;
2995  buffer += NAMEDATALEN;
2996  }
2997  }
2998 
2999  /* Create or attach to the shared client hostname buffer */
3001  BackendClientHostnameBuffer = (char *)
3002  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
3003 
3004  if (!found)
3005  {
3007 
3008  /* Initialize st_clienthostname pointers. */
3009  buffer = BackendClientHostnameBuffer;
3010  for (i = 0; i < NumBackendStatSlots; i++)
3011  {
3013  buffer += NAMEDATALEN;
3014  }
3015  }
3016 
3017  /* Create or attach to the shared activity buffer */
3020  BackendActivityBuffer = (char *)
3021  ShmemInitStruct("Backend Activity Buffer",
3023  &found);
3024 
3025  if (!found)
3026  {
3028 
3029  /* Initialize st_activity pointers. */
3030  buffer = BackendActivityBuffer;
3031  for (i = 0; i < NumBackendStatSlots; i++)
3032  {
3035  }
3036  }
3037 
3038 #ifdef USE_SSL
3039  /* Create or attach to the shared SSL status buffer */
3041  BackendSslStatusBuffer = (PgBackendSSLStatus *)
3042  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
3043 
3044  if (!found)
3045  {
3046  PgBackendSSLStatus *ptr;
3047 
3048  MemSet(BackendSslStatusBuffer, 0, size);
3049 
3050  /* Initialize st_sslstatus pointers. */
3051  ptr = BackendSslStatusBuffer;
3052  for (i = 0; i < NumBackendStatSlots; i++)
3053  {
3055  ptr++;
3056  }
3057  }
3058 #endif
3059 
3060 #ifdef ENABLE_GSS
3061  /* Create or attach to the shared GSSAPI status buffer */
3063  BackendGssStatusBuffer = (PgBackendGSSStatus *)
3064  ShmemInitStruct("Backend GSS Status Buffer", size, &found);
3065 
3066  if (!found)
3067  {
3068  PgBackendGSSStatus *ptr;
3069 
3070  MemSet(BackendGssStatusBuffer, 0, size);
3071 
3072  /* Initialize st_gssstatus pointers. */
3073  ptr = BackendGssStatusBuffer;
3074  for (i = 0; i < NumBackendStatSlots; i++)
3075  {
3077  ptr++;
3078  }
3079  }
3080 #endif
3081 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2910
static char * BackendActivityBuffer
Definition: pgstat.c:2914
static Size BackendActivityBufferSize
Definition: pgstat.c:2915
#define MemSet(start, val, len)
Definition: c.h:996
#define NumBackendStatSlots
Definition: pgstat.c:119
char * st_clienthostname
Definition: pgstat.h:1218
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2912
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
char * st_activity_raw
Definition: pgstat.h:1241
int pgstat_track_activity_query_size
Definition: pgstat.c:129
char * st_appname
Definition: pgstat.h:1232
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
size_t Size
Definition: c.h:528
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1222
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1226
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2913

◆ find_funcstat_entry()

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

Definition at line 1906 of file pgstat.c.

References HASH_FIND, and hash_search().

Referenced by pg_stat_get_xact_function_calls(), pg_stat_get_xact_function_self_time(), and pg_stat_get_xact_function_total_time().

1907 {
1908  if (pgStatFunctions == NULL)
1909  return NULL;
1910 
1912  (void *) &func_id,
1913  HASH_FIND, NULL);
1914 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static HTAB * pgStatFunctions
Definition: pgstat.c:233

◆ find_tabstat_entry()

PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

Definition at line 2106 of file pgstat.c.

References HASH_FIND, hash_search(), and TabStatHashEntry::tsa_entry.

Referenced by pg_stat_get_xact_blocks_fetched(), pg_stat_get_xact_blocks_hit(), pg_stat_get_xact_numscans(), pg_stat_get_xact_tuples_deleted(), pg_stat_get_xact_tuples_fetched(), pg_stat_get_xact_tuples_hot_updated(), pg_stat_get_xact_tuples_inserted(), pg_stat_get_xact_tuples_returned(), and pg_stat_get_xact_tuples_updated().

2107 {
2108  TabStatHashEntry *hash_entry;
2109 
2110  /* If hashtable doesn't exist, there are no entries at all */
2111  if (!pgStatTabHash)
2112  return NULL;
2113 
2114  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
2115  if (!hash_entry)
2116  return NULL;
2117 
2118  /* Note that this step could also return NULL, but that's correct */
2119  return hash_entry->tsa_entry;
2120 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static HTAB * pgStatTabHash
Definition: pgstat.c:227
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:221

◆ get_dbstat_filename()

static void get_dbstat_filename ( bool  permanent,
bool  tempname,
Oid  databaseid,
char *  filename,
int  len 
)
static

Definition at line 5350 of file pgstat.c.

References elog, ERROR, pgstat_stat_directory, PGSTAT_STAT_PERMANENT_DIRECTORY, and snprintf.

Referenced by pgstat_read_db_statsfile(), pgstat_recv_dropdb(), and pgstat_write_db_statsfile().

5352 {
5353  int printed;
5354 
5355  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
5356  printed = snprintf(filename, len, "%s/db_%u.%s",
5357  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
5359  databaseid,
5360  tempname ? "tmp" : "stat");
5361  if (printed >= len)
5362  elog(ERROR, "overlength pgstat path");
5363 }
#define PGSTAT_STAT_PERMANENT_DIRECTORY
Definition: pgstat.h:29
#define ERROR
Definition: elog.h:45
char * pgstat_stat_directory
Definition: pgstat.c:135
static char * filename
Definition: pg_dumpall.c:91
#define elog(elevel,...)
Definition: elog.h:228
#define snprintf
Definition: port.h:215

◆ get_tabstat_entry()

static PgStat_TableStatus * get_tabstat_entry ( Oid  rel_id,
bool  isshared 
)
static

Definition at line 2018 of file pgstat.c.

References HASHCTL::entrysize, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::keysize, MemoryContextAllocZero(), pgStatTabList, PgStat_TableStatus::t_id, PgStat_TableStatus::t_shared, TABSTAT_QUANTUM, TopMemoryContext, TabStatusArray::tsa_entries, TabStatHashEntry::tsa_entry, TabStatusArray::tsa_next, and TabStatusArray::tsa_used.

Referenced by pgstat_initstats(), pgstat_twophase_postabort(), and pgstat_twophase_postcommit().

2019 {
2020  TabStatHashEntry *hash_entry;
2021  PgStat_TableStatus *entry;
2022  TabStatusArray *tsa;
2023  bool found;
2024 
2025  /*
2026  * Create hash table if we don't have it already.
2027  */
2028  if (pgStatTabHash == NULL)
2029  {
2030  HASHCTL ctl;
2031 
2032  ctl.keysize = sizeof(Oid);
2033  ctl.entrysize = sizeof(TabStatHashEntry);
2034 
2035  pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
2037  &ctl,
2038  HASH_ELEM | HASH_BLOBS);
2039  }
2040 
2041  /*
2042  * Find an entry or create a new one.
2043  */
2044  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
2045  if (!found)
2046  {
2047  /* initialize new entry with null pointer */
2048  hash_entry->tsa_entry = NULL;
2049  }
2050 
2051  /*
2052  * If entry is already valid, we're done.
2053  */
2054  if (hash_entry->tsa_entry)
2055  return hash_entry->tsa_entry;
2056 
2057  /*
2058  * Locate the first pgStatTabList entry with free space, making a new list
2059  * entry if needed. Note that we could get an OOM failure here, but if so
2060  * we have left the hashtable and the list in a consistent state.
2061  */
2062  if (pgStatTabList == NULL)
2063  {
2064  /* Set up first pgStatTabList entry */
2067  sizeof(TabStatusArray));
2068  }
2069 
2070  tsa = pgStatTabList;
2071  while (tsa->tsa_used >= TABSTAT_QUANTUM)
2072  {
2073  if (tsa->tsa_next == NULL)
2074  tsa->tsa_next = (TabStatusArray *)
2076  sizeof(TabStatusArray));
2077  tsa = tsa->tsa_next;
2078  }
2079 
2080  /*
2081  * Allocate a PgStat_TableStatus entry within this list entry. We assume
2082  * the entry was already zeroed, either at creation or after last use.
2083  */
2084  entry = &tsa->tsa_entries[tsa->tsa_used++];
2085  entry->t_id = rel_id;
2086  entry->t_shared = isshared;
2087 
2088  /*
2089  * Now we can fill the entry in pgStatTabHash.
2090  */
2091  hash_entry->tsa_entry = entry;
2092 
2093  return entry;
2094 }
int tsa_used
Definition: pgstat.c:209
#define HASH_ELEM
Definition: hsearch.h:95
Size entrysize
Definition: hsearch.h:76
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
struct TabStatusArray * tsa_next
Definition: pgstat.c:208
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:227
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:210
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define HASH_BLOBS
Definition: hsearch.h:97
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:221
Size keysize
Definition: hsearch.h:75
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:840
static TabStatusArray * pgStatTabList
Definition: pgstat.c:213
#define TABSTAT_QUANTUM
Definition: pgstat.c:204

◆ get_tabstat_stack_level()

static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

Definition at line 2126 of file pgstat.c.

References PgStat_SubXactStatus::first, MemoryContextAlloc(), PgStat_SubXactStatus::nest_level, pgStatXactStack, PgStat_SubXactStatus::prev, and TopTransactionContext.

Referenced by add_tabstat_xact_level(), and AtEOSubXact_PgStat().

2127 {
2128  PgStat_SubXactStatus *xact_state;
2129 
2130  xact_state = pgStatXactStack;
2131  if (xact_state == NULL || xact_state->nest_level != nest_level)
2132  {
2133  xact_state = (PgStat_SubXactStatus *)
2135  sizeof(PgStat_SubXactStatus));
2136  xact_state->nest_level = nest_level;
2137  xact_state->prev = pgStatXactStack;
2138  xact_state->first = NULL;
2139  pgStatXactStack = xact_state;
2140  }
2141  return xact_state;
2142 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:251
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:255
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
PgStat_TableXactStatus * first
Definition: pgstat.c:252

◆ pgstat_beshutdown_hook()

static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

Definition at line 3317 of file pgstat.c.

References MyBEEntry, MyDatabaseId, OidIsValid, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_report_stat(), and PgBackendStatus::st_procpid.

Referenced by pgstat_initialize().

3318 {
3319  volatile PgBackendStatus *beentry = MyBEEntry;
3320 
3321  /*
3322  * If we got as far as discovering our own database ID, we can report what
3323  * we did to the collector. Otherwise, we'd be sending an invalid
3324  * database ID, so forget it. (This means that accesses to pg_database
3325  * during failed backend starts might never get counted.)
3326  */
3327  if (OidIsValid(MyDatabaseId))
3328  pgstat_report_stat(true);
3329 
3330  /*
3331  * Clear my status entry, following the protocol of bumping st_changecount
3332  * before and after. We use a volatile pointer here to ensure the
3333  * compiler doesn't try to get cute.
3334  */
3335  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3336 
3337  beentry->st_procpid = 0; /* mark invalid */
3338 
3339  PGSTAT_END_WRITE_ACTIVITY(beentry);
3340 }
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:870
#define OidIsValid(objectId)
Definition: c.h:698
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
Oid MyDatabaseId
Definition: globals.c:86
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286

◆ pgstat_bestart()

void pgstat_bestart ( void  )

Definition at line 3145 of file pgstat.c.

References application_name, Assert, B_BACKEND, B_BG_WORKER, B_WAL_SENDER, be_gssapi_get_auth(), be_gssapi_get_enc(), be_gssapi_get_princ(), be_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_compression(), be_tls_get_peer_issuer_name(), be_tls_get_peer_serial(), be_tls_get_peer_subject_name(), be_tls_get_version(), GetSessionUserId(), Port::gss, PgBackendGSSStatus::gss_auth, PgBackendGSSStatus::gss_enc, PgBackendGSSStatus::gss_princ, InvalidOid, MemSet, MyBackendType, MyBEEntry, MyDatabaseId, MyProcPid, MyProcPort, MyStartTimestamp, NAMEDATALEN, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_report_appname(), pgstat_track_activity_query_size, PROGRESS_COMMAND_INVALID, Port::raddr, Port::remote_hostname, PgBackendSSLStatus::ssl_bits, PgBackendSSLStatus::ssl_cipher, PgBackendSSLStatus::ssl_client_dn, PgBackendSSLStatus::ssl_client_serial, PgBackendSSLStatus::ssl_compression, Port::ssl_in_use, PgBackendSSLStatus::ssl_issuer_dn, PgBackendSSLStatus::ssl_version, PgBackendStatus::st_activity_raw, PgBackendStatus::st_activity_start_timestamp, PgBackendStatus::st_appname, PgBackendStatus::st_backendType, PgBackendStatus::st_changecount, PgBackendStatus::st_clientaddr, PgBackendStatus::st_clienthostname, PgBackendStatus::st_databaseid, PgBackendStatus::st_gss, PgBackendStatus::st_gssstatus, PgBackendStatus::st_proc_start_timestamp, PgBackendStatus::st_procpid, PgBackendStatus::st_progress_command, PgBackendStatus::st_progress_command_target, PgBackendStatus::st_ssl, PgBackendStatus::st_sslstatus, PgBackendStatus::st_state, PgBackendStatus::st_state_start_timestamp, PgBackendStatus::st_userid, PgBackendStatus::st_xact_start_timestamp, STATE_UNDEFINED, strlcpy(), and unvolatize.

Referenced by AuxiliaryProcessMain(), and InitPostgres().

3146 {
3147  volatile PgBackendStatus *vbeentry = MyBEEntry;
3148  PgBackendStatus lbeentry;
3149 #ifdef USE_SSL
3150  PgBackendSSLStatus lsslstatus;
3151 #endif
3152 #ifdef ENABLE_GSS
3153  PgBackendGSSStatus lgssstatus;
3154 #endif
3155 
3156  /* pgstats state must be initialized from pgstat_initialize() */
3157  Assert(vbeentry != NULL);
3158 
3159  /*
3160  * To minimize the time spent modifying the PgBackendStatus entry, and
3161  * avoid risk of errors inside the critical section, we first copy the
3162  * shared-memory struct to a local variable, then modify the data in the
3163  * local variable, then copy the local variable back to shared memory.
3164  * Only the last step has to be inside the critical section.
3165  *
3166  * Most of the data we copy from shared memory is just going to be
3167  * overwritten, but the struct's not so large that it's worth the
3168  * maintenance hassle to copy only the needful fields.
3169  */
3170  memcpy(&lbeentry,
3171  unvolatize(PgBackendStatus *, vbeentry),
3172  sizeof(PgBackendStatus));
3173 
3174  /* These structs can just start from zeroes each time, though */
3175 #ifdef USE_SSL
3176  memset(&lsslstatus, 0, sizeof(lsslstatus));
3177 #endif
3178 #ifdef ENABLE_GSS
3179  memset(&lgssstatus, 0, sizeof(lgssstatus));
3180 #endif
3181 
3182  /*
3183  * Now fill in all the fields of lbeentry, except for strings that are
3184  * out-of-line data. Those have to be handled separately, below.
3185  */
3186  lbeentry.st_procpid = MyProcPid;
3187  lbeentry.st_backendType = MyBackendType;
3189  lbeentry.st_activity_start_timestamp = 0;
3190  lbeentry.st_state_start_timestamp = 0;
3191  lbeentry.st_xact_start_timestamp = 0;
3192  lbeentry.st_databaseid = MyDatabaseId;
3193 
3194  /* We have userid for client-backends, wal-sender and bgworker processes */
3195  if (lbeentry.st_backendType == B_BACKEND
3196  || lbeentry.st_backendType == B_WAL_SENDER
3197  || lbeentry.st_backendType == B_BG_WORKER)
3198  lbeentry.st_userid = GetSessionUserId();
3199  else
3200  lbeentry.st_userid = InvalidOid;
3201 
3202  /*
3203  * We may not have a MyProcPort (eg, if this is the autovacuum process).
3204  * If so, use all-zeroes client address, which is dealt with specially in
3205  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
3206  */
3207  if (MyProcPort)
3208  memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
3209  sizeof(lbeentry.st_clientaddr));
3210  else
3211  MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
3212 
3213 #ifdef USE_SSL
3215  {
3216  lbeentry.st_ssl = true;
3224  }
3225  else
3226  {
3227  lbeentry.st_ssl = false;
3228  }
3229 #else
3230  lbeentry.st_ssl = false;
3231 #endif
3232 
3233 #ifdef ENABLE_GSS
3234  if (MyProcPort && MyProcPort->gss != NULL)
3235  {
3236  const char *princ = be_gssapi_get_princ(MyProcPort);
3237 
3238  lbeentry.st_gss = true;
3239  lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
3240  lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
3241  if (princ)
3242  strlcpy(lgssstatus.gss_princ, princ, NAMEDATALEN);
3243  }
3244  else
3245  {
3246  lbeentry.st_gss = false;
3247  }
3248 #else
3249  lbeentry.st_gss = false;
3250 #endif
3251 
3252  lbeentry.st_state = STATE_UNDEFINED;
3255 
3256  /*
3257  * we don't zero st_progress_param here to save cycles; nobody should
3258  * examine it until st_progress_command has been set to something other
3259  * than PROGRESS_COMMAND_INVALID
3260  */
3261 
3262  /*
3263  * We're ready to enter the critical section that fills the shared-memory
3264  * status entry. We follow the protocol of bumping st_changecount before
3265  * and after; and make sure it's even afterwards. We use a volatile
3266  * pointer here to ensure the compiler doesn't try to get cute.
3267  */
3268  PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
3269 
3270  /* make sure we'll memcpy the same st_changecount back */
3271  lbeentry.st_changecount = vbeentry->st_changecount;
3272 
3273  memcpy(unvolatize(PgBackendStatus *, vbeentry),
3274  &lbeentry,
3275  sizeof(PgBackendStatus));
3276 
3277  /*
3278  * We can write the out-of-line strings and structs using the pointers
3279  * that are in lbeentry; this saves some de-volatilizing messiness.
3280  */
3281  lbeentry.st_appname[0] = '\0';
3284  NAMEDATALEN);
3285  else
3286  lbeentry.st_clienthostname[0] = '\0';
3287  lbeentry.st_activity_raw[0] = '\0';
3288  /* Also make sure the last byte in each string area is always 0 */
3289  lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
3290  lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
3292 
3293 #ifdef USE_SSL
3294  memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
3295 #endif
3296 #ifdef ENABLE_GSS
3297  memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
3298 #endif
3299 
3300  PGSTAT_END_WRITE_ACTIVITY(vbeentry);
3301 
3302  /* Update app name to current GUC setting */
3303  if (application_name)
3305 }
char ssl_issuer_dn[NAMEDATALEN]
Definition: pgstat.h:1149
char gss_princ[NAMEDATALEN]
Definition: pgstat.h:1163
bool ssl_compression
Definition: pgstat.h:1138
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:1140
Oid st_progress_command_target
Definition: pgstat.h:1253
int MyProcPid
Definition: globals.c:41
struct Port * MyProcPort
Definition: globals.c:44
const char * be_gssapi_get_princ(Port *port)
BackendType MyBackendType
Definition: miscinit.c:62
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:1211
char ssl_client_dn[NAMEDATALEN]
Definition: pgstat.h:1141
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:1139
SockAddr st_clientaddr
Definition: pgstat.h:1217
#define MemSet(start, val, len)
Definition: c.h:996
bool ssl_in_use
Definition: libpq-be.h:191
ProgressCommandType st_progress_command
Definition: pgstat.h:1252
char ssl_client_serial[NAMEDATALEN]
Definition: pgstat.h:1147
BackendState st_state
Definition: pgstat.h:1229
char * st_clienthostname
Definition: pgstat.h:1218
Oid GetSessionUserId(void)
Definition: miscinit.c:510
Oid st_databaseid
Definition: pgstat.h:1215
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:128
SockAddr raddr
Definition: libpq-be.h:126
bool be_tls_get_compression(Port *port)
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
char * st_activity_raw
Definition: pgstat.h:1241
int pgstat_track_activity_query_size
Definition: pgstat.c:129
TimestampTz st_state_start_timestamp
Definition: pgstat.h:1212
char * st_appname
Definition: pgstat.h:1232
bool be_gssapi_get_enc(Port *port)
TimestampTz MyStartTimestamp
Definition: globals.c:43
int be_tls_get_cipher_bits(Port *port)
Oid MyDatabaseId
Definition: globals.c:86
BackendType st_backendType
Definition: pgstat.h:1206
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3552
#define InvalidOid
Definition: postgres_ext.h:36
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:792
const char * be_tls_get_version(Port *port)
void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
char * application_name
Definition: guc.c:565
void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
void * gss
Definition: libpq-be.h:185
#define unvolatize(underlying_type, expr)
Definition: c.h:1233
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:1210
int st_changecount
Definition: pgstat.h:1200
const char * be_tls_get_cipher(Port *port)
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:1209
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1222
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1226
bool be_gssapi_get_auth(Port *port)

◆ pgstat_clear_snapshot()

void pgstat_clear_snapshot ( void  )

Definition at line 6270 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

Referenced by AtEOXact_PgStat(), autovac_refresh_stats(), AutoVacLauncherMain(), pg_stat_clear_snapshot(), and PostPrepare_PgStat().

6271 {
6272  /* Release memory, if any was allocated */
6273  if (pgStatLocalContext)
6275 
6276  /* Reset variables */
6277  pgStatLocalContext = NULL;
6278  pgStatDBHash = NULL;
6279  localBackendStatusTable = NULL;
6280  localNumBackends = 0;
6281 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:286
static HTAB * pgStatDBHash
Definition: pgstat.c:283
static int localNumBackends
Definition: pgstat.c:289
static MemoryContext pgStatLocalContext
Definition: pgstat.c:282

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

Definition at line 7220 of file pgstat.c.

References cliplen(), pg_mbcliplen(), pgstat_track_activity_query_size, and pnstrdup().

Referenced by pg_stat_get_activity(), pg_stat_get_backend_activity(), and pgstat_get_backend_current_activity().

7221 {
7222  char *activity;
7223  int rawlen;
7224  int cliplen;
7225 
7226  /*
7227  * Some callers, like pgstat_get_backend_current_activity(), do not
7228  * guarantee that the buffer isn't concurrently modified. We try to take
7229  * care that the buffer is always terminated by a NUL byte regardless, but
7230  * let's still be paranoid about the string's length. In those cases the
7231  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
7232  * large.
7233  */
7234  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
7235 
7236  /* now double-guaranteed to be NUL terminated */
7237  rawlen = strlen(activity);
7238 
7239  /*
7240  * All supported server-encodings make it possible to determine the length
7241  * of a multi-byte character from its first byte (this is not the case for
7242  * client encodings, see GB18030). As st_activity is always stored using
7243  * server encoding, this allows us to perform multi-byte aware truncation,
7244  * even if the string earlier was truncated in the middle of a multi-byte
7245  * character.
7246  */
7247  cliplen = pg_mbcliplen(activity, rawlen,
7249 
7250  activity[cliplen] = '\0';
7251 
7252  return activity;
7253 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1198
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
int pgstat_track_activity_query_size
Definition: pgstat.c:129
static int cliplen(const char *str, int len, int limit)
Definition: mbutils.c:1034

◆ pgstat_collect_oids()

static HTAB * pgstat_collect_oids ( Oid  catalogid,
AttrNumber  anum_oid 
)
static

Definition at line 1273 of file pgstat.c.

References AccessShareLock, Assert, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, HASHCTL::entrysize, ForwardScanDirection, GetLatestSnapshot(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, heap_getattr, heap_getnext(), HASHCTL::keysize, PGSTAT_TAB_HASH_SIZE, RegisterSnapshot(), RelationGetDescr, table_beginscan(), table_close(), table_endscan(), table_open(), and UnregisterSnapshot().

Referenced by pgstat_vacuum_stat().

1274 {
1275  HTAB *htab;
1276  HASHCTL hash_ctl;
1277  Relation rel;
1278  TableScanDesc scan;
1279  HeapTuple tup;
1280  Snapshot snapshot;
1281 
1282  hash_ctl.keysize = sizeof(Oid);
1283  hash_ctl.entrysize = sizeof(Oid);
1284  hash_ctl.hcxt = CurrentMemoryContext;
1285  htab = hash_create("Temporary table of OIDs",
1287  &hash_ctl,
1289 
1290  rel = table_open(catalogid, AccessShareLock);
1291  snapshot = RegisterSnapshot(GetLatestSnapshot());
1292  scan = table_beginscan(rel, snapshot, 0, NULL);
1293  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1294  {
1295  Oid thisoid;
1296  bool isnull;
1297 
1298  thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1299  Assert(!isnull);
1300 
1302 
1303  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1304  }
1305  table_endscan(scan);
1306  UnregisterSnapshot(snapshot);
1308 
1309  return htab;
1310 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
MemoryContext hcxt
Definition: hsearch.h:86
#define RelationGetDescr(relation)
Definition: rel.h:483
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:106
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:76
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:219
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:854
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
#define HASH_BLOBS
Definition: hsearch.h:97
Size keysize
Definition: hsearch.h:75
#define Assert(condition)
Definition: c.h:792
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ pgstat_count_heap_delete()

void pgstat_count_heap_delete ( Relation  rel)

Definition at line 2221 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, RelationData::pgstat_info, PgStat_TableStatus::trans, and PgStat_TableXactStatus::tuples_deleted.

Referenced by heap_abort_speculative(), and heap_delete().

2222 {
2223  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2224 
2225  if (pgstat_info != NULL)
2226  {
2227  /* We have to log the effect at the proper transactional level */
2228  int nest_level = GetCurrentTransactionNestLevel();
2229 
2230  if (pgstat_info->trans == NULL ||
2231  pgstat_info->trans->nest_level != nest_level)
2232  add_tabstat_xact_level(pgstat_info, nest_level);
2233 
2234  pgstat_info->trans->tuples_deleted++;
2235  }
2236 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:187
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2148
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175

◆ pgstat_count_heap_insert()

void pgstat_count_heap_insert ( Relation  rel,
PgStat_Counter  n 
)

Definition at line 2175 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, RelationData::pgstat_info, PgStat_TableStatus::trans, and PgStat_TableXactStatus::tuples_inserted.

Referenced by ExecRefreshMatView(), heap_insert(), and heap_multi_insert().

2176 {
2177  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2178 
2179  if (pgstat_info != NULL)
2180  {
2181  /* We have to log the effect at the proper transactional level */
2182  int nest_level = GetCurrentTransactionNestLevel();
2183 
2184  if (pgstat_info->trans == NULL ||
2185  pgstat_info->trans->nest_level != nest_level)
2186  add_tabstat_xact_level(pgstat_info, nest_level);
2187 
2188  pgstat_info->trans->tuples_inserted += n;
2189  }
2190 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:185
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2148
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175

◆ pgstat_count_heap_update()

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

Definition at line 2196 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, RelationData::pgstat_info, PgStat_TableStatus::t_counts, PgStat_TableCounts::t_tuples_hot_updated, PgStat_TableStatus::trans, and PgStat_TableXactStatus::tuples_updated.

Referenced by heap_update().

2197 {
2198  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2199 
2200  if (pgstat_info != NULL)
2201  {
2202  /* We have to log the effect at the proper transactional level */
2203  int nest_level = GetCurrentTransactionNestLevel();
2204 
2205  if (pgstat_info->trans == NULL ||
2206  pgstat_info->trans->nest_level != nest_level)
2207  add_tabstat_xact_level(pgstat_info, nest_level);
2208 
2209  pgstat_info->trans->tuples_updated++;
2210 
2211  /* t_tuples_hot_updated is nontransactional, so just advance it */
2212  if (hot)
2213  pgstat_info->t_counts.t_tuples_hot_updated++;
2214  }
2215 }
PgStat_Counter tuples_updated
Definition: pgstat.h:186
PgStat_Counter t_tuples_hot_updated
Definition: pgstat.h:124
PgStat_TableCounts t_counts
Definition: pgstat.h:176
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2148
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175

◆ pgstat_count_slru_flush()

void pgstat_count_slru_flush ( int  slru_idx)

Definition at line 7402 of file pgstat.c.

References PgStat_MsgSLRU::m_flush, and slru_entry().

Referenced by SimpleLruWriteAll().

7403 {
7404  slru_entry(slru_idx)->m_flush += 1;
7405 }
PgStat_Counter m_flush
Definition: pgstat.h:492
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354

◆ pgstat_count_slru_page_exists()

void pgstat_count_slru_page_exists ( int  slru_idx)

Definition at line 7384 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_exists, and slru_entry().

Referenced by SimpleLruDoesPhysicalPageExist().

7385 {
7386  slru_entry(slru_idx)->m_blocks_exists += 1;
7387 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_blocks_exists
Definition: pgstat.h:491

◆ pgstat_count_slru_page_hit()

void pgstat_count_slru_page_hit ( int  slru_idx)

Definition at line 7378 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_hit, and slru_entry().

Referenced by SimpleLruReadPage(), and SimpleLruReadPage_ReadOnly().

7379 {
7380  slru_entry(slru_idx)->m_blocks_hit += 1;
7381 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_blocks_hit
Definition: pgstat.h:488

◆ pgstat_count_slru_page_read()

void pgstat_count_slru_page_read ( int  slru_idx)

Definition at line 7390 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_read, and slru_entry().

Referenced by SimpleLruReadPage().

7391 {
7392  slru_entry(slru_idx)->m_blocks_read += 1;
7393 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_blocks_read
Definition: pgstat.h:489

◆ pgstat_count_slru_page_written()

void pgstat_count_slru_page_written ( int  slru_idx)

Definition at line 7396 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_written, and slru_entry().

Referenced by SlruPhysicalWritePage().

7397 {
7398  slru_entry(slru_idx)->m_blocks_written += 1;
7399 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_blocks_written
Definition: pgstat.h:490

◆ pgstat_count_slru_page_zeroed()

void pgstat_count_slru_page_zeroed ( int  slru_idx)

Definition at line 7372 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_zeroed, and slru_entry().

Referenced by SimpleLruZeroPage().

7373 {
7374  slru_entry(slru_idx)->m_blocks_zeroed += 1;
7375 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_blocks_zeroed
Definition: pgstat.h:487

◆ pgstat_count_slru_truncate()

void pgstat_count_slru_truncate ( int  slru_idx)

Definition at line 7408 of file pgstat.c.

References PgStat_MsgSLRU::m_truncate, and slru_entry().

Referenced by SimpleLruTruncate().

7409 {
7410  slru_entry(slru_idx)->m_truncate += 1;
7411 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7354
PgStat_Counter m_truncate
Definition: pgstat.h:493

◆ pgstat_count_truncate()

void pgstat_count_truncate ( Relation  rel)

Definition at line 2276 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, RelationData::pgstat_info, pgstat_truncate_save_counters(), PgStat_TableStatus::trans, PgStat_TableXactStatus::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, and PgStat_TableXactStatus::tuples_updated.

Referenced by ExecRefreshMatView(), and ExecuteTruncateGuts().

2277 {
2278  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2279 
2280  if (pgstat_info != NULL)
2281  {
2282  /* We have to log the effect at the proper transactional level */
2283  int nest_level = GetCurrentTransactionNestLevel();
2284 
2285  if (pgstat_info->trans == NULL ||
2286  pgstat_info->trans->nest_level != nest_level)
2287  add_tabstat_xact_level(pgstat_info, nest_level);
2288 
2289  pgstat_truncate_save_counters(pgstat_info->trans);
2290  pgstat_info->trans->tuples_inserted = 0;
2291  pgstat_info->trans->tuples_updated = 0;
2292  pgstat_info->trans->tuples_deleted = 0;
2293  }
2294 }
PgStat_Counter tuples_updated
Definition: pgstat.h:186
PgStat_Counter tuples_inserted
Definition: pgstat.h:185
PgStat_Counter tuples_deleted
Definition: pgstat.h:187
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2148
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:175
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2247

◆ pgstat_db_requested()

static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 7193 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

7194 {
7195  /*
7196  * If any requests are outstanding at all, we should write the stats for
7197  * shared catalogs (the "database" with OID 0). This ensures that
7198  * backends will see up-to-date stats for shared catalogs, even though
7199  * they send inquiry messages mentioning only their own DB.
7200  */
7201  if (databaseid == InvalidOid && pending_write_requests != NIL)
7202  return true;
7203 
7204  /* Search to see if there's an open request to write this database. */
7205  if (list_member_oid(pending_write_requests, databaseid))
7206  return true;
7207 
7208  return false;
7209 }
#define NIL
Definition: pg_list.h:65
static List * pending_write_requests
Definition: pgstat.c:308
#define InvalidOid
Definition: postgres_ext.h:36
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674

◆ pgstat_drop_database()

void pgstat_drop_database ( Oid  databaseid)

Definition at line 1322 of file pgstat.c.

References PgStat_MsgTabpurge::m_databaseid, PgStat_MsgDropdb::m_databaseid, PgStat_MsgTabpurge::m_hdr, PgStat_MsgDropdb::m_hdr, PgStat_MsgTabpurge::m_nentries, PgStat_MsgTabpurge::m_tableid, MyDatabaseId, offsetof, PGINVALID_SOCKET, PGSTAT_MTYPE_DROPDB, PGSTAT_MTYPE_TABPURGE, pgstat_send(), pgstat_setheader(), and pgStatSock.

Referenced by dropdb(), and pgstat_vacuum_stat().

1323 {
1324  PgStat_MsgDropdb msg;
1325 
1327  return;
1328 
1330  msg.m_databaseid = databaseid;
1331  pgstat_send(&msg, sizeof(msg));
1332 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4593
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:185
Oid m_databaseid
Definition: pgstat.h:324
PgStat_MsgHdr m_hdr
Definition: pgstat.h:323
#define PGINVALID_SOCKET
Definition: port.h:33
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4580

◆ pgstat_end_function_usage()

void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1926 of file pgstat.c.

References PgStat_FunctionCounts::f_numcalls, PgStat_FunctionCounts::f_self_time, PgStat_FunctionCallUsage::f_start, PgStat_FunctionCounts::f_total_time, PgStat_FunctionCallUsage::fs, have_function_stats, INSTR_TIME_ADD, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, PgStat_FunctionCallUsage::save_f_total_time, PgStat_FunctionCallUsage::save_total, and total_func_time.

Referenced by call_pltcl_start_proc(), EventTriggerInvoke(), ExecCallTriggerFunc(), ExecEvalFuncExprFusage(), ExecEvalFuncExprStrictFusage(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), ExecuteCallStmt(), and fmgr_security_definer().

1927 {
1928  PgStat_FunctionCounts *fs = fcu->fs;
1929  instr_time f_total;
1930  instr_time f_others;
1931  instr_time f_self;
1932 
1933  /* stats not wanted? */
1934  if (fs == NULL)
1935  return;
1936 
1937  /* total elapsed time in this function call */
1938  INSTR_TIME_SET_CURRENT(f_total);
1939  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1940 
1941  /* self usage: elapsed minus anything already charged to other calls */
1942  f_others = total_func_time;
1943  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1944  f_self = f_total;
1945  INSTR_TIME_SUBTRACT(f_self, f_others);
1946 
1947  /* update backend-wide total time */
1949 
1950  /*
1951  * Compute the new f_total_time as the total elapsed time added to the
1952  * pre-call value of f_total_time. This is necessary to avoid
1953  * double-counting any time taken by recursive calls of myself. (We do
1954  * not need any similar kluge for self time, since that already excludes
1955  * any recursive calls.)
1956  */
1957  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1958 
1959  /* update counters in function stats table */
1960  if (finalize)
1961  fs->f_numcalls++;
1962  fs->f_total_time = f_total;
1963  INSTR_TIME_ADD(fs->f_self_time, f_self);
1964 
1965  /* indicate that we have something to send */
1966  have_function_stats = true;
1967 }
instr_time f_self_time
Definition: pgstat.h:553
instr_time save_total
Definition: pgstat.h:1357
struct timeval instr_time
Definition: instr_time.h:150
instr_time f_total_time
Definition: pgstat.h:552
PgStat_FunctionCounts * fs
Definition: pgstat.h:1353
PgStat_Counter f_numcalls
Definition: pgstat.h:551
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
#define INSTR_TIME_ADD(x, y)
Definition: instr_time.h:158
static instr_time total_func_time
Definition: pgstat.c:315
static bool have_function_stats
Definition: pgstat.c:239
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1355

◆ pgstat_fetch_global()

◆ pgstat_fetch_replslot()

PgStat_ReplSlotStats* pgstat_fetch_replslot ( int *  nslots_p)

Definition at line 2897 of file pgstat.c.

References backend_read_statsfile(), nReplSlotStats, and replSlotStats.

Referenced by pg_stat_get_replication_slots().

2898 {
2900 
2901  *nslots_p = nReplSlotStats;
2902  return replSlotStats;
2903 }
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
static int nReplSlotStats
Definition: pgstat.c:301
static PgStat_ReplSlotStats * replSlotStats
Definition: pgstat.c:300

◆ pgstat_fetch_slru()

PgStat_SLRUStats* pgstat_fetch_slru ( void  )

Definition at line 2880 of file pgstat.c.

References backend_read_statsfile(), and slruStats.

Referenced by pg_stat_get_slru().

2881 {
2883 
2884  return slruStats;
2885 }
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
static PgStat_SLRUStats slruStats[SLRU_NUM_ELEMENTS]
Definition: pgstat.c:299

◆ pgstat_fetch_stat_archiver()

PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2831 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2832 {
2834 
2835  return &archiverStats;
2836 }
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:296

◆ pgstat_fetch_stat_beentry()

◆ pgstat_fetch_stat_dbentry()

PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

Definition at line 2659 of file pgstat.c.

References backend_read_statsfile(), HASH_FIND, and hash_search().

Referenced by do_autovacuum(), do_start_worker(), pg_stat_get_db_active_time(), pg_stat_get_db_blk_read_time(), pg_stat_get_db_blk_write_time(), pg_stat_get_db_blocks_fetched(), pg_stat_get_db_blocks_hit(), pg_stat_get_db_checksum_failures(), pg_stat_get_db_checksum_last_failure(), pg_stat_get_db_conflict_all(), pg_stat_get_db_conflict_bufferpin(), pg_stat_get_db_conflict_lock(), pg_stat_get_db_conflict_snapshot(), pg_stat_get_db_conflict_startup_deadlock(), pg_stat_get_db_conflict_tablespace(), pg_stat_get_db_deadlocks(), pg_stat_get_db_idle_in_transaction_time(), pg_stat_get_db_session_time(), pg_stat_get_db_sessions(), pg_stat_get_db_sessions_abandoned(), pg_stat_get_db_sessions_fatal(), pg_stat_get_db_sessions_killed(), pg_stat_get_db_stat_reset_time(), pg_stat_get_db_temp_bytes(), pg_stat_get_db_temp_files(), pg_stat_get_db_tuples_deleted(), pg_stat_get_db_tuples_fetched(), pg_stat_get_db_tuples_inserted(), pg_stat_get_db_tuples_returned(), pg_stat_get_db_tuples_updated(), pg_stat_get_db_xact_commit(), pg_stat_get_db_xact_rollback(), pgstat_fetch_stat_funcentry(), rebuild_database_list(), and recheck_relation_needs_vacanalyze().

2660 {
2661  /*
2662  * If not done for this transaction, read the statistics collector stats
2663  * file into some hash tables.
2664  */
2666 
2667  /*
2668  * Lookup the requested database; return NULL if not found
2669  */
2671  (void *) &dbid,
2672  HASH_FIND, NULL);
2673 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
static HTAB * pgStatDBHash
Definition: pgstat.c:283

◆ pgstat_fetch_stat_funcentry()

PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

Definition at line 2742 of file pgstat.c.

References backend_read_statsfile(), PgStat_StatDBEntry::functions, HASH_FIND, hash_search(), MyDatabaseId, and pgstat_fetch_stat_dbentry().

Referenced by pg_stat_get_function_calls(), pg_stat_get_function_self_time(), and pg_stat_get_function_total_time().

2743 {
2744  PgStat_StatDBEntry *dbentry;
2745  PgStat_StatFuncEntry *funcentry = NULL;
2746 
2747  /* load the stats file if needed */
2749 
2750  /* Lookup our database, then find the requested function. */
2752  if (dbentry != NULL && dbentry->functions != NULL)
2753  {
2754  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2755  (void *) &func_id,
2756  HASH_FIND, NULL);
2757  }
2758 
2759  return funcentry;
2760 }
HTAB * functions
Definition: pgstat.h:742
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2659
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
Oid MyDatabaseId
Definition: globals.c:86

◆ pgstat_fetch_stat_local_beentry()

LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2796 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2797 {
2799 
2800  if (beid < 1 || beid > localNumBackends)
2801  return NULL;
2802 
2803  return &localBackendStatusTable[beid - 1];
2804 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3608
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:286
static int localNumBackends
Definition: pgstat.c:289

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

Definition at line 2815 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), pg_stat_get_backend_idset(), pg_stat_get_db_numbackends(), and pg_stat_get_progress_info().

2816 {
2818 
2819  return localNumBackends;
2820 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3608
static int localNumBackends
Definition: pgstat.c:289

◆ pgstat_fetch_stat_tabentry()

PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

Definition at line 2686 of file pgstat.c.

References backend_read_statsfile(), HASH_FIND, hash_search(), InvalidOid, MyDatabaseId, and PgStat_StatDBEntry::tables.

Referenced by index_concurrently_swap(), pg_stat_get_analyze_count(), pg_stat_get_autoanalyze_count(), pg_stat_get_autovacuum_count(), pg_stat_get_blocks_fetched(), pg_stat_get_blocks_hit(), pg_stat_get_dead_tuples(), pg_stat_get_ins_since_vacuum(), pg_stat_get_last_analyze_time(), pg_stat_get_last_autoanalyze_time(), pg_stat_get_last_autovacuum_time(), pg_stat_get_last_vacuum_time(), pg_stat_get_live_tuples(), pg_stat_get_mod_since_analyze(), pg_stat_get_numscans(), pg_stat_get_tuples_deleted(), pg_stat_get_tuples_fetched(), pg_stat_get_tuples_hot_updated(), pg_stat_get_tuples_inserted(), pg_stat_get_tuples_returned(), pg_stat_get_tuples_updated(), and pg_stat_get_vacuum_count().

2687 {
2688  Oid dbid;
2689  PgStat_StatDBEntry *dbentry;
2690  PgStat_StatTabEntry *tabentry;
2691 
2692  /*
2693  * If not done for this transaction, read the statistics collector stats
2694  * file into some hash tables.
2695  */
2697 
2698  /*
2699  * Lookup our database, then look in its table hash table.
2700  */
2701  dbid = MyDatabaseId;
2703  (void *) &dbid,
2704  HASH_FIND, NULL);
2705  if (dbentry != NULL && dbentry->tables != NULL)
2706  {
2707  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2708  (void *) &relid,
2709  HASH_FIND, NULL);
2710  if (tabentry)
2711  return tabentry;
2712  }
2713 
2714  /*
2715  * If we didn't find it, maybe it's a shared table.
2716  */
2717  dbid = InvalidOid;
2719  (void *) &dbid,
2720  HASH_FIND, NULL);
2721  if (dbentry != NULL && dbentry->tables != NULL)
2722  {
2723  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2724  (void *) &relid,
2725  HASH_FIND, NULL);
2726  if (tabentry)
2727  return tabentry;
2728  }
2729 
2730  return NULL;
2731 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:6115
Oid MyDatabaseId
Definition: globals.c:86
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pgStatDBHash
Definition: pgstat.c:283

◆ pgstat_fetch_stat_wal()

PgStat_WalStats* pgstat_fetch_stat_wal ( void  )

Definition at line 2864 of file pgstat.c.

References backend_read_statsfile(), and walStats.

Referenced by pg_stat_get_wal().

2865 {
2867 
2868  return &walStats;
2869 }
static PgStat_WalStats walStats
Definition: pgstat.c:298
static void backend_read_statsfile(void)
Definition: pgstat.c:6115

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 4431 of file pgstat.c.

References BackendStatusArray, CHECK_FOR_INTERRUPTS, GetUserId(), i, MaxBackends, pgstat_begin_read_activity, pgstat_clip_activity(), pgstat_end_read_activity, pgstat_read_activity_complete, PgBackendStatus::st_activity_raw, PgBackendStatus::st_procpid, PgBackendStatus::st_userid, and superuser().

Referenced by DeadLockReport().

4432 {
4433  PgBackendStatus *beentry;
4434  int i;
4435 
4436  beentry = BackendStatusArray;
4437  for (i = 1; i <= MaxBackends; i++)
4438  {
4439  /*
4440  * Although we expect the target backend's entry to be stable, that
4441  * doesn't imply that anyone else's is. To avoid identifying the
4442  * wrong backend, while we check for a match to the desired PID we
4443  * must follow the protocol of retrying if st_changecount changes
4444  * while we examine the entry, or if it's odd. (This might be
4445  * unnecessary, since fetching or storing an int is almost certainly
4446  * atomic, but let's play it safe.) We use a volatile pointer here to
4447  * ensure the compiler doesn't try to get cute.
4448  */
4449  volatile PgBackendStatus *vbeentry = beentry;
4450  bool found;
4451 
4452  for (;;)
4453  {
4454  int before_changecount;
4455  int after_changecount;
4456 
4457  pgstat_begin_read_activity(vbeentry, before_changecount);
4458 
4459  found = (vbeentry->st_procpid == pid);
4460 
4461  pgstat_end_read_activity(vbeentry, after_changecount);
4462 
4463  if (pgstat_read_activity_complete(before_changecount,
4464  after_changecount))
4465  break;
4466 
4467  /* Make sure we can break out of loop if stuck... */
4469  }
4470 
4471  if (found)
4472  {
4473  /* Now it is safe to use the non-volatile pointer */
4474  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4475  return "<insufficient privilege>";
4476  else if (*(beentry->st_activity_raw) == '\0')
4477  return "<command string not enabled>";
4478  else
4479  {
4480  /* this'll leak a bit of memory, but that seems acceptable */
4481  return pgstat_clip_activity(beentry->st_activity_raw);
4482  }
4483  }
4484 
4485  beentry++;
4486  }
4487 
4488  /* If we get here, caller is in error ... */
4489  return "<backend information not available>";
4490 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2910
Oid GetUserId(void)
Definition: miscinit.c:476
bool superuser(void)
Definition: superuser.c:46
int MaxBackends
Definition: globals.c:137
char * st_activity_raw
Definition: pgstat.h:1241
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1307
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1301
char * pgstat_clip_activity(const char *raw_activity)
Definition: pgstat.c:7220
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1313

◆ pgstat_get_crashed_backend_activity()

const char* pgstat_get_crashed_backend_activity ( int  pid,
char *  buffer,
int  buflen 
)

Definition at line 4509 of file pgstat.c.

References ascii_safe_strlcpy(), BackendActivityBuffer, BackendActivityBufferSize, BackendStatusArray, i, MaxBackends, Min, pgstat_track_activity_query_size, PgBackendStatus::st_activity_raw, and PgBackendStatus::st_procpid.

Referenced by LogChildExit().

4510 {
4511  volatile PgBackendStatus *beentry;
4512  int i;
4513 
4514  beentry = BackendStatusArray;
4515 
4516  /*
4517  * We probably shouldn't get here before shared memory has been set up,
4518  * but be safe.
4519  */
4520  if (beentry == NULL || BackendActivityBuffer == NULL)
4521  return NULL;
4522 
4523  for (i = 1; i <= MaxBackends; i++)
4524  {
4525  if (beentry->st_procpid == pid)
4526  {
4527  /* Read pointer just once, so it can't change after validation */
4528  const char *activity = beentry->st_activity_raw;
4529  const char *activity_last;
4530 
4531  /*
4532  * We mustn't access activity string before we verify that it
4533  * falls within the BackendActivityBuffer. To make sure that the
4534  * entire string including its ending is contained within the
4535  * buffer, subtract one activity length from the buffer size.
4536  */
4539 
4540  if (activity < BackendActivityBuffer ||
4541  activity > activity_last)
4542  return NULL;
4543 
4544  /* If no string available, no point in a report */
4545  if (activity[0] == '\0')
4546  return NULL;
4547 
4548  /*
4549  * Copy only ASCII-safe characters so we don't run into encoding
4550  * problems when reporting the message; and be sure not to run off
4551  * the end of memory. As only ASCII characters are reported, it
4552  * doesn't seem necessary to perform multibyte aware clipping.
4553  */
4554  ascii_safe_strlcpy(buffer, activity,
4555  Min(buflen, pgstat_track_activity_query_size));
4556 
4557  return buffer;
4558  }
4559 
4560  beentry++;
4561  }
4562 
4563  /* PID not found */
4564  return NULL;
4565 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2910
static char * BackendActivityBuffer
Definition: pgstat.c:2914
#define Min(x, y)
Definition: c.h:974
static Size BackendActivityBufferSize
Definition: pgstat.c:2915
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
int MaxBackends
Definition: globals.c:137
char * st_activity_raw
Definition: pgstat.h:1241
int pgstat_track_activity_query_size
Definition: pgstat.c:129
int i

◆ pgstat_get_db_entry()

static PgStat_StatDBEntry * pgstat_get_db_entry ( Oid  databaseid,
bool  create 
)
static

Definition at line 5112 of file pgstat.c.

References generate_unaccent_rules::action, HASH_ENTER, HASH_FIND, hash_search(), and reset_dbentry_counters().

Referenced by pgstat_recv_analyze(), pgstat_recv_autovac(), pgstat_recv_checksum_failure(), pgstat_recv_connstat(), pgstat_recv_deadlock(), pgstat_recv_dropdb(), pgstat_recv_funcpurge(), pgstat_recv_funcstat(), pgstat_recv_inquiry(), pgstat_recv_recoveryconflict(), pgstat_recv_resetcounter(), pgstat_recv_resetsinglecounter(), pgstat_recv_tabpurge(), pgstat_recv_tabstat(), pgstat_recv_tempfile(), and pgstat_recv_vacuum().

5113 {
5114  PgStat_StatDBEntry *result;
5115  bool found;
5116  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
5117 
5118  /* Lookup or create the hash table entry for this database */
5120  &databaseid,
5121  action, &found);
5122 
5123  if (!create && !found)
5124  return NULL;
5125 
5126  /*
5127  * If not found, initialize the new one. This creates empty hash tables
5128  * for tables and functions, too.
5129  */
5130  if (!found)
5131  reset_dbentry_counters(result);
5132 
5133  return result;
5134 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:5054
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static HTAB * pgStatDBHash
Definition: pgstat.c:283
HASHACTION
Definition: hsearch.h:111

◆ pgstat_get_tab_entry()

static PgStat_StatTabEntry * pgstat_get_tab_entry ( PgStat_StatDBEntry dbentry,
Oid  tableoid,
bool  create 
)
static

Definition at line 5143 of file pgstat.c.

References generate_unaccent_rules::action, PgStat_StatTabEntry::analyze_count, PgStat_StatTabEntry::analyze_timestamp, PgStat_StatTabEntry::autovac_analyze_count, PgStat_StatTabEntry::autovac_analyze_timestamp, PgStat_StatTabEntry::autovac_vacuum_count, PgStat_StatTabEntry::autovac_vacuum_timestamp, PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, PgStat_StatTabEntry::changes_since_analyze, HASH_ENTER, HASH_FIND, hash_search(), PgStat_StatTabEntry::inserts_since_vacuum, PgStat_StatTabEntry::n_dead_tuples, PgStat_StatTabEntry::n_live_tuples, PgStat_StatTabEntry::numscans, PgStat_StatDBEntry::tables, PgStat_StatTabEntry::tuples_deleted, PgStat_StatTabEntry::tuples_fetched, PgStat_StatTabEntry::tuples_hot_updated, PgStat_StatTabEntry::tuples_inserted, PgStat_StatTabEntry::tuples_returned, PgStat_StatTabEntry::tuples_updated, PgStat_StatTabEntry::vacuum_count, and PgStat_StatTabEntry::vacuum_timestamp.

Referenced by pgstat_recv_analyze(), and pgstat_recv_vacuum().

5144 {
5145  PgStat_StatTabEntry *result;
5146  bool found;
5147  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
5148 
5149  /* Lookup or create the hash table entry for this table */
5150  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
5151  &tableoid,
5152  action, &found);
5153 
5154  if (!create && !found)
5155  return NULL;
5156 
5157  /* If not found, initialize the new one. */
5158  if (!found)
5159  {
5160  result->numscans = 0;
5161  result->tuples_returned = 0;
5162  result->tuples_fetched = 0;
5163  result->tuples_inserted = 0;
5164  result->tuples_updated = 0;
5165  result->tuples_deleted = 0;
5166  result->tuples_hot_updated = 0;
5167  result->n_live_tuples = 0;
5168  result->n_dead_tuples = 0;
5169  result->changes_since_analyze = 0;
5170  result->inserts_since_vacuum = 0;
5171  result->blocks_fetched = 0;
5172  result->blocks_hit = 0;
5173  result->vacuum_timestamp = 0;
5174  result->vacuum_count = 0;
5175  result->autovac_vacuum_timestamp = 0;
5176  result->autovac_vacuum_count = 0;
5177  result->analyze_timestamp = 0;
5178  result->analyze_count = 0;
5179  result->autovac_analyze_timestamp = 0;
5180  result->autovac_analyze_count = 0;
5181  }
5182 
5183  return result;
5184 }
PgStat_Counter analyze_count
Definition: pgstat.h:777
PgStat_Counter tuples_returned
Definition: pgstat.h:756
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:778
PgStat_Counter vacuum_count
Definition: pgstat.h:773
PgStat_Counter numscans
Definition: pgstat.h:754
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:762
PgStat_Counter tuples_inserted
Definition: pgstat.h:759
PgStat_Counter n_live_tuples
Definition: pgstat.h:764
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:767
TimestampTz vacuum_timestamp
Definition: pgstat.h:772
PgStat_Counter n_dead_tuples
Definition: pgstat.h:765
PgStat_Counter tuples_fetched
Definition: pgstat.h:757
PgStat_Counter blocks_hit
Definition: pgstat.h:770
TimestampTz analyze_timestamp
Definition: pgstat.h:776
PgStat_Counter changes_since_analyze
Definition: pgstat.h:766
PgStat_Counter tuples_deleted
Definition: pgstat.h:761
PgStat_Counter tuples_updated
Definition: pgstat.h:760
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:774
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:779
PgStat_Counter blocks_fetched
Definition: pgstat.h:769
HASHACTION
Definition: hsearch.h:111
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:775

◆ pgstat_get_wait_activity()

static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

Definition at line 3892 of file pgstat.c.

References WAIT_EVENT_ARCHIVER_MAIN, WAIT_EVENT_AUTOVACUUM_MAIN, WAIT_EVENT_BGWRITER_HIBERNATE, WAIT_EVENT_BGWRITER_MAIN, WAIT_EVENT_CHECKPOINTER_MAIN, WAIT_EVENT_LOGICAL_APPLY_MAIN, WAIT_EVENT_LOGICAL_LAUNCHER_MAIN, WAIT_EVENT_PGSTAT_MAIN, WAIT_EVENT_RECOVERY_WAL_STREAM, WAIT_EVENT_SYSLOGGER_MAIN, WAIT_EVENT_WAL_RECEIVER_MAIN, WAIT_EVENT_WAL_SENDER_MAIN, and WAIT_EVENT_WAL_WRITER_MAIN.

Referenced by pgstat_get_wait_event().

3893 {
3894  const char *event_name = "unknown wait event";
3895 
3896  switch (w)
3897  {
3899  event_name = "ArchiverMain";
3900  break;
3902  event_name = "AutoVacuumMain";
3903  break;
3905  event_name = "BgWriterHibernate";
3906  break;
3908  event_name = "BgWriterMain";
3909  break;
3911  event_name = "CheckpointerMain";
3912  break;
3914  event_name = "LogicalApplyMain";
3915  break;
3917  event_name = "LogicalLauncherMain";
3918  break;
3920  event_name = "PgStatMain";
3921  break;
3923  event_name = "RecoveryWalStream";
3924  break;
3926  event_name = "SysLoggerMain";
3927  break;
3929  event_name = "WalReceiverMain";
3930  break;
3932  event_name = "WalSenderMain";
3933  break;
3935  event_name = "WalWriterMain";
3936  break;
3937  /* no default case, so that compiler will warn */
3938  }
3939 
3940  return event_name;
3941 }

◆ pgstat_get_wait_client()

static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3950 of file pgstat.c.

References WAIT_EVENT_CLIENT_READ, WAIT_EVENT_CLIENT_WRITE, WAIT_EVENT_GSS_OPEN_SERVER, WAIT_EVENT_LIBPQWALRECEIVER_CONNECT, WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE, WAIT_EVENT_SSL_OPEN_SERVER, WAIT_EVENT_WAL_RECEIVER_WAIT_START, WAIT_EVENT_WAL_SENDER_WAIT_WAL, and WAIT_EVENT_WAL_SENDER_WRITE_DATA.

Referenced by pgstat_get_wait_event().

3951 {
3952  const char *event_name = "unknown wait event";
3953 
3954  switch (w)
3955  {
3957  event_name = "ClientRead";
3958  break;
3960  event_name = "ClientWrite";
3961  break;
3963  event_name = "GSSOpenServer";
3964  break;
3966  event_name = "LibPQWalReceiverConnect";
3967  break;
3969  event_name = "LibPQWalReceiverReceive";
3970  break;
3972  event_name = "SSLOpenServer";
3973  break;
3975  event_name = "WalReceiverWaitStart";
3976  break;
3978  event_name = "WalSenderWaitForWAL";
3979  break;
3981  event_name = "WalSenderWriteData";
3982  break;
3983  /* no default case, so that compiler will warn */
3984  }
3985 
3986  return event_name;
3987 }

◆ pgstat_get_wait_event()

const char* pgstat_get_wait_event ( uint32  wait_event_info)

Definition at line 3815 of file pgstat.c.

References GetLockNameFromTagType(), GetLWLockIdentifier(), PG_WAIT_ACTIVITY, PG_WAIT_BUFFER_PIN, PG_WAIT_CLIENT, PG_WAIT_EXTENSION, PG_WAIT_IO, PG_WAIT_IPC, PG_WAIT_LOCK, PG_WAIT_LWLOCK, PG_WAIT_TIMEOUT, pgstat_get_wait_activity(), pgstat_get_wait_client(), pgstat_get_wait_io(), pgstat_get_wait_ipc(), and pgstat_get_wait_timeout().

Referenced by pg_stat_get_activity(), and pg_stat_get_backend_wait_event().

3816 {
3817  uint32 classId;
3818  uint16 eventId;
3819  const char *event_name;
3820 
3821  /* report process as not waiting. */
3822  if (wait_event_info == 0)
3823  return NULL;
3824 
3825  classId = wait_event_info & 0xFF000000;
3826  eventId = wait_event_info & 0x0000FFFF;
3827 
3828  switch (classId)
3829  {
3830  case PG_WAIT_LWLOCK:
3831  event_name = GetLWLockIdentifier(classId, eventId);
3832  break;
3833  case PG_WAIT_LOCK:
3834  event_name = GetLockNameFromTagType(eventId);
3835  break;
3836  case PG_WAIT_BUFFER_PIN:
3837  event_name = "BufferPin";
3838  break;
3839  case PG_WAIT_ACTIVITY:
3840  {
3841  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3842 
3843  event_name = pgstat_get_wait_activity(w);
3844  break;
3845  }
3846  case PG_WAIT_CLIENT:
3847  {
3848  WaitEventClient w = (WaitEventClient) wait_event_info;
3849 
3850  event_name = pgstat_get_wait_client(w);
3851  break;
3852  }
3853  case PG_WAIT_EXTENSION:
3854  event_name = "Extension";
3855  break;
3856  case PG_WAIT_IPC:
3857  {
3858  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3859 
3860  event_name = pgstat_get_wait_ipc(w);
3861  break;
3862  }
3863  case PG_WAIT_TIMEOUT:
3864  {
3865  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3866 
3867  event_name = pgstat_get_wait_timeout(w);
3868  break;
3869  }
3870  case PG_WAIT_IO:
3871  {
3872  WaitEventIO w = (WaitEventIO) wait_event_info;
3873 
3874  event_name = pgstat_get_wait_io(w);
3875  break;
3876  }
3877  default:
3878  event_name = "unknown wait event";
3879  break;
3880  }
3881 
3882  return event_name;
3883 }
#define PG_WAIT_LOCK
Definition: pgstat.h:896
WaitEventIPC
Definition: pgstat.h:958
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:4141
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3996
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:898
#define PG_WAIT_IO
Definition: pgstat.h:903
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3892
unsigned short uint16
Definition: c.h:428
#define PG_WAIT_CLIENT
Definition: pgstat.h:899
WaitEventClient
Definition: pgstat.h:938
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3950
unsigned int uint32
Definition: c.h:429
WaitEventTimeout
Definition: pgstat.h:1010
#define PG_WAIT_EXTENSION
Definition: pgstat.h:900
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:897
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1190
WaitEventIO
Definition: pgstat.h:1025
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:902
#define PG_WAIT_IPC
Definition: pgstat.h:901
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:807
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:4175
#define PG_WAIT_LWLOCK
Definition: pgstat.h:895
WaitEventActivity
Definition: pgstat.h:913

◆ pgstat_get_wait_event_type()

const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

Definition at line 3760 of file pgstat.c.

References PG_WAIT_ACTIVITY, PG_WAIT_BUFFER_PIN, PG_WAIT_CLIENT, PG_WAIT_EXTENSION, PG_WAIT_IO, PG_WAIT_IPC, PG_WAIT_LOCK, PG_WAIT_LWLOCK, and PG_WAIT_TIMEOUT.

Referenced by pg_stat_get_activity(), and pg_stat_get_backend_wait_event_type().

3761 {
3762  uint32 classId;
3763  const char *event_type;
3764 
3765  /* report process as not waiting. */
3766  if (wait_event_info == 0)
3767  return NULL;
3768 
3769  classId = wait_event_info & 0xFF000000;
3770 
3771  switch (classId)
3772  {
3773  case PG_WAIT_LWLOCK:
3774  event_type = "LWLock";
3775  break;
3776  case PG_WAIT_LOCK:
3777  event_type = "Lock";
3778  break;
3779  case PG_WAIT_BUFFER_PIN:
3780  event_type = "BufferPin";
3781  break;
3782  case PG_WAIT_ACTIVITY:
3783  event_type = "Activity";
3784  break;
3785  case PG_WAIT_CLIENT:
3786  event_type = "Client";
3787  break;
3788  case PG_WAIT_EXTENSION:
3789  event_type = "Extension";
3790  break;
3791  case PG_WAIT_IPC:
3792  event_type = "IPC";
3793  break;
3794  case PG_WAIT_TIMEOUT:
3795  event_type = "Timeout";
3796  break;
3797  case PG_WAIT_IO:
3798  event_type = "IO";
3799  break;
3800  default:
3801  event_type = "???";
3802  break;
3803  }
3804 
3805  return event_type;
3806 }
#define PG_WAIT_LOCK
Definition: pgstat.h:896
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:898
#define PG_WAIT_IO
Definition: pgstat.h:903
#define PG_WAIT_CLIENT
Definition: pgstat.h:899
unsigned int uint32
Definition: c.h:429
#define PG_WAIT_EXTENSION
Definition: pgstat.h:900
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:897
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:902
#define PG_WAIT_IPC
Definition: pgstat.h:901
#define PG_WAIT_LWLOCK
Definition: pgstat.h:895

◆ pgstat_get_wait_io()

static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

Definition at line 4175 of file pgstat.c.

References WAIT_EVENT_BASEBACKUP_READ, WAIT_EVENT_BUFFILE_READ, WAIT_EVENT_BUFFILE_TRUNCATE, WAIT_EVENT_BUFFILE_WRITE, WAIT_EVENT_CONTROL_FILE_READ, WAIT_EVENT_CONTROL_FILE_SYNC, WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE, WAIT_EVENT_CONTROL_FILE_WRITE, WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE, WAIT_EVENT_COPY_FILE_READ, WAIT_EVENT_COPY_FILE_WRITE, WAIT_EVENT_DATA_FILE_EXTEND, WAIT_EVENT_DATA_FILE_FLUSH, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC, WAIT_EVENT_DATA_FILE_PREFETCH, WAIT_EVENT_DATA_FILE_READ, WAIT_EVENT_DATA_FILE_SYNC, WAIT_EVENT_DATA_FILE_TRUNCATE, WAIT_EVENT_DATA_FILE_WRITE, WAIT_EVENT_DSM_FILL_ZERO_WRITE, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE, WAIT_EVENT_LOCK_FILE_CREATE_READ, WAIT_EVENT_LOCK_FILE_CREATE_SYNC, WAIT_EVENT_LOCK_FILE_CREATE_WRITE, WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ, WAIT_EVENT_LOGICAL_CHANGES_READ, WAIT_EVENT_LOGICAL_CHANGES_WRITE, WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC, WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC, WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE, WAIT_EVENT_LOGICAL_REWRITE_SYNC, WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE, WAIT_EVENT_LOGICAL_REWRITE_WRITE, WAIT_EVENT_LOGICAL_SUBXACT_READ, WAIT_EVENT_LOGICAL_SUBXACT_WRITE, WAIT_EVENT_RELATION_MAP_READ, WAIT_EVENT_RELATION_MAP_SYNC, WAIT_EVENT_RELATION_MAP_WRITE, WAIT_EVENT_REORDER_BUFFER_READ, WAIT_EVENT_REORDER_BUFFER_WRITE, WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ, WAIT_EVENT_REPLICATION_SLOT_READ, WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC, WAIT_EVENT_REPLICATION_SLOT_SYNC, WAIT_EVENT_REPLICATION_SLOT_WRITE, WAIT_EVENT_SLRU_FLUSH_SYNC, WAIT_EVENT_SLRU_READ, WAIT_EVENT_SLRU_SYNC, WAIT_EVENT_SLRU_WRITE, WAIT_EVENT_SNAPBUILD_READ, WAIT_EVENT_SNAPBUILD_SYNC, WAIT_EVENT_SNAPBUILD_WRITE, WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC, WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE, WAIT_EVENT_TIMELINE_HISTORY_READ, WAIT_EVENT_TIMELINE_HISTORY_SYNC, WAIT_EVENT_TIMELINE_HISTORY_WRITE, WAIT_EVENT_TWOPHASE_FILE_READ, WAIT_EVENT_TWOPHASE_FILE_SYNC, WAIT_EVENT_TWOPHASE_FILE_WRITE, WAIT_EVENT_WAL_BOOTSTRAP_SYNC, WAIT_EVENT_WAL_BOOTSTRAP_WRITE, WAIT_EVENT_WAL_COPY_READ, WAIT_EVENT_WAL_COPY_SYNC, WAIT_EVENT_WAL_COPY_WRITE, WAIT_EVENT_WAL_INIT_SYNC, WAIT_EVENT_WAL_INIT_WRITE, WAIT_EVENT_WAL_READ, WAIT_EVENT_WAL_SYNC, WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN, WAIT_EVENT_WAL_WRITE, and WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ.

Referenced by pgstat_get_wait_event().

4176 {
4177  const char *event_name = "unknown wait event";
4178 
4179  switch (w)
4180  {
4182  event_name = "BaseBackupRead";
4183  break;
4185  event_name = "BufFileRead";
4186  break;
4188  event_name = "BufFileWrite";
4189  break;
4191  event_name = "BufFileTruncate";
4192  break;
4194  event_name = "ControlFileRead";
4195  break;
4197  event_name = "ControlFileSync";
4198  break;
4200  event_name = "ControlFileSyncUpdate";
4201  break;
4203  event_name = "ControlFileWrite";
4204  break;
4206  event_name = "ControlFileWriteUpdate";
4207  break;
4209  event_name = "CopyFileRead";
4210  break;
4212  event_name = "CopyFileWrite";
4213  break;
4215  event_name = "DataFileExtend";
4216  break;
4218  event_name = "DataFileFlush";
4219  break;
4221  event_name = "DataFileImmediateSync";
4222  break;
4224  event_name = "DataFilePrefetch";
4225  break;
4227  event_name = "DataFileRead";
4228  break;
4230  event_name = "DataFileSync";
4231  break;
4233  event_name = "DataFileTruncate";
4234  break;
4236  event_name = "DataFileWrite";
4237  break;
4239  event_name = "DSMFillZeroWrite";
4240  break;
4242  event_name = "LockFileAddToDataDirRead";
4243  break;
4245  event_name = "LockFileAddToDataDirSync";
4246  break;
4248  event_name = "LockFileAddToDataDirWrite";
4249  break;
4251  event_name = "LockFileCreateRead";
4252  break;
4254  event_name = "LockFileCreateSync";
4255  break;
4257  event_name = "LockFileCreateWrite";
4258  break;
4260  event_name = "LockFileReCheckDataDirRead";
4261  break;
4263  event_name = "LogicalRewriteCheckpointSync";
4264  break;
4266  event_name = "LogicalRewriteMappingSync";
4267  break;
4269  event_name = "LogicalRewriteMappingWrite";
4270  break;
4272  event_name = "LogicalRewriteSync";
4273  break;
4275  event_name = "LogicalRewriteTruncate";
4276  break;
4278  event_name = "LogicalRewriteWrite";
4279  break;
4281  event_name = "RelationMapRead";
4282  break;
4284  event_name = "RelationMapSync";
4285  break;
4287  event_name = "RelationMapWrite";
4288  break;
4290  event_name = "ReorderBufferRead";
4291  break;
4293  event_name = "ReorderBufferWrite";
4294  break;
4296  event_name = "ReorderLogicalMappingRead";
4297  break;
4299  event_name = "ReplicationSlotRead";
4300  break;
4302  event_name = "ReplicationSlotRestoreSync";
4303  break;
4305  event_name = "ReplicationSlotSync";
4306  break;
4308  event_name = "ReplicationSlotWrite";
4309  break;
4311  event_name = "SLRUFlushSync";
4312  break;
4313  case WAIT_EVENT_SLRU_READ:
4314  event_name = "SLRURead";
4315  break;
4316  case WAIT_EVENT_SLRU_SYNC:
4317  event_name = "SLRUSync";
4318  break;
4319  case WAIT_EVENT_SLRU_WRITE:
4320  event_name = "SLRUWrite";
4321  break;
4323  event_name = "SnapbuildRead";
4324  break;
4326  event_name = "SnapbuildSync";
4327  break;
4329  event_name = "SnapbuildWrite";
4330  break;
4332  event_name = "TimelineHistoryFileSync";
4333  break;
4335  event_name = "TimelineHistoryFileWrite";
4336  break;
4338  event_name = "TimelineHistoryRead";
4339  break;
4341  event_name = "TimelineHistorySync";
4342  break;
4344  event_name = "TimelineHistoryWrite";
4345  break;
4347  event_name = "TwophaseFileRead";
4348  break;
4350  event_name = "TwophaseFileSync";
4351  break;
4353  event_name = "TwophaseFileWrite";
4354  break;
4356  event_name = "WALSenderTimelineHistoryRead";
4357  break;
4359  event_name = "WALBootstrapSync";
4360  break;
4362  event_name = "WALBootstrapWrite";
4363  break;
4365  event_name = "WALCopyRead";
4366  break;
4368  event_name = "WALCopySync";
4369  break;
4371  event_name = "WALCopyWrite";
4372  break;
4374  event_name = "WALInitSync";
4375  break;
4377  event_name = "WALInitWrite";
4378  break;
4379  case WAIT_EVENT_WAL_READ:
4380  event_name = "WALRead";
4381  break;
4382  case WAIT_EVENT_WAL_SYNC:
4383  event_name = "WALSync";
4384  break;
4386  event_name = "WALSyncMethodAssign";
4387  break;
4388  case WAIT_EVENT_WAL_WRITE:
4389  event_name = "WALWrite";
4390  break;
4392  event_name = "LogicalChangesRead";
4393  break;
4395  event_name = "LogicalChangesWrite";
4396  break;
4398  event_name = "LogicalSubxactRead";
4399  break;
4401  event_name = "LogicalSubxactWrite";
4402  break;
4403 
4404  /* no default case, so that compiler will warn */
4405  }
4406 
4407  return event_name;
4408 }

◆ pgstat_get_wait_ipc()

static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3996 of file pgstat.c.

References WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE, WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WAIT_EVENT_BTREE_PAGE, WAIT_EVENT_CHECKPOINT_DONE, WAIT_EVENT_CHECKPOINT_START, WAIT_EVENT_EXECUTE_GATHER, WAIT_EVENT_HASH_BATCH_ALLOCATE, WAIT_EVENT_HASH_BATCH_ELECT, WAIT_EVENT_HASH_BATCH_LOAD, WAIT_EVENT_HASH_BUILD_ALLOCATE, WAIT_EVENT_HASH_BUILD_ELECT, WAIT_EVENT_HASH_BUILD_HASH_INNER, WAIT_EVENT_HASH_BUILD_HASH_OUTER, WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATE, WAIT_EVENT_HASH_GROW_BATCHES_DECIDE, WAIT_EVENT_HASH_GROW_BATCHES_ELECT, WAIT_EVENT_HASH_GROW_BATCHES_FINISH, WAIT_EVENT_HASH_GROW_BATCHES_REPARTITION, WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATE, WAIT_EVENT_HASH_GROW_BUCKETS_ELECT, WAIT_EVENT_HASH_GROW_BUCKETS_REINSERT, WAIT_EVENT_LOGICAL_SYNC_DATA, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE, WAIT_EVENT_MQ_INTERNAL, WAIT_EVENT_MQ_PUT_MESSAGE, WAIT_EVENT_MQ_RECEIVE, WAIT_EVENT_MQ_SEND, WAIT_EVENT_PARALLEL_BITMAP_SCAN, WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN, WAIT_EVENT_PARALLEL_FINISH, WAIT_EVENT_PROC_SIGNAL_BARRIER, WAIT_EVENT_PROCARRAY_GROUP_UPDATE, WAIT_EVENT_PROMOTE, WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, WAIT_EVENT_RECOVERY_CONFLICT_TABLESPACE, WAIT_EVENT_RECOVERY_PAUSE, WAIT_EVENT_REPLICATION_ORIGIN_DROP, WAIT_EVENT_REPLICATION_SLOT_DROP, WAIT_EVENT_SAFE_SNAPSHOT, WAIT_EVENT_SYNC_REP, and WAIT_EVENT_XACT_GROUP_UPDATE.

Referenced by pgstat_get_wait_event().

3997 {
3998  const char *event_name = "unknown wait event";
3999 
4000  switch (w)
4001  {
4003  event_name = "BackupWaitWalArchive";
4004  break;
4006  event_name = "BgWorkerShutdown";
4007  break;
4009  event_name = "BgWorkerStartup";
4010  break;
4011  case WAIT_EVENT_BTREE_PAGE:
4012  event_name = "BtreePage";
4013  break;
4015  event_name = "CheckpointDone";
4016  break;
4018  event_name = "CheckpointStart";
4019  break;
4021  event_name = "ExecuteGather";
4022  break;
4024  event_name = "HashBatchAllocate";
4025  break;
4027  event_name = "HashBatchElect";
4028  break;
4030  event_name = "HashBatchLoad";
4031  break;
4033  event_name = "HashBuildAllocate";
4034  break;
4036  event_name = "HashBuildElect";
4037  break;
4039  event_name = "HashBuildHashInner";
4040  break;
4042  event_name = "HashBuildHashOuter";
4043  break;
4045  event_name = "HashGrowBatchesAllocate";
4046  break;
4048  event_name = "HashGrowBatchesDecide";
4049  break;
4051  event_name = "HashGrowBatchesElect";
4052  break;
4054  event_name = "HashGrowBatchesFinish";
4055  break;
4057  event_name = "HashGrowBatchesRepartition";
4058  break;
4060  event_name = "HashGrowBucketsAllocate";
4061  break;
4063  event_name = "HashGrowBucketsElect";
4064  break;
4066  event_name = "HashGrowBucketsReinsert";
4067  break;
4069  event_name = "LogicalSyncData";
4070  break;
4072  event_name = "LogicalSyncStateChange";
4073  break;
4075  event_name = "MessageQueueInternal";
4076  break;
4078  event_name = "MessageQueuePutMessage";
4079  break;
4080  case WAIT_EVENT_MQ_RECEIVE:
4081  event_name = "MessageQueueReceive";
4082  break;
4083  case WAIT_EVENT_MQ_SEND:
4084  event_name = "MessageQueueSend";
4085  break;
4087  event_name = "ParallelBitmapScan";
4088  break;
4090  event_name = "ParallelCreateIndexScan";
4091  break;
4093  event_name = "ParallelFinish";
4094  break;
4096  event_name = "ProcArrayGroupUpdate";
4097  break;
4099  event_name = "ProcSignalBarrier";
4100  break;
4101  case WAIT_EVENT_PROMOTE:
4102  event_name = "Promote";
4103  break;
4105  event_name = "RecoveryConflictSnapshot";
4106  break;
4108  event_name = "RecoveryConflictTablespace";
4109  break;
4111  event_name = "RecoveryPause";
4112  break;
4114  event_name = "ReplicationOriginDrop";
4115  break;
4117  event_name = "ReplicationSlotDrop";
4118  break;
4120  event_name = "SafeSnapshot";
4121  break;
4122  case WAIT_EVENT_SYNC_REP:
4123  event_name = "SyncRep";
4124  break;
4126  event_name = "XactGroupUpdate";
4127  break;
4128  /* no default case, so that compiler will warn */
4129  }
4130 
4131  return event_name;
4132 }

◆ pgstat_get_wait_timeout()

static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

Definition at line 4141 of file pgstat.c.

References WAIT_EVENT_BASE_BACKUP_THROTTLE, WAIT_EVENT_PG_SLEEP, WAIT_EVENT_RECOVERY_APPLY_DELAY, WAIT_EVENT_RECOVERY_RETRIEVE_RETRY_INTERVAL, and WAIT_EVENT_VACUUM_DELAY.

Referenced by pgstat_get_wait_event().

4142 {
4143  const char *event_name = "unknown wait event";
4144 
4145  switch (w)
4146  {
4148  event_name = "BaseBackupThrottle";
4149  break;
4150  case WAIT_EVENT_PG_SLEEP:
4151  event_name = "PgSleep";
4152  break;
4154  event_name = "RecoveryApplyDelay";
4155  break;
4157  event_name = "RecoveryRetrieveRetryInterval";
4158  break;
4160  event_name = "VacuumDelay";
4161  break;
4162  /* no default case, so that compiler will warn */
4163  }
4164 
4165  return event_name;
4166 }

◆ pgstat_init()

void pgstat_init ( void  )

Definition at line 404 of file pgstat.c.

References addrinfo::ai_next, AI_PASSIVE, bind, closesocket, connect, EINTR, ereport, errcode(), errcode_for_socket_access(), errmsg(), gai_strerror, LOG, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_set_noblock(), PGC_INTERNAL, PGC_S_OVERRIDE, PGINVALID_SOCKET, PGSTAT_MAX_MSG_SIZE, PGSTAT_MIN_RCVBUF, pgStatAddr, pgStatSock, recv, ReserveExternalFD(), select, send, SetConfigOption(), socket, StaticAssertStmt, and TESTBYTEVAL.

Referenced by PostmasterMain().

405 {
406  ACCEPT_TYPE_ARG3 alen;
407  struct addrinfo *addrs = NULL,
408  *addr,
409  hints;
410  int ret;
411  fd_set rset;
412  struct timeval tv;
413  char test_byte;
414  int sel_res;
415  int tries = 0;
416 
417 #define TESTBYTEVAL ((char) 199)
418 
419  /*
420  * This static assertion verifies that we didn't mess up the calculations
421  * involved in selecting maximum payload sizes for our UDP messages.
422  * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
423  * be silent performance loss from fragmentation, it seems worth having a
424  * compile-time cross-check that we didn't.
425  */
427  "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
428 
429  /*
430  * Create the UDP socket for sending and receiving statistic messages
431  */
432  hints.ai_flags = AI_PASSIVE;
433  hints.ai_family = AF_UNSPEC;
434  hints.ai_socktype = SOCK_DGRAM;
435  hints.ai_protocol = 0;
436  hints.ai_addrlen = 0;
437  hints.ai_addr = NULL;
438  hints.ai_canonname = NULL;
439  hints.ai_next = NULL;
440  ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
441  if (ret || !addrs)
442  {
443  ereport(LOG,
444  (errmsg("could not resolve \"localhost\": %s",
445  gai_strerror(ret))));
446  goto startup_failed;
447  }
448 
449  /*
450  * On some platforms, pg_getaddrinfo_all() may return multiple addresses
451  * only one of which will actually work (eg, both IPv6 and IPv4 addresses
452  * when kernel will reject IPv6). Worse, the failure may occur at the
453  * bind() or perhaps even connect() stage. So we must loop through the
454  * results till we find a working combination. We will generate LOG
455  * messages, but no error, for bogus combinations.
456  */
457  for (addr = addrs; addr; addr = addr->ai_next)
458  {
459 #ifdef HAVE_UNIX_SOCKETS
460  /* Ignore AF_UNIX sockets, if any are returned. */
461  if (addr->ai_family == AF_UNIX)
462  continue;
463 #endif
464 
465  if (++tries > 1)
466  ereport(LOG,
467  (errmsg("trying another address for the statistics collector")));
468 
469  /*
470  * Create the socket.
471  */
472  if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
473  {
474  ereport(LOG,
476  errmsg("could not create socket for statistics collector: %m")));
477  continue;
478  }
479 
480  /*
481  * Bind it to a kernel assigned port on localhost and get the assigned
482  * port via getsockname().
483  */
484  if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
485  {
486  ereport(LOG,
488  errmsg("could not bind socket for statistics collector: %m")));
491  continue;
492  }
493 
494  alen = sizeof(pgStatAddr);
495  if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
496  {
497  ereport(LOG,
499  errmsg("could not get address of socket for statistics collector: %m")));
502  continue;
503  }
504 
505  /*
506  * Connect the socket to its own address. This saves a few cycles by
507  * not having to respecify the target address on every send. This also
508  * provides a kernel-level check that only packets from this same
509  * address will be received.
510  */
511  if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
512  {
513  ereport(LOG,
515  errmsg("could not connect socket for statistics collector: %m")));
518  continue;
519  }
520 
521  /*
522  * Try to send and receive a one-byte test message on the socket. This
523  * is to catch situations where the socket can be created but will not
524  * actually pass data (for instance, because kernel packet filtering
525  * rules prevent it).
526  */
527  test_byte = TESTBYTEVAL;
528 
529 retry1:
530  if (send(pgStatSock, &test_byte, 1, 0) != 1)
531  {
532  if (errno == EINTR)
533  goto retry1; /* if interrupted, just retry */
534  ereport(LOG,
536  errmsg("could not send test message on socket for statistics collector: %m")));
539  continue;
540  }
541 
542  /*
543  * There could possibly be a little delay before the message can be
544  * received. We arbitrarily allow up to half a second before deciding
545  * it's broken.
546  */
547  for (;;) /* need a loop to handle EINTR */
548  {
549  FD_ZERO(&rset);
550  FD_SET(pgStatSock, &rset);
551 
552  tv.tv_sec = 0;
553  tv.tv_usec = 500000;
554  sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
555  if (sel_res >= 0 || errno != EINTR)
556  break;
557  }
558  if (sel_res < 0)
559  {
560  ereport(LOG,
562  errmsg("select() failed in statistics collector: %m")));
565  continue;
566  }
567  if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
568  {
569  /*
570  * This is the case we actually think is likely, so take pains to
571  * give a specific message for it.
572  *
573  * errno will not be set meaningfully here, so don't use it.
574  */
575  ereport(LOG,
576  (errcode(ERRCODE_CONNECTION_FAILURE),
577  errmsg("test message did not get through on socket for statistics collector")));
580  continue;
581  }
582 
583  test_byte++; /* just make sure variable is changed */
584 
585 retry2:
586  if (recv(pgStatSock, &test_byte, 1, 0) != 1)
587  {
588  if (errno == EINTR)
589  goto retry2; /* if interrupted, just retry */
590  ereport(LOG,
592  errmsg("could not receive test message on socket for statistics collector: %m")));
595  continue;
596  }
597 
598  if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
599  {
600  ereport(LOG,
601  (errcode(ERRCODE_INTERNAL_ERROR),
602  errmsg("incorrect test message transmission on socket for statistics collector")));
605  continue;
606  }
607 
608  /* If we get here, we have a working socket */
609  break;
610  }
611 
612  /* Did we find a working address? */
613  if (!addr || pgStatSock == PGINVALID_SOCKET)
614  goto startup_failed;
615 
616  /*
617  * Set the socket to non-blocking IO. This ensures that if the collector
618  * falls behind, statistics messages will be discarded; backends won't
619  * block waiting to send messages to the collector.
620  */
622  {
623  ereport(LOG,
625  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
626  goto startup_failed;
627  }
628 
629  /*
630  * Try to ensure that the socket's receive buffer is at least
631  * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
632  * data. Use of UDP protocol means that we are willing to lose data under
633  * heavy load, but we don't want it to happen just because of ridiculously
634  * small default buffer sizes (such as 8KB on older Windows versions).
635  */
636  {
637  int old_rcvbuf;
638  int new_rcvbuf;
639  ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
640 
641  if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
642  (char *) &old_rcvbuf, &rcvbufsize) < 0)
643  {
644  ereport(LOG,
645  (errmsg("getsockopt(%s) failed: %m", "SO_RCVBUF")));
646  /* if we can't get existing size, always try to set it */
647  old_rcvbuf = 0;
648  }
649 
650  new_rcvbuf = PGSTAT_MIN_RCVBUF;
651  if (old_rcvbuf < new_rcvbuf)
652  {
653  if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
654  (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
655  ereport(LOG,
656  (errmsg("setsockopt(%s) failed: %m", "SO_RCVBUF")));
657  }
658  }
659 
660  pg_freeaddrinfo_all(hints.ai_family, addrs);
661 
662  /* Now that we have a long-lived socket, tell fd.c about it. */
664 
665  return;
666 
667 startup_failed:
668  ereport(LOG,
669  (errmsg("disabling statistics collector for lack of working socket")));
670 
671  if (addrs)
672  pg_freeaddrinfo_all(hints.ai_family, addrs);
673 
677 
678  /*
679  * Adjust GUC variables to suppress useless activity, and for debugging
680  * purposes (seeing track_counts off is a clue that we failed here). We
681  * use PGC_S_OVERRIDE because there is no point in trying to turn it back
682  * on from postgresql.conf without a restart.
683  */
684  SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
685 }
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:185
#define closesocket
Definition: port.h:331
int errcode(int sqlerrcode)
Definition: elog.c:704
#define connect(s, name, namelen)
Definition: win32_port.h:463
#define LOG
Definition: elog.h:26
#define bind(s, addr, addrlen)
Definition: win32_port.h:460
#define recv(s, buf, len, flags)
Definition: win32_port.h:465
#define gai_strerror
Definition: getaddrinfo.h:146
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:906
#define PGSTAT_MIN_RCVBUF
Definition: pgstat.c:98
#define TESTBYTEVAL
void ReserveExternalFD(void)
Definition: fd.c:1111
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7879
#define AI_PASSIVE
Definition: getaddrinfo.h:62
#define select(n, r, w, e, timeout)
Definition: win32_port.h:464
int errcode_for_socket_access(void)
Definition: elog.c:798
#define socket(af, type, protocol)
Definition: win32_port.h:459
#define PGSTAT_MAX_MSG_SIZE
Definition: pgstat.h:224
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:155
static struct sockaddr_storage pgStatAddr
Definition: pgstat.c:187
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
struct addrinfo * ai_next
Definition: getaddrinfo.h:107
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define EINTR
Definition: win32_port.h:343
#define send(s, buf, len, flags)
Definition: win32_port.h:466

◆ pgstat_init_function_usage()

void pgstat_init_function_usage ( FunctionCallInfo  fcinfo,
PgStat_FunctionCallUsage fcu 
)

Definition at line 1855 of file pgstat.c.

References HASHCTL::entrysize, PgStat_BackendFunctionEntry::f_counts, PgStat_FunctionCallUsage::f_start, PgStat_FunctionCounts::f_total_time, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_oid, PgStat_FunctionCallUsage::fs, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), INSTR_TIME_SET_CURRENT, HASHCTL::keysize, MemSet, PGSTAT_FUNCTION_HASH_SIZE, PgStat_FunctionCallUsage::save_f_total_time, PgStat_FunctionCallUsage::save_total, and total_func_time.

Referenced by call_pltcl_start_proc(), EventTriggerInvoke(), ExecCallTriggerFunc(), ExecEvalFuncExprFusage(), ExecEvalFuncExprStrictFusage(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), ExecuteCallStmt(), and fmgr_security_definer().

1857 {
1858  PgStat_BackendFunctionEntry *htabent;
1859  bool found;
1860 
1861  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1862  {
1863  /* stats not wanted */
1864  fcu->fs = NULL;
1865  return;
1866  }
1867 
1868  if (!pgStatFunctions)
1869  {
1870  /* First time through - initialize function stat table */
1871  HASHCTL hash_ctl;
1872 
1873  hash_ctl.keysize = sizeof(Oid);
1874  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1875  pgStatFunctions = hash_create("Function stat entries",
1877  &hash_ctl,
1878  HASH_ELEM | HASH_BLOBS);
1879  }
1880 
1881  /* Get the stats entry for this function, create if necessary */
1882  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1883  HASH_ENTER, &found);
1884  if (!found)
1885  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1886 
1887  fcu->fs = &htabent->f_counts;
1888 
1889  /* save stats for this function, later used to compensate for recursion */
1890  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1891 
1892  /* save current backend-wide total time */
1893  fcu->save_total = total_func_time;
1894 
1895  /* get clock time as of function start */
1897 }
#define HASH_ELEM
Definition: hsearch.h:95
instr_time save_total
Definition: pgstat.h:1357
Size entrysize
Definition: hsearch.h:76
#define MemSet(start, val, len)
Definition: c.h:996
instr_time f_total_time
Definition: pgstat.h:552
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1353
PgStat_FunctionCounts f_counts
Definition: pgstat.h:563
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:107
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
#define HASH_BLOBS
Definition: hsearch.h:97
FmgrInfo * flinfo
Definition: fmgr.h:87
Size keysize
Definition: hsearch.h:75
Oid fn_oid
Definition: fmgr.h:59
static instr_time total_func_time
Definition: pgstat.c:315
static HTAB * pgStatFunctions
Definition: pgstat.c:233
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1355
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry

◆ pgstat_initialize()

void pgstat_initialize ( void  )

Definition at line 3096 of file pgstat.c.

References Assert, InvalidBackendId, MaxBackends, MyAuxProcType, MyBackendId, NotAnAuxProcess, on_shmem_exit(), pgstat_beshutdown_hook(), and pgWalUsage.

Referenced by AuxiliaryProcessMain(), and InitPostgres().

3097 {
3098  /* Initialize MyBEEntry */
3100  {
3103  }
3104  else
3105  {
3106  /* Must be an auxiliary process */
3108 
3109  /*
3110  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
3111  * have a BackendId, the slot is statically allocated based on the
3112  * auxiliary process type (MyAuxProcType). Backends use slots indexed
3113  * in the range from 1 to MaxBackends (inclusive), so we use
3114  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
3115  * auxiliary process.
3116  */
3118  }
3119 
3120  /*
3121  * Initialize prevWalUsage with pgWalUsage so that pgstat_send_wal() can
3122  * calculate how much pgWalUsage counters are increased by substracting
3123  * prevWalUsage from pgWalUsage.
3124  */
3126 
3127  /* Set up a process-exit hook to clean up */
3129 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2910
BackendId MyBackendId
Definition: globals.c:82
WalUsage pgWalUsage
Definition: instrument.c:22
int MaxBackends
Definition: globals.c:137
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
static void pgstat_beshutdown_hook(int code, Datum arg)
Definition: pgstat.c:3317
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:70
#define Assert(condition)
Definition: c.h:792
static WalUsage prevWalUsage
Definition: pgstat.c:153

◆ pgstat_initstats()

void pgstat_initstats ( Relation  rel)

Definition at line 1983 of file pgstat.c.

References get_tabstat_entry(), PGINVALID_SOCKET, RelationData::pgstat_info, pgstat_track_counts, pgStatSock, RelationData::rd_id, RelationData::rd_rel, and PgStat_TableStatus::t_id.

Referenced by relation_open(), and try_relation_open().

1984 {
1985  Oid rel_id = rel->rd_id;
1986  char relkind = rel->rd_rel->relkind;
1987 
1988  /* We only count stats for things that have storage */
1989  if (!RELKIND_HAS_STORAGE(relkind))
1990  {
1991  rel->pgstat_info = NULL;
1992  return;
1993  }
1994 
1996  {
1997  /* We're not counting at all */
1998  rel->pgstat_info = NULL;
1999  return;
2000  }
2001 
2002  /*
2003  * If we already set up this relation in the current transaction, nothing
2004  * to do.
2005  */
2006  if (rel->pgstat_info != NULL &&
2007  rel->pgstat_info->t_id == rel_id)
2008  return;
2009 
2010  /* Else find or make the PgStat_TableStatus entry, and update link */
2011  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
2012 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:185
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
bool pgstat_track_counts
Definition: pgstat.c:127
Oid rd_id
Definition: rel.h:112
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:2018
#define PGINVALID_SOCKET
Definition: port.h:33
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237

◆ pgstat_ping()

void pgstat_ping ( void  )

Definition at line 1820 of file pgstat.c.

References PgStat_MsgDummy::m_hdr, PGINVALID_SOCKET, PGSTAT_MTYPE_DUMMY, pgstat_send(), pgstat_setheader(), and pgStatSock.

1821 {
1822  PgStat_MsgDummy msg;
1823 
1825  return;
1826 
1828  pgstat_send(&msg, sizeof(msg));
1829 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4593
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:185
#define PGINVALID_SOCKET
Definition: port.h:33
PgStat_MsgHdr m_hdr
Definition: pgstat.h:234
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4580

◆ pgstat_progress_end_command()

void pgstat_progress_end_command ( void  )

Definition at line 3529 of file pgstat.c.

References InvalidOid, MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_track_activities, PROGRESS_COMMAND_INVALID, PgBackendStatus::st_progress_command, and PgBackendStatus::st_progress_command_target.

Referenced by AbortSubTransaction(), AbortTransaction(), analyze_rel(), cluster_rel(), DefineIndex(), EndCopy(), EndCopyFrom(), heap_vacuum_rel(), perform_base_backup(), reindex_index(), and ReindexRelationConcurrently().

3530 {
3531  volatile PgBackendStatus *beentry = MyBEEntry;
3532 
3533  if (!beentry || !pgstat_track_activities)
3534  return;
3535 
3537  return;
3538 
3539  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3542  PGSTAT_END_WRITE_ACTIVITY(beentry);
3543 }
Oid st_progress_command_target
Definition: pgstat.h:1253
ProgressCommandType st_progress_command
Definition: pgstat.h:1252
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:126
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286

◆ pgstat_progress_start_command()

void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

Definition at line 3457 of file pgstat.c.

References MemSet, MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_track_activities, PgBackendStatus::st_progress_command, PgBackendStatus::st_progress_command_target, and PgBackendStatus::st_progress_param.

Referenced by analyze_rel(), BeginCopyFrom(), BeginCopyTo(), cluster_rel(), DefineIndex(), heap_vacuum_rel(), perform_base_backup(), reindex_index(), and ReindexRelationConcurrently().

3458 {
3459  volatile PgBackendStatus *beentry = MyBEEntry;
3460 
3461  if (!beentry || !pgstat_track_activities)
3462  return;
3463 
3464  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3465  beentry->st_progress_command = cmdtype;
3466  beentry->st_progress_command_target = relid;
3467  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3468  PGSTAT_END_WRITE_ACTIVITY(beentry);
3469 }
Oid st_progress_command_target
Definition: pgstat.h:1253
#define MemSet(start, val, len)
Definition: c.h:996
ProgressCommandType st_progress_command
Definition: pgstat.h:1252
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1254
bool pgstat_track_activities
Definition: pgstat.c:126
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286

◆ pgstat_progress_update_multi_param()

void pgstat_progress_update_multi_param ( int  nparam,
const int *  index,
const int64 *  val 
)

Definition at line 3500 of file pgstat.c.

References Assert, i, MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, PGSTAT_NUM_PROGRESS_PARAM, pgstat_track_activities, and PgBackendStatus::st_progress_param.

Referenced by _bt_spools_heapscan(), BuildRelationExtStatistics(), heapam_relation_copy_for_cluster(), index_build(), lazy_scan_heap(), perform_base_backup(), ReindexRelationConcurrently(), update_basebackup_progress(), validate_index(), and WaitForLockersMultiple().

3502 {
3503  volatile PgBackendStatus *beentry = MyBEEntry;
3504  int i;
3505 
3506  if (!beentry || !pgstat_track_activities || nparam == 0)
3507  return;
3508 
3509  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3510 
3511  for (i = 0; i < nparam; ++i)
3512  {
3513  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3514 
3515  beentry->st_progress_param[index[i]] = val[i];
3516  }
3517 
3518  PGSTAT_END_WRITE_ACTIVITY(beentry);
3519 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1118
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
#define Assert(condition)
Definition: c.h:792
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1254
bool pgstat_track_activities
Definition: pgstat.c:126
int i
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286
long val
Definition: informix.c:664

◆ pgstat_progress_update_param()

void pgstat_progress_update_param ( int  index,
int64  val 
)

Definition at line 3478 of file pgstat.c.

References Assert, MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, PGSTAT_NUM_PROGRESS_PARAM, pgstat_track_activities, PgBackendStatus::st_progress_param, and val.

Referenced by _bt_leafbuild(), _bt_load(), _bt_spools_heapscan(), _h_indexbuild(), acquire_inherited_sample_rows(), acquire_sample_rows(), BeginCopyFrom(), btvacuumscan(), BuildRelationExtStatistics(), cluster_rel(), copy_dest_receive(), CopyFrom(), CopyLoadRawBuf(), CopySendEndOfRow(), CopyTo(), DefineIndex(), do_analyze_rel(), finish_heap_swap(), hashbuild(), heap_vacuum_rel(), heapam_index_build_range_scan(), heapam_index_validate_scan(), heapam_relation_copy_for_cluster(), lazy_cleanup_all_indexes(), lazy_record_dead_tuple(), lazy_scan_heap(), lazy_truncate_heap(), lazy_vacuum_all_indexes(), lazy_vacuum_heap(), lazy_vacuum_page(), perform_base_backup(), reindex_index(), reindex_relation(), ReindexRelationConcurrently(), validate_index(), WaitForLockersMultiple(), and WaitForOlderSnapshots().

3479 {
3480  volatile PgBackendStatus *beentry = MyBEEntry;
3481 
3483 
3484  if (!beentry || !pgstat_track_activities)
3485  return;
3486 
3487  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3488  beentry->st_progress_param[index] = val;
3489  PGSTAT_END_WRITE_ACTIVITY(beentry);
3490 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1118
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2911
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1293
#define Assert(condition)
Definition: c.h:792
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1254
bool pgstat_track_activities
Definition: pgstat.c:126
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1286
long val
Definition: informix.c:664

◆ pgstat_read_current_status()

static void pgstat_read_current_status ( void  )
static

Definition at line 3608 of file pgstat.c.

References Assert, LocalPgBackendStatus::backend_xid, LocalPgBackendStatus::backend_xmin, BackendIdGetTransactionIds(), LocalPgBackendStatus::backendStatus, BackendStatusArray, CHECK_FOR_INTERRUPTS, i, localNumBackends, MemoryContextAlloc(), MemoryContextAllocHuge(), NAMEDATALEN, NumBackendStatSlots, pgstat_begin_read_activity, pgstat_end_read_activity, pgstat_read_activity_complete, pgstat_setup_memcxt(), pgstat_track_activity_query_size, pgStatRunningInCollector, PgBackendStatus::st_activity_raw, PgBackendStatus::st_appname, PgBackendStatus::st_clienthostname, PgBackendStatus::st_gss, PgBackendStatus::st_gssstatus, PgBackendStatus::st_procpid, PgBackendStatus::st_ssl, PgBackendStatus::st_sslstatus, and unvolatize.

Referenced by pgstat_fetch_stat_beentry(), pgstat_fetch_stat_local_beentry(), and pgstat_fetch_stat_numbackends().

3609 {
3610  volatile PgBackendStatus *beentry;
3611  LocalPgBackendStatus *localtable;
3612  LocalPgBackendStatus *localentry;
3613  char *localappname,
3614  *localclienthostname,
3615  *localactivity;
3616 #ifdef USE_SSL
3617  PgBackendSSLStatus *localsslstatus;
3618 #endif
3619 #ifdef ENABLE_GSS
3620  PgBackendGSSStatus *localgssstatus;
3621 #endif
3622  int i;
3623 
3626  return; /* already done */
3627 
3629 
3630  /*
3631  * Allocate storage for local copy of state data. We can presume that
3632  * none of these requests overflow size_t, because we already calculated
3633  * the same values using mul_size during shmem setup. However, with
3634  * probably-silly values of pgstat_track_activity_query_size and
3635  * max_connections, the localactivity buffer could exceed 1GB, so use
3636  * "huge" allocation for that one.
3637  */
3638  localtable = (LocalPgBackendStatus *)
3641  localappname = (char *)
3644  localclienthostname = (char *)
3646  NAMEDATALEN * NumBackendStatSlots);
3647  localactivity = (char *)
3649  pgstat_track_activity_query_size * NumBackendStatSlots);
3650 #ifdef USE_SSL
3651  localsslstatus = (PgBackendSSLStatus *)
3654 #endif
3655 #ifdef ENABLE_GSS
3656  localgssstatus = (PgBackendGSSStatus *)
3659 #endif
3660 
3661  localNumBackends = 0;
3662 
3663  beentry = BackendStatusArray;
3664  localentry = localtable;
3665  for (i = 1; i <= NumBackendStatSlots; i++)
3666  {
3667  /*
3668  * Follow the protocol of retrying if st_changecount changes while we
3669  * copy the entry, or if it's odd. (The check for odd is needed to
3670  * cover the case where we are able to completely copy the entry while
3671  * the source backend is between increment steps.) We use a volatile
3672  * pointer here to ensure the compiler doesn't try to get cute.
3673  */
3674  for (;;)
3675  {
3676  int before_changecount;
3677  int after_changecount;
3678 
3679  pgstat_begin_read_activity(beentry, before_changecount);
3680 
3681  localentry->backendStatus.st_procpid = beentry->st_procpid;
3682  /* Skip all the data-copying work if entry is not in use */
3683  if (localentry->backendStatus.st_procpid > 0)
3684  {
3685  memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3686 
3687  /*
3688  * For each PgBackendStatus field that is a pointer, copy the
3689  * pointed-to data, then adjust the local copy of the pointer
3690  * field to point at the local copy of the data.
3691  *
3692  * strcpy is safe even if the string is modified concurrently,
3693  * because there's always a \0 at the end of the buffer.
3694  */
3695  strcpy(localappname, (char *) beentry->st_appname);
3696  localentry->backendStatus.st_appname = localappname;
3697  strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3698  localentry->backendStatus.st_clienthostname = localclienthostname;
3699  strcpy(localactivity, (char *) beentry->st_activity_raw);
3700  localentry->backendStatus.st_activity_raw = localactivity;
3701 #ifdef USE_SSL
3702  if (beentry->st_ssl)
3703  {
3704  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3705  localentry->backendStatus.st_sslstatus = localsslstatus;
3706  }
3707 #endif
3708 #ifdef ENABLE_GSS
3709  if (beentry->st_gss)
3710  {
3711  memcpy(localgssstatus, beentry->st_gssstatus, sizeof(PgBackendGSSStatus));
3712  localentry->backendStatus.st_gssstatus = localgssstatus;
3713  }
3714 #endif
3715  }
3716 
3717  pgstat_end_read_activity(beentry, after_changecount);
3718 
3719  if (pgstat_read_activity_complete(before_changecount,
3720  after_changecount))
3721  break;
3722 
3723  /* Make sure we can break out of loop if stuck... */
3725  }
3726 
3727  beentry++;
3728  /* Only valid entries get included into the local array */
3729  if (localentry->backendStatus.st_procpid > 0)
3730  {
3732  &localentry->backend_xid,
3733  &localentry->backend_xmin);
3734 
3735  localentry++;
3736  localappname += NAMEDATALEN;
3737  localclienthostname += NAMEDATALEN;
3738  localactivity += pgstat_track_activity_query_size;
3739 #ifdef USE_SSL
3740  localsslstatus++;
3741 #endif
3742 #ifdef ENABLE_GSS
3743  localgssstatus++;
3744 #endif
3745  localNumBackends++;
3746  }
3747  }
3748 
3749  /* Set the pointer only after completion of a valid table */
3750  localBackendStatusTable = localtable;
3751 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2910
static bool pgStatRunningInCollector
Definition: pgstat.c:191
TransactionId backend_xmin
Definition: pgstat.h:1343
#define NumBackendStatSlots
Definition: pgstat.c:119
char * st_clienthostname
Definition: pgstat.h:1218
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1337
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition: mcxt.c:1106
char * st_activity_raw
Definition: pgstat.h:1241
int pgstat_track_activity_query_size
Definition: pgstat.c:129
char * st_appname
Definition: pgstat.h:1232
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1307
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:6250
PgBackendStatus backendStatus
Definition: pgstat.h:1331
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:403
#define Assert(condition)
Definition: c.h:792
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:286
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1301
static int localNumBackends
Definition: pgstat.c:289
#define unvolatize(underlying_type, expr)
Definition: c.h:1233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:282
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1222
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1226
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1313

◆ pgstat_read_db_statsfile()

static void pgstat_read_db_statsfile ( Oid  databaseid,
HTAB tabhash,
HTAB funchash,
bool  permanent 
)
static

Definition at line 5788 of file pgstat.c.

References AllocateFile(), DEBUG2, elog, ereport, errcode_for_file_access(), errmsg(), FreeFile(), PgStat_StatFuncEntry::functionid, get_dbstat_filename(), HASH_ENTER, hash_search(), LOG, MAXPGPATH, PG_BINARY_R, PGSTAT_FILE_FORMAT_ID, pgStatRunningInCollector, PgStat_StatTabEntry::tableid, and WARNING.

Referenced by pgstat_read_statsfiles().

5790 {
5791  PgStat_StatTabEntry *tabentry;
5792  PgStat_StatTabEntry tabbuf;
5793  PgStat_StatFuncEntry funcbuf;
5794  PgStat_StatFuncEntry *funcentry;
5795  FILE *fpin;
5796  int32 format_id;
5797  bool found;
5798  char statfile[MAXPGPATH];
5799 
5800  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5801 
5802  /*
5803  * Try to open the stats file. If it doesn't exist, the backends simply
5804  * return zero for anything and the collector simply starts from scratch
5805  * with empty counters.
5806  *
5807  * ENOENT is a possibility if the stats collector is not running or has
5808  * not yet written the stats file the first time. Any other failure
5809  * condition is suspicious.
5810  */
5811  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5812  {
5813  if (errno != ENOENT)
5816  errmsg("could not open statistics file \"%s\": %m",
5817  statfile)));
5818  return;
5819  }
5820 
5821  /*
5822  * Verify it's of the expected format.
5823  */
5824  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5825  format_id != PGSTAT_FILE_FORMAT_ID)
5826  {
5827  ereport(pgStatRunningInCollector ? LOG : WARNING,
5828  (errmsg("corrupted statistics file \"%s\"", statfile)));
5829  goto done;
5830  }
5831 
5832  /*
5833  * We found an existing collector stats file. Read it and put all the
5834  * hashtable entries into place.
5835  */
5836  for (;;)
5837  {
5838  switch (fgetc(fpin))
5839  {
5840  /*
5841  * 'T' A PgStat_StatTabEntry follows.
5842  */
5843  case 'T':
5844  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5845  fpin) != sizeof(PgStat_StatTabEntry))
5846  {
5847  ereport(pgStatRunningInCollector ? LOG : WARNING,
5848  (errmsg("corrupted statistics file \"%s\"",
5849  statfile)));
5850  goto done;
5851  }
5852 
5853  /*
5854  * Skip if table data not wanted.
5855  */
5856  if (tabhash == NULL)