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 "pgstat.h"
#include "access/heapam.h"
#include "access/htup_details.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 "postmaster/autovacuum.h"
#include "postmaster/fork_process.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 "utils/tqual.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_exit (SIGNAL_ARGS)
 
static void pgstat_beshutdown_hook (int code, Datum arg)
 
static void pgstat_sighup_handler (SIGNAL_ARGS)
 
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)
 
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_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_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 (FunctionCallInfoData *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)
 
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 volatile bool need_exit = false
 
static volatile bool got_SIGHUP = false
 
static instr_time total_func_time
 
static PgBackendStatusBackendStatusArray = NULL
 
static PgBackendStatusMyBEEntry = NULL
 
static char * BackendAppnameBuffer = NULL
 
static char * BackendClientHostnameBuffer = NULL
 
static char * BackendActivityBuffer = NULL
 
static Size BackendActivityBufferSize = 0
 

Macro Definition Documentation

◆ NumBackendStatSlots

#define NumBackendStatSlots   (MaxBackends + NUM_AUXPROCTYPES)

◆ PGSTAT_DB_HASH_SIZE

#define PGSTAT_DB_HASH_SIZE   16

Definition at line 104 of file pgstat.c.

Referenced by pgstat_read_statsfiles().

◆ PGSTAT_FUNCTION_HASH_SIZE

#define PGSTAT_FUNCTION_HASH_SIZE   512

◆ PGSTAT_INQ_INTERVAL

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

Definition at line 86 of file pgstat.c.

◆ PGSTAT_INQ_LOOP_COUNT

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

Definition at line 94 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_MAX_WAIT_TIME

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

Definition at line 83 of file pgstat.c.

◆ PGSTAT_MIN_RCVBUF

#define PGSTAT_MIN_RCVBUF   (100 * 1024)

Definition at line 97 of file pgstat.c.

Referenced by pgstat_init().

◆ PGSTAT_POLL_LOOP_COUNT

#define PGSTAT_POLL_LOOP_COUNT   (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)

Definition at line 93 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_RESTART_INTERVAL

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

Definition at line 89 of file pgstat.c.

Referenced by pgstat_start().

◆ PGSTAT_RETRY_DELAY

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

Definition at line 80 of file pgstat.c.

Referenced by backend_read_statsfile().

◆ PGSTAT_STAT_INTERVAL

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

Definition at line 77 of file pgstat.c.

Referenced by backend_read_statsfile(), and pgstat_report_stat().

◆ PGSTAT_TAB_HASH_SIZE

#define PGSTAT_TAB_HASH_SIZE   512

Definition at line 105 of file pgstat.c.

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

◆ TABSTAT_QUANTUM

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

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

1881 {
1882  PgStat_SubXactStatus *xact_state;
1884 
1885  /*
1886  * If this is the first rel to be modified at the current nest level, we
1887  * first have to push a transaction stack entry.
1888  */
1889  xact_state = get_tabstat_stack_level(nest_level);
1890 
1891  /* Now make a per-table stack entry */
1892  trans = (PgStat_TableXactStatus *)
1894  sizeof(PgStat_TableXactStatus));
1895  trans->nest_level = nest_level;
1896  trans->upper = pgstat_info->trans;
1897  trans->parent = pgstat_info;
1898  trans->next = xact_state->first;
1899  xact_state->first = trans;
1900  pgstat_info->trans = trans;
1901 }
MemoryContext TopTransactionContext
Definition: mcxt.c:48
struct PgStat_TableXactStatus * next
Definition: pgstat.h:179
static PgStat_SubXactStatus * get_tabstat_stack_level(int nest_level)
Definition: pgstat.c:1858
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:728
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:387
PgStat_TableXactStatus * first
Definition: pgstat.c:216
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ allow_immediate_pgstat_restart()

void allow_immediate_pgstat_restart ( void  )

Definition at line 790 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

791 {
793 }
static time_t last_pgstat_start_time
Definition: pgstat.c:153

◆ AtEOSubXact_PgStat()

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

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

2137 {
2138  PgStat_SubXactStatus *xact_state;
2139 
2140  /*
2141  * Transfer transactional insert/update counts into the next higher
2142  * subtransaction state.
2143  */
2144  xact_state = pgStatXactStack;
2145  if (xact_state != NULL &&
2146  xact_state->nest_level >= nestDepth)
2147  {
2149  PgStat_TableXactStatus *next_trans;
2150 
2151  /* delink xact_state from stack immediately to simplify reuse case */
2152  pgStatXactStack = xact_state->prev;
2153 
2154  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2155  {
2156  PgStat_TableStatus *tabstat;
2157 
2158  next_trans = trans->next;
2159  Assert(trans->nest_level == nestDepth);
2160  tabstat = trans->parent;
2161  Assert(tabstat->trans == trans);
2162  if (isCommit)
2163  {
2164  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2165  {
2166  if (trans->truncated)
2167  {
2168  /* propagate the truncate status one level up */
2170  /* replace upper xact stats with ours */
2171  trans->upper->tuples_inserted = trans->tuples_inserted;
2172  trans->upper->tuples_updated = trans->tuples_updated;
2173  trans->upper->tuples_deleted = trans->tuples_deleted;
2174  }
2175  else
2176  {
2177  trans->upper->tuples_inserted += trans->tuples_inserted;
2178  trans->upper->tuples_updated += trans->tuples_updated;
2179  trans->upper->tuples_deleted += trans->tuples_deleted;
2180  }
2181  tabstat->trans = trans->upper;
2182  pfree(trans);
2183  }
2184  else
2185  {
2186  /*
2187  * When there isn't an immediate parent state, we can just
2188  * reuse the record instead of going through a
2189  * palloc/pfree pushup (this works since it's all in
2190  * TopTransactionContext anyway). We have to re-link it
2191  * into the parent level, though, and that might mean
2192  * pushing a new entry into the pgStatXactStack.
2193  */
2194  PgStat_SubXactStatus *upper_xact_state;
2195 
2196  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2197  trans->next = upper_xact_state->first;
2198  upper_xact_state->first = trans;
2199  trans->nest_level = nestDepth - 1;
2200  }
2201  }
2202  else
2203  {
2204  /*
2205  * On abort, update top-level tabstat counts, then forget the
2206  * subtransaction
2207  */
2208 
2209  /* first restore values obliterated by truncate */
2211  /* count attempted actions regardless of commit/abort */
2212  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2213  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2214  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2215  /* inserted tuples are dead, deleted tuples are unaffected */
2216  tabstat->t_counts.t_delta_dead_tuples +=
2217  trans->tuples_inserted + trans->tuples_updated;
2218  tabstat->trans = trans->upper;
2219  pfree(trans);
2220  }
2221  }
2222  pfree(xact_state);
2223  }
2224 }
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:1858
void pfree(void *pointer)
Definition: mcxt.c:936
PgStat_Counter t_tuples_updated
Definition: pgstat.h:105
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1994
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:215
#define Assert(condition)
Definition: c.h:688
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:219
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:387
PgStat_TableXactStatus * first
Definition: pgstat.c:216
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1979
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ AtEOXact_PgStat()

void AtEOXact_PgStat ( bool  isCommit)

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

2054 {
2055  PgStat_SubXactStatus *xact_state;
2056 
2057  /*
2058  * Count transaction commit or abort. (We use counters, not just bools,
2059  * in case the reporting message isn't sent right away.)
2060  */
2061  if (isCommit)
2062  pgStatXactCommit++;
2063  else
2065 
2066  /*
2067  * Transfer transactional insert/update counts into the base tabstat
2068  * entries. We don't bother to free any of the transactional state, since
2069  * it's all in TopTransactionContext and will go away anyway.
2070  */
2071  xact_state = pgStatXactStack;
2072  if (xact_state != NULL)
2073  {
2075 
2076  Assert(xact_state->nest_level == 1);
2077  Assert(xact_state->prev == NULL);
2078  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2079  {
2080  PgStat_TableStatus *tabstat;
2081 
2082  Assert(trans->nest_level == 1);
2083  Assert(trans->upper == NULL);
2084  tabstat = trans->parent;
2085  Assert(tabstat->trans == trans);
2086  /* restore pre-truncate stats (if any) in case of aborted xact */
2087  if (!isCommit)
2089  /* count attempted actions regardless of commit/abort */
2090  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2091  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2092  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2093  if (isCommit)
2094  {
2095  tabstat->t_counts.t_truncated = trans->truncated;
2096  if (trans->truncated)
2097  {
2098  /* forget live/dead stats seen by backend thus far */
2099  tabstat->t_counts.t_delta_live_tuples = 0;
2100  tabstat->t_counts.t_delta_dead_tuples = 0;
2101  }
2102  /* insert adds a live tuple, delete removes one */
2103  tabstat->t_counts.t_delta_live_tuples +=
2104  trans->tuples_inserted - trans->tuples_deleted;
2105  /* update and delete each create a dead tuple */
2106  tabstat->t_counts.t_delta_dead_tuples +=
2107  trans->tuples_updated + trans->tuples_deleted;
2108  /* insert, update, delete each count as one change event */
2109  tabstat->t_counts.t_changed_tuples +=
2110  trans->tuples_inserted + trans->tuples_updated +
2111  trans->tuples_deleted;
2112  }
2113  else
2114  {
2115  /* inserted tuples are dead, deleted tuples are unaffected */
2116  tabstat->t_counts.t_delta_dead_tuples +=
2117  trans->tuples_inserted + trans->tuples_updated;
2118  /* an aborted xact generates no changed_tuple events */
2119  }
2120  tabstat->trans = NULL;
2121  }
2122  }
2123  pgStatXactStack = NULL;
2124 
2125  /* Make sure any stats snapshot is thrown away */
2127 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:110
PgStat_Counter tuples_updated
Definition: pgstat.h:168
static int pgStatXactCommit
Definition: pgstat.c:221
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:1994
static int pgStatXactRollback
Definition: pgstat.c:222
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:215
PgStat_Counter t_changed_tuples
Definition: pgstat.h:112
#define Assert(condition)
Definition: c.h:688
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5608
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:219
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:387
PgStat_TableXactStatus * first
Definition: pgstat.c:216
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 2235 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().

2236 {
2237  PgStat_SubXactStatus *xact_state;
2238 
2239  xact_state = pgStatXactStack;
2240  if (xact_state != NULL)
2241  {
2243 
2244  Assert(xact_state->nest_level == 1);
2245  Assert(xact_state->prev == NULL);
2246  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2247  {
2248  PgStat_TableStatus *tabstat;
2249  TwoPhasePgStatRecord record;
2250 
2251  Assert(trans->nest_level == 1);
2252  Assert(trans->upper == NULL);
2253  tabstat = trans->parent;
2254  Assert(tabstat->trans == trans);
2255 
2256  record.tuples_inserted = trans->tuples_inserted;
2257  record.tuples_updated = trans->tuples_updated;
2258  record.tuples_deleted = trans->tuples_deleted;
2259  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2260  record.updated_pre_trunc = trans->updated_pre_trunc;
2261  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2262  record.t_id = tabstat->t_id;
2263  record.t_shared = tabstat->t_shared;
2264  record.t_truncated = trans->truncated;
2265 
2267  &record, sizeof(TwoPhasePgStatRecord));
2268  }
2269  }
2270 }
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:234
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1164
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:233
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:232
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter tuples_updated
Definition: pgstat.c:230
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:215
#define Assert(condition)
Definition: c.h:688
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:171
PgStat_Counter tuples_inserted
Definition: pgstat.c:229
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:219
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
PgStat_Counter tuples_deleted
Definition: pgstat.c:231
#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:387
PgStat_TableXactStatus * first
Definition: pgstat.c:216
PgStat_TableStatus * parent
Definition: pgstat.h:177

◆ backend_read_statsfile()

static void backend_read_statsfile ( void  )
static

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

