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 "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  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 TABSTAT_QUANTUM   100 /* we alloc this many at a time */
 
#define TESTBYTEVAL   ((char) 199)
 

Typedefs

typedef struct TabStatusArray TabStatusArray
 
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 void pgstat_setheader (PgStat_MsgHdr *hdr, StatMsgType mtype)
 
static void pgstat_send (void *msg, int len)
 
static void pgstat_recv_inquiry (PgStat_MsgInquiry *msg, int len)
 
static void pgstat_recv_tabstat (PgStat_MsgTabstat *msg, int len)
 
static void pgstat_recv_tabpurge (PgStat_MsgTabpurge *msg, int len)
 
static void pgstat_recv_dropdb (PgStat_MsgDropdb *msg, int len)
 
static void pgstat_recv_resetcounter (PgStat_MsgResetcounter *msg, int len)
 
static void pgstat_recv_resetsharedcounter (PgStat_MsgResetsharedcounter *msg, int len)
 
static void pgstat_recv_resetsinglecounter (PgStat_MsgResetsinglecounter *msg, int len)
 
static void pgstat_recv_autovac (PgStat_MsgAutovacStart *msg, int len)
 
static void pgstat_recv_vacuum (PgStat_MsgVacuum *msg, int len)
 
static void pgstat_recv_analyze (PgStat_MsgAnalyze *msg, int len)
 
static void pgstat_recv_archiver (PgStat_MsgArchiver *msg, int len)
 
static void pgstat_recv_bgwriter (PgStat_MsgBgWriter *msg, int len)
 
static void pgstat_recv_funcstat (PgStat_MsgFuncstat *msg, int len)
 
static void pgstat_recv_funcpurge (PgStat_MsgFuncpurge *msg, int len)
 
static void pgstat_recv_recoveryconflict (PgStat_MsgRecoveryConflict *msg, int len)
 
static void pgstat_recv_deadlock (PgStat_MsgDeadlock *msg, int len)
 
static void pgstat_recv_tempfile (PgStat_MsgTempFile *msg, int len)
 
void pgstat_init (void)
 
static void pgstat_reset_remove_files (const char *directory)
 
void pgstat_reset_all (void)
 
int pgstat_start (void)
 
void allow_immediate_pgstat_restart (void)
 
void pgstat_report_stat (bool force)
 
void pgstat_vacuum_stat (void)
 
void pgstat_drop_database (Oid databaseid)
 
void pgstat_reset_counters (void)
 
void pgstat_reset_shared_counters (const char *target)
 
void pgstat_reset_single_counter (Oid objoid, PgStat_Single_Reset_Type type)
 
void pgstat_report_autovac (Oid dboid)
 
