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 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 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_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_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_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)
 
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)
 
const char * pgstat_get_backend_desc (BackendType backendType)
 
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)
 

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
 
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 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().

◆ TABSTAT_QUANTUM

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

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

1915 {
1916  PgStat_SubXactStatus *xact_state;
1918 
1919  /*
1920  * If this is the first rel to be modified at the current nest level, we
1921  * first have to push a transaction stack entry.
1922  */
1923  xact_state = get_tabstat_stack_level(nest_level);
1924 
1925  /* Now make a per-table stack entry */
1926  trans = (PgStat_TableXactStatus *)
1928  sizeof(PgStat_TableXactStatus));
1929  trans->nest_level = nest_level;
1930  trans->upper = pgstat_info->trans;
1931  trans->parent = pgstat_info;
1932  trans->next = xact_state->first;
1933  xact_state->first = trans;
1934  pgstat_info->trans = trans;
1935 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_TableXactStatus * next
Definition: pgstat.h:179
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:1892
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:396
PgStat_TableXactStatus * first
Definition: pgstat.c:215
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ allow_immediate_pgstat_restart()

void allow_immediate_pgstat_restart ( void  )

Definition at line 784 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

785 {
787 }
static time_t last_pgstat_start_time
Definition: pgstat.c:152

◆ AtEOSubXact_PgStat()

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

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

