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 "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 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_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 force)
 
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 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 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 104 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 86 of file pgstat.c.

◆ PGSTAT_INQ_LOOP_COUNT

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

Definition at line 94 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 83 of file pgstat.c.

◆ PGSTAT_MIN_RCVBUF

#define PGSTAT_MIN_RCVBUF   (100 * 1024)

Definition at line 97 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 93 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 89 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 80 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 77 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 105 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 195 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 2084 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().

2085 {
2086  PgStat_SubXactStatus *xact_state;
2088 
2089  /*
2090  * If this is the first rel to be modified at the current nest level, we
2091  * first have to push a transaction stack entry.
2092  */
2093  xact_state = get_tabstat_stack_level(nest_level);
2094 
2095  /* Now make a per-table stack entry */
2096  trans = (PgStat_TableXactStatus *)
2098  sizeof(PgStat_TableXactStatus));
2099  trans->nest_level = nest_level;
2100  trans->upper = pgstat_info->trans;
2101  trans->parent = pgstat_info;
2102  trans->next = xact_state->first;
2103  xact_state->first = trans;
2104  pgstat_info->trans = trans;
2105 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_TableXactStatus * next
Definition: pgstat.h:186
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:2062
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:183
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:840
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:243
PgStat_TableStatus * parent
Definition: pgstat.h:184

◆ allow_immediate_pgstat_restart()

void allow_immediate_pgstat_restart ( void  )

Definition at line 828 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

829 {
831 }
static time_t last_pgstat_start_time
Definition: pgstat.c:180

◆ AtEOSubXact_PgStat()

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

Definition at line 2344 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().

2345 {
2346  PgStat_SubXactStatus *xact_state;
2347 
2348  /*
2349  * Transfer transactional insert/update counts into the next higher
2350  * subtransaction state.
2351  */
2352  xact_state = pgStatXactStack;
2353  if (xact_state != NULL &&
2354  xact_state->nest_level >= nestDepth)
2355  {
2357  PgStat_TableXactStatus *next_trans;
2358 
2359  /* delink xact_state from stack immediately to simplify reuse case */
2360  pgStatXactStack = xact_state->prev;
2361 
2362  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2363  {
2364  PgStat_TableStatus *tabstat;
2365 
2366  next_trans = trans->next;
2367  Assert(trans->nest_level == nestDepth);
2368  tabstat = trans->parent;
2369  Assert(tabstat->trans == trans);
2370  if (isCommit)
2371  {
2372  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2373  {
2374  if (trans->truncated)
2375  {
2376  /* propagate the truncate status one level up */
2378  /* replace upper xact stats with ours */
2379  trans->upper->tuples_inserted = trans->tuples_inserted;
2380  trans->upper->tuples_updated = trans->tuples_updated;
2381  trans->upper->tuples_deleted = trans->tuples_deleted;
2382  }
2383  else
2384  {
2385  trans->upper->tuples_inserted += trans->tuples_inserted;
2386  trans->upper->tuples_updated += trans->tuples_updated;
2387  trans->upper->tuples_deleted += trans->tuples_deleted;
2388  }
2389  tabstat->trans = trans->upper;
2390  pfree(trans);
2391  }
2392  else
2393  {
2394  /*
2395  * When there isn't an immediate parent state, we can just
2396  * reuse the record instead of going through a
2397  * palloc/pfree pushup (this works since it's all in
2398  * TopTransactionContext anyway). We have to re-link it
2399  * into the parent level, though, and that might mean
2400  * pushing a new entry into the pgStatXactStack.
2401  */
2402  PgStat_SubXactStatus *upper_xact_state;
2403 
2404  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2405  trans->next = upper_xact_state->first;
2406  upper_xact_state->first = trans;
2407  trans->nest_level = nestDepth - 1;
2408  }
2409  }
2410  else
2411  {
2412  /*
2413  * On abort, update top-level tabstat counts, then forget the
2414  * subtransaction
2415  */
2416 
2417  /* first restore values obliterated by truncate */
2419  /* count attempted actions regardless of commit/abort */
2420  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2421  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2422  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2423  /* inserted tuples are dead, deleted tuples are unaffected */
2424  tabstat->t_counts.t_delta_dead_tuples +=
2425  trans->tuples_inserted + trans->tuples_updated;
2426  tabstat->trans = trans->upper;
2427  pfree(trans);
2428  }
2429  }
2430  pfree(xact_state);
2431  }
2432 }
PgStat_Counter tuples_updated
Definition: pgstat.h:175
struct PgStat_TableXactStatus * next
Definition: pgstat.h:186
PgStat_TableCounts t_counts
Definition: pgstat.h:165
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:2062
void pfree(void *pointer)
Definition: mcxt.c:1057
PgStat_Counter t_tuples_updated
Definition: pgstat.h:111
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2198
PgStat_Counter tuples_inserted
Definition: pgstat.h:174
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:117
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:183
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:112
PgStat_Counter tuples_deleted
Definition: pgstat.h:176
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:242
#define Assert(condition)
Definition: c.h:746
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:246
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:243
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2183
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:110
PgStat_TableStatus * parent
Definition: pgstat.h:184

◆ AtEOXact_PgStat()

void AtEOXact_PgStat ( bool  isCommit,
bool  parallel 
)

Definition at line 2257 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().

2258 {
2259  PgStat_SubXactStatus *xact_state;
2260 
2261  /* Don't count parallel worker transaction stats */
2262  if (!parallel)
2263  {
2264  /*
2265  * Count transaction commit or abort. (We use counters, not just
2266  * bools, in case the reporting message isn't sent right away.)
2267  */
2268  if (isCommit)
2269  pgStatXactCommit++;
2270  else
2272  }
2273 
2274  /*
2275  * Transfer transactional insert/update counts into the base tabstat
2276  * entries. We don't bother to free any of the transactional state, since
2277  * it's all in TopTransactionContext and will go away anyway.
2278  */
2279  xact_state = pgStatXactStack;
2280  if (xact_state != NULL)
2281  {
2283 
2284  Assert(xact_state->nest_level == 1);
2285  Assert(xact_state->prev == NULL);
2286  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2287  {
2288  PgStat_TableStatus *tabstat;
2289 
2290  Assert(trans->nest_level == 1);
2291  Assert(trans->upper == NULL);
2292  tabstat = trans->parent;
2293  Assert(tabstat->trans == trans);
2294  /* restore pre-truncate stats (if any) in case of aborted xact */
2295  if (!isCommit)
2297  /* count attempted actions regardless of commit/abort */
2298  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2299  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2300  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2301  if (isCommit)
2302  {
2303  tabstat->t_counts.t_truncated = trans->truncated;
2304  if (trans->truncated)
2305  {
2306  /* forget live/dead stats seen by backend thus far */
2307  tabstat->t_counts.t_delta_live_tuples = 0;
2308  tabstat->t_counts.t_delta_dead_tuples = 0;
2309  }
2310  /* insert adds a live tuple, delete removes one */
2311  tabstat->t_counts.t_delta_live_tuples +=
2312  trans->tuples_inserted - trans->tuples_deleted;
2313  /* update and delete each create a dead tuple */
2314  tabstat->t_counts.t_delta_dead_tuples +=
2315  trans->tuples_updated + trans->tuples_deleted;
2316  /* insert, update, delete each count as one change event */
2317  tabstat->t_counts.t_changed_tuples +=
2318  trans->tuples_inserted + trans->tuples_updated +
2319  trans->tuples_deleted;
2320  }
2321  else
2322  {
2323  /* inserted tuples are dead, deleted tuples are unaffected */
2324  tabstat->t_counts.t_delta_dead_tuples +=
2325  trans->tuples_inserted + trans->tuples_updated;
2326  /* an aborted xact generates no changed_tuple events */
2327  }
2328  tabstat->trans = NULL;
2329  }
2330  }
2331  pgStatXactStack = NULL;
2332 
2333  /* Make sure any stats snapshot is thrown away */
2335 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:116
PgStat_Counter tuples_updated
Definition: pgstat.h:175
static int pgStatXactCommit
Definition: pgstat.c:248
struct PgStat_TableXactStatus * next
Definition: pgstat.h:186
PgStat_TableCounts t_counts
Definition: pgstat.h:165
PgStat_Counter t_tuples_updated
Definition: pgstat.h:111
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2198
static int pgStatXactRollback
Definition: pgstat.c:249
PgStat_Counter tuples_inserted
Definition: pgstat.h:174
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:117
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:183
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:112
PgStat_Counter tuples_deleted
Definition: pgstat.h:176
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:242
PgStat_Counter t_changed_tuples
Definition: pgstat.h:118
#define Assert(condition)
Definition: c.h:746
void pgstat_clear_snapshot(void)
Definition: pgstat.c:6141
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:246
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:243
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:110
PgStat_TableStatus * parent
Definition: pgstat.h:184

◆ AtPrepare_PgStat()

void AtPrepare_PgStat ( void  )

Definition at line 2443 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().

2444 {
2445  PgStat_SubXactStatus *xact_state;
2446 
2447  xact_state = pgStatXactStack;
2448  if (xact_state != NULL)
2449  {
2451 
2452  Assert(xact_state->nest_level == 1);
2453  Assert(xact_state->prev == NULL);
2454  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2455  {
2456  PgStat_TableStatus *tabstat;
2457  TwoPhasePgStatRecord record;
2458 
2459  Assert(trans->nest_level == 1);
2460  Assert(trans->upper == NULL);
2461  tabstat = trans->parent;
2462  Assert(tabstat->trans == trans);
2463 
2464  record.tuples_inserted = trans->tuples_inserted;
2465  record.tuples_updated = trans->tuples_updated;
2466  record.tuples_deleted = trans->tuples_deleted;
2467  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2468  record.updated_pre_trunc = trans->updated_pre_trunc;
2469  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2470  record.t_id = tabstat->t_id;
2471  record.t_shared = tabstat->t_shared;
2472  record.t_truncated = trans->truncated;
2473 
2475  &record, sizeof(TwoPhasePgStatRecord));
2476  }
2477  }
2478 }
PgStat_Counter tuples_updated
Definition: pgstat.h:175
struct PgStat_TableXactStatus * next
Definition: pgstat.h:186
PgStat_Counter deleted_pre_trunc
Definition: pgstat.h:180
PgStat_Counter deleted_pre_trunc
Definition: pgstat.c:261
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1181
PgStat_Counter tuples_inserted
Definition: pgstat.h:174
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:260
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:259
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:183
PgStat_Counter tuples_updated
Definition: pgstat.c:257
PgStat_Counter tuples_deleted
Definition: pgstat.h:176
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:242
#define Assert(condition)
Definition: c.h:746
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:178
PgStat_Counter tuples_inserted
Definition: pgstat.c:256
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:246
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164
PgStat_Counter tuples_deleted
Definition: pgstat.c:258
#define TWOPHASE_RM_PGSTAT_ID
Definition: twophase_rmgr.h:26
PgStat_Counter updated_pre_trunc
Definition: pgstat.h:179
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:400
PgStat_TableXactStatus * first
Definition: pgstat.c:243
PgStat_TableStatus * parent
Definition: pgstat.h:184

◆ backend_read_statsfile()

static void backend_read_statsfile ( void  )
static

Definition at line 5987 of file pgstat.c.