void pgstat_report_vacuum (Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
 
void pgstat_report_analyze (Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
 
void pgstat_report_recovery_conflict (int reason)
 
void pgstat_report_deadlock (void)
 
void pgstat_report_tempfile (size_t filesize)
 
void pgstat_ping (void)
 
static void pgstat_send_inquiry (TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
 
void pgstat_init_function_usage (FunctionCallInfoData *fcinfo, PgStat_FunctionCallUsage *fcu)
 
PgStat_BackendFunctionEntryfind_funcstat_entry (Oid func_id)
 
void pgstat_end_function_usage (PgStat_FunctionCallUsage *fcu, bool finalize)
 
void pgstat_initstats (Relation rel)
 
PgStat_TableStatusfind_tabstat_entry (Oid rel_id)
 
static PgStat_SubXactStatusget_tabstat_stack_level (int nest_level)
 
static void add_tabstat_xact_level (PgStat_TableStatus *pgstat_info, int nest_level)
 
void pgstat_count_heap_insert (Relation rel, int 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)
 
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 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 PGSTAT_DB_HASH_SIZE   16

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

#define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)

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

#define PGSTAT_POLL_LOOP_COUNT   (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)

Definition at line 92 of file pgstat.c.

Referenced by backend_read_statsfile().

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

Definition at line 88 of file pgstat.c.

Referenced by pgstat_start().

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

Definition at line 79 of file pgstat.c.

Referenced by backend_read_statsfile().

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

Definition at line 76 of file pgstat.c.

Referenced by backend_read_statsfile(), and pgstat_report_stat().

#define PGSTAT_TAB_HASH_SIZE   512

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

Referenced by get_tabstat_entry().

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

1779 {
1780  PgStat_SubXactStatus *xact_state;
1782 
1783  /*
1784  * If this is the first rel to be modified at the current nest level, we
1785  * first have to push a transaction stack entry.
1786  */
1787  xact_state = get_tabstat_stack_level(nest_level);
1788 
1789  /* Now make a per-table stack entry */
1790  trans = (PgStat_TableXactStatus *)
1792  sizeof(PgStat_TableXactStatus));
1793  trans->nest_level = nest_level;
1794  trans->upper = pgstat_info->trans;
1795  trans->parent = pgstat_info;
1796  trans->next = xact_state->first;
1797  xact_state->first = trans;
1798  pgstat_info->trans = trans;
1799 }
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:1756
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:784
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:383
PgStat_TableXactStatus * first
Definition: pgstat.c:186
PgStat_TableStatus * parent
Definition: pgstat.h:177
void allow_immediate_pgstat_restart ( void  )

Definition at line 726 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

727 {
729 }
static time_t last_pgstat_start_time
Definition: pgstat.c:137
void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

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

2035 {
2036  PgStat_SubXactStatus *xact_state;
2037 
2038  /*
2039  * Transfer transactional insert/update counts into the next higher
2040  * subtransaction state.
2041  */
2042  xact_state = pgStatXactStack;
2043  if (xact_state != NULL &&
2044  xact_state->nest_level >= nestDepth)
2045  {
2047  PgStat_TableXactStatus *next_trans;
2048 
2049  /* delink xact_state from stack immediately to simplify reuse case */
2050  pgStatXactStack = xact_state->prev;
2051 
2052  for (trans = xact_state->first; trans != NULL; trans = next_trans)
2053  {
2054  PgStat_TableStatus *tabstat;
2055 
2056  next_trans = trans->next;
2057  Assert(trans->nest_level == nestDepth);
2058  tabstat = trans->parent;
2059  Assert(tabstat->trans == trans);
2060  if (isCommit)
2061  {
2062  if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2063  {
2064  if (trans->truncated)
2065  {
2066  /* propagate the truncate status one level up */
2068  /* replace upper xact stats with ours */
2069  trans->upper->tuples_inserted = trans->tuples_inserted;
2070  trans->upper->tuples_updated = trans->tuples_updated;
2071  trans->upper->tuples_deleted = trans->tuples_deleted;
2072  }
2073  else
2074  {
2075  trans->upper->tuples_inserted += trans->tuples_inserted;
2076  trans->upper->tuples_updated += trans->tuples_updated;
2077  trans->upper->tuples_deleted += trans->tuples_deleted;
2078  }
2079  tabstat->trans = trans->upper;
2080  pfree(trans);
2081  }
2082  else
2083  {
2084  /*
2085  * When there isn't an immediate parent state, we can just
2086  * reuse the record instead of going through a
2087  * palloc/pfree pushup (this works since it's all in
2088  * TopTransactionContext anyway). We have to re-link it
2089  * into the parent level, though, and that might mean
2090  * pushing a new entry into the pgStatXactStack.
2091  */
2092  PgStat_SubXactStatus *upper_xact_state;
2093 
2094  upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2095  trans->next = upper_xact_state->first;
2096  upper_xact_state->first = trans;
2097  trans->nest_level = nestDepth - 1;
2098  }
2099  }
2100  else
2101  {
2102  /*
2103  * On abort, update top-level tabstat counts, then forget the
2104  * subtransaction
2105  */
2106 
2107  /* first restore values obliterated by truncate */
2109  /* count attempted actions regardless of commit/abort */
2110  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2111  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2112  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2113  /* inserted tuples are dead, deleted tuples are unaffected */
2114  tabstat->t_counts.t_delta_dead_tuples +=
2115  trans->tuples_inserted + trans->tuples_updated;
2116  tabstat->trans = trans->upper;
2117  pfree(trans);
2118  }
2119  }
2120  pfree(xact_state);
2121  }
2122 }
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:1756
void pfree(void *pointer)
Definition: mcxt.c:992
PgStat_Counter t_tuples_updated
Definition: pgstat.h:105
static void pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1892
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:185
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:189
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:383
PgStat_TableXactStatus * first
Definition: pgstat.c:186
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1877
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177
void AtEOXact_PgStat ( bool  isCommit)

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

1952 {
1953  PgStat_SubXactStatus *xact_state;
1954 
1955  /*
1956  * Count transaction commit or abort. (We use counters, not just bools,
1957  * in case the reporting message isn't sent right away.)
1958  */
1959  if (isCommit)
1960  pgStatXactCommit++;
1961  else
1963 
1964  /*
1965  * Transfer transactional insert/update counts into the base tabstat
1966  * entries. We don't bother to free any of the transactional state, since
1967  * it's all in TopTransactionContext and will go away anyway.
1968  */
1969  xact_state = pgStatXactStack;
1970  if (xact_state != NULL)
1971  {
1973 
1974  Assert(xact_state->nest_level == 1);
1975  Assert(xact_state->prev == NULL);
1976  for (trans = xact_state->first; trans != NULL; trans = trans->next)
1977  {
1978  PgStat_TableStatus *tabstat;
1979 
1980  Assert(trans->nest_level == 1);
1981  Assert(trans->upper == NULL);
1982  tabstat = trans->parent;
1983  Assert(tabstat->trans == trans);
1984  /* restore pre-truncate stats (if any) in case of aborted xact */
1985  if (!isCommit)
1987  /* count attempted actions regardless of commit/abort */
1988  tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
1989  tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
1990  tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
1991  if (isCommit)
1992  {
1993  tabstat->t_counts.t_truncated = trans->truncated;
1994  if (trans->truncated)
1995  {
1996  /* forget live/dead stats seen by backend thus far */
1997  tabstat->t_counts.t_delta_live_tuples = 0;
1998  tabstat->t_counts.t_delta_dead_tuples = 0;
1999  }
2000  /* insert adds a live tuple, delete removes one */
2001  tabstat->t_counts.t_delta_live_tuples +=
2002  trans->tuples_inserted - trans->tuples_deleted;
2003  /* update and delete each create a dead tuple */
2004  tabstat->t_counts.t_delta_dead_tuples +=
2005  trans->tuples_updated + trans->tuples_deleted;
2006  /* insert, update, delete each count as one change event */
2007  tabstat->t_counts.t_changed_tuples +=
2008  trans->tuples_inserted + trans->tuples_updated +
2009  trans->tuples_deleted;
2010  }
2011  else
2012  {
2013  /* inserted tuples are dead, deleted tuples are unaffected */
2014  tabstat->t_counts.t_delta_dead_tuples +=
2015  trans->tuples_inserted + trans->tuples_updated;
2016  /* an aborted xact generates no changed_tuple events */
2017  }
2018  tabstat->trans = NULL;
2019  }
2020  }
2022 
2023  /* Make sure any stats snapshot is thrown away */
2025 }
PgStat_Counter t_delta_live_tuples
Definition: pgstat.h:110
PgStat_Counter tuples_updated
Definition: pgstat.h:168
static int pgStatXactCommit
Definition: pgstat.c:191
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:1892
static int pgStatXactRollback
Definition: pgstat.c:192
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:185
PgStat_Counter t_changed_tuples
Definition: pgstat.h:112
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5045
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:189
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static zic_t trans[TZ_MAX_LEAPS]
Definition: zic.c:383
PgStat_TableXactStatus * first
Definition: pgstat.c:186
PgStat_Counter t_tuples_inserted
Definition: pgstat.h:104
PgStat_TableStatus * parent
Definition: pgstat.h:177
void AtPrepare_PgStat ( void  )

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

2134 {
2135  PgStat_SubXactStatus *xact_state;
2136 
2137  xact_state = pgStatXactStack;
2138  if (xact_state != NULL)
2139  {
2141 
2142  Assert(xact_state->nest_level == 1);
2143  Assert(xact_state->prev == NULL);
2144  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2145  {
2146  PgStat_TableStatus *tabstat;
2147  TwoPhasePgStatRecord record;
2148 
2149  Assert(trans->nest_level == 1);
2150  Assert(trans->upper == NULL);
2151  tabstat = trans->parent;
2152  Assert(tabstat->trans == trans);
2153 
2154  record.tuples_inserted = trans->tuples_inserted;
2155  record.tuples_updated = trans->tuples_updated;
2156  record.tuples_deleted = trans->tuples_deleted;
2157  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2158  record.updated_pre_trunc = trans->updated_pre_trunc;
2159  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2160  record.t_id = tabstat->t_id;
2161  record.t_shared = tabstat->t_shared;
2162  record.t_truncated = trans->truncated;
2163 
2165  &record, sizeof(TwoPhasePgStatRecord));
2166  }
2167  }
2168 }
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:204
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1121
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter updated_pre_trunc
Definition: pgstat.c:203
PgStat_Counter inserted_pre_trunc
Definition: pgstat.c:202
struct PgStat_TableXactStatus * upper
Definition: pgstat.h:176
PgStat_Counter tuples_updated
Definition: pgstat.c:200
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:185
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
PgStat_Counter inserted_pre_trunc
Definition: pgstat.h:171
PgStat_Counter tuples_inserted
Definition: pgstat.c:199
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:189
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
PgStat_Counter tuples_deleted
Definition: pgstat.c:201
#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:383
PgStat_TableXactStatus * first
Definition: pgstat.c:186
PgStat_TableStatus * parent
Definition: pgstat.h:177
static void backend_read_statsfile ( void  )
static

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

4892 {
4893  TimestampTz min_ts = 0;
4894  TimestampTz ref_ts = 0;
4895  Oid inquiry_db;
4896  int count;
4897 
4898  /* already read it? */
4899  if (pgStatDBHash)
4900  return;
4902 
4903  /*
4904  * In a normal backend, we check staleness of the data for our own DB, and
4905  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
4906  * check staleness of the shared-catalog data, and send InvalidOid in
4907  * inquiry messages so as not to force writing unnecessary data.
4908  */
4910  inquiry_db = InvalidOid;
4911  else
4912  inquiry_db = MyDatabaseId;
4913 
4914  /*
4915  * Loop until fresh enough stats file is available or we ran out of time.
4916  * The stats inquiry message is sent repeatedly in case collector drops
4917  * it; but not every single time, as that just swamps the collector.
4918  */
4919  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
4920  {
4921  bool ok;
4922  TimestampTz file_ts = 0;
4923  TimestampTz cur_ts;
4924 
4926 
4927  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
4928 
4929  cur_ts = GetCurrentTimestamp();
4930  /* Calculate min acceptable timestamp, if we didn't already */
4931  if (count == 0 || cur_ts < ref_ts)
4932  {
4933  /*
4934  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
4935  * msec before now. This indirectly ensures that the collector
4936  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
4937  * an autovacuum worker, however, we want a lower delay to avoid
4938  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
4939  * number of workers is low, this shouldn't be a problem).
4940  *
4941  * We don't recompute min_ts after sleeping, except in the
4942  * unlikely case that cur_ts went backwards. So we might end up
4943  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
4944  * practice that shouldn't happen, though, as long as the sleep
4945  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
4946  * tell the collector that our cutoff time is less than what we'd
4947  * actually accept.
4948  */
4949  ref_ts = cur_ts;
4951  min_ts = TimestampTzPlusMilliseconds(ref_ts,
4953  else
4954  min_ts = TimestampTzPlusMilliseconds(ref_ts,
4956  }
4957 
4958  /*
4959  * If the file timestamp is actually newer than cur_ts, we must have
4960  * had a clock glitch (system time went backwards) or there is clock
4961  * skew between our processor and the stats collector's processor.
4962  * Accept the file, but send an inquiry message anyway to make
4963  * pgstat_recv_inquiry do a sanity check on the collector's time.
4964  */
4965  if (ok && file_ts > cur_ts)
4966  {
4967  /*
4968  * A small amount of clock skew between processors isn't terribly
4969  * surprising, but a large difference is worth logging. We
4970  * arbitrarily define "large" as 1000 msec.
4971  */
4972  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
4973  {
4974  char *filetime;
4975  char *mytime;
4976 
4977  /* Copy because timestamptz_to_str returns a static buffer */
4978  filetime = pstrdup(timestamptz_to_str(file_ts));
4979  mytime = pstrdup(timestamptz_to_str(cur_ts));
4980  elog(LOG, "stats collector's time %s is later than backend local time %s",
4981  filetime, mytime);
4982  pfree(filetime);
4983  pfree(mytime);
4984  }
4985 
4986  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
4987  break;
4988  }
4989 
4990  /* Normal acceptance case: file is not older than cutoff time */
4991  if (ok && file_ts >= min_ts)
4992  break;
4993 
4994  /* Not there or too old, so kick the collector and wait a bit */
4995  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
4996  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
4997 
4998  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
4999  }
5000 
5001  if (count >= PGSTAT_POLL_LOOP_COUNT)
5002  ereport(LOG,
5003  (errmsg("using stale statistics instead of current ones "
5004  "because stats collector is not responding")));
5005 
5006  /*
5007  * Autovacuum launcher wants stats about all databases, but a shallow read
5008  * is sufficient. Regular backends want a deep read for just the tables
5009  * they can see (MyDatabaseId + shared catalogs).
5010  */
5013  else
5015 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:79
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:93
char * pstrdup(const char *in)
Definition: mcxt.c:1165
static bool pgStatRunningInCollector
Definition: pgstat.c:139
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PGSTAT_POLL_LOOP_COUNT
Definition: pgstat.c:92
void pg_usleep(long microsec)
Definition: signal.c:53
double TimestampTz
Definition: timestamp.h:51
void pfree(void *pointer)
Definition: mcxt.c:992
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1488
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:76
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2989
#define ereport(elevel, rest)
Definition: elog.h:122
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:4399
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidOid
Definition: postgres_ext.h:36
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:80
static bool pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent, TimestampTz *ts)
Definition: pgstat.c:4772
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:2983
#define Assert(condition)
Definition: c.h:670
static HTAB * pgStatDBHash
Definition: pgstat.c:214
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:1894
Size BackendStatusShmemSize ( void  )

Definition at line 2502 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2503 {
2504  Size size;
2505 
2506  /* BackendStatusArray: */
2507  size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2508  /* BackendAppnameBuffer: */
2509  size = add_size(size,
2511  /* BackendClientHostnameBuffer: */
2512  size = add_size(size,
2514  /* BackendActivityBuffer: */
2515  size = add_size(size,
2517 #ifdef USE_SSL
2518  /* BackendSslStatusBuffer: */
2519  size = add_size(size,
2521 #endif
2522  return size;
2523 }
#define NAMEDATALEN
int MaxBackends
Definition: globals.c:126
int pgstat_track_activity_query_size
Definition: pgstat.c:112
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:352
void CreateSharedBackendStatus ( void  )

Definition at line 2530 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2531 {
2532  Size size;
2533  bool found;
2534  int i;
2535  char *buffer;
2536 
2537  /* Create or attach to the shared array */
2538  size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2540  ShmemInitStruct("Backend Status Array", size, &found);
2541 
2542  if (!found)
2543  {
2544  /*
2545  * We're the first - initialize.
2546  */
2547  MemSet(BackendStatusArray, 0, size);
2548  }
2549 
2550  /* Create or attach to the shared appname buffer */
2551  size = mul_size(NAMEDATALEN, MaxBackends);
2552  BackendAppnameBuffer = (char *)
2553  ShmemInitStruct("Backend Application Name Buffer", size, &found);
2554 
2555  if (!found)
2556  {
2557  MemSet(BackendAppnameBuffer, 0, size);
2558 
2559  /* Initialize st_appname pointers. */
2560  buffer = BackendAppnameBuffer;
2561  for (i = 0; i < MaxBackends; i++)
2562  {
2563  BackendStatusArray[i].st_appname = buffer;
2564  buffer += NAMEDATALEN;
2565  }
2566  }
2567 
2568  /* Create or attach to the shared client hostname buffer */
2569  size = mul_size(NAMEDATALEN, MaxBackends);
2570  BackendClientHostnameBuffer = (char *)
2571  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2572 
2573  if (!found)
2574  {
2576 
2577  /* Initialize st_clienthostname pointers. */
2578  buffer = BackendClientHostnameBuffer;
2579  for (i = 0; i < MaxBackends; i++)
2580  {
2582  buffer += NAMEDATALEN;
2583  }
2584  }
2585 
2586  /* Create or attach to the shared activity buffer */
2588  MaxBackends);
2589  BackendActivityBuffer = (char *)
2590  ShmemInitStruct("Backend Activity Buffer",
2592  &found);
2593 
2594  if (!found)
2595  {
2596  MemSet(BackendActivityBuffer, 0, size);
2597 
2598  /* Initialize st_activity pointers. */
2599  buffer = BackendActivityBuffer;
2600  for (i = 0; i < MaxBackends; i++)
2601  {
2602  BackendStatusArray[i].st_activity = buffer;
2604  }
2605  }
2606 
2607 #ifdef USE_SSL
2608  /* Create or attach to the shared SSL status buffer */
2609  size = mul_size(sizeof(PgBackendSSLStatus), MaxBackends);
2610  BackendSslStatusBuffer = (PgBackendSSLStatus *)
2611  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2612 
2613  if (!found)
2614  {
2615  PgBackendSSLStatus *ptr;
2616 
2617  MemSet(BackendSslStatusBuffer, 0, size);
2618 
2619  /* Initialize st_sslstatus pointers. */
2620  ptr = BackendSslStatusBuffer;
2621  for (i = 0; i < MaxBackends; i++)
2622  {
2624  ptr++;
2625  }
2626  }
2627 #endif
2628 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2487
static char * BackendActivityBuffer
Definition: pgstat.c:2491
static Size BackendActivityBufferSize
Definition: pgstat.c:2492
#define MemSet(start, val, len)
Definition: c.h:852
char * st_clienthostname
Definition: pgstat.h:883
#define NAMEDATALEN
static char * BackendAppnameBuffer
Definition: pgstat.c:2489
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:112
char * st_appname
Definition: pgstat.h:893
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
char * st_activity
Definition: pgstat.h:896
size_t Size
Definition: c.h:352
int i
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:887
static char * BackendClientHostnameBuffer
Definition: pgstat.c:2490
PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id)

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

1558 {
1559  if (pgStatFunctions == NULL)
1560  return NULL;
1561 
1563  (void *) &func_id,
1564  HASH_FIND, NULL);
1565 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * pgStatFunctions
Definition: pgstat.c:167
#define NULL
Definition: c.h:226
PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

Definition at line 1732 of file pgstat.c.

References i, NULL, PgStat_TableStatus::t_id, TabStatusArray::tsa_entries, TabStatusArray::tsa_next, and TabStatusArray::tsa_used.

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

1733 {
1734  PgStat_TableStatus *entry;
1735  TabStatusArray *tsa;
1736  int i;
1737 
1738  for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
1739  {
1740  for (i = 0; i < tsa->tsa_used; i++)
1741  {
1742  entry = &tsa->tsa_entries[i];
1743  if (entry->t_id == rel_id)
1744  return entry;
1745  }
1746  }
1747 
1748  /* Not present */
1749  return NULL;
1750 }
int tsa_used
Definition: pgstat.c:157
struct TabStatusArray * tsa_next
Definition: pgstat.c:156
PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]
Definition: pgstat.c:158
static TabStatusArray * pgStatTabList
Definition: pgstat.c:161
#define NULL
Definition: c.h:226
int i
static void get_dbstat_filename ( bool  permanent,
bool  tempname,
Oid  databaseid,
char *  filename,
int  len 
)
static

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

4252 {
4253  int printed;
4254 
4255  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4256  printed = snprintf(filename, len, "%s/db_%u.%s",
4257  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4259  databaseid,
4260  tempname ? "tmp" : "stat");
4261  if (printed > len)
4262  elog(ERROR, "overlength pgstat path");
4263 }
#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:118
static char * filename
Definition: pg_dumpall.c:84
#define elog
Definition: elog.h:219
static PgStat_TableStatus * get_tabstat_entry ( Oid  rel_id,
bool  isshared 
)
static

Definition at line 1673 of file pgstat.c.

References i, MemoryContextAllocZero(), NULL, PgStat_TableStatus::t_id, PgStat_TableStatus::t_shared, TABSTAT_QUANTUM, TopMemoryContext, and TabStatusArray::tsa_next.

Referenced by pgstat_initstats(), pgstat_twophase_postabort(), and pgstat_twophase_postcommit().

1674 {
1675  PgStat_TableStatus *entry;
1676  TabStatusArray *tsa;
1677  TabStatusArray *prev_tsa;
1678  int i;
1679 
1680  /*
1681  * Search the already-used tabstat slots for this relation.
1682  */
1683  prev_tsa = NULL;
1684  for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1685  {
1686  for (i = 0; i < tsa->tsa_used; i++)
1687  {
1688  entry = &tsa->tsa_entries[i];
1689  if (entry->t_id == rel_id)
1690  return entry;
1691  }
1692 
1693  if (tsa->tsa_used < TABSTAT_QUANTUM)
1694  {
1695  /*
1696  * It must not be present, but we found a free slot instead. Fine,
1697  * let's use this one. We assume the entry was already zeroed,
1698  * either at creation or after last use.
1699  */
1700  entry = &tsa->tsa_entries[tsa->tsa_used++];
1701  entry->t_id = rel_id;
1702  entry->t_shared = isshared;
1703  return entry;
1704  }
1705  }
1706 
1707  /*
1708  * We ran out of tabstat slots, so allocate more. Be sure they're zeroed.
1709  */
1711  sizeof(TabStatusArray));
1712  if (prev_tsa)
1713  prev_tsa->tsa_next = tsa;
1714  else
1715  pgStatTabList = tsa;
1716 
1717  /*
1718  * Use the first entry of the new TabStatusArray.
1719  */
1720  entry = &tsa->tsa_entries[tsa->tsa_used++];
1721  entry->t_id = rel_id;
1722  entry->t_shared = isshared;
1723  return entry;
1724 }
struct TabStatusArray * tsa_next
Definition: pgstat.c:156
MemoryContext TopMemoryContext
Definition: mcxt.c:43
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:784
static TabStatusArray * pgStatTabList
Definition: pgstat.c:161
#define NULL
Definition: c.h:226
int i
#define TABSTAT_QUANTUM
Definition: pgstat.c:152
static PgStat_SubXactStatus* get_tabstat_stack_level ( int  nest_level)
static

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

1757 {
1758  PgStat_SubXactStatus *xact_state;
1759 
1760  xact_state = pgStatXactStack;
1761  if (xact_state == NULL || xact_state->nest_level != nest_level)
1762  {
1763  xact_state = (PgStat_SubXactStatus *)
1765  sizeof(PgStat_SubXactStatus));
1766  xact_state->nest_level = nest_level;
1767  xact_state->prev = pgStatXactStack;
1768  xact_state->first = NULL;
1769  pgStatXactStack = xact_state;
1770  }
1771  return xact_state;
1772 }
MemoryContext TopTransactionContext
Definition: mcxt.c:48
struct PgStat_SubXactStatus * prev
Definition: pgstat.c:185
#define NULL
Definition: c.h:226
static PgStat_SubXactStatus * pgStatXactStack
Definition: pgstat.c:189
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:749
PgStat_TableXactStatus * first
Definition: pgstat.c:186
static void pgstat_beshutdown_hook ( int  code,
Datum  arg 
)
static

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

2768 {
2769  volatile PgBackendStatus *beentry = MyBEEntry;
2770 
2771  /*
2772  * If we got as far as discovering our own database ID, we can report what
2773  * we did to the collector. Otherwise, we'd be sending an invalid
2774  * database ID, so forget it. (This means that accesses to pg_database
2775  * during failed backend starts might never get counted.)
2776  */
2777  if (OidIsValid(MyDatabaseId))
2778  pgstat_report_stat(true);
2779 
2780  /*
2781  * Clear my status entry, following the protocol of bumping st_changecount
2782  * before and after. We use a volatile pointer here to ensure the
2783  * compiler doesn't try to get cute.
2784  */
2786 
2787  beentry->st_procpid = 0; /* mark invalid */
2788 
2790 }
#define OidIsValid(objectId)
Definition: c.h:533
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
Oid MyDatabaseId
Definition: globals.c:76
int st_procpid
Definition: pgstat.h:871
void pgstat_report_stat(bool force)
Definition: pgstat.c:747
void pgstat_bestart ( void  )

Definition at line 2662 of file pgstat.c.

References application_name, be_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_compression(), be_tls_get_peerdn_name(), be_tls_get_version(), GetCurrentTimestamp(), GetSessionUserId(), InvalidOid, MemSet, MyBEEntry, MyDatabaseId, MyProcPid, MyProcPort, NAMEDATALEN, NULL, pgstat_increment_changecount_after, pgstat_increment_changecount_before, pgstat_report_appname(), pgstat_track_activity_query_size, 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_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, STATE_UNDEFINED, and strlcpy().

Referenced by InitPostgres().

2663 {
2664  TimestampTz proc_start_timestamp;
2665  Oid userid;
2666  SockAddr clientaddr;
2667  volatile PgBackendStatus *beentry;
2668 
2669  /*
2670  * To minimize the time spent modifying the PgBackendStatus entry, fetch
2671  * all the needed data first.
2672  *
2673  * If we have a MyProcPort, use its session start time (for consistency,
2674  * and to save a kernel call).
2675  */
2676  if (MyProcPort)
2677  proc_start_timestamp = MyProcPort->SessionStartTime;
2678  else
2679  proc_start_timestamp = GetCurrentTimestamp();
2680  userid = GetSessionUserId();
2681 
2682  /*
2683  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2684  * If so, use all-zeroes client address, which is dealt with specially in
2685  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2686  */
2687  if (MyProcPort)
2688  memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2689  else
2690  MemSet(&clientaddr, 0, sizeof(clientaddr));
2691 
2692  /*
2693  * Initialize my status entry, following the protocol of bumping
2694  * st_changecount before and after; and make sure it's even afterwards. We
2695  * use a volatile pointer here to ensure the compiler doesn't try to get
2696  * cute.
2697  */
2698  beentry = MyBEEntry;
2699  do
2700  {
2702  } while ((beentry->st_changecount & 1) == 0);
2703 
2704  beentry->st_procpid = MyProcPid;
2705  beentry->st_proc_start_timestamp = proc_start_timestamp;
2706  beentry->st_activity_start_timestamp = 0;
2707  beentry->st_state_start_timestamp = 0;
2708  beentry->st_xact_start_timestamp = 0;
2709  beentry->st_databaseid = MyDatabaseId;
2710  beentry->st_userid = userid;
2711  beentry->st_clientaddr = clientaddr;
2714  NAMEDATALEN);
2715  else
2716  beentry->st_clienthostname[0] = '\0';
2717 #ifdef USE_SSL
2718  if (MyProcPort && MyProcPort->ssl != NULL)
2719  {
2720  beentry->st_ssl = true;
2726  }
2727  else
2728  {
2729  beentry->st_ssl = false;
2730  }
2731 #else
2732  beentry->st_ssl = false;
2733 #endif
2734  beentry->st_state = STATE_UNDEFINED;
2735  beentry->st_appname[0] = '\0';
2736  beentry->st_activity[0] = '\0';
2737  /* Also make sure the last byte in each string area is always 0 */
2738  beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
2739  beentry->st_appname[NAMEDATALEN - 1] = '\0';
2740  beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2743 
2744  /*
2745  * we don't zero st_progress_param here to save cycles; nobody should
2746  * examine it until st_progress_command has been set to something other
2747  * than PROGRESS_COMMAND_INVALID
2748  */
2749 
2751 
2752  /* Update app name to current GUC setting */
2753  if (application_name)
2755 }
bool ssl_compression
Definition: pgstat.h:835
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:837
Oid st_progress_command_target
Definition: pgstat.h:908
int MyProcPid
Definition: globals.c:38
struct Port * MyProcPort
Definition: globals.c:40
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:876
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:836
SockAddr st_clientaddr
Definition: pgstat.h:882
#define MemSet(start, val, len)
Definition: c.h:852
ProgressCommandType st_progress_command
Definition: pgstat.h:907
unsigned int Oid
Definition: postgres_ext.h:31
BackendState st_state
Definition: pgstat.h:890
char * st_clienthostname
Definition: pgstat.h:883
Oid GetSessionUserId(void)
Definition: miscinit.c:317
Oid st_databaseid
Definition: pgstat.h:880
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:126
SockAddr raddr
Definition: libpq-be.h:124
double TimestampTz
Definition: timestamp.h:51
bool be_tls_get_compression(Port *port)
TimestampTz SessionStartTime
Definition: libpq-be.h:153
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
int pgstat_track_activity_query_size
Definition: pgstat.c:112
TimestampTz st_state_start_timestamp
Definition: pgstat.h:877
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
char * st_appname
Definition: pgstat.h:893
int be_tls_get_cipher_bits(Port *port)
Oid MyDatabaseId
Definition: globals.c:76
void be_tls_get_version(Port *port, char *ptr, size_t len)
void pgstat_report_appname(const char *appname)
Definition: pgstat.c:2974
#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
#define NULL
Definition: c.h:226
char * st_activity
Definition: pgstat.h:896
int st_procpid
Definition: pgstat.h:871
char * application_name
Definition: guc.c:471
void be_tls_get_cipher(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:875
int st_changecount
Definition: pgstat.h:868
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:874
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:887
char ssl_clientdn[NAMEDATALEN]
Definition: pgstat.h:838
void pgstat_clear_snapshot ( void  )

Definition at line 5045 of file pgstat.c.

References localNumBackends, MemoryContextDelete(), and NULL.

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

5046 {
5047  /* Release memory, if any was allocated */
5048  if (pgStatLocalContext)
5050 
5051  /* Reset variables */
5053  pgStatDBHash = NULL;
5055  localNumBackends = 0;
5056 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define NULL
Definition: c.h:226
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:215
static HTAB * pgStatDBHash
Definition: pgstat.c:214
static int localNumBackends
Definition: pgstat.c:216
static MemoryContext pgStatLocalContext
Definition: pgstat.c:213
static HTAB * pgstat_collect_oids ( Oid  catalogid)
static

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

1129 {
1130  HTAB *htab;
1131  HASHCTL hash_ctl;
1132  Relation rel;
1133  HeapScanDesc scan;
1134  HeapTuple tup;
1135  Snapshot snapshot;
1136 
1137  memset(&hash_ctl, 0, sizeof(hash_ctl));
1138  hash_ctl.keysize = sizeof(Oid);
1139  hash_ctl.entrysize = sizeof(Oid);
1140  hash_ctl.hcxt = CurrentMemoryContext;
1141  htab = hash_create("Temporary table of OIDs",
1143  &hash_ctl,
1145 
1146  rel = heap_open(catalogid, AccessShareLock);
1147  snapshot = RegisterSnapshot(GetLatestSnapshot());
1148  scan = heap_beginscan(rel, snapshot, 0, NULL);
1149  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1150  {
1151  Oid thisoid = HeapTupleGetOid(tup);
1152 
1154 
1155  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1156  }
1157  heap_endscan(scan);
1158  UnregisterSnapshot(snapshot);
1160 
1161  return htab;
1162 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
#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:101
#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:1781
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
Size keysize
Definition: hsearch.h:72
#define NULL
Definition: c.h:226
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:1394
void pgstat_count_heap_delete ( Relation  rel)

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

1852 {
1853  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1854 
1855  if (pgstat_info != NULL)
1856  {
1857  /* We have to log the effect at the proper transactional level */
1858  int nest_level = GetCurrentTransactionNestLevel();
1859 
1860  if (pgstat_info->trans == NULL ||
1861  pgstat_info->trans->nest_level != nest_level)
1862  add_tabstat_xact_level(pgstat_info, nest_level);
1863 
1864  pgstat_info->trans->tuples_deleted++;
1865  }
1866 }
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:760
#define NULL
Definition: c.h:226
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:214
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1778
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_heap_insert ( Relation  rel,
int  n 
)

Definition at line 1805 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 heap_insert(), and heap_multi_insert().

1806 {
1807  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1808 
1809  if (pgstat_info != NULL)
1810  {
1811  /* We have to log the effect at the proper transactional level */
1812  int nest_level = GetCurrentTransactionNestLevel();
1813 
1814  if (pgstat_info->trans == NULL ||
1815  pgstat_info->trans->nest_level != nest_level)
1816  add_tabstat_xact_level(pgstat_info, nest_level);
1817 
1818  pgstat_info->trans->tuples_inserted += n;
1819  }
1820 }
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:760
#define NULL
Definition: c.h:226
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:214
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1778
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

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

1827 {
1828  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1829 
1830  if (pgstat_info != NULL)
1831  {
1832  /* We have to log the effect at the proper transactional level */
1833  int nest_level = GetCurrentTransactionNestLevel();
1834 
1835  if (pgstat_info->trans == NULL ||
1836  pgstat_info->trans->nest_level != nest_level)
1837  add_tabstat_xact_level(pgstat_info, nest_level);
1838 
1839  pgstat_info->trans->tuples_updated++;
1840 
1841  /* t_tuples_hot_updated is nontransactional, so just advance it */
1842  if (hot)
1843  pgstat_info->t_counts.t_tuples_hot_updated++;
1844  }
1845 }
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:760
#define NULL
Definition: c.h:226
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:214
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1778
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_truncate ( Relation  rel)

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

1907 {
1908  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1909 
1910  if (pgstat_info != NULL)
1911  {
1912  /* We have to log the effect at the proper transactional level */
1913  int nest_level = GetCurrentTransactionNestLevel();
1914 
1915  if (pgstat_info->trans == NULL ||
1916  pgstat_info->trans->nest_level != nest_level)
1917  add_tabstat_xact_level(pgstat_info, nest_level);
1918 
1919  pgstat_truncate_save_counters(pgstat_info->trans);
1920  pgstat_info->trans->tuples_inserted = 0;
1921  pgstat_info->trans->tuples_updated = 0;
1922  pgstat_info->trans->tuples_deleted = 0;
1923  }
1924 }
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:760
#define NULL
Definition: c.h:226
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:214
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1778
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1877
static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 5749 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

5750 {
5751  /*
5752  * If any requests are outstanding at all, we should write the stats for
5753  * shared catalogs (the "database" with OID 0). This ensures that
5754  * backends will see up-to-date stats for shared catalogs, even though
5755  * they send inquiry messages mentioning only their own DB.
5756  */
5757  if (databaseid == InvalidOid && pending_write_requests != NIL)
5758  return true;
5759 
5760  /* Search to see if there's an open request to write this database. */
5761  if (list_member_oid(pending_write_requests, databaseid))
5762  return true;
5763 
5764  return false;
5765 }
#define NIL
Definition: pg_list.h:69
static List * pending_write_requests
Definition: pgstat.c:231
#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 1174 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().

1175 {
1176  PgStat_MsgDropdb msg;
1177 
1179  return;
1180 
1182  msg.m_databaseid = databaseid;
1183  pgstat_send(&msg, sizeof(msg));
1184 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:3617
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:133
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:3604
void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1577 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 EventTriggerInvoke(), ExecCallTriggerFunc(), ExecMakeFunctionResultNoSets(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

1578 {
1579  PgStat_FunctionCounts *fs = fcu->fs;
1580  instr_time f_total;
1581  instr_time f_others;
1582  instr_time f_self;
1583 
1584  /* stats not wanted? */
1585  if (fs == NULL)
1586  return;
1587 
1588  /* total elapsed time in this function call */
1589  INSTR_TIME_SET_CURRENT(f_total);
1590  INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1591 
1592  /* self usage: elapsed minus anything already charged to other calls */
1593  f_others = total_func_time;
1594  INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1595  f_self = f_total;
1596  INSTR_TIME_SUBTRACT(f_self, f_others);
1597 
1598  /* update backend-wide total time */
1600 
1601  /*
1602  * Compute the new f_total_time as the total elapsed time added to the
1603  * pre-call value of f_total_time. This is necessary to avoid
1604  * double-counting any time taken by recursive calls of myself. (We do
1605  * not need any similar kluge for self time, since that already excludes
1606  * any recursive calls.)
1607  */
1608  INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1609 
1610  /* update counters in function stats table */
1611  if (finalize)
1612  fs->f_numcalls++;
1613  fs->f_total_time = f_total;
1614  INSTR_TIME_ADD(fs->f_self_time, f_self);
1615 
1616  /* indicate that we have something to send */
1617  have_function_stats = true;
1618 }
instr_time f_self_time
Definition: pgstat.h:463
instr_time f_start
Definition: pgstat.h:990
instr_time save_total
Definition: pgstat.h:988
struct timeval instr_time
Definition: instr_time.h:147
instr_time f_total_time
Definition: pgstat.h:462
PgStat_FunctionCounts * fs
Definition: pgstat.h:984
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:242
static bool have_function_stats
Definition: pgstat.c:173
#define NULL
Definition: c.h:226
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:986
static void pgstat_exit ( SIGNAL_ARGS  )
static

Definition at line 3958 of file pgstat.c.

References MyLatch, need_exit, and SetLatch().

Referenced by PgstatCollectorMain().

3959 {
3960  int save_errno = errno;
3961 
3962  need_exit = true;
3963  SetLatch(MyLatch);
3964 
3965  errno = save_errno;
3966 }
static volatile bool need_exit
Definition: pgstat.c:234
void SetLatch(volatile Latch *latch)
Definition: latch.c:380
struct Latch * MyLatch
Definition: globals.c:51
PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2457 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2458 {
2460 
2461  return &archiverStats;
2462 }
static void backend_read_statsfile(void)
Definition: pgstat.c:4891
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:223
PgBackendStatus* pgstat_fetch_stat_beentry ( int  beid)
PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid)

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

2286 {
2287  /*
2288  * If not done for this transaction, read the statistics collector stats
2289  * file into some hash tables.
2290  */
2292 
2293  /*
2294  * Lookup the requested database; return NULL if not found
2295  */
2297  (void *) &dbid,
2298  HASH_FIND, NULL);
2299 }
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:4891
#define NULL
Definition: c.h:226
static HTAB * pgStatDBHash
Definition: pgstat.c:214
PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  func_id)

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

2369 {
2370  PgStat_StatDBEntry *dbentry;
2371  PgStat_StatFuncEntry *funcentry = NULL;
2372 
2373  /* load the stats file if needed */
2375 
2376  /* Lookup our database, then find the requested function. */
2378  if (dbentry != NULL && dbentry->functions != NULL)
2379  {
2380  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2381  (void *) &func_id,
2382  HASH_FIND, NULL);
2383  }
2384 
2385  return funcentry;
2386 }
HTAB * functions
Definition: pgstat.h:607
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2285
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:4891
Oid MyDatabaseId
Definition: globals.c:76
#define NULL
Definition: c.h:226
LocalPgBackendStatus* pgstat_fetch_stat_local_beentry ( int  beid)

Definition at line 2422 of file pgstat.c.

References localNumBackends, NULL, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

2423 {
2425 
2426  if (beid < 1 || beid > localNumBackends)
2427  return NULL;
2428 
2429  return &localBackendStatusTable[beid - 1];
2430 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3028
#define NULL
Definition: c.h:226
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:215
static int localNumBackends
Definition: pgstat.c:216
int pgstat_fetch_stat_numbackends ( void  )

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

2442 {
2444 
2445  return localNumBackends;
2446 }
static void pgstat_read_current_status(void)
Definition: pgstat.c:3028
static int localNumBackends
Definition: pgstat.c:216
PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid)

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

2313 {
2314  Oid dbid;
2315  PgStat_StatDBEntry *dbentry;
2316  PgStat_StatTabEntry *tabentry;
2317 
2318  /*
2319  * If not done for this transaction, read the statistics collector stats
2320  * file into some hash tables.
2321  */
2323 
2324  /*
2325  * Lookup our database, then look in its table hash table.
2326  */
2327  dbid = MyDatabaseId;
2329  (void *) &dbid,
2330  HASH_FIND, NULL);
2331  if (dbentry != NULL && dbentry->tables != NULL)
2332  {
2333  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2334  (void *) &relid,
2335  HASH_FIND, NULL);
2336  if (tabentry)
2337  return tabentry;
2338  }
2339 
2340  /*
2341  * If we didn't find it, maybe it's a shared table.
2342  */
2343  dbid = InvalidOid;
2345  (void *) &dbid,
2346  HASH_FIND, NULL);
2347  if (dbentry != NULL && dbentry->tables != NULL)
2348  {
2349  tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2350  (void *) &relid,
2351  HASH_FIND, NULL);
2352  if (tabentry)
2353  return tabentry;
2354  }
2355 
2356  return NULL;
2357 }
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:4891
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
static HTAB * pgStatDBHash
Definition: pgstat.c:214
const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

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