5455 {
5456  TimestampTz min_ts = 0;
5457  TimestampTz ref_ts = 0;
5458  Oid inquiry_db;
5459  int count;
5460 
5461  /* already read it? */
5462  if (pgStatDBHash)
5463  return;
5465 
5466  /*
5467  * In a normal backend, we check staleness of the data for our own DB, and
5468  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5469  * check staleness of the shared-catalog data, and send InvalidOid in
5470  * inquiry messages so as not to force writing unnecessary data.
5471  */
5473  inquiry_db = InvalidOid;
5474  else
5475  inquiry_db = MyDatabaseId;
5476 
5477  /*
5478  * Loop until fresh enough stats file is available or we ran out of time.
5479  * The stats inquiry message is sent repeatedly in case collector drops
5480  * it; but not every single time, as that just swamps the collector.
5481  */
5482  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5483  {
5484  bool ok;
5485  TimestampTz file_ts = 0;
5486  TimestampTz cur_ts;
5487 
5489 
5490  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5491 
5492  cur_ts = GetCurrentTimestamp();
5493  /* Calculate min acceptable timestamp, if we didn't already */
5494  if (count == 0 || cur_ts < ref_ts)
5495  {
5496  /*
5497  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5498  * msec before now. This indirectly ensures that the collector
5499  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5500  * an autovacuum worker, however, we want a lower delay to avoid
5501  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5502  * number of workers is low, this shouldn't be a problem).
5503  *
5504  * We don't recompute min_ts after sleeping, except in the
5505  * unlikely case that cur_ts went backwards. So we might end up
5506  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5507  * practice that shouldn't happen, though, as long as the sleep
5508  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5509  * tell the collector that our cutoff time is less than what we'd
5510  * actually accept.
5511  */
5512  ref_ts = cur_ts;
5514  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5516  else
5517  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5519  }
5520 
5521  /*
5522  * If the file timestamp is actually newer than cur_ts, we must have
5523  * had a clock glitch (system time went backwards) or there is clock
5524  * skew between our processor and the stats collector's processor.
5525  * Accept the file, but send an inquiry message anyway to make
5526  * pgstat_recv_inquiry do a sanity check on the collector's time.
5527  */
5528  if (ok && file_ts > cur_ts)
5529  {
5530  /*
5531  * A small amount of clock skew between processors isn't terribly
5532  * surprising, but a large difference is worth logging. We
5533  * arbitrarily define "large" as 1000 msec.
5534  */
5535  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5536  {
5537  char *filetime;
5538  char *mytime;
5539 
5540  /* Copy because timestamptz_to_str returns a static buffer */
5541  filetime = pstrdup(timestamptz_to_str(file_ts));
5542  mytime = pstrdup(timestamptz_to_str(cur_ts));
5543  elog(LOG, "stats collector's time %s is later than backend local time %s",
5544  filetime, mytime);
5545  pfree(filetime);
5546  pfree(mytime);
5547  }
5548 
5549  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5550  break;
5551  }
5552 
5553  /* Normal acceptance case: file is not older than cutoff time */
5554  if (ok && file_ts >= min_ts)
5555  break;
5556 
5557  /* Not there or too old, so kick the collector and wait a bit */
5558  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5559  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5560 
5561  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5562  }
5563 
5564  if (count >= PGSTAT_POLL_LOOP_COUNT)
5565  ereport(LOG,
5566  (errmsg("using stale statistics instead of current ones "
5567  "because stats collector is not responding")));
5568 
5569  /*
5570  * Autovacuum launcher wants stats about all databases, but a shallow read
5571  * is sufficient. Regular backends want a deep read for just the tables
5572  * they can see (MyDatabaseId + shared catalogs).
5573  */
5576  else
5578 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:80
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:94
char * pstrdup(const char *in)
Definition: mcxt.c:1063
static bool pgStatRunningInCollector
Definition: pgstat.c:155
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PGSTAT_POLL_LOOP_COUNT
Definition: pgstat.c:93
void pg_usleep(long microsec)
Definition: signal.c:53
void pfree(void *pointer)
Definition: mcxt.c:936
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1564
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:77
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
#define ereport(elevel, rest)
Definition: elog.h:122
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:4941
Oid MyDatabaseId
Definition: globals.c:77
#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:5335
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3249
#define Assert(condition)
Definition: c.h:688
static HTAB * pgStatDBHash
Definition: pgstat.c:244
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define elog
Definition: elog.h:219
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1710

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 2604 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2605 {
2606  Size size;
2607 
2608  /* BackendStatusArray: */
2609  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2610  /* BackendAppnameBuffer: */
2611  size = add_size(size,
2613  /* BackendClientHostnameBuffer: */
2614  size = add_size(size,
2616  /* BackendActivityBuffer: */
2617  size = add_size(size,
2619 #ifdef USE_SSL
2620  /* BackendSslStatusBuffer: */
2621  size = add_size(size,
2623 #endif
2624  return size;
2625 }
#define NumBackendStatSlots
Definition: pgstat.c:118
#define NAMEDATALEN
int pgstat_track_activity_query_size
Definition: pgstat.c:128
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:422

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

Definition at line 2632 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2633 {
2634  Size size;
2635  bool found;
2636  int i;
2637  char *buffer;
2638 
2639  /* Create or attach to the shared array */
2640  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2642  ShmemInitStruct("Backend Status Array", size, &found);
2643 
2644  if (!found)
2645  {
2646  /*
2647  * We're the first - initialize.
2648  */
2649  MemSet(BackendStatusArray, 0, size);
2650  }
2651 
2652  /* Create or attach to the shared appname buffer */
2653  size = mul_size(NAMEDATALEN, MaxBackends);
2654  BackendAppnameBuffer = (char *)
2655  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2656 
2657  if (!found)
2658  {
2659  MemSet(BackendAppnameBuffer, 0, size);
2660 
2661  /* Initialize st_appname pointers. */
2662  buffer = BackendAppnameBuffer;
2663  for (i = 0; i < NumBackendStatSlots; i++)
2664  {
2666  buffer += NAMEDATALEN;
2667  }
2668  }
2669 
2670  /* Create or attach to the shared client hostname buffer */
2671  size = mul_size(NAMEDATALEN, MaxBackends);
2672  BackendClientHostnameBuffer = (char *)
2673  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2674 
2675  if (!found)
2676  {
2678 
2679  /* Initialize st_clienthostname pointers. */
2680  buffer = BackendClientHostnameBuffer;
2681  for (i = 0; i < NumBackendStatSlots; i++)
2682  {
2684  buffer += NAMEDATALEN;
2685  }
2686  }
2687 
2688  /* Create or attach to the shared activity buffer */
2691  BackendActivityBuffer = (char *)
2692  ShmemInitStruct("Backend Activity Buffer",
2694  &found);
2695 
2696  if (!found)
2697  {
2698  MemSet(BackendActivityBuffer, 0, size);
2699 
2700  /* Initialize st_activity pointers. */
2701  buffer = BackendActivityBuffer;
2702  for (i = 0; i < NumBackendStatSlots; i++)
2703  {
2706  }
2707  }
2708 
2709 #ifdef USE_SSL
2710  /* Create or attach to the shared SSL status buffer */
2712  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2713  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2714 
2715  if (!found)
2716  {
2717  PgBackendSSLStatus *ptr;
2718 
2719  MemSet(BackendSslStatusBuffer, 0, size);
2720 
2721  /* Initialize st_sslstatus pointers. */
2722  ptr = BackendSslStatusBuffer;
2723  for (i = 0; i < NumBackendStatSlots; i++)
2724  {
2726  ptr++;
2727  }
2728  }
2729 #endif
2730 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2589
static char * BackendActivityBuffer
Definition: pgstat.c:2593
static Size BackendActivityBufferSize
Definition: pgstat.c:2594
#define MemSet(start, val, len)
Definition: c.h:897
#define NumBackendStatSlots
Definition: pgstat.c:118
char * st_clienthostname
Definition: pgstat.h:1010
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2591
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
int MaxBackends
Definition: globals.c:127
char * st_activity_raw
Definition: pgstat.h:1029
int pgstat_track_activity_query_size
Definition: pgstat.c:128
char * st_appname
Definition: pgstat.h:1020
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
size_t Size
Definition: c.h:422
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1014
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2592

◆ find_funcstat_entry()

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

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

1634 {
1635  if (pgStatFunctions == NULL)
1636  return NULL;
1637 
1639  (void *) &func_id,
1640  HASH_FIND, NULL);
1641 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
static HTAB * pgStatFunctions
Definition: pgstat.c:197

◆ find_tabstat_entry()

PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

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

1839 {
1840  TabStatHashEntry *hash_entry;
1841 
1842  /* If hashtable doesn't exist, there are no entries at all */
1843  if (!pgStatTabHash)
1844  return NULL;
1845 
1846  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1847  if (!hash_entry)
1848  return NULL;
1849 
1850  /* Note that this step could also return NULL, but that's correct */
1851  return hash_entry->tsa_entry;
1852 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
static HTAB * pgStatTabHash
Definition: pgstat.c:191
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:185

◆ get_dbstat_filename()

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

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

4794 {
4795  int printed;
4796 
4797  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4798  printed = snprintf(filename, len, "%s/db_%u.%s",
4799  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4801  databaseid,
4802  tempname ? "tmp" : "stat");
4803  if (printed > len)
4804  elog(ERROR, "overlength pgstat path");
4805 }
#define PGSTAT_STAT_PERMANENT_DIRECTORY
Definition: pgstat.h:29
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define ERROR
Definition: elog.h:43
char * pgstat_stat_directory
Definition: pgstat.c:134
static char * filename
Definition: pg_dumpall.c:85
#define elog
Definition: elog.h:219

◆ get_tabstat_entry()

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

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

1750 {
1751  TabStatHashEntry *hash_entry;
1752  PgStat_TableStatus *entry;
1753  TabStatusArray *tsa;
1754  bool found;
1755 
1756  /*
1757  * Create hash table if we don't have it already.
1758  */
1759  if (pgStatTabHash == NULL)
1760  {
1761  HASHCTL ctl;
1762 
1763  memset(&ctl, 0, sizeof(ctl));
1764  ctl.keysize = sizeof(Oid);
1765  ctl.entrysize = sizeof(TabStatHashEntry);
1766 
1767  pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1769  &ctl,
1770  HASH_ELEM | HASH_BLOBS);
1771  }
1772 
1773  /*
1774  * Find an entry or create a new one.
1775  */
1776  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1777  if (!found)
1778  {
1779  /* initialize new entry with null pointer */
1780  hash_entry->tsa_entry = NULL;
1781  }
1782 
1783  /*
1784  * If entry is already valid, we're done.
1785  */
1786  if (hash_entry->tsa_entry)
1787  return hash_entry->tsa_entry;
1788 
1789  /*
1790  * Locate the first pgStatTabList entry with free space, making a new list
1791  * entry if needed. Note that we could get an OOM failure here, but if so
1792  * we have left the hashtable and the list in a consistent state.
1793  */
1794  if (pgStatTabList == NULL)
1795  {
1796  /* Set up first pgStatTabList entry */
1799  sizeof(TabStatusArray));
1800  }
1801 
1802  tsa = pgStatTabList;
1803  while (tsa->tsa_used >= TABSTAT_QUANTUM)
1804  {
1805  if (tsa->tsa_next == NULL)
1806  tsa->tsa_next = (TabStatusArray *)
1808  sizeof(TabStatusArray));
1809  tsa = tsa->tsa_next;
1810  }
1811 
1812  /*
1813  * Allocate a PgStat_TableStatus entry within this list entry. We assume
1814  * the entry was already zeroed, either at creation or after last use.
1815  */
1816  entry = &tsa->tsa_entries[tsa->tsa_used++];
1817  entry->t_id = rel_id;
1818  entry->t_shared = isshared;
1819 
1820  /*
1821  * Now we can fill the entry in pgStatTabHash.
1822  */
1823  hash_entry->tsa_entry = entry;
1824 
1825  return entry;
1826 }
int tsa_used
Definition: pgstat.c:173
#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:904
struct TabStatusArray * tsa_next
Definition: pgstat.c:172
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:191
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:174
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define HASH_BLOBS
Definition: hsearch.h:88
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:185
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:728
static TabStatusArray * pgStatTabList
Definition: pgstat.c:177
#define TABSTAT_QUANTUM
Definition: pgstat.c:168

◆ get_tabstat_stack_level()

static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

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

1859 {
1860  PgStat_SubXactStatus *xact_state;
1861 
1862  xact_state = pgStatXactStack;
1863  if (xact_state == NULL || xact_state->nest_level != nest_level)
1864  {
1865  xact_state = (PgStat_SubXactStatus *)
1867  sizeof(PgStat_SubXactStatus));
1868  xact_state->nest_level = nest_level;
1869  xact_state->prev = pgStatXactStack;
1870  xact_state->first = NULL;
1871  pgStatXactStack = xact_state;
1872  }
1873  return xact_state;
1874 }
MemoryContext TopTransactionContext
Definition: mcxt.c:48
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:215
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:219
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:693
PgStat_TableXactStatus * first
Definition: pgstat.c:216

◆ pgstat_beshutdown_hook()

static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

Definition at line 2956 of file pgstat.c.

References MyBEEntry, MyDatabaseId, OidIsValid, pgstat_increment_changecount_after, pgstat_increment_changecount_before, pgstat_report_stat(), and PgBackendStatus::st_procpid.

Referenced by pgstat_initialize().

2957 {
2958  volatile PgBackendStatus *beentry = MyBEEntry;
2959 
2960  /*
2961  * If we got as far as discovering our own database ID, we can report what
2962  * we did to the collector. Otherwise, we'd be sending an invalid
2963  * database ID, so forget it. (This means that accesses to pg_database
2964  * during failed backend starts might never get counted.)
2965  */
2966  if (OidIsValid(MyDatabaseId))
2967  pgstat_report_stat(true);
2968 
2969  /*
2970  * Clear my status entry, following the protocol of bumping st_changecount
2971  * before and after. We use a volatile pointer here to ensure the
2972  * compiler doesn't try to get cute.
2973  */
2975 
2976  beentry->st_procpid = 0; /* mark invalid */
2977 
2979 }
#define OidIsValid(objectId)
Definition: c.h:594
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
Oid MyDatabaseId
Definition: globals.c:77
int st_procpid
Definition: pgstat.h:995
void pgstat_report_stat(bool force)
Definition: pgstat.c:812

◆ pgstat_bestart()

void pgstat_bestart ( void  )

Definition at line 2785 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_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_compression(), be_tls_get_peerdn_name(), be_tls_get_version(), BgWriterProcess, CheckpointerProcess, elog, FATAL, GetCurrentTimestamp(), GetSessionUserId(), InvalidBackendId, InvalidOid, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, MemSet, MyAuxProcType, MyBackendId, MyBEEntry, MyDatabaseId, MyProcPid, MyProcPort, NAMEDATALEN, NotAnAuxProcess, pgstat_increment_changecount_after, pgstat_increment_changecount_before, pgstat_report_appname(), pgstat_track_activity_query_size, proc_exit(), PROGRESS_COMMAND_INVALID, Port::raddr, Port::remote_hostname, Port::SessionStartTime, PgBackendSSLStatus::ssl_bits, PgBackendSSLStatus::ssl_cipher, PgBackendSSLStatus::ssl_clientdn, PgBackendSSLStatus::ssl_compression, 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_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(), WalReceiverProcess, and WalWriterProcess.

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2786 {
2787  TimestampTz proc_start_timestamp;
2788  SockAddr clientaddr;
2789  volatile PgBackendStatus *beentry;
2790 
2791  /*
2792  * To minimize the time spent modifying the PgBackendStatus entry, fetch
2793  * all the needed data first.
2794  *
2795  * If we have a MyProcPort, use its session start time (for consistency,
2796  * and to save a kernel call).
2797  */
2798  if (MyProcPort)
2799  proc_start_timestamp = MyProcPort->SessionStartTime;
2800  else
2801  proc_start_timestamp = GetCurrentTimestamp();
2802 
2803  /*
2804  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2805  * If so, use all-zeroes client address, which is dealt with specially in
2806  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2807  */
2808  if (MyProcPort)
2809  memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2810  else
2811  MemSet(&clientaddr, 0, sizeof(clientaddr));
2812 
2813  /*
2814  * Initialize my status entry, following the protocol of bumping
2815  * st_changecount before and after; and make sure it's even afterwards. We
2816  * use a volatile pointer here to ensure the compiler doesn't try to get
2817  * cute.
2818  */
2819  beentry = MyBEEntry;
2820 
2821  /* pgstats state must be initialized from pgstat_initialize() */
2822  Assert(beentry != NULL);
2823 
2825  {
2827  {
2828  /* Autovacuum Launcher */
2830  }
2831  else if (IsAutoVacuumWorkerProcess())
2832  {
2833  /* Autovacuum Worker */
2834  beentry->st_backendType = B_AUTOVAC_WORKER;
2835  }
2836  else if (am_walsender)
2837  {
2838  /* Wal sender */
2839  beentry->st_backendType = B_WAL_SENDER;
2840  }
2841  else if (IsBackgroundWorker)
2842  {
2843  /* bgworker */
2844  beentry->st_backendType = B_BG_WORKER;
2845  }
2846  else
2847  {
2848  /* client-backend */
2849  beentry->st_backendType = B_BACKEND;
2850  }
2851  }
2852  else
2853  {
2854  /* Must be an auxiliary process */
2856  switch (MyAuxProcType)
2857  {
2858  case StartupProcess:
2859  beentry->st_backendType = B_STARTUP;
2860  break;
2861  case BgWriterProcess:
2862  beentry->st_backendType = B_BG_WRITER;
2863  break;
2864  case CheckpointerProcess:
2865  beentry->st_backendType = B_CHECKPOINTER;
2866  break;
2867  case WalWriterProcess:
2868  beentry->st_backendType = B_WAL_WRITER;
2869  break;
2870  case WalReceiverProcess:
2871  beentry->st_backendType = B_WAL_RECEIVER;
2872  break;
2873  default:
2874  elog(FATAL, "unrecognized process type: %d",
2875  (int) MyAuxProcType);
2876  proc_exit(1);
2877  }
2878  }
2879 
2880  do
2881  {
2883  } while ((beentry->st_changecount & 1) == 0);
2884 
2885  beentry->st_procpid = MyProcPid;
2886  beentry->st_proc_start_timestamp = proc_start_timestamp;
2887  beentry->st_activity_start_timestamp = 0;
2888  beentry->st_state_start_timestamp = 0;
2889  beentry->st_xact_start_timestamp = 0;
2890  beentry->st_databaseid = MyDatabaseId;
2891 
2892  /* We have userid for client-backends, wal-sender and bgworker processes */
2893  if (beentry->st_backendType == B_BACKEND
2894  || beentry->st_backendType == B_WAL_SENDER
2895  || beentry->st_backendType == B_BG_WORKER)
2896  beentry->st_userid = GetSessionUserId();
2897  else
2898  beentry->st_userid = InvalidOid;
2899 
2900  beentry->st_clientaddr = clientaddr;
2903  NAMEDATALEN);
2904  else
2905  beentry->st_clienthostname[0] = '\0';
2906 #ifdef USE_SSL
2907  if (MyProcPort && MyProcPort->ssl != NULL)
2908  {
2909  beentry->st_ssl = true;
2915  }
2916  else
2917  {
2918  beentry->st_ssl = false;
2919  }
2920 #else
2921  beentry->st_ssl = false;
2922 #endif
2923  beentry->st_state = STATE_UNDEFINED;
2924  beentry->st_appname[0] = '\0';
2925  beentry->st_activity_raw[0] = '\0';
2926  /* Also make sure the last byte in each string area is always 0 */
2927  beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
2928  beentry->st_appname[NAMEDATALEN - 1] = '\0';
2932 
2933  /*
2934  * we don't zero st_progress_param here to save cycles; nobody should
2935  * examine it until st_progress_command has been set to something other
2936  * than PROGRESS_COMMAND_INVALID
2937  */
2938 
2940 
2941  /* Update app name to current GUC setting */
2942  if (application_name)
2944 }
bool ssl_compression
Definition: pgstat.h:956
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:958
Oid st_progress_command_target
Definition: pgstat.h:1041
int MyProcPid
Definition: globals.c:39
BackendId MyBackendId
Definition: globals.c:73
struct Port * MyProcPort
Definition: globals.c:41
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:1003
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:957
SockAddr st_clientaddr
Definition: pgstat.h:1009
void proc_exit(int code)
Definition: ipc.c:104
#define MemSet(start, val, len)
Definition: c.h:897
ProgressCommandType st_progress_command
Definition: pgstat.h:1040
BackendState st_state
Definition: pgstat.h:1017
char * st_clienthostname
Definition: pgstat.h:1010
Oid GetSessionUserId(void)
Definition: miscinit.c:318
bool IsBackgroundWorker
Definition: globals.c:103
Oid st_databaseid
Definition: pgstat.h:1007
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:124
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:115
bool be_tls_get_compression(Port *port)
#define FATAL
Definition: elog.h:52
TimestampTz SessionStartTime
Definition: libpq-be.h:151
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
char * st_activity_raw
Definition: pgstat.h:1029
int pgstat_track_activity_query_size
Definition: pgstat.c:128
TimestampTz st_state_start_timestamp
Definition: pgstat.h:1004
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3255
char * st_appname
Definition: pgstat.h:1020
#define InvalidBackendId
Definition: backendid.h:23
int be_tls_get_cipher_bits(Port *port)
AuxProcType MyAuxProcType
Definition: bootstrap.c:69
Oid MyDatabaseId
Definition: globals.c:77
BackendType st_backendType
Definition: pgstat.h:998
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3167
#define InvalidOid
Definition: postgres_ext.h:36
void be_tls_get_peerdn_name(Port *port, char *ptr, size_t len)
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3249
#define Assert(condition)
Definition: c.h:688
const char * be_tls_get_version(Port *port)
int st_procpid
Definition: pgstat.h:995
char * application_name
Definition: guc.c:470
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:1002
int st_changecount
Definition: pgstat.h:992
const char * be_tls_get_cipher(Port *port)
#define elog
Definition: elog.h:219
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:1001
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1014
char ssl_clientdn[NAMEDATALEN]
Definition: pgstat.h:959

◆ pgstat_clear_snapshot()

void pgstat_clear_snapshot ( void  )

Definition at line 5608 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

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

5609 {
5610  /* Release memory, if any was allocated */
5611  if (pgStatLocalContext)
5613 
5614  /* Reset variables */
5615  pgStatLocalContext = NULL;
5616  pgStatDBHash = NULL;
5617  localBackendStatusTable = NULL;
5618  localNumBackends = 0;
5619 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:247
static HTAB * pgStatDBHash
Definition: pgstat.c:244
static int localNumBackends
Definition: pgstat.c:250
static MemoryContext pgStatLocalContext
Definition: pgstat.c:243

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

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

6340 {
6341  char *activity;
6342  int rawlen;
6343  int cliplen;
6344 
6345  /*
6346  * Some callers, like pgstat_get_backend_current_activity(), do not
6347  * guarantee that the buffer isn't concurrently modified. We try to take
6348  * care that the buffer is always terminated by a NUL byte regardless, but
6349  * let's still be paranoid about the string's length. In those cases the
6350  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
6351  * large.
6352  */
6353  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
6354 
6355  /* now double-guaranteed to be NUL terminated */
6356  rawlen = strlen(activity);
6357 
6358  /*
6359  * All supported server-encodings make it possible to determine the length
6360  * of a multi-byte character from its first byte (this is not the case for
6361  * client encodings, see GB18030). As st_activity is always stored using
6362  * server encoding, this allows us to perform multi-byte aware truncation,
6363  * even if the string earlier was truncated in the middle of a multi-byte
6364  * character.
6365  */
6366  cliplen = pg_mbcliplen(activity, rawlen,
6368 
6369  activity[cliplen] = '\0';
6370 
6371  return activity;
6372 }
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1074
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
int pgstat_track_activity_query_size
Definition: pgstat.c:128
static int cliplen(const char *str, int len, int limit)
Definition: mbutils.c:887

◆ pgstat_collect_oids()

static HTAB * pgstat_collect_oids ( Oid  catalogid)
static

Definition at line 1204 of file pgstat.c.

References AccessShareLock, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, HASHCTL::entrysize, ForwardScanDirection, GetLatestSnapshot(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, heap_beginscan(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HASHCTL::keysize, PGSTAT_TAB_HASH_SIZE, RegisterSnapshot(), and UnregisterSnapshot().

Referenced by pgstat_vacuum_stat().

1205 {
1206  HTAB *htab;
1207  HASHCTL hash_ctl;
1208  Relation rel;
1209  HeapScanDesc scan;
1210  HeapTuple tup;
1211  Snapshot snapshot;
1212 
1213  memset(&hash_ctl, 0, sizeof(hash_ctl));
1214  hash_ctl.keysize = sizeof(Oid);
1215  hash_ctl.entrysize = sizeof(Oid);
1216  hash_ctl.hcxt = CurrentMemoryContext;
1217  htab = hash_create("Temporary table of OIDs",
1219  &hash_ctl,
1221 
1222  rel = heap_open(catalogid, AccessShareLock);
1223  snapshot = RegisterSnapshot(GetLatestSnapshot());
1224  scan = heap_beginscan(rel, snapshot, 0, NULL);
1225  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1226  {
1227  Oid thisoid = HeapTupleGetOid(tup);
1228 
1230 
1231  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1232  }
1233  heap_endscan(scan);
1234  UnregisterSnapshot(snapshot);
1236 
1237  return htab;
1238 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1568
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:863
MemoryContext hcxt
Definition: hsearch.h:78
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:105
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:73
#define heap_close(r, l)
Definition: heapam.h:97
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:208
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:905
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1831
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
Size keysize
Definition: hsearch.h:72
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:379
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
HeapScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
Definition: heapam.c:1400

◆ pgstat_count_heap_delete()

void pgstat_count_heap_delete ( Relation  rel)

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

1954 {
1955  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1956 
1957  if (pgstat_info != NULL)
1958  {
1959  /* We have to log the effect at the proper transactional level */
1960  int nest_level = GetCurrentTransactionNestLevel();
1961 
1962  if (pgstat_info->trans == NULL ||
1963  pgstat_info->trans->nest_level != nest_level)
1964  add_tabstat_xact_level(pgstat_info, nest_level);
1965 
1966  pgstat_info->trans->tuples_deleted++;
1967  }
1968 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:754
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1880
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 1907 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().

1908 {
1909  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1910 
1911  if (pgstat_info != NULL)
1912  {
1913  /* We have to log the effect at the proper transactional level */
1914  int nest_level = GetCurrentTransactionNestLevel();
1915 
1916  if (pgstat_info->trans == NULL ||
1917  pgstat_info->trans->nest_level != nest_level)
1918  add_tabstat_xact_level(pgstat_info, nest_level);
1919 
1920  pgstat_info->trans->tuples_inserted += n;
1921  }
1922 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:754
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1880
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157

◆ pgstat_count_heap_update()

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

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

1929 {
1930  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1931 
1932  if (pgstat_info != NULL)
1933  {
1934  /* We have to log the effect at the proper transactional level */
1935  int nest_level = GetCurrentTransactionNestLevel();
1936 
1937  if (pgstat_info->trans == NULL ||
1938  pgstat_info->trans->nest_level != nest_level)
1939  add_tabstat_xact_level(pgstat_info, nest_level);
1940 
1941  pgstat_info->trans->tuples_updated++;
1942 
1943  /* t_tuples_hot_updated is nontransactional, so just advance it */
1944  if (hot)
1945  pgstat_info->t_counts.t_tuples_hot_updated++;
1946  }
1947 }
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:754
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1880
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157

◆ pgstat_count_truncate()

void pgstat_count_truncate ( Relation  rel)

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

2009 {
2010  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2011 
2012  if (pgstat_info != NULL)
2013  {
2014  /* We have to log the effect at the proper transactional level */
2015  int nest_level = GetCurrentTransactionNestLevel();
2016 
2017  if (pgstat_info->trans == NULL ||
2018  pgstat_info->trans->nest_level != nest_level)
2019  add_tabstat_xact_level(pgstat_info, nest_level);
2020 
2021  pgstat_truncate_save_counters(pgstat_info->trans);
2022  pgstat_info->trans->tuples_inserted = 0;
2023  pgstat_info->trans->tuples_updated = 0;
2024  pgstat_info->trans->tuples_deleted = 0;
2025  }
2026 }
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:754
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1880
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1979

◆ pgstat_db_requested()

static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 6312 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

6313 {
6314  /*
6315  * If any requests are outstanding at all, we should write the stats for
6316  * shared catalogs (the "database" with OID 0). This ensures that
6317  * backends will see up-to-date stats for shared catalogs, even though
6318  * they send inquiry messages mentioning only their own DB.
6319  */
6320  if (databaseid == InvalidOid && pending_write_requests != NIL)
6321  return true;
6322 
6323  /* Search to see if there's an open request to write this database. */
6324  if (list_member_oid(pending_write_requests, databaseid))
6325  return true;
6326 
6327  return false;
6328 }
#define NIL
Definition: pg_list.h:69
static List * pending_write_requests
Definition: pgstat.c:265
#define InvalidOid
Definition: postgres_ext.h:36
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505

◆ pgstat_drop_database()

void pgstat_drop_database ( Oid  databaseid)

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

1251 {
1252  PgStat_MsgDropdb msg;
1253 
1255  return;
1256 
1258  msg.m_databaseid = databaseid;
1259  pgstat_send(&msg, sizeof(msg));
1260 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4159
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:149
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:4146

◆ pgstat_end_function_usage()

void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1653 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(), ExecInterpExpr(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

1654 {
1655  PgStat_FunctionCounts *fs = fcu->fs;
1656  instr_time f_total;
1657  instr_time f_others;
1658  instr_time f_self;
1659 
1660  /* stats not wanted? */
1661  if (fs == NULL)
1662  return;
1663 
1664  /* total elapsed time in this function call */
1665  INSTR_TIME_SET_CURRENT(f_total);
1666  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1667 
1668  /* self usage: elapsed minus anything already charged to other calls */
1669  f_others = total_func_time;
1670  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1671  f_self = f_total;
1672  INSTR_TIME_SUBTRACT(f_self, f_others);
1673 
1674  /* update backend-wide total time */
1676 
1677  /*
1678  * Compute the new f_total_time as the total elapsed time added to the
1679  * pre-call value of f_total_time. This is necessary to avoid
1680  * double-counting any time taken by recursive calls of myself. (We do
1681  * not need any similar kluge for self time, since that already excludes
1682  * any recursive calls.)
1683  */
1684  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1685 
1686  /* update counters in function stats table */
1687  if (finalize)
1688  fs->f_numcalls++;
1689  fs->f_total_time = f_total;
1690  INSTR_TIME_ADD(fs->f_self_time, f_self);
1691 
1692  /* indicate that we have something to send */
1693  have_function_stats = true;
1694 }
instr_time f_self_time
Definition: pgstat.h:463
instr_time save_total
Definition: pgstat.h:1121
struct timeval instr_time
Definition: instr_time.h:147
instr_time f_total_time
Definition: pgstat.h:462
PgStat_FunctionCounts * fs
Definition: pgstat.h:1117
PgStat_Counter f_numcalls
Definition: pgstat.h:461
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
#define INSTR_TIME_ADD(x, y)
Definition: instr_time.h:155
static instr_time total_func_time
Definition: pgstat.c:276
static bool have_function_stats
Definition: pgstat.c:203
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:1119

◆ pgstat_exit()

static void pgstat_exit ( SIGNAL_ARGS  )
static

Definition at line 4500 of file pgstat.c.

References MyLatch, need_exit, and SetLatch().

Referenced by PgstatCollectorMain().

4501 {
4502  int save_errno = errno;
4503 
4504  need_exit = true;
4505  SetLatch(MyLatch);
4506 
4507  errno = save_errno;
4508 }
static volatile bool need_exit
Definition: pgstat.c:268
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ pgstat_fetch_global()

◆ pgstat_fetch_stat_archiver()

PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2559 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2560 {
2562 
2563  return &archiverStats;
2564 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5454
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:257

◆ pgstat_fetch_stat_beentry()

◆ pgstat_fetch_stat_dbentry()

PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

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

2388 {
2389  /*
2390  * If not done for this transaction, read the statistics collector stats
2391  * file into some hash tables.
2392  */
2394 
2395  /*
2396  * Lookup the requested database; return NULL if not found
2397  */
2399  (void *) &dbid,
2400  HASH_FIND, NULL);
2401 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
static void backend_read_statsfile(void)
Definition: pgstat.c:5454
static HTAB * pgStatDBHash
Definition: pgstat.c:244

◆ pgstat_fetch_stat_funcentry()

PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

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

2471 {
2472  PgStat_StatDBEntry *dbentry;
2473  PgStat_StatFuncEntry *funcentry = NULL;
2474 
2475  /* load the stats file if needed */
2477 
2478  /* Lookup our database, then find the requested function. */
2480  if (dbentry != NULL && dbentry->functions != NULL)
2481  {
2482  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2483  (void *) &func_id,
2484  HASH_FIND, NULL);
2485  }
2486 
2487  return funcentry;
2488 }
HTAB * functions
Definition: pgstat.h:607
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2387
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
static void backend_read_statsfile(void)
Definition: pgstat.c:5454
Oid MyDatabaseId
Definition: globals.c:77

◆ pgstat_fetch_stat_local_beentry()

LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2524 of file pgstat.c.

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2525 {
2527 
2528  if (beid < 1 || beid > localNumBackends)
2529  return NULL;
2530 
2531  return &localBackendStatusTable[beid - 1];
2532 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3221
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:247
static int localNumBackends
Definition: pgstat.c:250

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

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

2544 {
2546 
2547  return localNumBackends;
2548 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3221
static int localNumBackends
Definition: pgstat.c:250

◆ pgstat_fetch_stat_tabentry()

PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

Definition at line 2414 of file pgstat.c.

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

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

2415 {
2416  Oid dbid;
2417  PgStat_StatDBEntry *dbentry;
2418  PgStat_StatTabEntry *tabentry;
2419 
2420  /*
2421  * If not done for this transaction, read the statistics collector stats
2422  * file into some hash tables.
2423  */
2425 
2426  /*
2427  * Lookup our database, then look in its table hash table.
2428  */
2429  dbid = MyDatabaseId;
2431  (void *) &dbid,
2432  HASH_FIND, NULL);
2433  if (dbentry != NULL && dbentry->tables != NULL)
2434  {
2435  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2436  (void *) &relid,
2437  HASH_FIND, NULL);
2438  if (tabentry)
2439  return tabentry;
2440  }
2441 
2442  /*
2443  * If we didn't find it, maybe it's a shared table.
2444  */
2445  dbid = InvalidOid;
2447  (void *) &dbid,
2448  HASH_FIND, NULL);
2449  if (dbentry != NULL && dbentry->tables != NULL)
2450  {
2451  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2452  (void *) &relid,
2453  HASH_FIND, NULL);
2454  if (tabentry)
2455  return tabentry;
2456  }
2457 
2458  return NULL;
2459 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:5454
Oid MyDatabaseId
Definition: globals.c:77
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pgStatDBHash
Definition: pgstat.c:244

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 3955 of file pgstat.c.

References BackendStatusArray, CHECK_FOR_INTERRUPTS, GetUserId(), i, MaxBackends, pgstat_clip_activity(), pgstat_save_changecount_after, pgstat_save_changecount_before, PgBackendStatus::st_activity_raw, PgBackendStatus::st_procpid, PgBackendStatus::st_userid, and superuser().

Referenced by DeadLockReport().

3956 {
3957  PgBackendStatus *beentry;
3958  int i;
3959 
3960  beentry = BackendStatusArray;
3961  for (i = 1; i <= MaxBackends; i++)
3962  {
3963  /*
3964  * Although we expect the target backend's entry to be stable, that
3965  * doesn't imply that anyone else's is. To avoid identifying the
3966  * wrong backend, while we check for a match to the desired PID we
3967  * must follow the protocol of retrying if st_changecount changes
3968  * while we examine the entry, or if it's odd. (This might be
3969  * unnecessary, since fetching or storing an int is almost certainly
3970  * atomic, but let's play it safe.) We use a volatile pointer here to
3971  * ensure the compiler doesn't try to get cute.
3972  */
3973  volatile PgBackendStatus *vbeentry = beentry;
3974  bool found;
3975 
3976  for (;;)
3977  {
3978  int before_changecount;
3979  int after_changecount;
3980 
3981  pgstat_save_changecount_before(vbeentry, before_changecount);
3982 
3983  found = (vbeentry->st_procpid == pid);
3984 
3985  pgstat_save_changecount_after(vbeentry, after_changecount);
3986 
3987  if (before_changecount == after_changecount &&
3988  (before_changecount & 1) == 0)
3989  break;
3990 
3991  /* Make sure we can break out of loop if stuck... */
3993  }
3994 
3995  if (found)
3996  {
3997  /* Now it is safe to use the non-volatile pointer */
3998  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
3999  return "<insufficient privilege>";
4000  else if (*(beentry->st_activity_raw) == '\0')
4001  return "<command string not enabled>";
4002  else
4003  {
4004  /* this'll leak a bit of memory, but that seems acceptable */
4005  return pgstat_clip_activity(beentry->st_activity_raw);
4006  }
4007  }
4008 
4009  beentry++;
4010  }
4011 
4012  /* If we get here, caller is in error ... */
4013  return "<backend information not available>";
4014 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2589
Oid GetUserId(void)
Definition: miscinit.c:284
bool superuser(void)
Definition: superuser.c:47
int MaxBackends
Definition: globals.c:127
char * st_activity_raw
Definition: pgstat.h:1029
#define pgstat_save_changecount_before(beentry, save_changecount)
Definition: pgstat.h:1070
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:1076
int st_procpid
Definition: pgstat.h:995
char * pgstat_clip_activity(const char *raw_activity)
Definition: pgstat.c:6339
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

◆ pgstat_get_backend_desc()

const char* pgstat_get_backend_desc ( BackendType  backendType)

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

4093 {
4094  const char *backendDesc = "unknown process type";
4095 
4096  switch (backendType)
4097  {
4098  case B_AUTOVAC_LAUNCHER:
4099  backendDesc = "autovacuum launcher";
4100  break;
4101  case B_AUTOVAC_WORKER:
4102  backendDesc = "autovacuum worker";
4103  break;
4104  case B_BACKEND:
4105  backendDesc = "client backend";
4106  break;
4107  case B_BG_WORKER:
4108  backendDesc = "background worker";
4109  break;
4110  case B_BG_WRITER:
4111  backendDesc = "background writer";
4112  break;
4113  case B_CHECKPOINTER:
4114  backendDesc = "checkpointer";
4115  break;
4116  case B_STARTUP:
4117  backendDesc = "startup";
4118  break;
4119  case B_WAL_RECEIVER:
4120  backendDesc = "walreceiver";
4121  break;
4122  case B_WAL_SENDER:
4123  backendDesc = "walsender";
4124  break;
4125  case B_WAL_WRITER:
4126  backendDesc = "walwriter";
4127  break;
4128  }
4129 
4130  return backendDesc;
4131 }

◆ pgstat_get_crashed_backend_activity()

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

Definition at line 4033 of file pgstat.c.

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

Referenced by LogChildExit().

4034 {
4035  volatile PgBackendStatus *beentry;
4036  int i;
4037 
4038  beentry = BackendStatusArray;
4039 
4040  /*
4041  * We probably shouldn't get here before shared memory has been set up,
4042  * but be safe.
4043  */
4044  if (beentry == NULL || BackendActivityBuffer == NULL)
4045  return NULL;
4046 
4047  for (i = 1; i <= MaxBackends; i++)
4048  {
4049  if (beentry->st_procpid == pid)
4050  {
4051  /* Read pointer just once, so it can't change after validation */
4052  const char *activity = beentry->st_activity_raw;
4053  const char *activity_last;
4054 
4055  /*
4056  * We mustn't access activity string before we verify that it
4057  * falls within the BackendActivityBuffer. To make sure that the
4058  * entire string including its ending is contained within the
4059  * buffer, subtract one activity length from the buffer size.
4060  */
4063 
4064  if (activity < BackendActivityBuffer ||
4065  activity > activity_last)
4066  return NULL;
4067 
4068  /* If no string available, no point in a report */
4069  if (activity[0] == '\0')
4070  return NULL;
4071 
4072  /*
4073  * Copy only ASCII-safe characters so we don't run into encoding
4074  * problems when reporting the message; and be sure not to run off
4075  * the end of memory. As only ASCII characters are reported, it
4076  * doesn't seem necessary to perform multibyte aware clipping.
4077  */
4078  ascii_safe_strlcpy(buffer, activity,
4079  Min(buflen, pgstat_track_activity_query_size));
4080 
4081  return buffer;
4082  }
4083 
4084  beentry++;
4085  }
4086 
4087  /* PID not found */
4088  return NULL;
4089 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2589
static char * BackendActivityBuffer
Definition: pgstat.c:2593
#define Min(x, y)
Definition: c.h:846
static Size BackendActivityBufferSize
Definition: pgstat.c:2594
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
int MaxBackends
Definition: globals.c:127
char * st_activity_raw
Definition: pgstat.h:1029
int pgstat_track_activity_query_size
Definition: pgstat.c:128
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
int st_procpid
Definition: pgstat.h:995
int i

◆ pgstat_get_db_entry()

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

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

4579 {
4580  PgStat_StatDBEntry *result;
4581  bool found;
4582  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4583 
4584  /* Lookup or create the hash table entry for this database */
4586  &databaseid,
4587  action, &found);
4588 
4589  if (!create && !found)
4590  return NULL;
4591 
4592  /*
4593  * If not found, initialize the new one. This creates empty hash tables
4594  * for tables and functions, too.
4595  */
4596  if (!found)
4597  reset_dbentry_counters(result);
4598 
4599  return result;
4600 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4528
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
static HTAB * pgStatDBHash
Definition: pgstat.c:244
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 4609 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().

4610 {
4611  PgStat_StatTabEntry *result;
4612  bool found;
4613  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4614 
4615  /* Lookup or create the hash table entry for this table */
4616  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4617  &tableoid,
4618  action, &found);
4619 
4620  if (!create && !found)
4621  return NULL;
4622 
4623  /* If not found, initialize the new one. */
4624  if (!found)
4625  {
4626  result->numscans = 0;
4627  result->tuples_returned = 0;
4628  result->tuples_fetched = 0;
4629  result->tuples_inserted = 0;
4630  result->tuples_updated = 0;
4631  result->tuples_deleted = 0;
4632  result->tuples_hot_updated = 0;
4633  result->n_live_tuples = 0;
4634  result->n_dead_tuples = 0;
4635  result->changes_since_analyze = 0;
4636  result->blocks_fetched = 0;
4637  result->blocks_hit = 0;
4638  result->vacuum_timestamp = 0;
4639  result->vacuum_count = 0;
4640  result->autovac_vacuum_timestamp = 0;
4641  result->autovac_vacuum_count = 0;
4642  result->analyze_timestamp = 0;
4643  result->analyze_count = 0;
4644  result->autovac_analyze_timestamp = 0;
4645  result->autovac_analyze_count = 0;
4646  }
4647 
4648  return result;
4649 }
PgStat_Counter analyze_count
Definition: pgstat.h:641
PgStat_Counter tuples_returned
Definition: pgstat.h:621
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:642
PgStat_Counter vacuum_count
Definition: pgstat.h:637
PgStat_Counter numscans
Definition: pgstat.h:619
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:627
PgStat_Counter tuples_inserted
Definition: pgstat.h:624
PgStat_Counter n_live_tuples
Definition: pgstat.h:629
TimestampTz vacuum_timestamp
Definition: pgstat.h:636
PgStat_Counter n_dead_tuples
Definition: pgstat.h:630
PgStat_Counter tuples_fetched
Definition: pgstat.h:622
PgStat_Counter blocks_hit
Definition: pgstat.h:634
TimestampTz analyze_timestamp
Definition: pgstat.h:640
PgStat_Counter changes_since_analyze
Definition: pgstat.h:631
PgStat_Counter tuples_deleted
Definition: pgstat.h:626
PgStat_Counter tuples_updated
Definition: pgstat.h:625
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:638
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:643
PgStat_Counter blocks_fetched
Definition: pgstat.h:633
HASHACTION
Definition: hsearch.h:103
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:639

◆ pgstat_get_wait_activity()

static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

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

3468 {
3469  const char *event_name = "unknown wait event";
3470 
3471  switch (w)
3472  {
3474  event_name = "ArchiverMain";
3475  break;
3477  event_name = "AutoVacuumMain";
3478  break;
3480  event_name = "BgWriterHibernate";
3481  break;
3483  event_name = "BgWriterMain";
3484  break;
3486  event_name = "CheckpointerMain";
3487  break;
3489  event_name = "LogicalLauncherMain";
3490  break;
3492  event_name = "LogicalApplyMain";
3493  break;
3495  event_name = "PgStatMain";
3496  break;
3498  event_name = "RecoveryWalAll";
3499  break;
3501  event_name = "RecoveryWalStream";
3502  break;
3504  event_name = "SysLoggerMain";
3505  break;
3507  event_name = "WalReceiverMain";
3508  break;
3510  event_name = "WalSenderMain";
3511  break;
3513  event_name = "WalWriterMain";
3514  break;
3515  /* no default case, so that compiler will warn */
3516  }
3517 
3518  return event_name;
3519 }

◆ pgstat_get_wait_client()

static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3528 of file pgstat.c.

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

3529 {
3530  const char *event_name = "unknown wait event";
3531 
3532  switch (w)
3533  {
3535  event_name = "ClientRead";
3536  break;
3538  event_name = "ClientWrite";
3539  break;
3541  event_name = "LibPQWalReceiverConnect";
3542  break;
3544  event_name = "LibPQWalReceiverReceive";
3545  break;
3547  event_name = "SSLOpenServer";
3548  break;
3550  event_name = "WalReceiverWaitStart";
3551  break;
3553  event_name = "WalSenderWaitForWAL";
3554  break;
3556  event_name = "WalSenderWriteData";
3557  break;
3558  /* no default case, so that compiler will warn */
3559  }
3560 
3561  return event_name;
3562 }

◆ pgstat_get_wait_event()

const char* pgstat_get_wait_event ( uint32  wait_event_info)

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

3391 {
3392  uint32 classId;
3393  uint16 eventId;
3394  const char *event_name;
3395 
3396  /* report process as not waiting. */
3397  if (wait_event_info == 0)
3398  return NULL;
3399 
3400  classId = wait_event_info & 0xFF000000;
3401  eventId = wait_event_info & 0x0000FFFF;
3402 
3403  switch (classId)
3404  {
3405  case PG_WAIT_LWLOCK:
3406  event_name = GetLWLockIdentifier(classId, eventId);
3407  break;
3408  case PG_WAIT_LOCK:
3409  event_name = GetLockNameFromTagType(eventId);
3410  break;
3411  case PG_WAIT_BUFFER_PIN:
3412  event_name = "BufferPin";
3413  break;
3414  case PG_WAIT_ACTIVITY:
3415  {
3416  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3417 
3418  event_name = pgstat_get_wait_activity(w);
3419  break;
3420  }
3421  case PG_WAIT_CLIENT:
3422  {
3423  WaitEventClient w = (WaitEventClient) wait_event_info;
3424 
3425  event_name = pgstat_get_wait_client(w);
3426  break;
3427  }
3428  case PG_WAIT_EXTENSION:
3429  event_name = "Extension";
3430  break;
3431  case PG_WAIT_IPC:
3432  {
3433  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3434 
3435  event_name = pgstat_get_wait_ipc(w);
3436  break;
3437  }
3438  case PG_WAIT_TIMEOUT:
3439  {
3440  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3441 
3442  event_name = pgstat_get_wait_timeout(w);
3443  break;
3444  }
3445  case PG_WAIT_IO:
3446  {
3447  WaitEventIO w = (WaitEventIO) wait_event_info;
3448 
3449  event_name = pgstat_get_wait_io(w);
3450  break;
3451  }
3452  default:
3453  event_name = "unknown wait event";
3454  break;
3455  }
3456 
3457  return event_name;
3458 }
#define PG_WAIT_LOCK
Definition: pgstat.h:738
WaitEventIPC
Definition: pgstat.h:800
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3692
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3571
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:740
#define PG_WAIT_IO
Definition: pgstat.h:745
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3467
unsigned short uint16
Definition: c.h:313
#define PG_WAIT_CLIENT
Definition: pgstat.h:741
WaitEventClient
Definition: pgstat.h:781
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3528
unsigned int uint32
Definition: c.h:314
WaitEventTimeout
Definition: pgstat.h:844
#define PG_WAIT_EXTENSION
Definition: pgstat.h:742
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:739
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1065
WaitEventIO
Definition: pgstat.h:857
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:744
#define PG_WAIT_IPC
Definition: pgstat.h:743
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:712
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:3720
#define PG_WAIT_LWLOCK
Definition: pgstat.h:737
WaitEventActivity
Definition: pgstat.h:755

◆ pgstat_get_wait_event_type()

const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

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

3336 {
3337  uint32 classId;
3338  const char *event_type;
3339 
3340  /* report process as not waiting. */
3341  if (wait_event_info == 0)
3342  return NULL;
3343 
3344  classId = wait_event_info & 0xFF000000;
3345 
3346  switch (classId)
3347  {
3348  case PG_WAIT_LWLOCK:
3349  event_type = "LWLock";
3350  break;
3351  case PG_WAIT_LOCK:
3352  event_type = "Lock";
3353  break;
3354  case PG_WAIT_BUFFER_PIN:
3355  event_type = "BufferPin";
3356  break;
3357  case PG_WAIT_ACTIVITY:
3358  event_type = "Activity";
3359  break;
3360  case PG_WAIT_CLIENT:
3361  event_type = "Client";
3362  break;
3363  case PG_WAIT_EXTENSION:
3364  event_type = "Extension";
3365  break;
3366  case PG_WAIT_IPC:
3367  event_type = "IPC";
3368  break;
3369  case PG_WAIT_TIMEOUT:
3370  event_type = "Timeout";
3371  break;
3372  case PG_WAIT_IO:
3373  event_type = "IO";
3374  break;
3375  default:
3376  event_type = "???";
3377  break;
3378  }
3379 
3380  return event_type;
3381 }
#define PG_WAIT_LOCK
Definition: pgstat.h:738
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:740
#define PG_WAIT_IO
Definition: pgstat.h:745
#define PG_WAIT_CLIENT
Definition: pgstat.h:741
unsigned int uint32
Definition: c.h:314
#define PG_WAIT_EXTENSION
Definition: pgstat.h:742
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:739
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:744
#define PG_WAIT_IPC
Definition: pgstat.h:743
#define PG_WAIT_LWLOCK
Definition: pgstat.h:737

◆ pgstat_get_wait_io()

static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

Definition at line 3720 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_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_METHOD_ASSIGN, WAIT_EVENT_WAL_WRITE, and WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ.

Referenced by pgstat_get_wait_event().

3721 {
3722  const char *event_name = "unknown wait event";
3723 
3724  switch (w)
3725  {
3727  event_name = "BufFileRead";
3728  break;
3730  event_name = "BufFileWrite";
3731  break;
3733  event_name = "ControlFileRead";
3734  break;
3736  event_name = "ControlFileSync";
3737  break;
3739  event_name = "ControlFileSyncUpdate";
3740  break;
3742  event_name = "ControlFileWrite";
3743  break;
3745  event_name = "ControlFileWriteUpdate";
3746  break;
3748  event_name = "CopyFileRead";
3749  break;
3751  event_name = "CopyFileWrite";
3752  break;
3754  event_name = "DataFileExtend";
3755  break;
3757  event_name = "DataFileFlush";
3758  break;
3760  event_name = "DataFileImmediateSync";
3761  break;
3763  event_name = "DataFilePrefetch";
3764  break;
3766  event_name = "DataFileRead";
3767  break;
3769  event_name = "DataFileSync";
3770  break;
3772  event_name = "DataFileTruncate";
3773  break;
3775  event_name = "DataFileWrite";
3776  break;
3778  event_name = "DSMFillZeroWrite";
3779  break;
3781  event_name = "LockFileAddToDataDirRead";
3782  break;
3784  event_name = "LockFileAddToDataDirSync";
3785  break;
3787  event_name = "LockFileAddToDataDirWrite";
3788  break;
3790  event_name = "LockFileCreateRead";
3791  break;
3793  event_name = "LockFileCreateSync";
3794  break;
3796  event_name = "LockFileCreateWRITE";
3797  break;
3799  event_name = "LockFileReCheckDataDirRead";
3800  break;
3802  event_name = "LogicalRewriteCheckpointSync";
3803  break;
3805  event_name = "LogicalRewriteMappingSync";
3806  break;
3808  event_name = "LogicalRewriteMappingWrite";
3809  break;
3811  event_name = "LogicalRewriteSync";
3812  break;
3814  event_name = "LogicalRewriteTruncate";
3815  break;
3817  event_name = "LogicalRewriteWrite";
3818  break;
3820  event_name = "RelationMapRead";
3821  break;
3823  event_name = "RelationMapSync";
3824  break;
3826  event_name = "RelationMapWrite";
3827  break;
3829  event_name = "ReorderBufferRead";
3830  break;
3832  event_name = "ReorderBufferWrite";
3833  break;
3835  event_name = "ReorderLogicalMappingRead";
3836  break;
3838  event_name = "ReplicationSlotRead";
3839  break;
3841  event_name = "ReplicationSlotRestoreSync";
3842  break;
3844  event_name = "ReplicationSlotSync";
3845  break;
3847  event_name = "ReplicationSlotWrite";
3848  break;
3850  event_name = "SLRUFlushSync";
3851  break;
3852  case WAIT_EVENT_SLRU_READ:
3853  event_name = "SLRURead";
3854  break;
3855  case WAIT_EVENT_SLRU_SYNC:
3856  event_name = "SLRUSync";
3857  break;
3858  case WAIT_EVENT_SLRU_WRITE:
3859  event_name = "SLRUWrite";
3860  break;
3862  event_name = "SnapbuildRead";
3863  break;
3865  event_name = "SnapbuildSync";
3866  break;
3868  event_name = "SnapbuildWrite";
3869  break;
3871  event_name = "TimelineHistoryFileSync";
3872  break;
3874  event_name = "TimelineHistoryFileWrite";
3875  break;
3877  event_name = "TimelineHistoryRead";
3878  break;
3880  event_name = "TimelineHistorySync";
3881  break;
3883  event_name = "TimelineHistoryWrite";
3884  break;
3886  event_name = "TwophaseFileRead";
3887  break;
3889  event_name = "TwophaseFileSync";
3890  break;
3892  event_name = "TwophaseFileWrite";
3893  break;
3895  event_name = "WALSenderTimelineHistoryRead";
3896  break;
3898  event_name = "WALBootstrapSync";
3899  break;
3901  event_name = "WALBootstrapWrite";
3902  break;
3904  event_name = "WALCopyRead";
3905  break;
3907  event_name = "WALCopySync";
3908  break;
3910  event_name = "WALCopyWrite";
3911  break;
3913  event_name = "WALInitSync";
3914  break;
3916  event_name = "WALInitWrite";
3917  break;
3918  case WAIT_EVENT_WAL_READ:
3919  event_name = "WALRead";
3920  break;
3922  event_name = "WALSyncMethodAssign";
3923  break;
3924  case WAIT_EVENT_WAL_WRITE:
3925  event_name = "WALWrite";
3926  break;
3927 
3928  /* no default case, so that compiler will warn */
3929  }
3930 
3931  return event_name;
3932 }

◆ pgstat_get_wait_ipc()

static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3571 of file pgstat.c.

References WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WAIT_EVENT_BTREE_PAGE, 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_REPLICATION_ORIGIN_DROP, WAIT_EVENT_REPLICATION_SLOT_DROP, WAIT_EVENT_SAFE_SNAPSHOT, and WAIT_EVENT_SYNC_REP.

Referenced by pgstat_get_wait_event().

3572 {
3573  const char *event_name = "unknown wait event";
3574 
3575  switch (w)
3576  {
3578  event_name = "BgWorkerShutdown";
3579  break;
3581  event_name = "BgWorkerStartup";
3582  break;
3583  case WAIT_EVENT_BTREE_PAGE:
3584  event_name = "BtreePage";
3585  break;
3587  event_name = "ExecuteGather";
3588  break;
3590  event_name = "Hash/Batch/Allocating";
3591  break;
3593  event_name = "Hash/Batch/Electing";
3594  break;
3596  event_name = "Hash/Batch/Loading";
3597  break;
3599  event_name = "Hash/Build/Allocating";
3600  break;
3602  event_name = "Hash/Build/Electing";
3603  break;
3605  event_name = "Hash/Build/HashingInner";
3606  break;
3608  event_name = "Hash/Build/HashingOuter";
3609  break;
3611  event_name = "Hash/GrowBatches/Allocating";
3612  break;
3614  event_name = "Hash/GrowBatches/Deciding";
3615  break;
3617  event_name = "Hash/GrowBatches/Electing";
3618  break;
3620  event_name = "Hash/GrowBatches/Finishing";
3621  break;
3623  event_name = "Hash/GrowBatches/Repartitioning";
3624  break;
3626  event_name = "Hash/GrowBuckets/Allocating";
3627  break;
3629  event_name = "Hash/GrowBuckets/Electing";
3630  break;
3632  event_name = "Hash/GrowBuckets/Reinserting";
3633  break;
3635  event_name = "LogicalSyncData";
3636  break;
3638  event_name = "LogicalSyncStateChange";
3639  break;
3641  event_name = "MessageQueueInternal";
3642  break;
3644  event_name = "MessageQueuePutMessage";
3645  break;
3646  case WAIT_EVENT_MQ_RECEIVE:
3647  event_name = "MessageQueueReceive";
3648  break;
3649  case WAIT_EVENT_MQ_SEND:
3650  event_name = "MessageQueueSend";
3651  break;
3653  event_name = "ParallelFinish";
3654  break;
3656  event_name = "ParallelBitmapScan";
3657  break;
3659  event_name = "ParallelCreateIndexScan";
3660  break;
3662  event_name = "ProcArrayGroupUpdate";
3663  break;
3665  event_name = "ClogGroupUpdate";
3666  break;
3668  event_name = "ReplicationOriginDrop";
3669  break;
3671  event_name = "ReplicationSlotDrop";
3672  break;
3674  event_name = "SafeSnapshot";
3675  break;
3676  case WAIT_EVENT_SYNC_REP:
3677  event_name = "SyncRep";
3678  break;
3679  /* no default case, so that compiler will warn */
3680  }
3681 
3682  return event_name;
3683 }

◆ pgstat_get_wait_timeout()

static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

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

3693 {
3694  const char *event_name = "unknown wait event";
3695 
3696  switch (w)
3697  {
3699  event_name = "BaseBackupThrottle";
3700  break;
3701  case WAIT_EVENT_PG_SLEEP:
3702  event_name = "PgSleep";
3703  break;
3705  event_name = "RecoveryApplyDelay";
3706  break;
3707  /* no default case, so that compiler will warn */
3708  }
3709 
3710  return event_name;
3711 }

◆ pgstat_init()

void pgstat_init ( void  )

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

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

◆ pgstat_init_function_usage()

void pgstat_init_function_usage ( FunctionCallInfoData fcinfo,
PgStat_FunctionCallUsage fcu 
)

Definition at line 1581 of file pgstat.c.

References HASHCTL::entrysize, PgStat_BackendFunctionEntry::f_counts, PgStat_FunctionCallUsage::f_start, PgStat_FunctionCounts::f_total_time, FunctionCallInfoData::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(), ExecInterpExpr(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

1583 {
1584  PgStat_BackendFunctionEntry *htabent;
1585  bool found;
1586 
1587  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1588  {
1589  /* stats not wanted */
1590  fcu->fs = NULL;
1591  return;
1592  }
1593 
1594  if (!pgStatFunctions)
1595  {
1596  /* First time through - initialize function stat table */
1597  HASHCTL hash_ctl;
1598 
1599  memset(&hash_ctl, 0, sizeof(hash_ctl));
1600  hash_ctl.keysize = sizeof(Oid);
1601  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1602  pgStatFunctions = hash_create("Function stat entries",
1604  &hash_ctl,
1605  HASH_ELEM | HASH_BLOBS);
1606  }
1607 
1608  /* Get the stats entry for this function, create if necessary */
1609  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1610  HASH_ENTER, &found);
1611  if (!found)
1612  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1613 
1614  fcu->fs = &htabent->f_counts;
1615 
1616  /* save stats for this function, later used to compensate for recursion */
1617  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1618 
1619  /* save current backend-wide total time */
1620  fcu->save_total = total_func_time;
1621 
1622  /* get clock time as of function start */
1624 }
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:1121
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:897
instr_time f_total_time
Definition: pgstat.h:462
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1117
FmgrInfo * flinfo
Definition: fmgr.h:79
PgStat_FunctionCounts f_counts
Definition: pgstat.h:473
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:106
#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
Oid fn_oid
Definition: fmgr.h:59
static instr_time total_func_time
Definition: pgstat.c:276
static HTAB * pgStatFunctions
Definition: pgstat.c:197
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:1119
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry

◆ pgstat_initialize()

void pgstat_initialize ( void  )

Definition at line 2745 of file pgstat.c.

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

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2746 {
2747  /* Initialize MyBEEntry */
2749  {
2752  }
2753  else
2754  {
2755  /* Must be an auxiliary process */
2757 
2758  /*
2759  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
2760  * have a BackendId, the slot is statically allocated based on the
2761  * auxiliary process type (MyAuxProcType). Backends use slots indexed
2762  * in the range from 1 to MaxBackends (inclusive), so we use
2763  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2764  * auxiliary process.
2765  */
2767  }
2768 
2769  /* Set up a process-exit hook to clean up */
2771 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2589
BackendId MyBackendId
Definition: globals.c:73
int MaxBackends
Definition: globals.c:127
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:355
static void pgstat_beshutdown_hook(int code, Datum arg)
Definition: pgstat.c:2956
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:69
#define Assert(condition)
Definition: c.h:688

◆ pgstat_initstats()

void pgstat_initstats ( Relation  rel)

Definition at line 1710 of file pgstat.c.

References get_tabstat_entry(), PGINVALID_SOCKET, RelationData::pgstat_info, pgstat_track_counts, pgStatSock, RelationData::rd_id, RelationData::rd_rel, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, and PgStat_TableStatus::t_id.

Referenced by relation_open(), and try_relation_open().

1711 {
1712  Oid rel_id = rel->rd_id;
1713  char relkind = rel->rd_rel->relkind;
1714 
1715  /* We only count stats for things that have storage */
1716  if (!(relkind == RELKIND_RELATION ||
1717  relkind == RELKIND_MATVIEW ||
1718  relkind == RELKIND_INDEX ||
1719  relkind == RELKIND_TOASTVALUE ||
1720  relkind == RELKIND_SEQUENCE))
1721  {
1722  rel->pgstat_info = NULL;
1723  return;
1724  }
1725 
1727  {
1728  /* We're not counting at all */
1729  rel->pgstat_info = NULL;
1730  return;
1731  }
1732 
1733  /*
1734  * If we already set up this relation in the current transaction, nothing
1735  * to do.
1736  */
1737  if (rel->pgstat_info != NULL &&
1738  rel->pgstat_info->t_id == rel_id)
1739  return;
1740 
1741  /* Else find or make the PgStat_TableStatus entry, and update link */
1742  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1743 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:149
#define RELKIND_MATVIEW
Definition: pg_class.h:165
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool pgstat_track_counts
Definition: pgstat.c:126
Oid rd_id
Definition: rel.h:116
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:1749
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#define PGINVALID_SOCKET
Definition: port.h:33
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
#define RELKIND_INDEX
Definition: pg_class.h:161
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162

◆ pgstat_ping()

void pgstat_ping ( void  )

Definition at line 1546 of file pgstat.c.

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

1547 {
1548  PgStat_MsgDummy msg;
1549 
1551  return;
1552 
1554  pgstat_send(&msg, sizeof(msg));
1555 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4159
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:149
#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:4146

◆ pgstat_progress_end_command()

void pgstat_progress_end_command ( void  )

Definition at line 3144 of file pgstat.c.

References InvalidOid, MyBEEntry, pgstat_increment_changecount_after, pgstat_increment_changecount_before, pgstat_track_activities, PROGRESS_COMMAND_INVALID, PgBackendStatus::st_progress_command, and PgBackendStatus::st_progress_command_target.

Referenced by AbortSubTransaction(), AbortTransaction(), and lazy_vacuum_rel().

3145 {
3146  volatile PgBackendStatus *beentry = MyBEEntry;
3147 
3148  if (!beentry)
3149  return;
3152  return;
3153 
3158 }
Oid st_progress_command_target
Definition: pgstat.h:1041
ProgressCommandType st_progress_command
Definition: pgstat.h:1040
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:125

◆ pgstat_progress_start_command()

void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

Definition at line 3072 of file pgstat.c.

References MemSet, MyBEEntry, pgstat_increment_changecount_after, pgstat_increment_changecount_before, pgstat_track_activities, PgBackendStatus::st_progress_command, PgBackendStatus::st_progress_command_target, and PgBackendStatus::st_progress_param.

Referenced by lazy_vacuum_rel().

3073 {
3074  volatile PgBackendStatus *beentry = MyBEEntry;
3075 
3076  if (!beentry || !pgstat_track_activities)
3077  return;
3078 
3080  beentry->st_progress_command = cmdtype;
3081  beentry->st_progress_command_target = relid;
3082  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3084 }
Oid st_progress_command_target
Definition: pgstat.h:1041
#define MemSet(start, val, len)
Definition: c.h:897
ProgressCommandType st_progress_command
Definition: pgstat.h:1040
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1042
bool pgstat_track_activities
Definition: pgstat.c:125

◆ pgstat_progress_update_multi_param()

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

Definition at line 3115 of file pgstat.c.

References Assert, i, MyBEEntry, pgstat_increment_changecount_after, pgstat_increment_changecount_before, PGSTAT_NUM_PROGRESS_PARAM, pgstat_track_activities, and PgBackendStatus::st_progress_param.

Referenced by lazy_scan_heap().

3117 {
3118  volatile PgBackendStatus *beentry = MyBEEntry;
3119  int i;
3120 
3121  if (!beentry || !pgstat_track_activities || nparam == 0)
3122  return;
3123 
3125 
3126  for (i = 0; i < nparam; ++i)
3127  {
3128  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3129 
3130  beentry->st_progress_param[index[i]] = val[i];
3131  }
3132 
3134 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:938
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
#define Assert(condition)
Definition: c.h:688
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1042
bool pgstat_track_activities
Definition: pgstat.c:125
int i
long val
Definition: informix.c:689

◆ pgstat_progress_update_param()

void pgstat_progress_update_param ( int  index,
int64  val 
)

Definition at line 3093 of file pgstat.c.

References Assert, MyBEEntry, pgstat_increment_changecount_after, pgstat_increment_changecount_before, PGSTAT_NUM_PROGRESS_PARAM, pgstat_track_activities, PgBackendStatus::st_progress_param, and val.

Referenced by lazy_record_dead_tuple(), lazy_scan_heap(), lazy_truncate_heap(), lazy_vacuum_page(), and lazy_vacuum_rel().

3094 {
3095  volatile PgBackendStatus *beentry = MyBEEntry;
3096 
3098 
3099  if (!beentry || !pgstat_track_activities)
3100  return;
3101 
3103  beentry->st_progress_param[index] = val;
3105 }
Definition: type.h:89
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:938
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2590
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1057
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1063
#define Assert(condition)
Definition: c.h:688
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1042
bool pgstat_track_activities
Definition: pgstat.c:125
long val
Definition: informix.c:689

◆ pgstat_read_current_status()

static void pgstat_read_current_status ( void  )
static

Definition at line 3221 of file pgstat.c.

References Assert, LocalPgBackendStatus::backend_xid, LocalPgBackendStatus::backend_xmin, BackendIdGetTransactionIds(), LocalPgBackendStatus::backendStatus, BackendStatusArray, CHECK_FOR_INTERRUPTS, i, localNumBackends, MemoryContextAlloc(), NAMEDATALEN, NumBackendStatSlots, pgstat_save_changecount_after, pgstat_save_changecount_before, pgstat_setup_memcxt(), pgstat_track_activity_query_size, pgStatRunningInCollector, PgBackendStatus::st_activity_raw, PgBackendStatus::st_appname, PgBackendStatus::st_procpid, PgBackendStatus::st_ssl, and PgBackendStatus::st_sslstatus.

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

3222 {
3223  volatile PgBackendStatus *beentry;
3224  LocalPgBackendStatus *localtable;
3225  LocalPgBackendStatus *localentry;
3226  char *localappname,
3227  *localactivity;
3228 #ifdef USE_SSL
3229  PgBackendSSLStatus *localsslstatus;
3230 #endif
3231  int i;
3232 
3235  return; /* already done */
3236 
3238 
3239  localtable = (LocalPgBackendStatus *)
3242  localappname = (char *)
3245  localactivity = (char *)
3247  pgstat_track_activity_query_size * NumBackendStatSlots);
3248 #ifdef USE_SSL
3249  localsslstatus = (PgBackendSSLStatus *)
3252 #endif
3253 
3254  localNumBackends = 0;
3255 
3256  beentry = BackendStatusArray;
3257  localentry = localtable;
3258  for (i = 1; i <= NumBackendStatSlots; i++)
3259  {
3260  /*
3261  * Follow the protocol of retrying if st_changecount changes while we
3262  * copy the entry, or if it's odd. (The check for odd is needed to
3263  * cover the case where we are able to completely copy the entry while
3264  * the source backend is between increment steps.) We use a volatile
3265  * pointer here to ensure the compiler doesn't try to get cute.
3266  */
3267  for (;;)
3268  {
3269  int before_changecount;
3270  int after_changecount;
3271 
3272  pgstat_save_changecount_before(beentry, before_changecount);
3273 
3274  localentry->backendStatus.st_procpid = beentry->st_procpid;
3275  if (localentry->backendStatus.st_procpid > 0)
3276  {
3277  memcpy(&localentry->backendStatus, (char *) beentry, sizeof(PgBackendStatus));
3278 
3279  /*
3280  * strcpy is safe even if the string is modified concurrently,
3281  * because there's always a \0 at the end of the buffer.
3282  */
3283  strcpy(localappname, (char *) beentry->st_appname);
3284  localentry->backendStatus.st_appname = localappname;
3285  strcpy(localactivity, (char *) beentry->st_activity_raw);
3286  localentry->backendStatus.st_activity_raw = localactivity;
3287  localentry->backendStatus.st_ssl = beentry->st_ssl;
3288 #ifdef USE_SSL
3289  if (beentry->st_ssl)
3290  {
3291  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3292  localentry->backendStatus.st_sslstatus = localsslstatus;
3293  }
3294 #endif
3295  }
3296 
3297  pgstat_save_changecount_after(beentry, after_changecount);
3298  if (before_changecount == after_changecount &&
3299  (before_changecount & 1) == 0)
3300  break;
3301 
3302  /* Make sure we can break out of loop if stuck... */
3304  }
3305 
3306  beentry++;
3307  /* Only valid entries get included into the local array */
3308  if (localentry->backendStatus.st_procpid > 0)
3309  {
3311  &localentry->backend_xid,
3312  &localentry->backend_xmin);
3313 
3314  localentry++;
3315  localappname += NAMEDATALEN;
3316  localactivity += pgstat_track_activity_query_size;
3317 #ifdef USE_SSL
3318  localsslstatus++;
3319 #endif
3320  localNumBackends++;
3321  }
3322  }
3323 
3324  /* Set the pointer only after completion of a valid table */
3325  localBackendStatusTable = localtable;
3326 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2589
static bool pgStatRunningInCollector
Definition: pgstat.c:155
TransactionId backend_xmin
Definition: pgstat.h:1107
#define NumBackendStatSlots
Definition: pgstat.c:118
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1101
char * st_activity_raw
Definition: pgstat.h:1029
#define pgstat_save_changecount_before(beentry, save_changecount)
Definition: pgstat.h:1070
int pgstat_track_activity_query_size
Definition: pgstat.c:128
char * st_appname
Definition: pgstat.h:1020
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5588
PgBackendStatus backendStatus
Definition: pgstat.h:1095
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:404
#define Assert(condition)
Definition: c.h:688
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:247
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:1076
int st_procpid
Definition: pgstat.h:995
static int localNumBackends
Definition: pgstat.c:250
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:693
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:243
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:1014

◆ pgstat_read_db_statsfile()

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

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

5175 {
5176  PgStat_StatTabEntry *tabentry;
5177  PgStat_StatTabEntry tabbuf;
5178  PgStat_StatFuncEntry funcbuf;
5179  PgStat_StatFuncEntry *funcentry;
5180  FILE *fpin;
5181  int32 format_id;
5182  bool found;
5183  char statfile[MAXPGPATH];
5184 
5185  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5186 
5187  /*
5188  * Try to open the stats file. If it doesn't exist, the backends simply
5189  * return zero for anything and the collector simply starts from scratch
5190  * with empty counters.
5191  *
5192  * ENOENT is a possibility if the stats collector is not running or has
5193  * not yet written the stats file the first time. Any other failure
5194  * condition is suspicious.
5195  */
5196  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5197  {
5198  if (errno != ENOENT)
5201  errmsg("could not open statistics file \"%s\": %m",
5202  statfile)));
5203  return;
5204  }
5205 
5206  /*
5207  * Verify it's of the expected format.
5208  */
5209  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5210  format_id != PGSTAT_FILE_FORMAT_ID)
5211  {
5212  ereport(pgStatRunningInCollector ? LOG : WARNING,
5213  (errmsg("corrupted statistics file \"%s\"", statfile)));
5214  goto done;
5215  }
5216 
5217  /*
5218  * We found an existing collector stats file. Read it and put all the
5219  * hashtable entries into place.
5220  */
5221  for (;;)
5222  {
5223  switch (fgetc(fpin))
5224  {
5225  /*
5226  * 'T' A PgStat_StatTabEntry follows.
5227  */
5228  case 'T':
5229  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5230  fpin) != sizeof(PgStat_StatTabEntry))
5231  {
5232  ereport(pgStatRunningInCollector ? LOG : WARNING,
5233  (errmsg("corrupted statistics file \"%s\"",
5234  statfile)));
5235  goto done;
5236  }
5237 
5238  /*
5239  * Skip if table data not wanted.
5240  */
5241  if (tabhash == NULL)
5242  break;
5243 
5244  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5245  (void *) &tabbuf.tableid,
5246  HASH_ENTER, &found);
5247 
5248  if (found)
5249  {
5250  ereport(pgStatRunningInCollector ? LOG : WARNING,
5251  (errmsg("corrupted statistics file \"%s\"",
5252  statfile)));
5253  goto done;
5254  }
5255 
5256  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5257  break;
5258 
5259  /*
5260  * 'F' A PgStat_StatFuncEntry follows.
5261  */
5262  case 'F':
5263  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5264  fpin) != sizeof(PgStat_StatFuncEntry))
5265  {
5266  ereport(pgStatRunningInCollector ? LOG : WARNING,
5267  (errmsg("corrupted statistics file \"%s\"",
5268  statfile)));
5269  goto done;
5270  }
5271 
5272  /*
5273  * Skip if function data not wanted.
5274  */
5275  if (funchash == NULL)
5276  break;
5277 
5278  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5279  (void *) &funcbuf.functionid,
5280  HASH_ENTER, &found);
5281 
5282  if (found)
5283  {
5284  ereport(pgStatRunningInCollector ? LOG : WARNING,
5285  (errmsg("corrupted statistics file \"%s\"",
5286  statfile)));
5287  goto done;
5288  }
5289 
5290  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5291  break;
5292 
5293  /*
5294  * 'E' The EOF marker of a complete stats file.
5295  */
5296  case 'E':
5297  goto done;
5298 
5299  default:
5300  ereport(pgStatRunningInCollector ? LOG : WARNING,
5301  (errmsg("corrupted statistics file \"%s\"",
5302  statfile)));
5303  goto done;
5304  }
5305  }
5306 
5307 done:
5308  FreeFile(fpin);
5309 
5310  if (permanent)
5311  {
5312  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5313  unlink(statfile);
5314  }
5315 }
static bool pgStatRunningInCollector
Definition: pgstat.c:155
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
#define LOG
Definition: elog.h:26
#define PG_BINARY_R
Definition: c.h:1071
signed int int32
Definition: c.h:302
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2353
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int FreeFile(FILE *file)
Definition: fd.c:2545
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:569
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
static void get_dbstat_filename(bool permanent, bool tempname, Oid databaseid, char *filename, int len)
Definition: pgstat.c:4792

◆ pgstat_read_db_statsfile_timestamp()

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

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

5337 {
5338  PgStat_StatDBEntry dbentry;
5339  PgStat_GlobalStats myGlobalStats;
5340  PgStat_ArchiverStats myArchiverStats;
5341  FILE *fpin;
5342  int32 format_id;
5343  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5344 
5345  /*
5346  * Try to open the stats file. As above, anything but ENOENT is worthy of
5347  * complaining about.
5348  */
5349  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5350  {
5351  if (errno != ENOENT)
5354  errmsg("could not open statistics file \"%s\": %m",
5355  statfile)));
5356  return false;
5357  }
5358 
5359  /*
5360  * Verify it's of the expected format.
5361  */
5362  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5363  format_id != PGSTAT_FILE_FORMAT_ID)
5364  {
5365  ereport(pgStatRunningInCollector ? LOG : WARNING,
5366  (errmsg("corrupted statistics file \"%s\"", statfile)));
5367  FreeFile(fpin);
5368  return false;
5369  }
5370 
5371  /*
5372  * Read global stats struct
5373  */
5374  if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5375  fpin) != sizeof(myGlobalStats))
5376  {
5377  ereport(pgStatRunningInCollector ? LOG : WARNING,
5378  (errmsg("corrupted statistics file \"%s\"", statfile)));
5379  FreeFile(fpin);
5380  return false;
5381  }
5382 
5383  /*
5384  * Read archiver stats struct
5385  */
5386  if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
5387  fpin) != sizeof(myArchiverStats))
5388  {
5389  ereport(pgStatRunningInCollector ? LOG : WARNING,
5390  (errmsg("corrupted statistics file \"%s\"", statfile)));
5391  FreeFile(fpin);
5392  return false;
5393  }
5394 
5395  /* By default, we're going to return the timestamp of the global file. */
5396  *ts = myGlobalStats.stats_timestamp;
5397 
5398  /*
5399  * We found an existing collector stats file. Read it and look for a
5400  * record for the requested database. If found, use its timestamp.
5401  */
5402  for (;;)
5403  {
5404  switch (fgetc(fpin))
5405  {
5406  /*
5407  * 'D' A PgStat_StatDBEntry struct describing a database
5408  * follows.
5409  */
5410  case 'D':
5411  if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
5412  fpin) != offsetof(PgStat_StatDBEntry, tables))
5413  {
5414  ereport(pgStatRunningInCollector ? LOG : WARNING,
5415  (errmsg("corrupted statistics file \"%s\"",
5416  statfile)));
5417  goto done;
5418  }
5419 
5420  /*
5421  * If this is the DB we're looking for, save its timestamp and
5422  * we're done.
5423  */
5424  if (dbentry.databaseid == databaseid)
5425  {
5426  *ts = dbentry.stats_timestamp;
5427  goto done;
5428  }
5429 
5430  break;
5431 
5432  case 'E':
5433  goto done;
5434 
5435  default:
5436  ereport(pgStatRunningInCollector ? LOG : WARNING,
5437  (errmsg("corrupted statistics file \"%s\"",
5438  statfile)));
5439  goto done;
5440  }
5441  }
5442 
5443 done:
5444  FreeFile(fpin);
5445  return true;
5446 }
TimestampTz stats_timestamp
Definition: pgstat.h:600
static bool pgStatRunningInCollector
Definition: pgstat.c:155
TimestampTz stats_timestamp
Definition: pgstat.h:683
#define PGSTAT_STAT_PERMANENT_FILENAME
Definition: pgstat.h:30
#define LOG
Definition: elog.h:26
#define PG_BINARY_R
Definition: c.h:1071
signed int int32
Definition: c.h:302
char * pgstat_stat_filename
Definition: pgstat.c:135
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2353
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int FreeFile(FILE *file)
Definition: fd.c:2545
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:569
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define offsetof(type, field)
Definition: c.h:611

