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 const char * pgstat_get_wait_io (WaitEventIO w)
 
static void pgstat_setheader (PgStat_MsgHdr *hdr, StatMsgType mtype)
 
static void pgstat_send (void *msg, int len)
 
static void pgstat_recv_inquiry (PgStat_MsgInquiry *msg, int len)
 
static void pgstat_recv_tabstat (PgStat_MsgTabstat *msg, int len)
 
static void pgstat_recv_tabpurge (PgStat_MsgTabpurge *msg, int len)
 
static void pgstat_recv_dropdb (PgStat_MsgDropdb *msg, int len)
 
static void pgstat_recv_resetcounter (PgStat_MsgResetcounter *msg, int len)
 
static void pgstat_recv_resetsharedcounter (PgStat_MsgResetsharedcounter *msg, int len)
 
static void pgstat_recv_resetsinglecounter (PgStat_MsgResetsinglecounter *msg, int len)
 
static void pgstat_recv_autovac (PgStat_MsgAutovacStart *msg, int len)
 
static void pgstat_recv_vacuum (PgStat_MsgVacuum *msg, int len)
 
static void pgstat_recv_analyze (PgStat_MsgAnalyze *msg, int len)
 
static void pgstat_recv_archiver (PgStat_MsgArchiver *msg, int len)
 
static void pgstat_recv_bgwriter (PgStat_MsgBgWriter *msg, int len)
 
static void pgstat_recv_funcstat (PgStat_MsgFuncstat *msg, int len)
 
static void pgstat_recv_funcpurge (PgStat_MsgFuncpurge *msg, int len)
 
static void pgstat_recv_recoveryconflict (PgStat_MsgRecoveryConflict *msg, int len)
 
static void pgstat_recv_deadlock (PgStat_MsgDeadlock *msg, int len)
 
static void pgstat_recv_tempfile (PgStat_MsgTempFile *msg, int len)
 
void pgstat_init (void)
 
static void pgstat_reset_remove_files (const char *directory)
 
void pgstat_reset_all (void)
 
int pgstat_start (void)
 
void allow_immediate_pgstat_restart (void)
 
void pgstat_report_stat (bool force)
 
void pgstat_vacuum_stat (void)
 
void pgstat_drop_database (Oid databaseid)
 
void pgstat_reset_counters (void)
 
void pgstat_reset_shared_counters (const char *target)
 
void pgstat_reset_single_counter (Oid objoid, PgStat_Single_Reset_Type type)
 
void pgstat_report_autovac (Oid dboid)
 