3459 {
3460  PgBackendStatus *beentry;
3461  int i;
3462 
3463  beentry = BackendStatusArray;
3464  for (i = 1; i <= MaxBackends; i++)
3465  {
3466  /*
3467  * Although we expect the target backend's entry to be stable, that
3468  * doesn't imply that anyone else's is. To avoid identifying the
3469  * wrong backend, while we check for a match to the desired PID we
3470  * must follow the protocol of retrying if st_changecount changes
3471  * while we examine the entry, or if it's odd. (This might be
3472  * unnecessary, since fetching or storing an int is almost certainly
3473  * atomic, but let's play it safe.) We use a volatile pointer here to
3474  * ensure the compiler doesn't try to get cute.
3475  */
3476  volatile PgBackendStatus *vbeentry = beentry;
3477  bool found;
3478 
3479  for (;;)
3480  {
3481  int before_changecount;
3482  int after_changecount;
3483 
3484  pgstat_save_changecount_before(vbeentry, before_changecount);
3485 
3486  found = (vbeentry->st_procpid == pid);
3487 
3488  pgstat_save_changecount_after(vbeentry, after_changecount);
3489 
3490  if (before_changecount == after_changecount &&
3491  (before_changecount & 1) == 0)
3492  break;
3493 
3494  /* Make sure we can break out of loop if stuck... */
3496  }
3497 
3498  if (found)
3499  {
3500  /* Now it is safe to use the non-volatile pointer */
3501  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
3502  return "<insufficient privilege>";
3503  else if (*(beentry->st_activity) == '\0')
3504  return "<command string not enabled>";
3505  else
3506  return beentry->st_activity;
3507  }
3508 
3509  beentry++;
3510  }
3511 
3512  /* If we get here, caller is in error ... */
3513  return "<backend information not available>";
3514 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2487
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:937
char * st_activity
Definition: pgstat.h:896
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:943
int st_procpid
Definition: pgstat.h:871
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
const char* pgstat_get_crashed_backend_activity ( int  pid,
char *  buffer,
int  buflen 
)

Definition at line 3533 of file pgstat.c.

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

Referenced by LogChildExit().

3534 {
3535  volatile PgBackendStatus *beentry;
3536  int i;
3537 
3538  beentry = BackendStatusArray;
3539 
3540  /*
3541  * We probably shouldn't get here before shared memory has been set up,
3542  * but be safe.
3543  */
3544  if (beentry == NULL || BackendActivityBuffer == NULL)
3545  return NULL;
3546 
3547  for (i = 1; i <= MaxBackends; i++)
3548  {
3549  if (beentry->st_procpid == pid)
3550  {
3551  /* Read pointer just once, so it can't change after validation */
3552  const char *activity = beentry->st_activity;
3553  const char *activity_last;
3554 
3555  /*
3556  * We mustn't access activity string before we verify that it
3557  * falls within the BackendActivityBuffer. To make sure that the
3558  * entire string including its ending is contained within the
3559  * buffer, subtract one activity length from the buffer size.
3560  */
3563 
3564  if (activity < BackendActivityBuffer ||
3565  activity > activity_last)
3566  return NULL;
3567 
3568  /* If no string available, no point in a report */
3569  if (activity[0] == '\0')
3570  return NULL;
3571 
3572  /*
3573  * Copy only ASCII-safe characters so we don't run into encoding
3574  * problems when reporting the message; and be sure not to run off
3575  * the end of memory.
3576  */
3577  ascii_safe_strlcpy(buffer, activity,
3578  Min(buflen, pgstat_track_activity_query_size));
3579 
3580  return buffer;
3581  }
3582 
3583  beentry++;
3584  }
3585 
3586  /* PID not found */
3587  return NULL;
3588 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2487
static char * BackendActivityBuffer
Definition: pgstat.c:2491
#define Min(x, y)
Definition: c.h:801
static Size BackendActivityBufferSize
Definition: pgstat.c:2492
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:112
#define NULL
Definition: c.h:226
char * st_activity
Definition: pgstat.h:896
int st_procpid
Definition: pgstat.h:871
int i
static PgStat_StatDBEntry * pgstat_get_db_entry ( Oid  databaseid,
bool  create 
)
static

Definition at line 4036 of file pgstat.c.

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

Referenced by pgstat_recv_analyze(), pgstat_recv_autovac(), pgstat_recv_deadlock(), pgstat_recv_dropdb(), pgstat_recv_funcpurge(), pgstat_recv_funcstat(), pgstat_recv_inquiry(), pgstat_recv_recoveryconflict(), pgstat_recv_resetcounter(), pgstat_recv_resetsinglecounter(), pgstat_recv_tabpurge(), pgstat_recv_tabstat(), pgstat_recv_tempfile(), and pgstat_recv_vacuum().

4037 {
4038  PgStat_StatDBEntry *result;
4039  bool found;
4040  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4041 
4042  /* Lookup or create the hash table entry for this database */
4044  &databaseid,
4045  action, &found);
4046 
4047  if (!create && !found)
4048  return NULL;
4049 
4050  /*
4051  * If not found, initialize the new one. This creates empty hash tables
4052  * for tables and functions, too.
4053  */
4054  if (!found)
4055  reset_dbentry_counters(result);
4056 
4057  return result;
4058 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:3986
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define NULL
Definition: c.h:226
static HTAB * pgStatDBHash
Definition: pgstat.c:214
HASHACTION
Definition: hsearch.h:103
static PgStat_StatTabEntry * pgstat_get_tab_entry ( PgStat_StatDBEntry dbentry,
Oid  tableoid,
bool  create 
)
static

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

4068 {
4069  PgStat_StatTabEntry *result;
4070  bool found;
4071  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4072 
4073  /* Lookup or create the hash table entry for this table */
4074  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4075  &tableoid,
4076  action, &found);
4077 
4078  if (!create && !found)
4079  return NULL;
4080 
4081  /* If not found, initialize the new one. */
4082  if (!found)
4083  {
4084  result->numscans = 0;
4085  result->tuples_returned = 0;
4086  result->tuples_fetched = 0;
4087  result->tuples_inserted = 0;
4088  result->tuples_updated = 0;
4089  result->tuples_deleted = 0;
4090  result->tuples_hot_updated = 0;
4091  result->n_live_tuples = 0;
4092  result->n_dead_tuples = 0;
4093  result->changes_since_analyze = 0;
4094  result->blocks_fetched = 0;
4095  result->blocks_hit = 0;
4096  result->vacuum_timestamp = 0;
4097  result->vacuum_count = 0;
4098  result->autovac_vacuum_timestamp = 0;
4099  result->autovac_vacuum_count = 0;
4100  result->analyze_timestamp = 0;
4101  result->analyze_count = 0;
4102  result->autovac_analyze_timestamp = 0;
4103  result->autovac_analyze_count = 0;
4104  }
4105 
4106  return result;
4107 }
PgStat_Counter analyze_count
Definition: pgstat.h:641
PgStat_Counter tuples_returned
Definition: pgstat.h:621
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:642
PgStat_Counter vacuum_count
Definition: pgstat.h:637
PgStat_Counter numscans
Definition: pgstat.h:619
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c: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:226
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 3264 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().

3265 {
3266  const char *event_name = "unknown wait event";
3267 
3268  switch (w)
3269  {
3271  event_name = "ArchiverMain";
3272  break;
3274  event_name = "AutoVacuumMain";
3275  break;
3277  event_name = "BgWriterHibernate";
3278  break;
3280  event_name = "BgWriterMain";
3281  break;
3283  event_name = "CheckpointerMain";
3284  break;
3286  event_name = "PgStatMain";
3287  break;
3289  event_name = "RecoveryWalAll";
3290  break;
3292  event_name = "RecoveryWalStream";
3293  break;
3295  event_name = "SysLoggerMain";
3296  break;
3298  event_name = "WalReceiverMain";
3299  break;
3301  event_name = "WalSenderMain";
3302  break;
3304  event_name = "WalWriterMain";
3305  break;
3307  event_name = "LogicalLauncherMain";
3308  break;
3310  event_name = "LogicalApplyMain";
3311  break;
3312  /* no default case, so that compiler will warn */
3313  }
3314 
3315  return event_name;
3316 }
static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3325 of file pgstat.c.

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

3326 {
3327  const char *event_name = "unknown wait event";
3328 
3329  switch (w)
3330  {
3332  event_name = "ClientRead";
3333  break;
3335  event_name = "ClientWrite";
3336  break;
3338  event_name = "SSLOpenServer";
3339  break;
3341  event_name = "WalReceiverWaitStart";
3342  break;
3344  event_name = "LibPQWalReceiverRead";
3345  break;
3347  event_name = "WalSenderWaitForWAL";
3348  break;
3350  event_name = "WalSenderWriteData";
3351  break;
3352  /* no default case, so that compiler will warn */
3353  }
3354 
3355  return event_name;
3356 }
const char* pgstat_get_wait_event ( uint32  wait_event_info)

Definition at line 3194 of file pgstat.c.

References GetLockNameFromTagType(), GetLWLockIdentifier(), NULL, PG_WAIT_ACTIVITY, PG_WAIT_BUFFER_PIN, PG_WAIT_CLIENT, PG_WAIT_EXTENSION, PG_WAIT_IPC, PG_WAIT_LOCK, PG_WAIT_LWLOCK, PG_WAIT_TIMEOUT, pgstat_get_wait_activity(), pgstat_get_wait_client(), pgstat_get_wait_ipc(), and pgstat_get_wait_timeout().

Referenced by pg_stat_get_activity(), and pg_stat_get_backend_wait_event().

3195 {
3196  uint32 classId;
3197  uint16 eventId;
3198  const char *event_name;
3199 
3200  /* report process as not waiting. */
3201  if (wait_event_info == 0)
3202  return NULL;
3203 
3204  classId = wait_event_info & 0xFF000000;
3205  eventId = wait_event_info & 0x0000FFFF;
3206 
3207  switch (classId)
3208  {
3209  case PG_WAIT_LWLOCK:
3210  event_name = GetLWLockIdentifier(classId, eventId);
3211  break;
3212  case PG_WAIT_LOCK:
3213  event_name = GetLockNameFromTagType(eventId);
3214  break;
3215  case PG_WAIT_BUFFER_PIN:
3216  event_name = "BufferPin";
3217  break;
3218  case PG_WAIT_ACTIVITY:
3219  {
3220  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3221 
3222  event_name = pgstat_get_wait_activity(w);
3223  break;
3224  }
3225  case PG_WAIT_CLIENT:
3226  {
3227  WaitEventClient w = (WaitEventClient) wait_event_info;
3228 
3229  event_name = pgstat_get_wait_client(w);
3230  break;
3231  }
3232  case PG_WAIT_EXTENSION:
3233  event_name = "Extension";
3234  break;
3235  case PG_WAIT_IPC:
3236  {
3237  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3238 
3239  event_name = pgstat_get_wait_ipc(w);
3240  break;
3241  }
3242  case PG_WAIT_TIMEOUT:
3243  {
3244  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3245 
3246  event_name = pgstat_get_wait_timeout(w);
3247  break;
3248  }
3249  default:
3250  event_name = "unknown wait event";
3251  break;
3252  }
3253 
3254  return event_name;
3255 }
#define PG_WAIT_LOCK
Definition: pgstat.h:719
WaitEventIPC
Definition: pgstat.h:779
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3417
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3365
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:721
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3264
unsigned short uint16
Definition: c.h:264
#define PG_WAIT_CLIENT
Definition: pgstat.h:722
WaitEventClient
Definition: pgstat.h:761
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3325
unsigned int uint32
Definition: c.h:265
WaitEventTimeout
Definition: pgstat.h:800
#define PG_WAIT_EXTENSION
Definition: pgstat.h:723
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:720
#define NULL
Definition: c.h:226
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1039
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:725
#define PG_WAIT_IPC
Definition: pgstat.h:724
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:702
#define PG_WAIT_LWLOCK
Definition: pgstat.h:718
WaitEventActivity
Definition: pgstat.h:735
const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

Definition at line 3142 of file pgstat.c.

References NULL, PG_WAIT_ACTIVITY, PG_WAIT_BUFFER_PIN, PG_WAIT_CLIENT, PG_WAIT_EXTENSION, 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().

3143 {
3144  uint32 classId;
3145  const char *event_type;
3146 
3147  /* report process as not waiting. */
3148  if (wait_event_info == 0)
3149  return NULL;
3150 
3151  classId = wait_event_info & 0xFF000000;
3152 
3153  switch (classId)
3154  {
3155  case PG_WAIT_LWLOCK:
3156  event_type = "LWLock";
3157  break;
3158  case PG_WAIT_LOCK:
3159  event_type = "Lock";
3160  break;
3161  case PG_WAIT_BUFFER_PIN:
3162  event_type = "BufferPin";
3163  break;
3164  case PG_WAIT_ACTIVITY:
3165  event_type = "Activity";
3166  break;
3167  case PG_WAIT_CLIENT:
3168  event_type = "Client";
3169  break;
3170  case PG_WAIT_EXTENSION:
3171  event_type = "Extension";
3172  break;
3173  case PG_WAIT_IPC:
3174  event_type = "IPC";
3175  break;
3176  case PG_WAIT_TIMEOUT:
3177  event_type = "Timeout";
3178  break;
3179  default:
3180  event_type = "???";
3181  break;
3182  }
3183 
3184  return event_type;
3185 }
#define PG_WAIT_LOCK
Definition: pgstat.h:719
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:721
#define PG_WAIT_CLIENT
Definition: pgstat.h:722
unsigned int uint32
Definition: c.h:265
#define PG_WAIT_EXTENSION
Definition: pgstat.h:723
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:720
#define NULL
Definition: c.h:226
#define PG_WAIT_TIMEOUT
Definition: pgstat.h:725
#define PG_WAIT_IPC
Definition: pgstat.h:724
#define PG_WAIT_LWLOCK
Definition: pgstat.h:718
static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3365 of file pgstat.c.

References WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WAIT_EVENT_BTREE_PAGE, WAIT_EVENT_EXECUTE_GATHER, WAIT_EVENT_MQ_INTERNAL, WAIT_EVENT_MQ_PUT_MESSAGE, WAIT_EVENT_MQ_RECEIVE, WAIT_EVENT_MQ_SEND, WAIT_EVENT_PARALLEL_FINISH, WAIT_EVENT_SAFE_SNAPSHOT, and WAIT_EVENT_SYNC_REP.

Referenced by pgstat_get_wait_event().

3366 {
3367  const char *event_name = "unknown wait event";
3368 
3369  switch (w)
3370  {
3372  event_name = "BgWorkerShutdown";
3373  break;
3375  event_name = "BgWorkerStartup";
3376  break;
3377  case WAIT_EVENT_BTREE_PAGE:
3378  event_name = "BtreePage";
3379  break;
3381  event_name = "ExecuteGather";
3382  break;
3384  event_name = "MessageQueueInternal";
3385  break;
3387  event_name = "MessageQueuePutMessage";
3388  break;
3389  case WAIT_EVENT_MQ_RECEIVE:
3390  event_name = "MessageQueueReceive";
3391  break;
3392  case WAIT_EVENT_MQ_SEND:
3393  event_name = "MessageQueueSend";
3394  break;
3396  event_name = "ParallelFinish";
3397  break;
3399  event_name = "SafeSnapshot";
3400  break;
3401  case WAIT_EVENT_SYNC_REP:
3402  event_name = "SyncRep";
3403  break;
3404  /* no default case, so that compiler will warn */
3405  }
3406 
3407  return event_name;
3408 }
static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

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

3418 {
3419  const char *event_name = "unknown wait event";
3420 
3421  switch (w)
3422  {
3424  event_name = "BaseBackupThrottle";
3425  break;
3426  case WAIT_EVENT_PG_SLEEP:
3427  event_name = "PgSleep";
3428  break;
3430  event_name = "RecoveryApplyDelay";
3431  break;
3432  /* no default case, so that compiler will warn */
3433  }
3434 
3435  return event_name;
3436 }
void pgstat_init ( void  )

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

321 {
322  ACCEPT_TYPE_ARG3 alen;
323  struct addrinfo *addrs = NULL,
324  *addr,
325  hints;
326  int ret;
327  fd_set rset;
328  struct timeval tv;
329  char test_byte;
330  int sel_res;
331  int tries = 0;
332 
333 #define TESTBYTEVAL ((char) 199)
334 
335  /*
336  * This static assertion verifies that we didn't mess up the calculations
337  * involved in selecting maximum payload sizes for our UDP messages.
338  * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
339  * be silent performance loss from fragmentation, it seems worth having a
340  * compile-time cross-check that we didn't.
341  */
343  "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
344 
345  /*
346  * Create the UDP socket for sending and receiving statistic messages
347  */
348  hints.ai_flags = AI_PASSIVE;
349  hints.ai_family = AF_UNSPEC;
350  hints.ai_socktype = SOCK_DGRAM;
351  hints.ai_protocol = 0;
352  hints.ai_addrlen = 0;
353  hints.ai_addr = NULL;
354  hints.ai_canonname = NULL;
355  hints.ai_next = NULL;
356  ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
357  if (ret || !addrs)
358  {
359  ereport(LOG,
360  (errmsg("could not resolve \"localhost\": %s",
361  gai_strerror(ret))));
362  goto startup_failed;
363  }
364 
365  /*
366  * On some platforms, pg_getaddrinfo_all() may return multiple addresses
367  * only one of which will actually work (eg, both IPv6 and IPv4 addresses
368  * when kernel will reject IPv6). Worse, the failure may occur at the
369  * bind() or perhaps even connect() stage. So we must loop through the
370  * results till we find a working combination. We will generate LOG
371  * messages, but no error, for bogus combinations.
372  */
373  for (addr = addrs; addr; addr = addr->ai_next)
374  {
375 #ifdef HAVE_UNIX_SOCKETS
376  /* Ignore AF_UNIX sockets, if any are returned. */
377  if (addr->ai_family == AF_UNIX)
378  continue;
379 #endif
380 
381  if (++tries > 1)
382  ereport(LOG,
383  (errmsg("trying another address for the statistics collector")));
384 
385  /*
386  * Create the socket.
387  */
388  if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
389  {
390  ereport(LOG,
392  errmsg("could not create socket for statistics collector: %m")));
393  continue;
394  }
395 
396  /*
397  * Bind it to a kernel assigned port on localhost and get the assigned
398  * port via getsockname().
399  */
400  if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
401  {
402  ereport(LOG,
404  errmsg("could not bind socket for statistics collector: %m")));
407  continue;
408  }
409 
410  alen = sizeof(pgStatAddr);
411  if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
412  {
413  ereport(LOG,
415  errmsg("could not get address of socket for statistics collector: %m")));
418  continue;
419  }
420 
421  /*
422  * Connect the socket to its own address. This saves a few cycles by
423  * not having to respecify the target address on every send. This also
424  * provides a kernel-level check that only packets from this same
425  * address will be received.
426  */
427  if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
428  {
429  ereport(LOG,
431  errmsg("could not connect socket for statistics collector: %m")));
434  continue;
435  }
436 
437  /*
438  * Try to send and receive a one-byte test message on the socket. This
439  * is to catch situations where the socket can be created but will not
440  * actually pass data (for instance, because kernel packet filtering
441  * rules prevent it).
442  */
443  test_byte = TESTBYTEVAL;
444 
445 retry1:
446  if (send(pgStatSock, &test_byte, 1, 0) != 1)
447  {
448  if (errno == EINTR)
449  goto retry1; /* if interrupted, just retry */
450  ereport(LOG,
452  errmsg("could not send test message on socket for statistics collector: %m")));
455  continue;
456  }
457 
458  /*
459  * There could possibly be a little delay before the message can be
460  * received. We arbitrarily allow up to half a second before deciding
461  * it's broken.
462  */
463  for (;;) /* need a loop to handle EINTR */
464  {
465  FD_ZERO(&rset);
466  FD_SET(pgStatSock, &rset);
467 
468  tv.tv_sec = 0;
469  tv.tv_usec = 500000;
470  sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
471  if (sel_res >= 0 || errno != EINTR)
472  break;
473  }
474  if (sel_res < 0)
475  {
476  ereport(LOG,
478  errmsg("select() failed in statistics collector: %m")));
481  continue;
482  }
483  if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
484  {
485  /*
486  * This is the case we actually think is likely, so take pains to
487  * give a specific message for it.
488  *
489  * errno will not be set meaningfully here, so don't use it.
490  */
491  ereport(LOG,
492  (errcode(ERRCODE_CONNECTION_FAILURE),
493  errmsg("test message did not get through on socket for statistics collector")));
496  continue;
497  }
498 
499  test_byte++; /* just make sure variable is changed */
500 
501 retry2:
502  if (recv(pgStatSock, &test_byte, 1, 0) != 1)
503  {
504  if (errno == EINTR)
505  goto retry2; /* if interrupted, just retry */
506  ereport(LOG,
508  errmsg("could not receive test message on socket for statistics collector: %m")));
511  continue;
512  }
513 
514  if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
515  {
516  ereport(LOG,
517  (errcode(ERRCODE_INTERNAL_ERROR),
518  errmsg("incorrect test message transmission on socket for statistics collector")));
521  continue;
522  }
523 
524  /* If we get here, we have a working socket */
525  break;
526  }
527 
528  /* Did we find a working address? */
529  if (!addr || pgStatSock == PGINVALID_SOCKET)
530  goto startup_failed;
531 
532  /*
533  * Set the socket to non-blocking IO. This ensures that if the collector
534  * falls behind, statistics messages will be discarded; backends won't
535  * block waiting to send messages to the collector.
536  */
538  {
539  ereport(LOG,
541  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
542  goto startup_failed;
543  }
544 
545  pg_freeaddrinfo_all(hints.ai_family, addrs);
546 
547  return;
548 
549 startup_failed:
550  ereport(LOG,
551  (errmsg("disabling statistics collector for lack of working socket")));
552 
553  if (addrs)
554  pg_freeaddrinfo_all(hints.ai_family, addrs);
555 
559 
560  /*
561  * Adjust GUC variables to suppress useless activity, and for debugging
562  * purposes (seeing track_counts off is a clue that we failed here). We
563  * use PGC_S_OVERRIDE because there is no point in trying to turn it back
564  * on from postgresql.conf without a restart.
565  */
566  SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
567 }
#define send(s, buf, len, flags)
Definition: win32.h:386
#define connect(s, name, namelen)
Definition: win32.h:383
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:89
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:133
#define closesocket
Definition: port.h:328
#define socket(af, type, protocol)
Definition: win32.h:379
int errcode(int sqlerrcode)
Definition: elog.c:575
#define select(n, r, w, e, timeout)
Definition: win32.h:384
#define recv(s, buf, len, flags)
Definition: win32.h:385
#define LOG
Definition: elog.h:26
#define gai_strerror
Definition: getaddrinfo.h:148
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:58
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:752
#define bind(s, addr, addrlen)
Definition: win32.h:380
#define TESTBYTEVAL
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6633
#define AI_PASSIVE
Definition: getaddrinfo.h:64
#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:295
static struct sockaddr_storage pgStatAddr
Definition: pgstat.c:135
#define NULL
Definition: c.h:226
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:21
struct addrinfo * ai_next
Definition: getaddrinfo.h:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
void pgstat_init_function_usage ( FunctionCallInfoData fcinfo,
PgStat_FunctionCallUsage fcu 
)

