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/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 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_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_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_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_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_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_SLRUStatspgstat_fetch_slru (void)
 
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)
 
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
 
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_SLRUStats slruStats [SLRU_NUM_ELEMENTS]
 
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 103 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 85 of file pgstat.c.

◆ PGSTAT_INQ_LOOP_COUNT

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

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

◆ PGSTAT_MIN_RCVBUF

#define PGSTAT_MIN_RCVBUF   (100 * 1024)

Definition at line 96 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 92 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 88 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 79 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 76 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 104 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 193 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 1970 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().

1971 {
1972  PgStat_SubXactStatus *xact_state;
1974 
1975  /*
1976  * If this is the first rel to be modified at the current nest level, we
1977  * first have to push a transaction stack entry.
1978  */
1979  xact_state = get_tabstat_stack_level(nest_level);
1980 
1981  /* Now make a per-table stack entry */
1982  trans = (PgStat_TableXactStatus *)
1984  sizeof(PgStat_TableXactStatus));
1985  trans->nest_level = nest_level;
1986  trans->upper = pgstat_info->trans;
1987  trans->parent = pgstat_info;
1988  trans->next = xact_state->first;
1989  xact_state->first = trans;
1990  pgstat_info->trans = trans;
1991 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_TableXactStatus * next
Definition: pgstat.h:182
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:1948
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:179
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:402
PgStat_TableXactStatus * first
Definition: pgstat.c:241
PgStat_TableStatus * parent
Definition: pgstat.h:180

◆ allow_immediate_pgstat_restart()

void allow_immediate_pgstat_restart ( void  )

Definition at line 817 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

818 {
820 }
static time_t last_pgstat_start_time
Definition: pgstat.c:178

◆ AtEOSubXact_PgStat()

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

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

2231 {
2232  PgStat_SubXactStatus *xact_state;
2233 
2234  /*
2235  * Transfer transactional insert/update counts into the next higher
2236  * subtransaction state.
2237  */
2238  xact_state = pgStatXactStack;
2239  if (xact_state != NULL &&
2240  xact_state->nest_level >= nestDepth)
2241  {
2243  PgStat_TableXactStatus *next_trans;
2244 
2245  /* delink xact_state from stack immediately to simplify reuse case */
2246  pgStatXactStack = xact_state->prev;
2247 
2248  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2249  {
2250  PgStat_TableStatus *tabstat;
2251 
2252  next_trans = trans->next;
2253  Assert(trans->nest_level == nestDepth);
2254  tabstat = trans->parent;
2255  Assert(tabstat->trans == trans);
2256  if (isCommit)
2257  {
2258  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2259  {
2260  if (trans->truncated)
2261  {
2262  /* propagate the truncate status one level up */
2264  /* replace upper xact stats with ours */
2265  trans->upper->tuples_inserted = trans->tuples_inserted;
2266  trans->upper->tuples_updated = trans->tuples_updated;
2267  trans->upper->tuples_deleted = trans->tuples_deleted;
2268  }
2269  else
2270  {
2271  trans->upper->tuples_inserted += trans->tuples_inserted;
2272  trans->upper->tuples_updated += trans->tuples_updated;
2273  trans->upper->tuples_deleted += trans->tuples_deleted;
2274  }
2275  tabstat->trans = trans->upper;
2276  pfree(trans);
2277  }
2278  else
2279  {
2280  /*
2281  * When there isn't an immediate parent state, we can just
2282  * reuse the record instead of going through a
2283  * palloc/pfree pushup (this works since it's all in
2284  * TopTransactionContext anyway). We have to re-link it
2285  * into the parent level, though, and that might mean
2286  * pushing a new entry into the pgStatXactStack.
2287  */
2288  PgStat_SubXactStatus *upper_xact_state;
2289 
2290  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2291  trans->next = upper_xact_state->first;
2292  upper_xact_state->first = trans;
2293  trans->nest_level = nestDepth - 1;
2294  }
2295  }
2296  else
2297  {
2298  /*
2299  * On abort, update top-level tabstat counts, then forget the
2300  * subtransaction
2301  */
2302 
2303  /* first restore values obliterated by truncate */
2305  /* count attempted actions regardless of commit/abort */
2306  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2307  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2308  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2309  /* inserted tuples are dead, deleted tuples are unaffected */
2310  tabstat->t_counts.t_delta_dead_tuples +=
2311  trans->tuples_inserted + trans->tuples_updated;
2312  tabstat->trans = trans->upper;
2313  pfree(trans);
2314  }
2315  }
2316  pfree(xact_state);
2317  }
2318 }
PgStat_Counter tuples_updated
Definition: pgstat.h:171
struct PgStat_TableXactStatus * next
Definition: pgstat.h:182
PgStat_TableCounts t_counts
Definition: pgstat.h:161
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:1948
void pfree(void *pointer)
Definition: mcxt.c:1056
PgStat_Counter t_tuples_updated
Definition: pgstat.h:108
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2084
PgStat_Counter tuples_inserted
Definition: pgstat.h:170
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:114
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:179
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:109
PgStat_Counter tuples_deleted
Definition: pgstat.h:172
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:240
#define Assert(condition)
Definition: c.h:738
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:244
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:402
PgStat_TableXactStatus * first
Definition: pgstat.c:241
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2069
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:107
PgStat_TableStatus * parent
Definition: pgstat.h:180

◆ AtEOXact_PgStat()

void AtEOXact_PgStat ( bool  isCommit,
bool  parallel 
)

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

2144 {
2145  PgStat_SubXactStatus *xact_state;
2146 
2147  /* Don't count parallel worker transaction stats */
2148  if (!parallel)
2149  {
2150  /*
2151  * Count transaction commit or abort. (We use counters, not just
2152  * bools, in case the reporting message isn't sent right away.)
2153  */
2154  if (isCommit)
2155  pgStatXactCommit++;
2156  else
2158  }
2159 
2160  /*
2161  * Transfer transactional insert/update counts into the base tabstat
2162  * entries. We don't bother to free any of the transactional state, since
2163  * it's all in TopTransactionContext and will go away anyway.
2164  */
2165  xact_state = pgStatXactStack;
2166  if (xact_state != NULL)
2167  {
2169 
2170  Assert(xact_state->nest_level == 1);
2171  Assert(xact_state->prev == NULL);
2172  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2173  {
2174  PgStat_TableStatus *tabstat;
2175 
2176  Assert(trans->nest_level == 1);
2177  Assert(trans->upper == NULL);
2178  tabstat = trans->parent;
2179  Assert(tabstat->trans == trans);
2180  /* restore pre-truncate stats (if any) in case of aborted xact */
2181  if (!isCommit)
2183  /* count attempted actions regardless of commit/abort */
2184  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2185  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2186  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2187  if (isCommit)
2188  {
2189  tabstat->t_counts.t_truncated = trans->truncated;
2190  if (trans->truncated)
2191  {
2192  /* forget live/dead stats seen by backend thus far */
2193  tabstat->t_counts.t_delta_live_tuples = 0;
2194  tabstat->t_counts.t_delta_dead_tuples = 0;
2195  }
2196  /* insert adds a live tuple, delete removes one */
2197  tabstat->t_counts.t_delta_live_tuples +=
2198  trans->tuples_inserted - trans->tuples_deleted;
2199  /* update and delete each create a dead tuple */
2200  tabstat->t_counts.t_delta_dead_tuples +=
2201  trans->tuples_updated + trans->tuples_deleted;
2202  /* insert, update, delete each count as one change event */
2203  tabstat->t_counts.t_changed_tuples +=
2204  trans->tuples_inserted + trans->tuples_updated +
2205  trans->tuples_deleted;
2206  }
2207  else
2208  {
2209  /* inserted tuples are dead, deleted tuples are unaffected */
2210  tabstat->t_counts.t_delta_dead_tuples +=
2211  trans->tuples_inserted + trans->tuples_updated;
2212  /* an aborted xact generates no changed_tuple events */
2213  }
2214  tabstat->trans = NULL;
2215  }
2216  }
2217  pgStatXactStack = NULL;
2218 
2219  /* Make sure any stats snapshot is thrown away */
2221 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:113
PgStat_Counter tuples_updated
Definition: pgstat.h:171
static int pgStatXactCommit
Definition: pgstat.c:246
struct PgStat_TableXactStatus * next
Definition: pgstat.h:182
PgStat_TableCounts t_counts
Definition: pgstat.h:161
PgStat_Counter t_tuples_updated
Definition: pgstat.h:108
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2084
static int pgStatXactRollback
Definition: pgstat.c:247
PgStat_Counter tuples_inserted
Definition: pgstat.h:170
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:114
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:179
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:109
PgStat_Counter tuples_deleted
Definition: pgstat.h:172
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:240
PgStat_Counter t_changed_tuples
Definition: pgstat.h:115
#define Assert(condition)
Definition: c.h:738
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5840
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:244
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:402
PgStat_TableXactStatus * first
Definition: pgstat.c:241
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:107
PgStat_TableStatus * parent
Definition: pgstat.h:180

◆ AtPrepare_PgStat()

void AtPrepare_PgStat ( void  )

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

2330 {
2331  PgStat_SubXactStatus *xact_state;
2332 
2333  xact_state = pgStatXactStack;
2334  if (xact_state != NULL)
2335  {
2337 
2338  Assert(xact_state->nest_level == 1);
2339  Assert(xact_state->prev == NULL);
2340  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2341  {
2342  PgStat_TableStatus *tabstat;
2343  TwoPhasePgStatRecord record;
2344 
2345  Assert(trans->nest_level == 1);
2346  Assert(trans->upper == NULL);
2347  tabstat = trans->parent;
2348  Assert(tabstat->trans == trans);
2349 
2350  record.tuples_inserted = trans->tuples_inserted;
2351  record.tuples_updated = trans->tuples_updated;
2352  record.tuples_deleted = trans->tuples_deleted;
2353  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2354  record.updated_pre_trunc = trans->updated_pre_trunc;
2355  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2356  record.t_id = tabstat->t_id;
2357  record.t_shared = tabstat->t_shared;
2358  record.t_truncated = trans->truncated;
2359 
2361  &record, sizeof(TwoPhasePgStatRecord));
2362  }
2363  }
2364 }
PgStat_Counter tuples_updated
Definition: pgstat.h:171
struct PgStat_TableXactStatus * next
Definition: pgstat.h:182
PgStat_Counter deleted_pre_trunc
Definition: pgstat.h:176
PgStat_Counter deleted_pre_trunc
Definition: pgstat.c:259
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1187
PgStat_Counter tuples_inserted
Definition: pgstat.h:170
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:258
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:257
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:179
PgStat_Counter tuples_updated
Definition: pgstat.c:255
PgStat_Counter tuples_deleted
Definition: pgstat.h:172
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:240
#define Assert(condition)
Definition: c.h:738
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:174
PgStat_Counter tuples_inserted
Definition: pgstat.c:254
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:244
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160
PgStat_Counter tuples_deleted
Definition: pgstat.c:256
#define TWOPHASE_RM_PGSTAT_ID
Definition: twophase_rmgr.h:26
PgStat_Counter updated_pre_trunc
Definition: pgstat.h:175
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:402
PgStat_TableXactStatus * first
Definition: pgstat.c:241
PgStat_TableStatus * parent
Definition: pgstat.h:180