void pgstat_report_vacuum (Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
 
void pgstat_report_analyze (Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
 
void pgstat_report_recovery_conflict (int reason)
 
void pgstat_report_deadlock (void)
 
void pgstat_report_tempfile (size_t filesize)
 
void pgstat_ping (void)
 
static void pgstat_send_inquiry (TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
 
void pgstat_init_function_usage (FunctionCallInfoData *fcinfo, PgStat_FunctionCallUsage *fcu)
 
PgStat_BackendFunctionEntryfind_funcstat_entry (Oid func_id)
 
void pgstat_end_function_usage (PgStat_FunctionCallUsage *fcu, bool finalize)
 
void pgstat_initstats (Relation rel)
 
PgStat_TableStatusfind_tabstat_entry (Oid rel_id)
 
static PgStat_SubXactStatusget_tabstat_stack_level (int nest_level)
 
static void add_tabstat_xact_level (PgStat_TableStatus *pgstat_info, int nest_level)
 
void pgstat_count_heap_insert (Relation rel, PgStat_Counter n)
 
void pgstat_count_heap_update (Relation rel, bool hot)
 
void pgstat_count_heap_delete (Relation rel)
 
static void pgstat_truncate_save_counters (PgStat_TableXactStatus *trans)
 
static void pgstat_truncate_restore_counters (PgStat_TableXactStatus *trans)
 
void pgstat_count_truncate (Relation rel)
 
void pgstat_update_heap_dead_tuples (Relation rel, int delta)
 
void AtEOXact_PgStat (bool isCommit)
 
void AtEOSubXact_PgStat (bool isCommit, int nestDepth)
 
void AtPrepare_PgStat (void)
 
void PostPrepare_PgStat (void)
 
void pgstat_twophase_postcommit (TransactionId xid, uint16 info, void *recdata, uint32 len)
 
void pgstat_twophase_postabort (TransactionId xid, uint16 info, void *recdata, uint32 len)
 
PgStat_StatDBEntrypgstat_fetch_stat_dbentry (Oid dbid)
 
PgStat_StatTabEntrypgstat_fetch_stat_tabentry (Oid relid)
 
PgStat_StatFuncEntrypgstat_fetch_stat_funcentry (Oid func_id)
 
PgBackendStatuspgstat_fetch_stat_beentry (int beid)
 
LocalPgBackendStatuspgstat_fetch_stat_local_beentry (int beid)
 
int pgstat_fetch_stat_numbackends (void)
 
PgStat_ArchiverStatspgstat_fetch_stat_archiver (void)
 
PgStat_GlobalStatspgstat_fetch_global (void)
 
Size BackendStatusShmemSize (void)
 
void CreateSharedBackendStatus (void)
 
void pgstat_initialize (void)
 
void pgstat_bestart (void)
 
void pgstat_report_activity (BackendState state, const char *cmd_str)
 
void pgstat_progress_start_command (ProgressCommandType cmdtype, Oid relid)
 
void pgstat_progress_update_param (int index, int64 val)
 
void pgstat_progress_update_multi_param (int nparam, const int *index, const int64 *val)
 
void pgstat_progress_end_command (void)
 
void pgstat_report_appname (const char *appname)
 
void pgstat_report_xact_timestamp (TimestampTz tstamp)
 
const char * pgstat_get_wait_event_type (uint32 wait_event_info)
 
const char * pgstat_get_wait_event (uint32 wait_event_info)
 
const char * pgstat_get_backend_current_activity (int pid, bool checkUser)
 
const char * pgstat_get_crashed_backend_activity (int pid, char *buffer, int buflen)
 
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 1779 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().

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

Definition at line 727 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

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

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

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

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

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

2135 {
2136  PgStat_SubXactStatus *xact_state;
2137 
2138  xact_state = pgStatXactStack;
2139  if (xact_state != NULL)
2140  {
2142 
2143  Assert(xact_state->nest_level == 1);
2144  Assert(xact_state->prev == NULL);
2145  for (trans = xact_state->first; trans != NULL; trans = trans->next)
2146  {
2147  PgStat_TableStatus *tabstat;
2148  TwoPhasePgStatRecord record;
2149 
2150  Assert(trans->nest_level == 1);
2151  Assert(trans->upper == NULL);
2152  tabstat = trans->parent;
2153  Assert(tabstat->trans == trans);
2154 
2155  record.tuples_inserted = trans->tuples_inserted;
2156  record.tuples_updated = trans->tuples_updated;
2157  record.tuples_deleted = trans->tuples_deleted;
2158  record.inserted_pre_trunc = trans->inserted_pre_trunc;
2159  record.updated_pre_trunc = trans->updated_pre_trunc;
2160  record.deleted_pre_trunc = trans->deleted_pre_trunc;
2161  record.t_id = tabstat->t_id;
2162  record.t_shared = tabstat->t_shared;
2163  record.t_truncated = trans->truncated;
2164 
2166  &record, sizeof(TwoPhasePgStatRecord));
2167  }
2168  }
2169 }
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:1120
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:229
#define Assert(condition)
Definition: c.h:675
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:382
PgStat_TableXactStatus * first
Definition: pgstat.c:186
PgStat_TableStatus * parent
Definition: pgstat.h:177
static void backend_read_statsfile ( void  )
static

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

5134 {
5135  TimestampTz min_ts = 0;
5136  TimestampTz ref_ts = 0;
5137  Oid inquiry_db;
5138  int count;
5139 
5140  /* already read it? */
5141  if (pgStatDBHash)
5142  return;
5144 
5145  /*
5146  * In a normal backend, we check staleness of the data for our own DB, and
5147  * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5148  * check staleness of the shared-catalog data, and send InvalidOid in
5149  * inquiry messages so as not to force writing unnecessary data.
5150  */
5152  inquiry_db = InvalidOid;
5153  else
5154  inquiry_db = MyDatabaseId;
5155 
5156  /*
5157  * Loop until fresh enough stats file is available or we ran out of time.
5158  * The stats inquiry message is sent repeatedly in case collector drops
5159  * it; but not every single time, as that just swamps the collector.
5160  */
5161  for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5162  {
5163  bool ok;
5164  TimestampTz file_ts = 0;
5165  TimestampTz cur_ts;
5166 
5168 
5169  ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5170 
5171  cur_ts = GetCurrentTimestamp();
5172  /* Calculate min acceptable timestamp, if we didn't already */
5173  if (count == 0 || cur_ts < ref_ts)
5174  {
5175  /*
5176  * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5177  * msec before now. This indirectly ensures that the collector
5178  * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5179  * an autovacuum worker, however, we want a lower delay to avoid
5180  * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5181  * number of workers is low, this shouldn't be a problem).
5182  *
5183  * We don't recompute min_ts after sleeping, except in the
5184  * unlikely case that cur_ts went backwards. So we might end up
5185  * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5186  * practice that shouldn't happen, though, as long as the sleep
5187  * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5188  * tell the collector that our cutoff time is less than what we'd
5189  * actually accept.
5190  */
5191  ref_ts = cur_ts;
5193  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5195  else
5196  min_ts = TimestampTzPlusMilliseconds(ref_ts,
5198  }
5199 
5200  /*
5201  * If the file timestamp is actually newer than cur_ts, we must have
5202  * had a clock glitch (system time went backwards) or there is clock
5203  * skew between our processor and the stats collector's processor.
5204  * Accept the file, but send an inquiry message anyway to make
5205  * pgstat_recv_inquiry do a sanity check on the collector's time.
5206  */
5207  if (ok && file_ts > cur_ts)
5208  {
5209  /*
5210  * A small amount of clock skew between processors isn't terribly
5211  * surprising, but a large difference is worth logging. We
5212  * arbitrarily define "large" as 1000 msec.
5213  */
5214  if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5215  {
5216  char *filetime;
5217  char *mytime;
5218 
5219  /* Copy because timestamptz_to_str returns a static buffer */
5220  filetime = pstrdup(timestamptz_to_str(file_ts));
5221  mytime = pstrdup(timestamptz_to_str(cur_ts));
5222  elog(LOG, "stats collector's time %s is later than backend local time %s",
5223  filetime, mytime);
5224  pfree(filetime);
5225  pfree(mytime);
5226  }
5227 
5228  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5229  break;
5230  }
5231 
5232  /* Normal acceptance case: file is not older than cutoff time */
5233  if (ok && file_ts >= min_ts)
5234  break;
5235 
5236  /* Not there or too old, so kick the collector and wait a bit */
5237  if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5238  pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5239 
5240  pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5241  }
5242 
5243  if (count >= PGSTAT_POLL_LOOP_COUNT)
5244  ereport(LOG,
5245  (errmsg("using stale statistics instead of current ones "
5246  "because stats collector is not responding")));
5247 
5248  /*
5249  * Autovacuum launcher wants stats about all databases, but a shallow read
5250  * is sufficient. Regular backends want a deep read for just the tables
5251  * they can see (MyDatabaseId + shared catalogs).
5252  */
5255  else
5257 }
#define PGSTAT_RETRY_DELAY
Definition: pgstat.c:79
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
#define PGSTAT_INQ_LOOP_COUNT
Definition: pgstat.c:93
char * pstrdup(const char *in)
Definition: mcxt.c:1077
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
void pfree(void *pointer)
Definition: mcxt.c:950
static void pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
Definition: pgstat.c:1489
#define PGSTAT_STAT_INTERVAL
Definition: pgstat.c:76
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2988
#define ereport(elevel, rest)
Definition: elog.h:122
static HTAB * pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
Definition: pgstat.c:4641
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidOid
Definition: postgres_ext.h:36
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
static bool pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent, TimestampTz *ts)
Definition: pgstat.c:5014
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:2982
#define Assert(condition)
Definition: c.h:675
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:1709
Size BackendStatusShmemSize ( void  )

Definition at line 2503 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

2504 {
2505  Size size;
2506 
2507  /* BackendStatusArray: */
2508  size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2509  /* BackendAppnameBuffer: */
2510  size = add_size(size,
2512  /* BackendClientHostnameBuffer: */
2513  size = add_size(size,
2515  /* BackendActivityBuffer: */
2516  size = add_size(size,
2518 #ifdef USE_SSL
2519  /* BackendSslStatusBuffer: */
2520  size = add_size(size,
2522 #endif
2523  return size;
2524 }
#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:356
void CreateSharedBackendStatus ( void  )

Definition at line 2531 of file pgstat.c.

References BackendActivityBuffer, BackendAppnameBuffer, BackendClientHostnameBuffer, buffer, 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().

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

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

1559 {
1560  if (pgStatFunctions == NULL)
1561  return NULL;
1562 
1564  (void *) &func_id,
1565  HASH_FIND, NULL);
1566 }
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:229
PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id)

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

1734 {
1735  PgStat_TableStatus *entry;
1736  TabStatusArray *tsa;
1737  int i;
1738 
1739  for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
1740  {
1741  for (i = 0; i < tsa->tsa_used; i++)
1742  {
1743  entry = &tsa->tsa_entries[i];
1744  if (entry->t_id == rel_id)
1745  return entry;
1746  }
1747  }
1748 
1749  /* Not present */
1750  return NULL;
1751 }
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:229
int i
static void get_dbstat_filename ( bool  permanent,
bool  tempname,
Oid  databaseid,
char *  filename,
int  len 
)
static

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

4494 {
4495  int printed;
4496 
4497  /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4498  printed = snprintf(filename, len, "%s/db_%u.%s",
4499  permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4501  databaseid,
4502  tempname ? "tmp" : "stat");
4503  if (printed > len)
4504  elog(ERROR, "overlength pgstat path");
4505 }
#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:87
#define elog
Definition: elog.h:219
static PgStat_TableStatus * get_tabstat_entry ( Oid  rel_id,
bool  isshared 
)
static

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

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

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

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

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

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

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

2664 {
2665  TimestampTz proc_start_timestamp;
2666  Oid userid;
2667  SockAddr clientaddr;
2668  volatile PgBackendStatus *beentry;
2669 
2670  /*
2671  * To minimize the time spent modifying the PgBackendStatus entry, fetch
2672  * all the needed data first.
2673  *
2674  * If we have a MyProcPort, use its session start time (for consistency,
2675  * and to save a kernel call).
2676  */
2677  if (MyProcPort)
2678  proc_start_timestamp = MyProcPort->SessionStartTime;
2679  else
2680  proc_start_timestamp = GetCurrentTimestamp();
2681  userid = GetSessionUserId();
2682 
2683  /*
2684  * We may not have a MyProcPort (eg, if this is the autovacuum process).
2685  * If so, use all-zeroes client address, which is dealt with specially in
2686  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2687  */
2688  if (MyProcPort)
2689  memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2690  else
2691  MemSet(&clientaddr, 0, sizeof(clientaddr));
2692 
2693  /*
2694  * Initialize my status entry, following the protocol of bumping
2695  * st_changecount before and after; and make sure it's even afterwards. We
2696  * use a volatile pointer here to ensure the compiler doesn't try to get
2697  * cute.
2698  */
2699  beentry = MyBEEntry;
2700  do
2701  {
2703  } while ((beentry->st_changecount & 1) == 0);
2704 
2705  beentry->st_procpid = MyProcPid;
2706  beentry->st_proc_start_timestamp = proc_start_timestamp;
2707  beentry->st_activity_start_timestamp = 0;
2708  beentry->st_state_start_timestamp = 0;
2709  beentry->st_xact_start_timestamp = 0;
2710  beentry->st_databaseid = MyDatabaseId;
2711  beentry->st_userid = userid;
2712  beentry->st_clientaddr = clientaddr;
2715  NAMEDATALEN);
2716  else
2717  beentry->st_clienthostname[0] = '\0';
2718 #ifdef USE_SSL
2719  if (MyProcPort && MyProcPort->ssl != NULL)
2720  {
2721  beentry->st_ssl = true;
2727  }
2728  else
2729  {
2730  beentry->st_ssl = false;
2731  }
2732 #else
2733  beentry->st_ssl = false;
2734 #endif
2735  beentry->st_state = STATE_UNDEFINED;
2736  beentry->st_appname[0] = '\0';
2737  beentry->st_activity[0] = '\0';
2738  /* Also make sure the last byte in each string area is always 0 */
2739  beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
2740  beentry->st_appname[NAMEDATALEN - 1] = '\0';
2741  beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2744 
2745  /*
2746  * we don't zero st_progress_param here to save cycles; nobody should
2747  * examine it until st_progress_command has been set to something other
2748  * than PROGRESS_COMMAND_INVALID
2749  */
2750 
2752 
2753  /* Update app name to current GUC setting */
2754  if (application_name)
2756 }
bool ssl_compression
Definition: pgstat.h:916
char ssl_cipher[NAMEDATALEN]
Definition: pgstat.h:918
Oid st_progress_command_target
Definition: pgstat.h:989
int MyProcPid
Definition: globals.c:38
struct Port * MyProcPort
Definition: globals.c:40
TimestampTz st_activity_start_timestamp
Definition: pgstat.h:957
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
char ssl_version[NAMEDATALEN]
Definition: pgstat.h:917
SockAddr st_clientaddr
Definition: pgstat.h:963
#define MemSet(start, val, len)
Definition: c.h:857
ProgressCommandType st_progress_command
Definition: pgstat.h:988
unsigned int Oid
Definition: postgres_ext.h:31
BackendState st_state
Definition: pgstat.h:971
char * st_clienthostname
Definition: pgstat.h:964
Oid GetSessionUserId(void)
Definition: miscinit.c:317
Oid st_databaseid
Definition: pgstat.h:961
#define NAMEDATALEN
char * remote_hostname
Definition: libpq-be.h:124
SockAddr raddr
Definition: libpq-be.h:122
bool be_tls_get_compression(Port *port)
TimestampTz SessionStartTime
Definition: libpq-be.h:151
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2489
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1005
int pgstat_track_activity_query_size
Definition: pgstat.c:112
TimestampTz st_state_start_timestamp
Definition: pgstat.h:958
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1011
char * st_appname
Definition: pgstat.h:974
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:2975
#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:229
char * st_activity
Definition: pgstat.h:977
int st_procpid
Definition: pgstat.h:952
char * application_name
Definition: guc.c:472
void be_tls_get_cipher(Port *port, char *ptr, size_t len)
TimestampTz st_xact_start_timestamp
Definition: pgstat.h:956
int st_changecount
Definition: pgstat.h:949
TimestampTz st_proc_start_timestamp
Definition: pgstat.h:955
PgBackendSSLStatus * st_sslstatus
Definition: pgstat.h:968
char ssl_clientdn[NAMEDATALEN]
Definition: pgstat.h:919
void pgstat_clear_snapshot ( void  )

Definition at line 5287 of file pgstat.c.

References localNumBackends, MemoryContextDelete(), and NULL.

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

5288 {
5289  /* Release memory, if any was allocated */
5290  if (pgStatLocalContext)
5292 
5293  /* Reset variables */
5295  pgStatDBHash = NULL;
5297  localNumBackends = 0;
5298 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define NULL
Definition: c.h:229
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 1129 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().

1130 {
1131  HTAB *htab;
1132  HASHCTL hash_ctl;
1133  Relation rel;
1134  HeapScanDesc scan;
1135  HeapTuple tup;
1136  Snapshot snapshot;
1137 
1138  memset(&hash_ctl, 0, sizeof(hash_ctl));
1139  hash_ctl.keysize = sizeof(Oid);
1140  hash_ctl.entrysize = sizeof(Oid);
1141  hash_ctl.hcxt = CurrentMemoryContext;
1142  htab = hash_create("Temporary table of OIDs",
1144  &hash_ctl,
1146 
1147  rel = heap_open(catalogid, AccessShareLock);
1148  snapshot = RegisterSnapshot(GetLatestSnapshot());
1149  scan = heap_beginscan(rel, snapshot, 0, NULL);
1150  while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1151  {
1152  Oid thisoid = HeapTupleGetOid(tup);
1153 
1155 
1156  (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1157  }
1158  heap_endscan(scan);
1159  UnregisterSnapshot(snapshot);
1161 
1162  return htab;
1163 }
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:1797
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
Size keysize
Definition: hsearch.h:72
#define NULL
Definition: c.h:229
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:375
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
Definition: heapam.c:1394
void pgstat_count_heap_delete ( Relation  rel)

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

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

Definition at line 1806 of file pgstat.c.

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

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

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

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

1828 {
1829  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1830 
1831  if (pgstat_info != NULL)
1832  {
1833  /* We have to log the effect at the proper transactional level */
1834  int nest_level = GetCurrentTransactionNestLevel();
1835 
1836  if (pgstat_info->trans == NULL ||
1837  pgstat_info->trans->nest_level != nest_level)
1838  add_tabstat_xact_level(pgstat_info, nest_level);
1839 
1840  pgstat_info->trans->tuples_updated++;
1841 
1842  /* t_tuples_hot_updated is nontransactional, so just advance it */
1843  if (hot)
1844  pgstat_info->t_counts.t_tuples_hot_updated++;
1845  }
1846 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
PgStat_Counter t_tuples_hot_updated
Definition: pgstat.h:107
PgStat_TableCounts t_counts
Definition: pgstat.h:158
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1779
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
void pgstat_count_truncate ( Relation  rel)

Definition at line 1907 of file pgstat.c.

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

Referenced by ExecRefreshMatView(), and ExecuteTruncate().

1908 {
1909  PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1910 
1911  if (pgstat_info != NULL)
1912  {
1913  /* We have to log the effect at the proper transactional level */
1914  int nest_level = GetCurrentTransactionNestLevel();
1915 
1916  if (pgstat_info->trans == NULL ||
1917  pgstat_info->trans->nest_level != nest_level)
1918  add_tabstat_xact_level(pgstat_info, nest_level);
1919 
1920  pgstat_truncate_save_counters(pgstat_info->trans);
1921  pgstat_info->trans->tuples_inserted = 0;
1922  pgstat_info->trans->tuples_updated = 0;
1923  pgstat_info->trans->tuples_deleted = 0;
1924  }
1925 }
PgStat_Counter tuples_updated
Definition: pgstat.h:168
PgStat_Counter tuples_inserted
Definition: pgstat.h:167
PgStat_Counter tuples_deleted
Definition: pgstat.h:169
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:218
static void add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
Definition: pgstat.c:1779
struct PgStat_TableXactStatus * trans
Definition: pgstat.h:157
static void pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
Definition: pgstat.c:1878
static bool pgstat_db_requested ( Oid  databaseid)
static

Definition at line 5991 of file pgstat.c.

References InvalidOid, list_member_oid(), and NIL.

Referenced by pgstat_write_statsfiles().

5992 {
5993  /*
5994  * If any requests are outstanding at all, we should write the stats for
5995  * shared catalogs (the "database" with OID 0). This ensures that
5996  * backends will see up-to-date stats for shared catalogs, even though
5997  * they send inquiry messages mentioning only their own DB.
5998  */
5999  if (databaseid == InvalidOid && pending_write_requests != NIL)
6000  return true;
6001 
6002  /* Search to see if there's an open request to write this database. */
6003  if (list_member_oid(pending_write_requests, databaseid))
6004  return true;
6005 
6006  return false;
6007 }
#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 1175 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().

1176 {
1177  PgStat_MsgDropdb msg;
1178 
1180  return;
1181 
1183  msg.m_databaseid = databaseid;
1184  pgstat_send(&msg, sizeof(msg));
1185 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:3859
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:3846
void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1578 of file pgstat.c.

References PgStat_FunctionCounts::f_numcalls, PgStat_FunctionCounts::f_self_time, PgStat_FunctionCallUsage::f_start, PgStat_FunctionCounts::f_total_time, PgStat_FunctionCallUsage::fs, have_function_stats, INSTR_TIME_ADD, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, NULL, PgStat_FunctionCallUsage::save_f_total_time, PgStat_FunctionCallUsage::save_total, and total_func_time.

Referenced by call_pltcl_start_proc(), EventTriggerInvoke(), ExecCallTriggerFunc(), ExecMakeFunctionResultNoSets(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

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

Definition at line 4200 of file pgstat.c.

References MyLatch, need_exit, and SetLatch().

Referenced by PgstatCollectorMain().

4201 {
4202  int save_errno = errno;
4203 
4204  need_exit = true;
4205  SetLatch(MyLatch);
4206 
4207  errno = save_errno;
4208 }
static volatile bool need_exit
Definition: pgstat.c:234
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
struct Latch * MyLatch
Definition: globals.c:51
PgStat_ArchiverStats* pgstat_fetch_stat_archiver ( void  )

Definition at line 2458 of file pgstat.c.

References archiverStats, and backend_read_statsfile().

Referenced by pg_stat_get_archiver().

2459 {
2461 
2462  return &archiverStats;
2463 }
static void backend_read_statsfile(void)
Definition: pgstat.c:5133
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 2286 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().

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

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

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

Definition at line 2423 of file pgstat.c.

References localNumBackends, NULL, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), and pg_stat_get_progress_info().

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

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

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

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

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

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

3701 {
3702  PgBackendStatus *beentry;
3703  int i;
3704 
3705  beentry = BackendStatusArray;
3706  for (i = 1; i <= MaxBackends; i++)
3707  {
3708  /*
3709  * Although we expect the target backend's entry to be stable, that
3710  * doesn't imply that anyone else's is. To avoid identifying the
3711  * wrong backend, while we check for a match to the desired PID we
3712  * must follow the protocol of retrying if st_changecount changes
3713  * while we examine the entry, or if it's odd. (This might be
3714  * unnecessary, since fetching or storing an int is almost certainly
3715  * atomic, but let's play it safe.) We use a volatile pointer here to
3716  * ensure the compiler doesn't try to get cute.
3717  */
3718  volatile PgBackendStatus *vbeentry = beentry;
3719  bool found;
3720 
3721  for (;;)
3722  {
3723  int before_changecount;
3724  int after_changecount;
3725 
3726  pgstat_save_changecount_before(vbeentry, before_changecount);
3727 
3728  found = (vbeentry->st_procpid == pid);
3729 
3730  pgstat_save_changecount_after(vbeentry, after_changecount);
3731 
3732  if (before_changecount == after_changecount &&
3733  (before_changecount & 1) == 0)
3734  break;
3735 
3736  /* Make sure we can break out of loop if stuck... */
3738  }
3739 
3740  if (found)
3741  {
3742  /* Now it is safe to use the non-volatile pointer */
3743  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
3744  return "<insufficient privilege>";
3745  else if (*(beentry->st_activity) == '\0')
3746  return "<command string not enabled>";
3747  else
3748  return beentry->st_activity;
3749  }
3750 
3751  beentry++;
3752  }
3753 
3754  /* If we get here, caller is in error ... */
3755  return "<backend information not available>";
3756 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2488
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:1018
char * st_activity
Definition: pgstat.h:977
#define pgstat_save_changecount_after(beentry, save_changecount)
Definition: pgstat.h:1024
int st_procpid
Definition: pgstat.h:952
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 3775 of file pgstat.c.

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

Referenced by LogChildExit().

3776 {
3777  volatile PgBackendStatus *beentry;
3778  int i;
3779 
3780  beentry = BackendStatusArray;
3781 
3782  /*
3783  * We probably shouldn't get here before shared memory has been set up,
3784  * but be safe.
3785  */
3786  if (beentry == NULL || BackendActivityBuffer == NULL)
3787  return NULL;
3788 
3789  for (i = 1; i <= MaxBackends; i++)
3790  {
3791  if (beentry->st_procpid == pid)
3792  {
3793  /* Read pointer just once, so it can't change after validation */
3794  const char *activity = beentry->st_activity;
3795  const char *activity_last;
3796 
3797  /*
3798  * We mustn't access activity string before we verify that it
3799  * falls within the BackendActivityBuffer. To make sure that the
3800  * entire string including its ending is contained within the
3801  * buffer, subtract one activity length from the buffer size.
3802  */
3805 
3806  if (activity < BackendActivityBuffer ||
3807  activity > activity_last)
3808  return NULL;
3809 
3810  /* If no string available, no point in a report */
3811  if (activity[0] == '\0')
3812  return NULL;
3813 
3814  /*
3815  * Copy only ASCII-safe characters so we don't run into encoding
3816  * problems when reporting the message; and be sure not to run off
3817  * the end of memory.
3818  */
3819  ascii_safe_strlcpy(buffer, activity,
3820  Min(buflen, pgstat_track_activity_query_size));
3821 
3822  return buffer;
3823  }
3824 
3825  beentry++;
3826  }
3827 
3828  /* PID not found */
3829  return NULL;
3830 }
static PgBackendStatus * BackendStatusArray
Definition: pgstat.c:2488
static char * BackendActivityBuffer
Definition: pgstat.c:2492
#define Min(x, y)
Definition: c.h:806
static Size BackendActivityBufferSize
Definition: pgstat.c:2493
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:229
char * st_activity
Definition: pgstat.h:977
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
int st_procpid
Definition: pgstat.h:952
int i
static PgStat_StatDBEntry * pgstat_get_db_entry ( Oid  databaseid,
bool  create 
)
static

Definition at line 4278 of file pgstat.c.

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

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

4279 {
4281  bool found;
4282  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4283 
4284  /* Lookup or create the hash table entry for this database */
4286  &databaseid,
4287  action, &found);
4288 
4289  if (!create && !found)
4290  return NULL;
4291 
4292  /*
4293  * If not found, initialize the new one. This creates empty hash tables
4294  * for tables and functions, too.
4295  */
4296  if (!found)
4297  reset_dbentry_counters(result);
4298 
4299  return result;
4300 }
static void reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
Definition: pgstat.c:4228
return result
Definition: formatting.c:1618
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define NULL
Definition: c.h:229
static HTAB * pgStatDBHash
Definition: pgstat.c:214
HASHACTION
Definition: hsearch.h:103
static PgStat_StatTabEntry * pgstat_get_tab_entry ( PgStat_StatDBEntry dbentry,
Oid  tableoid,
bool  create 
)
static

Definition at line 4309 of file pgstat.c.

References PgStat_StatTabEntry::analyze_count, PgStat_StatTabEntry::analyze_timestamp, PgStat_StatTabEntry::autovac_analyze_count, PgStat_StatTabEntry::autovac_analyze_timestamp, PgStat_StatTabEntry::autovac_vacuum_count, PgStat_StatTabEntry::autovac_vacuum_timestamp, PgStat_StatTabEntry::blocks_fetched, PgStat_StatTabEntry::blocks_hit, PgStat_StatTabEntry::changes_since_analyze, HASH_ENTER, HASH_FIND, hash_search(), PgStat_StatTabEntry::n_dead_tuples, PgStat_StatTabEntry::n_live_tuples, NULL, PgStat_StatTabEntry::numscans, result, PgStat_StatDBEntry::tables, PgStat_StatTabEntry::tuples_deleted, PgStat_StatTabEntry::tuples_fetched, PgStat_StatTabEntry::tuples_hot_updated, PgStat_StatTabEntry::tuples_inserted, PgStat_StatTabEntry::tuples_returned, PgStat_StatTabEntry::tuples_updated, PgStat_StatTabEntry::vacuum_count, and PgStat_StatTabEntry::vacuum_timestamp.

Referenced by pgstat_recv_analyze(), and pgstat_recv_vacuum().

4310 {
4312  bool found;
4313  HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4314 
4315  /* Lookup or create the hash table entry for this table */
4316  result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4317  &tableoid,
4318  action, &found);
4319 
4320  if (!create && !found)
4321  return NULL;
4322 
4323  /* If not found, initialize the new one. */
4324  if (!found)
4325  {
4326  result->numscans = 0;
4327  result->tuples_returned = 0;
4328  result->tuples_fetched = 0;
4329  result->tuples_inserted = 0;
4330  result->tuples_updated = 0;
4331  result->tuples_deleted = 0;
4332  result->tuples_hot_updated = 0;
4333  result->n_live_tuples = 0;
4334  result->n_dead_tuples = 0;
4335  result->changes_since_analyze = 0;
4336  result->blocks_fetched = 0;
4337  result->blocks_hit = 0;
4338  result->vacuum_timestamp = 0;
4339  result->vacuum_count = 0;
4340  result->autovac_vacuum_timestamp = 0;
4341  result->autovac_vacuum_count = 0;
4342  result->analyze_timestamp = 0;
4343  result->analyze_count = 0;
4344  result->autovac_analyze_timestamp = 0;
4345  result->autovac_analyze_count = 0;
4346  }
4347 
4348  return result;
4349 }
PgStat_Counter analyze_count
Definition: pgstat.h:641
PgStat_Counter tuples_returned
Definition: pgstat.h:621
TimestampTz autovac_analyze_timestamp
Definition: pgstat.h:642
PgStat_Counter vacuum_count
Definition: pgstat.h:637
return result
Definition: formatting.c:1618
PgStat_Counter numscans
Definition: pgstat.h:619
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
PgStat_Counter tuples_hot_updated
Definition: pgstat.h:627
PgStat_Counter tuples_inserted
Definition: pgstat.h:624
PgStat_Counter n_live_tuples
Definition: pgstat.h:629
TimestampTz vacuum_timestamp
Definition: pgstat.h:636
PgStat_Counter n_dead_tuples
Definition: pgstat.h:630
PgStat_Counter tuples_fetched
Definition: pgstat.h:622
PgStat_Counter blocks_hit
Definition: pgstat.h:634
TimestampTz analyze_timestamp
Definition: pgstat.h:640
PgStat_Counter changes_since_analyze
Definition: pgstat.h:631
#define NULL
Definition: c.h:229
PgStat_Counter tuples_deleted
Definition: pgstat.h:626
PgStat_Counter tuples_updated
Definition: pgstat.h:625
TimestampTz autovac_vacuum_timestamp
Definition: pgstat.h:638
PgStat_Counter autovac_analyze_count
Definition: pgstat.h:643
PgStat_Counter blocks_fetched
Definition: pgstat.h:633
HASHACTION
Definition: hsearch.h:103
PgStat_Counter autovac_vacuum_count
Definition: pgstat.h:639
static const char * pgstat_get_wait_activity ( WaitEventActivity  w)
static

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

3276 {
3277  const char *event_name = "unknown wait event";
3278 
3279  switch (w)
3280  {
3282  event_name = "ArchiverMain";
3283  break;
3285  event_name = "AutoVacuumMain";
3286  break;
3288  event_name = "BgWriterHibernate";
3289  break;
3291  event_name = "BgWriterMain";
3292  break;
3294  event_name = "CheckpointerMain";
3295  break;
3297  event_name = "PgStatMain";
3298  break;
3300  event_name = "RecoveryWalAll";
3301  break;
3303  event_name = "RecoveryWalStream";
3304  break;
3306  event_name = "SysLoggerMain";
3307  break;
3309  event_name = "WalReceiverMain";
3310  break;
3312  event_name = "WalSenderMain";
3313  break;
3315  event_name = "WalWriterMain";
3316  break;
3318  event_name = "LogicalLauncherMain";
3319  break;
3321  event_name = "LogicalApplyMain";
3322  break;
3323  /* no default case, so that compiler will warn */
3324  }
3325 
3326  return event_name;
3327 }
static const char * pgstat_get_wait_client ( WaitEventClient  w)
static

Definition at line 3336 of file pgstat.c.

References WAIT_EVENT_CLIENT_READ, WAIT_EVENT_CLIENT_WRITE, WAIT_EVENT_LIBPQWALRECEIVER, WAIT_EVENT_SSL_OPEN_SERVER, WAIT_EVENT_WAL_RECEIVER_WAIT_START, WAIT_EVENT_WAL_SENDER_WAIT_WAL, and WAIT_EVENT_WAL_SENDER_WRITE_DATA.

Referenced by pgstat_get_wait_event().

3337 {
3338  const char *event_name = "unknown wait event";
3339 
3340  switch (w)
3341  {
3343  event_name = "ClientRead";
3344  break;
3346  event_name = "ClientWrite";
3347  break;
3349  event_name = "SSLOpenServer";
3350  break;
3352  event_name = "WalReceiverWaitStart";
3353  break;
3355  event_name = "LibPQWalReceiver";
3356  break;
3358  event_name = "WalSenderWaitForWAL";
3359  break;
3361  event_name = "WalSenderWriteData";
3362  break;
3363  /* no default case, so that compiler will warn */
3364  }
3365 
3366  return event_name;
3367 }
const char* pgstat_get_wait_event ( uint32  wait_event_info)

Definition at line 3198 of file pgstat.c.

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

Referenced by pg_stat_get_activity(), and pg_stat_get_backend_wait_event().

3199 {
3200  uint32 classId;
3201  uint16 eventId;
3202  const char *event_name;
3203 
3204  /* report process as not waiting. */
3205  if (wait_event_info == 0)
3206  return NULL;
3207 
3208  classId = wait_event_info & 0xFF000000;
3209  eventId = wait_event_info & 0x0000FFFF;
3210 
3211  switch (classId)
3212  {
3213  case PG_WAIT_LWLOCK:
3214  event_name = GetLWLockIdentifier(classId, eventId);
3215  break;
3216  case PG_WAIT_LOCK:
3217  event_name = GetLockNameFromTagType(eventId);
3218  break;
3219  case PG_WAIT_BUFFER_PIN:
3220  event_name = "BufferPin";
3221  break;
3222  case PG_WAIT_ACTIVITY:
3223  {
3224  WaitEventActivity w = (WaitEventActivity) wait_event_info;
3225 
3226  event_name = pgstat_get_wait_activity(w);
3227  break;
3228  }
3229  case PG_WAIT_CLIENT:
3230  {
3231  WaitEventClient w = (WaitEventClient) wait_event_info;
3232 
3233  event_name = pgstat_get_wait_client(w);
3234  break;
3235  }
3236  case PG_WAIT_EXTENSION:
3237  event_name = "Extension";
3238  break;
3239  case PG_WAIT_IPC:
3240  {
3241  WaitEventIPC w = (WaitEventIPC) wait_event_info;
3242 
3243  event_name = pgstat_get_wait_ipc(w);
3244  break;
3245  }
3246  case PG_WAIT_TIMEOUT:
3247  {
3248  WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3249 
3250  event_name = pgstat_get_wait_timeout(w);
3251  break;
3252  }
3253  case PG_WAIT_IO:
3254  {
3255  WaitEventIO w = (WaitEventIO) wait_event_info;
3256 
3257  event_name = pgstat_get_wait_io(w);
3258  break;
3259  }
3260  default:
3261  event_name = "unknown wait event";
3262  break;
3263  }
3264 
3265  return event_name;
3266 }
#define PG_WAIT_LOCK
Definition: pgstat.h:719
WaitEventIPC
Definition: pgstat.h:780
static const char * pgstat_get_wait_timeout(WaitEventTimeout w)
Definition: pgstat.c:3437
static const char * pgstat_get_wait_ipc(WaitEventIPC w)
Definition: pgstat.c:3376
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:721
#define PG_WAIT_IO
Definition: pgstat.h:726
static const char * pgstat_get_wait_activity(WaitEventActivity w)
Definition: pgstat.c:3275
unsigned short uint16
Definition: c.h:267
#define PG_WAIT_CLIENT
Definition: pgstat.h:722
WaitEventClient
Definition: pgstat.h:762
static const char * pgstat_get_wait_client(WaitEventClient w)
Definition: pgstat.c:3336
unsigned int uint32
Definition: c.h:268
WaitEventTimeout
Definition: pgstat.h:804
#define PG_WAIT_EXTENSION
Definition: pgstat.h:723
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:720
#define NULL
Definition: c.h:229
const char * GetLockNameFromTagType(uint16 locktag_type)
Definition: lmgr.c:1039
WaitEventIO
Definition: pgstat.h:817
#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:703
static const char * pgstat_get_wait_io(WaitEventIO w)
Definition: pgstat.c:3465
#define PG_WAIT_LWLOCK
Definition: pgstat.h:718
WaitEventActivity
Definition: pgstat.h:736
const char* pgstat_get_wait_event_type ( uint32  wait_event_info)

Definition at line 3143 of file pgstat.c.

References NULL, PG_WAIT_ACTIVITY, PG_WAIT_BUFFER_PIN, PG_WAIT_CLIENT, PG_WAIT_EXTENSION, PG_WAIT_IO, PG_WAIT_IPC, PG_WAIT_LOCK, PG_WAIT_LWLOCK, and PG_WAIT_TIMEOUT.

Referenced by pg_stat_get_activity(), and pg_stat_get_backend_wait_event_type().

3144 {
3145  uint32 classId;
3146  const char *event_type;
3147 
3148  /* report process as not waiting. */
3149  if (wait_event_info == 0)
3150  return NULL;
3151 
3152  classId = wait_event_info & 0xFF000000;
3153 
3154  switch (classId)
3155  {
3156  case PG_WAIT_LWLOCK:
3157  event_type = "LWLock";
3158  break;
3159  case PG_WAIT_LOCK:
3160  event_type = "Lock";
3161  break;
3162  case PG_WAIT_BUFFER_PIN:
3163  event_type = "BufferPin";
3164  break;
3165  case PG_WAIT_ACTIVITY:
3166  event_type = "Activity";
3167  break;
3168  case PG_WAIT_CLIENT:
3169  event_type = "Client";
3170  break;
3171  case PG_WAIT_EXTENSION:
3172  event_type = "Extension";
3173  break;
3174  case PG_WAIT_IPC:
3175  event_type = "IPC";
3176  break;
3177  case PG_WAIT_TIMEOUT:
3178  event_type = "Timeout";
3179  break;
3180  case PG_WAIT_IO:
3181  event_type = "IO";
3182  break;
3183  default:
3184  event_type = "???";
3185  break;
3186  }
3187 
3188  return event_type;
3189 }
#define PG_WAIT_LOCK
Definition: pgstat.h:719
#define PG_WAIT_ACTIVITY
Definition: pgstat.h:721
#define PG_WAIT_IO
Definition: pgstat.h:726
#define PG_WAIT_CLIENT
Definition: pgstat.h:722
unsigned int uint32
Definition: c.h:268
#define PG_WAIT_EXTENSION
Definition: pgstat.h:723
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:720
#define NULL
Definition: c.h:229
#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_io ( WaitEventIO  w)
static

Definition at line 3465 of file pgstat.c.

References WAIT_EVENT_BUFFILE_READ, WAIT_EVENT_BUFFILE_WRITE, WAIT_EVENT_CONTROL_FILE_READ, WAIT_EVENT_CONTROL_FILE_SYNC, WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE, WAIT_EVENT_CONTROL_FILE_WRITE, WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE, WAIT_EVENT_COPY_FILE_READ, WAIT_EVENT_COPY_FILE_WRITE, WAIT_EVENT_DATA_FILE_EXTEND, WAIT_EVENT_DATA_FILE_FLUSH, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC, WAIT_EVENT_DATA_FILE_PREFETCH, WAIT_EVENT_DATA_FILE_READ, WAIT_EVENT_DATA_FILE_SYNC, WAIT_EVENT_DATA_FILE_TRUNCATE, WAIT_EVENT_DATA_FILE_WRITE, WAIT_EVENT_DSM_FILL_ZERO_WRITE, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE, WAIT_EVENT_LOCK_FILE_CREATE_READ, WAIT_EVENT_LOCK_FILE_CREATE_SYNC, WAIT_EVENT_LOCK_FILE_CREATE_WRITE, WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ, WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC, WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC, WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE, WAIT_EVENT_LOGICAL_REWRITE_SYNC, WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE, WAIT_EVENT_LOGICAL_REWRITE_WRITE, WAIT_EVENT_RELATION_MAP_READ, WAIT_EVENT_RELATION_MAP_SYNC, WAIT_EVENT_RELATION_MAP_WRITE, WAIT_EVENT_REORDER_BUFFER_READ, WAIT_EVENT_REORDER_BUFFER_WRITE, WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ, WAIT_EVENT_REPLICATION_SLOT_READ, WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC, WAIT_EVENT_REPLICATION_SLOT_SYNC, WAIT_EVENT_REPLICATION_SLOT_WRITE, WAIT_EVENT_SLRU_FLUSH_SYNC, WAIT_EVENT_SLRU_READ, WAIT_EVENT_SLRU_SYNC, WAIT_EVENT_SLRU_WRITE, WAIT_EVENT_SNAPBUILD_READ, WAIT_EVENT_SNAPBUILD_SYNC, WAIT_EVENT_SNAPBUILD_WRITE, WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC, WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE, WAIT_EVENT_TIMELINE_HISTORY_READ, WAIT_EVENT_TIMELINE_HISTORY_SYNC, WAIT_EVENT_TIMELINE_HISTORY_WRITE, WAIT_EVENT_TWOPHASE_FILE_READ, WAIT_EVENT_TWOPHASE_FILE_SYNC, WAIT_EVENT_TWOPHASE_FILE_WRITE, WAIT_EVENT_WAL_BOOTSTRAP_SYNC, WAIT_EVENT_WAL_BOOTSTRAP_WRITE, WAIT_EVENT_WAL_COPY_READ, WAIT_EVENT_WAL_COPY_SYNC, WAIT_EVENT_WAL_COPY_WRITE, WAIT_EVENT_WAL_INIT_SYNC, WAIT_EVENT_WAL_INIT_WRITE, WAIT_EVENT_WAL_READ, WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN, WAIT_EVENT_WAL_WRITE, and WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ.

Referenced by pgstat_get_wait_event().

3466 {
3467  const char *event_name = "unknown wait event";
3468 
3469  switch (w)
3470  {
3472  event_name = "BufFileRead";
3473  break;
3475  event_name = "BufFileWrite";
3476  break;
3478  event_name = "ControlFileRead";
3479  break;
3481  event_name = "ControlFileSync";
3482  break;
3484  event_name = "ControlFileSyncUpdate";
3485  break;
3487  event_name = "ControlFileWrite";
3488  break;
3490  event_name = "ControlFileWriteUpdate";
3491  break;
3493  event_name = "CopyFileRead";
3494  break;
3496  event_name = "CopyFileWrite";
3497  break;
3499  event_name = "DataFileExtend";
3500  break;
3502  event_name = "DataFileFlush";
3503  break;
3505  event_name = "DataFileImmediateSync";
3506  break;
3508  event_name = "DataFilePrefetch";
3509  break;
3511  event_name = "DataFileRead";
3512  break;
3514  event_name = "DataFileSync";
3515  break;
3517  event_name = "DataFileTruncate";
3518  break;
3520  event_name = "DataFileWrite";
3521  break;
3523  event_name = "DSMFillZeroWrite";
3524  break;
3526  event_name = "LockFileAddToDataDirRead";
3527  break;
3529  event_name = "LockFileAddToDataDirSync";
3530  break;
3532  event_name = "LockFileAddToDataDirWrite";
3533  break;
3535  event_name = "LockFileCreateRead";
3536  break;
3538  event_name = "LockFileCreateSync";
3539  break;
3541  event_name = "LockFileCreateWRITE";
3542  break;
3544  event_name = "LockFileReCheckDataDirRead";
3545  break;
3547  event_name = "LogicalRewriteCheckpointSync";
3548  break;
3550  event_name = "LogicalRewriteMappingSync";
3551  break;
3553  event_name = "LogicalRewriteMappingWrite";
3554  break;
3556  event_name = "LogicalRewriteSync";
3557  break;
3559  event_name = "LogicalRewriteTruncate";
3560  break;
3562  event_name = "LogicalRewriteWrite";
3563  break;
3565  event_name = "RelationMapRead";
3566  break;
3568  event_name = "RelationMapSync";
3569  break;
3571  event_name = "RelationMapWrite";
3572  break;
3574  event_name = "ReorderBufferRead";
3575  break;
3577  event_name = "ReorderBufferWrite";
3578  break;
3580  event_name = "ReorderLogicalMappingRead";
3581  break;
3583  event_name = "ReplicationSlotRead";
3584  break;
3586  event_name = "ReplicationSlotRestoreSync";
3587  break;
3589  event_name = "ReplicationSlotSync";
3590  break;
3592  event_name = "ReplicationSlotWrite";
3593  break;
3595  event_name = "SLRUFlushSync";
3596  break;
3597  case WAIT_EVENT_SLRU_READ:
3598  event_name = "SLRURead";
3599  break;
3600  case WAIT_EVENT_SLRU_SYNC:
3601  event_name = "SLRUSync";
3602  break;
3603  case WAIT_EVENT_SLRU_WRITE:
3604  event_name = "SLRUWrite";
3605  break;
3607  event_name = "SnapbuildRead";
3608  break;
3610  event_name = "SnapbuildSync";
3611  break;
3613  event_name = "SnapbuildWrite";
3614  break;
3616  event_name = "TimelineHistoryFileSync";
3617  break;
3619  event_name = "TimelineHistoryFileWrite";
3620  break;
3622  event_name = "TimelineHistoryRead";
3623  break;
3625  event_name = "TimelineHistorySync";
3626  break;
3628  event_name = "TimelineHistoryWrite";
3629  break;
3631  event_name = "TwophaseFileRead";
3632  break;
3634  event_name = "TwophaseFileSync";
3635  break;
3637  event_name = "TwophaseFileWrite";
3638  break;
3640  event_name = "WALSenderTimelineHistoryRead";
3641  break;
3643  event_name = "WALBootstrapSync";
3644  break;
3646  event_name = "WALBootstrapWrite";
3647  break;
3649  event_name = "WALCopyRead";
3650  break;
3652  event_name = "WALCopySync";
3653  break;
3655  event_name = "WALCopyWrite";
3656  break;
3658  event_name = "WALInitSync";
3659  break;
3661  event_name = "WALInitWrite";
3662  break;
3663  case WAIT_EVENT_WAL_READ:
3664  event_name = "WALRead";
3665  break;
3667  event_name = "WALSyncMethodAssign";
3668  break;
3669  case WAIT_EVENT_WAL_WRITE:
3670  event_name = "WALWrite";
3671  break;
3672 
3673  /* no default case, so that compiler will warn */
3674  }
3675 
3676  return event_name;
3677 }
static const char * pgstat_get_wait_ipc ( WaitEventIPC  w)
static

Definition at line 3376 of file pgstat.c.

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

Referenced by pgstat_get_wait_event().

3377 {
3378  const char *event_name = "unknown wait event";
3379 
3380  switch (w)
3381  {
3383  event_name = "BgWorkerShutdown";
3384  break;
3386  event_name = "BgWorkerStartup";
3387  break;
3388  case WAIT_EVENT_BTREE_PAGE:
3389  event_name = "BtreePage";
3390  break;
3392  event_name = "ExecuteGather";
3393  break;
3395  event_name = "MessageQueueInternal";
3396  break;
3398  event_name = "MessageQueuePutMessage";
3399  break;
3400  case WAIT_EVENT_MQ_RECEIVE:
3401  event_name = "MessageQueueReceive";
3402  break;
3403  case WAIT_EVENT_MQ_SEND:
3404  event_name = "MessageQueueSend";
3405  break;
3407  event_name = "ParallelFinish";
3408  break;
3410  event_name = "ParallelBitmapScan";
3411  break;
3413  event_name = "SafeSnapshot";
3414  break;
3415  case WAIT_EVENT_SYNC_REP:
3416  event_name = "SyncRep";
3417  break;
3419  event_name = "LogicalSyncData";
3420  break;
3422  event_name = "LogicalSyncStateChange";
3423  break;
3424  /* no default case, so that compiler will warn */
3425  }
3426 
3427  return event_name;
3428 }
static const char * pgstat_get_wait_timeout ( WaitEventTimeout  w)
static

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

3438 {
3439  const char *event_name = "unknown wait event";
3440 
3441  switch (w)
3442  {
3444  event_name = "BaseBackupThrottle";
3445  break;
3446  case WAIT_EVENT_PG_SLEEP:
3447  event_name = "PgSleep";
3448  break;
3450  event_name = "RecoveryApplyDelay";
3451  break;
3452  /* no default case, so that compiler will warn */
3453  }
3454 
3455  return event_name;
3456 }
void pgstat_init ( void  )

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

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

References HASHCTL::entrysize, PgStat_BackendFunctionEntry::f_counts, PgStat_FunctionCallUsage::f_start, PgStat_FunctionCounts::f_total_time, FunctionCallInfoData::flinfo, FmgrInfo::fn_oid, PgStat_FunctionCallUsage::fs, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), INSTR_TIME_SET_CURRENT, HASHCTL::keysize, MemSet, NULL, PGSTAT_FUNCTION_HASH_SIZE, PgStat_FunctionCallUsage::save_f_total_time, PgStat_FunctionCallUsage::save_total, and total_func_time.

Referenced by call_pltcl_start_proc(), EventTriggerInvoke(), ExecCallTriggerFunc(), ExecMakeFunctionResultNoSets(), ExecMakeFunctionResultSet(), ExecMakeTableFunctionResult(), and fmgr_security_definer().

1508 {
1509  PgStat_BackendFunctionEntry *htabent;
1510  bool found;
1511 
1512  if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1513  {
1514  /* stats not wanted */
1515  fcu->fs = NULL;
1516  return;
1517  }
1518 
1519  if (!pgStatFunctions)
1520  {
1521  /* First time through - initialize function stat table */
1522  HASHCTL hash_ctl;
1523 
1524  memset(&hash_ctl, 0, sizeof(hash_ctl));
1525  hash_ctl.keysize = sizeof(Oid);
1526  hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1527  pgStatFunctions = hash_create("Function stat entries",
1529  &hash_ctl,
1530  HASH_ELEM | HASH_BLOBS);
1531  }
1532 
1533  /* Get the stats entry for this function, create if necessary */
1534  htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1535  HASH_ENTER, &found);
1536  if (!found)
1537  MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1538 
1539  fcu->fs = &htabent->f_counts;
1540 
1541  /* save stats for this function, later used to compensate for recursion */
1542  fcu->save_f_total_time = htabent->f_counts.f_total_time;
1543 
1544  /* save current backend-wide total time */
1545  fcu->save_total = total_func_time;
1546 
1547  /* get clock time as of function start */
1549 }
#define HASH_ELEM
Definition: hsearch.h:87
instr_time save_total
Definition: pgstat.h:1069
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:857
instr_time f_total_time
Definition: pgstat.h:462
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
unsigned int Oid
Definition: postgres_ext.h:31
PgStat_FunctionCounts * fs
Definition: pgstat.h:1065
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:229
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
instr_time save_f_total_time
Definition: pgstat.h:1067
struct PgStat_BackendFunctionEntry PgStat_BackendFunctionEntry
void pgstat_initialize ( void  )

Definition at line 2643 of file pgstat.c.

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

Referenced by InitPostgres().

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

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

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

Definition at line 1471 of file pgstat.c.

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

1472 {
1473  PgStat_MsgDummy msg;
1474 
1476  return;
1477 
1479  pgstat_send(&msg, sizeof(msg));
1480 }
static void pgstat_send(void *msg, int len)
Definition: pgstat.c:3859
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:3846
void pgstat_progress_end_command ( void  )

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

2953 {
2954  volatile PgBackendStatus *beentry = MyBEEntry;
2955 
2956  if (!beentry)
2957  return;
2960  return;
2961 
2966 }
Oid st_progress_command_target
Definition: pgstat.h:989
ProgressCommandType st_progress_command
Definition: pgstat.h:988
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2489
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1005
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1011
#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 2880 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().

2881 {
2882  volatile PgBackendStatus *beentry = MyBEEntry;
2883 
2884  if (!beentry || !pgstat_track_activities)
2885  return;
2886 
2888  beentry->st_progress_command = cmdtype;
2889  beentry->st_progress_command_target = relid;
2890  MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
2892 }
Oid st_progress_command_target
Definition: pgstat.h:989
#define MemSet(start, val, len)
Definition: c.h:857
ProgressCommandType st_progress_command
Definition: pgstat.h:988
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2489
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1005
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1011
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:990
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 2923 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().

2925 {
2926  volatile PgBackendStatus *beentry = MyBEEntry;
2927  int i;
2928 
2929  if (!beentry || !pgstat_track_activities || nparam == 0)
2930  return;
2931 
2933 
2934  for (i = 0; i < nparam; ++i)
2935  {
2936  Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
2937 
2938  beentry->st_progress_param[index[i]] = val[i];
2939  }
2940 
2942 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:898
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2489
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1005
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1011
#define Assert(condition)
Definition: c.h:675
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:990
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 2901 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().

2902 {
2903  volatile PgBackendStatus *beentry = MyBEEntry;
2904 
2906 
2907  if (!beentry || !pgstat_track_activities)
2908  return;
2909 
2911  beentry->st_progress_param[index] = val;
2913 }
Definition: type.h:90
#define PGSTAT_NUM_PROGRESS_PARAM
Definition: pgstat.h:898
static PgBackendStatus * MyBEEntry
Definition: pgstat.c:2489
#define pgstat_increment_changecount_before(beentry)
Definition: pgstat.h:1005
#define pgstat_increment_changecount_after(beentry)
Definition: pgstat.h:1011
#define Assert(condition)
Definition: c.h:675
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Definition: pgstat.h:990
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 3029 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().

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

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

4854 {
4855  PgStat_StatTabEntry *tabentry;
4856  PgStat_StatTabEntry tabbuf;
4857  PgStat_StatFuncEntry funcbuf;
4858  PgStat_StatFuncEntry *funcentry;
4859  FILE *fpin;
4860  int32 format_id;
4861  bool found;
4862  char statfile[MAXPGPATH];
4863 
4864  get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
4865 
4866  /*
4867  * Try to open the stats file. If it doesn't exist, the backends simply
4868  * return zero for anything and the collector simply starts from scratch
4869  * with empty counters.
4870  *
4871  * ENOENT is a possibility if the stats collector is not running or has
4872  * not yet written the stats file the first time. Any other failure
4873  * condition is suspicious.
4874  */
4875  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4876  {
4877  if (errno != ENOENT)
4880  errmsg("could not open statistics file \"%s\": %m",
4881  statfile)));
4882  return;
4883  }
4884 
4885  /*
4886  * Verify it's of the expected format.
4887  */
4888  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4889  format_id != PGSTAT_FILE_FORMAT_ID)
4890  {
4891  ereport(pgStatRunningInCollector ? LOG : WARNING,
4892  (errmsg("corrupted statistics file \"%s\"", statfile)));
4893  goto done;
4894  }
4895 
4896  /*
4897  * We found an existing collector stats file. Read it and put all the
4898  * hashtable entries into place.
4899  */
4900  for (;;)
4901  {
4902  switch (fgetc(fpin))
4903  {
4904  /*
4905  * 'T' A PgStat_StatTabEntry follows.
4906  */
4907  case 'T':
4908  if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
4909  fpin) != sizeof(PgStat_StatTabEntry))
4910  {
4911  ereport(pgStatRunningInCollector ? LOG : WARNING,
4912  (errmsg("corrupted statistics file \"%s\"",
4913  statfile)));
4914  goto done;
4915  }
4916 
4917  /*
4918  * Skip if table data not wanted.
4919  */
4920  if (tabhash == NULL)
4921  break;
4922 
4923  tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
4924  (void *) &tabbuf.tableid,
4925  HASH_ENTER, &found);
4926 
4927  if (found)
4928  {
4929  ereport(pgStatRunningInCollector ? LOG : WARNING,
4930  (errmsg("corrupted statistics file \"%s\"",
4931  statfile)));
4932  goto done;
4933  }
4934 
4935  memcpy(tabentry, &tabbuf, sizeof(tabbuf));
4936  break;
4937 
4938  /*
4939  * 'F' A PgStat_StatFuncEntry follows.
4940  */
4941  case 'F':
4942  if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
4943  fpin) != sizeof(PgStat_StatFuncEntry))
4944  {
4945  ereport(pgStatRunningInCollector ? LOG : WARNING,
4946  (errmsg("corrupted statistics file \"%s\"",
4947  statfile)));
4948  goto done;
4949  }
4950 
4951  /*
4952  * Skip if function data not wanted.
4953  */
4954  if (funchash == NULL)
4955  break;
4956 
4957  funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
4958  (void *) &funcbuf.functionid,
4959  HASH_ENTER, &found);
4960 
4961  if (found)
4962  {
4963  ereport(pgStatRunningInCollector ? LOG : WARNING,
4964  (errmsg("corrupted statistics file \"%s\"",
4965  statfile)));
4966  goto done;
4967  }
4968 
4969  memcpy(funcentry, &funcbuf, sizeof(funcbuf));
4970  break;
4971 
4972  /*
4973  * 'E' The EOF marker of a complete stats file.
4974  */
4975  case 'E':
4976  goto done;
4977 
4978  default:
4979  ereport(pgStatRunningInCollector ? LOG : WARNING,
4980  (errmsg("corrupted statistics file \"%s\"",
4981  statfile)));
4982  goto done;
4983  }
4984  }
4985 
4986 done:
4987  FreeFile(fpin);
4988 
4989  if (permanent)
4990  {
4991  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4992  unlink(statfile);
4993  }
4994 }
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:1040
signed int int32
Definition: c.h:256
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2057
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
int FreeFile(FILE *file)
Definition: fd.c:2240
#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:4492
static bool pgstat_read_db_statsfile_timestamp ( Oid  databaseid,
bool  permanent,
TimestampTz ts 
)
static

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