Definition at line 1505 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 EventTriggerInvoke(), ExecCallTriggerFunc(), ExecMakeFunctionResultNoSets(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

1507 {
1508  PgStat_BackendFunctionEntry *htabent;
1509  bool found;
1510 
1511  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1512  {
1513  /* stats not wanted */
1514  fcu->fs = NULL;
1515  return;
1516  }
1517 
1518  if (!pgStatFunctions)
1519  {
1520  /* First time through - initialize function stat table */
1521  HASHCTL hash_ctl;
1522 
1523  memset(&hash_ctl, 0, sizeof(hash_ctl));
1524  hash_ctl.keysize = sizeof(Oid);
1525  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1526  pgStatFunctions = hash_create("Function stat entries",
1528  &hash_ctl,
1529  HASH_ELEM | HASH_BLOBS);
1530  }
1531 
1532  /* Get the stats entry for this function, create if necessary */
1533  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1534  HASH_ENTER, &found);
1535  if (!found)
1536  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1537 
1538  fcu->fs = &htabent->f_counts;
1539 
1540  /* save stats for this function, later used to compensate for recursion */
1541  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1542 
1543  /* save current backend-wide total time */
1544  fcu->save_total = total_func_time;
1545 
1546  /* get clock time as of function start */
1548 }
instr_time f_start
Definition: pgstat.h:990
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:988
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:852
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:984
FmgrInfo * flinfo
Definition: fmgr.h:71
PgStat_FunctionCounts f_counts
Definition: pgstat.h:473
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:102
#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:56
static instr_time total_func_time
Definition: pgstat.c:242
static HTAB * pgStatFunctions
Definition: pgstat.c:167
#define NULL
Definition: c.h:226
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:986
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry
void pgstat_initialize ( void  )