2175 {
2176  PgStat_SubXactStatus *xact_state;
2177 
2178  /*
2179  * Transfer transactional insert/update counts into the next higher
2180  * subtransaction state.
2181  */
2182  xact_state = pgStatXactStack;
2183  if (xact_state != NULL &&
2184  xact_state->nest_level >= nestDepth)
2185  {
2187  PgStat_TableXactStatus *next_trans;
2188 
2189  /* delink xact_state from stack immediately to simplify reuse case */
2190  pgStatXactStack = xact_state->prev;
2191 
2192  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2193  {
2194  PgStat_TableStatus *tabstat;
2195 
2196  next_trans = trans->next;
2197  Assert(trans->nest_level == nestDepth);
2198  tabstat = trans->parent;
2199  Assert(tabstat->trans == trans);
2200  if (isCommit)
2201  {
2202  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2203  {
2204  if (trans->truncated)
2205  {
2206  /* propagate the truncate status one level up */
2208  /* replace upper xact stats with ours */
2209  trans->upper->tuples_inserted = trans->tuples_inserted;
2210  trans->upper->tuples_updated = trans->tuples_updated;
2211  trans->upper->tuples_deleted = trans->tuples_deleted;
2212  }
2213  else
2214  {
2215  trans->upper->tuples_inserted += trans->tuples_inserted;
2216  trans->upper->tuples_updated += trans->tuples_updated;
2217  trans->upper->tuples_deleted += trans->tuples_deleted;
2218  }
2219  tabstat->trans = trans->upper;
2220  pfree(trans);
2221  }
2222  else
2223  {
2224  /*
2225  * When there isn't an immediate parent state, we can just
2226  * reuse the record instead of going through a
2227  * palloc/pfree pushup (this works since it's all in
2228  * TopTransactionContext anyway). We have to re-link it
2229  * into the parent level, though, and that might mean
2230  * pushing a new entry into the pgStatXactStack.
2231  */
2232  PgStat_SubXactStatus *upper_xact_state;
2233 
2234  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2235  trans->next = upper_xact_state->first;
2236  upper_xact_state->first = trans;
2237  trans->nest_level = nestDepth - 1;
2238  }
2239  }
2240  else
2241  {
2242  /*
2243  * On abort, update top-level tabstat counts, then forget the
2244  * subtransaction
2245  */
2246 
2247  /* first restore values obliterated by truncate */
2249  /* count attempted actions regardless of commit/abort */
2250  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2251  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2252  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2253  /* inserted tuples are dead, deleted tuples are unaffected */
2254  tabstat->t_counts.t_delta_dead_tuples +=
2255  trans->tuples_inserted + trans->tuples_updated;
2256  tabstat->trans = trans->upper;
2257  pfree(trans);
2258  }
2259  }
2260  pfree(xact_state);
2261  }
2262 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
struct PgStat_TableXactStatus * next
Definition: pgstat.h:179
PgStat_TableCounts t_counts
Definition: pgstat.h:158
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:1892
void pfree(void *pointer)
Definition: mcxt.c:1056
PgStat_Counter t_tuples_updated
Definition: pgstat.h:105
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2028
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:111
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:106
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:214
#define Assert(condition)
Definition: c.h:739
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:218
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:396
PgStat_TableXactStatus * first
Definition: pgstat.c:215
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2013
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ AtEOXact_PgStat()

void AtEOXact_PgStat ( bool  isCommit,
bool  parallel 
)

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

2088 {
2089  PgStat_SubXactStatus *xact_state;
2090 
2091  /* Don't count parallel worker transaction stats */
2092  if (!parallel)
2093  {
2094  /*
2095  * Count transaction commit or abort. (We use counters, not just
2096  * bools, in case the reporting message isn't sent right away.)
2097  */
2098  if (isCommit)
2099  pgStatXactCommit++;
2100  else
2102  }
2103 
2104  /*
2105  * Transfer transactional insert/update counts into the base tabstat
2106  * entries. We don't bother to free any of the transactional state, since
2107  * it's all in TopTransactionContext and will go away anyway.
2108  */
2109  xact_state = pgStatXactStack;
2110  if (xact_state != NULL)
2111  {
2113 
2114  Assert(xact_state->nest_level == 1);
2115  Assert(xact_state->prev == NULL);
2116  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2117  {
2118  PgStat_TableStatus *tabstat;
2119 
2120  Assert(trans->nest_level == 1);
2121  Assert(trans->upper == NULL);
2122  tabstat = trans->parent;
2123  Assert(tabstat->trans == trans);
2124  /* restore pre-truncate stats (if any) in case of aborted xact */
2125  if (!isCommit)
2127  /* count attempted actions regardless of commit/abort */
2128  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2129  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2130  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2131  if (isCommit)
2132  {
2133  tabstat->t_counts.t_truncated = trans->truncated;
2134  if (trans->truncated)
2135  {
2136  /* forget live/dead stats seen by backend thus far */
2137  tabstat->t_counts.t_delta_live_tuples = 0;
2138  tabstat->t_counts.t_delta_dead_tuples = 0;
2139  }
2140  /* insert adds a live tuple, delete removes one */
2141  tabstat->t_counts.t_delta_live_tuples +=
2142  trans->tuples_inserted - trans->tuples_deleted;
2143  /* update and delete each create a dead tuple */
2144  tabstat->t_counts.t_delta_dead_tuples +=
2145  trans->tuples_updated + trans->tuples_deleted;
2146  /* insert, update, delete each count as one change event */
2147  tabstat->t_counts.t_changed_tuples +=
2148  trans->tuples_inserted + trans->tuples_updated +
2149  trans->tuples_deleted;
2150  }
2151  else
2152  {
2153  /* inserted tuples are dead, deleted tuples are unaffected */
2154  tabstat->t_counts.t_delta_dead_tuples +=
2155  trans->tuples_inserted + trans->tuples_updated;
2156  /* an aborted xact generates no changed_tuple events */
2157  }
2158  tabstat->trans = NULL;
2159  }
2160  }
2161  pgStatXactStack = NULL;
2162 
2163  /* Make sure any stats snapshot is thrown away */
2165 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:110
PgStat_Counter tuples_updated
Definition: pgstat.h:168
static int pgStatXactCommit
Definition: pgstat.c:220
struct PgStat_TableXactStatus * next
Definition: pgstat.h:179
PgStat_TableCounts t_counts
Definition: pgstat.h:158
PgStat_Counter t_tuples_updated
Definition: pgstat.h:105
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2028
static int pgStatXactRollback
Definition: pgstat.c:221
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter t_delta_dead_tuples
Definition: pgstat.h:111
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter t_tuples_deleted
Definition: pgstat.h:106
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:214
PgStat_Counter t_changed_tuples
Definition: pgstat.h:112
#define Assert(condition)
Definition: c.h:739
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5767
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:218
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:396
PgStat_TableXactStatus * first
Definition: pgstat.c:215
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ AtPrepare_PgStat()

void AtPrepare_PgStat ( void  )

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

2274 {
2275  PgStat_SubXactStatus *xact_state;
2276 
2277  xact_state = pgStatXactStack;
2278  if (xact_state != NULL)
2279  {
2281 
2282  Assert(xact_state->nest_level == 1);
2283  Assert(xact_state->prev == NULL);
2284  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2285  {
2286  PgStat_TableStatus *tabstat;
2287  TwoPhasePgStatRecord record;
2288 
2289  Assert(trans->nest_level == 1);
2290  Assert(trans->upper == NULL);
2291  tabstat = trans->parent;
2292  Assert(tabstat->trans == trans);
2293 
2294  record.tuples_inserted = trans->tuples_inserted;
2295  record.tuples_updated = trans->tuples_updated;
2296  record.tuples_deleted = trans->tuples_deleted;
2297  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2298  record.updated_pre_trunc = trans->updated_pre_trunc;
2299  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2300  record.t_id = tabstat->t_id;
2301  record.t_shared = tabstat->t_shared;
2302  record.t_truncated = trans->truncated;
2303 
2305  &record, sizeof(TwoPhasePgStatRecord));
2306  }
2307  }
2308 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
struct PgStat_TableXactStatus * next
Definition: pgstat.h:179
PgStat_Counter deleted_pre_trunc
Definition: pgstat.h:173
PgStat_Counter deleted_pre_trunc
Definition: pgstat.c:233
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1187
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:232
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:231
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter tuples_updated
Definition: pgstat.c:229
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:214
#define Assert(condition)
Definition: c.h:739
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:171
PgStat_Counter tuples_inserted
Definition: pgstat.c:228
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:218
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
PgStat_Counter tuples_deleted
Definition: pgstat.c:230
#define TWOPHASE_RM_PGSTAT_ID
Definition: twophase_rmgr.h:26
PgStat_Counter updated_pre_trunc
Definition: pgstat.h:172
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:396
PgStat_TableXactStatus * first
Definition: pgstat.c:215
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ backend_read_statsfile()

static void backend_read_statsfile ( void  )
static

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

5614 {
5615  TimestampTz min_ts = 0;
5616  TimestampTz ref_ts = 0;
5617  Oid inquiry_db;
5618  int count;
5619 
5620  /* already read it? */
5621  if (pgStatDBHash)
5622  return;
5624 
5625  /*
5626  * In a normal backend, we check staleness of the data for our own DB, and
5627  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5628  * check staleness of the shared-catalog data, and send InvalidOid in
5629  * inquiry messages so as not to force writing unnecessary data.
5630  */
5632  inquiry_db = InvalidOid;
5633  else
5634  inquiry_db = MyDatabaseId;
5635 
5636  /*
5637  * Loop until fresh enough stats file is available or we ran out of time.
5638  * The stats inquiry message is sent repeatedly in case collector drops
5639  * it; but not every single time, as that just swamps the collector.
5640  */
5641  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5642  {
5643  bool ok;
5644  TimestampTz file_ts = 0;
5645  TimestampTz cur_ts;
5646 
5648 
5649  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5650 
5651  cur_ts = GetCurrentTimestamp();
5652  /* Calculate min acceptable timestamp, if we didn't already */
5653  if (count == 0 || cur_ts < ref_ts)
5654  {
5655  /*
5656  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5657  * msec before now. This indirectly ensures that the collector
5658  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5659  * an autovacuum worker, however, we want a lower delay to avoid
5660  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5661  * number of workers is low, this shouldn't be a problem).
5662  *
5663  * We don't recompute min_ts after sleeping, except in the
5664  * unlikely case that cur_ts went backwards. So we might end up
5665  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5666  * practice that shouldn't happen, though, as long as the sleep
5667  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5668  * tell the collector that our cutoff time is less than what we'd
5669  * actually accept.
5670  */
5671  ref_ts = cur_ts;
5673  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5675  else
5676  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5678  }
5679 
5680  /*
5681  * If the file timestamp is actually newer than cur_ts, we must have
5682  * had a clock glitch (system time went backwards) or there is clock
5683  * skew between our processor and the stats collector's processor.
5684  * Accept the file, but send an inquiry message anyway to make
5685  * pgstat_recv_inquiry do a sanity check on the collector's time.
5686  */
5687  if (ok && file_ts > cur_ts)
5688  {
5689  /*
5690  * A small amount of clock skew between processors isn't terribly
5691  * surprising, but a large difference is worth logging. We
5692  * arbitrarily define "large" as 1000 msec.
5693  */
5694  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5695  {
5696  char *filetime;
5697  char *mytime;
5698 
5699  /* Copy because timestamptz_to_str returns a static buffer */
5700  filetime = pstrdup(timestamptz_to_str(file_ts));
5701  mytime = pstrdup(timestamptz_to_str(cur_ts));
5702  elog(LOG, "stats collector's time %s is later than backend local time %s",
5703  filetime, mytime);
5704  pfree(filetime);
5705  pfree(mytime);
5706  }
5707 
5708  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5709  break;
5710  }
5711 
5712  /* Normal acceptance case: file is not older than cutoff time */
5713  if (ok && file_ts >= min_ts)
5714  break;
5715 
5716  /* Not there or too old, so kick the collector and wait a bit */
5717  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5718  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5719 
5720  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5721  }
5722 
5723  if (count >= PGSTAT_POLL_LOOP_COUNT)
5724  ereport(LOG,
5725  (errmsg("using stale statistics instead of current ones "
5726  "because stats collector is not responding")));
5727 
5728  /*
5729  * Autovacuum launcher wants stats about all databases, but a shallow read
5730  * is sufficient. Regular backends want a deep read for just the tables
5731  * they can see (MyDatabaseId + shared catalogs).
5732  */
5735  else
5737 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:79
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
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:154
#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:1598
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:76
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3276
#define ereport(elevel, rest)
Definition: elog.h:141
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:5100
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
static bool pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent, TimestampTz *ts)
Definition: pgstat.c:5494
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3270
#define Assert(condition)
Definition: c.h:739
static HTAB * pgStatDBHash
Definition: pgstat.c:243
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1743

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 2645 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2646 {
2647  Size size;
2648 
2649  /* BackendStatusArray: */
2650  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2651  /* BackendAppnameBuffer: */
2652  size = add_size(size,
2654  /* BackendClientHostnameBuffer: */
2655  size = add_size(size,
2657  /* BackendActivityBuffer: */
2658  size = add_size(size,
2660 #ifdef USE_SSL
2661  /* BackendSslStatusBuffer: */
2662  size = add_size(size,
2664 #endif
2665  return size;
2666 }
#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:467

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

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

2674 {
2675  Size size;
2676  bool found;
2677  int i;
2678  char *buffer;
2679 
2680  /* Create or attach to the shared array */
2681  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2683  ShmemInitStruct("Backend Status Array", size, &found);
2684 
2685  if (!found)
2686  {
2687  /*
2688  * We're the first - initialize.
2689  */
2690  MemSet(BackendStatusArray, 0, size);
2691  }
2692 
2693  /* Create or attach to the shared appname buffer */
2695  BackendAppnameBuffer = (char *)
2696  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2697 
2698  if (!found)
2699  {
2700  MemSet(BackendAppnameBuffer, 0, size);
2701 
2702  /* Initialize st_appname pointers. */
2703  buffer = BackendAppnameBuffer;
2704  for (i = 0; i < NumBackendStatSlots; i++)
2705  {
2706  BackendStatusArray[i].st_appname = buffer;
2707  buffer += NAMEDATALEN;
2708  }
2709  }
2710 
2711  /* Create or attach to the shared client hostname buffer */
2713  BackendClientHostnameBuffer = (char *)
2714  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2715 
2716  if (!found)
2717  {
2719 
2720  /* Initialize st_clienthostname pointers. */
2721  buffer = BackendClientHostnameBuffer;
2722  for (i = 0; i < NumBackendStatSlots; i++)
2723  {
2725  buffer += NAMEDATALEN;
2726  }
2727  }
2728 
2729  /* Create or attach to the shared activity buffer */
2732  BackendActivityBuffer = (char *)
2733  ShmemInitStruct("Backend Activity Buffer",
2735  &found);
2736 
2737  if (!found)
2738  {
2740 
2741  /* Initialize st_activity pointers. */
2742  buffer = BackendActivityBuffer;
2743  for (i = 0; i < NumBackendStatSlots; i++)
2744  {
2747  }
2748  }
2749 
2750 #ifdef USE_SSL
2751  /* Create or attach to the shared SSL status buffer */
2753  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2754  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2755 
2756  if (!found)
2757  {
2758  PgBackendSSLStatus *ptr;
2759 
2760  MemSet(BackendSslStatusBuffer, 0, size);
2761 
2762  /* Initialize st_sslstatus pointers. */
2763  ptr = BackendSslStatusBuffer;
2764  for (i = 0; i < NumBackendStatSlots; i++)
2765  {
2767  ptr++;
2768  }
2769  }
2770 #endif
2771 
2772 #ifdef ENABLE_GSS
2773  /* Create or attach to the shared GSSAPI status buffer */
2775  BackendGssStatusBuffer = (PgBackendGSSStatus *)
2776  ShmemInitStruct("Backend GSS Status Buffer", size, &found);
2777 
2778  if (!found)
2779  {
2780  PgBackendGSSStatus *ptr;
2781 
2782  MemSet(BackendGssStatusBuffer, 0, size);
2783 
2784  /* Initialize st_gssstatus pointers. */
2785  ptr = BackendGssStatusBuffer;
2786  for (i = 0; i < NumBackendStatSlots; i++)
2787  {
2789  ptr++;
2790  }
2791  }
2792 #endif
2793 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2627
static char * BackendActivityBuffer
Definition: pgstat.c:2631
static Size BackendActivityBufferSize
Definition: pgstat.c:2632
#define MemSet(start, val, len)
Definition: c.h:962
#define NumBackendStatSlots
Definition: pgstat.c:117
char * st_clienthostname
Definition: pgstat.h:1064
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2629
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
char * st_activity_raw
Definition: pgstat.h:1087
int pgstat_track_activity_query_size
Definition: pgstat.c:127
char * st_appname
Definition: pgstat.h:1078
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
size_t Size
Definition: c.h:467
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1068
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1072
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2630

◆ find_funcstat_entry()

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

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

1668 {
1669  if (pgStatFunctions == NULL)
1670  return NULL;
1671 
1673  (void *) &func_id,
1674  HASH_FIND, NULL);
1675 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static HTAB * pgStatFunctions
Definition: pgstat.c:196

◆ find_tabstat_entry()

PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

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

1873 {
1874  TabStatHashEntry *hash_entry;
1875 
1876  /* If hashtable doesn't exist, there are no entries at all */
1877  if (!pgStatTabHash)
1878  return NULL;
1879 
1880  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1881  if (!hash_entry)
1882  return NULL;
1883 
1884  /* Note that this step could also return NULL, but that's correct */
1885  return hash_entry->tsa_entry;
1886 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static HTAB * pgStatTabHash
Definition: pgstat.c:190
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:184

◆ get_dbstat_filename()

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

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

4953 {
4954  int printed;
4955 
4956  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4957  printed = snprintf(filename, len, "%s/db_%u.%s",
4958  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4960  databaseid,
4961  tempname ? "tmp" : "stat");
4962  if (printed >= len)
4963  elog(ERROR, "overlength pgstat path");
4964 }
#define PGSTAT_STAT_PERMANENT_DIRECTORY
Definition: pgstat.h:28
#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:228
#define snprintf
Definition: port.h:192

◆ get_tabstat_entry()

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

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

1784 {
1785  TabStatHashEntry *hash_entry;
1786  PgStat_TableStatus *entry;
1787  TabStatusArray *tsa;
1788  bool found;
1789 
1790  /*
1791  * Create hash table if we don't have it already.
1792  */
1793  if (pgStatTabHash == NULL)
1794  {
1795  HASHCTL ctl;
1796 
1797  memset(&ctl, 0, sizeof(ctl));
1798  ctl.keysize = sizeof(Oid);
1799  ctl.entrysize = sizeof(TabStatHashEntry);
1800 
1801  pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1803  &ctl,
1804  HASH_ELEM | HASH_BLOBS);
1805  }
1806 
1807  /*
1808  * Find an entry or create a new one.
1809  */
1810  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1811  if (!found)
1812  {
1813  /* initialize new entry with null pointer */
1814  hash_entry->tsa_entry = NULL;
1815  }
1816 
1817  /*
1818  * If entry is already valid, we're done.
1819  */
1820  if (hash_entry->tsa_entry)
1821  return hash_entry->tsa_entry;
1822 
1823  /*
1824  * Locate the first pgStatTabList entry with free space, making a new list
1825  * entry if needed. Note that we could get an OOM failure here, but if so
1826  * we have left the hashtable and the list in a consistent state.
1827  */
1828  if (pgStatTabList == NULL)
1829  {
1830  /* Set up first pgStatTabList entry */
1833  sizeof(TabStatusArray));
1834  }
1835 
1836  tsa = pgStatTabList;
1837  while (tsa->tsa_used >= TABSTAT_QUANTUM)
1838  {
1839  if (tsa->tsa_next == NULL)
1840  tsa->tsa_next = (TabStatusArray *)
1842  sizeof(TabStatusArray));
1843  tsa = tsa->tsa_next;
1844  }
1845 
1846  /*
1847  * Allocate a PgStat_TableStatus entry within this list entry. We assume
1848  * the entry was already zeroed, either at creation or after last use.
1849  */
1850  entry = &tsa->tsa_entries[tsa->tsa_used++];
1851  entry->t_id = rel_id;
1852  entry->t_shared = isshared;
1853 
1854  /*
1855  * Now we can fill the entry in pgStatTabHash.
1856  */
1857  hash_entry->tsa_entry = entry;
1858 
1859  return entry;
1860 }
int tsa_used
Definition: pgstat.c:172
#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:906
struct TabStatusArray * tsa_next
Definition: pgstat.c:171
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:190
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:173
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define HASH_BLOBS
Definition: hsearch.h:88
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:184
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
static TabStatusArray * pgStatTabList
Definition: pgstat.c:176
#define TABSTAT_QUANTUM
Definition: pgstat.c:167

◆ get_tabstat_stack_level()

static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

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

1893 {
1894  PgStat_SubXactStatus *xact_state;
1895 
1896  xact_state = pgStatXactStack;
1897  if (xact_state == NULL || xact_state->nest_level != nest_level)
1898  {
1899  xact_state = (PgStat_SubXactStatus *)
1901  sizeof(PgStat_SubXactStatus));
1902  xact_state->nest_level = nest_level;
1903  xact_state->prev = pgStatXactStack;
1904  xact_state->first = NULL;
1905  pgStatXactStack = xact_state;
1906  }
1907  return xact_state;
1908 }
MemoryContext TopTransactionContext
Definition: mcxt.c:49
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:214
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:218
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
PgStat_TableXactStatus * first
Definition: pgstat.c:215

◆ pgstat_beshutdown_hook()

static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

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

3077 {
3078  volatile PgBackendStatus *beentry = MyBEEntry;
3079 
3080  /*
3081  * If we got as far as discovering our own database ID, we can report what
3082  * we did to the collector. Otherwise, we'd be sending an invalid
3083  * database ID, so forget it. (This means that accesses to pg_database
3084  * during failed backend starts might never get counted.)
3085  */
3086  if (OidIsValid(MyDatabaseId))
3087  pgstat_report_stat(true);
3088 
3089  /*
3090  * Clear my status entry, following the protocol of bumping st_changecount
3091  * before and after. We use a volatile pointer here to ensure the
3092  * compiler doesn't try to get cute.
3093  */
3094  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3095 
3096  beentry->st_procpid = 0; /* mark invalid */
3097 
3098  PGSTAT_END_WRITE_ACTIVITY(beentry);
3099 }
#define OidIsValid(objectId)
Definition: c.h:645
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
Oid MyDatabaseId
Definition: globals.c:85
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132
void pgstat_report_stat(bool force)
Definition: pgstat.c:806

◆ pgstat_bestart()

void pgstat_bestart ( void  )

Definition at line 2850 of file pgstat.c.

References am_walsender, application_name, Assert, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, B_WAL_WRITER, 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(), BgWriterProcess, CheckpointerProcess, elog, FATAL, GetSessionUserId(), Port::gss, PgBackendGSSStatus::gss_auth, PgBackendGSSStatus::gss_enc, PgBackendGSSStatus::gss_princ, InvalidBackendId, InvalidOid, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, MemSet, MyAuxProcType, MyBackendId, MyBEEntry, MyDatabaseId, MyProcPid, MyProcPort, MyStartTimestamp, NAMEDATALEN, NotAnAuxProcess, 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, 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, StartupProcess, STATE_UNDEFINED, strlcpy(), unvolatize, WalReceiverProcess, and WalWriterProcess.

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2851 {
2852  volatile PgBackendStatus *vbeentry = MyBEEntry;
2853  PgBackendStatus lbeentry;
2854 #ifdef USE_SSL
2855  PgBackendSSLStatus lsslstatus;
2856 #endif
2857 #ifdef ENABLE_GSS
2858  PgBackendGSSStatus lgssstatus;
2859 #endif
2860 
2861  /* pgstats state must be initialized from pgstat_initialize() */
2862  Assert(vbeentry != NULL);
2863 
2864  /*
2865  * To minimize the time spent modifying the PgBackendStatus entry, and
2866  * avoid risk of errors inside the critical section, we first copy the
2867  * shared-memory struct to a local variable, then modify the data in the
2868  * local variable, then copy the local variable back to shared memory.
2869  * Only the last step has to be inside the critical section.
2870  *
2871  * Most of the data we copy from shared memory is just going to be
2872  * overwritten, but the struct's not so large that it's worth the
2873  * maintenance hassle to copy only the needful fields.
2874  */
2875  memcpy(&lbeentry,
2876  unvolatize(PgBackendStatus *, vbeentry),
2877  sizeof(PgBackendStatus));
2878 
2879  /* These structs can just start from zeroes each time, though */
2880 #ifdef USE_SSL
2881  memset(&lsslstatus, 0, sizeof(lsslstatus));
2882 #endif
2883 #ifdef ENABLE_GSS
2884  memset(&lgssstatus, 0, sizeof(lgssstatus));
2885 #endif
2886 
2887  /*
2888  * Now fill in all the fields of lbeentry, except for strings that are
2889  * out-of-line data. Those have to be handled separately, below.
2890  */
2891  lbeentry.st_procpid = MyProcPid;
2892 
2894  {
2896  {
2897  /* Autovacuum Launcher */
2899  }
2900  else if (IsAutoVacuumWorkerProcess())
2901  {
2902  /* Autovacuum Worker */
2903  lbeentry.st_backendType = B_AUTOVAC_WORKER;
2904  }
2905  else if (am_walsender)
2906  {
2907  /* Wal sender */
2908  lbeentry.st_backendType = B_WAL_SENDER;
2909  }
2910  else if (IsBackgroundWorker)
2911  {
2912  /* bgworker */
2913  lbeentry.st_backendType = B_BG_WORKER;
2914  }
2915  else
2916  {
2917  /* client-backend */
2918  lbeentry.st_backendType = B_BACKEND;
2919  }
2920  }
2921  else
2922  {
2923  /* Must be an auxiliary process */
2925  switch (MyAuxProcType)
2926  {
2927  case StartupProcess:
2928  lbeentry.st_backendType = B_STARTUP;
2929  break;
2930  case BgWriterProcess:
2931  lbeentry.st_backendType = B_BG_WRITER;
2932  break;
2933  case CheckpointerProcess:
2934  lbeentry.st_backendType = B_CHECKPOINTER;
2935  break;
2936  case WalWriterProcess:
2937  lbeentry.st_backendType = B_WAL_WRITER;
2938  break;
2939  case WalReceiverProcess:
2940  lbeentry.st_backendType = B_WAL_RECEIVER;
2941  break;
2942  default:
2943  elog(FATAL, "unrecognized process type: %d",
2944  (int) MyAuxProcType);
2945  }
2946  }
2947 
2949  lbeentry.st_activity_start_timestamp = 0;
2950  lbeentry.st_state_start_timestamp = 0;
2951  lbeentry.st_xact_start_timestamp = 0;
2952  lbeentry.st_databaseid = MyDatabaseId;
2953 
2954  /* We have userid for client-backends, wal-sender and bgworker processes */
2955  if (lbeentry.st_backendType == B_BACKEND
2956  || lbeentry.st_backendType == B_WAL_SENDER
2957  || lbeentry.st_backendType == B_BG_WORKER)
2958  lbeentry.st_userid = GetSessionUserId();
2959  else
2960  lbeentry.st_userid = InvalidOid;
2961 
2962  /*
2963  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2964  * If so, use all-zeroes client address, which is dealt with specially in
2965  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2966  */
2967  if (MyProcPort)
2968  memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
2969  sizeof(lbeentry.st_clientaddr));
2970  else
2971  MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
2972 
2973 #ifdef USE_SSL
2974  if (MyProcPort && MyProcPort->ssl != NULL)
2975  {
2976  lbeentry.st_ssl = true;
2984  }
2985  else
2986  {
2987  lbeentry.st_ssl = false;
2988  }
2989 #else
2990  lbeentry.st_ssl = false;
2991 #endif
2992 
2993 #ifdef ENABLE_GSS
2994  if (MyProcPort && MyProcPort->gss != NULL)
2995  {
2996  lbeentry.st_gss = true;
2997  lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
2998  lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
2999 
3000  if (lgssstatus.gss_auth)
3002  }
3003  else
3004  {
3005  lbeentry.st_gss = false;
3006  }
3007 #else
3008  lbeentry.st_gss = false;
3009 #endif
3010 
3011  lbeentry.st_state = STATE_UNDEFINED;
3014 
3015  /*
3016  * we don't zero st_progress_param here to save cycles; nobody should
3017  * examine it until st_progress_command has been set to something other
3018  * than PROGRESS_COMMAND_INVALID
3019  */
3020 
3021  /*
3022  * We're ready to enter the critical section that fills the shared-memory
3023  * status entry. We follow the protocol of bumping st_changecount before
3024  * and after; and make sure it's even afterwards. We use a volatile
3025  * pointer here to ensure the compiler doesn't try to get cute.
3026  */
3027  PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
3028 
3029  /* make sure we'll memcpy the same st_changecount back */
3030  lbeentry.st_changecount = vbeentry->st_changecount;
3031 
3032  memcpy(unvolatize(PgBackendStatus *, vbeentry),
3033  &lbeentry,
3034  sizeof(PgBackendStatus));
3035 
3036  /*
3037  * We can write the out-of-line strings and structs using the pointers
3038  * that are in lbeentry; this saves some de-volatilizing messiness.
3039  */
3040  lbeentry.st_appname[0] = '\0';
3043  NAMEDATALEN);
3044  else
3045  lbeentry.st_clienthostname[0] = '\0';
3046  lbeentry.st_activity_raw[0] = '\0';
3047  /* Also make sure the last byte in each string area is always 0 */
3048  lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
3049  lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
3051 
3052 #ifdef USE_SSL
3053  memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
3054 #endif
3055 #ifdef ENABLE_GSS
3056  memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
3057 #endif
3058 
3059  PGSTAT_END_WRITE_ACTIVITY(vbeentry);
3060 
3061  /* Update app name to current GUC setting */
3062  if (application_name)
3064 }
char ssl_issuer_dn[NAMEDATALEN]
Definition: pgstat.h:995
char gss_princ[NAMEDATALEN]
Definition: pgstat.h:1009
bool ssl_compression
Definition: pgstat.h:984
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:986
Oid st_progress_command_target
Definition: pgstat.h:1099
int MyProcPid
Definition: globals.c:40
BackendId MyBackendId
Definition: globals.c:81
struct Port * MyProcPort
Definition: globals.c:43
const char * be_gssapi_get_princ(Port *port)
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:1057
char ssl_client_dn[NAMEDATALEN]
Definition: pgstat.h:987
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:985
SockAddr st_clientaddr
Definition: pgstat.h:1063
#define MemSet(start, val, len)
Definition: c.h:962
ProgressCommandType st_progress_command
Definition: pgstat.h:1098
char ssl_client_serial[NAMEDATALEN]
Definition: pgstat.h:993
BackendState st_state
Definition: pgstat.h:1075
char * st_clienthostname
Definition: pgstat.h:1064
Oid GetSessionUserId(void)
Definition: miscinit.c:414
bool IsBackgroundWorker
Definition: globals.c:111
Oid st_databaseid
Definition: pgstat.h:1061
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:128
SockAddr raddr
Definition: libpq-be.h:126
bool am_walsender
Definition: walsender.c:115
bool be_tls_get_compression(Port *port)
#define FATAL
Definition: elog.h:52
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
char * st_activity_raw
Definition: pgstat.h:1087
int pgstat_track_activity_query_size
Definition: pgstat.c:127
TimestampTz st_state_start_timestamp
Definition: pgstat.h:1058
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3276
char * st_appname
Definition: pgstat.h:1078
bool be_gssapi_get_enc(Port *port)
#define InvalidBackendId
Definition: backendid.h:23
TimestampTz MyStartTimestamp
Definition: globals.c:42
int be_tls_get_cipher_bits(Port *port)
AuxProcType MyAuxProcType
Definition: bootstrap.c:72
Oid MyDatabaseId
Definition: globals.c:85
BackendType st_backendType
Definition: pgstat.h:1052
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3287
#define InvalidOid
Definition: postgres_ext.h:36
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3270
#define Assert(condition)
Definition: c.h:739
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:541
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:1195
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:1056
#define elog(elevel,...)
Definition: elog.h:228
int st_changecount
Definition: pgstat.h:1046
const char * be_tls_get_cipher(Port *port)
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:1055
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1068
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1072
bool be_gssapi_get_auth(Port *port)

◆ pgstat_clear_snapshot()

void pgstat_clear_snapshot ( void  )

Definition at line 5767 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

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

5768 {
5769  /* Release memory, if any was allocated */
5770  if (pgStatLocalContext)
5772 
5773  /* Reset variables */
5774  pgStatLocalContext = NULL;
5775  pgStatDBHash = NULL;
5776  localBackendStatusTable = NULL;
5777  localNumBackends = 0;
5778 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:246
static HTAB * pgStatDBHash
Definition: pgstat.c:243
static int localNumBackends
Definition: pgstat.c:249
static MemoryContext pgStatLocalContext
Definition: pgstat.c:242

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

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

6516 {
6517  char *activity;
6518  int rawlen;
6519  int cliplen;
6520 
6521  /*
6522  * Some callers, like pgstat_get_backend_current_activity(), do not
6523  * guarantee that the buffer isn't concurrently modified. We try to take
6524  * care that the buffer is always terminated by a NUL byte regardless, but
6525  * let's still be paranoid about the string's length. In those cases the
6526  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
6527  * large.
6528  */
6529  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
6530 
6531  /* now double-guaranteed to be NUL terminated */
6532  rawlen = strlen(activity);
6533 
6534  /*
6535  * All supported server-encodings make it possible to determine the length
6536  * of a multi-byte character from its first byte (this is not the case for
6537  * client encodings, see GB18030). As st_activity is always stored using
6538  * server encoding, this allows us to perform multi-byte aware truncation,
6539  * even if the string earlier was truncated in the middle of a multi-byte
6540  * character.
6541  */
6542  cliplen = pg_mbcliplen(activity, rawlen,
6544 
6545  activity[cliplen] = '\0';
6546 
6547  return activity;
6548 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:862
int pgstat_track_activity_query_size
Definition: pgstat.c:127
static int cliplen(const char *str, int len, int limit)
Definition: mbutils.c:929

◆ pgstat_collect_oids()

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

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

1199 {
1200  HTAB *htab;
1201  HASHCTL hash_ctl;
1202  Relation rel;
1203  TableScanDesc scan;
1204  HeapTuple tup;
1205  Snapshot snapshot;
1206 
1207  memset(&hash_ctl, 0, sizeof(hash_ctl));
1208  hash_ctl.keysize = sizeof(Oid);
1209  hash_ctl.entrysize = sizeof(Oid);
1210  hash_ctl.hcxt = CurrentMemoryContext;
1211  htab = hash_create("Temporary table of OIDs",
1213  &hash_ctl,
1215 
1216  rel = table_open(catalogid, AccessShareLock);
1217  snapshot = RegisterSnapshot(GetLatestSnapshot());
1218  scan = table_beginscan(rel, snapshot, 0, NULL);
1219  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1220  {
1221  Oid thisoid;
1222  bool isnull;
1223 
1224  thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1225  Assert(!isnull);
1226 
1228 
1229  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1230  }
1231  table_endscan(scan);
1232  UnregisterSnapshot(snapshot);
1234 
1235  return htab;
1236 }
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:454
#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:906
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:208
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:1290
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:316
Size keysize
Definition: hsearch.h:72
#define Assert(condition)
Definition: c.h:739
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:849
#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 1987 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().

1988 {
1989  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1990 
1991  if (pgstat_info != NULL)
1992  {
1993  /* We have to log the effect at the proper transactional level */
1994  int nest_level = GetCurrentTransactionNestLevel();
1995 
1996  if (pgstat_info->trans == NULL ||
1997  pgstat_info->trans->nest_level != nest_level)
1998  add_tabstat_xact_level(pgstat_info, nest_level);
1999 
2000  pgstat_info->trans->tuples_deleted++;
2001  }
2002 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:210
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1914
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157

◆ pgstat_count_heap_insert()

void pgstat_count_heap_insert ( Relation  rel,
PgStat_Counter  n 
)

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

1942 {
1943  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1944 
1945  if (pgstat_info != NULL)
1946  {
1947  /* We have to log the effect at the proper transactional level */
1948  int nest_level = GetCurrentTransactionNestLevel();
1949 
1950  if (pgstat_info->trans == NULL ||
1951  pgstat_info->trans->nest_level != nest_level)
1952  add_tabstat_xact_level(pgstat_info, nest_level);
1953 
1954  pgstat_info->trans->tuples_inserted += n;
1955  }
1956 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:210
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1914
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157

◆ pgstat_count_heap_update()

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

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

1963 {
1964  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1965 
1966  if (pgstat_info != NULL)
1967  {
1968  /* We have to log the effect at the proper transactional level */
1969  int nest_level = GetCurrentTransactionNestLevel();
1970 
1971  if (pgstat_info->trans == NULL ||
1972  pgstat_info->trans->nest_level != nest_level)
1973  add_tabstat_xact_level(pgstat_info, nest_level);
1974 
1975  pgstat_info->trans->tuples_updated++;
1976 
1977  /* t_tuples_hot_updated is nontransactional, so just advance it */
1978  if (hot)
1979  pgstat_info->t_counts.t_tuples_hot_updated++;
1980  }
1981 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
PgStat_Counter t_tuples_hot_updated
Definition: pgstat.h:107
PgStat_TableCounts t_counts
Definition: pgstat.h:158
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:210
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1914
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157

◆ pgstat_count_truncate()

void pgstat_count_truncate ( Relation  rel)

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

2043 {
2044  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2045 
2046  if (pgstat_info != NULL)
2047  {
2048  /* We have to log the effect at the proper transactional level */
2049  int nest_level = GetCurrentTransactionNestLevel();
2050 
2051  if (pgstat_info->trans == NULL ||
2052  pgstat_info->trans->nest_level != nest_level)
2053  add_tabstat_xact_level(pgstat_info, nest_level);
2054 
2055  pgstat_truncate_save_counters(pgstat_info->trans);
2056  pgstat_info->trans->tuples_inserted = 0;
2057  pgstat_info->trans->tuples_updated = 0;
2058  pgstat_info->trans->tuples_deleted = 0;
2059  }
2060 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:210
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1914
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:2013

◆ pgstat_db_requested()

static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 6488 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

6489 {
6490  /*
6491  * If any requests are outstanding at all, we should write the stats for
6492  * shared catalogs (the "database" with OID 0). This ensures that
6493  * backends will see up-to-date stats for shared catalogs, even though
6494  * they send inquiry messages mentioning only their own DB.
6495  */
6496  if (databaseid == InvalidOid && pending_write_requests != NIL)
6497  return true;
6498 
6499  /* Search to see if there's an open request to write this database. */
6500  if (list_member_oid(pending_write_requests, databaseid))
6501  return true;
6502 
6503  return false;
6504 }
#define NIL
Definition: pg_list.h:65
static List * pending_write_requests
Definition: pgstat.c:264
#define InvalidOid
Definition: postgres_ext.h:36
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:675

◆ pgstat_drop_database()

void pgstat_drop_database ( Oid  databaseid)

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

1249 {
1250  PgStat_MsgDropdb msg;
1251 
1253  return;
1254 
1256  msg.m_databaseid = databaseid;
1257  pgstat_send(&msg, sizeof(msg));
1258 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4337
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:148
Oid m_databaseid
Definition: pgstat.h:306
PgStat_MsgHdr m_hdr
Definition: pgstat.h:305
#define PGINVALID_SOCKET
Definition: port.h:33
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4324

◆ pgstat_end_function_usage()

void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

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

1688 {
1689  PgStat_FunctionCounts *fs = fcu->fs;
1690  instr_time f_total;
1691  instr_time f_others;
1692  instr_time f_self;
1693 
1694  /* stats not wanted? */
1695  if (fs == NULL)
1696  return;
1697 
1698  /* total elapsed time in this function call */
1699  INSTR_TIME_SET_CURRENT(f_total);
1700  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1701 
1702  /* self usage: elapsed minus anything already charged to other calls */
1703  f_others = total_func_time;
1704  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1705  f_self = f_total;
1706  INSTR_TIME_SUBTRACT(f_self, f_others);
1707 
1708  /* update backend-wide total time */
1710 
1711  /*
1712  * Compute the new f_total_time as the total elapsed time added to the
1713  * pre-call value of f_total_time. This is necessary to avoid
1714  * double-counting any time taken by recursive calls of myself. (We do
1715  * not need any similar kluge for self time, since that already excludes
1716  * any recursive calls.)
1717  */
1718  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1719 
1720  /* update counters in function stats table */
1721  if (finalize)
1722  fs->f_numcalls++;
1723  fs->f_total_time = f_total;
1724  INSTR_TIME_ADD(fs->f_self_time, f_self);
1725 
1726  /* indicate that we have something to send */
1727  have_function_stats = true;
1728 }
instr_time f_self_time
Definition: pgstat.h:463
instr_time save_total
Definition: pgstat.h:1203
struct timeval instr_time
Definition: instr_time.h:150
instr_time f_total_time
Definition: pgstat.h:462
PgStat_FunctionCounts * fs
Definition: pgstat.h:1199
PgStat_Counter f_numcalls
Definition: pgstat.h:461
#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:271
static bool have_function_stats
Definition: pgstat.c:202
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1201

◆ pgstat_fetch_global()

◆ pgstat_fetch_stat_archiver()

PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2597 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2598 {
2600 
2601  return &archiverStats;
2602 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5613
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:256

◆ pgstat_fetch_stat_beentry()

◆ pgstat_fetch_stat_dbentry()

PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

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

2426 {
2427  /*
2428  * If not done for this transaction, read the statistics collector stats
2429  * file into some hash tables.
2430  */
2432 
2433  /*
2434  * Lookup the requested database; return NULL if not found
2435  */
2437  (void *) &dbid,
2438  HASH_FIND, NULL);
2439 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static void backend_read_statsfile(void)
Definition: pgstat.c:5613
static HTAB * pgStatDBHash
Definition: pgstat.c:243

◆ pgstat_fetch_stat_funcentry()

PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

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

2509 {
2510  PgStat_StatDBEntry *dbentry;
2511  PgStat_StatFuncEntry *funcentry = NULL;
2512 
2513  /* load the stats file if needed */
2515 
2516  /* Lookup our database, then find the requested function. */
2518  if (dbentry != NULL && dbentry->functions != NULL)
2519  {
2520  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2521  (void *) &func_id,
2522  HASH_FIND, NULL);
2523  }
2524 
2525  return funcentry;
2526 }
HTAB * functions
Definition: pgstat.h:624
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2425
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static void backend_read_statsfile(void)
Definition: pgstat.c:5613
Oid MyDatabaseId
Definition: globals.c:85

◆ pgstat_fetch_stat_local_beentry()

LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2562 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2563 {
2565 
2566  if (beid < 1 || beid > localNumBackends)
2567  return NULL;
2568 
2569  return &localBackendStatusTable[beid - 1];
2570 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3343
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:246
static int localNumBackends
Definition: pgstat.c:249

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

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

2582 {
2584 
2585  return localNumBackends;
2586 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3343
static int localNumBackends
Definition: pgstat.c:249

◆ pgstat_fetch_stat_tabentry()

PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

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

2453 {
2454  Oid dbid;
2455  PgStat_StatDBEntry *dbentry;
2456  PgStat_StatTabEntry *tabentry;
2457 
2458  /*
2459  * If not done for this transaction, read the statistics collector stats
2460  * file into some hash tables.
2461  */
2463 
2464  /*
2465  * Lookup our database, then look in its table hash table.
2466  */
2467  dbid = MyDatabaseId;
2469  (void *) &dbid,
2470  HASH_FIND, NULL);
2471  if (dbentry != NULL && dbentry->tables != NULL)
2472  {
2473  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2474  (void *) &relid,
2475  HASH_FIND, NULL);
2476  if (tabentry)
2477  return tabentry;
2478  }
2479 
2480  /*
2481  * If we didn't find it, maybe it's a shared table.
2482  */
2483  dbid = InvalidOid;
2485  (void *) &dbid,
2486  HASH_FIND, NULL);
2487  if (dbentry != NULL && dbentry->tables != NULL)
2488  {
2489  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2490  (void *) &relid,
2491  HASH_FIND, NULL);
2492  if (tabentry)
2493  return tabentry;
2494  }
2495 
2496  return NULL;
2497 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:5613
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pgStatDBHash
Definition: pgstat.c:243

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

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

4134 {
4135  PgBackendStatus *beentry;
4136  int i;
4137 
4138  beentry = BackendStatusArray;
4139  for (i = 1; i <= MaxBackends; i++)
4140  {
4141  /*
4142  * Although we expect the target backend's entry to be stable, that
4143  * doesn't imply that anyone else's is. To avoid identifying the
4144  * wrong backend, while we check for a match to the desired PID we
4145  * must follow the protocol of retrying if st_changecount changes
4146  * while we examine the entry, or if it's odd. (This might be
4147  * unnecessary, since fetching or storing an int is almost certainly
4148  * atomic, but let's play it safe.) We use a volatile pointer here to
4149  * ensure the compiler doesn't try to get cute.
4150  */
4151  volatile PgBackendStatus *vbeentry = beentry;
4152  bool found;
4153 
4154  for (;;)
4155  {
4156  int before_changecount;
4157  int after_changecount;
4158 
4159  pgstat_begin_read_activity(vbeentry, before_changecount);
4160 
4161  found = (vbeentry->st_procpid == pid);
4162 
4163  pgstat_end_read_activity(vbeentry, after_changecount);
4164 
4165  if (pgstat_read_activity_complete(before_changecount,
4166  after_changecount))
4167  break;
4168 
4169  /* Make sure we can break out of loop if stuck... */
4171  }
4172 
4173  if (found)
4174  {
4175  /* Now it is safe to use the non-volatile pointer */
4176  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4177  return "<insufficient privilege>";
4178  else if (*(beentry->st_activity_raw) == '\0')
4179  return "<command string not enabled>";
4180  else
4181  {
4182  /* this'll leak a bit of memory, but that seems acceptable */
4183  return pgstat_clip_activity(beentry->st_activity_raw);
4184  }
4185  }
4186 
4187  beentry++;
4188  }
4189 
4190  /* If we get here, caller is in error ... */
4191  return "<backend information not available>";
4192 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2627
Oid GetUserId(void)
Definition: miscinit.c:380
bool superuser(void)
Definition: superuser.c:46
int MaxBackends
Definition: globals.c:135
char * st_activity_raw
Definition: pgstat.h:1087
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1153
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1147
char * pgstat_clip_activity(const char *raw_activity)
Definition: pgstat.c:6515
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1159

◆ pgstat_get_backend_desc()

const char* pgstat_get_backend_desc ( BackendType  backendType)

Definition at line 4270 of file pgstat.c.

References B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, and B_WAL_WRITER.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), BackendInitialize(), and pg_stat_get_activity().

4271 {
4272  const char *backendDesc = "unknown process type";
4273 
4274  switch (backendType)
4275  {
4276  case B_AUTOVAC_LAUNCHER:
4277  backendDesc = "autovacuum launcher";
4278  break;
4279  case B_AUTOVAC_WORKER:
4280  backendDesc = "autovacuum worker";
4281  break;
4282  case B_BACKEND:
4283  backendDesc = "client backend";
4284  break;
4285  case B_BG_WORKER:
4286  backendDesc = "background worker";
4287  break;
4288  case B_BG_WRITER:
4289  backendDesc = "background writer";
4290  break;
4291  case B_CHECKPOINTER:
4292  backendDesc = "checkpointer";
4293  break;
4294  case B_STARTUP:
4295  backendDesc = "startup";
4296  break;
4297  case B_WAL_RECEIVER:
4298  backendDesc = "walreceiver";
4299  break;
4300  case B_WAL_SENDER:
4301  backendDesc = "walsender";
4302  break;
4303  case B_WAL_WRITER:
4304  backendDesc = "walwriter";
4305  break;
4306  }
4307 
4308  return backendDesc;
4309 }

◆ pgstat_get_crashed_backend_activity()

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

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

4212 {
4213  volatile PgBackendStatus *beentry;
4214  int i;
4215 
4216  beentry = BackendStatusArray;
4217 
4218  /*
4219  * We probably shouldn't get here before shared memory has been set up,
4220  * but be safe.
4221  */
4222  if (beentry == NULL || BackendActivityBuffer == NULL)
4223  return NULL;
4224 
4225  for (i = 1; i <= MaxBackends; i++)
4226  {
4227  if (beentry->st_procpid == pid)
4228  {
4229  /* Read pointer just once, so it can't change after validation */
4230  const char *activity = beentry->st_activity_raw;
4231  const char *activity_last;
4232 
4233  /*
4234  * We mustn't access activity string before we verify that it
4235  * falls within the BackendActivityBuffer. To make sure that the
4236  * entire string including its ending is contained within the
4237  * buffer, subtract one activity length from the buffer size.
4238  */
4241 
4242  if (activity < BackendActivityBuffer ||
4243  activity > activity_last)
4244  return NULL;
4245 
4246  /* If no string available, no point in a report */
4247  if (activity[0] == '\0')
4248  return NULL;
4249 
4250  /*
4251  * Copy only ASCII-safe characters so we don't run into encoding
4252  * problems when reporting the message; and be sure not to run off
4253  * the end of memory. As only ASCII characters are reported, it
4254  * doesn't seem necessary to perform multibyte aware clipping.
4255  */
4256  ascii_safe_strlcpy(buffer, activity,
4257  Min(buflen, pgstat_track_activity_query_size));
4258 
4259  return buffer;
4260  }
4261 
4262  beentry++;
4263  }
4264 
4265  /* PID not found */
4266  return NULL;
4267 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2627
static char * BackendActivityBuffer
Definition: pgstat.c:2631
#define Min(x, y)
Definition: c.h:911
static Size BackendActivityBufferSize
Definition: pgstat.c:2632
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:1087
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 4737 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().

4738 {
4739  PgStat_StatDBEntry *result;
4740  bool found;
4741  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4742 
4743  /* Lookup or create the hash table entry for this database */
4745  &databaseid,
4746  action, &found);
4747 
4748  if (!create && !found)
4749  return NULL;
4750 
4751  /*
4752  * If not found, initialize the new one. This creates empty hash tables
4753  * for tables and functions, too.
4754  */
4755  if (!found)
4756  reset_dbentry_counters(result);
4757 
4758  return result;
4759 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4685
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static HTAB * pgStatDBHash
Definition: pgstat.c:243
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 4768 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::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().

4769 {
4770  PgStat_StatTabEntry *result;
4771  bool found;
4772  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4773 
4774  /* Lookup or create the hash table entry for this table */
4775  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4776  &tableoid,
4777  action, &found);
4778 
4779  if (!create && !found)
4780  return NULL;
4781 
4782  /* If not found, initialize the new one. */
4783  if (!found)
4784  {
4785  result->numscans = 0;
4786  result->tuples_returned = 0;
4787  result->tuples_fetched = 0;
4788  result->tuples_inserted = 0;
4789  result->tuples_updated = 0;
4790  result->tuples_deleted = 0;
4791  result->tuples_hot_updated = 0;
4792  result->n_live_tuples = 0;
4793  result->n_dead_tuples = 0;
4794  result->changes_since_analyze = 0;
4795  result->blocks_fetched = 0;
4796  result->blocks_hit = 0;
4797  result->vacuum_timestamp = 0;
4798  result->vacuum_count = 0;
4799  result->autovac_vacuum_timestamp = 0;
4800  result->autovac_vacuum_count = 0;
4801  result->analyze_timestamp = 0;
4802  result->analyze_count = 0;
4803  result->autovac_analyze_timestamp = 0;
4804  result->autovac_analyze_count = 0;
4805  }
4806 
4807  return result;
4808 }
PgStat_Counter analyze_count
Definition: pgstat.h:658
PgStat_Counter tuples_returned
Definition: pgstat.h:638
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:659
PgStat_Counter vacuum_count
Definition: pgstat.h:654
PgStat_Counter numscans
Definition: pgstat.h:636
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:644
PgStat_Counter tuples_inserted
Definition: pgstat.h:641
PgStat_Counter n_live_tuples
Definition: pgstat.h:646
TimestampTz vacuum_timestamp
Definition: pgstat.h:653
PgStat_Counter n_dead_tuples
Definition: pgstat.h:647
PgStat_Counter tuples_fetched
Definition: pgstat.h:639
PgStat_Counter blocks_hit
Definition: pgstat.h:651
TimestampTz analyze_timestamp
Definition: pgstat.h:657
PgStat_Counter changes_since_analyze
Definition: pgstat.h:648
PgStat_Counter tuples_deleted
Definition: pgstat.h:643
PgStat_Counter tuples_updated
Definition: pgstat.h:642
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:655
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:660
PgStat_Counter blocks_fetched
Definition: pgstat.h:650
HASHACTION
Definition: hsearch.h:103
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:656

◆ pgstat_get_wait_activity()

static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

Definition at line 3627 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_ALL, 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().

3628 {
3629  const char *event_name = "unknown wait event";
3630 
3631  switch (w)
3632  {
3634  event_name = "ArchiverMain";
3635  break;
3637  event_name = "AutoVacuumMain";
3638  break;
3640  event_name = "BgWriterHibernate";
3641  break;
3643  event_name = "BgWriterMain";
3644  break;
3646  event_name = "CheckpointerMain";
3647  break;
3649  event_name = "LogicalApplyMain";
3650  break;
3652  event_name = "LogicalLauncherMain";
3653  break;
3655  event_name = "PgStatMain";
3656  break;
3658  event_name = "RecoveryWalAll";
3659  break;
3661  event_name = "RecoveryWalStream";
3662  break;
3664  event_name = "SysLoggerMain";
3665  break;
3667  event_name = "WalReceiverMain";
3668  break;
3670  event_name = "WalSenderMain";
3671  break;
3673  event_name = "WalWriterMain";
3674  break;
3675  /* no default case, so that compiler will warn */
3676  }
3677 
3678  return event_name;
3679 }

◆ pgstat_get_wait_client()

static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

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

3689 {
3690  const char *event_name = "unknown wait event";
3691 
3692  switch (w)
3693  {
3695  event_name = "ClientRead";
3696  break;
3698  event_name = "ClientWrite";
3699  break;
3701  event_name = "LibPQWalReceiverConnect";
3702  break;
3704  event_name = "LibPQWalReceiverReceive";
3705  break;
3707  event_name = "SSLOpenServer";
3708  break;
3710  event_name = "WalReceiverWaitStart";
3711  break;
3713  event_name = "WalSenderWaitForWAL";
3714  break;
3716  event_name = "WalSenderWriteData";
3717  break;
3719  event_name = "GSSOpenServer";
3720  break;
3721  /* no default case, so that compiler will warn */
3722  }
3723 
3724  return event_name;
3725 }

◆ pgstat_get_wait_event()

const char* pgstat_get_wait_event ( uint32  wait_event_info)

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

3551 {
3552  uint32 classId;
3553  uint16 eventId;
3554  const char *event_name;
3555 
3556  /* report process as not waiting. */
3557  if (wait_event_info == 0)
3558  return NULL;
3559 
3560  classId = wait_event_info & 0xFF000000;
3561  eventId = wait_event_info & 0x0000FFFF;
3562 
3563  switch (classId)
3564  {
3565  case PG_WAIT_LWLOCK:
3566  event_name = GetLWLockIdentifier(classId, eventId);
3567  break;
3568  case PG_WAIT_LOCK:
3569  event_name = GetLockNameFromTagType(eventId);
3570  break;
3571  case PG_WAIT_BUFFER_PIN:
3572  event_name = "BufferPin";
3573  break;
3574  case PG_WAIT_ACTIVITY:
3575  {
3576  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3577 
3578  event_name = pgstat_get_wait_activity(w);
3579  break;
3580  }
3581  case PG_WAIT_CLIENT:
3582  {
3583  WaitEventClient w = (WaitEventClient) wait_event_info;
3584 
3585  event_name = pgstat_get_wait_client(w);
3586  break;
3587  }
3588  case PG_WAIT_EXTENSION:
3589  event_name = "Extension";
3590  break;
3591  case PG_WAIT_IPC:
3592  {
3593  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3594 
3595  event_name = pgstat_get_wait_ipc(w);
3596  break;
3597  }
3598  case PG_WAIT_TIMEOUT:
3599  {
3600  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3601 
3602  event_name = pgstat_get_wait_timeout(w);
3603  break;
3604  }
3605  case PG_WAIT_IO:
3606  {
3607  WaitEventIO w = (WaitEventIO) wait_event_info;
3608 
3609  event_name = pgstat_get_wait_io(w);
3610  break;
3611  }
3612  default:
3613  event_name = "unknown wait event";
3614  break;
3615  }
3616 
3617  return event_name;
3618 }
#define PG_WAIT_LOCK
Definition: pgstat.h:755
WaitEventIPC
Definition: pgstat.h:818
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3864
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3734
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:757
#define PG_WAIT_IO
Definition: pgstat.h:762
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3627
unsigned short uint16
Definition: c.h:358
#define PG_WAIT_CLIENT
Definition: pgstat.h:758
WaitEventClient
Definition: pgstat.h:798
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3688
unsigned int uint32
Definition: c.h:359
WaitEventTimeout
Definition: pgstat.h:865
#define PG_WAIT_EXTENSION
Definition: pgstat.h:759
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:756
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1170
WaitEventIO
Definition: pgstat.h:878
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:761
#define PG_WAIT_IPC
Definition: pgstat.h:760
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:714
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:3892
#define PG_WAIT_LWLOCK
Definition: pgstat.h:754
WaitEventActivity
Definition: pgstat.h:772

◆ pgstat_get_wait_event_type()

const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

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

3496 {
3497  uint32 classId;
3498  const char *event_type;
3499 
3500  /* report process as not waiting. */
3501  if (wait_event_info == 0)
3502  return NULL;
3503 
3504  classId = wait_event_info & 0xFF000000;
3505 
3506  switch (classId)
3507  {
3508  case PG_WAIT_LWLOCK:
3509  event_type = "LWLock";
3510  break;
3511  case PG_WAIT_LOCK:
3512  event_type = "Lock";
3513  break;
3514  case PG_WAIT_BUFFER_PIN:
3515  event_type = "BufferPin";
3516  break;
3517  case PG_WAIT_ACTIVITY:
3518  event_type = "Activity";
3519  break;
3520  case PG_WAIT_CLIENT:
3521  event_type = "Client";
3522  break;
3523  case PG_WAIT_EXTENSION:
3524  event_type = "Extension";
3525  break;
3526  case PG_WAIT_IPC:
3527  event_type = "IPC";
3528  break;
3529  case PG_WAIT_TIMEOUT:
3530  event_type = "Timeout";
3531  break;
3532  case PG_WAIT_IO:
3533  event_type = "IO";
3534  break;
3535  default:
3536  event_type = "???";
3537  break;
3538  }
3539 
3540  return event_type;
3541 }
#define PG_WAIT_LOCK
Definition: pgstat.h:755
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:757
#define PG_WAIT_IO
Definition: pgstat.h:762
#define PG_WAIT_CLIENT
Definition: pgstat.h:758
unsigned int uint32
Definition: c.h:359
#define PG_WAIT_EXTENSION
Definition: pgstat.h:759
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:756
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:761
#define PG_WAIT_IPC
Definition: pgstat.h:760
#define PG_WAIT_LWLOCK
Definition: pgstat.h:754

◆ pgstat_get_wait_io()

static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

Definition at line 3892 of file pgstat.c.

References 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_PROC_SIGNAL_BARRIER, 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().

3893 {
3894  const char *event_name = "unknown wait event";
3895 
3896  switch (w)
3897  {
3899  event_name = "BufFileRead";
3900  break;
3902  event_name = "BufFileWrite";
3903  break;
3905  event_name = "ControlFileRead";
3906  break;
3908  event_name = "ControlFileSync";
3909  break;
3911  event_name = "ControlFileSyncUpdate";
3912  break;
3914  event_name = "ControlFileWrite";
3915  break;
3917  event_name = "ControlFileWriteUpdate";
3918  break;
3920  event_name = "CopyFileRead";
3921  break;
3923  event_name = "CopyFileWrite";
3924  break;
3926  event_name = "DataFileExtend";
3927  break;
3929  event_name = "DataFileFlush";
3930  break;
3932  event_name = "DataFileImmediateSync";
3933  break;
3935  event_name = "DataFilePrefetch";
3936  break;
3938  event_name = "DataFileRead";
3939  break;
3941  event_name = "DataFileSync";
3942  break;
3944  event_name = "DataFileTruncate";
3945  break;
3947  event_name = "DataFileWrite";
3948  break;
3950  event_name = "DSMFillZeroWrite";
3951  break;
3953  event_name = "LockFileAddToDataDirRead";
3954  break;
3956  event_name = "LockFileAddToDataDirSync";
3957  break;
3959  event_name = "LockFileAddToDataDirWrite";
3960  break;
3962  event_name = "LockFileCreateRead";
3963  break;
3965  event_name = "LockFileCreateSync";
3966  break;
3968  event_name = "LockFileCreateWrite";
3969  break;
3971  event_name = "LockFileReCheckDataDirRead";
3972  break;
3974  event_name = "LogicalRewriteCheckpointSync";
3975  break;
3977  event_name = "LogicalRewriteMappingSync";
3978  break;
3980  event_name = "LogicalRewriteMappingWrite";
3981  break;
3983  event_name = "LogicalRewriteSync";
3984  break;
3986  event_name = "LogicalRewriteTruncate";
3987  break;
3989  event_name = "LogicalRewriteWrite";
3990  break;
3992  event_name = "ProcSignalBarrier";
3993  break;
3995  event_name = "RelationMapRead";
3996  break;
3998  event_name = "RelationMapSync";
3999  break;
4001  event_name = "RelationMapWrite";
4002  break;
4004  event_name = "ReorderBufferRead";
4005  break;
4007  event_name = "ReorderBufferWrite";
4008  break;
4010  event_name = "ReorderLogicalMappingRead";
4011  break;
4013  event_name = "ReplicationSlotRead";
4014  break;
4016  event_name = "ReplicationSlotRestoreSync";
4017  break;
4019  event_name = "ReplicationSlotSync";
4020  break;
4022  event_name = "ReplicationSlotWrite";
4023  break;
4025  event_name = "SLRUFlushSync";
4026  break;
4027  case WAIT_EVENT_SLRU_READ:
4028  event_name = "SLRURead";
4029  break;
4030  case WAIT_EVENT_SLRU_SYNC:
4031  event_name = "SLRUSync";
4032  break;
4033  case WAIT_EVENT_SLRU_WRITE:
4034  event_name = "SLRUWrite";
4035  break;
4037  event_name = "SnapbuildRead";
4038  break;
4040  event_name = "SnapbuildSync";
4041  break;
4043  event_name = "SnapbuildWrite";
4044  break;
4046  event_name = "TimelineHistoryFileSync";
4047  break;
4049  event_name = "TimelineHistoryFileWrite";
4050  break;
4052  event_name = "TimelineHistoryRead";
4053  break;
4055  event_name = "TimelineHistorySync";
4056  break;
4058  event_name = "TimelineHistoryWrite";
4059  break;
4061  event_name = "TwophaseFileRead";
4062  break;
4064  event_name = "TwophaseFileSync";
4065  break;
4067  event_name = "TwophaseFileWrite";
4068  break;
4070  event_name = "WALSenderTimelineHistoryRead";
4071  break;
4073  event_name = "WALBootstrapSync";
4074  break;
4076  event_name = "WALBootstrapWrite";
4077  break;
4079  event_name = "WALCopyRead";
4080  break;
4082  event_name = "WALCopySync";
4083  break;
4085  event_name = "WALCopyWrite";
4086  break;
4088  event_name = "WALInitSync";
4089  break;
4091  event_name = "WALInitWrite";
4092  break;
4093  case WAIT_EVENT_WAL_READ:
4094  event_name = "WALRead";
4095  break;
4096  case WAIT_EVENT_WAL_SYNC:
4097  event_name = "WALSync";
4098  break;
4100  event_name = "WALSyncMethodAssign";
4101  break;
4102  case WAIT_EVENT_WAL_WRITE:
4103  event_name = "WALWrite";
4104  break;
4105 
4106  /* no default case, so that compiler will warn */
4107  }
4108 
4109  return event_name;
4110 }

◆ pgstat_get_wait_ipc()

static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3734 of file pgstat.c.

References WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WAIT_EVENT_BTREE_PAGE, WAIT_EVENT_CHECKPOINT_DONE, WAIT_EVENT_CHECKPOINT_START, WAIT_EVENT_CLOG_GROUP_UPDATE, WAIT_EVENT_EXECUTE_GATHER, WAIT_EVENT_HASH_BATCH_ALLOCATING, WAIT_EVENT_HASH_BATCH_ELECTING, WAIT_EVENT_HASH_BATCH_LOADING, WAIT_EVENT_HASH_BUILD_ALLOCATING, WAIT_EVENT_HASH_BUILD_ELECTING, WAIT_EVENT_HASH_BUILD_HASHING_INNER, WAIT_EVENT_HASH_BUILD_HASHING_OUTER, WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATING, WAIT_EVENT_HASH_GROW_BATCHES_DECIDING, WAIT_EVENT_HASH_GROW_BATCHES_ELECTING, WAIT_EVENT_HASH_GROW_BATCHES_FINISHING, WAIT_EVENT_HASH_GROW_BATCHES_REPARTITIONING, WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATING, WAIT_EVENT_HASH_GROW_BUCKETS_ELECTING, WAIT_EVENT_HASH_GROW_BUCKETS_REINSERTING, 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_PROCARRAY_GROUP_UPDATE, WAIT_EVENT_PROMOTE, WAIT_EVENT_REPLICATION_ORIGIN_DROP, WAIT_EVENT_REPLICATION_SLOT_DROP, WAIT_EVENT_SAFE_SNAPSHOT, and WAIT_EVENT_SYNC_REP.

Referenced by pgstat_get_wait_event().

3735 {
3736  const char *event_name = "unknown wait event";
3737 
3738  switch (w)
3739  {
3741  event_name = "BgWorkerShutdown";
3742  break;
3744  event_name = "BgWorkerStartup";
3745  break;
3746  case WAIT_EVENT_BTREE_PAGE:
3747  event_name = "BtreePage";
3748  break;
3750  event_name = "CheckpointDone";
3751  break;
3753  event_name = "CheckpointStart";
3754  break;
3756  event_name = "ClogGroupUpdate";
3757  break;
3759  event_name = "ExecuteGather";
3760  break;
3762  event_name = "Hash/Batch/Allocating";
3763  break;
3765  event_name = "Hash/Batch/Electing";
3766  break;
3768  event_name = "Hash/Batch/Loading";
3769  break;
3771  event_name = "Hash/Build/Allocating";
3772  break;
3774  event_name = "Hash/Build/Electing";
3775  break;
3777  event_name = "Hash/Build/HashingInner";
3778  break;
3780  event_name = "Hash/Build/HashingOuter";
3781  break;
3783  event_name = "Hash/GrowBatches/Allocating";
3784  break;
3786  event_name = "Hash/GrowBatches/Deciding";
3787  break;
3789  event_name = "Hash/GrowBatches/Electing";
3790  break;
3792  event_name = "Hash/GrowBatches/Finishing";
3793  break;
3795  event_name = "Hash/GrowBatches/Repartitioning";
3796  break;
3798  event_name = "Hash/GrowBuckets/Allocating";
3799  break;
3801  event_name = "Hash/GrowBuckets/Electing";
3802  break;
3804  event_name = "Hash/GrowBuckets/Reinserting";
3805  break;
3807  event_name = "LogicalSyncData";
3808  break;
3810  event_name = "LogicalSyncStateChange";
3811  break;
3813  event_name = "MessageQueueInternal";
3814  break;
3816  event_name = "MessageQueuePutMessage";
3817  break;
3818  case WAIT_EVENT_MQ_RECEIVE:
3819  event_name = "MessageQueueReceive";
3820  break;
3821  case WAIT_EVENT_MQ_SEND:
3822  event_name = "MessageQueueSend";
3823  break;
3825  event_name = "ParallelBitmapScan";
3826  break;
3828  event_name = "ParallelCreateIndexScan";
3829  break;
3831  event_name = "ParallelFinish";
3832  break;
3834  event_name = "ProcArrayGroupUpdate";
3835  break;
3836  case WAIT_EVENT_PROMOTE:
3837  event_name = "Promote";
3838  break;
3840  event_name = "ReplicationOriginDrop";
3841  break;
3843  event_name = "ReplicationSlotDrop";
3844  break;
3846  event_name = "SafeSnapshot";
3847  break;
3848  case WAIT_EVENT_SYNC_REP:
3849  event_name = "SyncRep";
3850  break;
3851  /* no default case, so that compiler will warn */
3852  }
3853 
3854  return event_name;
3855 }

◆ pgstat_get_wait_timeout()

static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

Definition at line 3864 of file pgstat.c.

References WAIT_EVENT_BASE_BACKUP_THROTTLE, WAIT_EVENT_PG_SLEEP, and WAIT_EVENT_RECOVERY_APPLY_DELAY.

Referenced by pgstat_get_wait_event().

3865 {
3866  const char *event_name = "unknown wait event";
3867 
3868  switch (w)
3869  {
3871  event_name = "BaseBackupThrottle";
3872  break;
3873  case WAIT_EVENT_PG_SLEEP:
3874  event_name = "PgSleep";
3875  break;
3877  event_name = "RecoveryApplyDelay";
3878  break;
3879  /* no default case, so that compiler will warn */
3880  }
3881 
3882  return event_name;
3883 }

◆ pgstat_init()

void pgstat_init ( void  )

Definition at line 349 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, select, send, SetConfigOption(), socket, StaticAssertStmt, and TESTBYTEVAL.

Referenced by PostmasterMain().

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

1617 {
1618  PgStat_BackendFunctionEntry *htabent;
1619  bool found;
1620 
1621  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1622  {
1623  /* stats not wanted */
1624  fcu->fs = NULL;
1625  return;
1626  }
1627 
1628  if (!pgStatFunctions)
1629  {
1630  /* First time through - initialize function stat table */
1631  HASHCTL hash_ctl;
1632 
1633  memset(&hash_ctl, 0, sizeof(hash_ctl));
1634  hash_ctl.keysize = sizeof(Oid);
1635  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1636  pgStatFunctions = hash_create("Function stat entries",
1638  &hash_ctl,
1639  HASH_ELEM | HASH_BLOBS);
1640  }
1641 
1642  /* Get the stats entry for this function, create if necessary */
1643  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1644  HASH_ENTER, &found);
1645  if (!found)
1646  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1647 
1648  fcu->fs = &htabent->f_counts;
1649 
1650  /* save stats for this function, later used to compensate for recursion */
1651  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1652 
1653  /* save current backend-wide total time */
1654  fcu->save_total = total_func_time;
1655 
1656  /* get clock time as of function start */
1658 }
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:1203
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:962
instr_time f_total_time
Definition: pgstat.h:462
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1199
PgStat_FunctionCounts f_counts
Definition: pgstat.h:473
#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:316
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:271
static HTAB * pgStatFunctions
Definition: pgstat.c:196
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
instr_time save_f_total_time
Definition: pgstat.h:1201
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry

◆ pgstat_initialize()

void pgstat_initialize ( void  )

Definition at line 2808 of file pgstat.c.

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

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2809 {
2810  /* Initialize MyBEEntry */
2812  {
2815  }
2816  else
2817  {
2818  /* Must be an auxiliary process */
2820 
2821  /*
2822  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
2823  * have a BackendId, the slot is statically allocated based on the
2824  * auxiliary process type (MyAuxProcType). Backends use slots indexed
2825  * in the range from 1 to MaxBackends (inclusive), so we use
2826  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2827  * auxiliary process.
2828  */
2830  }
2831 
2832  /* Set up a process-exit hook to clean up */
2834 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2627
BackendId MyBackendId
Definition: globals.c:81
int MaxBackends
Definition: globals.c:135
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
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:3076
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:72
#define Assert(condition)
Definition: c.h:739

◆ pgstat_initstats()

void pgstat_initstats ( Relation  rel)

Definition at line 1744 of file pgstat.c.

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

Referenced by relation_open(), and try_relation_open().

1745 {
1746  Oid rel_id = rel->rd_id;
1747  char relkind = rel->rd_rel->relkind;
1748 
1749  /* We only count stats for things that have storage */
1750  if (!(relkind == RELKIND_RELATION ||
1751  relkind == RELKIND_MATVIEW ||
1752  relkind == RELKIND_INDEX ||
1753  relkind == RELKIND_TOASTVALUE ||
1754  relkind == RELKIND_SEQUENCE))
1755  {
1756  rel->pgstat_info = NULL;
1757  return;
1758  }
1759 
1761  {
1762  /* We're not counting at all */
1763  rel->pgstat_info = NULL;
1764  return;
1765  }
1766 
1767  /*
1768  * If we already set up this relation in the current transaction, nothing
1769  * to do.
1770  */
1771  if (rel->pgstat_info != NULL &&
1772  rel->pgstat_info->t_id == rel_id)
1773  return;
1774 
1775  /* Else find or make the PgStat_TableStatus entry, and update link */
1776  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1777 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:148
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
char relkind
Definition: pg_class.h:81
bool pgstat_track_counts
Definition: pgstat.c:125
Oid rd_id
Definition: rel.h:86
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:1783
#define PGINVALID_SOCKET
Definition: port.h:33
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:210

◆ pgstat_ping()

void pgstat_ping ( void  )

Definition at line 1580 of file pgstat.c.

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

1581 {
1582  PgStat_MsgDummy msg;
1583 
1585  return;
1586 
1588  pgstat_send(&msg, sizeof(msg));
1589 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4337
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:148
#define PGINVALID_SOCKET
Definition: port.h:33
PgStat_MsgHdr m_hdr
Definition: pgstat.h:216
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4324

◆ pgstat_progress_end_command()

void pgstat_progress_end_command ( void  )

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

3265 {
3266  volatile PgBackendStatus *beentry = MyBEEntry;
3267 
3268  if (!beentry || !pgstat_track_activities)
3269  return;
3270 
3272  return;
3273 
3274  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3277  PGSTAT_END_WRITE_ACTIVITY(beentry);
3278 }
Oid st_progress_command_target
Definition: pgstat.h:1099
ProgressCommandType st_progress_command
Definition: pgstat.h:1098
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132

◆ pgstat_progress_start_command()

void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

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

3193 {
3194  volatile PgBackendStatus *beentry = MyBEEntry;
3195 
3196  if (!beentry || !pgstat_track_activities)
3197  return;
3198 
3199  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3200  beentry->st_progress_command = cmdtype;
3201  beentry->st_progress_command_target = relid;
3202  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3203  PGSTAT_END_WRITE_ACTIVITY(beentry);
3204 }
Oid st_progress_command_target
Definition: pgstat.h:1099
#define MemSet(start, val, len)
Definition: c.h:962
ProgressCommandType st_progress_command
Definition: pgstat.h:1098
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1100
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132

◆ pgstat_progress_update_multi_param()

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

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

3237 {
3238  volatile PgBackendStatus *beentry = MyBEEntry;
3239  int i;
3240 
3241  if (!beentry || !pgstat_track_activities || nparam == 0)
3242  return;
3243 
3244  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3245 
3246  for (i = 0; i < nparam; ++i)
3247  {
3248  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3249 
3250  beentry->st_progress_param[index[i]] = val[i];
3251  }
3252 
3253  PGSTAT_END_WRITE_ACTIVITY(beentry);
3254 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:964
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
#define Assert(condition)
Definition: c.h:739
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1100
bool pgstat_track_activities
Definition: pgstat.c:124
int i
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132
long val
Definition: informix.c:664

◆ pgstat_progress_update_param()

void pgstat_progress_update_param ( int  index,
int64  val 
)

Definition at line 3213 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_record_dead_tuple(), lazy_scan_heap(), lazy_truncate_heap(), lazy_vacuum_all_indexes(), lazy_vacuum_heap(), lazy_vacuum_page(), reindex_index(), reindex_relation(), ReindexRelationConcurrently(), validate_index(), WaitForLockersMultiple(), and WaitForOlderSnapshots().

3214 {
3215  volatile PgBackendStatus *beentry = MyBEEntry;
3216 
3218 
3219  if (!beentry || !pgstat_track_activities)
3220  return;
3221 
3222  PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3223  beentry->st_progress_param[index] = val;
3224  PGSTAT_END_WRITE_ACTIVITY(beentry);
3225 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:964
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2628
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1139
#define Assert(condition)
Definition: c.h:739
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1100
bool pgstat_track_activities
Definition: pgstat.c:124
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
Definition: pgstat.h:1132
long val
Definition: informix.c:664

◆ pgstat_read_current_status()

static void pgstat_read_current_status ( void  )
static

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

3344 {
3345  volatile PgBackendStatus *beentry;
3346  LocalPgBackendStatus *localtable;
3347  LocalPgBackendStatus *localentry;
3348  char *localappname,
3349  *localclienthostname,
3350  *localactivity;
3351 #ifdef USE_SSL
3352  PgBackendSSLStatus *localsslstatus;
3353 #endif
3354 #ifdef ENABLE_GSS
3355  PgBackendGSSStatus *localgssstatus;
3356 #endif
3357  int i;
3358 
3361  return; /* already done */
3362 
3364 
3365  /*
3366  * Allocate storage for local copy of state data. We can presume that
3367  * none of these requests overflow size_t, because we already calculated
3368  * the same values using mul_size during shmem setup. However, with
3369  * probably-silly values of pgstat_track_activity_query_size and
3370  * max_connections, the localactivity buffer could exceed 1GB, so use
3371  * "huge" allocation for that one.
3372  */
3373  localtable = (LocalPgBackendStatus *)
3376  localappname = (char *)
3379  localclienthostname = (char *)
3381  NAMEDATALEN * NumBackendStatSlots);
3382  localactivity = (char *)
3384  pgstat_track_activity_query_size * NumBackendStatSlots);
3385 #ifdef USE_SSL
3386  localsslstatus = (PgBackendSSLStatus *)
3389 #endif
3390 #ifdef ENABLE_GSS
3391  localgssstatus = (PgBackendGSSStatus *)
3394 #endif
3395 
3396  localNumBackends = 0;
3397 
3398  beentry = BackendStatusArray;
3399  localentry = localtable;
3400  for (i = 1; i <= NumBackendStatSlots; i++)
3401  {
3402  /*
3403  * Follow the protocol of retrying if st_changecount changes while we
3404  * copy the entry, or if it's odd. (The check for odd is needed to
3405  * cover the case where we are able to completely copy the entry while
3406  * the source backend is between increment steps.) We use a volatile
3407  * pointer here to ensure the compiler doesn't try to get cute.
3408  */
3409  for (;;)
3410  {
3411  int before_changecount;
3412  int after_changecount;
3413 
3414  pgstat_begin_read_activity(beentry, before_changecount);
3415 
3416  localentry->backendStatus.st_procpid = beentry->st_procpid;
3417  /* Skip all the data-copying work if entry is not in use */
3418  if (localentry->backendStatus.st_procpid > 0)
3419  {
3420  memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3421 
3422  /*
3423  * For each PgBackendStatus field that is a pointer, copy the
3424  * pointed-to data, then adjust the local copy of the pointer
3425  * field to point at the local copy of the data.
3426  *
3427  * strcpy is safe even if the string is modified concurrently,
3428  * because there's always a \0 at the end of the buffer.
3429  */
3430  strcpy(localappname, (char *) beentry->st_appname);
3431  localentry->backendStatus.st_appname = localappname;
3432  strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3433  localentry->backendStatus.st_clienthostname = localclienthostname;
3434  strcpy(localactivity, (char *) beentry->st_activity_raw);
3435  localentry->backendStatus.st_activity_raw = localactivity;
3436 #ifdef USE_SSL
3437  if (beentry->st_ssl)
3438  {
3439  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3440  localentry->backendStatus.st_sslstatus = localsslstatus;
3441  }
3442 #endif
3443 #ifdef ENABLE_GSS
3444  if (beentry->st_gss)
3445  {
3446  memcpy(localgssstatus, beentry->st_gssstatus, sizeof(PgBackendGSSStatus));
3447  localentry->backendStatus.st_gssstatus = localgssstatus;
3448  }
3449 #endif
3450  }
3451 
3452  pgstat_end_read_activity(beentry, after_changecount);
3453 
3454  if (pgstat_read_activity_complete(before_changecount,
3455  after_changecount))
3456  break;
3457 
3458  /* Make sure we can break out of loop if stuck... */
3460  }
3461 
3462  beentry++;
3463  /* Only valid entries get included into the local array */
3464  if (localentry->backendStatus.st_procpid > 0)
3465  {
3467  &localentry->backend_xid,
3468  &localentry->backend_xmin);
3469 
3470  localentry++;
3471  localappname += NAMEDATALEN;
3472  localclienthostname += NAMEDATALEN;
3473  localactivity += pgstat_track_activity_query_size;
3474 #ifdef USE_SSL
3475  localsslstatus++;
3476 #endif
3477 #ifdef ENABLE_GSS
3478  localgssstatus++;
3479 #endif
3480  localNumBackends++;
3481  }
3482  }
3483 
3484  /* Set the pointer only after completion of a valid table */
3485  localBackendStatusTable = localtable;
3486 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2627
static bool pgStatRunningInCollector
Definition: pgstat.c:154
TransactionId backend_xmin
Definition: pgstat.h:1189
#define NumBackendStatSlots
Definition: pgstat.c:117
char * st_clienthostname
Definition: pgstat.h:1064
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1183
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition: mcxt.c:1105
char * st_activity_raw
Definition: pgstat.h:1087
int pgstat_track_activity_query_size
Definition: pgstat.c:127
char * st_appname
Definition: pgstat.h:1078
#define pgstat_end_read_activity(beentry, after_changecount)
Definition: pgstat.h:1153
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5747
PgBackendStatus backendStatus
Definition: pgstat.h:1177
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:403
#define Assert(condition)
Definition: c.h:739
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:246
#define pgstat_begin_read_activity(beentry, before_changecount)
Definition: pgstat.h:1147
static int localNumBackends
Definition: pgstat.c:249
#define unvolatize(underlying_type, expr)
Definition: c.h:1195
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:242
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1068
PgBackendGSSStatus * st_gssstatus
Definition: pgstat.h:1072
#define pgstat_read_activity_complete(before_changecount, after_changecount)
Definition: pgstat.h:1159

◆ pgstat_read_db_statsfile()

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

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

5334 {
5335  PgStat_StatTabEntry *tabentry;
5336  PgStat_StatTabEntry tabbuf;
5337  PgStat_StatFuncEntry funcbuf;
5338  PgStat_StatFuncEntry *funcentry;
5339  FILE *fpin;
5340  int32 format_id;
5341  bool found;
5342  char statfile[MAXPGPATH];
5343 
5344  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5345 
5346  /*
5347  * Try to open the stats file. If it doesn't exist, the backends simply
5348  * return zero for anything and the collector simply starts from scratch
5349  * with empty counters.
5350  *
5351  * ENOENT is a possibility if the stats collector is not running or has
5352  * not yet written the stats file the first time. Any other failure
5353  * condition is suspicious.
5354  */
5355  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5356  {
5357  if (errno != ENOENT)
5360  errmsg("could not open statistics file \"%s\": %m",
5361  statfile)));
5362  return;
5363  }
5364 
5365  /*
5366  * Verify it's of the expected format.
5367  */
5368  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5369  format_id != PGSTAT_FILE_FORMAT_ID)
5370  {
5371  ereport(pgStatRunningInCollector ? LOG : WARNING,
5372  (errmsg("corrupted statistics file \"%s\"", statfile)));
5373  goto done;
5374  }
5375 
5376  /*
5377  * We found an existing collector stats file. Read it and put all the
5378  * hashtable entries into place.
5379  */
5380  for (;;)
5381  {
5382  switch (fgetc(fpin))
5383  {
5384  /*
5385  * 'T' A PgStat_StatTabEntry follows.
5386  */
5387  case 'T':
5388  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5389  fpin) != sizeof(PgStat_StatTabEntry))
5390  {
5391  ereport(pgStatRunningInCollector ? LOG : WARNING,
5392  (errmsg("corrupted statistics file \"%s\"",
5393  statfile)));
5394  goto done;
5395  }
5396 
5397  /*
5398  * Skip if table data not wanted.
5399  */
5400  if (tabhash == NULL)
5401  break;
5402 
5403  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5404  (void *) &tabbuf.tableid,
5405  HASH_ENTER, &found);
5406 
5407  if (found)
5408  {
5409  ereport(pgStatRunningInCollector ? LOG : WARNING,
5410  (errmsg("corrupted statistics file \"%s\"",
5411  statfile)));
5412  goto done;
5413  }
5414 
5415  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5416  break;
5417 
5418  /*
5419  * 'F' A PgStat_StatFuncEntry follows.
5420  */
5421  case 'F':
5422  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5423  fpin) != sizeof(PgStat_StatFuncEntry))
5424  {
5425  ereport(pgStatRunningInCollector ? LOG : WARNING,
5426  (errmsg("corrupted statistics file \"%s\"",
5427  statfile)));
5428  goto done;
5429  }
5430 
5431  /*
5432  * Skip if function data not wanted.
5433  */
5434  if (funchash == NULL)
5435  break;
5436 
5437  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5438  (void *) &funcbuf.functionid,
5439  HASH_ENTER, &found);
5440 
5441  if (found)
5442  {
5443  ereport(pgStatRunningInCollector ? LOG : WARNING,
5444  (errmsg("corrupted statistics file \"%s\"",
5445  statfile)));
5446  goto done;
5447  }
5448 
5449  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5450  break;
5451 
5452  /*
5453  * 'E' The EOF marker of a complete stats file.
5454  */
5455  case 'E':
5456  goto done;
5457 
5458  default:
5459  ereport(pgStatRunningInCollector ? LOG : WARNING,
5460  (errmsg("corrupted statistics file \"%s\"",
5461  statfile)));
5462  goto done;
5463  }
5464  }
5465 
5466 done:
5467  FreeFile(fpin);
5468 
5469  if (permanent)
5470  {
5471  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5472  unlink(statfile);
5473  }
5474 }
static bool pgStatRunningInCollector
Definition: pgstat.c:154
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
#define LOG
Definition: elog.h:26
#define PG_BINARY_R
Definition: c.h:1223
signed int int32
Definition: c.h:347
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
int errcode_for_file_access(void)
Definition: elog.c:631
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2242
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
int FreeFile(FILE *file)
Definition: fd.c:2441
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:584
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
static void get_dbstat_filename(bool permanent, bool tempname, Oid databaseid, char *filename, int len)
Definition: pgstat.c:4951

◆ pgstat_read_db_statsfile_timestamp()

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

Definition at line 5494 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, PgStat_StatDBEntry::stats_timestamp, PgStat_GlobalStats::stats_timestamp, and WARNING.

Referenced by backend_read_statsfile().

5496 {
5497  PgStat_StatDBEntry dbentry;
5498  PgStat_GlobalStats myGlobalStats;
5499  PgStat_ArchiverStats myArchiverStats;
5500  FILE *fpin;
5501  int32 format_id;
5502  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5503 
5504  /*
5505  * Try to open the stats file. As above, anything but ENOENT is worthy of
5506  * complaining about.
5507  */
5508  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5509  {
5510  if (errno != ENOENT)
5513  errmsg("could not open statistics file \"%s\": %m",
5514  statfile)));
5515  return false;
5516  }
5517 
5518  /*
5519  * Verify it's of the expected format.
5520  */
5521  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5522  format_id != PGSTAT_FILE_FORMAT_ID)
5523  {
5524  ereport(pgStatRunningInCollector ? LOG : WARNING,
5525  (errmsg("corrupted statistics file \"%s\"", statfile)));
5526  FreeFile(fpin);
5527  return false;
5528  }
5529 
5530  /*
5531  * Read global stats struct
5532  */
5533  if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5534  fpin) != sizeof(myGlobalStats))
5535  {
5536  ereport(pgStatRunningInCollector ? LOG : WARNING,
5537  (errmsg("corrupted statistics file \"%s\"", statfile)));
5538  FreeFile(fpin);
5539  return false;
5540  }
5541