◆ backend_read_statsfile()

static void backend_read_statsfile ( void  )
static

Definition at line 5686 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_slru(), pgstat_fetch_stat_archiver(), pgstat_fetch_stat_dbentry(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), and pgstat_vacuum_stat().

5687 {
5688  TimestampTz min_ts = 0;
5689  TimestampTz ref_ts = 0;
5690  Oid inquiry_db;
5691  int count;
5692 
5693  /* already read it? */
5694  if (pgStatDBHash)
5695  return;
5697 
5698  /*
5699  * In a normal backend, we check staleness of the data for our own DB, and
5700  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5701  * check staleness of the shared-catalog data, and send InvalidOid in
5702  * inquiry messages so as not to force writing unnecessary data.
5703  */
5705  inquiry_db = InvalidOid;
5706  else
5707  inquiry_db = MyDatabaseId;
5708 
5709  /*
5710  * Loop until fresh enough stats file is available or we ran out of time.
5711  * The stats inquiry message is sent repeatedly in case collector drops
5712  * it; but not every single time, as that just swamps the collector.
5713  */
5714  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5715  {
5716  bool ok;
5717  TimestampTz file_ts = 0;
5718  TimestampTz cur_ts;
5719 
5721 
5722  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5723 
5724  cur_ts = GetCurrentTimestamp();
5725  /* Calculate min acceptable timestamp, if we didn't already */
5726  if (count == 0 || cur_ts < ref_ts)
5727  {
5728  /*
5729  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5730  * msec before now. This indirectly ensures that the collector
5731  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5732  * an autovacuum worker, however, we want a lower delay to avoid
5733  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5734  * number of workers is low, this shouldn't be a problem).
5735  *
5736  * We don't recompute min_ts after sleeping, except in the
5737  * unlikely case that cur_ts went backwards. So we might end up
5738  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5739  * practice that shouldn't happen, though, as long as the sleep
5740  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5741  * tell the collector that our cutoff time is less than what we'd
5742  * actually accept.
5743  */
5744  ref_ts = cur_ts;
5746  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5748  else
5749  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5751  }
5752 
5753  /*
5754  * If the file timestamp is actually newer than cur_ts, we must have
5755  * had a clock glitch (system time went backwards) or there is clock
5756  * skew between our processor and the stats collector's processor.
5757  * Accept the file, but send an inquiry message anyway to make
5758  * pgstat_recv_inquiry do a sanity check on the collector's time.
5759  */
5760  if (ok && file_ts > cur_ts)
5761  {
5762  /*
5763  * A small amount of clock skew between processors isn't terribly
5764  * surprising, but a large difference is worth logging. We
5765  * arbitrarily define "large" as 1000 msec.
5766  */
5767  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5768  {
5769  char *filetime;
5770  char *mytime;
5771 
5772  /* Copy because timestamptz_to_str returns a static buffer */
5773  filetime = pstrdup(timestamptz_to_str(file_ts));
5774  mytime = pstrdup(timestamptz_to_str(cur_ts));
5775  elog(LOG, "stats collector's time %s is later than backend local time %s",
5776  filetime, mytime);
5777  pfree(filetime);
5778  pfree(mytime);
5779  }
5780 
5781  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5782  break;
5783  }
5784 
5785  /* Normal acceptance case: file is not older than cutoff time */
5786  if (ok && file_ts >= min_ts)
5787  break;
5788 
5789  /* Not there or too old, so kick the collector and wait a bit */
5790  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5791  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5792 
5793  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5794  }
5795 
5796  if (count >= PGSTAT_POLL_LOOP_COUNT)
5797  ereport(LOG,
5798  (errmsg("using stale statistics instead of current ones "
5799  "because stats collector is not responding")));
5800 
5801  /*
5802  * Autovacuum launcher wants stats about all databases, but a shallow read
5803  * is sufficient. Regular backends want a deep read for just the tables
5804  * they can see (MyDatabaseId + shared catalogs).
5805  */
5808  else
5810 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:79
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:93
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static bool pgStatRunningInCollector
Definition: pgstat.c:180
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PGSTAT_POLL_LOOP_COUNT
Definition: pgstat.c:92
void pg_usleep(long microsec)
Definition: signal.c:53
void pfree(void *pointer)
Definition: mcxt.c:1056
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1658
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:76
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3301
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:5142
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:5555
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3295
#define Assert(condition)
Definition: c.h:738
static HTAB * pgStatDBHash
Definition: pgstat.c:269
int errmsg(const char *fmt,...)
Definition: elog.c:824
#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:1736

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 2718 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2719 {
2720  Size size;
2721 
2722  /* BackendStatusArray: */
2723  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2724  /* BackendAppnameBuffer: */
2725  size = add_size(size,
2727  /* BackendClientHostnameBuffer: */
2728  size = add_size(size,
2730  /* BackendActivityBuffer: */
2731  size = add_size(size,
2733 #ifdef USE_SSL
2734  /* BackendSslStatusBuffer: */
2735  size = add_size(size,
2737 #endif
2738  return size;
2739 }
#define NumBackendStatSlots
Definition: pgstat.c:117
#define NAMEDATALEN
int pgstat_track_activity_query_size
Definition: pgstat.c:127
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:466

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

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

2747 {
2748  Size size;
2749  bool found;
2750  int i;
2751  char *buffer;
2752 
2753  /* Create or attach to the shared array */
2754  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2756  ShmemInitStruct("Backend Status Array", size, &found);
2757 
2758  if (!found)
2759  {
2760  /*
2761  * We're the first - initialize.
2762  */
2763  MemSet(BackendStatusArray, 0, size);
2764  }
2765 
2766  /* Create or attach to the shared appname buffer */
2768  BackendAppnameBuffer = (char *)
2769  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2770 
2771  if (!found)
2772  {
2773  MemSet(BackendAppnameBuffer, 0, size);
2774 
2775  /* Initialize st_appname pointers. */
2776  buffer = BackendAppnameBuffer;
2777  for (i = 0; i < NumBackendStatSlots; i++)
2778  {
2779  BackendStatusArray[i].st_appname = buffer;
2780  buffer += NAMEDATALEN;
2781  }
2782  }
2783 
2784  /* Create or attach to the shared client hostname buffer */
2786  BackendClientHostnameBuffer = (char *)
2787  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2788 
2789  if (!found)
2790  {
2792 
2793  /* Initialize st_clienthostname pointers. */
2794  buffer = BackendClientHostnameBuffer;
2795  for (i = 0; i < NumBackendStatSlots; i++)
2796  {
2798  buffer += NAMEDATALEN;
2799  }
2800  }
2801 
2802  /* Create or attach to the shared activity buffer */
2805  BackendActivityBuffer = (char *)
2806  ShmemInitStruct("Backend Activity Buffer",
2808  &found);
2809 
2810  if (!found)
2811  {
2813 
2814  /* Initialize st_activity pointers. */
2815  buffer = BackendActivityBuffer;
2816  for (i = 0; i < NumBackendStatSlots; i++)
2817  {
2820  }
2821  }
2822 
2823 #ifdef USE_SSL
2824  /* Create or attach to the shared SSL status buffer */
2826  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2827  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2828 
2829  if (!found)
2830  {
2831  PgBackendSSLStatus *ptr;
2832 
2833  MemSet(BackendSslStatusBuffer, 0, size);
2834 
2835  /* Initialize st_sslstatus pointers. */
2836  ptr = BackendSslStatusBuffer;
2837  for (i = 0; i < NumBackendStatSlots; i++)
2838  {
2840  ptr++;
2841  }
2842  }
2843 #endif
2844 
2845 #ifdef ENABLE_GSS
2846  /* Create or attach to the shared GSSAPI status buffer */
2848  BackendGssStatusBuffer = (PgBackendGSSStatus *)
2849  ShmemInitStruct("Backend GSS Status Buffer", size, &found);
2850 
2851  if (!found)
2852  {
2853  PgBackendGSSStatus *ptr;
2854 
2855  MemSet(BackendGssStatusBuffer, 0, size);
2856 
2857  /* Initialize st_gssstatus pointers. */
2858  ptr = BackendGssStatusBuffer;
2859  for (i = 0; i < NumBackendStatSlots; i++)
2860  {
2862  ptr++;
2863  }
2864  }
2865 #endif
2866 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2700
static char * BackendActivityBuffer
Definition: pgstat.c:2704
static Size BackendActivityBufferSize
Definition: pgstat.c:2705
#define MemSet(start, val, len)
Definition: c.h:971
#define NumBackendStatSlots
Definition: pgstat.c:117
char * st_clienthostname
Definition: pgstat.h:1101
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2702
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
char * st_activity_raw
Definition: pgstat.h:1124
int pgstat_track_activity_query_size
Definition: pgstat.c:127
char * st_appname
Definition: pgstat.h:1115
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
size_t Size
Definition: c.h:466
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1105
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1109
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2703

◆ find_funcstat_entry()

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

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

1728 {
1729  if (pgStatFunctions == NULL)
1730  return NULL;
1731 
1733  (void *) &func_id,
1734  HASH_FIND, NULL);
1735 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
static HTAB * pgStatFunctions
Definition: pgstat.c:222

◆ find_tabstat_entry()

PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

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

1929 {
1930  TabStatHashEntry *hash_entry;
1931 
1932  /* If hashtable doesn't exist, there are no entries at all */
1933  if (!pgStatTabHash)
1934  return NULL;
1935 
1936  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1937  if (!hash_entry)
1938  return NULL;
1939 
1940  /* Note that this step could also return NULL, but that's correct */
1941  return hash_entry->tsa_entry;
1942 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
static HTAB * pgStatTabHash
Definition: pgstat.c:216
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:210

◆ get_dbstat_filename()

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

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

4995 {
4996  int printed;
4997 
4998  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4999  printed = snprintf(filename, len, "%s/db_%u.%s",
5000  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
5002  databaseid,
5003  tempname ? "tmp" : "stat");
5004  if (printed >= len)
5005  elog(ERROR, "overlength pgstat path");
5006 }
#define PGSTAT_STAT_PERMANENT_DIRECTORY
Definition: pgstat.h:29
#define ERROR
Definition: elog.h:43
char * pgstat_stat_directory
Definition: pgstat.c:133
static char * filename
Definition: pg_dumpall.c:90
#define elog(elevel,...)
Definition: elog.h:214
#define snprintf
Definition: port.h:193

◆ get_tabstat_entry()

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

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

1840 {
1841  TabStatHashEntry *hash_entry;
1842  PgStat_TableStatus *entry;
1843  TabStatusArray *tsa;
1844  bool found;
1845 
1846  /*
1847  * Create hash table if we don't have it already.
1848  */
1849  if (pgStatTabHash == NULL)
1850  {
1851  HASHCTL ctl;
1852 
1853  memset(&ctl, 0, sizeof(ctl));
1854  ctl.keysize = sizeof(Oid);
1855  ctl.entrysize = sizeof(TabStatHashEntry);
1856 
1857  pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1859  &ctl,
1860  HASH_ELEM | HASH_BLOBS);
1861  }
1862 
1863  /*
1864  * Find an entry or create a new one.
1865  */
1866  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1867  if (!found)
1868  {
1869  /* initialize new entry with null pointer */
1870  hash_entry->tsa_entry = NULL;
1871  }
1872 
1873  /*
1874  * If entry is already valid, we're done.
1875  */
1876  if (hash_entry->tsa_entry)
1877  return hash_entry->tsa_entry;
1878 
1879  /*
1880  * Locate the first pgStatTabList entry with free space, making a new list
1881  * entry if needed. Note that we could get an OOM failure here, but if so
1882  * we have left the hashtable and the list in a consistent state.
1883  */
1884  if (pgStatTabList == NULL)
1885  {
1886  /* Set up first pgStatTabList entry */
1889  sizeof(TabStatusArray));
1890  }
1891 
1892  tsa = pgStatTabList;
1893  while (tsa->tsa_used >= TABSTAT_QUANTUM)
1894  {
1895  if (tsa->tsa_next == NULL)
1896  tsa->tsa_next = (TabStatusArray *)
1898  sizeof(TabStatusArray));
1899  tsa = tsa->tsa_next;
1900  }
1901 
1902  /*
1903  * Allocate a PgStat_TableStatus entry within this list entry. We assume
1904  * the entry was already zeroed, either at creation or after last use.
1905  */
1906  entry = &tsa->tsa_entries[tsa->tsa_used++];
1907  entry->t_id = rel_id;
1908  entry->t_shared = isshared;
1909 
1910  /*
1911  * Now we can fill the entry in pgStatTabHash.
1912  */
1913  hash_entry->tsa_entry = entry;
1914 
1915  return entry;
1916 }
int tsa_used
Definition: pgstat.c:198
#define HASH_ELEM
Definition: hsearch.h:87
Size entrysize
Definition: hsearch.h:73
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
struct TabStatusArray * tsa_next
Definition: pgstat.c:197
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:216
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:199
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define HASH_BLOBS
Definition: hsearch.h:88
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:210
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:318
Size keysize
Definition: hsearch.h:72
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
static TabStatusArray * pgStatTabList
Definition: pgstat.c:202
#define TABSTAT_QUANTUM
Definition: pgstat.c:193

◆ get_tabstat_stack_level()

static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

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

1949 {
1950  PgStat_SubXactStatus *xact_state;
1951 
1952  xact_state = pgStatXactStack;
1953  if (xact_state == NULL || xact_state->nest_level != nest_level)
1954  {
1955  xact_state = (PgStat_SubXactStatus *)
1957  sizeof(PgStat_SubXactStatus));
1958  xact_state->nest_level = nest_level;
1959  xact_state->prev = pgStatXactStack;
1960  xact_state->first = NULL;
1961  pgStatXactStack = xact_state;
1962  }
1963  return xact_state;
1964 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:240
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:244
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
PgStat_TableXactStatus * first
Definition: pgstat.c:241

◆ pgstat_beshutdown_hook()

static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

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

3095 {
3096  volatile PgBackendStatus *beentry = MyBEEntry;
3097 
3098  /*
3099  * If we got as far as discovering our own database ID, we can report what
3100  * we did to the collector. Otherwise, we'd be sending an invalid
3101  * database ID, so forget it. (This means that accesses to pg_database
3102  * during failed backend starts might never get counted.)
3103  */
3104  if (OidIsValid(MyDatabaseId))
3105  pgstat_report_stat(true);
3106 
3107  /*
3108  * Clear my status entry, following the protocol of bumping st_changecount
3109  * before and after. We use a volatile pointer here to ensure the
3110  * compiler doesn't try to get cute.
3111  */
3112  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3113 
3114  beentry->st_procpid = 0; /* mark invalid */
3115 
3116  PGSTAT_END_WRITE_ACTIVITY(beentry);
3117 }
#define OidIsValid(objectId)
Definition: c.h:644
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
Oid MyDatabaseId
Definition: globals.c:85
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169
void pgstat_report_stat(bool force)
Definition: pgstat.c:839

◆ pgstat_bestart()

void pgstat_bestart ( void  )

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

2924 {
2925  volatile PgBackendStatus *vbeentry = MyBEEntry;
2926  PgBackendStatus lbeentry;
2927 #ifdef USE_SSL
2928  PgBackendSSLStatus lsslstatus;
2929 #endif
2930 #ifdef ENABLE_GSS
2931  PgBackendGSSStatus lgssstatus;
2932 #endif
2933 
2934  /* pgstats state must be initialized from pgstat_initialize() */
2935  Assert(vbeentry != NULL);
2936 
2937  /*
2938  * To minimize the time spent modifying the PgBackendStatus entry, and
2939  * avoid risk of errors inside the critical section, we first copy the
2940  * shared-memory struct to a local variable, then modify the data in the
2941  * local variable, then copy the local variable back to shared memory.
2942  * Only the last step has to be inside the critical section.
2943  *
2944  * Most of the data we copy from shared memory is just going to be
2945  * overwritten, but the struct's not so large that it's worth the
2946  * maintenance hassle to copy only the needful fields.
2947  */
2948  memcpy(&lbeentry,
2949  unvolatize(PgBackendStatus *, vbeentry),
2950  sizeof(PgBackendStatus));
2951 
2952  /* These structs can just start from zeroes each time, though */
2953 #ifdef USE_SSL
2954  memset(&lsslstatus, 0, sizeof(lsslstatus));
2955 #endif
2956 #ifdef ENABLE_GSS
2957  memset(&lgssstatus, 0, sizeof(lgssstatus));
2958 #endif
2959 
2960  /*
2961  * Now fill in all the fields of lbeentry, except for strings that are
2962  * out-of-line data. Those have to be handled separately, below.
2963  */
2964  lbeentry.st_procpid = MyProcPid;
2965  lbeentry.st_backendType = MyBackendType;
2967  lbeentry.st_activity_start_timestamp = 0;
2968  lbeentry.st_state_start_timestamp = 0;
2969  lbeentry.st_xact_start_timestamp = 0;
2970  lbeentry.st_databaseid = MyDatabaseId;
2971 
2972  /* We have userid for client-backends, wal-sender and bgworker processes */
2973  if (lbeentry.st_backendType == B_BACKEND
2974  || lbeentry.st_backendType == B_WAL_SENDER
2975  || lbeentry.st_backendType == B_BG_WORKER)
2976  lbeentry.st_userid = GetSessionUserId();
2977  else
2978  lbeentry.st_userid = InvalidOid;
2979 
2980  /*
2981  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2982  * If so, use all-zeroes client address, which is dealt with specially in
2983  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2984  */
2985  if (MyProcPort)
2986  memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
2987  sizeof(lbeentry.st_clientaddr));
2988  else
2989  MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
2990 
2991 #ifdef USE_SSL
2993  {
2994  lbeentry.st_ssl = true;
3002  }
3003  else
3004  {
3005  lbeentry.st_ssl = false;
3006  }
3007 #else
3008  lbeentry.st_ssl = false;
3009 #endif
3010 
3011 #ifdef ENABLE_GSS
3012  if (MyProcPort && MyProcPort->gss != NULL)
3013  {
3014  lbeentry.st_gss = true;
3015  lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
3016  lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
3017 
3018  if (lgssstatus.gss_auth)
3020  }
3021  else
3022  {
3023  lbeentry.st_gss = false;
3024  }
3025 #else
3026  lbeentry.st_gss = false;
3027 #endif
3028 
3029  lbeentry.st_state = STATE_UNDEFINED;
3032 
3033  /*
3034  * we don't zero st_progress_param here to save cycles; nobody should
3035  * examine it until st_progress_command has been set to something other
3036  * than PROGRESS_COMMAND_INVALID
3037  */
3038 
3039  /*
3040  * We're ready to enter the critical section that fills the shared-memory
3041  * status entry. We follow the protocol of bumping st_changecount before
3042  * and after; and make sure it's even afterwards. We use a volatile
3043  * pointer here to ensure the compiler doesn't try to get cute.
3044  */
3045  PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
3046 
3047  /* make sure we'll memcpy the same st_changecount back */
3048  lbeentry.st_changecount = vbeentry->st_changecount;
3049 
3050  memcpy(unvolatize(PgBackendStatus *, vbeentry),
3051  &lbeentry,
3052  sizeof(PgBackendStatus));
3053 
3054  /*
3055  * We can write the out-of-line strings and structs using the pointers
3056  * that are in lbeentry; this saves some de-volatilizing messiness.
3057  */
3058  lbeentry.st_appname[0] = '\0';
3061  NAMEDATALEN);
3062  else
3063  lbeentry.st_clienthostname[0] = '\0';
3064  lbeentry.st_activity_raw[0] = '\0';
3065  /* Also make sure the last byte in each string area is always 0 */
3066  lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
3067  lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
3069 
3070 #ifdef USE_SSL
3071  memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
3072 #endif
3073 #ifdef ENABLE_GSS
3074  memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
3075 #endif
3076 
3077  PGSTAT_END_WRITE_ACTIVITY(vbeentry);
3078 
3079  /* Update app name to current GUC setting */
3080  if (application_name)
3082 }
char ssl_issuer_dn[NAMEDATALEN]
Definition: pgstat.h:1032
char gss_princ[NAMEDATALEN]
Definition: pgstat.h:1046
bool ssl_compression
Definition: pgstat.h:1021
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:1023
Oid st_progress_command_target
Definition: pgstat.h:1136
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:60
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:1094
char ssl_client_dn[NAMEDATALEN]
Definition: pgstat.h:1024
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:1022
SockAddr st_clientaddr
Definition: pgstat.h:1100
#define MemSet(start, val, len)
Definition: c.h:971
bool ssl_in_use
Definition: libpq-be.h:190
ProgressCommandType st_progress_command
Definition: pgstat.h:1135
char ssl_client_serial[NAMEDATALEN]
Definition: pgstat.h:1030
BackendState st_state
Definition: pgstat.h:1112
char * st_clienthostname
Definition: pgstat.h:1101
Oid GetSessionUserId(void)
Definition: miscinit.c:482
Oid st_databaseid
Definition: pgstat.h:1098
#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:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
char * st_activity_raw
Definition: pgstat.h:1124
int pgstat_track_activity_query_size
Definition: pgstat.c:127
TimestampTz st_state_start_timestamp
Definition: pgstat.h:1095
char * st_appname
Definition: pgstat.h:1115
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:1089
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3305
#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:738
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:559
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:1207
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:1093
int st_changecount
Definition: pgstat.h:1083
const char * be_tls_get_cipher(Port *port)
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:1092
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1105
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1109
bool be_gssapi_get_auth(Port *port)

◆ pgstat_clear_snapshot()

void pgstat_clear_snapshot ( void  )

Definition at line 5840 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

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

5841 {
5842  /* Release memory, if any was allocated */
5843  if (pgStatLocalContext)
5845 
5846  /* Reset variables */
5847  pgStatLocalContext = NULL;
5848  pgStatDBHash = NULL;
5849  localBackendStatusTable = NULL;
5850  localNumBackends = 0;
5851 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:272
static HTAB * pgStatDBHash
Definition: pgstat.c:269
static int localNumBackends
Definition: pgstat.c:275
static MemoryContext pgStatLocalContext
Definition: pgstat.c:268

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

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

6645 {
6646  char *activity;
6647  int rawlen;
6648  int cliplen;
6649 
6650  /*
6651  * Some callers, like pgstat_get_backend_current_activity(), do not
6652  * guarantee that the buffer isn't concurrently modified. We try to take
6653  * care that the buffer is always terminated by a NUL byte regardless, but
6654  * let's still be paranoid about the string's length. In those cases the
6655  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
6656  * large.
6657  */
6658  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
6659 
6660  /* now double-guaranteed to be NUL terminated */
6661  rawlen = strlen(activity);
6662 
6663  /*
6664  * All supported server-encodings make it possible to determine the length
6665  * of a multi-byte character from its first byte (this is not the case for
6666  * client encodings, see GB18030). As st_activity is always stored using
6667  * server encoding, this allows us to perform multi-byte aware truncation,
6668  * even if the string earlier was truncated in the middle of a multi-byte
6669  * character.
6670  */
6671  cliplen = pg_mbcliplen(activity, rawlen,
6673 
6674  activity[cliplen] = '\0';
6675 
6676  return activity;
6677 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:967
int pgstat_track_activity_query_size
Definition: pgstat.c:127
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 1234 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().

1235 {
1236  HTAB *htab;
1237  HASHCTL hash_ctl;
1238  Relation rel;
1239  TableScanDesc scan;
1240  HeapTuple tup;
1241  Snapshot snapshot;
1242 
1243  memset(&hash_ctl, 0, sizeof(hash_ctl));
1244  hash_ctl.keysize = sizeof(Oid);
1245  hash_ctl.entrysize = sizeof(Oid);
1246  hash_ctl.hcxt = CurrentMemoryContext;
1247  htab = hash_create("Temporary table of OIDs",
1249  &hash_ctl,
1251 
1252  rel = table_open(catalogid, AccessShareLock);
1253  snapshot = RegisterSnapshot(GetLatestSnapshot());
1254  scan = table_beginscan(rel, snapshot, 0, NULL);
1255  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1256  {
1257  Oid thisoid;
1258  bool isnull;
1259 
1260  thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1261  Assert(!isnull);
1262 
1264 
1265  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1266  }
1267  table_endscan(scan);
1268  UnregisterSnapshot(snapshot);
1270 
1271  return htab;
1272 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
MemoryContext hcxt
Definition: hsearch.h:78
#define RelationGetDescr(relation)
Definition: rel.h:482
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:104
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:73
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:210
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:754
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1275
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:318
Size keysize
Definition: hsearch.h:72
#define Assert(condition)
Definition: c.h:738
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:862
#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 2043 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().

2044 {
2045  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2046 
2047  if (pgstat_info != NULL)
2048  {
2049  /* We have to log the effect at the proper transactional level */
2050  int nest_level = GetCurrentTransactionNestLevel();
2051 
2052  if (pgstat_info->trans == NULL ||
2053  pgstat_info->trans->nest_level != nest_level)
2054  add_tabstat_xact_level(pgstat_info, nest_level);
2055 
2056  pgstat_info->trans->tuples_deleted++;
2057  }
2058 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:172
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
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:1970
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160

◆ pgstat_count_heap_insert()

void pgstat_count_heap_insert ( Relation  rel,
PgStat_Counter  n 
)

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

1998 {
1999  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2000 
2001  if (pgstat_info != NULL)
2002  {
2003  /* We have to log the effect at the proper transactional level */
2004  int nest_level = GetCurrentTransactionNestLevel();
2005 
2006  if (pgstat_info->trans == NULL ||
2007  pgstat_info->trans->nest_level != nest_level)
2008  add_tabstat_xact_level(pgstat_info, nest_level);
2009 
2010  pgstat_info->trans->tuples_inserted += n;
2011  }
2012 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:170
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
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:1970
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160

◆ pgstat_count_heap_update()

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

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

2019 {
2020  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2021 
2022  if (pgstat_info != NULL)
2023  {
2024  /* We have to log the effect at the proper transactional level */
2025  int nest_level = GetCurrentTransactionNestLevel();
2026 
2027  if (pgstat_info->trans == NULL ||
2028  pgstat_info->trans->nest_level != nest_level)
2029  add_tabstat_xact_level(pgstat_info, nest_level);
2030 
2031  pgstat_info->trans->tuples_updated++;
2032 
2033  /* t_tuples_hot_updated is nontransactional, so just advance it */
2034  if (hot)
2035  pgstat_info->t_counts.t_tuples_hot_updated++;
2036  }
2037 }
PgStat_Counter tuples_updated
Definition: pgstat.h:171
PgStat_Counter t_tuples_hot_updated
Definition: pgstat.h:110
PgStat_TableCounts t_counts
Definition: pgstat.h:161
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
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:1970
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160

◆ pgstat_count_slru_flush()

void pgstat_count_slru_flush ( int  slru_idx)

Definition at line 6772 of file pgstat.c.

References PgStat_MsgSLRU::m_flush, and slru_entry().

Referenced by SimpleLruFlush().

6773 {
6774  slru_entry(slru_idx)->m_flush += 1;
6775 }
PgStat_Counter m_flush
Definition: pgstat.h:452
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724

◆ pgstat_count_slru_page_exists()

void pgstat_count_slru_page_exists ( int  slru_idx)

Definition at line 6754 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_exists, and slru_entry().

Referenced by SimpleLruDoesPhysicalPageExist().

6755 {
6756  slru_entry(slru_idx)->m_blocks_exists += 1;
6757 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_blocks_exists
Definition: pgstat.h:451

◆ pgstat_count_slru_page_hit()

void pgstat_count_slru_page_hit ( int  slru_idx)

Definition at line 6748 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_hit, and slru_entry().

Referenced by SimpleLruReadPage(), and SimpleLruReadPage_ReadOnly().

6749 {
6750  slru_entry(slru_idx)->m_blocks_hit += 1;
6751 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_blocks_hit
Definition: pgstat.h:448

◆ pgstat_count_slru_page_read()

void pgstat_count_slru_page_read ( int  slru_idx)

Definition at line 6760 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_read, and slru_entry().

Referenced by SimpleLruReadPage().

6761 {
6762  slru_entry(slru_idx)->m_blocks_read += 1;
6763 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_blocks_read
Definition: pgstat.h:449

◆ pgstat_count_slru_page_written()

void pgstat_count_slru_page_written ( int  slru_idx)

Definition at line 6766 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_written, and slru_entry().

Referenced by SlruPhysicalWritePage().

6767 {
6768  slru_entry(slru_idx)->m_blocks_written += 1;
6769 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_blocks_written
Definition: pgstat.h:450

◆ pgstat_count_slru_page_zeroed()

void pgstat_count_slru_page_zeroed ( int  slru_idx)

Definition at line 6742 of file pgstat.c.

References PgStat_MsgSLRU::m_blocks_zeroed, and slru_entry().

Referenced by SimpleLruZeroPage().

6743 {
6744  slru_entry(slru_idx)->m_blocks_zeroed += 1;
6745 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_blocks_zeroed
Definition: pgstat.h:447

◆ pgstat_count_slru_truncate()

void pgstat_count_slru_truncate ( int  slru_idx)

Definition at line 6778 of file pgstat.c.

References PgStat_MsgSLRU::m_truncate, and slru_entry().

Referenced by SimpleLruTruncate().

6779 {
6780  slru_entry(slru_idx)->m_truncate += 1;
6781 }
static PgStat_MsgSLRU * slru_entry(int slru_idx)
Definition: pgstat.c:6724
PgStat_Counter m_truncate
Definition: pgstat.h:453

◆ pgstat_count_truncate()

void pgstat_count_truncate ( Relation  rel)

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

2099 {
2100  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2101 
2102  if (pgstat_info != NULL)
2103  {
2104  /* We have to log the effect at the proper transactional level */
2105  int nest_level = GetCurrentTransactionNestLevel();
2106 
2107  if (pgstat_info->trans == NULL ||
2108  pgstat_info->trans->nest_level != nest_level)
2109  add_tabstat_xact_level(pgstat_info, nest_level);
2110 
2111  pgstat_truncate_save_counters(pgstat_info->trans);
2112  pgstat_info->trans->tuples_inserted = 0;
2113  pgstat_info->trans->tuples_updated = 0;
2114  pgstat_info->trans->tuples_deleted = 0;
2115  }
2116 }
PgStat_Counter tuples_updated
Definition: pgstat.h:171
PgStat_Counter tuples_inserted
Definition: pgstat.h:170
PgStat_Counter tuples_deleted
Definition: pgstat.h:172
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
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:1970
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:160
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2069

◆ pgstat_db_requested()

static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 6617 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

6618 {
6619  /*
6620  * If any requests are outstanding at all, we should write the stats for
6621  * shared catalogs (the "database" with OID 0). This ensures that
6622  * backends will see up-to-date stats for shared catalogs, even though
6623  * they send inquiry messages mentioning only their own DB.
6624  */
6625  if (databaseid == InvalidOid && pending_write_requests != NIL)
6626  return true;
6627 
6628  /* Search to see if there's an open request to write this database. */
6629  if (list_member_oid(pending_write_requests, databaseid))
6630  return true;
6631 
6632  return false;
6633 }
#define NIL
Definition: pg_list.h:65
static List * pending_write_requests
Definition: pgstat.c:291
#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 1284 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().

1285 {
1286  PgStat_MsgDropdb msg;
1287 
1289  return;
1290 
1292  msg.m_databaseid = databaseid;
1293  pgstat_send(&msg, sizeof(msg));
1294 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4331
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:174
Oid m_databaseid
Definition: pgstat.h:309
PgStat_MsgHdr m_hdr
Definition: pgstat.h:308
#define PGINVALID_SOCKET
Definition: port.h:33
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4318

◆ pgstat_end_function_usage()

void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

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

1748 {
1749  PgStat_FunctionCounts *fs = fcu->fs;
1750  instr_time f_total;
1751  instr_time f_others;
1752  instr_time f_self;
1753 
1754  /* stats not wanted? */
1755  if (fs == NULL)
1756  return;
1757 
1758  /* total elapsed time in this function call */
1759  INSTR_TIME_SET_CURRENT(f_total);
1760  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1761 
1762  /* self usage: elapsed minus anything already charged to other calls */
1763  f_others = total_func_time;
1764  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1765  f_self = f_total;
1766  INSTR_TIME_SUBTRACT(f_self, f_others);
1767 
1768  /* update backend-wide total time */
1770 
1771  /*
1772  * Compute the new f_total_time as the total elapsed time added to the
1773  * pre-call value of f_total_time. This is necessary to avoid
1774  * double-counting any time taken by recursive calls of myself. (We do
1775  * not need any similar kluge for self time, since that already excludes
1776  * any recursive calls.)
1777  */
1778  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1779 
1780  /* update counters in function stats table */
1781  if (finalize)
1782  fs->f_numcalls++;
1783  fs->f_total_time = f_total;
1784  INSTR_TIME_ADD(fs->f_self_time, f_self);
1785 
1786  /* indicate that we have something to send */
1787  have_function_stats = true;
1788 }
instr_time f_self_time
Definition: pgstat.h:494
instr_time save_total
Definition: pgstat.h:1240
struct timeval instr_time
Definition: instr_time.h:150
instr_time f_total_time
Definition: pgstat.h:493
PgStat_FunctionCounts * fs
Definition: pgstat.h:1236
PgStat_Counter f_numcalls
Definition: pgstat.h:492
#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:298
static bool have_function_stats
Definition: pgstat.c:228
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1238

◆ pgstat_fetch_global()

◆ pgstat_fetch_slru()

PgStat_SLRUStats* pgstat_fetch_slru ( void  )

Definition at line 2687 of file pgstat.c.

References backend_read_statsfile(), and slruStats.

Referenced by pg_stat_get_slru().

2688 {
2690 
2691  return slruStats;
2692 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5686
static PgStat_SLRUStats slruStats[SLRU_NUM_ELEMENTS]
Definition: pgstat.c:284

◆ pgstat_fetch_stat_archiver()

PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2653 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2654 {
2656 
2657  return &archiverStats;
2658 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5686
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:282

◆ pgstat_fetch_stat_beentry()

◆ pgstat_fetch_stat_dbentry()

PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

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

2482 {
2483  /*
2484  * If not done for this transaction, read the statistics collector stats
2485  * file into some hash tables.
2486  */
2488 
2489  /*
2490  * Lookup the requested database; return NULL if not found
2491  */
2493  (void *) &dbid,
2494  HASH_FIND, NULL);
2495 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
static void backend_read_statsfile(void)
Definition: pgstat.c:5686
static HTAB * pgStatDBHash
Definition: pgstat.c:269

◆ pgstat_fetch_stat_funcentry()

PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

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

2565 {
2566  PgStat_StatDBEntry *dbentry;
2567  PgStat_StatFuncEntry *funcentry = NULL;
2568 
2569  /* load the stats file if needed */
2571 
2572  /* Lookup our database, then find the requested function. */
2574  if (dbentry != NULL && dbentry->functions != NULL)
2575  {
2576  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2577  (void *) &func_id,
2578  HASH_FIND, NULL);
2579  }
2580 
2581  return funcentry;
2582 }
HTAB * functions
Definition: pgstat.h:657
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2481
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
static void backend_read_statsfile(void)
Definition: pgstat.c:5686
Oid MyDatabaseId
Definition: globals.c:85

◆ pgstat_fetch_stat_local_beentry()

LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2618 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2619 {
2621 
2622  if (beid < 1 || beid > localNumBackends)
2623  return NULL;
2624 
2625  return &localBackendStatusTable[beid - 1];
2626 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3361
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:272
static int localNumBackends
Definition: pgstat.c:275

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

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

2638 {
2640 
2641  return localNumBackends;
2642 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3361
static int localNumBackends
Definition: pgstat.c:275

◆ pgstat_fetch_stat_tabentry()

PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

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

2509 {
2510  Oid dbid;
2511  PgStat_StatDBEntry *dbentry;
2512  PgStat_StatTabEntry *tabentry;
2513 
2514  /*
2515  * If not done for this transaction, read the statistics collector stats
2516  * file into some hash tables.
2517  */
2519 
2520  /*
2521  * Lookup our database, then look in its table hash table.
2522  */
2523  dbid = MyDatabaseId;
2525  (void *) &dbid,
2526  HASH_FIND, NULL);
2527  if (dbentry != NULL && dbentry->tables != NULL)
2528  {
2529  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2530  (void *) &relid,
2531  HASH_FIND, NULL);
2532  if (tabentry)
2533  return tabentry;
2534  }
2535 
2536  /*
2537  * If we didn't find it, maybe it's a shared table.
2538  */
2539  dbid = InvalidOid;
2541  (void *) &dbid,
2542  HASH_FIND, NULL);
2543  if (dbentry != NULL && dbentry->tables != NULL)
2544  {
2545  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2546  (void *) &relid,
2547  HASH_FIND, NULL);
2548  if (tabentry)
2549  return tabentry;
2550  }
2551 
2552  return NULL;
2553 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:5686
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pgStatDBHash
Definition: pgstat.c:269

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

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

4170 {
4171  PgBackendStatus *beentry;
4172  int i;
4173 
4174  beentry = BackendStatusArray;
4175  for (i = 1; i <= MaxBackends; i++)
4176  {
4177  /*
4178  * Although we expect the target backend's entry to be stable, that
4179  * doesn't imply that anyone else's is. To avoid identifying the
4180  * wrong backend, while we check for a match to the desired PID we
4181  * must follow the protocol of retrying if st_changecount changes
4182  * while we examine the entry, or if it's odd. (This might be
4183  * unnecessary, since fetching or storing an int is almost certainly
4184  * atomic, but let's play it safe.) We use a volatile pointer here to
4185  * ensure the compiler doesn't try to get cute.
4186  */
4187  volatile PgBackendStatus *vbeentry = beentry;
4188  bool found;
4189 
4190  for (;;)
4191  {
4192  int before_changecount;
4193  int after_changecount;
4194 
4195  pgstat_begin_read_activity(vbeentry, before_changecount);
4196 
4197  found = (vbeentry->st_procpid == pid);
4198 
4199  pgstat_end_read_activity(vbeentry, after_changecount);
4200 
4201  if (pgstat_read_activity_complete(before_changecount,
4202  after_changecount))
4203  break;
4204 
4205  /* Make sure we can break out of loop if stuck... */
4207  }
4208 
4209  if (found)
4210  {
4211  /* Now it is safe to use the non-volatile pointer */
4212  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4213  return "<insufficient privilege>";
4214  else if (*(beentry->st_activity_raw) == '\0')
4215  return "<command string not enabled>";
4216  else
4217  {
4218  /* this'll leak a bit of memory, but that seems acceptable */
4219  return pgstat_clip_activity(beentry->st_activity_raw);
4220  }
4221  }
4222 
4223  beentry++;
4224  }
4225 
4226  /* If we get here, caller is in error ... */
4227  return "<backend information not available>";
4228 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2700
Oid GetUserId(void)
Definition: miscinit.c:448
bool superuser(void)
Definition: superuser.c:46
int MaxBackends
Definition: globals.c:135
char * st_activity_raw
Definition: pgstat.h:1124
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1190
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1184
char * pgstat_clip_activity(const char *raw_activity)
Definition: pgstat.c:6644
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1196

◆ pgstat_get_crashed_backend_activity()

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

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

4248 {
4249  volatile PgBackendStatus *beentry;
4250  int i;
4251 
4252  beentry = BackendStatusArray;
4253 
4254  /*
4255  * We probably shouldn't get here before shared memory has been set up,
4256  * but be safe.
4257  */
4258  if (beentry == NULL || BackendActivityBuffer == NULL)
4259  return NULL;
4260 
4261  for (i = 1; i <= MaxBackends; i++)
4262  {
4263  if (beentry->st_procpid == pid)
4264  {
4265  /* Read pointer just once, so it can't change after validation */
4266  const char *activity = beentry->st_activity_raw;
4267  const char *activity_last;
4268 
4269  /*
4270  * We mustn't access activity string before we verify that it
4271  * falls within the BackendActivityBuffer. To make sure that the
4272  * entire string including its ending is contained within the
4273  * buffer, subtract one activity length from the buffer size.
4274  */
4277 
4278  if (activity < BackendActivityBuffer ||
4279  activity > activity_last)
4280  return NULL;
4281 
4282  /* If no string available, no point in a report */
4283  if (activity[0] == '\0')
4284  return NULL;
4285 
4286  /*
4287  * Copy only ASCII-safe characters so we don't run into encoding
4288  * problems when reporting the message; and be sure not to run off
4289  * the end of memory. As only ASCII characters are reported, it
4290  * doesn't seem necessary to perform multibyte aware clipping.
4291  */
4292  ascii_safe_strlcpy(buffer, activity,
4293  Min(buflen, pgstat_track_activity_query_size));
4294 
4295  return buffer;
4296  }
4297 
4298  beentry++;
4299  }
4300 
4301  /* PID not found */
4302  return NULL;
4303 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2700
static char * BackendActivityBuffer
Definition: pgstat.c:2704
#define Min(x, y)
Definition: c.h:920
static Size BackendActivityBufferSize
Definition: pgstat.c:2705
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
int MaxBackends
Definition: globals.c:135
char * st_activity_raw
Definition: pgstat.h:1124
int pgstat_track_activity_query_size
Definition: pgstat.c:127
int i

◆ pgstat_get_db_entry()

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

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

4773 {
4774  PgStat_StatDBEntry *result;
4775  bool found;
4776  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4777 
4778  /* Lookup or create the hash table entry for this database */
4780  &databaseid,
4781  action, &found);
4782 
4783  if (!create && !found)
4784  return NULL;
4785 
4786  /*
4787  * If not found, initialize the new one. This creates empty hash tables
4788  * for tables and functions, too.
4789  */
4790  if (!found)
4791  reset_dbentry_counters(result);
4792 
4793  return result;
4794 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4720
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
static HTAB * pgStatDBHash
Definition: pgstat.c:269
HASHACTION
Definition: hsearch.h:103

◆ pgstat_get_tab_entry()

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

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

4804 {
4805  PgStat_StatTabEntry *result;
4806  bool found;
4807  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4808 
4809  /* Lookup or create the hash table entry for this table */
4810  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4811  &tableoid,
4812  action, &found);
4813 
4814  if (!create && !found)
4815  return NULL;
4816 
4817  /* If not found, initialize the new one. */
4818  if (!found)
4819  {
4820  result->numscans = 0;
4821  result->tuples_returned = 0;
4822  result->tuples_fetched = 0;
4823  result->tuples_inserted = 0;
4824  result->tuples_updated = 0;
4825  result->tuples_deleted = 0;
4826  result->tuples_hot_updated = 0;
4827  result->n_live_tuples = 0;
4828  result->n_dead_tuples = 0;
4829  result->changes_since_analyze = 0;
4830  result->inserts_since_vacuum = 0;
4831  result->blocks_fetched = 0;
4832  result->blocks_hit = 0;
4833  result->vacuum_timestamp = 0;
4834  result->vacuum_count = 0;
4835  result->autovac_vacuum_timestamp = 0;
4836  result->autovac_vacuum_count = 0;
4837  result->analyze_timestamp = 0;
4838  result->analyze_count = 0;
4839  result->autovac_analyze_timestamp = 0;
4840  result->autovac_analyze_count = 0;
4841  }
4842 
4843  return result;
4844 }
PgStat_Counter analyze_count
Definition: pgstat.h:692
PgStat_Counter tuples_returned
Definition: pgstat.h:671
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:693
PgStat_Counter vacuum_count
Definition: pgstat.h:688
PgStat_Counter numscans
Definition: pgstat.h:669
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:677
PgStat_Counter tuples_inserted
Definition: pgstat.h:674
PgStat_Counter n_live_tuples
Definition: pgstat.h:679
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:682
TimestampTz vacuum_timestamp
Definition: pgstat.h:687
PgStat_Counter n_dead_tuples
Definition: pgstat.h:680
PgStat_Counter tuples_fetched
Definition: pgstat.h:672
PgStat_Counter blocks_hit
Definition: pgstat.h:685
TimestampTz analyze_timestamp
Definition: pgstat.h:691
PgStat_Counter changes_since_analyze
Definition: pgstat.h:681
PgStat_Counter tuples_deleted
Definition: pgstat.h:676
PgStat_Counter tuples_updated
Definition: pgstat.h:675
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:689
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:694
PgStat_Counter blocks_fetched
Definition: pgstat.h:684
HASHACTION
Definition: hsearch.h:103
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:690

◆ pgstat_get_wait_activity()

static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

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

3646 {
3647  const char *event_name = "unknown wait event";
3648 
3649  switch (w)
3650  {
3652  event_name = "ArchiverMain";
3653  break;
3655  event_name = "AutoVacuumMain";
3656  break;
3658  event_name = "BgWriterHibernate";
3659  break;
3661  event_name = "BgWriterMain";
3662  break;
3664  event_name = "CheckpointerMain";
3665  break;
3667  event_name = "LogicalApplyMain";
3668  break;
3670  event_name = "LogicalLauncherMain";
3671  break;
3673  event_name = "PgStatMain";
3674  break;
3676  event_name = "RecoveryWalStream";
3677  break;
3679  event_name = "SysLoggerMain";
3680  break;
3682  event_name = "WalReceiverMain";
3683  break;
3685  event_name = "WalSenderMain";
3686  break;
3688  event_name = "WalWriterMain";
3689  break;
3690  /* no default case, so that compiler will warn */
3691  }
3692 
3693  return event_name;
3694 }

◆ pgstat_get_wait_client()

static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

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

3704 {
3705  const char *event_name = "unknown wait event";
3706 
3707  switch (w)
3708  {
3710  event_name = "ClientRead";
3711  break;
3713  event_name = "ClientWrite";
3714  break;
3716  event_name = "GSSOpenServer";
3717  break;
3719  event_name = "LibPQWalReceiverConnect";
3720  break;
3722  event_name = "LibPQWalReceiverReceive";
3723  break;
3725  event_name = "SSLOpenServer";
3726  break;
3728  event_name = "WalReceiverWaitStart";
3729  break;
3731  event_name = "WalSenderWaitForWAL";
3732  break;
3734  event_name = "WalSenderWriteData";
3735  break;
3736  /* no default case, so that compiler will warn */
3737  }
3738 
3739  return event_name;
3740 }

◆ pgstat_get_wait_event()

const char* pgstat_get_wait_event ( uint32  wait_event_info)

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

3569 {
3570  uint32 classId;
3571  uint16 eventId;
3572  const char *event_name;
3573 
3574  /* report process as not waiting. */
3575  if (wait_event_info == 0)
3576  return NULL;
3577 
3578  classId = wait_event_info & 0xFF000000;
3579  eventId = wait_event_info & 0x0000FFFF;
3580 
3581  switch (classId)
3582  {
3583  case PG_WAIT_LWLOCK:
3584  event_name = GetLWLockIdentifier(classId, eventId);
3585  break;
3586  case PG_WAIT_LOCK:
3587  event_name = GetLockNameFromTagType(eventId);
3588  break;
3589  case PG_WAIT_BUFFER_PIN:
3590  event_name = "BufferPin";
3591  break;
3592  case PG_WAIT_ACTIVITY:
3593  {
3594  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3595 
3596  event_name = pgstat_get_wait_activity(w);
3597  break;
3598  }
3599  case PG_WAIT_CLIENT:
3600  {
3601  WaitEventClient w = (WaitEventClient) wait_event_info;
3602 
3603  event_name = pgstat_get_wait_client(w);
3604  break;
3605  }
3606  case PG_WAIT_EXTENSION:
3607  event_name = "Extension";
3608  break;
3609  case PG_WAIT_IPC:
3610  {
3611  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3612 
3613  event_name = pgstat_get_wait_ipc(w);
3614  break;
3615  }
3616  case PG_WAIT_TIMEOUT:
3617  {
3618  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3619 
3620  event_name = pgstat_get_wait_timeout(w);
3621  break;
3622  }
3623  case PG_WAIT_IO:
3624  {
3625  WaitEventIO w = (WaitEventIO) wait_event_info;
3626 
3627  event_name = pgstat_get_wait_io(w);
3628  break;
3629  }
3630  default:
3631  event_name = "unknown wait event";
3632  break;
3633  }
3634 
3635  return event_name;
3636 }
#define PG_WAIT_LOCK
Definition: pgstat.h:785
WaitEventIPC
Definition: pgstat.h:847
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3894
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3749
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:787
#define PG_WAIT_IO
Definition: pgstat.h:792
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3645
unsigned short uint16
Definition: c.h:366
#define PG_WAIT_CLIENT
Definition: pgstat.h:788
WaitEventClient
Definition: pgstat.h:827
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3703
unsigned int uint32
Definition: c.h:367
WaitEventTimeout
Definition: pgstat.h:899
#define PG_WAIT_EXTENSION
Definition: pgstat.h:789
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:786
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1170
WaitEventIO
Definition: pgstat.h:914
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:791
#define PG_WAIT_IPC
Definition: pgstat.h:790
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:809
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:3928
#define PG_WAIT_LWLOCK
Definition: pgstat.h:784
WaitEventActivity
Definition: pgstat.h:802

◆ pgstat_get_wait_event_type()

const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

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

3514 {
3515  uint32 classId;
3516  const char *event_type;
3517 
3518  /* report process as not waiting. */
3519  if (wait_event_info == 0)
3520  return NULL;
3521 
3522  classId = wait_event_info & 0xFF000000;
3523 
3524  switch (classId)
3525  {
3526  case PG_WAIT_LWLOCK:
3527  event_type = "LWLock";
3528  break;
3529  case PG_WAIT_LOCK:
3530  event_type = "Lock";
3531  break;
3532  case PG_WAIT_BUFFER_PIN:
3533  event_type = "BufferPin";
3534  break;
3535  case PG_WAIT_ACTIVITY:
3536  event_type = "Activity";
3537  break;
3538  case PG_WAIT_CLIENT:
3539  event_type = "Client";
3540  break;
3541  case PG_WAIT_EXTENSION:
3542  event_type = "Extension";
3543  break;
3544  case PG_WAIT_IPC:
3545  event_type = "IPC";
3546  break;
3547  case PG_WAIT_TIMEOUT:
3548  event_type = "Timeout";
3549  break;
3550  case PG_WAIT_IO:
3551  event_type = "IO";
3552  break;
3553  default:
3554  event_type = "???";
3555  break;
3556  }
3557 
3558  return event_type;
3559 }
#define PG_WAIT_LOCK
Definition: pgstat.h:785
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:787
#define PG_WAIT_IO
Definition: pgstat.h:792
#define PG_WAIT_CLIENT
Definition: pgstat.h:788
unsigned int uint32
Definition: c.h:367
#define PG_WAIT_EXTENSION
Definition: pgstat.h:789
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:786
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:791
#define PG_WAIT_IPC
Definition: pgstat.h:790
#define PG_WAIT_LWLOCK
Definition: pgstat.h:784

◆ pgstat_get_wait_io()

static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

Definition at line 3928 of file pgstat.c.

References WAIT_EVENT_BASEBACKUP_READ, WAIT_EVENT_BUFFILE_READ, 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_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_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().

3929 {
3930  const char *event_name = "unknown wait event";
3931 
3932  switch (w)
3933  {
3935  event_name = "BaseBackupRead";
3936  break;
3938  event_name = "BufFileRead";
3939  break;
3941  event_name = "BufFileWrite";
3942  break;
3944  event_name = "ControlFileRead";
3945  break;
3947  event_name = "ControlFileSync";
3948  break;
3950  event_name = "ControlFileSyncUpdate";
3951  break;
3953  event_name = "ControlFileWrite";
3954  break;
3956  event_name = "ControlFileWriteUpdate";
3957  break;
3959  event_name = "CopyFileRead";
3960  break;
3962  event_name = "CopyFileWrite";
3963  break;
3965  event_name = "DataFileExtend";
3966  break;
3968  event_name = "DataFileFlush";
3969  break;
3971  event_name = "DataFileImmediateSync";
3972  break;
3974  event_name = "DataFilePrefetch";
3975  break;
3977  event_name = "DataFileRead";
3978  break;
3980  event_name = "DataFileSync";
3981  break;
3983  event_name = "DataFileTruncate";
3984  break;
3986  event_name = "DataFileWrite";
3987  break;
3989  event_name = "DSMFillZeroWrite";
3990  break;
3992  event_name = "LockFileAddToDataDirRead";
3993  break;
3995  event_name = "LockFileAddToDataDirSync";
3996  break;
3998  event_name = "LockFileAddToDataDirWrite";
3999  break;
4001  event_name = "LockFileCreateRead";
4002  break;
4004  event_name = "LockFileCreateSync";
4005  break;
4007  event_name = "LockFileCreateWrite";
4008  break;
4010  event_name = "LockFileReCheckDataDirRead";
4011  break;
4013  event_name = "LogicalRewriteCheckpointSync";
4014  break;
4016  event_name = "LogicalRewriteMappingSync";
4017  break;
4019  event_name = "LogicalRewriteMappingWrite";
4020  break;
4022  event_name = "LogicalRewriteSync";
4023  break;
4025  event_name = "LogicalRewriteTruncate";
4026  break;
4028  event_name = "LogicalRewriteWrite";
4029  break;
4031  event_name = "RelationMapRead";
4032  break;
4034  event_name = "RelationMapSync";
4035  break;
4037  event_name = "RelationMapWrite";
4038  break;
4040  event_name = "ReorderBufferRead";
4041  break;
4043  event_name = "ReorderBufferWrite";
4044  break;
4046  event_name = "ReorderLogicalMappingRead";
4047  break;
4049  event_name = "ReplicationSlotRead";
4050  break;
4052  event_name = "ReplicationSlotRestoreSync";
4053  break;
4055  event_name = "ReplicationSlotSync";
4056  break;
4058  event_name = "ReplicationSlotWrite";
4059  break;
4061  event_name = "SLRUFlushSync";
4062  break;
4063  case WAIT_EVENT_SLRU_READ:
4064  event_name = "SLRURead";
4065  break;
4066  case WAIT_EVENT_SLRU_SYNC:
4067  event_name = "SLRUSync";
4068  break;
4069  case WAIT_EVENT_SLRU_WRITE:
4070  event_name = "SLRUWrite";
4071  break;
4073  event_name = "SnapbuildRead";
4074  break;
4076  event_name = "SnapbuildSync";
4077  break;
4079  event_name = "SnapbuildWrite";
4080  break;
4082  event_name = "TimelineHistoryFileSync";
4083  break;
4085  event_name = "TimelineHistoryFileWrite";
4086  break;
4088  event_name = "TimelineHistoryRead";
4089  break;
4091  event_name = "TimelineHistorySync";
4092  break;
4094  event_name = "TimelineHistoryWrite";
4095  break;
4097  event_name = "TwophaseFileRead";
4098  break;
4100  event_name = "TwophaseFileSync";
4101  break;
4103  event_name = "TwophaseFileWrite";
4104  break;
4106  event_name = "WALSenderTimelineHistoryRead";
4107  break;
4109  event_name = "WALBootstrapSync";
4110  break;
4112  event_name = "WALBootstrapWrite";
4113  break;
4115  event_name = "WALCopyRead";
4116  break;
4118  event_name = "WALCopySync";
4119  break;
4121  event_name = "WALCopyWrite";
4122  break;
4124  event_name = "WALInitSync";
4125  break;
4127  event_name = "WALInitWrite";
4128  break;
4129  case WAIT_EVENT_WAL_READ:
4130  event_name = "WALRead";
4131  break;
4132  case WAIT_EVENT_WAL_SYNC:
4133  event_name = "WALSync";
4134  break;
4136  event_name = "WALSyncMethodAssign";
4137  break;
4138  case WAIT_EVENT_WAL_WRITE:
4139  event_name = "WALWrite";
4140  break;
4141 
4142  /* no default case, so that compiler will warn */
4143  }
4144 
4145  return event_name;
4146 }

◆ pgstat_get_wait_ipc()

static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

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

3750 {
3751  const char *event_name = "unknown wait event";
3752 
3753  switch (w)
3754  {
3756  event_name = "BackupWaitWalArchive";
3757  break;
3759  event_name = "BgWorkerShutdown";
3760  break;
3762  event_name = "BgWorkerStartup";
3763  break;
3764  case WAIT_EVENT_BTREE_PAGE:
3765  event_name = "BtreePage";
3766  break;
3768  event_name = "CheckpointDone";
3769  break;
3771  event_name = "CheckpointStart";
3772  break;
3774  event_name = "ExecuteGather";
3775  break;
3777  event_name = "HashBatchAllocate";
3778  break;
3780  event_name = "HashBatchElect";
3781  break;
3783  event_name = "HashBatchLoad";
3784  break;
3786  event_name = "HashBuildAllocate";
3787  break;
3789  event_name = "HashBuildElect";
3790  break;
3792  event_name = "HashBuildHashInner";
3793  break;
3795  event_name = "HashBuildHashOuter";
3796  break;
3798  event_name = "HashGrowBatchesAllocate";
3799  break;
3801  event_name = "HashGrowBatchesDecide";
3802  break;
3804  event_name = "HashGrowBatchesElect";
3805  break;
3807  event_name = "HashGrowBatchesFinish";
3808  break;
3810  event_name = "HashGrowBatchesRepartition";
3811  break;
3813  event_name = "HashGrowBucketsAllocate";
3814  break;
3816  event_name = "HashGrowBucketsElect";
3817  break;
3819  event_name = "HashGrowBucketsReinsert";
3820  break;
3822  event_name = "LogicalSyncData";
3823  break;
3825  event_name = "LogicalSyncStateChange";
3826  break;
3828  event_name = "MessageQueueInternal";
3829  break;
3831  event_name = "MessageQueuePutMessage";
3832  break;
3833  case WAIT_EVENT_MQ_RECEIVE:
3834  event_name = "MessageQueueReceive";
3835  break;
3836  case WAIT_EVENT_MQ_SEND:
3837  event_name = "MessageQueueSend";
3838  break;
3840  event_name = "ParallelBitmapScan";
3841  break;
3843  event_name = "ParallelCreateIndexScan";
3844  break;
3846  event_name = "ParallelFinish";
3847  break;
3849  event_name = "ProcArrayGroupUpdate";
3850  break;
3852  event_name = "ProcSignalBarrier";
3853  break;
3854  case WAIT_EVENT_PROMOTE:
3855  event_name = "Promote";
3856  break;
3858  event_name = "RecoveryConflictSnapshot";
3859  break;
3861  event_name = "RecoveryConflictTablespace";
3862  break;
3864  event_name = "RecoveryPause";
3865  break;
3867  event_name = "ReplicationOriginDrop";
3868  break;
3870  event_name = "ReplicationSlotDrop";
3871  break;
3873  event_name = "SafeSnapshot";
3874  break;
3875  case WAIT_EVENT_SYNC_REP:
3876  event_name = "SyncRep";
3877  break;
3879  event_name = "XactGroupUpdate";
3880  break;
3881  /* no default case, so that compiler will warn */
3882  }
3883 
3884  return event_name;
3885 }

◆ pgstat_get_wait_timeout()

static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

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

3895 {
3896  const char *event_name = "unknown wait event";
3897 
3898  switch (w)
3899  {
3901  event_name = "BaseBackupThrottle";
3902  break;
3903  case WAIT_EVENT_PG_SLEEP:
3904  event_name = "PgSleep";
3905  break;
3907  event_name = "RecoveryApplyDelay";
3908  break;
3910  event_name = "RecoveryRetrieveRetryInterval";
3911  break;
3913  event_name = "VacuumDelay";
3914  break;
3915  /* no default case, so that compiler will warn */
3916  }
3917 
3918  return event_name;
3919 }

◆ pgstat_init()

void pgstat_init ( void  )

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

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

◆ pgstat_init_function_usage()

void pgstat_init_function_usage ( FunctionCallInfo  fcinfo,
PgStat_FunctionCallUsage fcu 
)

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

1677 {
1678  PgStat_BackendFunctionEntry *htabent;
1679  bool found;
1680 
1681  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1682  {
1683  /* stats not wanted */
1684  fcu->fs = NULL;
1685  return;
1686  }
1687 
1688  if (!pgStatFunctions)
1689  {
1690  /* First time through - initialize function stat table */
1691  HASHCTL hash_ctl;
1692 
1693  memset(&hash_ctl, 0, sizeof(hash_ctl));
1694  hash_ctl.keysize = sizeof(Oid);
1695  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1696  pgStatFunctions = hash_create("Function stat entries",
1698  &hash_ctl,
1699  HASH_ELEM | HASH_BLOBS);
1700  }
1701 
1702  /* Get the stats entry for this function, create if necessary */
1703  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1704  HASH_ENTER, &found);
1705  if (!found)
1706  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1707 
1708  fcu->fs = &htabent->f_counts;
1709 
1710  /* save stats for this function, later used to compensate for recursion */
1711  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1712 
1713  /* save current backend-wide total time */
1714  fcu->save_total = total_func_time;
1715 
1716  /* get clock time as of function start */
1718 }
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:1240
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:971
instr_time f_total_time
Definition: pgstat.h:493
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1236
PgStat_FunctionCounts f_counts
Definition: pgstat.h:504
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:105
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:318
FmgrInfo * flinfo
Definition: fmgr.h:87
Size keysize
Definition: hsearch.h:72
Oid fn_oid
Definition: fmgr.h:59
static instr_time total_func_time
Definition: pgstat.c:298
static HTAB * pgStatFunctions
Definition: pgstat.c:222
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1238
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry

◆ pgstat_initialize()

void pgstat_initialize ( void  )

Definition at line 2881 of file pgstat.c.

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

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2882 {
2883  /* Initialize MyBEEntry */
2885  {
2888  }
2889  else
2890  {
2891  /* Must be an auxiliary process */
2893 
2894  /*
2895  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
2896  * have a BackendId, the slot is statically allocated based on the
2897  * auxiliary process type (MyAuxProcType). Backends use slots indexed
2898  * in the range from 1 to MaxBackends (inclusive), so we use
2899  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2900  * auxiliary process.
2901  */
2903  }
2904 
2905  /* Set up a process-exit hook to clean up */
2907 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2700
BackendId MyBackendId
Definition: globals.c:81
int MaxBackends
Definition: globals.c:135
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
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:3094
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:72
#define Assert(condition)
Definition: c.h:738

◆ pgstat_initstats()

void pgstat_initstats ( Relation  rel)

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

1805 {
1806  Oid rel_id = rel->rd_id;
1807  char relkind = rel->rd_rel->relkind;
1808 
1809  /* We only count stats for things that have storage */
1810  if (!RELKIND_HAS_STORAGE(relkind))
1811  {
1812  rel->pgstat_info = NULL;
1813  return;
1814  }
1815 
1817  {
1818  /* We're not counting at all */
1819  rel->pgstat_info = NULL;
1820  return;
1821  }
1822 
1823  /*
1824  * If we already set up this relation in the current transaction, nothing
1825  * to do.
1826  */
1827  if (rel->pgstat_info != NULL &&
1828  rel->pgstat_info->t_id == rel_id)
1829  return;
1830 
1831  /* Else find or make the PgStat_TableStatus entry, and update link */
1832  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1833 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:174
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool pgstat_track_counts
Definition: pgstat.c:125
Oid rd_id
Definition: rel.h:111
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:1839
#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 1640 of file pgstat.c.

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

1641 {
1642  PgStat_MsgDummy msg;
1643 
1645  return;
1646 
1648  pgstat_send(&msg, sizeof(msg));
1649 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4331
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:174
#define PGINVALID_SOCKET
Definition: port.h:33
PgStat_MsgHdr m_hdr
Definition: pgstat.h:219
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4318

◆ pgstat_progress_end_command()

void pgstat_progress_end_command ( void  )

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

3283 {
3284  volatile PgBackendStatus *beentry = MyBEEntry;
3285 
3286  if (!beentry || !pgstat_track_activities)
3287  return;
3288 
3290  return;
3291 
3292  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3295  PGSTAT_END_WRITE_ACTIVITY(beentry);
3296 }
Oid st_progress_command_target
Definition: pgstat.h:1136
ProgressCommandType st_progress_command
Definition: pgstat.h:1135
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169

◆ pgstat_progress_start_command()

void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

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

3211 {
3212  volatile PgBackendStatus *beentry = MyBEEntry;
3213 
3214  if (!beentry || !pgstat_track_activities)
3215  return;
3216 
3217  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3218  beentry->st_progress_command = cmdtype;
3219  beentry->st_progress_command_target = relid;
3220  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3221  PGSTAT_END_WRITE_ACTIVITY(beentry);
3222 }
Oid st_progress_command_target
Definition: pgstat.h:1136
#define MemSet(start, val, len)
Definition: c.h:971
ProgressCommandType st_progress_command
Definition: pgstat.h:1135
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1137
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169

◆ pgstat_progress_update_multi_param()

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

Definition at line 3253 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(), update_basebackup_progress(), validate_index(), and WaitForLockersMultiple().

3255 {
3256  volatile PgBackendStatus *beentry = MyBEEntry;
3257  int i;
3258 
3259  if (!beentry || !pgstat_track_activities || nparam == 0)
3260  return;
3261 
3262  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3263 
3264  for (i = 0; i < nparam; ++i)
3265  {
3266  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3267 
3268  beentry->st_progress_param[index[i]] = val[i];
3269  }
3270 
3271  PGSTAT_END_WRITE_ACTIVITY(beentry);
3272 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1001
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
#define Assert(condition)
Definition: c.h:738
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1137
bool pgstat_track_activities
Definition: pgstat.c:124
int i
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169
long val
Definition: informix.c:664

◆ pgstat_progress_update_param()

void pgstat_progress_update_param ( int  index,
int64  val 
)

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

3232 {
3233  volatile PgBackendStatus *beentry = MyBEEntry;
3234 
3236 
3237  if (!beentry || !pgstat_track_activities)
3238  return;
3239 
3240  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3241  beentry->st_progress_param[index] = val;
3242  PGSTAT_END_WRITE_ACTIVITY(beentry);
3243 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:1001
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2701
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1176
#define Assert(condition)
Definition: c.h:738
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1137
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1169
long val
Definition: informix.c:664

◆ pgstat_read_current_status()

static void pgstat_read_current_status ( void  )
static

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

3362 {
3363  volatile PgBackendStatus *beentry;
3364  LocalPgBackendStatus *localtable;
3365  LocalPgBackendStatus *localentry;
3366  char *localappname,
3367  *localclienthostname,
3368  *localactivity;
3369 #ifdef USE_SSL
3370  PgBackendSSLStatus *localsslstatus;
3371 #endif
3372 #ifdef ENABLE_GSS
3373  PgBackendGSSStatus *localgssstatus;
3374 #endif
3375  int i;
3376 
3379  return; /* already done */
3380 
3382 
3383  /*
3384  * Allocate storage for local copy of state data. We can presume that
3385  * none of these requests overflow size_t, because we already calculated
3386  * the same values using mul_size during shmem setup. However, with
3387  * probably-silly values of pgstat_track_activity_query_size and
3388  * max_connections, the localactivity buffer could exceed 1GB, so use
3389  * "huge" allocation for that one.
3390  */
3391  localtable = (LocalPgBackendStatus *)
3394  localappname = (char *)
3397  localclienthostname = (char *)
3399  NAMEDATALEN * NumBackendStatSlots);
3400  localactivity = (char *)
3402  pgstat_track_activity_query_size * NumBackendStatSlots);
3403 #ifdef USE_SSL
3404  localsslstatus = (PgBackendSSLStatus *)
3407 #endif
3408 #ifdef ENABLE_GSS
3409  localgssstatus = (PgBackendGSSStatus *)
3412 #endif
3413 
3414  localNumBackends = 0;
3415 
3416  beentry = BackendStatusArray;
3417  localentry = localtable;
3418  for (i = 1; i <= NumBackendStatSlots; i++)
3419  {
3420  /*
3421  * Follow the protocol of retrying if st_changecount changes while we
3422  * copy the entry, or if it's odd. (The check for odd is needed to
3423  * cover the case where we are able to completely copy the entry while
3424  * the source backend is between increment steps.) We use a volatile
3425  * pointer here to ensure the compiler doesn't try to get cute.
3426  */
3427  for (;;)
3428  {
3429  int before_changecount;
3430  int after_changecount;
3431 
3432  pgstat_begin_read_activity(beentry, before_changecount);
3433 
3434  localentry->backendStatus.st_procpid = beentry->st_procpid;
3435  /* Skip all the data-copying work if entry is not in use */
3436  if (localentry->backendStatus.st_procpid > 0)
3437  {
3438  memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3439 
3440  /*
3441  * For each PgBackendStatus field that is a pointer, copy the
3442  * pointed-to data, then adjust the local copy of the pointer
3443  * field to point at the local copy of the data.
3444  *
3445  * strcpy is safe even if the string is modified concurrently,
3446  * because there's always a \0 at the end of the buffer.
3447  */
3448  strcpy(localappname, (char *) beentry->st_appname);
3449  localentry->backendStatus.st_appname = localappname;
3450  strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3451  localentry->backendStatus.st_clienthostname = localclienthostname;
3452  strcpy(localactivity, (char *) beentry->st_activity_raw);
3453  localentry->backendStatus.st_activity_raw = localactivity;
3454 #ifdef USE_SSL
3455  if (beentry->st_ssl)
3456  {
3457  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3458  localentry->backendStatus.st_sslstatus = localsslstatus;
3459  }
3460 #endif
3461 #ifdef ENABLE_GSS
3462  if (beentry->st_gss)
3463  {
3464  memcpy(localgssstatus, beentry->st_gssstatus, sizeof(PgBackendGSSStatus));
3465  localentry->backendStatus.st_gssstatus = localgssstatus;
3466  }
3467 #endif
3468  }
3469 
3470  pgstat_end_read_activity(beentry, after_changecount);
3471 
3472  if (pgstat_read_activity_complete(before_changecount,
3473  after_changecount))
3474  break;
3475 
3476  /* Make sure we can break out of loop if stuck... */
3478  }
3479 
3480  beentry++;
3481  /* Only valid entries get included into the local array */
3482  if (localentry->backendStatus.st_procpid > 0)
3483  {
3485  &localentry->backend_xid,
3486  &localentry->backend_xmin);
3487 
3488  localentry++;
3489  localappname += NAMEDATALEN;
3490  localclienthostname += NAMEDATALEN;
3491  localactivity += pgstat_track_activity_query_size;
3492 #ifdef USE_SSL
3493  localsslstatus++;
3494 #endif
3495 #ifdef ENABLE_GSS
3496  localgssstatus++;
3497 #endif
3498  localNumBackends++;
3499  }
3500  }
3501 
3502  /* Set the pointer only after completion of a valid table */
3503  localBackendStatusTable = localtable;
3504 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2700
static bool pgStatRunningInCollector
Definition: pgstat.c:180
TransactionId backend_xmin
Definition: pgstat.h:1226
#define NumBackendStatSlots
Definition: pgstat.c:117
char * st_clienthostname
Definition: pgstat.h:1101
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1220
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition: mcxt.c:1105
char * st_activity_raw
Definition: pgstat.h:1124
int pgstat_track_activity_query_size
Definition: pgstat.c:127
char * st_appname
Definition: pgstat.h:1115
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1190
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5820
PgBackendStatus backendStatus
Definition: pgstat.h:1214
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:403
#define Assert(condition)
Definition: c.h:738
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:272
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1184
static int localNumBackends
Definition: pgstat.c:275
#define unvolatize(underlying_type, expr)
Definition: c.h:1207
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:268
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1105
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1109
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1196

◆ pgstat_read_db_statsfile()

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

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

5395 {
5396  PgStat_StatTabEntry *tabentry;
5397  PgStat_StatTabEntry tabbuf;
5398  PgStat_StatFuncEntry funcbuf;
5399  PgStat_StatFuncEntry *funcentry;
5400  FILE *fpin;
5401  int32 format_id;
5402  bool found;
5403  char statfile[MAXPGPATH];
5404 
5405  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5406 
5407  /*
5408  * Try to open the stats file. If it doesn't exist, the backends simply
5409  * return zero for anything and the collector simply starts from scratch
5410  * with empty counters.
5411  *
5412  * ENOENT is a possibility if the stats collector is not running or has
5413  * not yet written the stats file the first time. Any other failure
5414  * condition is suspicious.
5415  */
5416  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5417  {
5418  if (errno != ENOENT)
5421  errmsg("could not open statistics file \"%s\": %m",
5422  statfile)));
5423  return;
5424  }
5425 
5426  /*
5427  * Verify it's of the expected format.
5428  */
5429  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5430  format_id != PGSTAT_FILE_FORMAT_ID)
5431  {
5432  ereport(pgStatRunningInCollector ? LOG : WARNING,
5433  (errmsg("corrupted statistics file \"%s\"", statfile)));
5434  goto done;
5435  }
5436 
5437  /*
5438  * We found an existing collector stats file. Read it and put all the
5439  * hashtable entries into place.
5440  */
5441  for (;;)
5442  {
5443  switch (fgetc(fpin))
5444  {
5445  /*
5446  * 'T' A PgStat_StatTabEntry follows.
5447  */
5448  case 'T':
5449  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5450  fpin) != sizeof(PgStat_StatTabEntry))
5451  {
5452  ereport(pgStatRunningInCollector ? LOG : WARNING,
5453  (errmsg("corrupted statistics file \"%s\"",
5454  statfile)));
5455  goto done;
5456  }
5457 
5458  /*
5459  * Skip if table data not wanted.
5460  */
5461  if (tabhash == NULL)
5462  break;
5463 
5464  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5465  (void *) &tabbuf.tableid,
5466  HASH_ENTER, &found);
5467 
5468  if (found)
5469  {
5470  ereport(pgStatRunningInCollector ? LOG : WARNING,
5471  (errmsg("corrupted statistics file \"%s\"",
5472  statfile)));
5473  goto done;
5474  }
5475 
5476  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5477  break;
5478 
5479  /*
5480  * 'F' A PgStat_StatFuncEntry follows.
5481  */
5482  case 'F':
5483  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5484  fpin) != sizeof(PgStat_StatFuncEntry))
5485  {
5486  ereport(pgStatRunningInCollector ? LOG : WARNING,
5487  (errmsg("corrupted statistics file \"%s\"",
5488  statfile)));
5489  goto done;
5490  }
5491 
5492  /*
5493  * Skip if function data not wanted.
5494  */
5495  if (funchash == NULL)
5496  break;
5497 
5498  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5499  (void *) &funcbuf.functionid,
5500  HASH_ENTER, &found);
5501 
5502  if (found)
5503  {
5504  ereport(pgStatRunningInCollector ? LOG : WARNING,
5505  (errmsg("corrupted statistics file \"%s\"",
5506  statfile)));
5507  goto done;
5508  }
5509 
5510  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5511  break;
5512 
5513  /*
5514  * 'E' The EOF marker of a complete stats file.
5515  */
5516  case 'E':
5517  goto done;
5518 
5519  default:
5520  ereport(pgStatRunningInCollector ? LOG : WARNING,
5521  (errmsg("corrupted statistics file \"%s\"",
5522  statfile)));
5523  goto done;
5524  }
5525  }
5526 
5527 done:
5528  FreeFile(fpin);
5529 
5530  if (permanent)
5531  {
5532  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5533  unlink(statfile);
5534  }
5535 }
static bool pgStatRunningInCollector
Definition: pgstat.c:180
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
#define LOG
Definition: elog.h:26
#define PG_BINARY_R
Definition: c.h:1235
signed int int32
Definition: c.h:355
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
int errcode_for_file_access(void)
Definition: elog.c:633
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:144
int FreeFile(FILE *file)
Definition: fd.c:2521
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:617
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
static void get_dbstat_filename(bool permanent, bool tempname, Oid databaseid, char *filename, int len)
Definition: pgstat.c:4993

◆ pgstat_read_db_statsfile_timestamp()

static bool pgstat_read_db_statsfile_timestamp ( Oid  databaseid,
bool  permanent,
TimestampTz ts 
)
static

Definition at line 5555 of file pgstat.c.

References AllocateFile(), PgStat_StatDBEntry::databaseid, ereport, errcode_for_file_access(), errmsg(), FreeFile(), LOG, offsetof, PG_BINARY_R, PGSTAT_FILE_FORMAT_ID, pgstat_stat_filename, PGSTAT_STAT_PERMANENT_FILENAME, pgStatRunningInCollector, SLRU_NUM_ELEMENTS, PgStat_StatDBEntry::stats_timestamp, PgStat_GlobalStats::stats_timestamp, and WARNING.

Referenced by backend_read_statsfile().

5557 {
5558  PgStat_StatDBEntry dbentry;
5559  PgStat_GlobalStats myGlobalStats;
5560  PgStat_ArchiverStats myArchiverStats;
5561  PgStat_SLRUStats mySLRUStats[SLRU_NUM_ELEMENTS];
5562  FILE *fpin;
5563  int32 format_id;
5564  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5565 
5566  /*
5567  * Try to open the stats file. As above, anything but ENOENT is worthy of
5568  * complaining about.
5569  */
5570  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5571  {
5572  if (errno != ENOENT)