Definition at line 2642 of file pgstat.c.

References Assert, MaxBackends, MyBackendId, on_shmem_exit(), and pgstat_beshutdown_hook().

Referenced by InitPostgres().

2643 {
2644  /* Initialize MyBEEntry */
2647 
2648  /* Set up a process-exit hook to clean up */
2650 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2487
BackendId MyBackendId
Definition: globals.c:72
int MaxBackends
Definition: globals.c:126
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
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:2767
#define Assert(condition)
Definition: c.h:670
void pgstat_initstats ( Relation  rel)

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

1635 {
1636  Oid rel_id = rel->rd_id;
1637  char relkind = rel->rd_rel->relkind;
1638 
1639  /* We only count stats for things that have storage */
1640  if (!(relkind == RELKIND_RELATION ||
1641  relkind == RELKIND_MATVIEW ||
1642  relkind == RELKIND_INDEX ||
1643  relkind == RELKIND_TOASTVALUE ||
1644  relkind == RELKIND_SEQUENCE))
1645  {
1646  rel->pgstat_info = NULL;
1647  return;
1648  }
1649 
1651  {
1652  /* We're not counting at all */
1653  rel->pgstat_info = NULL;
1654  return;
1655  }
1656 
1657  /*
1658  * If we already set up this relation in the current transaction, nothing
1659  * to do.
1660  */
1661  if (rel->pgstat_info != NULL &&
1662  rel->pgstat_info->t_id == rel_id)
1663  return;
1664 
1665  /* Else find or make the PgStat_TableStatus entry, and update link */
1666  rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1667 }
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:133
#define RELKIND_MATVIEW
Definition: pg_class.h:167
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool pgstat_track_counts
Definition: pgstat.c:110
Oid rd_id
Definition: rel.h:115
static PgStat_TableStatus * get_tabstat_entry(Oid rel_id, bool isshared)
Definition: pgstat.c:1673
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#define PGINVALID_SOCKET
Definition: port.h:24
#define NULL
Definition: c.h:226
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:214
#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 1470 of file pgstat.c.

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

1471 {
1472  PgStat_MsgDummy msg;
1473 
1475  return;
1476 
1478  pgstat_send(&msg, sizeof(msg));
1479 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:3617
NON_EXEC_STATIC pgsocket pgStatSock
Definition: pgstat.c:133
#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:3604
void pgstat_progress_end_command ( void  )

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

2952 {
2953  volatile PgBackendStatus *beentry = MyBEEntry;
2954 
2955  if (!beentry)
2956  return;
2959  return;
2960 
2965 }
Oid st_progress_command_target
Definition: pgstat.h:908
ProgressCommandType st_progress_command
Definition: pgstat.h:907
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
#define InvalidOid
Definition: postgres_ext.h:36
bool pgstat_track_activities
Definition: pgstat.c:109
void pgstat_progress_start_command ( ProgressCommandType  cmdtype,
Oid  relid 
)

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

2880 {
2881  volatile PgBackendStatus *beentry = MyBEEntry;
2882 
2883  if (!beentry || !pgstat_track_activities)
2884  return;
2885 
2887  beentry->st_progress_command = cmdtype;
2888  beentry->st_progress_command_target = relid;
2889  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
2891 }
Oid st_progress_command_target
Definition: pgstat.h:908
#define MemSet(start, val, len)
Definition: c.h:852
ProgressCommandType st_progress_command
Definition: pgstat.h:907
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:909
bool pgstat_track_activities
Definition: pgstat.c:109
void pgstat_progress_update_multi_param ( int  nparam,
const int *  index,
const int64 *  val 
)

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

2924 {
2925  volatile PgBackendStatus *beentry = MyBEEntry;
2926  int i;
2927 
2928  if (!beentry || !pgstat_track_activities || nparam == 0)
2929  return;
2930 
2932 
2933  for (i = 0; i < nparam; ++i)
2934  {
2935  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
2936 
2937  beentry->st_progress_param[index[i]] = val[i];
2938  }
2939 
2941 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:817
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
#define Assert(condition)
Definition: c.h:670
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:909
bool pgstat_track_activities
Definition: pgstat.c:109
int i
long val
Definition: informix.c:689
void pgstat_progress_update_param ( int  index,
int64  val 
)

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

2901 {
2902  volatile PgBackendStatus *beentry = MyBEEntry;
2903 
2905 
2906  if (!beentry || !pgstat_track_activities)
2907  return;
2908 
2910  beentry->st_progress_param[index] = val;
2912 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:817
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2488
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:924
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:930
#define Assert(condition)
Definition: c.h:670
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:909
bool pgstat_track_activities
Definition: pgstat.c:109
long val
Definition: informix.c:689
static void pgstat_read_current_status ( void  )
static

Definition at line 3028 of file pgstat.c.

References Assert, LocalPgBackendStatus::backend_xid, LocalPgBackendStatus::backend_xmin, BackendIdGetTransactionIds(), LocalPgBackendStatus::backendStatus, BackendStatusArray, CHECK_FOR_INTERRUPTS, i, localNumBackends, MaxBackends, MemoryContextAlloc(), NAMEDATALEN, 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().

3029 {
3030  volatile PgBackendStatus *beentry;
3031  LocalPgBackendStatus *localtable;
3032  LocalPgBackendStatus *localentry;
3033  char *localappname,
3034  *localactivity;
3035 #ifdef USE_SSL
3036  PgBackendSSLStatus *localsslstatus;
3037 #endif
3038  int i;
3039 
3042  return; /* already done */
3043 
3045 
3046  localtable = (LocalPgBackendStatus *)
3048  sizeof(LocalPgBackendStatus) * MaxBackends);
3049  localappname = (char *)
3052  localactivity = (char *)
3054  pgstat_track_activity_query_size * MaxBackends);
3055 #ifdef USE_SSL
3056  localsslstatus = (PgBackendSSLStatus *)
3058  sizeof(PgBackendSSLStatus) * MaxBackends);
3059 #endif
3060 
3061  localNumBackends = 0;
3062 
3063  beentry = BackendStatusArray;
3064  localentry = localtable;
3065  for (i = 1; i <= MaxBackends; i++)
3066  {
3067  /*
3068  * Follow the protocol of retrying if st_changecount changes while we
3069  * copy the entry, or if it's odd. (The check for odd is needed to
3070  * cover the case where we are able to completely copy the entry while
3071  * the source backend is between increment steps.) We use a volatile
3072  * pointer here to ensure the compiler doesn't try to get cute.
3073  */
3074  for (;;)
3075  {
3076  int before_changecount;
3077  int after_changecount;
3078 
3079  pgstat_save_changecount_before(beentry, before_changecount);
3080 
3081  localentry->backendStatus.st_procpid = beentry->st_procpid;
3082  if (localentry->backendStatus.st_procpid > 0)
3083  {
3084  memcpy(&localentry->backendStatus, (char *) beentry, sizeof(PgBackendStatus));
3085 
3086  /*
3087  * strcpy is safe even if the string is modified concurrently,
3088  * because there's always a \0 at the end of the buffer.
3089  */
3090  strcpy(localappname, (char *) beentry->st_appname);
3091  localentry->backendStatus.st_appname = localappname;
3092  strcpy(localactivity, (char *) beentry->st_activity);
3093  localentry->backendStatus.st_activity = localactivity;
3094  localentry->backendStatus.st_ssl = beentry->st_ssl;
3095 #ifdef USE_SSL
3096  if (beentry->st_ssl)
3097  {
3098  memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3099  localentry->backendStatus.st_sslstatus = localsslstatus;
3100  }
3101 #endif
3102  }
3103 
3104  pgstat_save_changecount_after(beentry, after_changecount);
3105  if (before_changecount == after_changecount &&
3106  (before_changecount & 1) == 0)
3107  break;
3108 
3109  /* Make sure we can break out of loop if stuck... */
3111  }
3112 
3113  beentry++;
3114  /* Only valid entries get included into the local array */
3115  if (localentry->backendStatus.st_procpid > 0)
3116  {
3118  &localentry->backend_xid,
3119  &localentry->backend_xmin);
3120 
3121  localentry++;
3122  localappname += NAMEDATALEN;
3123  localactivity += pgstat_track_activity_query_size;
3124 #ifdef USE_SSL
3125  localsslstatus++;
3126 #endif
3127  localNumBackends++;
3128  }
3129  }
3130 
3131  /* Set the pointer only after completion of a valid table */
3132  localBackendStatusTable = localtable;
3133 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2487
static bool pgStatRunningInCollector
Definition: pgstat.c:139
TransactionId backend_xmin
Definition: pgstat.h:974
#define NAMEDATALEN
TransactionId backend_xid
Definition: pgstat.h:968
int MaxBackends
Definition: globals.c:126
#define pgstat_save_changecount_before(beentry, save_changecount)
Definition: pgstat.h:937
int pgstat_track_activity_query_size
Definition: pgstat.c:112
char * st_appname
Definition: pgstat.h:893
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5025
PgBackendStatus backendStatus
Definition: pgstat.h:962
void BackendIdGetTransactionIds(int backendID, TransactionId *xid, TransactionId *xmin)
Definition: sinvaladt.c:404
#define Assert(condition)
Definition: c.h:670
char * st_activity
Definition: pgstat.h:896
static LocalPgBackendStatus * localBackendStatusTable
Definition: pgstat.c:215
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:943
int st_procpid
Definition: pgstat.h:871
static int localNumBackends
Definition: pgstat.c:216
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:749
int i
static MemoryContext pgStatLocalContext
Definition: pgstat.c:213
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:887
static void pgstat_read_db_statsfile ( Oid  databaseid,
HTAB tabhash,
HTAB funchash,
bool  permanent 
)
static

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

4612 {
4613  PgStat_StatTabEntry *tabentry;
4614  PgStat_StatTabEntry tabbuf;
4615  PgStat_StatFuncEntry funcbuf;
4616  PgStat_StatFuncEntry *funcentry;
4617  FILE *fpin;
4618  int32 format_id;
4619  bool found;
4620  char statfile[MAXPGPATH];
4621 
4622  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
4623 
4624  /*
4625  * Try to open the stats file. If it doesn't exist, the backends simply
4626  * return zero for anything and the collector simply starts from scratch
4627  * with empty counters.
4628  *
4629  * ENOENT is a possibility if the stats collector is not running or has
4630  * not yet written the stats file the first time. Any other failure
4631  * condition is suspicious.
4632  */
4633  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4634  {
4635  if (errno != ENOENT)
4638  errmsg("could not open statistics file \"%s\": %m",
4639  statfile)));
4640  return;
4641  }
4642 
4643  /*
4644  * Verify it's of the expected format.
4645  */
4646  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4647  format_id != PGSTAT_FILE_FORMAT_ID)
4648  {
4649  ereport(pgStatRunningInCollector ? LOG : WARNING,
4650  (errmsg("corrupted statistics file \"%s\"", statfile)));
4651  goto done;
4652  }
4653 
4654  /*
4655  * We found an existing collector stats file. Read it and put all the
4656  * hashtable entries into place.
4657  */
4658  for (;;)
4659  {
4660  switch (fgetc(fpin))
4661  {
4662  /*
4663  * 'T' A PgStat_StatTabEntry follows.
4664  */
4665  case 'T':
4666  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
4667  fpin) != sizeof(PgStat_StatTabEntry))
4668  {
4669  ereport(pgStatRunningInCollector ? LOG : WARNING,
4670  (errmsg("corrupted statistics file \"%s\"",
4671  statfile)));
4672  goto done;
4673  }
4674 
4675  /*
4676  * Skip if table data not wanted.
4677  */
4678  if (tabhash == NULL)
4679  break;
4680 
4681  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
4682  (void *) &tabbuf.tableid,
4683  HASH_ENTER, &found);
4684 
4685  if (found)
4686  {
4687  ereport(pgStatRunningInCollector ? LOG : WARNING,
4688  (errmsg("corrupted statistics file \"%s\"",
4689  statfile)));
4690  goto done;
4691  }
4692 
4693  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
4694  break;
4695 
4696  /*
4697  * 'F' A PgStat_StatFuncEntry follows.
4698  */
4699  case 'F':
4700  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
4701  fpin) != sizeof(PgStat_StatFuncEntry))
4702  {
4703  ereport(pgStatRunningInCollector ? LOG : WARNING,
4704  (errmsg("corrupted statistics file \"%s\"",
4705  statfile)));
4706  goto done;
4707  }
4708 
4709  /*
4710  * Skip if function data not wanted.
4711  */
4712  if (funchash == NULL)
4713  break;
4714 
4715  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
4716  (void *) &funcbuf.functionid,
4717  HASH_ENTER, &found);
4718 
4719  if (found)
4720  {
4721  ereport(pgStatRunningInCollector ? LOG : WARNING,
4722  (errmsg("corrupted statistics file \"%s\"",
4723  statfile)));
4724  goto done;
4725  }
4726 
4727  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
4728  break;
4729 
4730  /*
4731  * 'E' The EOF marker of a complete stats file.
4732  */
4733  case 'E':
4734  goto done;
4735 
4736  default:
4737  ereport(pgStatRunningInCollector ? LOG : WARNING,
4738  (errmsg("corrupted statistics file \"%s\"",
4739  statfile)));
4740  goto done;
4741  }
4742  }
4743 
4744 done:
4745  FreeFile(fpin);
4746 
4747  if (permanent)
4748  {
4749  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4750  unlink(statfile);
4751  }
4752 }
static bool pgStatRunningInCollector
Definition: pgstat.c:139
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:1039
signed int int32
Definition: c.h:253
#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:1966
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:226
int FreeFile(FILE *file)
Definition: fd.c:2149
#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:4250
static bool pgstat_read_db_statsfile_timestamp ( Oid  databaseid,
bool  permanent,
TimestampTz ts 
)
static

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

