PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_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)
 
static void make_sure_stat_tab_initialized ()
 
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)
 

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

#define NumBackendStatSlots   (MaxBackends + NUM_AUXPROCTYPES)
#define PGSTAT_DB_HASH_SIZE   16

Definition at line 101 of file pgstat.c.

Referenced by pgstat_read_statsfiles().

#define PGSTAT_FUNCTION_HASH_SIZE   512
#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.

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

Definition at line 94 of file pgstat.c.

Referenced by backend_read_statsfile().

#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.

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

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

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

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

#define PGSTAT_TAB_HASH_SIZE   512

Definition at line 102 of file pgstat.c.

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

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

Definition at line 165 of file pgstat.c.

Referenced by get_tabstat_entry(), and make_sure_stat_tab_initialized().

#define TESTBYTEVAL   ((char) 199)

Referenced by pgstat_init().

Typedef Documentation

Function Documentation

static void add_tabstat_xact_level ( PgStat_TableStatus pgstat_info,
int  nest_level 
)
static

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

1845 {
1846  PgStat_SubXactStatus *xact_state;
1848 
1849  /*
1850  * If this is the first rel to be modified at the current nest level, we
1851  * first have to push a transaction stack entry.
1852  */
1853  xact_state = get_tabstat_stack_level(nest_level);
1854 
1855  /* Now make a per-table stack entry */
1856  trans = (PgStat_TableXactStatus *)
1858  sizeof(PgStat_TableXactStatus));
1859  trans->nest_level = nest_level;
1860  trans->upper = pgstat_info->trans;
1861  trans->parent = pgstat_info;
1862  trans->next = xact_state->first;
1863  xact_state->first = trans;
1864  pgstat_info->trans = trans;
1865 }
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:1822
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:742
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:382
PgStat_TableXactStatus * first
Definition: pgstat.c:213
PgStat_TableStatus * parent
Definition: pgstat.h:177
void allow_immediate_pgstat_restart ( void  )

Definition at line 758 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

759 {
761 }
static time_t last_pgstat_start_time
Definition: pgstat.c:150
void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

Definition at line 2100 of file pgstat.c.

References Assert, PgStat_SubXactStatus::first, get_tabstat_stack_level(), PgStat_TableXactStatus::nest_level, PgStat_SubXactStatus::nest_level, PgStat_TableXactStatus::next, NULL, 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().

2101 {
2102  PgStat_SubXactStatus *xact_state;
2103 
2104  /*
2105  * Transfer transactional insert/update counts into the next higher
2106  * subtransaction state.
2107  */
2108  xact_state = pgStatXactStack;
2109  if (xact_state != NULL &&
2110  xact_state->nest_level >= nestDepth)
2111  {
2113  PgStat_TableXactStatus *next_trans;
2114 
2115  /* delink xact_state from stack immediately to simplify reuse case */
2116  pgStatXactStack = xact_state->prev;
2117 
2118  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2119  {
2120  PgStat_TableStatus *tabstat;
2121 
2122  next_trans = trans->next;
2123  Assert(trans->nest_level == nestDepth);
2124  tabstat = trans->parent;
2125  Assert(tabstat->trans == trans);
2126  if (isCommit)
2127  {
2128  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2129  {
2130  if (trans->truncated)
2131  {
2132  /* propagate the truncate status one level up */
2134  /* replace upper xact stats with ours */
2135  trans->upper->tuples_inserted = trans->tuples_inserted;
2136  trans->upper->tuples_updated = trans->tuples_updated;
2137  trans->upper->tuples_deleted = trans->tuples_deleted;
2138  }
2139  else
2140  {
2141  trans->upper->tuples_inserted += trans->tuples_inserted;
2142  trans->upper->tuples_updated += trans->tuples_updated;
2143  trans->upper->tuples_deleted += trans->tuples_deleted;
2144  }
2145  tabstat->trans = trans->upper;
2146  pfree(trans);
2147  }
2148  else
2149  {
2150  /*
2151  * When there isn't an immediate parent state, we can just
2152  * reuse the record instead of going through a
2153  * palloc/pfree pushup (this works since it's all in
2154  * TopTransactionContext anyway). We have to re-link it
2155  * into the parent level, though, and that might mean
2156  * pushing a new entry into the pgStatXactStack.
2157  */
2158  PgStat_SubXactStatus *upper_xact_state;
2159 
2160  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2161  trans->next = upper_xact_state->first;
2162  upper_xact_state->first = trans;
2163  trans->nest_level = nestDepth - 1;
2164  }
2165  }
2166  else
2167  {
2168  /*
2169  * On abort, update top-level tabstat counts, then forget the
2170  * subtransaction
2171  */
2172 
2173  /* first restore values obliterated by truncate */
2175  /* count attempted actions regardless of commit/abort */
2176  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2177  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2178  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2179  /* inserted tuples are dead, deleted tuples are unaffected */
2180  tabstat->t_counts.t_delta_dead_tuples +=
2181  trans->tuples_inserted + trans->tuples_updated;
2182  tabstat->trans = trans->upper;
2183  pfree(trans);
2184  }
2185  }
2186  pfree(xact_state);
2187  }
2188 }
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:1822
void pfree(void *pointer)
Definition: mcxt.c:950
PgStat_Counter t_tuples_updated
Definition: pgstat.h:105
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1958
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:212
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:216
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:382
PgStat_TableXactStatus * first
Definition: pgstat.c:213
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1943
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177
void AtEOXact_PgStat ( bool  isCommit)

Definition at line 2017 of file pgstat.c.

References Assert, PgStat_SubXactStatus::first, PgStat_TableXactStatus::nest_level, PgStat_SubXactStatus::nest_level, PgStat_TableXactStatus::next, NULL, 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().

2018 {
2019  PgStat_SubXactStatus *xact_state;
2020 
2021  /*
2022  * Count transaction commit or abort. (We use counters, not just bools,
2023  * in case the reporting message isn't sent right away.)
2024  */
2025  if (isCommit)
2026  pgStatXactCommit++;
2027  else
2029 
2030  /*
2031  * Transfer transactional insert/update counts into the base tabstat
2032  * entries. We don't bother to free any of the transactional state, since
2033  * it's all in TopTransactionContext and will go away anyway.
2034  */
2035  xact_state = pgStatXactStack;
2036  if (xact_state != NULL)
2037  {
2039 
2040  Assert(xact_state->nest_level == 1);
2041  Assert(xact_state->prev == NULL);
2042  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2043  {
2044  PgStat_TableStatus *tabstat;
2045 
2046  Assert(trans->nest_level == 1);
2047  Assert(trans->upper == NULL);
2048  tabstat = trans->parent;
2049  Assert(tabstat->trans == trans);
2050  /* restore pre-truncate stats (if any) in case of aborted xact */
2051  if (!isCommit)
2053  /* count attempted actions regardless of commit/abort */
2054  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2055  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2056  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2057  if (isCommit)
2058  {
2059  tabstat->t_counts.t_truncated = trans->truncated;
2060  if (trans->truncated)
2061  {
2062  /* forget live/dead stats seen by backend thus far */
2063  tabstat->t_counts.t_delta_live_tuples = 0;
2064  tabstat->t_counts.t_delta_dead_tuples = 0;
2065  }
2066  /* insert adds a live tuple, delete removes one */
2067  tabstat->t_counts.t_delta_live_tuples +=
2068  trans->tuples_inserted - trans->tuples_deleted;
2069  /* update and delete each create a dead tuple */
2070  tabstat->t_counts.t_delta_dead_tuples +=
2071  trans->tuples_updated + trans->tuples_deleted;
2072  /* insert, update, delete each count as one change event */
2073  tabstat->t_counts.t_changed_tuples +=
2074  trans->tuples_inserted + trans->tuples_updated +
2075  trans->tuples_deleted;
2076  }
2077  else
2078  {
2079  /* inserted tuples are dead, deleted tuples are unaffected */
2080  tabstat->t_counts.t_delta_dead_tuples +=
2081  trans->tuples_inserted + trans->tuples_updated;
2082  /* an aborted xact generates no changed_tuple events */
2083  }
2084  tabstat->trans = NULL;
2085  }
2086  }
2088 
2089  /* Make sure any stats snapshot is thrown away */
2091 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:110
PgStat_Counter tuples_updated
Definition: pgstat.h:168
static int pgStatXactCommit
Definition: pgstat.c:218
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:1958
static int pgStatXactRollback
Definition: pgstat.c:219
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:212
PgStat_Counter t_changed_tuples
Definition: pgstat.h:112
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5482
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:216
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:382
PgStat_TableXactStatus * first
Definition: pgstat.c:213
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177
void AtPrepare_PgStat ( void  )

Definition at line 2199 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, NULL, 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().

2200 {
2201  PgStat_SubXactStatus *xact_state;
2202 
2203  xact_state = pgStatXactStack;
2204  if (xact_state != NULL)
2205  {
2207 
2208  Assert(xact_state->nest_level == 1);
2209  Assert(xact_state->prev == NULL);
2210  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2211  {
2212  PgStat_TableStatus *tabstat;
2213  TwoPhasePgStatRecord record;
2214 
2215  Assert(trans->nest_level == 1);
2216  Assert(trans->upper == NULL);
2217  tabstat = trans->parent;
2218  Assert(tabstat->trans == trans);
2219 
2220  record.tuples_inserted = trans->tuples_inserted;
2221  record.tuples_updated = trans->tuples_updated;
2222  record.tuples_deleted = trans->tuples_deleted;
2223  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2224  record.updated_pre_trunc = trans->updated_pre_trunc;
2225  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2226  record.t_id = tabstat->t_id;
2227  record.t_shared = tabstat->t_shared;
2228  record.t_truncated = trans->truncated;
2229 
2231  &record, sizeof(TwoPhasePgStatRecord));
2232  }
2233  }
2234 }
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:231
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:230
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:229
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter tuples_updated
Definition: pgstat.c:227
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:212
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:171
PgStat_Counter tuples_inserted
Definition: pgstat.c:226
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:216
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
PgStat_Counter tuples_deleted
Definition: pgstat.c:228
#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:382
PgStat_TableXactStatus * first
Definition: pgstat.c:213
PgStat_TableStatus * parent
Definition: pgstat.h:177
static void backend_read_statsfile ( void  )
static

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