5016 {
5017  PgStat_StatDBEntry dbentry;
5018  PgStat_GlobalStats myGlobalStats;
5019  PgStat_ArchiverStats myArchiverStats;
5020  FILE *fpin;
5021  int32 format_id;
5022  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5023 
5024  /*
5025  * Try to open the stats file. As above, anything but ENOENT is worthy of
5026  * complaining about.
5027  */
5028  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5029  {
5030  if (errno != ENOENT)
5033  errmsg("could not open statistics file \"%s\": %m",
5034  statfile)));
5035  return false;
5036  }
5037 
5038  /*
5039  * Verify it's of the expected format.
5040  */
5041  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5042  format_id != PGSTAT_FILE_FORMAT_ID)
5043  {
5044  ereport(pgStatRunningInCollector ? LOG : WARNING,
5045  (errmsg("corrupted statistics file \"%s\"", statfile)));
5046  FreeFile(fpin);
5047  return false;
5048  }
5049 
5050  /*
5051  * Read global stats struct
5052  */
5053  if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5054  fpin) != sizeof(myGlobalStats))
5055  {
5056  ereport(pgStatRunningInCollector ? LOG : WARNING,
5057  (errmsg("corrupted statistics file \"%s\"", statfile)));
5058  FreeFile(fpin);
5059  return false;
5060  }
5061 
5062  /*
5063  * Read archiver stats struct
5064  */
5065  if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
5066  fpin) != sizeof(myArchiverStats))
5067  {
5068  ereport(pgStatRunningInCollector ? LOG : WARNING,
5069  (errmsg("corrupted statistics file \"%s\"", statfile)));
5070  FreeFile(fpin);
5071  return false;
5072  }
5073 
5074  /* By default, we're going to return the timestamp of the global file. */
5075  *ts = myGlobalStats.stats_timestamp;
5076 
5077  /*
5078  * We found an existing collector stats file. Read it and look for a
5079  * record for the requested database. If found, use its timestamp.
5080  */
5081  for (;;)
5082  {
5083  switch (fgetc(fpin))
5084  {
5085  /*
5086  * 'D' A PgStat_StatDBEntry struct describing a database
5087  * follows.
5088  */
5089  case 'D':
5090  if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
5091  fpin) != offsetof(PgStat_StatDBEntry, tables))
5092  {
5093  ereport(pgStatRunningInCollector ? LOG : WARNING,
5094  (errmsg("corrupted statistics file \"%s\"",
5095  statfile)));
5096  goto done;
5097  }
5098 
5099  /*
5100  * If this is the DB we're looking for, save its timestamp and
5101  * we're done.
5102  */
5103  if (dbentry.databaseid == databaseid)
5104  {
5105  *ts = dbentry.stats_timestamp;
5106  goto done;
5107  }
5108 
5109  break;
5110 
5111  case 'E':
5112  goto done;
5113 
5114  default:
5115  ereport(pgStatRunningInCollector ? LOG : WARNING,
5116  (errmsg("corrupted statistics file \"%s\"",
5117  statfile)));
5118  goto done;
5119  }
5120  }
5121 
5122 done:
5123  FreeFile(fpin);
5124  return true;
5125 }
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:1040
signed int int32
Definition: c.h:256
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:2057
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
int FreeFile(FILE *file)
Definition: fd.c:2240
#define PGSTAT_FILE_FORMAT_ID
Definition: pgstat.h:569
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define offsetof(type, field)
Definition: c.h:555
static HTAB * pgstat_read_statsfiles ( Oid  onlydb,
bool  permanent,
bool  deep 
)
static

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