4774 {
4775  PgStat_StatDBEntry dbentry;
4776  PgStat_GlobalStats myGlobalStats;
4777  PgStat_ArchiverStats myArchiverStats;
4778  FILE *fpin;
4779  int32 format_id;
4780  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4781 
4782  /*
4783  * Try to open the stats file. As above, anything but ENOENT is worthy of
4784  * complaining about.
4785  */
4786  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4787  {
4788  if (errno != ENOENT)
4791  errmsg("could not open statistics file \"%s\": %m",
4792  statfile)));
4793  return false;
4794  }
4795 
4796  /*
4797  * Verify it's of the expected format.
4798  */
4799  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4800  format_id != PGSTAT_FILE_FORMAT_ID)
4801  {
4802  ereport(pgStatRunningInCollector ? LOG : WARNING,
4803  (errmsg("corrupted statistics file \"%s\"", statfile)));
4804  FreeFile(fpin);
4805  return false;
4806  }
4807 
4808  /*
4809  * Read global stats struct
4810  */
4811  if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
4812  fpin) != sizeof(myGlobalStats))
4813  {
4814  ereport(pgStatRunningInCollector ? LOG : WARNING,
4815  (errmsg("corrupted statistics file \"%s\"", statfile)));
4816  FreeFile(fpin);
4817  return false;
4818  }
4819 
4820  /*
4821  * Read archiver stats struct
4822  */
4823  if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
4824  fpin) != sizeof(myArchiverStats))
4825  {
4826  ereport(pgStatRunningInCollector ? LOG : WARNING,
4827  (errmsg("corrupted statistics file \"%s\"", statfile)));
4828  FreeFile(fpin);
4829  return false;
4830  }
4831 
4832  /* By default, we're going to return the timestamp of the global file. */
4833  *ts = myGlobalStats.stats_timestamp;
4834 
4835  /*
4836  * We found an existing collector stats file. Read it and look for a
4837  * record for the requested database. If found, use its timestamp.
4838  */
4839  for (;;)
4840  {
4841  switch (fgetc(fpin))
4842  {
4843  /*
4844  * 'D' A PgStat_StatDBEntry struct describing a database
4845  * follows.
4846  */
4847  case 'D':
4848  if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
4849  fpin) != offsetof(PgStat_StatDBEntry, tables))
4850  {
4851  ereport(pgStatRunningInCollector ? LOG : WARNING,
4852  (errmsg("corrupted statistics file \"%s\"",
4853  statfile)));
4854  goto done;
4855  }
4856 
4857  /*
4858  * If this is the DB we're looking for, save its timestamp and
4859  * we're done.
4860  */
4861  if (dbentry.databaseid == databaseid)
4862  {
4863  *ts = dbentry.stats_timestamp;
4864  goto done;
4865  }
4866 
4867  break;
4868 
4869  case 'E':
4870  goto done;
4871 
4872  default:
4873  ereport(pgStatRunningInCollector ? LOG : WARNING,
4874  (errmsg("corrupted statistics file \"%s\"",
4875  statfile)));
4876  goto done;
4877  }
4878  }
4879 
4880 done:
4881  FreeFile(fpin);
4882  return true;
4883 }
TimestampTz stats_timestamp
Definition: pgstat.h:600
static bool pgStatRunningInCollector
Definition: pgstat.c:139
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:1039
signed int int32
Definition: c.h:253
char * pgstat_stat_filename
Definition: pgstat.c:119
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:1966
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:226
int FreeFile(FILE *file)
Definition: fd.c:2149
#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:550
static HTAB * pgstat_read_statsfiles ( Oid  onlydb,
bool  permanent,
bool  deep 
)
static

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