5329 {
5330  TimestampTz min_ts = 0;
5331  TimestampTz ref_ts = 0;
5332  Oid inquiry_db;
5333  int count;
5334 
5335  /* already read it? */
5336  if (pgStatDBHash)
5337  return;
5339 
5340  /*
5341  * In a normal backend, we check staleness of the data for our own DB, and
5342  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5343  * check staleness of the shared-catalog data, and send InvalidOid in
5344  * inquiry messages so as not to force writing unnecessary data.
5345  */
5347  inquiry_db = InvalidOid;
5348  else
5349  inquiry_db = MyDatabaseId;
5350 
5351  /*
5352  * Loop until fresh enough stats file is available or we ran out of time.
5353  * The stats inquiry message is sent repeatedly in case collector drops
5354  * it; but not every single time, as that just swamps the collector.
5355  */
5356  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5357  {
5358  bool ok;
5359  TimestampTz file_ts = 0;
5360  TimestampTz cur_ts;
5361 
5363 
5364  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5365 
5366  cur_ts = GetCurrentTimestamp();
5367  /* Calculate min acceptable timestamp, if we didn't already */
5368  if (count == 0 || cur_ts < ref_ts)
5369  {
5370  /*
5371  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5372  * msec before now. This indirectly ensures that the collector
5373  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5374  * an autovacuum worker, however, we want a lower delay to avoid
5375  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5376  * number of workers is low, this shouldn't be a problem).
5377  *
5378  * We don't recompute min_ts after sleeping, except in the
5379  * unlikely case that cur_ts went backwards. So we might end up
5380  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5381  * practice that shouldn't happen, though, as long as the sleep
5382  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5383  * tell the collector that our cutoff time is less than what we'd
5384  * actually accept.
5385  */
5386  ref_ts = cur_ts;
5388  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5390  else
5391  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5393  }
5394 
5395  /*
5396  * If the file timestamp is actually newer than cur_ts, we must have
5397  * had a clock glitch (system time went backwards) or there is clock
5398  * skew between our processor and the stats collector's processor.
5399  * Accept the file, but send an inquiry message anyway to make
5400  * pgstat_recv_inquiry do a sanity check on the collector's time.
5401  */
5402  if (ok && file_ts > cur_ts)
5403  {
5404  /*
5405  * A small amount of clock skew between processors isn't terribly
5406  * surprising, but a large difference is worth logging. We
5407  * arbitrarily define "large" as 1000 msec.
5408  */
5409  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5410  {
5411  char *filetime;
5412  char *mytime;
5413 
5414  /* Copy because timestamptz_to_str returns a static buffer */
5415  filetime = pstrdup(timestamptz_to_str(file_ts));
5416  mytime = pstrdup(timestamptz_to_str(cur_ts));
5417  elog(LOG, "stats collector's time %s is later than backend local time %s",
5418  filetime, mytime);
5419  pfree(filetime);
5420  pfree(mytime);
5421  }
5422 
5423  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5424  break;
5425  }
5426 
5427  /* Normal acceptance case: file is not older than cutoff time */
5428  if (ok && file_ts >= min_ts)
5429  break;
5430 
5431  /* Not there or too old, so kick the collector and wait a bit */
5432  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5433  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5434 
5435  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5436  }
5437 
5438  if (count >= PGSTAT_POLL_LOOP_COUNT)
5439  ereport(LOG,
5440  (errmsg("using stale statistics instead of current ones "
5441  "because stats collector is not responding")));
5442 
5443  /*
5444  * Autovacuum launcher wants stats about all databases, but a shallow read
5445  * is sufficient. Regular backends want a deep read for just the tables
5446  * they can see (MyDatabaseId + shared catalogs).
5447  */
5450  else
5452 }
#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:1077
static bool pgStatRunningInCollector
Definition: pgstat.c:152
#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:950
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1529
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:77
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3360
#define ereport(elevel, rest)
Definition: elog.h:122
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:4836
Oid MyDatabaseId
Definition: globals.c:76
#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:5209
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3354
#define Assert(condition)
Definition: c.h:675
static HTAB * pgStatDBHash
Definition: pgstat.c:241
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1710
Size BackendStatusShmemSize ( void  )