4642 {
4643  PgStat_StatDBEntry *dbentry;
4644  PgStat_StatDBEntry dbbuf;
4645  HASHCTL hash_ctl;
4646  HTAB *dbhash;
4647  FILE *fpin;
4648  int32 format_id;
4649  bool found;
4650  const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4651 
4652  /*
4653  * The tables will live in pgStatLocalContext.
4654  */
4656 
4657  /*
4658  * Create the DB hashtable
4659  */
4660  memset(&hash_ctl, 0, sizeof(hash_ctl));
4661  hash_ctl.keysize = sizeof(Oid);
4662  hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
4663  hash_ctl.hcxt = pgStatLocalContext;
4664  dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
4666 
4667  /*
4668  * Clear out global and archiver statistics so they start from zero in
4669  * case we can't load an existing statsfile.
4670  */
4671  memset(&globalStats, 0, sizeof(globalStats));
4672  memset(&archiverStats, 0, sizeof(archiverStats));
4673 
4674  /*
4675  * Set the current timestamp (will be kept only in case we can't load an
4676  * existing statsfile).
4677  */
4680 
4681  /*
4682  * Try to open the stats file. If it doesn't exist, the backends simply
4683  * return zero for anything and the collector simply starts from scratch
4684  * with empty counters.
4685  *
4686  * ENOENT is a possibility if the stats collector is not running or has
4687  * not yet written the stats file the first time. Any other failure
4688  * condition is suspicious.
4689  */
4690  if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4691  {
4692  if (errno != ENOENT)
4695  errmsg("could not open statistics file \"%s\": %m",
4696  statfile)));
4697  return dbhash;
4698  }
4699 
4700  /*
4701  * Verify it's of the expected format.
4702  */
4703  if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4704  format_id != PGSTAT_FILE_FORMAT_ID)
4705  {
4706  ereport(pgStatRunningInCollector ? LOG : WARNING,
4707  (errmsg("corrupted statistics file \"%s\"", statfile)));
4708  goto done;
4709  }
4710 
4711  /*
4712  * Read global stats struct
4713  */
4714  if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
4715  {
4716  ereport(pgStatRunningInCollector ? LOG : WARNING,
4717  (errmsg("corrupted statistics file \"%s\"", statfile)));
4718  goto done;
4719  }
4720 
4721  /*
4722  * Read archiver stats struct
4723  */
4724  if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
4725  {
4726  ereport(pgStatRunningInCollector ? LOG : WARNING,
4727  (errmsg("corrupted statistics file \"%s\"", statfile)));
4728  goto done;
4729  }
4730 
4731  /*
4732  * We found an existing collector stats file. Read it and put all the
4733  * hashtable entries into place.
4734  */
4735  for (;;)
4736  {
4737  switch (fgetc(fpin))
4738  {
4739  /*
4740  * 'D' A PgStat_StatDBEntry struct describing a database
4741  * follows.
4742  */
4743  case 'D':
4744  if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
4745  fpin) != offsetof(PgStat_StatDBEntry, tables))
4746  {
4747  ereport(pgStatRunningInCollector ? LOG : WARNING,
4748  (errmsg("corrupted statistics file \"%s\"",
4749  statfile)));
4750  goto done;
4751  }
4752 
4753  /*
4754  * Add to the DB hash
4755  */
4756  dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
4757  (void *) &dbbuf.databaseid,
4758  HASH_ENTER,
4759  &found);
4760  if (found)
4761  {
4762  ereport(pgStatRunningInCollector ? LOG : WARNING,
4763  (errmsg("corrupted statistics file \"%s\"",
4764  statfile)));
4765  goto done;
4766  }
4767 
4768  memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
4769  dbentry->tables = NULL;
4770  dbentry->functions = NULL;
4771 
4772  /*
4773  * Don't create tables/functions hashtables for uninteresting
4774  * databases.
4775  */
4776  if (onlydb != InvalidOid)
4777  {
4778  if (dbbuf.databaseid != onlydb &&
4779  dbbuf.databaseid != InvalidOid)
4780  break;
4781  }
4782 
4783  memset(&hash_ctl, 0, sizeof(hash_ctl));
4784  hash_ctl.keysize = sizeof(Oid);
4785  hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4786  hash_ctl.hcxt = pgStatLocalContext;
4787  dbentry->tables = hash_create("Per-database table",
4789  &hash_ctl,
4791 
4792  hash_ctl.keysize = sizeof(Oid);
4793  hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4794  hash_ctl.hcxt = pgStatLocalContext;
4795  dbentry->functions = hash_create("Per-database function",
4797  &hash_ctl,
4799 
4800  /*
4801  * If requested, read the data from the database-specific
4802  * file. Otherwise we just leave the hashtables empty.
4803  */
4804  if (deep)
4806  dbentry->tables,
4807  dbentry->functions,
4808  permanent);
4809 
4810  break;
4811 
4812  case 'E':
4813  goto done;
4814 
4815  default:
4816  ereport(pgStatRunningInCollector ? LOG : WARNING,
4817  (errmsg("corrupted statistics file \"%s\"",
4818  statfile)));
4819  goto done;
4820  }
4821  }
4822 
4823 done:
4824  FreeFile(fpin);
4825 
4826  /* If requested to read the permanent file, also get rid of it. */
4827  if (permanent)
4828  {
4829  elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4830  unlink(statfile);
4831  }
4832 
4833  return dbhash;
4834 }
#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:1569
#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:1040
struct PgStat_StatFuncEntry PgStat_StatFuncEntry
signed int int32
Definition: c.h:256
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:2057
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
static void pgstat_setup_memcxt(void)
Definition: pgstat.c:5267
static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent)
Definition: pgstat.c:4852
#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:229
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:2240
#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:555
static void pgstat_recv_analyze ( PgStat_MsgAnalyze msg,
int  len 
)
static

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