4400 {
4401  PgStat_StatDBEntry *dbentry;
4402  PgStat_StatDBEntry dbbuf;
4403  HASHCTL hash_ctl;
4404  HTAB *dbhash;
4405  FILE *fpin;
4406  int32 format_id;
4407  bool found;
4408  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4409 
4410  /*
4411  * The tables will live in pgStatLocalContext.
4412  */
4414 
4415  /*
4416  * Create the DB hashtable
4417  */
4418  memset(&hash_ctl, 0, sizeof(hash_ctl));
4419  hash_ctl.keysize = sizeof(Oid);
4420  hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
4421  hash_ctl.hcxt = pgStatLocalContext;
4422  dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
4424 
4425  /*
4426  * Clear out global and archiver statistics so they start from zero in
4427  * case we can't load an existing statsfile.
4428  */
4429  memset(&globalStats, 0, sizeof(globalStats));
4430  memset(&archiverStats, 0, sizeof(archiverStats));
4431 
4432  /*
4433  * Set the current timestamp (will be kept only in case we can't load an
4434  * existing statsfile).
4435  */
4438 
4439  /*
4440  * Try to open the stats file. If it doesn't exist, the backends simply
4441  * return zero for anything and the collector simply starts from scratch
4442  * with empty counters.
4443  *
4444  * ENOENT is a possibility if the stats collector is not running or has
4445  * not yet written the stats file the first time. Any other failure
4446  * condition is suspicious.
4447  */
4448  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4449  {
4450  if (errno != ENOENT)
4453  errmsg("could not open statistics file \"%s\": %m",
4454  statfile)));
4455  return dbhash;
4456  }
4457 
4458  /*
4459  * Verify it's of the expected format.
4460  */
4461  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4462  format_id != PGSTAT_FILE_FORMAT_ID)
4463  {
4464  ereport(pgStatRunningInCollector ? LOG : WARNING,
4465  (errmsg("corrupted statistics file \"%s\"", statfile)));
4466  goto done;
4467  }
4468 
4469  /*
4470  * Read global stats struct
4471  */
4472  if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
4473  {
4474  ereport(pgStatRunningInCollector ? LOG : WARNING,
4475  (errmsg("corrupted statistics file \"%s\"", statfile)));
4476  goto done;
4477  }
4478 
4479  /*
4480  * Read archiver stats struct
4481  */
4482  if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
4483  {
4484  ereport(pgStatRunningInCollector ? LOG : WARNING,
4485  (errmsg("corrupted statistics file \"%s\"", statfile)));
4486  goto done;
4487  }
4488 
4489  /*
4490  * We found an existing collector stats file. Read it and put all the
4491  * hashtable entries into place.
4492  */
4493  for (;;)
4494  {
4495  switch (fgetc(fpin))
4496  {
4497  /*
4498  * 'D' A PgStat_StatDBEntry struct describing a database
4499  * follows.
4500  */
4501  case 'D':
4502  if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
4503  fpin) != offsetof(PgStat_StatDBEntry, tables))
4504  {
4505  ereport(pgStatRunningInCollector ? LOG : WARNING,
4506  (errmsg("corrupted statistics file \"%s\"",
4507  statfile)));
4508  goto done;
4509  }
4510 
4511  /*
4512  * Add to the DB hash
4513  */
4514  dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
4515  (void *) &dbbuf.databaseid,
4516  HASH_ENTER,
4517  &found);
4518  if (found)
4519  {
4520  ereport(pgStatRunningInCollector ? LOG : WARNING,
4521  (errmsg("corrupted statistics file \"%s\"",
4522  statfile)));
4523  goto done;
4524  }
4525 
4526  memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
4527  dbentry->tables = NULL;
4528  dbentry->functions = NULL;
4529 
4530  /*
4531  * Don't create tables/functions hashtables for uninteresting
4532  * databases.
4533  */
4534  if (onlydb != InvalidOid)
4535  {
4536  if (dbbuf.databaseid != onlydb &&
4537  dbbuf.databaseid != InvalidOid)
4538  break;
4539  }
4540 
4541  memset(&hash_ctl, 0, sizeof(hash_ctl));
4542  hash_ctl.keysize = sizeof(Oid);
4543  hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4544  hash_ctl.hcxt = pgStatLocalContext;
4545  dbentry->tables = hash_create("Per-database table",
4547  &hash_ctl,
4549 
4550  hash_ctl.keysize = sizeof(Oid);
4551  hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4552  hash_ctl.hcxt = pgStatLocalContext;
4553  dbentry->functions = hash_create("Per-database function",
4555  &hash_ctl,
4557 
4558  /*
4559  * If requested, read the data from the database-specific
4560  * file. Otherwise we just leave the hashtables empty.
4561  */
4562  if (deep)
4564  dbentry->tables,
4565  dbentry->functions,
4566  permanent);
4567 
4568  break;
4569 
4570  case 'E':
4571  goto done;
4572 
4573  default:
4574  ereport(pgStatRunningInCollector ? LOG : WARNING,
4575  (errmsg("corrupted statistics file \"%s\"",
4576  statfile)));
4577  goto done;
4578  }
4579  }
4580 
4581 done:
4582  FreeFile(fpin);
4583 
4584  /* If requested to read the permanent file, also get rid of it. */
4585  if (permanent)
4586  {
4587  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4588  unlink(statfile);
4589  }
4590 
4591  return dbhash;
4592 }
#define PGSTAT_DB_HASH_SIZE
Definition: pgstat.c:100
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
static PgStat_GlobalStats globalStats
Definition: pgstat.c:224
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
#define PGSTAT_TAB_HASH_SIZE
Definition: pgstat.c:101
static bool pgStatRunningInCollector
Definition: pgstat.c:139
HTAB * functions
Definition: pgstat.h:607
Size entrysize
Definition: hsearch.h:73
#define PGSTAT_STAT_PERMANENT_FILENAME
Definition: pgstat.h:30
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_BINARY_R
Definition: c.h:1039
struct PgStat_StatFuncEntry PgStat_StatFuncEntry
signed int int32
Definition: c.h:253
Definition: dynahash.c:193
char * pgstat_stat_filename
Definition: pgstat.c:119
#define DEBUG2
Definition: elog.h:24
#define PGSTAT_FUNCTION_HASH_SIZE
Definition: pgstat.c:102
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:1966
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5025
static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent)
Definition: pgstat.c:4610
#define WARNING
Definition: elog.h:40
#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
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
struct PgStat_StatTabEntry PgStat_StatTabEntry
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:223
TimestampTz stat_reset_timestamp
Definition: pgstat.h:694
struct PgStat_StatDBEntry PgStat_StatDBEntry
int FreeFile(FILE *file)
Definition: fd.c:2149
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:569
TimestampTz stat_reset_timestamp
Definition: pgstat.h:675
int errmsg(const char *fmt,...)
Definition: elog.c:797
static MemoryContext pgStatLocalContext
Definition: pgstat.c:213
#define elog
Definition: elog.h:219
#define offsetof(type, field)
Definition: c.h:550
static void pgstat_recv_analyze ( PgStat_MsgAnalyze msg,
int  len 
)
static

Definition at line 5489 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::changes_since_analyze, PgStat_MsgAnalyze::m_analyzetime, PgStat_MsgAnalyze::m_autovacuum, PgStat_MsgAnalyze::m_databaseid, PgStat_MsgAnalyze::m_dead_tuples, PgStat_MsgAnalyze::m_live_tuples, PgStat_MsgAnalyze::m_resetcounter, PgStat_MsgAnalyze::m_tableoid, PgStat_StatTabEntry::n_dead_tuples, PgStat_StatTabEntry::n_live_tuples, pgstat_get_db_entry(), and pgstat_get_tab_entry().

Referenced by PgstatCollectorMain().

5490 {
5491  PgStat_StatDBEntry *dbentry;
5492  PgStat_StatTabEntry *tabentry;
5493 
5494  /*
5495  * Store the data in the table's hashtable entry.
5496  */
5497  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5498 
5499  tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
5500 
5501  tabentry->n_live_tuples = msg->m_live_tuples;
5502  tabentry->n_dead_tuples = msg->m_dead_tuples;
5503 
5504  /*
5505  * If commanded, reset changes_since_analyze to zero. This forgets any
5506  * changes that were committed while the ANALYZE was in progress, but we
5507  * have no good way to estimate how many of those there were.
5508  */
5509  if (msg->m_resetcounter)
5510  tabentry->changes_since_analyze = 0;
5511 
5512  if (msg->m_autovacuum)
5513  {
5514  tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
5515  tabentry->autovac_analyze_count++;
5516  }
5517  else
5518  {
5519  tabentry->analyze_timestamp = msg->m_analyzetime;
5520  tabentry->analyze_count++;
5521  }
5522 }
PgStat_Counter analyze_count
Definition: pgstat.h:641
static PgStat_StatTabEntry * pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
Definition: pgstat.c:4067
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:642
TimestampTz m_analyzetime
Definition: pgstat.h:387
bool m_resetcounter
Definition: pgstat.h:386
PgStat_Counter n_live_tuples
Definition: pgstat.h:629
PgStat_Counter n_dead_tuples
Definition: pgstat.h:630
PgStat_Counter m_live_tuples
Definition: pgstat.h:388
bool m_autovacuum
Definition: pgstat.h:385
TimestampTz analyze_timestamp
Definition: pgstat.h:640
PgStat_Counter changes_since_analyze
Definition: pgstat.h:631
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:643
PgStat_Counter m_dead_tuples
Definition: pgstat.h:389
static void pgstat_recv_archiver ( PgStat_MsgArchiver msg,
int  len 
)
static

Definition at line 5532 of file pgstat.c.

References PgStat_ArchiverStats::archived_count, PgStat_ArchiverStats::failed_count, PgStat_ArchiverStats::last_archived_timestamp, PgStat_ArchiverStats::last_archived_wal, PgStat_ArchiverStats::last_failed_timestamp, PgStat_ArchiverStats::last_failed_wal, PgStat_MsgArchiver::m_failed, PgStat_MsgArchiver::m_timestamp, and PgStat_MsgArchiver::m_xlog.

Referenced by PgstatCollectorMain().