References Assert, CHECK_FOR_INTERRUPTS, elog, 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().

5988 {
5989  TimestampTz min_ts = 0;
5990  TimestampTz ref_ts = 0;
5991  Oid inquiry_db;
5992  int count;
5993 
5994  /* already read it? */
5995  if (pgStatDBHash)
5996  return;
5998 
5999  /*
6000  * In a normal backend, we check staleness of the data for our own DB, and
6001  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
6002  * check staleness of the shared-catalog data, and send InvalidOid in
6003  * inquiry messages so as not to force writing unnecessary data.
6004  */
6006  inquiry_db = InvalidOid;
6007  else
6008  inquiry_db = MyDatabaseId;
6009 
6010  /*
6011  * Loop until fresh enough stats file is available or we ran out of time.
6012  * The stats inquiry message is sent repeatedly in case collector drops
6013  * it; but not every single time, as that just swamps the collector.
6014  */
6015  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
6016  {
6017  bool ok;
6018  TimestampTz file_ts = 0;
6019  TimestampTz cur_ts;
6020 
6022 
6023  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
6024 
6025  cur_ts = GetCurrentTimestamp();
6026  /* Calculate min acceptable timestamp, if we didn't already */
6027  if (count == 0 || cur_ts < ref_ts)
6028  {
6029  /*
6030  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
6031  * msec before now. This indirectly ensures that the collector
6032  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
6033  * an autovacuum worker, however, we want a lower delay to avoid
6034  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
6035  * number of workers is low, this shouldn't be a problem).
6036  *
6037  * We don't recompute min_ts after sleeping, except in the
6038  * unlikely case that cur_ts went backwards. So we might end up
6039  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
6040  * practice that shouldn't happen, though, as long as the sleep
6041  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
6042  * tell the collector that our cutoff time is less than what we'd
6043  * actually accept.
6044  */
6045  ref_ts = cur_ts;
6047  min_ts = TimestampTzPlusMilliseconds(ref_ts,
6049  else
6050  min_ts = TimestampTzPlusMilliseconds(ref_ts,
6052  }
6053 
6054  /*
6055  * If the file timestamp is actually newer than cur_ts, we must have
6056  * had a clock glitch (system time went backwards) or there is clock
6057  * skew between our processor and the stats collector's processor.
6058  * Accept the file, but send an inquiry message anyway to make
6059  * pgstat_recv_inquiry do a sanity check on the collector's time.
6060  */
6061  if (ok && file_ts > cur_ts)
6062  {
6063  /*
6064  * A small amount of clock skew between processors isn't terribly
6065  * surprising, but a large difference is worth logging. We
6066  * arbitrarily define "large" as 1000 msec.
6067  */
6068  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
6069  {
6070  char *filetime;
6071  char *mytime;
6072 
6073  /* Copy because timestamptz_to_str returns a static buffer */
6074  filetime = pstrdup(timestamptz_to_str(file_ts));
6075  mytime = pstrdup(timestamptz_to_str(cur_ts));
6076  elog(LOG, "stats collector's time %s is later than backend local time %s",
6077  filetime, mytime);
6078  pfree(filetime);
6079  pfree(mytime);
6080  }
6081 
6082  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
6083  break;
6084  }
6085 
6086  /* Normal acceptance case: file is not older than cutoff time */
6087  if (ok && file_ts >= min_ts)
6088  break;
6089 
6090  /* Not there or too old, so kick the collector and wait a bit */
6091  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
6092  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
6093 
6094  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
6095  }
6096 
6097  if (count >= PGSTAT_POLL_LOOP_COUNT)
6098  ereport(LOG,
6099  (errmsg("using stale statistics instead of current ones "
6100  "because stats collector is not responding")));
6101 
6102  /*
6103  * Autovacuum launcher wants stats about all databases, but a shallow read
6104  * is sufficient. Regular backends want a deep read for just the tables
6105  * they can see (MyDatabaseId + shared catalogs).
6106  */
6109  else
6111 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:80
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
int64 TimestampTz
Definition: timestamp.h:39
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:94
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static bool pgStatRunningInCollector
Definition: pgstat.c:182
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PGSTAT_POLL_LOOP_COUNT
Definition: pgstat.c:93
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:1772
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:77
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:5369
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:144
static bool pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent, TimestampTz *ts)
Definition: pgstat.c:5823
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3319
#define Assert(condition)
Definition: c.h:746
static HTAB * pgStatDBHash
Definition: pgstat.c:271
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1740

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 2864 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2865 {
2866  Size size;
2867 
2868  /* BackendStatusArray: */
2869  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2870  /* BackendAppnameBuffer: */
2871  size = add_size(size,
2873  /* BackendClientHostnameBuffer: */
2874  size = add_size(size,
2876  /* BackendActivityBuffer: */
2877  size = add_size(size,
2879 #ifdef USE_SSL
2880  /* BackendSslStatusBuffer: */
2881  size = add_size(size,
2883 #endif
2884  return size;
2885 }
#define NumBackendStatSlots
Definition: pgstat.c:118
#define NAMEDATALEN
int pgstat_track_activity_query_size
Definition: pgstat.c:128
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:474

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

Definition at line 2892 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().

2893 {
2894  Size size;
2895  bool found;
2896  int i;
2897  char *buffer;
2898 
2899  /* Create or attach to the shared array */
2900  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2902  ShmemInitStruct("Backend Status Array", size, &found);
2903 
2904  if (!found)
2905  {
2906  /*
2907  * We're the first - initialize.
2908  */
2909  MemSet(BackendStatusArray, 0, size);
2910  }
2911 
2912  /* Create or attach to the shared appname buffer */
2914  BackendAppnameBuffer = (char *)
2915  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2916 
2917  if (!found)
2918  {
2919  MemSet(BackendAppnameBuffer, 0, size);
2920 
2921  /* Initialize st_appname pointers. */
2922  buffer = BackendAppnameBuffer;
2923  for (i = 0; i < NumBackendStatSlots; i++)
2924  {
2925  BackendStatusArray[i].st_appname = buffer;
2926  buffer += NAMEDATALEN;
2927  }
2928  }
2929 
2930  /* Create or attach to the shared client hostname buffer */
2932  BackendClientHostnameBuffer = (char *)
2933  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2934 
2935  if (!found)
2936  {
2938 
2939  /* Initialize st_clienthostname pointers. */
2940  buffer = BackendClientHostnameBuffer;
2941  for (i = 0; i < NumBackendStatSlots; i++)
2942  {
2944  buffer += NAMEDATALEN;
2945  }
2946  }
2947 
2948  /* Create or attach to the shared activity buffer */
2951  BackendActivityBuffer = (char *)
2952  ShmemInitStruct("Backend Activity Buffer",
2954  &found);
2955 
2956  if (!found)
2957  {
2959 
2960  /* Initialize st_activity pointers. */
2961  buffer = BackendActivityBuffer;
2962  for (i = 0; i < NumBackendStatSlots; i++)
2963  {
2966  }
2967  }
2968 
2969 #ifdef USE_SSL
2970  /* Create or attach to the shared SSL status buffer */
2972  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2973  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2974 
2975  if (!found)
2976  {
2977  PgBackendSSLStatus *ptr;
2978 
2979  MemSet(BackendSslStatusBuffer, 0, size);
2980 
2981  /* Initialize st_sslstatus pointers. */
2982  ptr = BackendSslStatusBuffer;
2983  for (i = 0; i < NumBackendStatSlots; i++)
2984  {
2986  ptr++;
2987  }
2988  }
2989 #endif
2990 
2991 #ifdef ENABLE_GSS
2992  /* Create or attach to the shared GSSAPI status buffer */
2994  BackendGssStatusBuffer = (PgBackendGSSStatus *)
2995  ShmemInitStruct("Backend GSS Status Buffer", size, &found);
2996 
2997  if (!found)
2998  {
2999  PgBackendGSSStatus *ptr;
3000 
3001  MemSet(BackendGssStatusBuffer, 0, size);
3002 
3003  /* Initialize st_gssstatus pointers. */
3004  ptr = BackendGssStatusBuffer;
3005  for (i = 0; i < NumBackendStatSlots; i++)
3006  {
3008  ptr++;
3009  }
3010  }
3011 #endif
3012 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2846
static char * BackendActivityBuffer
Definition: pgstat.c:2850
static Size BackendActivityBufferSize
Definition: pgstat.c:2851
#define MemSet(start, val, len)
Definition: c.h:950
#define NumBackendStatSlots
Definition: pgstat.c:118
char * st_clienthostname
Definition: pgstat.h:1177
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2848
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
char * st_activity_raw
Definition: pgstat.h:1200
int pgstat_track_activity_query_size
Definition: pgstat.c:128
char * st_appname
Definition: pgstat.h:1191
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
size_t Size
Definition: c.h:474
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1181
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1185
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2849

◆ find_funcstat_entry()

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

Definition at line 1841 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().

1842 {
1843  if (pgStatFunctions == NULL)
1844  return NULL;
1845 
1847  (void *) &func_id,
1848  HASH_FIND, NULL);
1849 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
static HTAB * pgStatFunctions
Definition: pgstat.c:224

◆ find_tabstat_entry()

PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

Definition at line 2042 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().

2043 {
2044  TabStatHashEntry *hash_entry;
2045 
2046  /* If hashtable doesn't exist, there are no entries at all */
2047  if (!pgStatTabHash)
2048  return NULL;
2049 
2050  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
2051  if (!hash_entry)
2052  return NULL;
2053 
2054  /* Note that this step could also return NULL, but that's correct */
2055  return hash_entry->tsa_entry;
2056 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
static HTAB * pgStatTabHash
Definition: pgstat.c:218
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:212

◆ get_dbstat_filename()

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

Definition at line 5220 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().

5222 {
5223  int printed;
5224 
5225  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
5226  printed = snprintf(filename, len, "%s/db_%u.%s",
5227  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
5229  databaseid,
5230  tempname ? "tmp" : "stat");
5231  if (printed >= len)
5232  elog(ERROR, "overlength pgstat path");
5233 }
#define PGSTAT_STAT_PERMANENT_DIRECTORY
Definition: pgstat.h:29
#define ERROR
Definition: elog.h:43
char * pgstat_stat_directory
Definition: pgstat.c:134
static char * filename
Definition: pg_dumpall.c:91
#define elog(elevel,...)
Definition: elog.h:214
#define snprintf
Definition: port.h:215

◆ get_tabstat_entry()

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

Definition at line 1953 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().

1954 {
1955  TabStatHashEntry *hash_entry;
1956  PgStat_TableStatus *entry;
1957  TabStatusArray *tsa;
1958  bool found;
1959 
1960  /*
1961  * Create hash table if we don't have it already.
1962  */
1963  if (pgStatTabHash == NULL)
1964  {
1965  HASHCTL ctl;
1966 
1967  memset(&ctl, 0, sizeof(ctl));
1968  ctl.keysize = sizeof(Oid);
1969  ctl.entrysize = sizeof(TabStatHashEntry);
1970 
1971  pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1973  &ctl,
1974  HASH_ELEM | HASH_BLOBS);
1975  }
1976 
1977  /*
1978  * Find an entry or create a new one.
1979  */
1980  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1981  if (!found)
1982  {
1983  /* initialize new entry with null pointer */
1984  hash_entry->tsa_entry = NULL;
1985  }
1986 
1987  /*
1988  * If entry is already valid, we're done.
1989  */
1990  if (hash_entry->tsa_entry)
1991  return hash_entry->tsa_entry;
1992 
1993  /*
1994  * Locate the first pgStatTabList entry with free space, making a new list
1995  * entry if needed. Note that we could get an OOM failure here, but if so
1996  * we have left the hashtable and the list in a consistent state.
1997  */
1998  if (pgStatTabList == NULL)
1999  {
2000  /* Set up first pgStatTabList entry */
2003  sizeof(TabStatusArray));
2004  }
2005 
2006  tsa = pgStatTabList;
2007  while (tsa->tsa_used >= TABSTAT_QUANTUM)
2008  {
2009  if (tsa->tsa_next == NULL)
2010  tsa->tsa_next = (TabStatusArray *)
2012  sizeof(TabStatusArray));
2013  tsa = tsa->tsa_next;
2014  }
2015 
2016  /*
2017  * Allocate a PgStat_TableStatus entry within this list entry. We assume
2018  * the entry was already zeroed, either at creation or after last use.
2019  */
2020  entry = &tsa->tsa_entries[tsa->tsa_used++];
2021  entry->t_id = rel_id;
2022  entry->t_shared = isshared;
2023 
2024  /*
2025  * Now we can fill the entry in pgStatTabHash.
2026  */
2027  hash_entry->tsa_entry = entry;
2028 
2029  return entry;
2030 }
int tsa_used
Definition: pgstat.c:200
#define HASH_ELEM
Definition: hsearch.h:85
Size entrysize
Definition: hsearch.h:72
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
struct TabStatusArray * tsa_next
Definition: pgstat.c:199
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:218
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:201
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define HASH_BLOBS
Definition: hsearch.h:86
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:212
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
Size keysize
Definition: hsearch.h:71
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:840
static TabStatusArray * pgStatTabList
Definition: pgstat.c:204
#define TABSTAT_QUANTUM
Definition: pgstat.c:195

◆ get_tabstat_stack_level()

static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

Definition at line 2062 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().

2063 {
2064  PgStat_SubXactStatus *xact_state;
2065 
2066  xact_state = pgStatXactStack;
2067  if (xact_state == NULL || xact_state->nest_level != nest_level)
2068  {
2069  xact_state = (PgStat_SubXactStatus *)
2071  sizeof(PgStat_SubXactStatus));
2072  xact_state->nest_level = nest_level;
2073  xact_state->prev = pgStatXactStack;
2074  xact_state->first = NULL;
2075  pgStatXactStack = xact_state;
2076  }
2077  return xact_state;
2078 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:242
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:246
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
PgStat_TableXactStatus * first
Definition: pgstat.c:243

◆ pgstat_beshutdown_hook()

static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

Definition at line 3240 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().

3241 {
3242  volatile PgBackendStatus *beentry = MyBEEntry;
3243 
3244  /*
3245  * If we got as far as discovering our own database ID, we can report what
3246  * we did to the collector. Otherwise, we'd be sending an invalid
3247  * database ID, so forget it. (This means that accesses to pg_database
3248  * during failed backend starts might never get counted.)
3249  */
3250  if (OidIsValid(MyDatabaseId))
3251  pgstat_report_stat(true);
3252 
3253  /*
3254  * Clear my status entry, following the protocol of bumping st_changecount
3255  * before and after. We use a volatile pointer here to ensure the
3256  * compiler doesn't try to get cute.
3257  */
3258  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3259 
3260  beentry->st_procpid = 0; /* mark invalid */
3261 
3262  PGSTAT_END_WRITE_ACTIVITY(beentry);
3263 }
#define OidIsValid(objectId)
Definition: c.h:652
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
Oid MyDatabaseId
Definition: globals.c:85
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245
void pgstat_report_stat(bool force)
Definition: pgstat.c:850

◆ pgstat_bestart()

void pgstat_bestart ( void  )

Definition at line 3069 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().

3070 {
3071  volatile PgBackendStatus *vbeentry = MyBEEntry;
3072  PgBackendStatus lbeentry;
3073 #ifdef USE_SSL
3074  PgBackendSSLStatus lsslstatus;
3075 #endif
3076 #ifdef ENABLE_GSS
3077  PgBackendGSSStatus lgssstatus;
3078 #endif
3079 
3080  /* pgstats state must be initialized from pgstat_initialize() */
3081  Assert(vbeentry != NULL);
3082 
3083  /*
3084  * To minimize the time spent modifying the PgBackendStatus entry, and
3085  * avoid risk of errors inside the critical section, we first copy the
3086  * shared-memory struct to a local variable, then modify the data in the
3087  * local variable, then copy the local variable back to shared memory.
3088  * Only the last step has to be inside the critical section.
3089  *
3090  * Most of the data we copy from shared memory is just going to be
3091  * overwritten, but the struct's not so large that it's worth the
3092  * maintenance hassle to copy only the needful fields.
3093  */
3094  memcpy(&lbeentry,
3095  unvolatize(PgBackendStatus *, vbeentry),
3096  sizeof(PgBackendStatus));
3097 
3098  /* These structs can just start from zeroes each time, though */
3099 #ifdef USE_SSL
3100  memset(&lsslstatus, 0, sizeof(lsslstatus));
3101 #endif
3102 #ifdef ENABLE_GSS
3103  memset(&lgssstatus, 0, sizeof(lgssstatus));
3104 #endif
3105 
3106  /*
3107  * Now fill in all the fields of lbeentry, except for strings that are
3108  * out-of-line data. Those have to be handled separately, below.
3109  */
3110  lbeentry.st_procpid = MyProcPid;
3111  lbeentry.st_backendType = MyBackendType;
3113  lbeentry.st_activity_start_timestamp = 0;
3114  lbeentry.st_state_start_timestamp = 0;
3115  lbeentry.st_xact_start_timestamp = 0;
3116  lbeentry.st_databaseid = MyDatabaseId;
3117 
3118  /* We have userid for client-backends, wal-sender and bgworker processes */
3119  if (lbeentry.st_backendType == B_BACKEND
3120  || lbeentry.st_backendType == B_WAL_SENDER
3121  || lbeentry.st_backendType == B_BG_WORKER)
3122  lbeentry.st_userid = GetSessionUserId();
3123  else
3124  lbeentry.st_userid = InvalidOid;
3125 
3126  /*
3127  * We may not have a MyProcPort (eg, if this is the autovacuum process).
3128  * If so, use all-zeroes client address, which is dealt with specially in
3129  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
3130  */
3131  if (MyProcPort)
3132  memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
3133  sizeof(lbeentry.st_clientaddr));
3134  else
3135  MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
3136 
3137 #ifdef USE_SSL
3139  {
3140  lbeentry.st_ssl = true;
3148  }
3149  else
3150  {
3151  lbeentry.st_ssl = false;
3152  }
3153 #else
3154  lbeentry.st_ssl = false;
3155 #endif
3156 
3157 #ifdef ENABLE_GSS
3158  if (MyProcPort && MyProcPort->gss != NULL)
3159  {
3160  lbeentry.st_gss = true;
3161  lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
3162  lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
3163 
3164  if (lgssstatus.gss_auth)
3166  }
3167  else
3168  {
3169  lbeentry.st_gss = false;
3170  }
3171 #else
3172  lbeentry.st_gss = false;
3173 #endif
3174 
3175  lbeentry.st_state = STATE_UNDEFINED;
3178 
3179  /*
3180  * we don't zero st_progress_param here to save cycles; nobody should
3181  * examine it until st_progress_command has been set to something other
3182  * than PROGRESS_COMMAND_INVALID
3183  */
3184 
3185  /*
3186  * We're ready to enter the critical section that fills the shared-memory
3187  * status entry. We follow the protocol of bumping st_changecount before
3188  * and after; and make sure it's even afterwards. We use a volatile
3189  * pointer here to ensure the compiler doesn't try to get cute.
3190  */
3191  PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
3192 
3193  /* make sure we'll memcpy the same st_changecount back */
3194  lbeentry.st_changecount = vbeentry->st_changecount;
3195 
3196  memcpy(unvolatize(PgBackendStatus *, vbeentry),
3197  &lbeentry,
3198  sizeof(PgBackendStatus));
3199 
3200  /*
3201  * We can write the out-of-line strings and structs using the pointers
3202  * that are in lbeentry; this saves some de-volatilizing messiness.
3203  */
3204  lbeentry.st_appname[0] = '\0';
3207  NAMEDATALEN);
3208  else
3209  lbeentry.st_clienthostname[0] = '\0';
3210  lbeentry.st_activity_raw[0] = '\0';
3211  /* Also make sure the last byte in each string area is always 0 */
3212  lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
3213  lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
3215 
3216 #ifdef USE_SSL
3217  memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
3218 #endif
3219 #ifdef ENABLE_GSS
3220  memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
3221 #endif
3222 
3223  PGSTAT_END_WRITE_ACTIVITY(vbeentry);
3224 
3225  /* Update app name to current GUC setting */
3226  if (application_name)
3228 }
char ssl_issuer_dn[NAMEDATALEN]
Definition: pgstat.h:1108
char gss_princ[NAMEDATALEN]
Definition: pgstat.h:1122
bool ssl_compression
Definition: pgstat.h:1097
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:1099
Oid st_progress_command_target
Definition: pgstat.h:1212
int MyProcPid
Definition: globals.c:40
struct Port * MyProcPort
Definition: globals.c:43
const char * be_gssapi_get_princ(Port *port)
BackendType MyBackendType
Definition: miscinit.c:62
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:1170
char ssl_client_dn[NAMEDATALEN]
Definition: pgstat.h:1100
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:1098
SockAddr st_clientaddr
Definition: pgstat.h:1176
#define MemSet(start, val, len)
Definition: c.h:950
bool ssl_in_use
Definition: libpq-be.h:190
ProgressCommandType st_progress_command
Definition: pgstat.h:1211
char ssl_client_serial[NAMEDATALEN]
Definition: pgstat.h:1106
BackendState st_state
Definition: pgstat.h:1188
char * st_clienthostname
Definition: pgstat.h:1177
Oid GetSessionUserId(void)
Definition: miscinit.c:510
Oid st_databaseid
Definition: pgstat.h:1174
#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:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
char * st_activity_raw
Definition: pgstat.h:1200
int pgstat_track_activity_query_size
Definition: pgstat.c:128
TimestampTz st_state_start_timestamp
Definition: pgstat.h:1171
char * st_appname
Definition: pgstat.h:1191
bool be_gssapi_get_enc(Port *port)
TimestampTz MyStartTimestamp
Definition: globals.c:42
int be_tls_get_cipher_bits(Port *port)
Oid MyDatabaseId
Definition: globals.c:85
BackendType st_backendType
Definition: pgstat.h:1165
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3451
#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:746
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:563
void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
void * gss
Definition: libpq-be.h:184
#define unvolatize(underlying_type, expr)
Definition: c.h:1187
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:1169
int st_changecount
Definition: pgstat.h:1159
const char * be_tls_get_cipher(Port *port)
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:1168
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1181
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1185
bool be_gssapi_get_auth(Port *port)

◆ pgstat_clear_snapshot()

void pgstat_clear_snapshot ( void  )

Definition at line 6141 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

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

6142 {
6143  /* Release memory, if any was allocated */
6144  if (pgStatLocalContext)
6146 
6147  /* Reset variables */
6148  pgStatLocalContext = NULL;
6149  pgStatDBHash = NULL;
6150  localBackendStatusTable = NULL;
6151  localNumBackends = 0;
6152 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:274
static HTAB * pgStatDBHash
Definition: pgstat.c:271
static int localNumBackends
Definition: pgstat.c:277
static MemoryContext pgStatLocalContext
Definition: pgstat.c:270

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

Definition at line 7051 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().

7052 {
7053  char *activity;
7054  int rawlen;
7055  int cliplen;
7056 
7057  /*
7058  * Some callers, like pgstat_get_backend_current_activity(), do not
7059  * guarantee that the buffer isn't concurrently modified. We try to take
7060  * care that the buffer is always terminated by a NUL byte regardless, but
7061  * let's still be paranoid about the string's length. In those cases the
7062  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
7063  * large.
7064  */
7065  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
7066 
7067  /* now double-guaranteed to be NUL terminated */
7068  rawlen = strlen(activity);
7069 
7070  /*
7071  * All supported server-encodings make it possible to determine the length
7072  * of a multi-byte character from its first byte (this is not the case for
7073  * client encodings, see GB18030). As st_activity is always stored using
7074  * server encoding, this allows us to perform multi-byte aware truncation,
7075  * even if the string earlier was truncated in the middle of a multi-byte
7076  * character.
7077  */
7078  cliplen = pg_mbcliplen(activity, rawlen,
7080 
7081  activity[cliplen] = '\0';
7082 
7083  return activity;
7084 }
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:128
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 1248 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().

1249 {
1250  HTAB *htab;
1251  HASHCTL hash_ctl;
1252  Relation rel;
1253  TableScanDesc scan;
1254  HeapTuple tup;
1255  Snapshot snapshot;
1256 
1257  memset(&hash_ctl, 0, sizeof(hash_ctl));
1258  hash_ctl.keysize = sizeof(Oid);
1259  hash_ctl.entrysize = sizeof(Oid);
1260  hash_ctl.hcxt = CurrentMemoryContext;
1261  htab = hash_create("Temporary table of OIDs",
1263  &hash_ctl,
1265 
1266  rel = table_open(catalogid, AccessShareLock);
1267  snapshot = RegisterSnapshot(GetLatestSnapshot());
1268  scan = table_beginscan(rel, snapshot, 0, NULL);
1269  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1270  {
1271  Oid thisoid;
1272  bool isnull;
1273 
1274  thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1275  Assert(!isnull);
1276 
1278 
1279  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1280  }
1281  table_endscan(scan);
1282  UnregisterSnapshot(snapshot);
1284 
1285  return htab;
1286 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define HASH_CONTEXT
Definition: hsearch.h:91
#define HASH_ELEM
Definition: hsearch.h:85
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
MemoryContext hcxt
Definition: hsearch.h:77
#define RelationGetDescr(relation)
Definition: rel.h:482
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:105
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:72
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:218
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:755
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
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:86
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
Size keysize
Definition: hsearch.h:71
#define Assert(condition)
Definition: c.h:746
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
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 2157 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().

2158 {
2159  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2160 
2161  if (pgstat_info != NULL)
2162  {
2163  /* We have to log the effect at the proper transactional level */
2164  int nest_level = GetCurrentTransactionNestLevel();
2165 
2166  if (pgstat_info->trans == NULL ||
2167  pgstat_info->trans->nest_level != nest_level)
2168  add_tabstat_xact_level(pgstat_info, nest_level);
2169 
2170  pgstat_info->trans->tuples_deleted++;
2171  }
2172 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:176
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2084
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164

◆ pgstat_count_heap_insert()

void pgstat_count_heap_insert ( Relation  rel,
PgStat_Counter  n 
)

Definition at line 2111 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().

2112 {
2113  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2114 
2115  if (pgstat_info != NULL)
2116  {
2117  /* We have to log the effect at the proper transactional level */
2118  int nest_level = GetCurrentTransactionNestLevel();
2119 
2120  if (pgstat_info->trans == NULL ||
2121  pgstat_info->trans->nest_level != nest_level)
2122  add_tabstat_xact_level(pgstat_info, nest_level);
2123 
2124  pgstat_info->trans->tuples_inserted += n;
2125  }
2126 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:174
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2084
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164

◆ pgstat_count_heap_update()

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

Definition at line 2132 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().

2133 {
2134  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2135 
2136  if (pgstat_info != NULL)
2137  {
2138  /* We have to log the effect at the proper transactional level */
2139  int nest_level = GetCurrentTransactionNestLevel();
2140 
2141  if (pgstat_info->trans == NULL ||
2142  pgstat_info->trans->nest_level != nest_level)
2143  add_tabstat_xact_level(pgstat_info, nest_level);
2144 
2145  pgstat_info->trans->tuples_updated++;
2146 
2147  /* t_tuples_hot_updated is nontransactional, so just advance it */
2148  if (hot)
2149  pgstat_info->t_counts.t_tuples_hot_updated++;
2150  }
2151 }
PgStat_Counter tuples_updated
Definition: pgstat.h:175
PgStat_Counter t_tuples_hot_updated
Definition: pgstat.h:113
PgStat_TableCounts t_counts
Definition: pgstat.h:165
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2084
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164

◆ pgstat_count_slru_flush()

void pgstat_count_slru_flush ( int  slru_idx)

Definition at line 7233 of file pgstat.c.

References PgStat_MsgSLRU::m_flush, and slru_entry().

Referenced by SimpleLruWriteAll().

7234 {
7235  slru_entry(slru_idx)->m_flush += 1;
7236 }
PgStat_Counter m_flush
Definition: pgstat.h:478
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185

◆ pgstat_count_slru_page_exists()

void pgstat_count_slru_page_exists ( int  slru_idx)

Definition at line 7215 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_exists, and slru_entry().

Referenced by SimpleLruDoesPhysicalPageExist().

7216 {
7217  slru_entry(slru_idx)->m_blocks_exists += 1;
7218 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_blocks_exists
Definition: pgstat.h:477

◆ pgstat_count_slru_page_hit()

void pgstat_count_slru_page_hit ( int  slru_idx)

Definition at line 7209 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_hit, and slru_entry().

Referenced by SimpleLruReadPage(), and SimpleLruReadPage_ReadOnly().

7210 {
7211  slru_entry(slru_idx)->m_blocks_hit += 1;
7212 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_blocks_hit
Definition: pgstat.h:474

◆ pgstat_count_slru_page_read()

void pgstat_count_slru_page_read ( int  slru_idx)

Definition at line 7221 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_read, and slru_entry().

Referenced by SimpleLruReadPage().

7222 {
7223  slru_entry(slru_idx)->m_blocks_read += 1;
7224 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_blocks_read
Definition: pgstat.h:475

◆ pgstat_count_slru_page_written()

void pgstat_count_slru_page_written ( int  slru_idx)

Definition at line 7227 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_written, and slru_entry().

Referenced by SlruPhysicalWritePage().

7228 {
7229  slru_entry(slru_idx)->m_blocks_written += 1;
7230 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_blocks_written
Definition: pgstat.h:476

◆ pgstat_count_slru_page_zeroed()

void pgstat_count_slru_page_zeroed ( int  slru_idx)

Definition at line 7203 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_zeroed, and slru_entry().

Referenced by SimpleLruZeroPage().

7204 {
7205  slru_entry(slru_idx)->m_blocks_zeroed += 1;
7206 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_blocks_zeroed
Definition: pgstat.h:473

◆ pgstat_count_slru_truncate()

void pgstat_count_slru_truncate ( int  slru_idx)

Definition at line 7239 of file pgstat.c.

References PgStat_MsgSLRU::m_truncate, and slru_entry().

Referenced by SimpleLruTruncate().

7240 {
7241  slru_entry(slru_idx)->m_truncate += 1;
7242 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:7185
PgStat_Counter m_truncate
Definition: pgstat.h:479

◆ pgstat_count_truncate()

void pgstat_count_truncate ( Relation  rel)

Definition at line 2212 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().

2213 {
2214  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2215 
2216  if (pgstat_info != NULL)
2217  {
2218  /* We have to log the effect at the proper transactional level */
2219  int nest_level = GetCurrentTransactionNestLevel();
2220 
2221  if (pgstat_info->trans == NULL ||
2222  pgstat_info->trans->nest_level != nest_level)
2223  add_tabstat_xact_level(pgstat_info, nest_level);
2224 
2225  pgstat_truncate_save_counters(pgstat_info->trans);
2226  pgstat_info->trans->tuples_inserted = 0;
2227  pgstat_info->trans->tuples_updated = 0;
2228  pgstat_info->trans->tuples_deleted = 0;
2229  }
2230 }
PgStat_Counter tuples_updated
Definition: pgstat.h:175
PgStat_Counter tuples_inserted
Definition: pgstat.h:174
PgStat_Counter tuples_deleted
Definition: pgstat.h:176
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:2084
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:164
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2183

◆ pgstat_db_requested()

static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 7024 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

7025 {
7026  /*
7027  * If any requests are outstanding at all, we should write the stats for
7028  * shared catalogs (the "database" with OID 0). This ensures that
7029  * backends will see up-to-date stats for shared catalogs, even though
7030  * they send inquiry messages mentioning only their own DB.
7031  */
7032  if (databaseid == InvalidOid && pending_write_requests != NIL)
7033  return true;
7034 
7035  /* Search to see if there's an open request to write this database. */
7036  if (list_member_oid(pending_write_requests, databaseid))
7037  return true;
7038 
7039  return false;
7040 }
#define NIL
Definition: pg_list.h:65
static List * pending_write_requests
Definition: pgstat.c:296
#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 1298 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().

1299 {
1300  PgStat_MsgDropdb msg;
1301 
1303  return;
1304 
1306  msg.m_databaseid = databaseid;
1307  pgstat_send(&msg, sizeof(msg));
1308 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4492
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:176
Oid m_databaseid
Definition: pgstat.h:313
PgStat_MsgHdr m_hdr
Definition: pgstat.h:312
#define PGINVALID_SOCKET
Definition: port.h:33
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4479

◆ pgstat_end_function_usage()

void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1861 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().

1862 {
1863  PgStat_FunctionCounts *fs = fcu->fs;
1864  instr_time f_total;
1865  instr_time f_others;
1866  instr_time f_self;
1867 
1868  /* stats not wanted? */
1869  if (fs == NULL)
1870  return;
1871 
1872  /* total elapsed time in this function call */
1873  INSTR_TIME_SET_CURRENT(f_total);
1874  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1875 
1876  /* self usage: elapsed minus anything already charged to other calls */
1877  f_others = total_func_time;
1878  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1879  f_self = f_total;
1880  INSTR_TIME_SUBTRACT(f_self, f_others);
1881 
1882  /* update backend-wide total time */
1884 
1885  /*
1886  * Compute the new f_total_time as the total elapsed time added to the
1887  * pre-call value of f_total_time. This is necessary to avoid
1888  * double-counting any time taken by recursive calls of myself. (We do
1889  * not need any similar kluge for self time, since that already excludes
1890  * any recursive calls.)
1891  */
1892  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1893 
1894  /* update counters in function stats table */
1895  if (finalize)
1896  fs->f_numcalls++;
1897  fs->f_total_time = f_total;
1898  INSTR_TIME_ADD(fs->f_self_time, f_self);
1899 
1900  /* indicate that we have something to send */
1901  have_function_stats = true;
1902 }
instr_time f_self_time
Definition: pgstat.h:539
instr_time save_total
Definition: pgstat.h:1316
struct timeval instr_time
Definition: instr_time.h:150
instr_time f_total_time
Definition: pgstat.h:538
PgStat_FunctionCounts * fs
Definition: pgstat.h:1312
PgStat_Counter f_numcalls
Definition: pgstat.h:537
#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:303
static bool have_function_stats
Definition: pgstat.c:230
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1314

◆ pgstat_fetch_global()

◆ pgstat_fetch_replslot()

PgStat_ReplSlotStats* pgstat_fetch_replslot ( int *  nslots_p)

Definition at line 2833 of file pgstat.c.

References backend_read_statsfile(), nReplSlotStats, and replSlotStats.

Referenced by pg_stat_get_replication_slots().

2834 {
2836 
2837  *nslots_p = nReplSlotStats;
2838  return replSlotStats;
2839 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
static int nReplSlotStats
Definition: pgstat.c:289
static PgStat_ReplSlotStats * replSlotStats
Definition: pgstat.c:288

◆ pgstat_fetch_slru()

PgStat_SLRUStats* pgstat_fetch_slru ( void  )

Definition at line 2816 of file pgstat.c.

References backend_read_statsfile(), and slruStats.

Referenced by pg_stat_get_slru().

2817 {
2819 
2820  return slruStats;
2821 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
static PgStat_SLRUStats slruStats[SLRU_NUM_ELEMENTS]
Definition: pgstat.c:287

◆ pgstat_fetch_stat_archiver()

PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2767 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2768 {
2770 
2771  return &archiverStats;
2772 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:284

◆ pgstat_fetch_stat_beentry()

◆ pgstat_fetch_stat_dbentry()

PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

Definition at line 2595 of file pgstat.c.

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

Referenced by do_autovacuum(), do_start_worker(), 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_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 table_recheck_autovac().

2596 {
2597  /*
2598  * If not done for this transaction, read the statistics collector stats
2599  * file into some hash tables.
2600  */
2602 
2603  /*
2604  * Lookup the requested database; return NULL if not found
2605  */
2607  (void *) &dbid,
2608  HASH_FIND, NULL);
2609 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
static HTAB * pgStatDBHash
Definition: pgstat.c:271

◆ pgstat_fetch_stat_funcentry()

PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

Definition at line 2678 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().

2679 {
2680  PgStat_StatDBEntry *dbentry;
2681  PgStat_StatFuncEntry *funcentry = NULL;
2682 
2683  /* load the stats file if needed */
2685 
2686  /* Lookup our database, then find the requested function. */
2688  if (dbentry != NULL && dbentry->functions != NULL)
2689  {
2690  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2691  (void *) &func_id,
2692  HASH_FIND, NULL);
2693  }
2694 
2695  return funcentry;
2696 }
HTAB * functions
Definition: pgstat.h:705
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2595
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
Oid MyDatabaseId
Definition: globals.c:85

◆ pgstat_fetch_stat_local_beentry()

LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2732 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2733 {
2735 
2736  if (beid < 1 || beid > localNumBackends)
2737  return NULL;
2738 
2739  return &localBackendStatusTable[beid - 1];
2740 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3507
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:274
static int localNumBackends
Definition: pgstat.c:277

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

Definition at line 2751 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().

2752 {
2754 
2755  return localNumBackends;
2756 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3507
static int localNumBackends
Definition: pgstat.c:277

◆ pgstat_fetch_stat_tabentry()

PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

Definition at line 2622 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().

2623 {
2624  Oid dbid;
2625  PgStat_StatDBEntry *dbentry;
2626  PgStat_StatTabEntry *tabentry;
2627 
2628  /*
2629  * If not done for this transaction, read the statistics collector stats
2630  * file into some hash tables.
2631  */
2633 
2634  /*
2635  * Lookup our database, then look in its table hash table.
2636  */
2637  dbid = MyDatabaseId;
2639  (void *) &dbid,
2640  HASH_FIND, NULL);
2641  if (dbentry != NULL && dbentry->tables != NULL)
2642  {
2643  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2644  (void *) &relid,
2645  HASH_FIND, NULL);
2646  if (tabentry)
2647  return tabentry;
2648  }
2649 
2650  /*
2651  * If we didn't find it, maybe it's a shared table.
2652  */
2653  dbid = InvalidOid;
2655  (void *) &dbid,
2656  HASH_FIND, NULL);
2657  if (dbentry != NULL && dbentry->tables != NULL)
2658  {
2659  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2660  (void *) &relid,
2661  HASH_FIND, NULL);
2662  if (tabentry)
2663  return tabentry;
2664  }
2665 
2666  return NULL;
2667 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:5987
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pgStatDBHash
Definition: pgstat.c:271

◆ pgstat_fetch_stat_wal()

PgStat_WalStats* pgstat_fetch_stat_wal ( void  )

Definition at line 2800 of file pgstat.c.

References backend_read_statsfile(), and walStats.

Referenced by pg_stat_get_wal().

2801 {
2803 
2804  return &walStats;
2805 }
static PgStat_WalStats walStats
Definition: pgstat.c:286
static void backend_read_statsfile(void)
Definition: pgstat.c:5987

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 4330 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().

4331 {
4332  PgBackendStatus *beentry;
4333  int i;
4334 
4335  beentry = BackendStatusArray;
4336  for (i = 1; i <= MaxBackends; i++)
4337  {
4338  /*
4339  * Although we expect the target backend's entry to be stable, that
4340  * doesn't imply that anyone else's is. To avoid identifying the
4341  * wrong backend, while we check for a match to the desired PID we
4342  * must follow the protocol of retrying if st_changecount changes
4343  * while we examine the entry, or if it's odd. (This might be
4344  * unnecessary, since fetching or storing an int is almost certainly
4345  * atomic, but let's play it safe.) We use a volatile pointer here to
4346  * ensure the compiler doesn't try to get cute.
4347  */
4348  volatile PgBackendStatus *vbeentry = beentry;
4349  bool found;
4350 
4351  for (;;)
4352  {
4353  int before_changecount;
4354  int after_changecount;
4355 
4356  pgstat_begin_read_activity(vbeentry, before_changecount);
4357 
4358  found = (vbeentry->st_procpid == pid);
4359 
4360  pgstat_end_read_activity(vbeentry, after_changecount);
4361 
4362  if (pgstat_read_activity_complete(before_changecount,
4363  after_changecount))
4364  break;
4365 
4366  /* Make sure we can break out of loop if stuck... */
4368  }
4369 
4370  if (found)
4371  {
4372  /* Now it is safe to use the non-volatile pointer */
4373  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4374  return "<insufficient privilege>";
4375  else if (*(beentry->st_activity_raw) == '\0')
4376  return "<command string not enabled>";
4377  else
4378  {
4379  /* this'll leak a bit of memory, but that seems acceptable */
4380  return pgstat_clip_activity(beentry->st_activity_raw);
4381  }
4382  }
4383 
4384  beentry++;
4385  }
4386 
4387  /* If we get here, caller is in error ... */
4388  return "<backend information not available>";
4389 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2846
Oid GetUserId(void)
Definition: miscinit.c:476
bool superuser(void)
Definition: superuser.c:46
int MaxBackends
Definition: globals.c:136
char * st_activity_raw
Definition: pgstat.h:1200
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1266
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1260
char * pgstat_clip_activity(const char *raw_activity)
Definition: pgstat.c:7051
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1272

◆ pgstat_get_crashed_backend_activity()

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

Definition at line 4408 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().

4409 {
4410  volatile PgBackendStatus *beentry;
4411  int i;
4412 
4413  beentry = BackendStatusArray;
4414 
4415  /*
4416  * We probably shouldn't get here before shared memory has been set up,
4417  * but be safe.
4418  */
4419  if (beentry == NULL || BackendActivityBuffer == NULL)
4420  return NULL;
4421 
4422  for (i = 1; i <= MaxBackends; i++)
4423  {
4424  if (beentry->st_procpid == pid)
4425  {
4426  /* Read pointer just once, so it can't change after validation */
4427  const char *activity = beentry->st_activity_raw;
4428  const char *activity_last;
4429 
4430  /*
4431  * We mustn't access activity string before we verify that it
4432  * falls within the BackendActivityBuffer. To make sure that the
4433  * entire string including its ending is contained within the
4434  * buffer, subtract one activity length from the buffer size.
4435  */
4438 
4439  if (activity < BackendActivityBuffer ||
4440  activity > activity_last)
4441  return NULL;
4442 
4443  /* If no string available, no point in a report */
4444  if (activity[0] == '\0')
4445  return NULL;
4446 
4447  /*
4448  * Copy only ASCII-safe characters so we don't run into encoding
4449  * problems when reporting the message; and be sure not to run off
4450  * the end of memory. As only ASCII characters are reported, it
4451  * doesn't seem necessary to perform multibyte aware clipping.
4452  */
4453  ascii_safe_strlcpy(buffer, activity,
4454  Min(buflen, pgstat_track_activity_query_size));
4455 
4456  return buffer;
4457  }
4458 
4459  beentry++;
4460  }
4461 
4462  /* PID not found */
4463  return NULL;
4464 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2846
static char * BackendActivityBuffer
Definition: pgstat.c:2850
#define Min(x, y)
Definition: c.h:928
static Size BackendActivityBufferSize
Definition: pgstat.c:2851
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
int MaxBackends
Definition: globals.c:136
char * st_activity_raw
Definition: pgstat.h:1200
int pgstat_track_activity_query_size
Definition: pgstat.c:128
int i

◆ pgstat_get_db_entry()

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

Definition at line 4982 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_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().

4983 {
4984  PgStat_StatDBEntry *result;
4985  bool found;
4986  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4987 
4988  /* Lookup or create the hash table entry for this database */
4990  &databaseid,
4991  action, &found);
4992 
4993  if (!create && !found)
4994  return NULL;
4995 
4996  /*
4997  * If not found, initialize the new one. This creates empty hash tables
4998  * for tables and functions, too.
4999  */
5000  if (!found)
5001  reset_dbentry_counters(result);
5002 
5003  return result;
5004 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4930
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
static HTAB * pgStatDBHash
Definition: pgstat.c:271
HASHACTION
Definition: hsearch.h:101

◆ pgstat_get_tab_entry()

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

Definition at line 5013 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().

5014 {
5015  PgStat_StatTabEntry *result;
5016  bool found;
5017  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
5018 
5019  /* Lookup or create the hash table entry for this table */
5020  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
5021  &tableoid,
5022  action, &found);
5023 
5024  if (!create && !found)
5025  return NULL;
5026 
5027  /* If not found, initialize the new one. */
5028  if (!found)
5029  {
5030  result->numscans = 0;
5031  result->tuples_returned = 0;
5032  result->tuples_fetched = 0;
5033  result->tuples_inserted = 0;
5034  result->tuples_updated = 0;
5035  result->tuples_deleted = 0;
5036  result->tuples_hot_updated = 0;
5037  result->n_live_tuples = 0;
5038  result->n_dead_tuples = 0;
5039  result->changes_since_analyze = 0;
5040  result->inserts_since_vacuum = 0;
5041  result->blocks_fetched = 0;
5042  result->blocks_hit = 0;
5043  result->vacuum_timestamp = 0;
5044  result->vacuum_count = 0;
5045  result->autovac_vacuum_timestamp = 0;
5046  result->autovac_vacuum_count = 0;
5047  result->analyze_timestamp = 0;
5048  result->analyze_count = 0;
5049  result->autovac_analyze_timestamp = 0;
5050  result->autovac_analyze_count = 0;
5051  }
5052 
5053  return result;
5054 }
PgStat_Counter analyze_count
Definition: pgstat.h:740
PgStat_Counter tuples_returned
Definition: pgstat.h:719
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:741
PgStat_Counter vacuum_count
Definition: pgstat.h:736
PgStat_Counter numscans
Definition: pgstat.h:717
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:725
PgStat_Counter tuples_inserted
Definition: pgstat.h:722
PgStat_Counter n_live_tuples
Definition: pgstat.h:727
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:730
TimestampTz vacuum_timestamp
Definition: pgstat.h:735
PgStat_Counter n_dead_tuples
Definition: pgstat.h:728
PgStat_Counter tuples_fetched
Definition: pgstat.h:720
PgStat_Counter blocks_hit
Definition: pgstat.h:733
TimestampTz analyze_timestamp
Definition: pgstat.h:739
PgStat_Counter changes_since_analyze
Definition: pgstat.h:729
PgStat_Counter tuples_deleted
Definition: pgstat.h:724
PgStat_Counter tuples_updated
Definition: pgstat.h:723
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:737
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:742
PgStat_Counter blocks_fetched
Definition: pgstat.h:732
HASHACTION
Definition: hsearch.h:101
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:738

◆ pgstat_get_wait_activity()

static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

Definition at line 3791 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().

3792 {
3793  const char *event_name = "unknown wait event";
3794 
3795  switch (w)
3796  {
3798  event_name = "ArchiverMain";
3799  break;
3801  event_name = "AutoVacuumMain";
3802  break;
3804  event_name = "BgWriterHibernate";
3805  break;
3807  event_name = "BgWriterMain";
3808  break;
3810  event_name = "CheckpointerMain";
3811  break;
3813  event_name = "LogicalApplyMain";
3814  break;
3816  event_name = "LogicalLauncherMain";
3817  break;
3819  event_name = "PgStatMain";
3820  break;
3822  event_name = "RecoveryWalStream";
3823  break;
3825  event_name = "SysLoggerMain";
3826  break;
3828  event_name = "WalReceiverMain";
3829  break;
3831  event_name = "WalSenderMain";
3832  break;
3834  event_name = "WalWriterMain";
3835  break;
3836  /* no default case, so that compiler will warn */
3837  }
3838 
3839  return event_name;
3840 }

◆ pgstat_get_wait_client()

static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3849 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().

3850 {
3851  const char *event_name = "unknown wait event";
3852 
3853  switch (w)
3854  {
3856  event_name = "ClientRead";
3857  break;
3859  event_name = "ClientWrite";
3860  break;
3862  event_name = "GSSOpenServer";
3863  break;
3865  event_name = "LibPQWalReceiverConnect";
3866  break;
3868  event_name = "LibPQWalReceiverReceive";
3869  break;
3871  event_name = "SSLOpenServer";
3872  break;
3874  event_name = "WalReceiverWaitStart";
3875  break;
3877  event_name = "WalSenderWaitForWAL";
3878  break;
3880  event_name = "WalSenderWriteData";
3881  break;
3882  /* no default case, so that compiler will warn */
3883  }
3884 
3885  return event_name;
3886 }

◆ pgstat_get_wait_event()

const char* pgstat_get_wait_event ( uint32  wait_event_info)

Definition at line 3714 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().

3715 {
3716  uint32 classId;
3717  uint16 eventId;
3718  const char *event_name;
3719 
3720  /* report process as not waiting. */
3721  if (wait_event_info == 0)
3722  return NULL;
3723 
3724  classId = wait_event_info & 0xFF000000;
3725  eventId = wait_event_info & 0x0000FFFF;
3726 
3727  switch (classId)
3728  {
3729  case PG_WAIT_LWLOCK:
3730  event_name = GetLWLockIdentifier(classId, eventId);
3731  break;
3732  case PG_WAIT_LOCK:
3733  event_name = GetLockNameFromTagType(eventId);
3734  break;
3735  case PG_WAIT_BUFFER_PIN:
3736  event_name = "BufferPin";
3737  break;
3738  case PG_WAIT_ACTIVITY:
3739  {
3740  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3741 
3742  event_name = pgstat_get_wait_activity(w);
3743  break;
3744  }
3745  case PG_WAIT_CLIENT:
3746  {
3747  WaitEventClient w = (WaitEventClient) wait_event_info;
3748 
3749  event_name = pgstat_get_wait_client(w);
3750  break;
3751  }
3752  case PG_WAIT_EXTENSION:
3753  event_name = "Extension";
3754  break;
3755  case PG_WAIT_IPC:
3756  {
3757  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3758 
3759  event_name = pgstat_get_wait_ipc(w);
3760  break;
3761  }
3762  case PG_WAIT_TIMEOUT:
3763  {
3764  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3765 
3766  event_name = pgstat_get_wait_timeout(w);
3767  break;
3768  }
3769  case PG_WAIT_IO:
3770  {
3771  WaitEventIO w = (WaitEventIO) wait_event_info;
3772 
3773  event_name = pgstat_get_wait_io(w);
3774  break;
3775  }
3776  default:
3777  event_name = "unknown wait event";
3778  break;
3779  }
3780 
3781  return event_name;
3782 }
#define PG_WAIT_LOCK
Definition: pgstat.h:856
WaitEventIPC
Definition: pgstat.h:918
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:4040
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3895
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:858
#define PG_WAIT_IO
Definition: pgstat.h:863
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3791
unsigned short uint16
Definition: c.h:374
#define PG_WAIT_CLIENT
Definition: pgstat.h:859
WaitEventClient
Definition: pgstat.h:898
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3849
unsigned int uint32
Definition: c.h:375
WaitEventTimeout
Definition: pgstat.h:970
#define PG_WAIT_EXTENSION
Definition: pgstat.h:860
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:857
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1190
WaitEventIO
Definition: pgstat.h:985
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:862
#define PG_WAIT_IPC
Definition: pgstat.h:861
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:809
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:4074
#define PG_WAIT_LWLOCK
Definition: pgstat.h:855
WaitEventActivity
Definition: pgstat.h:873

◆ pgstat_get_wait_event_type()

const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

Definition at line 3659 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().

3660 {
3661  uint32 classId;
3662  const char *event_type;
3663 
3664  /* report process as not waiting. */
3665  if (wait_event_info == 0)
3666  return NULL;
3667 
3668  classId = wait_event_info & 0xFF000000;
3669 
3670  switch (classId)
3671  {
3672  case PG_WAIT_LWLOCK:
3673  event_type = "LWLock";
3674  break;
3675  case PG_WAIT_LOCK:
3676  event_type = "Lock";
3677  break;
3678  case PG_WAIT_BUFFER_PIN:
3679  event_type = "BufferPin";
3680  break;
3681  case PG_WAIT_ACTIVITY:
3682  event_type = "Activity";
3683  break;
3684  case PG_WAIT_CLIENT:
3685  event_type = "Client";
3686  break;
3687  case PG_WAIT_EXTENSION:
3688  event_type = "Extension";
3689  break;
3690  case PG_WAIT_IPC:
3691  event_type = "IPC";
3692  break;
3693  case PG_WAIT_TIMEOUT:
3694  event_type = "Timeout";
3695  break;
3696  case PG_WAIT_IO:
3697  event_type = "IO";
3698  break;
3699  default:
3700  event_type = "???";
3701  break;
3702  }
3703 
3704  return event_type;
3705 }
#define PG_WAIT_LOCK
Definition: pgstat.h:856
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:858
#define PG_WAIT_IO
Definition: pgstat.h:863
#define PG_WAIT_CLIENT
Definition: pgstat.h:859
unsigned int uint32
Definition: c.h:375
#define PG_WAIT_EXTENSION
Definition: pgstat.h:860
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:857
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:862
#define PG_WAIT_IPC
Definition: pgstat.h:861
#define PG_WAIT_LWLOCK
Definition: pgstat.h:855

◆ pgstat_get_wait_io()

static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

Definition at line 4074 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().

4075 {
4076  const char *event_name = "unknown wait event";
4077 
4078  switch (w)
4079  {
4081  event_name = "BaseBackupRead";
4082  break;
4084  event_name = "BufFileRead";
4085  break;
4087  event_name = "BufFileWrite";
4088  break;
4090  event_name = "BufFileTruncate";
4091  break;
4093  event_name = "ControlFileRead";
4094  break;
4096  event_name = "ControlFileSync";
4097  break;
4099  event_name = "ControlFileSyncUpdate";
4100  break;
4102  event_name = "ControlFileWrite";
4103  break;
4105  event_name = "ControlFileWriteUpdate";
4106  break;
4108  event_name = "CopyFileRead";
4109  break;
4111  event_name = "CopyFileWrite";
4112  break;
4114  event_name = "DataFileExtend";
4115  break;
4117  event_name = "DataFileFlush";
4118  break;
4120  event_name = "DataFileImmediateSync";
4121  break;
4123  event_name = "DataFilePrefetch";
4124  break;
4126  event_name = "DataFileRead";
4127  break;
4129  event_name = "DataFileSync";
4130  break;
4132  event_name = "DataFileTruncate";
4133  break;
4135  event_name = "DataFileWrite";
4136  break;
4138  event_name = "DSMFillZeroWrite";
4139  break;
4141  event_name = "LockFileAddToDataDirRead";
4142  break;
4144  event_name = "LockFileAddToDataDirSync";
4145  break;
4147  event_name = "LockFileAddToDataDirWrite";
4148  break;
4150  event_name = "LockFileCreateRead";
4151  break;
4153  event_name = "LockFileCreateSync";
4154  break;
4156  event_name = "LockFileCreateWrite";
4157  break;
4159  event_name = "LockFileReCheckDataDirRead";
4160  break;
4162  event_name = "LogicalRewriteCheckpointSync";
4163  break;
4165  event_name = "LogicalRewriteMappingSync";
4166  break;
4168  event_name = "LogicalRewriteMappingWrite";
4169  break;
4171  event_name = "LogicalRewriteSync";
4172  break;
4174  event_name = "LogicalRewriteTruncate";
4175  break;
4177  event_name = "LogicalRewriteWrite";
4178  break;
4180  event_name = "RelationMapRead";
4181  break;
4183  event_name = "RelationMapSync";
4184  break;
4186  event_name = "RelationMapWrite";
4187  break;
4189  event_name = "ReorderBufferRead";
4190  break;
4192  event_name = "ReorderBufferWrite";
4193  break;
4195  event_name = "ReorderLogicalMappingRead";
4196  break;
4198  event_name = "ReplicationSlotRead";
4199  break;
4201  event_name = "ReplicationSlotRestoreSync";
4202  break;
4204  event_name = "ReplicationSlotSync";
4205  break;
4207  event_name = "ReplicationSlotWrite";
4208  break;
4210  event_name = "SLRUFlushSync";
4211  break;
4212  case WAIT_EVENT_SLRU_READ:
4213  event_name = "SLRURead";
4214  break;
4215  case WAIT_EVENT_SLRU_SYNC:
4216  event_name = "SLRUSync";
4217  break;
4218  case WAIT_EVENT_SLRU_WRITE:
4219  event_name = "SLRUWrite";
4220  break;
4222  event_name = "SnapbuildRead";
4223  break;
4225  event_name = "SnapbuildSync";
4226  break;
4228  event_name = "SnapbuildWrite";
4229  break;
4231  event_name = "TimelineHistoryFileSync";
4232  break;
4234  event_name = "TimelineHistoryFileWrite";
4235  break;
4237  event_name = "TimelineHistoryRead";
4238  break;
4240  event_name = "TimelineHistorySync";
4241  break;
4243  event_name = "TimelineHistoryWrite";
4244  break;
4246  event_name = "TwophaseFileRead";
4247  break;
4249  event_name = "TwophaseFileSync";
4250  break;
4252  event_name = "TwophaseFileWrite";
4253  break;
4255  event_name = "WALSenderTimelineHistoryRead";
4256  break;
4258  event_name = "WALBootstrapSync";
4259  break;
4261  event_name = "WALBootstrapWrite";
4262  break;
4264  event_name = "WALCopyRead";
4265  break;
4267  event_name = "WALCopySync";
4268  break;
4270  event_name = "WALCopyWrite";
4271  break;
4273  event_name = "WALInitSync";
4274  break;
4276  event_name = "WALInitWrite";
4277  break;
4278  case WAIT_EVENT_WAL_READ:
4279  event_name = "WALRead";
4280  break;
4281  case WAIT_EVENT_WAL_SYNC:
4282  event_name = "WALSync";
4283  break;
4285  event_name = "WALSyncMethodAssign";
4286  break;
4287  case WAIT_EVENT_WAL_WRITE:
4288  event_name = "WALWrite";
4289  break;
4291  event_name = "LogicalChangesRead";
4292  break;
4294  event_name = "LogicalChangesWrite";
4295  break;
4297  event_name = "LogicalSubxactRead";
4298  break;
4300  event_name = "LogicalSubxactWrite";
4301  break;
4302 
4303  /* no default case, so that compiler will warn */
4304  }
4305 
4306  return event_name;
4307 }

◆ pgstat_get_wait_ipc()

static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3895 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().

3896 {
3897  const char *event_name = "unknown wait event";
3898 
3899  switch (w)
3900  {
3902  event_name = "BackupWaitWalArchive";
3903  break;
3905  event_name = "BgWorkerShutdown";
3906  break;
3908  event_name = "BgWorkerStartup";
3909  break;
3910  case WAIT_EVENT_BTREE_PAGE:
3911  event_name = "BtreePage";
3912  break;
3914  event_name = "CheckpointDone";
3915  break;
3917  event_name = "CheckpointStart";
3918  break;
3920  event_name = "ExecuteGather";
3921  break;
3923  event_name = "HashBatchAllocate";
3924  break;
3926  event_name = "HashBatchElect";
3927  break;
3929  event_name = "HashBatchLoad";
3930  break;
3932  event_name = "HashBuildAllocate";
3933  break;
3935  event_name = "HashBuildElect";
3936  break;
3938  event_name = "HashBuildHashInner";
3939  break;
3941  event_name = "HashBuildHashOuter";
3942  break;
3944  event_name = "HashGrowBatchesAllocate";
3945  break;
3947  event_name = "HashGrowBatchesDecide";
3948  break;
3950  event_name = "HashGrowBatchesElect";
3951  break;
3953  event_name = "HashGrowBatchesFinish";
3954  break;
3956  event_name = "HashGrowBatchesRepartition";
3957  break;
3959  event_name = "HashGrowBucketsAllocate";
3960  break;
3962  event_name = "HashGrowBucketsElect";
3963  break;
3965  event_name = "HashGrowBucketsReinsert";
3966  break;
3968  event_name = "LogicalSyncData";
3969  break;
3971  event_name = "LogicalSyncStateChange";
3972  break;
3974  event_name = "MessageQueueInternal";
3975  break;
3977  event_name = "MessageQueuePutMessage";
3978  break;
3979  case WAIT_EVENT_MQ_RECEIVE:
3980  event_name = "MessageQueueReceive";
3981  break;
3982  case WAIT_EVENT_MQ_SEND:
3983  event_name = "MessageQueueSend";
3984  break;
3986  event_name = "ParallelBitmapScan";
3987  break;
3989  event_name = "ParallelCreateIndexScan";
3990  break;
3992  event_name = "ParallelFinish";
3993  break;
3995  event_name = "ProcArrayGroupUpdate";
3996  break;
3998  event_name = "ProcSignalBarrier";
3999  break;
4000  case WAIT_EVENT_PROMOTE:
4001  event_name = "Promote";
4002  break;
4004  event_name = "RecoveryConflictSnapshot";
4005  break;
4007  event_name = "RecoveryConflictTablespace";
4008  break;
4010  event_name = "RecoveryPause";
4011  break;
4013  event_name = "ReplicationOriginDrop";
4014  break;
4016  event_name = "ReplicationSlotDrop";
4017  break;
4019  event_name = "SafeSnapshot";
4020  break;
4021  case WAIT_EVENT_SYNC_REP:
4022  event_name = "SyncRep";
4023  break;
4025  event_name = "XactGroupUpdate";
4026  break;
4027  /* no default case, so that compiler will warn */
4028  }
4029 
4030  return event_name;
4031 }

◆ pgstat_get_wait_timeout()

static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

Definition at line 4040 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().

4041 {
4042  const char *event_name = "unknown wait event";
4043 
4044  switch (w)
4045  {
4047  event_name = "BaseBackupThrottle";
4048  break;
4049  case WAIT_EVENT_PG_SLEEP:
4050  event_name = "PgSleep";
4051  break;
4053  event_name = "RecoveryApplyDelay";
4054  break;
4056  event_name = "RecoveryRetrieveRetryInterval";
4057  break;
4059  event_name = "VacuumDelay";
4060  break;
4061  /* no default case, so that compiler will warn */
4062  }
4063 
4064  return event_name;
4065 }

◆ pgstat_init()

void pgstat_init ( void  )

Definition at line 390 of file pgstat.c.

References addrinfo::ai_next, AI_PASSIVE, bind, closesocket, connect, EINTR, elog, 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().

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

1791 {
1792  PgStat_BackendFunctionEntry *htabent;
1793  bool found;
1794 
1795  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1796  {
1797  /* stats not wanted */
1798  fcu->fs = NULL;
1799  return;
1800  }
1801 
1802  if (!pgStatFunctions)
1803  {
1804  /* First time through - initialize function stat table */
1805  HASHCTL hash_ctl;
1806 
1807  memset(&hash_ctl, 0, sizeof(hash_ctl));
1808  hash_ctl.keysize = sizeof(Oid);
1809  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1810  pgStatFunctions = hash_create("Function stat entries",
1812  &hash_ctl,
1813  HASH_ELEM | HASH_BLOBS);
1814  }
1815 
1816  /* Get the stats entry for this function, create if necessary */
1817  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1818  HASH_ENTER, &found);
1819  if (!found)
1820  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1821 
1822  fcu->fs = &htabent->f_counts;
1823 
1824  /* save stats for this function, later used to compensate for recursion */
1825  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1826 
1827  /* save current backend-wide total time */
1828  fcu->save_total = total_func_time;
1829 
1830  /* get clock time as of function start */
1832 }
#define HASH_ELEM
Definition: hsearch.h:85
instr_time save_total
Definition: pgstat.h:1316
Size entrysize
Definition: hsearch.h:72
#define MemSet(start, val, len)
Definition: c.h:950
instr_time f_total_time
Definition: pgstat.h:538
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1312
PgStat_FunctionCounts f_counts
Definition: pgstat.h:549
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:106
#define HASH_BLOBS
Definition: hsearch.h:86
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
FmgrInfo * flinfo
Definition: fmgr.h:87
Size keysize
Definition: hsearch.h:71
Oid fn_oid
Definition: fmgr.h:59
static instr_time total_func_time
Definition: pgstat.c:303
static HTAB * pgStatFunctions
Definition: pgstat.c:224
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1314
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry

◆ pgstat_initialize()

void pgstat_initialize ( void  )

Definition at line 3027 of file pgstat.c.

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

Referenced by AuxiliaryProcessMain(), and InitPostgres().

3028 {
3029  /* Initialize MyBEEntry */
3031  {
3034  }
3035  else
3036  {
3037  /* Must be an auxiliary process */
3039 
3040  /*
3041  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
3042  * have a BackendId, the slot is statically allocated based on the
3043  * auxiliary process type (MyAuxProcType). Backends use slots indexed
3044  * in the range from 1 to MaxBackends (inclusive), so we use
3045  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
3046  * auxiliary process.
3047  */
3049  }
3050 
3051  /* Set up a process-exit hook to clean up */
3053 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2846
BackendId MyBackendId
Definition: globals.c:81
int MaxBackends
Definition: globals.c:136
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
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:3240
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:70
#define Assert(condition)
Definition: c.h:746

◆ pgstat_initstats()

void pgstat_initstats ( Relation  rel)

Definition at line 1918 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().

1919 {
1920  Oid rel_id = rel->rd_id;
1921  char relkind = rel->rd_rel->relkind;
1922 
1923  /* We only count stats for things that have storage */
1924  if (!RELKIND_HAS_STORAGE(relkind))
1925  {
1926  rel->pgstat_info = NULL;
1927  return;
1928  }
1929 
1931  {
1932  /* We're not counting at all */
1933  rel->pgstat_info = NULL;
1934  return;
1935  }
1936 
1937  /*
1938  * If we already set up this relation in the current transaction, nothing
1939  * to do.
1940  */
1941  if (rel->pgstat_info != NULL &&
1942  rel->pgstat_info->t_id == rel_id)
1943  return;
1944 
1945  /* Else find or make the PgStat_TableStatus entry, and update link */
1946  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1947 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:176
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool pgstat_track_counts
Definition: pgstat.c:126
Oid rd_id
Definition: rel.h:111
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:1953
#define PGINVALID_SOCKET
Definition: port.h:33
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:236

◆ pgstat_ping()

void pgstat_ping ( void  )

Definition at line 1754 of file pgstat.c.

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

1755 {
1756  PgStat_MsgDummy msg;
1757 
1759  return;
1760 
1762  pgstat_send(&msg, sizeof(msg));
1763 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4492
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:176
#define PGINVALID_SOCKET
Definition: port.h:33
PgStat_MsgHdr m_hdr
Definition: pgstat.h:223
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4479

◆ pgstat_progress_end_command()

void pgstat_progress_end_command ( void  )

Definition at line 3428 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(), heap_vacuum_rel(), perform_base_backup(), reindex_index(), and ReindexRelationConcurrently().

3429 {
3430  volatile PgBackendStatus *beentry = MyBEEntry;
3431 
3432  if (!beentry || !pgstat_track_activities)
3433  return;
3434 
3436  return;
3437 
3438  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3441  PGSTAT_END_WRITE_ACTIVITY(beentry);
3442 }
Oid st_progress_command_target
Definition: pgstat.h:1212
ProgressCommandType st_progress_command
Definition: pgstat.h:1211
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:125
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245

◆ pgstat_progress_start_command()

void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

Definition at line 3356 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(), cluster_rel(), DefineIndex(), heap_vacuum_rel(), perform_base_backup(), reindex_index(), and ReindexRelationConcurrently().

3357 {
3358  volatile PgBackendStatus *beentry = MyBEEntry;
3359 
3360  if (!beentry || !pgstat_track_activities)
3361  return;
3362 
3363  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3364  beentry->st_progress_command = cmdtype;
3365  beentry->st_progress_command_target = relid;
3366  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3367  PGSTAT_END_WRITE_ACTIVITY(beentry);
3368 }
Oid st_progress_command_target
Definition: pgstat.h:1212
#define MemSet(start, val, len)
Definition: c.h:950
ProgressCommandType st_progress_command
Definition: pgstat.h:1211
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1213
bool pgstat_track_activities
Definition: pgstat.c:125
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245

◆ pgstat_progress_update_multi_param()

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

Definition at line 3399 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().

3401 {
3402  volatile PgBackendStatus *beentry = MyBEEntry;
3403  int i;
3404 
3405  if (!beentry || !pgstat_track_activities || nparam == 0)
3406  return;
3407 
3408  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3409 
3410  for (i = 0; i < nparam; ++i)
3411  {
3412  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3413 
3414  beentry->st_progress_param[index[i]] = val[i];
3415  }
3416 
3417  PGSTAT_END_WRITE_ACTIVITY(beentry);
3418 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1077
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
#define Assert(condition)
Definition: c.h:746
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1213
bool pgstat_track_activities
Definition: pgstat.c:125
int i
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245
long val
Definition: informix.c:664

◆ pgstat_progress_update_param()

void pgstat_progress_update_param ( int  index,
int64  val 
)

Definition at line 3377 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(), btvacuumscan(), BuildRelationExtStatistics(), cluster_rel(), 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().

3378 {
3379  volatile PgBackendStatus *beentry = MyBEEntry;
3380 
3382 
3383  if (!beentry || !pgstat_track_activities)
3384  return;
3385 
3386  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3387  beentry->st_progress_param[index] = val;
3388  PGSTAT_END_WRITE_ACTIVITY(beentry);
3389 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1077
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2847
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1252
#define Assert(condition)
Definition: c.h:746
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1213
bool pgstat_track_activities
Definition: pgstat.c:125
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1245
long val
Definition: informix.c:664

◆ pgstat_read_current_status()

static void pgstat_read_current_status ( void  )
static

Definition at line 3507 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().

3508 {
3509  volatile PgBackendStatus *beentry;
3510  LocalPgBackendStatus *localtable;
3511  LocalPgBackendStatus *localentry;
3512  char *localappname,
3513  *localclienthostname,
3514  *localactivity;
3515 #ifdef USE_SSL
3516  PgBackendSSLStatus *localsslstatus;
3517 #endif
3518 #ifdef ENABLE_GSS
3519  PgBackendGSSStatus *localgssstatus;
3520 #endif
3521  int i;
3522 
3525  return; /* already done */
3526 
3528 
3529  /*
3530  * Allocate storage for local copy of state data. We can presume that
3531  * none of these requests overflow size_t, because we already calculated
3532  * the same values using mul_size during shmem setup. However, with
3533  * probably-silly values of pgstat_track_activity_query_size and
3534  * max_connections, the localactivity buffer could exceed 1GB, so use
3535  * "huge" allocation for that one.
3536  */
3537  localtable = (LocalPgBackendStatus *)
3540  localappname = (char *)
3543  localclienthostname = (char *)
3545  NAMEDATALEN * NumBackendStatSlots);
3546  localactivity = (char *)
3548  pgstat_track_activity_query_size * NumBackendStatSlots);
3549 #ifdef USE_SSL
3550  localsslstatus = (PgBackendSSLStatus *)
3553 #endif
3554 #ifdef ENABLE_GSS
3555  localgssstatus = (PgBackendGSSStatus *)
3558 #endif
3559 
3560  localNumBackends = 0;
3561 
3562  beentry = BackendStatusArray;
3563  localentry = localtable;
3564  for (i = 1; i <= NumBackendStatSlots; i++)
3565  {
3566  /*
3567  * Follow the protocol of retrying if st_changecount changes while we
3568  * copy the entry, or if it's odd. (The check for odd is needed to
3569  * cover the case where we are able to completely copy the entry while
3570  * the source backend is between increment steps.) We use a volatile
3571  * pointer here to ensure the compiler doesn't try to get cute.
3572  */
3573  for (;;)
3574  {
3575  int before_changecount;
3576  int after_changecount;
3577 
3578  pgstat_begin_read_activity(beentry, before_changecount);
3579 
3580  localentry->backendStatus.st_procpid = beentry->st_procpid;
3581  /* Skip all the data-copying work if entry is not in use */
3582  if (localentry->backendStatus.st_procpid > 0)
3583  {
3584  memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3585 
3586  /*
3587  * For each PgBackendStatus field that is a pointer, copy the
3588  * pointed-to data, then adjust the local copy of the pointer
3589  * field to point at the local copy of the data.
3590  *
3591  * strcpy is safe even if the string is modified concurrently,
3592  * because there's always a \0 at the end of the buffer.
3593  */
3594  strcpy(localappname, (char *) beentry->st_appname);
3595  localentry->backendStatus.st_appname = localappname;
3596  strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3597  localentry->backendStatus.st_clienthostname = localclienthostname;
3598  strcpy(localactivity, (char *) beentry->st_activity_raw);
3599  localentry->backendStatus.st_activity_raw = localactivity;
3600 #ifdef USE_SSL
3601  if (beentry->st_ssl)
3602  {
3603  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3604  localentry->backendStatus.st_sslstatus = localsslstatus;
3605  }
3606 #endif
3607 #ifdef ENABLE_GSS
3608  if (beentry->st_gss)
3609  {
3610  memcpy(localgssstatus, beentry->st_gssstatus, sizeof(PgBackendGSSStatus));
3611  localentry->backendStatus.st_gssstatus = localgssstatus;
3612  }
3613 #endif
3614  }
3615 
3616  pgstat_end_read_activity(beentry, after_changecount);
3617 
3618  if (pgstat_read_activity_complete(before_changecount,
3619  after_changecount))
3620  break;
3621 
3622  /* Make sure we can break out of loop if stuck... */
3624  }
3625 
3626  beentry++;
3627  /* Only valid entries get included into the local array */
3628  if (localentry->backendStatus.st_procpid > 0)
3629  {
3631  &localentry->backend_xid,
3632  &localentry->backend_xmin);
3633 
3634  localentry++;
3635  localappname += NAMEDATALEN;
3636  localclienthostname += NAMEDATALEN;
3637  localactivity += pgstat_track_activity_query_size;
3638 #ifdef USE_SSL
3639  localsslstatus++;
3640 #endif
3641 #ifdef ENABLE_GSS
3642  localgssstatus++;
3643 #endif
3644  localNumBackends++;
3645  }
3646  }
3647 
3648  /* Set the pointer only after completion of a valid table */
3649  localBackendStatusTable = localtable;
3650 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2846
static bool pgStatRunningInCollector
Definition: pgstat.c:182
TransactionId backend_xmin
Definition: pgstat.h:1302
#define NumBackendStatSlots
Definition: pgstat.c:118
char * st_clienthostname
Definition: pgstat.h:1177
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1296
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition: mcxt.c:1106
char * st_activity_raw
Definition: pgstat.h:1200
int pgstat_track_activity_query_size
Definition: pgstat.c:128
char * st_appname
Definition: pgstat.h:1191
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1266
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:6121
PgBackendStatus backendStatus
Definition: pgstat.h:1290
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:403
#define Assert(condition)
Definition: c.h:746
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:274
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1260
static int localNumBackends
Definition: pgstat.c:277
#define unvolatize(underlying_type, expr)
Definition: c.h:1187
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:270
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1181
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1185
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1272

◆ pgstat_read_db_statsfile()

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

Definition at line 5660 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().

5662 {
5663  PgStat_StatTabEntry *tabentry;
5664  PgStat_StatTabEntry tabbuf;
5665  PgStat_StatFuncEntry funcbuf;
5666  PgStat_StatFuncEntry *funcentry;
5667  FILE *fpin;
5668  int32 format_id;
5669  bool found;
5670  char statfile[MAXPGPATH];
5671 
5672  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5673 
5674  /*
5675  * Try to open the stats file. If it doesn't exist, the backends simply
5676  * return zero for anything and the collector simply starts from scratch
5677  * with empty counters.
5678  *
5679  * ENOENT is a possibility if the stats collector is not running or has
5680  * not yet written the stats file the first time. Any other failure
5681  * condition is suspicious.
5682  */
5683  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5684  {
5685  if (errno != ENOENT)
5688  errmsg("could not open statistics file \"%s\": %m",
5689  statfile)));
5690  return;
5691  }
5692 
5693  /*
5694  * Verify it's of the expected format.
5695  */
5696  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5697  format_id != PGSTAT_FILE_FORMAT_ID)
5698  {
5699  ereport(pgStatRunningInCollector ? LOG : WARNING,
5700  (errmsg("corrupted statistics file \"%s\"", statfile)));
5701  goto done;
5702  }
5703 
5704  /*
5705  * We found an existing collector stats file. Read it and put all the
5706  * hashtable entries into place.
5707  */
5708  for (;;)
5709  {
5710  switch (fgetc(fpin))
5711  {
5712  /*
5713  * 'T' A PgStat_StatTabEntry follows.
5714  */
5715  case 'T':
5716  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5717  fpin) != sizeof(PgStat_StatTabEntry))
5718  {
5719  ereport(pgStatRunningInCollector ? LOG : WARNING,
5720  (errmsg("corrupted statistics file \"%s\"",
5721  statfile)));
5722  goto done;
5723  }
5724 
5725  /*
5726  * Skip if table data not wanted.
5727  */
5728  if (tabhash == NULL)
5729  break;
5730 
5731  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5732  (void *) &tabbuf.tableid,
5733  HASH_ENTER, &found);
5734 
5735  if (found)
5736  {
5737  ereport(pgStatRunningInCollector ? LOG : WARNING,
5738  (errmsg("corrupted statistics file \"%s\"",
5739  statfile)));
5740  goto done;
5741  }
5742 
5743  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5744  break;
5745 
5746  /*
5747  * 'F' A PgStat_StatFuncEntry follows.
5748  */
5749  case 'F':
5750  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5751  fpin) != sizeof(PgStat_StatFuncEntry))
5752  {
5753  ereport(pgStatRunningInCollector ? LOG : WARNING,
5754  (errmsg("corrupted statistics file \"%s\"",
5755  statfile)));
5756  goto done;
5757  }
5758 
5759  /*
5760  * Skip if function data not wanted.
5761  */
5762  if (funchash == NULL)
5763  break;
5764 
5765  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5766  (void *) &funcbuf.functionid,
5767  HASH_ENTER, &found);
5768 
5769  if (found)
5770  {
5771