◆ pgstat_read_statsfiles()

static HTAB * pgstat_read_statsfiles ( Oid  onlydb,
bool  permanent,
bool  deep 
)
static

Definition at line 4941 of file pgstat.c.

References AllocateFile(), PgStat_StatDBEntry::databaseid, DEBUG2, elog, HASHCTL::entrysize, ereport, errcode_for_file_access(), errmsg(), FreeFile(), PgStat_StatDBEntry::functions, GetCurrentTimestamp(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, InvalidOid, HASHCTL::keysize, LOG, offsetof, PG_BINARY_R, PGSTAT_DB_HASH_SIZE, PGSTAT_FILE_FORMAT_ID, PGSTAT_FUNCTION_HASH_SIZE, pgstat_read_db_statsfile(), pgstat_setup_memcxt(), pgstat_stat_filename, PGSTAT_STAT_PERMANENT_FILENAME, PGSTAT_TAB_HASH_SIZE, pgStatLocalContext, pgStatRunningInCollector, PgStat_ArchiverStats::stat_reset_timestamp, PgStat_GlobalStats::stat_reset_timestamp, PgStat_StatDBEntry::stats_timestamp, PgStat_GlobalStats::stats_timestamp, PgStat_StatDBEntry::tables, and WARNING.

Referenced by backend_read_statsfile(), and PgstatCollectorMain().

4942 {
4943  PgStat_StatDBEntry *dbentry;
4944  PgStat_StatDBEntry dbbuf;
4945  HASHCTL hash_ctl;
4946  HTAB *dbhash;
4947  FILE *fpin;
4948  int32 format_id;
4949  bool found;
4950  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4951 
4952  /*
4953  * The tables will live in pgStatLocalContext.
4954  */
4956 
4957  /*
4958  * Create the DB hashtable
4959  */
4960  memset(&hash_ctl, 0, sizeof(hash_ctl));
4961  hash_ctl.keysize = sizeof(Oid);
4962  hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
4963  hash_ctl.hcxt = pgStatLocalContext;
4964  dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
4966 
4967  /*
4968  * Clear out global and archiver statistics so they start from zero in
4969  * case we can't load an existing statsfile.
4970  */
4971  memset(&globalStats, 0, sizeof(globalStats));
4972  memset(&archiverStats, 0, sizeof(archiverStats));
4973 
4974  /*
4975  * Set the current timestamp (will be kept only in case we can't load an
4976  * existing statsfile).
4977  */
4980 
4981  /*
4982  * Try to open the stats file. If it doesn't exist, the backends simply
4983  * return zero for anything and the collector simply starts from scratch
4984  * with empty counters.
4985  *
4986  * ENOENT is a possibility if the stats collector is not running or has
4987  * not yet written the stats file the first time. Any other failure
4988  * condition is suspicious.
4989  */
4990  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4991  {
4992  if (errno != ENOENT)
4995  errmsg("could not open statistics file \"%s\": %m",
4996  statfile)));
4997  return dbhash;
4998  }
4999 
5000  /*
5001  * Verify it's of the expected format.
5002  */
5003  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||