Definition at line 2568 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2569 {
2570  Size size;
2571 
2572  /* BackendStatusArray: */
2573  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2574  /* BackendAppnameBuffer: */
2575  size = add_size(size,
2577  /* BackendClientHostnameBuffer: */
2578  size = add_size(size,
2580  /* BackendActivityBuffer: */
2581  size = add_size(size,
2583 #ifdef USE_SSL
2584  /* BackendSslStatusBuffer: */
2585  size = add_size(size,
2587 #endif
2588  return size;
2589 }
#define NumBackendStatSlots
Definition: pgstat.c:115
#define NAMEDATALEN
int pgstat_track_activity_query_size
Definition: pgstat.c:125
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:356
void CreateSharedBackendStatus ( void  )

Definition at line 2596 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2597 {
2598  Size size;
2599  bool found;
2600  int i;
2601  char *buffer;
2602 
2603  /* Create or attach to the shared array */
2604  size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2606  ShmemInitStruct("Backend Status Array", size, &found);
2607 
2608  if (!found)
2609  {
2610  /*
2611  * We're the first - initialize.
2612  */
2613  MemSet(BackendStatusArray, 0, size);
2614  }
2615 
2616  /* Create or attach to the shared appname buffer */
2617  size = mul_size(NAMEDATALEN, MaxBackends);
2618  BackendAppnameBuffer = (char *)
2619  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2620 
2621  if (!found)
2622  {
2623  MemSet(BackendAppnameBuffer, 0, size);
2624 
2625  /* Initialize st_appname pointers. */
2626  buffer = BackendAppnameBuffer;
2627  for (i = 0; i < NumBackendStatSlots; i++)
2628  {
2630  buffer += NAMEDATALEN;
2631  }
2632  }
2633 
2634  /* Create or attach to the shared client hostname buffer */
2635  size = mul_size(NAMEDATALEN, MaxBackends);
2636  BackendClientHostnameBuffer = (char *)
2637  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2638 
2639  if (!found)
2640  {
2642 
2643  /* Initialize st_clienthostname pointers. */
2644  buffer = BackendClientHostnameBuffer;
2645  for (i = 0; i < NumBackendStatSlots; i++)
2646  {
2648  buffer += NAMEDATALEN;
2649  }
2650  }
2651 
2652  /* Create or attach to the shared activity buffer */
2655  BackendActivityBuffer = (char *)
2656  ShmemInitStruct("Backend Activity Buffer",
2658  &found);
2659 
2660  if (!found)
2661  {
2662  MemSet(BackendActivityBuffer, 0, size);
2663 
2664  /* Initialize st_activity pointers. */
2665  buffer = BackendActivityBuffer;
2666  for (i = 0; i < NumBackendStatSlots; i++)
2667  {
2670  }
2671  }
2672 
2673 #ifdef USE_SSL
2674  /* Create or attach to the shared SSL status buffer */
2676  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2677  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2678 
2679  if (!found)
2680  {
2681  PgBackendSSLStatus *ptr;
2682 
2683  MemSet(BackendSslStatusBuffer, 0, size);
2684 
2685  /* Initialize st_sslstatus pointers. */
2686  ptr = BackendSslStatusBuffer;
2687  for (i = 0; i < NumBackendStatSlots; i++)
2688  {
2690  ptr++;
2691  }
2692  }
2693 #endif
2694 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2553
static char * BackendActivityBuffer
Definition: pgstat.c:2557
static Size BackendActivityBufferSize
Definition: pgstat.c:2558
#define MemSet(start, val, len)
Definition: c.h:857
#define NumBackendStatSlots
Definition: pgstat.c:115
char * st_clienthostname
Definition: pgstat.h:990
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2555
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
int MaxBackends
Definition: globals.c:126
int pgstat_track_activity_query_size
Definition: pgstat.c:125
char * st_appname
Definition: pgstat.h:1000
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
char * st_activity
Definition: pgstat.h:1003
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
size_t Size
Definition: c.h:356
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:994
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2556
PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

Definition at line 1598 of file pgstat.c.

References HASH_FIND, hash_search(), and NULL.

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

1599 {
1600  if (pgStatFunctions == NULL)
1601  return NULL;
1602 
1604  (void *) &func_id,
1605  HASH_FIND, NULL);
1606 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * pgStatFunctions
Definition: pgstat.c:194
#define NULL
Definition: c.h:229
PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

Definition at line 1801 of file pgstat.c.

References HASH_FIND, hash_search(), NULL, 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().

1802 {
1803  TabStatHashEntry* hash_entry;
1804 
1805  /*
1806  * There are no entries at all.
1807  */
1808  if(!pgStatTabHash)
1809  return NULL;
1810 
1811  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1812  if(!hash_entry)
1813  return NULL;
1814 
1815  return hash_entry->tsa_entry;
1816 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * pgStatTabHash
Definition: pgstat.c:188
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:182
#define NULL
Definition: c.h:229
static void get_dbstat_filename ( bool  permanent,
bool  tempname,
Oid  databaseid,
char *  filename,
int  len 
)
static

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

4689 {
4690  int printed;
4691 
4692  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4693  printed = snprintf(filename, len, "%s/db_%u.%s",
4694  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4696  databaseid,
4697  tempname ? "tmp" : "stat");
4698  if (printed > len)
4699  elog(ERROR, "overlength pgstat path");
4700 }
#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:131
static char * filename
Definition: pg_dumpall.c:87
#define elog
Definition: elog.h:219
static PgStat_TableStatus * get_tabstat_entry ( Oid  rel_id,
bool  isshared 
)
static

Definition at line 1749 of file pgstat.c.

References HASH_ENTER, hash_search(), make_sure_stat_tab_initialized(), MemoryContextAllocZero(), NULL, 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 
1757 
1758  /*
1759  * Find an entry or create a new one.
1760  */
1761  hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1762  if(found)
1763  return hash_entry->tsa_entry;
1764 
1765  /*
1766  * `hash_entry` was just created and now we have to fill it.
1767  * First make sure there is a free space in a last element of pgStatTabList.
1768  */
1769  tsa = pgStatTabList;
1770  while(tsa->tsa_used == TABSTAT_QUANTUM)
1771  {
1772  if(tsa->tsa_next == NULL)
1773  {
1775  sizeof(TabStatusArray));
1776  }
1777 
1778  tsa = tsa->tsa_next;
1779  }
1780 
1781  /*
1782  * Add an entry.
1783  */
1784  entry = &tsa->tsa_entries[tsa->tsa_used++];
1785  entry->t_id = rel_id;
1786  entry->t_shared = isshared;
1787 
1788  /*
1789  * Add a corresponding entry to pgStatTabHash.
1790  */
1791  hash_entry->tsa_entry = entry;
1792  return entry;
1793 }
int tsa_used
Definition: pgstat.c:170
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
struct TabStatusArray * tsa_next
Definition: pgstat.c:169
static HTAB * pgStatTabHash
Definition: pgstat.c:188
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:171
static void make_sure_stat_tab_initialized()
Definition: pgstat.c:1714
MemoryContext TopMemoryContext
Definition: mcxt.c:43
PgStat_TableStatus * tsa_entry
Definition: pgstat.c:182
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:742
static TabStatusArray * pgStatTabList
Definition: pgstat.c:174
#define NULL
Definition: c.h:229
#define TABSTAT_QUANTUM
Definition: pgstat.c:165
static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

Definition at line 1822 of file pgstat.c.

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

Referenced by add_tabstat_xact_level(), and AtEOSubXact_PgStat().

1823 {
1824  PgStat_SubXactStatus *xact_state;
1825 
1826  xact_state = pgStatXactStack;
1827  if (xact_state == NULL || xact_state->nest_level != nest_level)
1828  {
1829  xact_state = (PgStat_SubXactStatus *)
1831  sizeof(PgStat_SubXactStatus));
1832  xact_state->nest_level = nest_level;
1833  xact_state->prev = pgStatXactStack;
1834  xact_state->first = NULL;
1835  pgStatXactStack = xact_state;
1836  }
1837  return xact_state;
1838 }
MemoryContext TopTransactionContext
Definition: mcxt.c:48
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:212
#define NULL
Definition: c.h:229
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:216
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
PgStat_TableXactStatus * first
Definition: pgstat.c:213
static void make_sure_stat_tab_initialized ( )
static

Definition at line 1714 of file pgstat.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), HASHCTL::entrysize, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASHCTL::hcxt, HASHCTL::keysize, MemoryContextAllocZero(), TABSTAT_QUANTUM, and TopMemoryContext.

Referenced by get_tabstat_entry().

1715 {
1716  HASHCTL ctl;
1717  MemoryContext new_ctx;
1718 
1719  if(!pgStatTabList)
1720  {
1721  /* This is first time procedure is called */
1723  sizeof(TabStatusArray));
1724  }
1725 
1726  if(pgStatTabHash)
1727  return;
1728 
1729  /* Hash table was freed or never existed. */
1730 
1731  new_ctx = AllocSetContextCreate(
1733  "PGStatLookupHashTableContext",
1735 
1736  memset(&ctl, 0, sizeof(ctl));
1737  ctl.keysize = sizeof(Oid);
1738  ctl.entrysize = sizeof(TabStatHashEntry);
1739  ctl.hcxt = new_ctx;
1740 
1741  pgStatTabHash = hash_create("pgstat t_id to tsa_entry lookup hash table",
1743 }
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
Size entrysize
Definition: hsearch.h:73
unsigned int Oid
Definition: postgres_ext.h:31
struct TabStatHashEntry TabStatHashEntry
static HTAB * pgStatTabHash
Definition: pgstat.c:188
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define HASH_BLOBS
Definition: hsearch.h:88
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:742
static TabStatusArray * pgStatTabList
Definition: pgstat.c:174
#define TABSTAT_QUANTUM
Definition: pgstat.c:165
static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

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

2921 {
2922  volatile PgBackendStatus *beentry = MyBEEntry;
2923 
2924  /*
2925  * If we got as far as discovering our own database ID, we can report what
2926  * we did to the collector. Otherwise, we'd be sending an invalid
2927  * database ID, so forget it. (This means that accesses to pg_database
2928  * during failed backend starts might never get counted.)
2929  */
2930  if (OidIsValid(MyDatabaseId))
2931  pgstat_report_stat(true);
2932 
2933  /*
2934  * Clear my status entry, following the protocol of bumping st_changecount
2935  * before and after. We use a volatile pointer here to ensure the
2936  * compiler doesn't try to get cute.
2937  */
2939 
2940  beentry->st_procpid = 0; /* mark invalid */
2941 
2943 }
#define OidIsValid(objectId)
Definition: c.h:538
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
Oid MyDatabaseId
Definition: globals.c:76
int st_procpid
Definition: pgstat.h:975
void pgstat_report_stat(bool force)
Definition: pgstat.c:780
void pgstat_bestart ( void  )

Definition at line 2749 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, NULL, 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, 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().

2750 {
2751  TimestampTz proc_start_timestamp;
2752  SockAddr clientaddr;
2753  volatile PgBackendStatus *beentry;
2754 
2755  /*
2756  * To minimize the time spent modifying the PgBackendStatus entry, fetch
2757  * all the needed data first.
2758  *
2759  * If we have a MyProcPort, use its session start time (for consistency,
2760  * and to save a kernel call).
2761  */
2762  if (MyProcPort)
2763  proc_start_timestamp = MyProcPort->SessionStartTime;
2764  else
2765  proc_start_timestamp = GetCurrentTimestamp();
2766 
2767  /*
2768  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2769  * If so, use all-zeroes client address, which is dealt with specially in
2770  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2771  */
2772  if (MyProcPort)
2773  memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2774  else
2775  MemSet(&clientaddr, 0, sizeof(clientaddr));
2776 
2777  /*
2778  * Initialize my status entry, following the protocol of bumping
2779  * st_changecount before and after; and make sure it's even afterwards. We
2780  * use a volatile pointer here to ensure the compiler doesn't try to get
2781  * cute.
2782  */
2783  beentry = MyBEEntry;
2784 
2785  /* pgstats state must be initialized from pgstat_initialize() */
2786  Assert(beentry != NULL);
2787 
2789  {
2791  {
2792  /* Autovacuum Launcher */
2794  }
2795  else if (IsAutoVacuumWorkerProcess())
2796  {
2797  /* Autovacuum Worker */
2798  beentry->st_backendType = B_AUTOVAC_WORKER;
2799  }
2800  else if (am_walsender)
2801  {
2802  /* Wal sender */
2803  beentry->st_backendType = B_WAL_SENDER;
2804  }
2805  else if (IsBackgroundWorker)
2806  {
2807  /* bgworker */
2808  beentry->st_backendType = B_BG_WORKER;
2809  }
2810  else
2811  {
2812  /* client-backend */
2813  beentry->st_backendType = B_BACKEND;
2814  }
2815  }
2816  else
2817  {
2818  /* Must be an auxiliary process */
2820  switch (MyAuxProcType)
2821  {
2822  case StartupProcess:
2823  beentry->st_backendType = B_STARTUP;
2824  break;
2825  case BgWriterProcess:
2826  beentry->st_backendType = B_BG_WRITER;
2827  break;
2828  case CheckpointerProcess:
2829  beentry->st_backendType = B_CHECKPOINTER;
2830  break;
2831  case WalWriterProcess:
2832  beentry->st_backendType = B_WAL_WRITER;
2833  break;
2834  case WalReceiverProcess:
2835  beentry->st_backendType = B_WAL_RECEIVER;
2836  break;
2837  default:
2838  elog(FATAL, "unrecognized process type: %d",
2839  (int) MyAuxProcType);
2840  proc_exit(1);
2841  }
2842  }
2843 
2844  do
2845  {
2847  } while ((beentry->st_changecount & 1) == 0);
2848 
2849  beentry->st_procpid = MyProcPid;
2850  beentry->st_proc_start_timestamp = proc_start_timestamp;
2851  beentry->st_activity_start_timestamp = 0;
2852  beentry->st_state_start_timestamp = 0;
2853  beentry->st_xact_start_timestamp = 0;
2854  beentry->st_databaseid = MyDatabaseId;
2855 
2856  /* We have userid for client-backends, wal-sender and bgworker processes */
2857  if (beentry->st_backendType == B_BACKEND
2858  || beentry->st_backendType == B_WAL_SENDER
2859  || beentry->st_backendType == B_BG_WORKER)
2860  beentry->st_userid = GetSessionUserId();
2861  else
2862  beentry->st_userid = InvalidOid;
2863 
2864  beentry->st_clientaddr = clientaddr;
2867  NAMEDATALEN);
2868  else
2869  beentry->st_clienthostname[0] = '\0';
2870 #ifdef USE_SSL
2871  if (MyProcPort && MyProcPort->ssl != NULL)
2872  {
2873  beentry->st_ssl = true;
2879  }
2880  else
2881  {
2882  beentry->st_ssl = false;
2883  }
2884 #else
2885  beentry->st_ssl = false;
2886 #endif
2887  beentry->st_state = STATE_UNDEFINED;
2888  beentry->st_appname[0] = '\0';
2889  beentry->st_activity[0] = '\0';
2890  /* Also make sure the last byte in each string area is always 0 */
2891  beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
2892  beentry->st_appname[NAMEDATALEN - 1] = '\0';
2893  beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2896 
2897  /*
2898  * we don't zero st_progress_param here to save cycles; nobody should
2899  * examine it until st_progress_command has been set to something other
2900  * than PROGRESS_COMMAND_INVALID
2901  */
2902 
2904 
2905  /* Update app name to current GUC setting */
2906  if (application_name)
2908 }
bool ssl_compression
Definition: pgstat.h:936
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:938
Oid st_progress_command_target
Definition: pgstat.h:1015
int MyProcPid
Definition: globals.c:38
BackendId MyBackendId
Definition: globals.c:72
struct Port * MyProcPort
Definition: globals.c:40
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:983
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:937
SockAddr st_clientaddr
Definition: pgstat.h:989
void proc_exit(int code)
Definition: ipc.c:99
#define MemSet(start, val, len)
Definition: c.h:857
ProgressCommandType st_progress_command
Definition: pgstat.h:1014
BackendState st_state
Definition: pgstat.h:997
char * st_clienthostname
Definition: pgstat.h:990
Oid GetSessionUserId(void)
Definition: miscinit.c:317
bool IsBackgroundWorker
Definition: globals.c:102
Oid st_databaseid
Definition: pgstat.h:987
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:124
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:108
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:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
int pgstat_track_activity_query_size
Definition: pgstat.c:125
TimestampTz st_state_start_timestamp
Definition: pgstat.h:984
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3360
char * st_appname
Definition: pgstat.h:1000
#define InvalidBackendId
Definition: backendid.h:23
int be_tls_get_cipher_bits(Port *port)
AuxProcType MyAuxProcType
Definition: bootstrap.c:68
Oid MyDatabaseId
Definition: globals.c:76
BackendType st_backendType
Definition: pgstat.h:978
void be_tls_get_version(Port *port, char *ptr, size_t len)
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:3127
#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:3354
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
char * st_activity
Definition: pgstat.h:1003
int st_procpid
Definition: pgstat.h:975
char * application_name
Definition: guc.c:473
void be_tls_get_cipher(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:982
int st_changecount
Definition: pgstat.h:972
#define elog
Definition: elog.h:219
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:981
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:994
char ssl_clientdn[NAMEDATALEN]
Definition: pgstat.h:939
void pgstat_clear_snapshot ( void  )

Definition at line 5482 of file pgstat.c.

References localNumBackends, MemoryContextDelete(), and NULL.

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

5483 {
5484  /* Release memory, if any was allocated */
5485  if (pgStatLocalContext)
5487 
5488  /* Reset variables */
5490  pgStatDBHash = NULL;
5492  localNumBackends = 0;
5493 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define NULL
Definition: c.h:229
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:244
static HTAB * pgStatDBHash
Definition: pgstat.c:241
static int localNumBackends
Definition: pgstat.c:247
static MemoryContext pgStatLocalContext
Definition: pgstat.c:240
static HTAB * pgstat_collect_oids ( Oid  catalogid)
static

Definition at line 1169 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, NULL, PGSTAT_TAB_HASH_SIZE, RegisterSnapshot(), and UnregisterSnapshot().

Referenced by pgstat_vacuum_stat().

1170 {
1171  HTAB *htab;
1172  HASHCTL hash_ctl;
1173  Relation rel;
1174  HeapScanDesc scan;
1175  HeapTuple tup;
1176  Snapshot snapshot;
1177 
1178  memset(&hash_ctl, 0, sizeof(hash_ctl));
1179  hash_ctl.keysize = sizeof(Oid);
1180  hash_ctl.entrysize = sizeof(Oid);
1181  hash_ctl.hcxt = CurrentMemoryContext;
1182  htab = hash_create("Temporary table of OIDs",
1184  &hash_ctl,
1186 
1187  rel = heap_open(catalogid, AccessShareLock);
1188  snapshot = RegisterSnapshot(GetLatestSnapshot());
1189  scan = heap_beginscan(rel, snapshot, 0, NULL);
1190  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1191  {
1192  Oid thisoid = HeapTupleGetOid(tup);
1193 
1195 
1196  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1197  }
1198  heap_endscan(scan);
1199  UnregisterSnapshot(snapshot);
1201 
1202  return htab;
1203 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
MemoryContext hcxt
Definition: hsearch.h:78
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:102
#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:885
unsigned int Oid
Definition: postgres_ext.h:31
Definition: dynahash.c:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:900
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
Size keysize
Definition: hsearch.h:72
#define NULL
Definition: c.h:229
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:375
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
Definition: heapam.c:1391
void pgstat_count_heap_delete ( Relation  rel)

Definition at line 1917 of file pgstat.c.

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

Referenced by heap_abort_speculative(), and heap_delete().

1918 {
1919  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1920 
1921  if (pgstat_info != NULL)
1922  {
1923  /* We have to log the effect at the proper transactional level */
1924  int nest_level = GetCurrentTransactionNestLevel();
1925 
1926  if (pgstat_info->trans == NULL ||
1927  pgstat_info->trans->nest_level != nest_level)
1928  add_tabstat_xact_level(pgstat_info, nest_level);
1929 
1930  pgstat_info->trans->tuples_deleted++;
1931  }
1932 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
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:1844
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_heap_insert ( Relation  rel,
PgStat_Counter  n 
)

Definition at line 1871 of file pgstat.c.

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

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

1872 {
1873  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1874 
1875  if (pgstat_info != NULL)
1876  {
1877  /* We have to log the effect at the proper transactional level */
1878  int nest_level = GetCurrentTransactionNestLevel();
1879 
1880  if (pgstat_info->trans == NULL ||
1881  pgstat_info->trans->nest_level != nest_level)
1882  add_tabstat_xact_level(pgstat_info, nest_level);
1883 
1884  pgstat_info->trans->tuples_inserted += n;
1885  }
1886 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
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:1844
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

Definition at line 1892 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, NULL, 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().

1893 {
1894  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1895 
1896  if (pgstat_info != NULL)
1897  {
1898  /* We have to log the effect at the proper transactional level */
1899  int nest_level = GetCurrentTransactionNestLevel();
1900 
1901  if (pgstat_info->trans == NULL ||
1902  pgstat_info->trans->nest_level != nest_level)
1903  add_tabstat_xact_level(pgstat_info, nest_level);
1904 
1905  pgstat_info->trans->tuples_updated++;
1906 
1907  /* t_tuples_hot_updated is nontransactional, so just advance it */
1908  if (hot)
1909  pgstat_info->t_counts.t_tuples_hot_updated++;
1910  }
1911 }
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:761
#define NULL
Definition: c.h:229
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:1844
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_truncate ( Relation  rel)

Definition at line 1972 of file pgstat.c.

References add_tabstat_xact_level(), GetCurrentTransactionNestLevel(), PgStat_TableXactStatus::nest_level, NULL, 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().

1973 {
1974  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1975 
1976  if (pgstat_info != NULL)
1977  {
1978  /* We have to log the effect at the proper transactional level */
1979  int nest_level = GetCurrentTransactionNestLevel();
1980 
1981  if (pgstat_info->trans == NULL ||
1982  pgstat_info->trans->nest_level != nest_level)
1983  add_tabstat_xact_level(pgstat_info, nest_level);
1984 
1985  pgstat_truncate_save_counters(pgstat_info->trans);
1986  pgstat_info->trans->tuples_inserted = 0;
1987  pgstat_info->trans->tuples_updated = 0;
1988  pgstat_info->trans->tuples_deleted = 0;
1989  }
1990 }
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:761
#define NULL
Definition: c.h:229
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:1844
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1943
static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 6186 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

6187 {
6188  /*
6189  * If any requests are outstanding at all, we should write the stats for
6190  * shared catalogs (the "database" with OID 0). This ensures that
6191  * backends will see up-to-date stats for shared catalogs, even though
6192  * they send inquiry messages mentioning only their own DB.
6193  */
6194  if (databaseid == InvalidOid && pending_write_requests != NIL)
6195  return true;
6196 
6197  /* Search to see if there's an open request to write this database. */
6198  if (list_member_oid(pending_write_requests, databaseid))
6199  return true;
6200 
6201  return false;
6202 }
#define NIL
Definition: pg_list.h:69
static List * pending_write_requests
Definition: pgstat.c:262
#define InvalidOid
Definition: postgres_ext.h:36
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
void pgstat_drop_database ( Oid  databaseid)

Definition at line 1215 of file pgstat.c.

References PgStat_MsgDropdb::m_databaseid, PgStat_MsgDropdb::m_hdr, PGINVALID_SOCKET, PGSTAT_MTYPE_DROPDB, pgstat_send(), pgstat_setheader(), and pgStatSock.

Referenced by dropdb(), and pgstat_vacuum_stat().

1216 {
1217  PgStat_MsgDropdb msg;
1218 
1220  return;
1221 
1223  msg.m_databaseid = databaseid;
1224  pgstat_send(&msg, sizeof(msg));
1225 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4054
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:146
Oid m_databaseid
Definition: pgstat.h:306
PgStat_MsgHdr m_hdr
Definition: pgstat.h:305
#define PGINVALID_SOCKET
Definition: port.h:24
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4041
void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1618 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, NULL, 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().

1619 {
1620  PgStat_FunctionCounts *fs = fcu->fs;
1621  instr_time f_total;
1622  instr_time f_others;
1623  instr_time f_self;
1624 
1625  /* stats not wanted? */
1626  if (fs == NULL)
1627  return;
1628 
1629  /* total elapsed time in this function call */
1630  INSTR_TIME_SET_CURRENT(f_total);
1631  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1632 
1633  /* self usage: elapsed minus anything already charged to other calls */
1634  f_others = total_func_time;
1635  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1636  f_self = f_total;
1637  INSTR_TIME_SUBTRACT(f_self, f_others);
1638 
1639  /* update backend-wide total time */
1641 
1642  /*
1643  * Compute the new f_total_time as the total elapsed time added to the
1644  * pre-call value of f_total_time. This is necessary to avoid
1645  * double-counting any time taken by recursive calls of myself. (We do
1646  * not need any similar kluge for self time, since that already excludes
1647  * any recursive calls.)
1648  */
1649  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1650 
1651  /* update counters in function stats table */
1652  if (finalize)
1653  fs->f_numcalls++;
1654  fs->f_total_time = f_total;
1655  INSTR_TIME_ADD(fs->f_self_time, f_self);
1656 
1657  /* indicate that we have something to send */
1658  have_function_stats = true;
1659 }
instr_time f_self_time
Definition: pgstat.h:463
instr_time save_total
Definition: pgstat.h:1095
struct timeval instr_time
Definition: instr_time.h:147
instr_time f_total_time
Definition: pgstat.h:462
PgStat_FunctionCounts * fs
Definition: pgstat.h:1091
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:273
static bool have_function_stats
Definition: pgstat.c:200
#define NULL
Definition: c.h:229
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:1093
static void pgstat_exit ( SIGNAL_ARGS  )
static

Definition at line 4395 of file pgstat.c.

References MyLatch, need_exit, and SetLatch().

Referenced by PgstatCollectorMain().

4396 {
4397  int save_errno = errno;
4398 
4399  need_exit = true;
4400  SetLatch(MyLatch);
4401 
4402  errno = save_errno;
4403 }
static volatile bool need_exit
Definition: pgstat.c:265
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
struct Latch * MyLatch
Definition: globals.c:51
PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2523 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2524 {
2526 
2527  return &archiverStats;
2528 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5328
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:254
PgBackendStatus* pgstat_fetch_stat_beentry ( int  beid)
PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

Definition at line 2351 of file pgstat.c.

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

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

2352 {
2353  /*
2354  * If not done for this transaction, read the statistics collector stats
2355  * file into some hash tables.
2356  */
2358 
2359  /*
2360  * Lookup the requested database; return NULL if not found
2361  */
2363  (void *) &dbid,
2364  HASH_FIND, NULL);
2365 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static void backend_read_statsfile(void)
Definition: pgstat.c:5328
#define NULL
Definition: c.h:229
static HTAB * pgStatDBHash
Definition: pgstat.c:241
PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

Definition at line 2434 of file pgstat.c.

References backend_read_statsfile(), PgStat_StatDBEntry::functions, HASH_FIND, hash_search(), MyDatabaseId, NULL, 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().

2435 {
2436  PgStat_StatDBEntry *dbentry;
2437  PgStat_StatFuncEntry *funcentry = NULL;
2438 
2439  /* load the stats file if needed */
2441 
2442  /* Lookup our database, then find the requested function. */
2444  if (dbentry != NULL && dbentry->functions != NULL)
2445  {
2446  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2447  (void *) &func_id,
2448  HASH_FIND, NULL);
2449  }
2450 
2451  return funcentry;
2452 }
HTAB * functions
Definition: pgstat.h:607
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2351
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static void backend_read_statsfile(void)
Definition: pgstat.c:5328
Oid MyDatabaseId
Definition: globals.c:76
#define NULL
Definition: c.h:229
LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2488 of file pgstat.c.

References localNumBackends, NULL, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2489 {
2491 
2492  if (beid < 1 || beid > localNumBackends)
2493  return NULL;
2494 
2495  return &localBackendStatusTable[beid - 1];
2496 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3181
#define NULL
Definition: c.h:229
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:244
static int localNumBackends
Definition: pgstat.c:247
int pgstat_fetch_stat_numbackends ( void  )

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

2508 {
2510 
2511  return localNumBackends;
2512 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3181
static int localNumBackends
Definition: pgstat.c:247
PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

Definition at line 2378 of file pgstat.c.

References backend_read_statsfile(), HASH_FIND, hash_search(), InvalidOid, MyDatabaseId, NULL, 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().

2379 {
2380  Oid dbid;
2381  PgStat_StatDBEntry *dbentry;
2382  PgStat_StatTabEntry *tabentry;
2383 
2384  /*
2385  * If not done for this transaction, read the statistics collector stats
2386  * file into some hash tables.
2387  */
2389 
2390  /*
2391  * Lookup our database, then look in its table hash table.
2392  */
2393  dbid = MyDatabaseId;
2395  (void *) &dbid,
2396  HASH_FIND, NULL);
2397  if (dbentry != NULL && dbentry->tables != NULL)
2398  {
2399  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2400  (void *) &relid,
2401  HASH_FIND, NULL);
2402  if (tabentry)
2403  return tabentry;
2404  }
2405 
2406  /*
2407  * If we didn't find it, maybe it's a shared table.
2408  */
2409  dbid = InvalidOid;
2411  (void *) &dbid,
2412  HASH_FIND, NULL);
2413  if (dbentry != NULL && dbentry->tables != NULL)
2414  {
2415  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2416  (void *) &relid,
2417  HASH_FIND, NULL);
2418  if (tabentry)
2419  return tabentry;
2420  }
2421 
2422  return NULL;
2423 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
static void backend_read_statsfile(void)
Definition: pgstat.c:5328
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
static HTAB * pgStatDBHash
Definition: pgstat.c:241
const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 3855 of file pgstat.c.

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

Referenced by DeadLockReport().

3856 {
3857  PgBackendStatus *beentry;
3858  int i;
3859 
3860  beentry = BackendStatusArray;
3861  for (i = 1; i <= MaxBackends; i++)
3862  {
3863  /*
3864  * Although we expect the target backend's entry to be stable, that
3865  * doesn't imply that anyone else's is. To avoid identifying the
3866  * wrong backend, while we check for a match to the desired PID we
3867  * must follow the protocol of retrying if st_changecount changes
3868  * while we examine the entry, or if it's odd. (This might be
3869  * unnecessary, since fetching or storing an int is almost certainly
3870  * atomic, but let's play it safe.) We use a volatile pointer here to
3871  * ensure the compiler doesn't try to get cute.
3872  */
3873  volatile PgBackendStatus *vbeentry = beentry;
3874  bool found;
3875 
3876  for (;;)
3877  {
3878  int before_changecount;
3879  int after_changecount;
3880 
3881  pgstat_save_changecount_before(vbeentry, before_changecount);
3882 
3883  found = (vbeentry->st_procpid == pid);
3884 
3885  pgstat_save_changecount_after(vbeentry, after_changecount);
3886 
3887  if (before_changecount == after_changecount &&
3888  (before_changecount & 1) == 0)
3889  break;
3890 
3891  /* Make sure we can break out of loop if stuck... */
3893  }
3894 
3895  if (found)
3896  {
3897  /* Now it is safe to use the non-volatile pointer */
3898  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
3899  return "<insufficient privilege>";
3900  else if (*(beentry->st_activity) == '\0')
3901  return "<command string not enabled>";
3902  else
3903  return beentry->st_activity;
3904  }
3905 
3906  beentry++;
3907  }
3908 
3909  /* If we get here, caller is in error ... */
3910  return "<backend information not available>";
3911 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2553
Oid GetUserId(void)
Definition: miscinit.c:283
bool superuser(void)
Definition: superuser.c:47
int MaxBackends
Definition: globals.c:126
#define pgstat_save_changecount_before(beentry, save_changecount)
Definition: pgstat.h:1044
char * st_activity
Definition: pgstat.h:1003
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:1050
int st_procpid
Definition: pgstat.h:975
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
const char* pgstat_get_backend_desc ( BackendType  backendType)

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

3989 {
3990  const char *backendDesc = "unknown process type";
3991 
3992  switch (backendType)
3993  {
3994  case B_AUTOVAC_LAUNCHER:
3995  backendDesc = "autovacuum launcher";
3996  break;
3997  case B_AUTOVAC_WORKER:
3998  backendDesc = "autovacuum worker";
3999  break;
4000  case B_BACKEND:
4001  backendDesc = "client backend";
4002  break;
4003  case B_BG_WORKER:
4004  backendDesc = "background worker";
4005  break;
4006  case B_BG_WRITER:
4007  backendDesc = "background writer";
4008  break;
4009  case B_CHECKPOINTER:
4010  backendDesc = "checkpointer";
4011  break;
4012  case B_STARTUP:
4013  backendDesc = "startup";
4014  break;
4015  case B_WAL_RECEIVER:
4016  backendDesc = "walreceiver";
4017  break;
4018  case B_WAL_SENDER:
4019  backendDesc = "walsender";
4020  break;
4021  case B_WAL_WRITER:
4022  backendDesc = "walwriter";
4023  break;
4024  }
4025 
4026  return backendDesc;
4027 }
const char* pgstat_get_crashed_backend_activity ( int  pid,
char *  buffer,
int  buflen 
)

Definition at line 3930 of file pgstat.c.

References ascii_safe_strlcpy(), BackendStatusArray, buffer, i, MaxBackends, Min, NULL, pgstat_track_activity_query_size, PgBackendStatus::st_activity, and PgBackendStatus::st_procpid.

Referenced by LogChildExit().

3931 {
3932  volatile PgBackendStatus *beentry;
3933  int i;
3934 
3935  beentry = BackendStatusArray;
3936 
3937  /*
3938  * We probably shouldn't get here before shared memory has been set up,
3939  * but be safe.
3940  */
3941  if (beentry == NULL || BackendActivityBuffer == NULL)
3942  return NULL;
3943 
3944  for (i = 1; i <= MaxBackends; i++)
3945  {
3946  if (beentry->st_procpid == pid)
3947  {
3948  /* Read pointer just once, so it can't change after validation */
3949  const char *activity = beentry->st_activity;
3950  const char *activity_last;
3951 
3952  /*
3953  * We mustn't access activity string before we verify that it
3954  * falls within the BackendActivityBuffer. To make sure that the
3955  * entire string including its ending is contained within the
3956  * buffer, subtract one activity length from the buffer size.
3957  */
3960 
3961  if (activity < BackendActivityBuffer ||
3962  activity > activity_last)
3963  return NULL;
3964 
3965  /* If no string available, no point in a report */
3966  if (activity[0] == '\0')
3967  return NULL;
3968 
3969  /*
3970  * Copy only ASCII-safe characters so we don't run into encoding
3971  * problems when reporting the message; and be sure not to run off
3972  * the end of memory.
3973  */
3974  ascii_safe_strlcpy(buffer, activity,
3975  Min(buflen, pgstat_track_activity_query_size));
3976 
3977  return buffer;
3978  }
3979 
3980  beentry++;
3981  }
3982 
3983  /* PID not found */
3984  return NULL;
3985 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2553
static char * BackendActivityBuffer
Definition: pgstat.c:2557
#define Min(x, y)
Definition: c.h:806
static Size BackendActivityBufferSize
Definition: pgstat.c:2558
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
int MaxBackends
Definition: globals.c:126
int pgstat_track_activity_query_size
Definition: pgstat.c:125
#define NULL
Definition: c.h:229
char * st_activity
Definition: pgstat.h:1003
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
int st_procpid
Definition: pgstat.h:975
int i
static PgStat_StatDBEntry * pgstat_get_db_entry ( Oid  databaseid,
bool  create 
)
static

Definition at line 4473 of file pgstat.c.

References HASH_ENTER, HASH_FIND, hash_search(), NULL, reset_dbentry_counters(), and result.

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

4474 {
4476  bool found;
4477  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4478 
4479  /* Lookup or create the hash table entry for this database */
4481  &databaseid,
4482  action, &found);
4483 
4484  if (!create && !found)
4485  return NULL;
4486 
4487  /*
4488  * If not found, initialize the new one. This creates empty hash tables
4489  * for tables and functions, too.
4490  */
4491  if (!found)
4492  reset_dbentry_counters(result);
4493 
4494  return result;
4495 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4423
return result
Definition: formatting.c:1618
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define NULL
Definition: c.h:229
static HTAB * pgStatDBHash
Definition: pgstat.c:241
HASHACTION
Definition: hsearch.h:103
static PgStat_StatTabEntry * pgstat_get_tab_entry ( PgStat_StatDBEntry dbentry,
Oid  tableoid,
bool  create 
)
static

Definition at line 4504 of file pgstat.c.

References 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, NULL, PgStat_StatTabEntry::numscans, result, 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().

4505 {
4507  bool found;
4508  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4509 
4510  /* Lookup or create the hash table entry for this table */
4511  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4512  &tableoid,
4513  action, &found);
4514 
4515  if (!create && !found)
4516  return NULL;
4517 
4518  /* If not found, initialize the new one. */
4519  if (!found)
4520  {
4521  result->numscans = 0;
4522  result->tuples_returned = 0;
4523  result->tuples_fetched = 0;
4524  result->tuples_inserted = 0;
4525  result->tuples_updated = 0;
4526  result->tuples_deleted = 0;
4527  result->tuples_hot_updated = 0;
4528  result->n_live_tuples = 0;
4529  result->n_dead_tuples = 0;
4530  result->changes_since_analyze = 0;
4531  result->blocks_fetched = 0;
4532  result->blocks_hit = 0;
4533  result->vacuum_timestamp = 0;
4534  result->vacuum_count = 0;
4535  result->autovac_vacuum_timestamp = 0;
4536  result->autovac_vacuum_count = 0;
4537  result->analyze_timestamp = 0;
4538  result->analyze_count = 0;
4539  result->autovac_analyze_timestamp = 0;
4540  result->autovac_analyze_count = 0;
4541  }
4542 
4543  return result;
4544 }
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
return result
Definition: formatting.c:1618
PgStat_Counter numscans
Definition: pgstat.h:619
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
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
#define NULL
Definition: c.h:229
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
static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

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

3428 {
3429  const char *event_name = "unknown wait event";
3430 
3431  switch (w)
3432  {
3434  event_name = "ArchiverMain";
3435  break;
3437  event_name = "AutoVacuumMain";
3438  break;
3440  event_name = "BgWriterHibernate";
3441  break;
3443  event_name = "BgWriterMain";
3444  break;
3446  event_name = "CheckpointerMain";
3447  break;
3449  event_name = "PgStatMain";
3450  break;
3452  event_name = "RecoveryWalAll";
3453  break;
3455  event_name = "RecoveryWalStream";
3456  break;
3458  event_name = "SysLoggerMain";
3459  break;
3461  event_name = "WalReceiverMain";
3462  break;
3464  event_name = "WalSenderMain";
3465  break;
3467  event_name = "WalWriterMain";
3468  break;
3470  event_name = "LogicalLauncherMain";
3471  break;
3473  event_name = "LogicalApplyMain";
3474  break;
3475  /* no default case, so that compiler will warn */
3476  }
3477 
3478  return event_name;
3479 }
static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3488 of file pgstat.c.

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

3489 {
3490  const char *event_name = "unknown wait event";
3491 
3492  switch (w)
3493  {
3495  event_name = "ClientRead";
3496  break;
3498  event_name = "ClientWrite";
3499  break;
3501  event_name = "SSLOpenServer";
3502  break;
3504  event_name = "WalReceiverWaitStart";
3505  break;
3507  event_name = "LibPQWalReceiver";
3508  break;
3510  event_name = "WalSenderWaitForWAL";
3511  break;
3513  event_name = "WalSenderWriteData";
3514  break;
3515  /* no default case, so that compiler will warn */
3516  }
3517 
3518  return event_name;
3519 }
const char* pgstat_get_wait_event ( uint32  wait_event_info)

Definition at line 3350 of file pgstat.c.

References GetLockNameFromTagType(), GetLWLockIdentifier(), NULL, 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().

3351 {
3352  uint32 classId;
3353  uint16 eventId;
3354  const char *event_name;
3355 
3356  /* report process as not waiting. */
3357  if (wait_event_info == 0)
3358  return NULL;
3359 
3360  classId = wait_event_info & 0xFF000000;
3361  eventId = wait_event_info & 0x0000FFFF;
3362 
3363  switch (classId)
3364  {
3365  case PG_WAIT_LWLOCK:
3366  event_name = GetLWLockIdentifier(classId, eventId);
3367  break;
3368  case PG_WAIT_LOCK:
3369  event_name = GetLockNameFromTagType(eventId);
3370  break;
3371  case PG_WAIT_BUFFER_PIN:
3372  event_name = "BufferPin";
3373  break;
3374  case PG_WAIT_ACTIVITY:
3375  {
3376  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3377 
3378  event_name = pgstat_get_wait_activity(w);
3379  break;
3380  }
3381  case PG_WAIT_CLIENT:
3382  {
3383  WaitEventClient w = (WaitEventClient) wait_event_info;
3384 
3385  event_name = pgstat_get_wait_client(w);
3386  break;
3387  }
3388  case PG_WAIT_EXTENSION:
3389  event_name = "Extension";
3390  break;
3391  case PG_WAIT_IPC:
3392  {
3393  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3394 
3395  event_name = pgstat_get_wait_ipc(w);
3396  break;
3397  }
3398  case PG_WAIT_TIMEOUT:
3399  {
3400  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3401 
3402  event_name = pgstat_get_wait_timeout(w);
3403  break;
3404  }
3405  case PG_WAIT_IO:
3406  {
3407  WaitEventIO w = (WaitEventIO) wait_event_info;
3408 
3409  event_name = pgstat_get_wait_io(w);
3410  break;
3411  }
3412  default:
3413  event_name = "unknown wait event";
3414  break;
3415  }
3416 
3417  return event_name;
3418 }
#define PG_WAIT_LOCK
Definition: pgstat.h:738
WaitEventIPC
Definition: pgstat.h:799
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3592
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3528
#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:3427
unsigned short uint16
Definition: c.h:267
#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:3488
unsigned int uint32
Definition: c.h:268
WaitEventTimeout
Definition: pgstat.h:824
#define PG_WAIT_EXTENSION
Definition: pgstat.h:742
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:739
#define NULL
Definition: c.h:229
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1039
WaitEventIO
Definition: pgstat.h:837
#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:703
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:3620
#define PG_WAIT_LWLOCK
Definition: pgstat.h:737
WaitEventActivity
Definition: pgstat.h:755
const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

Definition at line 3295 of file pgstat.c.

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

3296 {
3297  uint32 classId;
3298  const char *event_type;
3299 
3300  /* report process as not waiting. */
3301  if (wait_event_info == 0)
3302  return NULL;
3303 
3304  classId = wait_event_info & 0xFF000000;
3305 
3306  switch (classId)
3307  {
3308  case PG_WAIT_LWLOCK:
3309  event_type = "LWLock";
3310  break;
3311  case PG_WAIT_LOCK:
3312  event_type = "Lock";
3313  break;
3314  case PG_WAIT_BUFFER_PIN:
3315  event_type = "BufferPin";
3316  break;
3317  case PG_WAIT_ACTIVITY:
3318  event_type = "Activity";
3319  break;
3320  case PG_WAIT_CLIENT:
3321  event_type = "Client";
3322  break;
3323  case PG_WAIT_EXTENSION:
3324  event_type = "Extension";
3325  break;
3326  case PG_WAIT_IPC:
3327  event_type = "IPC";
3328  break;
3329  case PG_WAIT_TIMEOUT:
3330  event_type = "Timeout";
3331  break;
3332  case PG_WAIT_IO:
3333  event_type = "IO";
3334  break;
3335  default:
3336  event_type = "???";
3337  break;
3338  }
3339 
3340  return event_type;
3341 }
#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:268
#define PG_WAIT_EXTENSION
Definition: pgstat.h:742
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:739
#define NULL
Definition: c.h:229
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:744
#define PG_WAIT_IPC
Definition: pgstat.h:743
#define PG_WAIT_LWLOCK
Definition: pgstat.h:737
static const char * pgstat_get_wait_io ( WaitEventIO  w)
static

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

3621 {
3622  const char *event_name = "unknown wait event";
3623 
3624  switch (w)
3625  {
3627  event_name = "BufFileRead";
3628  break;
3630  event_name = "BufFileWrite";
3631  break;
3633  event_name = "ControlFileRead";
3634  break;
3636  event_name = "ControlFileSync";
3637  break;
3639  event_name = "ControlFileSyncUpdate";
3640  break;
3642  event_name = "ControlFileWrite";
3643  break;
3645  event_name = "ControlFileWriteUpdate";
3646  break;
3648  event_name = "CopyFileRead";
3649  break;
3651  event_name = "CopyFileWrite";
3652  break;
3654  event_name = "DataFileExtend";
3655  break;
3657  event_name = "DataFileFlush";
3658  break;
3660  event_name = "DataFileImmediateSync";
3661  break;
3663  event_name = "DataFilePrefetch";
3664  break;
3666  event_name = "DataFileRead";
3667  break;
3669  event_name = "DataFileSync";
3670  break;
3672  event_name = "DataFileTruncate";
3673  break;
3675  event_name = "DataFileWrite";
3676  break;
3678  event_name = "DSMFillZeroWrite";
3679  break;
3681  event_name = "LockFileAddToDataDirRead";
3682  break;
3684  event_name = "LockFileAddToDataDirSync";
3685  break;
3687  event_name = "LockFileAddToDataDirWrite";
3688  break;
3690  event_name = "LockFileCreateRead";
3691  break;
3693  event_name = "LockFileCreateSync";
3694  break;
3696  event_name = "LockFileCreateWRITE";
3697  break;
3699  event_name = "LockFileReCheckDataDirRead";
3700  break;
3702  event_name = "LogicalRewriteCheckpointSync";
3703  break;
3705  event_name = "LogicalRewriteMappingSync";
3706  break;
3708  event_name = "LogicalRewriteMappingWrite";
3709  break;
3711  event_name = "LogicalRewriteSync";
3712  break;
3714  event_name = "LogicalRewriteTruncate";
3715  break;
3717  event_name = "LogicalRewriteWrite";
3718  break;
3720  event_name = "RelationMapRead";
3721  break;
3723  event_name = "RelationMapSync";
3724  break;
3726  event_name = "RelationMapWrite";
3727  break;
3729  event_name = "ReorderBufferRead";
3730  break;
3732  event_name = "ReorderBufferWrite";
3733  break;
3735  event_name = "ReorderLogicalMappingRead";
3736  break;
3738  event_name = "ReplicationSlotRead";
3739  break;
3741  event_name = "ReplicationSlotRestoreSync";
3742  break;
3744  event_name = "ReplicationSlotSync";
3745  break;
3747  event_name = "ReplicationSlotWrite";
3748  break;
3750  event_name = "SLRUFlushSync";
3751  break;
3752  case WAIT_EVENT_SLRU_READ:
3753  event_name = "SLRURead";
3754  break;
3755  case WAIT_EVENT_SLRU_SYNC:
3756  event_name = "SLRUSync";
3757  break;
3758  case WAIT_EVENT_SLRU_WRITE:
3759  event_name = "SLRUWrite";
3760  break;
3762  event_name = "SnapbuildRead";
3763  break;
3765  event_name = "SnapbuildSync";
3766  break;
3768  event_name = "SnapbuildWrite";
3769  break;
3771  event_name = "TimelineHistoryFileSync";
3772  break;
3774  event_name = "TimelineHistoryFileWrite";
3775  break;
3777  event_name = "TimelineHistoryRead";
3778  break;
3780  event_name = "TimelineHistorySync";
3781  break;
3783  event_name = "TimelineHistoryWrite";
3784  break;
3786  event_name = "TwophaseFileRead";
3787  break;
3789  event_name = "TwophaseFileSync";
3790  break;
3792  event_name = "TwophaseFileWrite";
3793  break;
3795  event_name = "WALSenderTimelineHistoryRead";
3796  break;
3798  event_name = "WALBootstrapSync";
3799  break;
3801  event_name = "WALBootstrapWrite";
3802  break;
3804  event_name = "WALCopyRead";
3805  break;
3807  event_name = "WALCopySync";
3808  break;
3810  event_name = "WALCopyWrite";
3811  break;
3813  event_name = "WALInitSync";
3814  break;
3816  event_name = "WALInitWrite";
3817  break;
3818  case WAIT_EVENT_WAL_READ:
3819  event_name = "WALRead";
3820  break;
3822  event_name = "WALSyncMethodAssign";
3823  break;
3824  case WAIT_EVENT_WAL_WRITE:
3825  event_name = "WALWrite";
3826  break;
3827 
3828  /* no default case, so that compiler will warn */
3829  }
3830 
3831  return event_name;
3832 }
static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3528 of file pgstat.c.

References WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WAIT_EVENT_BTREE_PAGE, WAIT_EVENT_EXECUTE_GATHER, 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_FINISH, WAIT_EVENT_PROCARRAY_GROUP_UPDATE, WAIT_EVENT_SAFE_SNAPSHOT, and WAIT_EVENT_SYNC_REP.

Referenced by pgstat_get_wait_event().

3529 {
3530  const char *event_name = "unknown wait event";
3531 
3532  switch (w)
3533  {
3535  event_name = "BgWorkerShutdown";
3536  break;
3538  event_name = "BgWorkerStartup";
3539  break;
3540  case WAIT_EVENT_BTREE_PAGE:
3541  event_name = "BtreePage";
3542  break;
3544  event_name = "ExecuteGather";
3545  break;
3547  event_name = "MessageQueueInternal";
3548  break;
3550  event_name = "MessageQueuePutMessage";
3551  break;
3552  case WAIT_EVENT_MQ_RECEIVE:
3553  event_name = "MessageQueueReceive";
3554  break;
3555  case WAIT_EVENT_MQ_SEND:
3556  event_name = "MessageQueueSend";
3557  break;
3559  event_name = "ParallelFinish";
3560  break;
3562  event_name = "ParallelBitmapScan";
3563  break;
3565  event_name = "ProcArrayGroupUpdate";
3566  break;
3568  event_name = "SafeSnapshot";
3569  break;
3570  case WAIT_EVENT_SYNC_REP:
3571  event_name = "SyncRep";
3572  break;
3574  event_name = "LogicalSyncData";
3575  break;
3577  event_name = "LogicalSyncStateChange";
3578  break;
3579  /* no default case, so that compiler will warn */
3580  }
3581 
3582  return event_name;
3583 }
static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

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

3593 {
3594  const char *event_name = "unknown wait event";
3595 
3596  switch (w)
3597  {
3599  event_name = "BaseBackupThrottle";
3600  break;
3601  case WAIT_EVENT_PG_SLEEP:
3602  event_name = "PgSleep";
3603  break;
3605  event_name = "RecoveryApplyDelay";
3606  break;
3607  /* no default case, so that compiler will warn */
3608  }
3609 
3610  return event_name;
3611 }
void pgstat_init ( void  )

Definition at line 352 of file pgstat.c.

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

Referenced by PostmasterMain().

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

Definition at line 1546 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, NULL, 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().

1548 {
1549  PgStat_BackendFunctionEntry *htabent;
1550  bool found;
1551 
1552  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1553  {
1554  /* stats not wanted */
1555  fcu->fs = NULL;
1556  return;
1557  }
1558 
1559  if (!pgStatFunctions)
1560  {
1561  /* First time through - initialize function stat table */
1562  HASHCTL hash_ctl;
1563 
1564  memset(&hash_ctl, 0, sizeof(hash_ctl));
1565  hash_ctl.keysize = sizeof(Oid);
1566  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1567  pgStatFunctions = hash_create("Function stat entries",
1569  &hash_ctl,
1570  HASH_ELEM | HASH_BLOBS);
1571  }
1572 
1573  /* Get the stats entry for this function, create if necessary */
1574  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1575  HASH_ENTER, &found);
1576  if (!found)
1577  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1578 
1579  fcu->fs = &htabent->f_counts;
1580 
1581  /* save stats for this function, later used to compensate for recursion */
1582  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1583 
1584  /* save current backend-wide total time */
1585  fcu->save_total = total_func_time;
1586 
1587  /* get clock time as of function start */
1589 }
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:1095
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:857
instr_time f_total_time
Definition: pgstat.h:462
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1091
FmgrInfo * flinfo
Definition: fmgr.h:79
PgStat_FunctionCounts f_counts
Definition: pgstat.h:473
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:103
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
Oid fn_oid
Definition: fmgr.h:59
static instr_time total_func_time
Definition: pgstat.c:273
static HTAB * pgStatFunctions
Definition: pgstat.c:194
#define NULL
Definition: c.h:229
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:1093
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry
void pgstat_initialize ( void  )

Definition at line 2709 of file pgstat.c.

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

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2710 {
2711  /* Initialize MyBEEntry */
2713  {
2716  }
2717  else
2718  {
2719  /* Must be an auxiliary process */
2721 
2722  /*
2723  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
2724  * have a BackendId, the slot is statically allocated based on the
2725  * auxiliary process type (MyAuxProcType). Backends use slots indexed
2726  * in the range from 1 to MaxBackends (inclusive), so we use
2727  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2728  * auxiliary process.
2729  */
2731  }
2732 
2733  /* Set up a process-exit hook to clean up */
2735 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2553
BackendId MyBackendId
Definition: globals.c:72
int MaxBackends
Definition: globals.c:126
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:348
static void pgstat_beshutdown_hook(int code, Datum arg)
Definition: pgstat.c:2920
#define InvalidBackendId
Definition: backendid.h:23
AuxProcType MyAuxProcType
Definition: bootstrap.c:68
#define Assert(condition)
Definition: c.h:675
void pgstat_initstats ( Relation  rel)

Definition at line 1675 of file pgstat.c.

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

1676 {
1677  Oid rel_id = rel->rd_id;
1678  char relkind = rel->rd_rel->relkind;
1679 
1680  /* We only count stats for things that have storage */
1681  if (!(relkind == RELKIND_RELATION ||
1682  relkind == RELKIND_MATVIEW ||
1683  relkind == RELKIND_INDEX ||
1684  relkind == RELKIND_TOASTVALUE ||
1685  relkind == RELKIND_SEQUENCE))
1686  {
1687  rel->pgstat_info = NULL;
1688  return;
1689  }
1690 
1692  {
1693  /* We're not counting at all */
1694  rel->pgstat_info = NULL;
1695  return;
1696  }
1697 
1698  /*
1699  * If we already set up this relation in the current transaction, nothing
1700  * to do.
1701  */
1702  if (rel->pgstat_info != NULL &&
1703  rel->pgstat_info->t_id == rel_id)
1704  return;
1705 
1706  /* Else find or make the PgStat_TableStatus entry, and update link */
1707  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1708 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:146
#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:123
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:24
#define NULL
Definition: c.h:229
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
void pgstat_ping ( void  )

Definition at line 1511 of file pgstat.c.

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

1512 {
1513  PgStat_MsgDummy msg;
1514 
1516  return;
1517 
1519  pgstat_send(&msg, sizeof(msg));
1520 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:4054
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:146
#define PGINVALID_SOCKET
Definition: port.h:24
PgStat_MsgHdr m_hdr
Definition: pgstat.h:216
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
Definition: pgstat.c:4041
void pgstat_progress_end_command ( void  )

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

3105 {
3106  volatile PgBackendStatus *beentry = MyBEEntry;
3107 
3108  if (!beentry)
3109  return;
3112  return;
3113 
3118 }
Oid st_progress_command_target
Definition: pgstat.h:1015
ProgressCommandType st_progress_command
Definition: pgstat.h:1014
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:122
void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

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

3033 {
3034  volatile PgBackendStatus *beentry = MyBEEntry;
3035 
3036  if (!beentry || !pgstat_track_activities)
3037  return;
3038 
3040  beentry->st_progress_command = cmdtype;
3041  beentry->st_progress_command_target = relid;
3042  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3044 }
Oid st_progress_command_target
Definition: pgstat.h:1015
#define MemSet(start, val, len)
Definition: c.h:857
ProgressCommandType st_progress_command
Definition: pgstat.h:1014
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1016
bool pgstat_track_activities
Definition: pgstat.c:122
void pgstat_progress_update_multi_param ( int  nparam,
const int *  index,
const int64 *  val 
)

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

3077 {
3078  volatile PgBackendStatus *beentry = MyBEEntry;
3079  int i;
3080 
3081  if (!beentry || !pgstat_track_activities || nparam == 0)
3082  return;
3083 
3085 
3086  for (i = 0; i < nparam; ++i)
3087  {
3088  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3089 
3090  beentry->st_progress_param[index[i]] = val[i];
3091  }
3092 
3094 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:918
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
#define Assert(condition)
Definition: c.h:675
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1016
bool pgstat_track_activities
Definition: pgstat.c:122
int i
long val
Definition: informix.c:689
void pgstat_progress_update_param ( int  index,
int64  val 
)

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

3054 {
3055  volatile PgBackendStatus *beentry = MyBEEntry;
3056 
3058 
3059  if (!beentry || !pgstat_track_activities)
3060  return;
3061 
3063  beentry->st_progress_param[index] = val;
3065 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:918
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2554
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1031
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1037
#define Assert(condition)
Definition: c.h:675
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:1016
bool pgstat_track_activities
Definition: pgstat.c:122
long val
Definition: informix.c:689
static void pgstat_read_current_status ( void  )
static

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

3182 {
3183  volatile PgBackendStatus *beentry;
3184  LocalPgBackendStatus *localtable;
3185  LocalPgBackendStatus *localentry;
3186  char *localappname,
3187  *localactivity;
3188 #ifdef USE_SSL
3189  PgBackendSSLStatus *localsslstatus;
3190 #endif
3191  int i;
3192 
3195  return; /* already done */
3196 
3198 
3199  localtable = (LocalPgBackendStatus *)
3202  localappname = (char *)
3205  localactivity = (char *)
3207  pgstat_track_activity_query_size * NumBackendStatSlots);
3208 #ifdef USE_SSL
3209  localsslstatus = (PgBackendSSLStatus *)
3212 #endif
3213 
3214  localNumBackends = 0;
3215 
3216  beentry = BackendStatusArray;
3217  localentry = localtable;
3218  for (i = 1; i <= NumBackendStatSlots; i++)
3219  {
3220  /*
3221  * Follow the protocol of retrying if st_changecount changes while we
3222  * copy the entry, or if it's odd. (The check for odd is needed to
3223  * cover the case where we are able to completely copy the entry while
3224  * the source backend is between increment steps.) We use a volatile
3225  * pointer here to ensure the compiler doesn't try to get cute.
3226  */
3227  for (;;)
3228  {
3229  int before_changecount;
3230  int after_changecount;
3231 
3232  pgstat_save_changecount_before(beentry, before_changecount);
3233 
3234  localentry->backendStatus.st_procpid = beentry->st_procpid;
3235  if (localentry->backendStatus.st_procpid > 0)
3236  {
3237  memcpy(&localentry->backendStatus, (char *) beentry, sizeof(PgBackendStatus));
3238 
3239  /*
3240  * strcpy is safe even if the string is modified concurrently,
3241  * because there's always a \0 at the end of the buffer.
3242  */
3243  strcpy(localappname, (char *) beentry->st_appname);
3244  localentry->backendStatus.st_appname = localappname;
3245  strcpy(localactivity, (char *) beentry->st_activity);
3246  localentry->backendStatus.st_activity = localactivity;
3247  localentry->backendStatus.st_ssl = beentry->st_ssl;
3248 #ifdef USE_SSL
3249  if (beentry->st_ssl)
3250  {
3251  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3252  localentry->backendStatus.st_sslstatus = localsslstatus;
3253  }
3254 #endif
3255  }
3256 
3257  pgstat_save_changecount_after(beentry, after_changecount);
3258  if (before_changecount == after_changecount &&
3259  (before_changecount & 1) == 0)
3260  break;
3261 
3262  /* Make sure we can break out of loop if stuck... */
3264  }
3265 
3266  beentry++;
3267  /* Only valid entries get included into the local array */
3268  if (localentry->backendStatus.st_procpid > 0)
3269  {
3271  &localentry->backend_xid,
3272  &localentry->backend_xmin);
3273 
3274  localentry++;
3275  localappname += NAMEDATALEN;
3276  localactivity += pgstat_track_activity_query_size;
3277 #ifdef USE_SSL
3278  localsslstatus++;
3279 #endif
3280  localNumBackends++;
3281  }
3282  }
3283 
3284  /* Set the pointer only after completion of a valid table */
3285  localBackendStatusTable = localtable;
3286 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2553
static bool pgStatRunningInCollector
Definition: pgstat.c:152
TransactionId backend_xmin
Definition: pgstat.h:1081
#define NumBackendStatSlots
Definition: pgstat.c:115
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:1075
#define pgstat_save_changecount_before(beentry, save_changecount)
Definition: pgstat.h:1044
int pgstat_track_activity_query_size
Definition: pgstat.c:125
char * st_appname
Definition: pgstat.h:1000
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5462
PgBackendStatus backendStatus
Definition: pgstat.h:1069
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:404
#define Assert(condition)
Definition: c.h:675
char * st_activity
Definition: pgstat.h:1003
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:244
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:1050
int st_procpid
Definition: pgstat.h:975
static int localNumBackends
Definition: pgstat.c:247
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:240
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:994
static void pgstat_read_db_statsfile ( Oid  databaseid,
HTAB tabhash,
HTAB funchash,
bool  permanent 
)
static

Definition at line 5047 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, NULL, PG_BINARY_R, PGSTAT_FILE_FORMAT_ID, pgStatRunningInCollector, PgStat_StatTabEntry::tableid, unlink(), and WARNING.

Referenced by pgstat_read_statsfiles().

5049 {
5050  PgStat_StatTabEntry *tabentry;
5051  PgStat_StatTabEntry tabbuf;
5052  PgStat_StatFuncEntry funcbuf;
5053  PgStat_StatFuncEntry *funcentry;
5054  FILE *fpin;
5055  int32 format_id;
5056  bool found;
5057  char statfile[MAXPGPATH];
5058 
5059  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5060 
5061  /*
5062  * Try to open the stats file. If it doesn't exist, the backends simply
5063  * return zero for anything and the collector simply starts from scratch
5064  * with empty counters.
5065  *
5066  * ENOENT is a possibility if the stats collector is not running or has
5067  * not yet written the stats file the first time. Any other failure
5068  * condition is suspicious.
5069  */
5070  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5071  {
5072  if (errno != ENOENT)
5075  errmsg("could not open statistics file \"%s\": %m",
5076  statfile)));
5077  return;
5078  }
5079 
5080  /*
5081  * Verify it's of the expected format.
5082  */
5083  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5084  format_id != PGSTAT_FILE_FORMAT_ID)
5085  {
5086  ereport(pgStatRunningInCollector ? LOG : WARNING,
5087  (errmsg("corrupted statistics file \"%s\"", statfile)));
5088  goto done;
5089  }
5090 
5091  /*
5092  * We found an existing collector stats file. Read it and put all the
5093  * hashtable entries into place.
5094  */
5095  for (;;)
5096  {
5097  switch (fgetc(fpin))
5098  {
5099  /*
5100  * 'T' A PgStat_StatTabEntry follows.
5101  */
5102  case 'T':
5103  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5104  fpin) != sizeof(PgStat_StatTabEntry))
5105  {
5106  ereport(pgStatRunningInCollector ? LOG : WARNING,
5107  (errmsg("corrupted statistics file \"%s\"",
5108  statfile)));
5109  goto done;
5110  }
5111 
5112  /*
5113  * Skip if table data not wanted.
5114  */
5115  if (tabhash == NULL)
5116  break;
5117 
5118  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5119  (void *) &tabbuf.tableid,
5120  HASH_ENTER, &found);
5121 
5122  if (found)
5123  {
5124  ereport(pgStatRunningInCollector ? LOG : WARNING,
5125  (errmsg("corrupted statistics file \"%s\"",
5126  statfile)));
5127  goto done;
5128  }
5129 
5130  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5131  break;
5132 
5133  /*
5134  * 'F' A PgStat_StatFuncEntry follows.
5135  */
5136  case 'F':
5137  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5138  fpin) != sizeof(PgStat_StatFuncEntry))
5139  {
5140  ereport(pgStatRunningInCollector ? LOG : WARNING,
5141  (errmsg("corrupted statistics file \"%s\"",
5142  statfile)));
5143  goto done;
5144  }
5145 
5146  /*
5147  * Skip if function data not wanted.
5148  */
5149  if (funchash == NULL)
5150  break;
5151 
5152  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5153  (void *) &funcbuf.functionid,
5154  HASH_ENTER, &found);
5155 
5156  if (found)
5157  {
5158  ereport(pgStatRunningInCollector ? LOG : WARNING,
5159  (errmsg("corrupted statistics file \"%s\"",
5160  statfile)));
5161  goto done;
5162  }
5163 
5164  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5165  break;
5166 
5167  /*
5168  * 'E' The EOF marker of a complete stats file.
5169  */
5170  case 'E':
5171  goto done;
5172 
5173  default:
5174  ereport(pgStatRunningInCollector ? LOG : WARNING,
5175  (errmsg("corrupted statistics file \"%s\"",
5176  statfile)));
5177  goto done;
5178  }
5179  }
5180 
5181 done:
5182  FreeFile(fpin);
5183 
5184  if (permanent)
5185  {
5186  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5187  unlink(statfile);
5188  }
5189 }
static bool pgStatRunningInCollector
Definition: pgstat.c:152
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define LOG
Definition: elog.h:26
#define PG_BINARY_R
Definition: c.h:1040
signed int int32
Definition: c.h:256
#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:2094
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
int FreeFile(FILE *file)
Definition: fd.c:2277
#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:4687
static bool pgstat_read_db_statsfile_timestamp ( Oid  databaseid,
bool  permanent,
TimestampTz ts 
)
static

Definition at line 5209 of file pgstat.c.

References AllocateFile(), PgStat_StatDBEntry::databaseid, ereport, errcode_for_file_access(), errmsg(), FreeFile(), LOG, NULL, 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().

5211 {
5212  PgStat_StatDBEntry dbentry;
5213  PgStat_GlobalStats myGlobalStats;
5214  PgStat_ArchiverStats myArchiverStats;
5215  FILE *fpin;
5216  int32 format_id;
5217  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5218 
5219  /*
5220  * Try to open the stats file. As above, anything but ENOENT is worthy of
5221  * complaining about.
5222  */
5223  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5224  {
5225  if (errno != ENOENT)
5228  errmsg("could not open statistics file \"%s\": %m",
5229  statfile)));
5230  return false;
5231  }
5232 
5233  /*
5234  * Verify it's of the expected format.
5235  */
5236  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5237  format_id != PGSTAT_FILE_FORMAT_ID)
5238  {
5239  ereport(pgStatRunningInCollector ? LOG : WARNING,
5240  (errmsg("corrupted statistics file \"%s\"", statfile)));
5241  FreeFile(fpin);
5242  return false;
5243  }
5244 
5245  /*
5246  * Read global stats struct
5247  */
5248  if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5249  fpin) != sizeof(myGlobalStats))
5250  {
5251  ereport(pgStatRunningInCollector ? LOG : WARNING,
5252  (errmsg("corrupted statistics file \"%s\"", statfile)));
5253  FreeFile(fpin);
5254  return false;
5255  }
5256 
5257  /*
5258  * Read archiver stats struct
5259  */
5260  if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
5261  fpin) != sizeof(myArchiverStats))
5262  {
5263  ereport(pgStatRunningInCollector ? LOG : WARNING,
5264  (errmsg("corrupted statistics file \"%s\"", statfile)));
5265  FreeFile(fpin);
5266  return false;
5267  }
5268 
5269  /* By default, we're going to return the timestamp of the global file. */
5270  *ts = myGlobalStats.stats_timestamp;
5271 
5272  /*
5273  * We found an existing collector stats file. Read it and look for a
5274  * record for the requested database. If found, use its timestamp.
5275  */
5276  for (;;)
5277  {
5278  switch (fgetc(fpin))
5279  {
5280  /*
5281  * 'D' A PgStat_StatDBEntry struct describing a database
5282  * follows.
5283  */
5284  case 'D':
5285  if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
5286  fpin) != offsetof(PgStat_StatDBEntry, tables))
5287  {
5288  ereport(pgStatRunningInCollector ? LOG : WARNING,
5289  (errmsg("corrupted statistics file \"%s\"",
5290  statfile)));
5291  goto done;
5292  }
5293 
5294  /*
5295  * If this is the DB we're looking for, save its timestamp and
5296  * we're done.
5297  */
5298  if (dbentry.databaseid == databaseid)
5299  {
5300  *ts = dbentry.stats_timestamp;
5301  goto done;
5302  }
5303 
5304  break;
5305 
5306  case 'E':
5307  goto done;
5308 
5309  default:
5310  ereport(pgStatRunningInCollector ? LOG : WARNING,
5311  (errmsg("corrupted statistics file \"%s\"",
5312  statfile)));
5313  goto done;
5314  }
5315  }
5316 
5317 done:
5318  FreeFile(fpin);
5319  return true;
5320 }
TimestampTz stats_timestamp
Definition: pgstat.h:600
static bool pgStatRunningInCollector
Definition: pgstat.c:152
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:1040
signed int int32
Definition: c.h:256
char * pgstat_stat_filename
Definition: pgstat.c:132
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2094
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
int FreeFile(FILE *file)
Definition: fd.c:2277
#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:555
static HTAB * pgstat_read_statsfiles ( Oid  onlydb,
bool  permanent,
bool  deep 
)
static