5732 {
5733  PgStat_StatDBEntry *dbentry;
5734  PgStat_StatTabEntry *tabentry;
5735 
5736  /*
5737  * Store the data in the table's hashtable entry.
5738  */
5739  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5740 
5741  tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
5742 
5743  tabentry->n_live_tuples = msg->m_live_tuples;
5744  tabentry->n_dead_tuples = msg->m_dead_tuples;
5745 
5746  /*
5747  * If commanded, reset changes_since_analyze to zero. This forgets any
5748  * changes that were committed while the ANALYZE was in progress, but we
5749  * have no good way to estimate how many of those there were.
5750  */
5751  if (msg->m_resetcounter)
5752  tabentry->changes_since_analyze = 0;
5753 
5754  if (msg->m_autovacuum)
5755  {
5756  tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
5757  tabentry->autovac_analyze_count++;
5758  }
5759  else
5760  {
5761  tabentry->analyze_timestamp = msg->m_analyzetime;
5762  tabentry->analyze_count++;
5763  }
5764 }
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:4309
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:4278
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 5774 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().

5775 {
5776  if (msg->m_failed)
5777  {
5778  /* Failed archival attempt */
5780  memcpy(archiverStats.last_failed_wal, msg->m_xlog,
5781  sizeof(archiverStats.last_failed_wal));
5783  }
5784  else
5785  {
5786  /* Successful archival operation */
5788  memcpy(archiverStats.last_archived_wal, msg->m_xlog,
5791  }
5792 }
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 5678 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().

5679 {
5680  PgStat_StatDBEntry *dbentry;
5681 
5682  /*
5683  * Store the last autovacuum time in the database's hashtable entry.
5684  */
5685  dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5686 
5687  dbentry->last_autovac_time = msg->m_start_time;
5688 }
TimestampTz last_autovac_time
Definition: pgstat.h:587
static PgStat_StatDBEntry * pgstat_get_db_entry(Oid databaseid, bool create)
Definition: pgstat.c:4278
TimestampTz m_start_time
Definition: pgstat.h:354
static void pgstat_recv_bgwriter ( PgStat_MsgBgWriter msg,
int  len 
)
static

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

5802 {
5813 }
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