5533 {
5534  if (msg->m_failed)
5535  {
5536  /* Failed archival attempt */
5538  memcpy(archiverStats.last_failed_wal, msg->m_xlog,
5539  sizeof(archiverStats.last_failed_wal));
5541  }
5542  else
5543  {
5544  /* Successful archival operation */
5546  memcpy(archiverStats.last_archived_wal, msg->m_xlog,
5549  }
5550 }
char last_failed_wal[MAX_XFN_CHARS+1]
Definition: pgstat.h:672
char m_xlog[MAX_XFN_CHARS+1]
Definition: pgstat.h:401
PgStat_Counter archived_count
Definition: pgstat.h:667
TimestampTz m_timestamp
Definition: pgstat.h:402
TimestampTz last_failed_timestamp
Definition: pgstat.h:674
PgStat_Counter failed_count
Definition: pgstat.h:671
static PgStat_ArchiverStats archiverStats
Definition: pgstat.c:223
TimestampTz last_archived_timestamp
Definition: pgstat.h:670
char last_archived_wal[MAX_XFN_CHARS+1]
Definition: pgstat.h:668
static void pgstat_recv_autovac ( PgStat_MsgAutovacStart msg,
int  len 
)
static

Definition at line 5436 of file pgstat.c.

References PgStat_StatDBEntry::last_autovac_time, PgStat_MsgAutovacStart::m_databaseid, PgStat_MsgAutovacStart::m_start_time, and pgstat_get_db_entry().

Referenced by PgstatCollectorMain().

5437 {
5438  PgStat_StatDBEntry *dbentry;
5439 
5440  /*
5441  * Store the last autovacuum time in the database's hashtable entry.
5442  */
5443  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5444 
5445  dbentry->last_autovac_time = msg->m_start_time;
5446 }
TimestampTz last_autovac_time
Definition: pgstat.h:587
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
TimestampTz m_start_time
Definition: pgstat.h:354
static void pgstat_recv_bgwriter ( PgStat_MsgBgWriter msg,
int  len 
)
static

Definition at line 5559 of file pgstat.c.

References PgStat_GlobalStats::buf_alloc, PgStat_GlobalStats::buf_fsync_backend, PgStat_GlobalStats::buf_written_backend, PgStat_GlobalStats::buf_written_checkpoints, PgStat_GlobalStats::buf_written_clean, PgStat_GlobalStats::checkpoint_sync_time, PgStat_GlobalStats::checkpoint_write_time, PgStat_MsgBgWriter::m_buf_alloc, PgStat_MsgBgWriter::m_buf_fsync_backend, PgStat_MsgBgWriter::m_buf_written_backend, PgStat_MsgBgWriter::m_buf_written_checkpoints, PgStat_MsgBgWriter::m_buf_written_clean, PgStat_MsgBgWriter::m_checkpoint_sync_time, PgStat_MsgBgWriter::m_checkpoint_write_time, PgStat_MsgBgWriter::m_maxwritten_clean, PgStat_MsgBgWriter::m_requested_checkpoints, PgStat_MsgBgWriter::m_timed_checkpoints, PgStat_GlobalStats::maxwritten_clean, PgStat_GlobalStats::requested_checkpoints, and PgStat_GlobalStats::timed_checkpoints.

Referenced by PgstatCollectorMain().

5560 {
5571 }
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:419
PgStat_Counter buf_alloc
Definition: pgstat.h:693
PgStat_Counter m_buf_written_checkpoints
Definition: pgstat.h:415
PgStat_Counter m_buf_alloc
Definition: pgstat.h:420
PgStat_Counter m_checkpoint_write_time
Definition: pgstat.h:421
static PgStat_GlobalStats globalStats
Definition: pgstat.c:224
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:413
PgStat_Counter m_maxwritten_clean
Definition: pgstat.h:417
PgStat_Counter timed_checkpoints
Definition: pgstat.h:684
PgStat_Counter m_buf_written_clean
Definition: pgstat.h:416
PgStat_Counter buf_fsync_backend
Definition: pgstat.h:692
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:414
PgStat_Counter buf_written_backend
Definition: pgstat.h:691
PgStat_Counter checkpoint_write_time
Definition: pgstat.h:686
PgStat_Counter buf_written_checkpoints
Definition: pgstat.h:688
PgStat_Counter buf_written_clean
Definition: pgstat.h:689
PgStat_Counter m_checkpoint_sync_time
Definition: pgstat.h:422
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:418
PgStat_Counter checkpoint_sync_time
Definition: pgstat.h:687
PgStat_Counter maxwritten_clean
Definition: pgstat.h:690
PgStat_Counter requested_checkpoints
Definition: pgstat.h:685
static void pgstat_recv_deadlock ( PgStat_MsgDeadlock msg,
int  len 
)
static

Definition at line 5620 of file pgstat.c.

References PgStat_MsgDeadlock::m_databaseid, PgStat_StatDBEntry::n_deadlocks, and pgstat_get_db_entry().

Referenced by PgstatCollectorMain().

5621 {
5622  PgStat_StatDBEntry *dbentry;
5623 
5624  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5625 
5626  dbentry->n_deadlocks++;
5627 }
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
PgStat_Counter n_deadlocks
Definition: pgstat.h:595
static void pgstat_recv_dropdb ( PgStat_MsgDropdb msg,
int  len 
)
static

Definition at line 5299 of file pgstat.c.

References DEBUG2, elog, ereport, errmsg(), ERROR, PgStat_StatDBEntry::functions, get_dbstat_filename(), hash_destroy(), HASH_REMOVE, hash_search(), PgStat_MsgDropdb::m_databaseid, MAXPGPATH, NULL, pgstat_get_db_entry(), PgStat_StatDBEntry::tables, and unlink().

Referenced by PgstatCollectorMain().

5300 {
5301  Oid dbid = msg->m_databaseid;
5302  PgStat_StatDBEntry *dbentry;
5303 
5304  /*
5305  * Lookup the database in the hashtable.
5306  */
5307  dbentry = pgstat_get_db_entry(dbid, false);
5308 
5309  /*
5310  * If found, remove it (along with the db statfile).
5311  */
5312  if (dbentry)
5313  {
5314  char statfile[MAXPGPATH];
5315 
5316  get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
5317 
5318  elog(DEBUG2, "removing stats file \"%s\"", statfile);
5319  unlink(statfile);
5320 
5321  if (dbentry->tables != NULL)
5322  hash_destroy(dbentry->tables);
5323  if (dbentry->functions != NULL)
5324  hash_destroy(dbentry->functions);
5325 
5327  (void *) &dbid,
5328  HASH_REMOVE, NULL) == NULL)
5329  ereport(ERROR,
5330  (errmsg("database hash table corrupted during cleanup --- abort")));
5331  }
5332 }
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:793
HTAB * functions
Definition: pgstat.h:607
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
Oid m_databaseid
Definition: pgstat.h:306
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
static HTAB * pgStatDBHash
Definition: pgstat.c:214
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:4250
static void pgstat_recv_funcpurge ( PgStat_MsgFuncpurge msg,
int  len 
)
static

Definition at line 5701 of file pgstat.c.

References PgStat_StatDBEntry::functions, HASH_REMOVE, hash_search(), i, PgStat_MsgFuncpurge::m_databaseid, PgStat_MsgFuncpurge::m_functionid, PgStat_MsgFuncpurge::m_nentries, NULL, and pgstat_get_db_entry().

Referenced by PgstatCollectorMain().

5702 {
5703  PgStat_StatDBEntry *dbentry;
5704  int i;
5705 
5706  dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5707 
5708  /*
5709  * No need to purge if we don't even know the database.
5710  */
5711  if (!dbentry || !dbentry->functions)
5712  return;
5713 
5714  /*
5715  * Process all function entries in the message.
5716  */
5717  for (i = 0; i < msg->m_nentries; i++)
5718  {
5719  /* Remove from hashtable if present; we don't care if it's not. */
5720  (void) hash_search(dbentry->functions,
5721  (void *) &(msg->m_functionid[i]),
5722  HASH_REMOVE, NULL);
5723  }
5724 }
HTAB * functions
Definition: pgstat.h:607
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define NULL
Definition: c.h:226
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
int i
Oid m_functionid[PGSTAT_NUM_FUNCPURGE]
Definition: pgstat.h:519
static void pgstat_recv_funcstat ( PgStat_MsgFuncstat msg,
int  len 
)
static

Definition at line 5653 of file pgstat.c.

References PgStat_FunctionEntry::f_id, PgStat_FunctionEntry::f_numcalls, PgStat_StatFuncEntry::f_numcalls, PgStat_FunctionEntry::f_self_time, PgStat_StatFuncEntry::f_self_time, PgStat_FunctionEntry::f_total_time, PgStat_StatFuncEntry::f_total_time, PgStat_StatDBEntry::functions, HASH_ENTER, hash_search(), i, PgStat_MsgFuncstat::m_databaseid, PgStat_MsgFuncstat::m_entry, PgStat_MsgFuncstat::m_nentries, and pgstat_get_db_entry().

Referenced by PgstatCollectorMain().

5654 {
5655  PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
5656  PgStat_StatDBEntry *dbentry;
5657  PgStat_StatFuncEntry *funcentry;
5658  int i;
5659  bool found;
5660 
5661  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5662 
5663  /*
5664  * Process all function entries in the message.
5665  */
5666  for (i = 0; i < msg->m_nentries; i++, funcmsg++)
5667  {
5668  funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
5669  (void *) &(funcmsg->f_id),
5670  HASH_ENTER, &found);
5671 
5672  if (!found)
5673  {
5674  /*
5675  * If it's a new function entry, initialize counters to the values
5676  * we just got.
5677  */
5678  funcentry->f_numcalls = funcmsg->f_numcalls;
5679  funcentry->f_total_time = funcmsg->f_total_time;
5680  funcentry->f_self_time = funcmsg->f_self_time;
5681  }
5682  else
5683  {
5684  /*
5685  * Otherwise add the values to the existing entry.
5686  */
5687  funcentry->f_numcalls += funcmsg->f_numcalls;
5688  funcentry->f_total_time += funcmsg->f_total_time;
5689  funcentry->f_self_time += funcmsg->f_self_time;
5690  }
5691  }
5692 }
PgStat_Counter f_self_time
Definition: pgstat.h:485
HTAB * functions
Definition: pgstat.h:607
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
PgStat_Counter f_total_time
Definition: pgstat.h:657
PgStat_Counter f_numcalls
Definition: pgstat.h:655
PgStat_Counter f_total_time
Definition: pgstat.h:484
PgStat_FunctionEntry m_entry[PGSTAT_NUM_FUNCENTRIES]
Definition: pgstat.h:502
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
int i
PgStat_Counter f_numcalls
Definition: pgstat.h:483
PgStat_Counter f_self_time
Definition: pgstat.h:658
static void pgstat_recv_inquiry ( PgStat_MsgInquiry msg,
int  len 
)
static

Definition at line 5066 of file pgstat.c.

References PgStat_MsgInquiry::clock_time, PgStat_MsgInquiry::cutoff_time, PgStat_MsgInquiry::databaseid, PgStat_StatDBEntry::databaseid, DEBUG2, elog, GetCurrentTimestamp(), lappend_oid(), list_member_oid(), LOG, NULL, pfree(), pgstat_get_db_entry(), pstrdup(), PgStat_StatDBEntry::stats_timestamp, and timestamptz_to_str().

Referenced by PgstatCollectorMain().

5067 {
5068  PgStat_StatDBEntry *dbentry;
5069 
5070  elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
5071 
5072  /*
5073  * If there's already a write request for this DB, there's nothing to do.
5074  *
5075  * Note that if a request is found, we return early and skip the below
5076  * check for clock skew. This is okay, since the only way for a DB
5077  * request to be present in the list is that we have been here since the
5078  * last write round. It seems sufficient to check for clock skew once per
5079  * write round.
5080  */
5082  return;
5083 
5084  /*
5085  * Check to see if we last wrote this database at a time >= the requested
5086  * cutoff time. If so, this is a stale request that was generated before
5087  * we updated the DB file, and we don't need to do so again.
5088  *
5089  * If the requestor's local clock time is older than stats_timestamp, we
5090  * should suspect a clock glitch, ie system time going backwards; though
5091  * the more likely explanation is just delayed message receipt. It is
5092  * worth expending a GetCurrentTimestamp call to be sure, since a large
5093  * retreat in the system clock reading could otherwise cause us to neglect
5094  * to update the stats file for a long time.
5095  */
5096  dbentry = pgstat_get_db_entry(msg->databaseid, false);
5097  if (dbentry == NULL)
5098  {
5099  /*
5100  * We have no data for this DB. Enter a write request anyway so that
5101  * the global stats will get updated. This is needed to prevent
5102  * backend_read_statsfile from waiting for data that we cannot supply,
5103  * in the case of a new DB that nobody has yet reported any stats for.
5104  * See the behavior of pgstat_read_db_statsfile_timestamp.
5105  */
5106  }
5107  else if (msg->clock_time < dbentry->stats_timestamp)
5108  {
5109  TimestampTz cur_ts = GetCurrentTimestamp();
5110 
5111  if (cur_ts < dbentry->stats_timestamp)
5112  {
5113  /*
5114  * Sure enough, time went backwards. Force a new stats file write
5115  * to get back in sync; but first, log a complaint.
5116  */
5117  char *writetime;
5118  char *mytime;
5119 
5120  /* Copy because timestamptz_to_str returns a static buffer */
5121  writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
5122  mytime = pstrdup(timestamptz_to_str(cur_ts));
5123  elog(LOG,
5124  "stats_timestamp %s is later than collector's time %s for database %u",
5125  writetime, mytime, dbentry->databaseid);
5126  pfree(writetime);
5127  pfree(mytime);
5128  }
5129  else
5130  {
5131  /*
5132  * Nope, it's just an old request. Assuming msg's clock_time is
5133  * >= its cutoff_time, it must be stale, so we can ignore it.
5134  */
5135  return;
5136  }
5137  }
5138  else if (msg->cutoff_time <= dbentry->stats_timestamp)
5139  {
5140  /* Stale request, ignore it */
5141  return;
5142  }
5143 
5144  /*
5145  * We need to write this DB, so create a request.
5146  */
5148  msg->databaseid);
5149 }
TimestampTz stats_timestamp
Definition: pgstat.h:600
static List * pending_write_requests
Definition: pgstat.c:231
TimestampTz clock_time
Definition: pgstat.h:242
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1688
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define LOG
Definition: elog.h:26
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
double TimestampTz
Definition: timestamp.h:51
void pfree(void *pointer)
Definition: mcxt.c:992
#define DEBUG2
Definition: elog.h:24
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:226
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4036
TimestampTz cutoff_time
Definition: pgstat.h:243
#define elog
Definition: elog.h:219
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1894
static void pgstat_recv_recoveryconflict ( PgStat_MsgRecoveryConflict msg,
int  len 
)
static

Definition at line 5580 of file pgstat.c.

References PgStat_MsgRecoveryConflict::m_databaseid, PgStat_MsgRecoveryConflict::m_reason, PgStat_StatDBEntry::n_conflict_bufferpin, PgStat_StatDBEntry::n_conflict_lock, PgStat_StatDBEntry::n_conflict_snapshot, PgStat_StatDBEntry::n_conflict_startup_deadlock, PgStat_StatDBEntry::n_conflict_tablespace, pgstat_get_db_entry(), PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, and PROCSIG_RECOVERY_CONFLICT_TABLESPACE.

Referenced by PgstatCollectorMain().

5581 {
5582  PgStat_StatDBEntry *dbentry;
5583 
5584  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5585 
5586  switch (msg->m_reason)
5587  {
5589 
5590  /*
5591  * Since we drop the information about the database as soon as it
5592  * replicates, there is no point in counting these conflicts.
5593  */
5594  break;
5596  dbentry->n_conflict_tablespace++;
5597  break;
5599  dbentry->n_conflict_lock++;
5600  break;
5602  dbentry->n_conflict_snapshot++;
5603  break;
5605  dbentry->n_conflict_bufferpin++;
5606  break;
5608  dbentry->n_conflict_startup_deadlock++;
5609  break;
5610  }
5611 }
PgStat_Counter n_conflict_bufferpin
Definition: pgstat.h:591
PgStat_Counter n_conflict_startup_deadlock
Definition: pgstat.h:592
PgStat_Counter n_conflict_tablespace
Definition: pgstat.h:588