Definition at line 4836 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, NULL, 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::tables, unlink(), and WARNING.

Referenced by backend_read_statsfile(), and PgstatCollectorMain().

4837 {
4838  PgStat_StatDBEntry *dbentry;
4839  PgStat_StatDBEntry dbbuf;
4840  HASHCTL hash_ctl;
4841  HTAB *dbhash;
4842  FILE *fpin;
4843  int32 format_id;
4844  bool found;
4845  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4846 
4847  /*
4848  * The tables will live in pgStatLocalContext.
4849  */
4851 
4852  /*
4853  * Create the DB hashtable
4854  */
4855  memset(&hash_ctl, 0, sizeof(hash_ctl));
4856  hash_ctl.keysize = sizeof(Oid);
4857  hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
4858  hash_ctl.hcxt = pgStatLocalContext;
4859  dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
4861 
4862  /*
4863  * Clear out global and archiver statistics so they start from zero in
4864  * case we can't load an existing statsfile.
4865  */
4866  memset(&globalStats, 0, sizeof(globalStats));
4867  memset(&archiverStats, 0, sizeof(archiverStats));
4868 
4869  /*
4870  * Set the current timestamp (will be kept only in case we can't load an
4871  * existing statsfile).
4872  */
4875 
4876  /*
4877  * Try to open the stats file. If it doesn't exist, the backends simply
4878  * return zero for anything and the collector simply starts from scratch
4879  * with empty counters.
4880  *
4881  * ENOENT is a possibility if the stats collector is not running or has
4882  * not yet written the stats file the first time. Any other failure
4883  * condition is suspicious.
4884  */
4885  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4886  {
4887  if (errno != ENOENT)
4890  errmsg("could not open statistics file \"%s\": %m",
4891  statfile)));
4892  return dbhash;
4893  }
4894 
4895  /*
4896  * Verify it's of the expected format.
4897  */
4898  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4899  format_id != PGSTAT_FILE_FORMAT_ID)
4900  {
4901  ereport(pgStatRunningInCollector ? LOG : WARNING,
4902  (errmsg("corrupted statistics file \"%s\"", statfile)));
4903  goto done;
4904  }
4905 
4906  /*
4907  * Read global stats struct
4908  */
4909  if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
4910  {
4911  ereport(pgStatRunningInCollector ? LOG : WARNING,
4912  (errmsg("corrupted statistics file \"%s\"", statfile)));
4913  goto done;
4914  }
4915 
4916  /*
4917  * Read archiver stats struct
4918  */
4919  if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
4920  {
4921  ereport(pgStatRunningInCollector ? LOG : WARNING,
4922  (errmsg("corrupted statistics file \"%s\"", statfile)));
4923  goto done;
4924  }
4925 
4926  /*
4927  * We found an existing collector stats file. Read it and put all the
4928  * hashtable entries into place.
4929  */
4930  for (;;)
4931  {
4932  switch (fgetc(fpin))
4933  {
4934  /*
4935  * 'D' A PgStat_StatDBEntry struct describing a database
4936  * follows.
4937  */
4938  case 'D':
4939  if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
4940  fpin) != offsetof(PgStat_StatDBEntry, tables))
4941  {
4942  ereport(pgStatRunningInCollector ? LOG : WARNING,
4943  (errmsg("corrupted statistics file \"%s\"",
4944  statfile)));
4945  goto done;
4946  }
4947 
4948  /*
4949  * Add to the DB hash
4950  */
4951  dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
4952  (void *) &dbbuf.databaseid,
4953  HASH_ENTER,
4954  &found);
4955  if (found)
4956  {
4957  ereport(pgStatRunningInCollector ? LOG : WARNING,
4958  (errmsg("corrupted statistics file \"%s\"",
4959  statfile)));
4960  goto done;
4961  }
4962 
4963  memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
4964  dbentry->tables = NULL;
4965  dbentry->functions = NULL;
4966 
4967  /*
4968  * Don't create tables/functions hashtables for uninteresting
4969  * databases.
4970  */
4971  if (onlydb != InvalidOid)
4972  {
4973  if (dbbuf.databaseid != onlydb &&
4974  dbbuf.databaseid != InvalidOid)
4975  break;
4976  }
4977 
4978  memset(&hash_ctl, 0, sizeof(hash_ctl));
4979  hash_ctl.keysize = sizeof(Oid);
4980  hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4981  hash_ctl.hcxt = pgStatLocalContext;
4982  dbentry->tables = hash_create("Per-database table",
4984  &hash_ctl,
4986 
4987  hash_ctl.keysize = sizeof(Oid);
4988  hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4989  hash_ctl.hcxt = pgStatLocalContext;
4990  dbentry->functions = hash_create("Per-database function",
4992  &hash_ctl,
4994 
4995  /*
4996  * If requested, read the data from the database-specific
4997  * file. Otherwise we just leave the hashtables empty.
4998  */
4999  if (deep)
5001  dbentry->tables,
5002  dbentry->functions,
5003  permanent);
5004 
5005  break;
5006 
5007  case 'E':
5008  goto done;
5009 
5010  default:
5011  ereport(pgStatRunningInCollector ? LOG : WARNING,
5012  (errmsg("corrupted statistics file \"%s\"",
5013  statfile)));
5014  goto done;
5015  }
5016  }
5017 
5018 done:
5019  FreeFile(fpin);
5020 
5021  /* If requested to read the permanent file, also get rid of it. */
5022  if (permanent)
5023  {
5024  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5025