Header And Logo

PostgreSQL
| The world's most advanced open source database.

Data Structures | Defines | Typedefs | Enumerations | Functions | Variables

pgstat.h File Reference

#include "datatype/timestamp.h"
#include "fmgr.h"
#include "libpq/pqcomm.h"
#include "portability/instr_time.h"
#include "utils/hsearch.h"
#include "utils/relcache.h"
Include dependency graph for pgstat.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PgStat_TableCounts
struct  PgStat_TableStatus
struct  PgStat_TableXactStatus
struct  PgStat_MsgHdr
struct  PgStat_MsgDummy
struct  PgStat_MsgInquiry
struct  PgStat_TableEntry
struct  PgStat_MsgTabstat
struct  PgStat_MsgTabpurge
struct  PgStat_MsgDropdb
struct  PgStat_MsgResetcounter
struct  PgStat_MsgResetsharedcounter
struct  PgStat_MsgResetsinglecounter
struct  PgStat_MsgAutovacStart
struct  PgStat_MsgVacuum
struct  PgStat_MsgAnalyze
struct  PgStat_MsgBgWriter
struct  PgStat_MsgRecoveryConflict
struct  PgStat_MsgTempFile
struct  PgStat_FunctionCounts
struct  PgStat_BackendFunctionEntry
struct  PgStat_FunctionEntry
struct  PgStat_MsgFuncstat
struct  PgStat_MsgFuncpurge
struct  PgStat_MsgDeadlock
union  PgStat_Msg
struct  PgStat_StatDBEntry
struct  PgStat_StatTabEntry
struct  PgStat_StatFuncEntry
struct  PgStat_GlobalStats
struct  PgBackendStatus
struct  PgStat_FunctionCallUsage

Defines

#define PGSTAT_MSG_PAYLOAD   (1000 - sizeof(PgStat_MsgHdr))
#define PGSTAT_NUM_TABENTRIES
#define PGSTAT_NUM_TABPURGE
#define PGSTAT_NUM_FUNCENTRIES
#define PGSTAT_NUM_FUNCPURGE
#define PGSTAT_FILE_FORMAT_ID   0x01A5BC9B
#define pgstat_count_heap_scan(rel)
#define pgstat_count_heap_getnext(rel)
#define pgstat_count_heap_fetch(rel)
#define pgstat_count_index_scan(rel)
#define pgstat_count_index_tuples(rel, n)
#define pgstat_count_buffer_read(rel)
#define pgstat_count_buffer_hit(rel)
#define pgstat_count_buffer_read_time(n)   (pgStatBlockReadTime += (n))
#define pgstat_count_buffer_write_time(n)   (pgStatBlockWriteTime += (n))

Typedefs

typedef enum TrackFunctionsLevel TrackFunctionsLevel
typedef enum StatMsgType StatMsgType
typedef int64 PgStat_Counter
typedef struct PgStat_TableCounts PgStat_TableCounts
typedef enum
PgStat_Shared_Reset_Target 
PgStat_Shared_Reset_Target
typedef enum
PgStat_Single_Reset_Type 
PgStat_Single_Reset_Type
typedef struct PgStat_TableStatus PgStat_TableStatus
typedef struct
PgStat_TableXactStatus 
PgStat_TableXactStatus
typedef struct PgStat_MsgHdr PgStat_MsgHdr
typedef struct PgStat_MsgDummy PgStat_MsgDummy
typedef struct PgStat_MsgInquiry PgStat_MsgInquiry
typedef struct PgStat_TableEntry PgStat_TableEntry
typedef struct PgStat_MsgTabstat PgStat_MsgTabstat
typedef struct PgStat_MsgTabpurge PgStat_MsgTabpurge
typedef struct PgStat_MsgDropdb PgStat_MsgDropdb
typedef struct
PgStat_MsgResetcounter 
PgStat_MsgResetcounter
typedef struct
PgStat_MsgResetsharedcounter 
PgStat_MsgResetsharedcounter
typedef struct
PgStat_MsgResetsinglecounter 
PgStat_MsgResetsinglecounter
typedef struct
PgStat_MsgAutovacStart 
PgStat_MsgAutovacStart
typedef struct PgStat_MsgVacuum PgStat_MsgVacuum
typedef struct PgStat_MsgAnalyze PgStat_MsgAnalyze
typedef struct PgStat_MsgBgWriter PgStat_MsgBgWriter
typedef struct
PgStat_MsgRecoveryConflict 
PgStat_MsgRecoveryConflict
typedef struct PgStat_MsgTempFile PgStat_MsgTempFile
typedef struct
PgStat_FunctionCounts 
PgStat_FunctionCounts
typedef struct
PgStat_BackendFunctionEntry 
PgStat_BackendFunctionEntry
typedef struct PgStat_FunctionEntry PgStat_FunctionEntry
typedef struct PgStat_MsgFuncstat PgStat_MsgFuncstat
typedef struct PgStat_MsgFuncpurge PgStat_MsgFuncpurge
typedef struct PgStat_MsgDeadlock PgStat_MsgDeadlock
typedef union PgStat_Msg PgStat_Msg
typedef struct PgStat_StatDBEntry PgStat_StatDBEntry
typedef struct PgStat_StatTabEntry PgStat_StatTabEntry
typedef struct PgStat_StatFuncEntry PgStat_StatFuncEntry
typedef struct PgStat_GlobalStats PgStat_GlobalStats
typedef enum BackendState BackendState
typedef struct PgBackendStatus PgBackendStatus
typedef struct
PgStat_FunctionCallUsage 
PgStat_FunctionCallUsage

Enumerations

enum  TrackFunctionsLevel { TRACK_FUNC_OFF, TRACK_FUNC_PL, TRACK_FUNC_ALL }
enum  StatMsgType {
  PGSTAT_MTYPE_DUMMY, PGSTAT_MTYPE_INQUIRY, PGSTAT_MTYPE_TABSTAT, PGSTAT_MTYPE_TABPURGE,
  PGSTAT_MTYPE_DROPDB, PGSTAT_MTYPE_RESETCOUNTER, PGSTAT_MTYPE_RESETSHAREDCOUNTER, PGSTAT_MTYPE_RESETSINGLECOUNTER,
  PGSTAT_MTYPE_AUTOVAC_START, PGSTAT_MTYPE_VACUUM, PGSTAT_MTYPE_ANALYZE, PGSTAT_MTYPE_BGWRITER,
  PGSTAT_MTYPE_FUNCSTAT, PGSTAT_MTYPE_FUNCPURGE, PGSTAT_MTYPE_RECOVERYCONFLICT, PGSTAT_MTYPE_TEMPFILE,
  PGSTAT_MTYPE_DEADLOCK
}
enum  PgStat_Shared_Reset_Target { RESET_BGWRITER }
enum  PgStat_Single_Reset_Type { RESET_TABLE, RESET_FUNCTION }
enum  BackendState {
  STATE_UNDEFINED, STATE_IDLE, STATE_RUNNING, STATE_IDLEINTRANSACTION,
  STATE_FASTPATH, STATE_IDLEINTRANSACTION_ABORTED, STATE_DISABLED
}

Functions

Size BackendStatusShmemSize (void)
void CreateSharedBackendStatus (void)
void pgstat_init (void)
int pgstat_start (void)
void pgstat_reset_all (void)
void allow_immediate_pgstat_restart (void)
void pgstat_ping (void)
void pgstat_report_stat (bool force)
void pgstat_vacuum_stat (void)
void pgstat_drop_database (Oid databaseid)
void pgstat_clear_snapshot (void)
void pgstat_reset_counters (void)
void pgstat_reset_shared_counters (const char *)
void pgstat_reset_single_counter (Oid objectid, PgStat_Single_Reset_Type type)
void pgstat_report_autovac (Oid dboid)
void pgstat_report_vacuum (Oid tableoid, bool shared, PgStat_Counter tuples)
void pgstat_report_analyze (Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples)
void pgstat_report_recovery_conflict (int reason)
void pgstat_report_deadlock (void)
void pgstat_initialize (void)
void pgstat_bestart (void)
void pgstat_report_activity (BackendState state, const char *cmd_str)
void pgstat_report_tempfile (size_t filesize)
void pgstat_report_appname (const char *appname)
void pgstat_report_xact_timestamp (TimestampTz tstamp)
void pgstat_report_waiting (bool waiting)
const char * pgstat_get_backend_current_activity (int pid, bool checkUser)
const char * pgstat_get_crashed_backend_activity (int pid, char *buffer, int buflen)
PgStat_TableStatusfind_tabstat_entry (Oid rel_id)
PgStat_BackendFunctionEntryfind_funcstat_entry (Oid func_id)
void pgstat_initstats (Relation rel)
void pgstat_count_heap_insert (Relation rel, int n)
void pgstat_count_heap_update (Relation rel, bool hot)
void pgstat_count_heap_delete (Relation rel)
void pgstat_update_heap_dead_tuples (Relation rel, int delta)
void pgstat_init_function_usage (FunctionCallInfoData *fcinfo, PgStat_FunctionCallUsage *fcu)
void pgstat_end_function_usage (PgStat_FunctionCallUsage *fcu, bool finalize)
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)
void pgstat_send_bgwriter (void)
PgStat_StatDBEntrypgstat_fetch_stat_dbentry (Oid dbid)
PgStat_StatTabEntrypgstat_fetch_stat_tabentry (Oid relid)
PgBackendStatuspgstat_fetch_stat_beentry (int beid)
PgStat_StatFuncEntrypgstat_fetch_stat_funcentry (Oid funcid)
int pgstat_fetch_stat_numbackends (void)
PgStat_GlobalStatspgstat_fetch_global (void)

Variables

bool pgstat_track_activities
bool pgstat_track_counts
int pgstat_track_functions
PGDLLIMPORT int pgstat_track_activity_query_size
char * pgstat_stat_directory
char * pgstat_stat_tmpname
char * pgstat_stat_filename
PgStat_MsgBgWriter BgWriterStats
PgStat_Counter pgStatBlockReadTime
PgStat_Counter pgStatBlockWriteTime

Define Documentation

#define pgstat_count_buffer_hit (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_blocks_hit++;            \
    } while (0)

Definition at line 832 of file pgstat.h.

Referenced by ReadBufferExtended().

#define pgstat_count_buffer_read (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_blocks_fetched++;        \
    } while (0)

Definition at line 827 of file pgstat.h.

Referenced by ReadBufferExtended().

#define pgstat_count_buffer_read_time (   n  )     (pgStatBlockReadTime += (n))

Definition at line 837 of file pgstat.h.

Referenced by ReadBuffer_common().

#define pgstat_count_buffer_write_time (   n  )     (pgStatBlockWriteTime += (n))

Definition at line 839 of file pgstat.h.

Referenced by FlushBuffer().

#define pgstat_count_heap_fetch (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_tuples_fetched++;        \
    } while (0)

Definition at line 812 of file pgstat.h.

Referenced by BitmapHeapNext(), heap_fetch(), and index_fetch_heap().

#define pgstat_count_heap_getnext (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_tuples_returned++;       \
    } while (0)

Definition at line 807 of file pgstat.h.

Referenced by heap_getnext().

#define pgstat_count_heap_scan (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_numscans++;              \
    } while (0)

Definition at line 802 of file pgstat.h.

Referenced by initscan().

#define pgstat_count_index_scan (   rel  ) 
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_numscans++;              \
    } while (0)

Definition at line 817 of file pgstat.h.

Referenced by _bt_first(), _hash_first(), ginNewScanKey(), gistgetbitmap(), and gistgettuple().

#define pgstat_count_index_tuples (   rel,
  n 
)
Value:
do {                                                            \
        if ((rel)->pgstat_info != NULL)                             \
            (rel)->pgstat_info->t_counts.t_tuples_returned += (n);  \
    } while (0)

Definition at line 822 of file pgstat.h.

Referenced by index_getbitmap(), and index_getnext_tid().

#define PGSTAT_FILE_FORMAT_ID   0x01A5BC9B
#define PGSTAT_MSG_PAYLOAD   (1000 - sizeof(PgStat_MsgHdr))

Definition at line 184 of file pgstat.h.

#define PGSTAT_NUM_FUNCENTRIES
Value:
((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int))  \
     / sizeof(PgStat_FunctionEntry))

Definition at line 443 of file pgstat.h.

Referenced by pgstat_send_funcstats().

#define PGSTAT_NUM_FUNCPURGE
Value:
((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int))  \
     / sizeof(Oid))

Definition at line 460 of file pgstat.h.

Referenced by pgstat_vacuum_stat().

#define PGSTAT_NUM_TABENTRIES
Value:
((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - 3 * sizeof(int))  \
     / sizeof(PgStat_TableEntry))

Definition at line 227 of file pgstat.h.

Referenced by pgstat_report_stat().

#define PGSTAT_NUM_TABPURGE
Value:
((PGSTAT_MSG_PAYLOAD - sizeof(Oid) - sizeof(int))  \
     / sizeof(Oid))

Definition at line 249 of file pgstat.h.

Referenced by pgstat_vacuum_stat().


Typedef Documentation

typedef enum BackendState BackendState
typedef int64 PgStat_Counter

Definition at line 59 of file pgstat.h.

typedef union PgStat_Msg PgStat_Msg
typedef struct PgStat_MsgHdr PgStat_MsgHdr
typedef enum StatMsgType StatMsgType

Enumeration Type Documentation

Enumerator:
STATE_UNDEFINED 
STATE_IDLE 
STATE_RUNNING 
STATE_IDLEINTRANSACTION 
STATE_FASTPATH 
STATE_IDLEINTRANSACTION_ABORTED 
STATE_DISABLED 

Definition at line 635 of file pgstat.h.

{
    STATE_UNDEFINED,
    STATE_IDLE,
    STATE_RUNNING,
    STATE_IDLEINTRANSACTION,
    STATE_FASTPATH,
    STATE_IDLEINTRANSACTION_ABORTED,
    STATE_DISABLED,
} BackendState;

Enumerator:
RESET_BGWRITER 

Definition at line 103 of file pgstat.h.

{
    RESET_BGWRITER
} PgStat_Shared_Reset_Target;

Enumerator:
RESET_TABLE 
RESET_FUNCTION 

Definition at line 109 of file pgstat.h.

{
    RESET_TABLE,
    RESET_FUNCTION
} PgStat_Single_Reset_Type;

Enumerator:
PGSTAT_MTYPE_DUMMY 
PGSTAT_MTYPE_INQUIRY 
PGSTAT_MTYPE_TABSTAT 
PGSTAT_MTYPE_TABPURGE 
PGSTAT_MTYPE_DROPDB 
PGSTAT_MTYPE_RESETCOUNTER 
PGSTAT_MTYPE_RESETSHAREDCOUNTER 
PGSTAT_MTYPE_RESETSINGLECOUNTER 
PGSTAT_MTYPE_AUTOVAC_START 
PGSTAT_MTYPE_VACUUM 
PGSTAT_MTYPE_ANALYZE 
PGSTAT_MTYPE_BGWRITER 
PGSTAT_MTYPE_FUNCSTAT 
PGSTAT_MTYPE_FUNCPURGE 
PGSTAT_MTYPE_RECOVERYCONFLICT 
PGSTAT_MTYPE_TEMPFILE 
PGSTAT_MTYPE_DEADLOCK 

Definition at line 34 of file pgstat.h.

{
    PGSTAT_MTYPE_DUMMY,
    PGSTAT_MTYPE_INQUIRY,
    PGSTAT_MTYPE_TABSTAT,
    PGSTAT_MTYPE_TABPURGE,
    PGSTAT_MTYPE_DROPDB,
    PGSTAT_MTYPE_RESETCOUNTER,
    PGSTAT_MTYPE_RESETSHAREDCOUNTER,
    PGSTAT_MTYPE_RESETSINGLECOUNTER,
    PGSTAT_MTYPE_AUTOVAC_START,
    PGSTAT_MTYPE_VACUUM,
    PGSTAT_MTYPE_ANALYZE,
    PGSTAT_MTYPE_BGWRITER,
    PGSTAT_MTYPE_FUNCSTAT,
    PGSTAT_MTYPE_FUNCPURGE,
    PGSTAT_MTYPE_RECOVERYCONFLICT,
    PGSTAT_MTYPE_TEMPFILE,
    PGSTAT_MTYPE_DEADLOCK
} StatMsgType;

Enumerator:
TRACK_FUNC_OFF 
TRACK_FUNC_PL 
TRACK_FUNC_ALL 

Definition at line 23 of file pgstat.h.

{
    TRACK_FUNC_OFF,
    TRACK_FUNC_PL,
    TRACK_FUNC_ALL
}   TrackFunctionsLevel;


Function Documentation

void allow_immediate_pgstat_restart ( void   ) 

Definition at line 692 of file pgstat.c.

References last_pgstat_start_time.

Referenced by HandleChildCrash().

void AtEOSubXact_PgStat ( bool  isCommit,
int  nestDepth 
)

Definition at line 1927 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_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::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, PgStat_TableXactStatus::tuples_updated, and PgStat_TableXactStatus::upper.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

{
    PgStat_SubXactStatus *xact_state;

    /*
     * Transfer transactional insert/update counts into the next higher
     * subtransaction state.
     */
    xact_state = pgStatXactStack;
    if (xact_state != NULL &&
        xact_state->nest_level >= nestDepth)
    {
        PgStat_TableXactStatus *trans;
        PgStat_TableXactStatus *next_trans;

        /* delink xact_state from stack immediately to simplify reuse case */
        pgStatXactStack = xact_state->prev;

        for (trans = xact_state->first; trans != NULL; trans = next_trans)
        {
            PgStat_TableStatus *tabstat;

            next_trans = trans->next;
            Assert(trans->nest_level == nestDepth);
            tabstat = trans->parent;
            Assert(tabstat->trans == trans);
            if (isCommit)
            {
                if (trans->upper && trans->upper->nest_level == nestDepth - 1)
                {
                    trans->upper->tuples_inserted += trans->tuples_inserted;
                    trans->upper->tuples_updated += trans->tuples_updated;
                    trans->upper->tuples_deleted += trans->tuples_deleted;
                    tabstat->trans = trans->upper;
                    pfree(trans);
                }
                else
                {
                    /*
                     * When there isn't an immediate parent state, we can just
                     * reuse the record instead of going through a
                     * palloc/pfree pushup (this works since it's all in
                     * TopTransactionContext anyway).  We have to re-link it
                     * into the parent level, though, and that might mean
                     * pushing a new entry into the pgStatXactStack.
                     */
                    PgStat_SubXactStatus *upper_xact_state;

                    upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
                    trans->next = upper_xact_state->first;
                    upper_xact_state->first = trans;
                    trans->nest_level = nestDepth - 1;
                }
            }
            else
            {
                /*
                 * On abort, update top-level tabstat counts, then forget the
                 * subtransaction
                 */

                /* count attempted actions regardless of commit/abort */
                tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
                tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
                tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
                /* inserted tuples are dead, deleted tuples are unaffected */
                tabstat->t_counts.t_delta_dead_tuples +=
                    trans->tuples_inserted + trans->tuples_updated;
                tabstat->trans = trans->upper;
                pfree(trans);
            }
        }
        pfree(xact_state);
    }
}

void AtEOXact_PgStat ( bool  isCommit  ) 

Definition at line 1854 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(), pgStatXactCommit, pgStatXactRollback, 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_tuples_deleted, PgStat_TableCounts::t_tuples_inserted, PgStat_TableCounts::t_tuples_updated, PgStat_TableStatus::trans, trans, PgStat_TableXactStatus::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, PgStat_TableXactStatus::tuples_updated, and PgStat_TableXactStatus::upper.

Referenced by AbortTransaction(), CommitTransaction(), and FinishPreparedTransaction().

{
    PgStat_SubXactStatus *xact_state;

    /*
     * Count transaction commit or abort.  (We use counters, not just bools,
     * in case the reporting message isn't sent right away.)
     */
    if (isCommit)
        pgStatXactCommit++;
    else
        pgStatXactRollback++;

    /*
     * Transfer transactional insert/update counts into the base tabstat
     * entries.  We don't bother to free any of the transactional state, since
     * it's all in TopTransactionContext and will go away anyway.
     */
    xact_state = pgStatXactStack;
    if (xact_state != NULL)
    {
        PgStat_TableXactStatus *trans;

        Assert(xact_state->nest_level == 1);
        Assert(xact_state->prev == NULL);
        for (trans = xact_state->first; trans != NULL; trans = trans->next)
        {
            PgStat_TableStatus *tabstat;

            Assert(trans->nest_level == 1);
            Assert(trans->upper == NULL);
            tabstat = trans->parent;
            Assert(tabstat->trans == trans);
            /* count attempted actions regardless of commit/abort */
            tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
            tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
            tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
            if (isCommit)
            {
                /* insert adds a live tuple, delete removes one */
                tabstat->t_counts.t_delta_live_tuples +=
                    trans->tuples_inserted - trans->tuples_deleted;
                /* update and delete each create a dead tuple */
                tabstat->t_counts.t_delta_dead_tuples +=
                    trans->tuples_updated + trans->tuples_deleted;
                /* insert, update, delete each count as one change event */
                tabstat->t_counts.t_changed_tuples +=
                    trans->tuples_inserted + trans->tuples_updated +
                    trans->tuples_deleted;
            }
            else
            {
                /* inserted tuples are dead, deleted tuples are unaffected */
                tabstat->t_counts.t_delta_dead_tuples +=
                    trans->tuples_inserted + trans->tuples_updated;
                /* an aborted xact generates no changed_tuple events */
            }
            tabstat->trans = NULL;
        }
    }
    pgStatXactStack = NULL;

    /* Make sure any stats snapshot is thrown away */
    pgstat_clear_snapshot();
}

void AtPrepare_PgStat ( void   ) 

Definition at line 2012 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_SubXactStatus::prev, RegisterTwoPhaseRecord(), PgStat_TableStatus::t_id, TwoPhasePgStatRecord::t_id, PgStat_TableStatus::t_shared, TwoPhasePgStatRecord::t_shared, PgStat_TableStatus::trans, trans, 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, and PgStat_TableXactStatus::upper.

Referenced by PrepareTransaction().

{
    PgStat_SubXactStatus *xact_state;

    xact_state = pgStatXactStack;
    if (xact_state != NULL)
    {
        PgStat_TableXactStatus *trans;

        Assert(xact_state->nest_level == 1);
        Assert(xact_state->prev == NULL);
        for (trans = xact_state->first; trans != NULL; trans = trans->next)
        {
            PgStat_TableStatus *tabstat;
            TwoPhasePgStatRecord record;

            Assert(trans->nest_level == 1);
            Assert(trans->upper == NULL);
            tabstat = trans->parent;
            Assert(tabstat->trans == trans);

            record.tuples_inserted = trans->tuples_inserted;
            record.tuples_updated = trans->tuples_updated;
            record.tuples_deleted = trans->tuples_deleted;
            record.t_id = tabstat->t_id;
            record.t_shared = tabstat->t_shared;

            RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
                                   &record, sizeof(TwoPhasePgStatRecord));
        }
    }
}

Size BackendStatusShmemSize ( void   ) 
void CreateSharedBackendStatus ( void   ) 

Definition at line 2341 of file pgstat.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

{
    Size        size;
    bool        found;
    int         i;
    char       *buffer;

    /* Create or attach to the shared array */
    size = mul_size(sizeof(PgBackendStatus), MaxBackends);
    BackendStatusArray = (PgBackendStatus *)
        ShmemInitStruct("Backend Status Array", size, &found);

    if (!found)
    {
        /*
         * We're the first - initialize.
         */
        MemSet(BackendStatusArray, 0, size);
    }

    /* Create or attach to the shared appname buffer */
    size = mul_size(NAMEDATALEN, MaxBackends);
    BackendAppnameBuffer = (char *)
        ShmemInitStruct("Backend Application Name Buffer", size, &found);

    if (!found)
    {
        MemSet(BackendAppnameBuffer, 0, size);

        /* Initialize st_appname pointers. */
        buffer = BackendAppnameBuffer;
        for (i = 0; i < MaxBackends; i++)
        {
            BackendStatusArray[i].st_appname = buffer;
            buffer += NAMEDATALEN;
        }
    }

    /* Create or attach to the shared client hostname buffer */
    size = mul_size(NAMEDATALEN, MaxBackends);
    BackendClientHostnameBuffer = (char *)
        ShmemInitStruct("Backend Client Host Name Buffer", size, &found);

    if (!found)
    {
        MemSet(BackendClientHostnameBuffer, 0, size);

        /* Initialize st_clienthostname pointers. */
        buffer = BackendClientHostnameBuffer;
        for (i = 0; i < MaxBackends; i++)
        {
            BackendStatusArray[i].st_clienthostname = buffer;
            buffer += NAMEDATALEN;
        }
    }

    /* Create or attach to the shared activity buffer */
    BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
                                         MaxBackends);
    BackendActivityBuffer = (char *)
        ShmemInitStruct("Backend Activity Buffer",
                        BackendActivityBufferSize,
                        &found);

    if (!found)
    {
        MemSet(BackendActivityBuffer, 0, size);

        /* Initialize st_activity pointers. */
        buffer = BackendActivityBuffer;
        for (i = 0; i < MaxBackends; i++)
        {
            BackendStatusArray[i].st_activity = buffer;
            buffer += pgstat_track_activity_query_size;
        }
    }
}

PgStat_BackendFunctionEntry* find_funcstat_entry ( Oid  func_id  ) 
PgStat_TableStatus* find_tabstat_entry ( Oid  rel_id  ) 
void pgstat_bestart ( void   ) 

Definition at line 2451 of file pgstat.c.

References application_name, Assert, GetCurrentTimestamp(), GetSessionUserId(), MemSet, MyDatabaseId, MyProcPid, MyProcPort, NAMEDATALEN, pgstat_report_appname(), pgstat_track_activity_query_size, Port::raddr, Port::remote_hostname, Port::SessionStartTime, 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_state, PgBackendStatus::st_state_start_timestamp, PgBackendStatus::st_userid, PgBackendStatus::st_waiting, PgBackendStatus::st_xact_start_timestamp, and strlcpy().

Referenced by InitPostgres().

{
    TimestampTz proc_start_timestamp;
    Oid         userid;
    SockAddr    clientaddr;
    volatile PgBackendStatus *beentry;

    /*
     * To minimize the time spent modifying the PgBackendStatus entry, fetch
     * all the needed data first.
     *
     * If we have a MyProcPort, use its session start time (for consistency,
     * and to save a kernel call).
     */
    if (MyProcPort)
        proc_start_timestamp = MyProcPort->SessionStartTime;
    else
        proc_start_timestamp = GetCurrentTimestamp();
    userid = GetSessionUserId();

    /*
     * We may not have a MyProcPort (eg, if this is the autovacuum process).
     * If so, use all-zeroes client address, which is dealt with specially in
     * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
     */
    if (MyProcPort)
        memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
    else
        MemSet(&clientaddr, 0, sizeof(clientaddr));

    /*
     * Initialize my status entry, following the protocol of bumping
     * st_changecount before and after; and make sure it's even afterwards. We
     * use a volatile pointer here to ensure the compiler doesn't try to get
     * cute.
     */
    beentry = MyBEEntry;
    do
    {
        beentry->st_changecount++;
    } while ((beentry->st_changecount & 1) == 0);

    beentry->st_procpid = MyProcPid;
    beentry->st_proc_start_timestamp = proc_start_timestamp;
    beentry->st_activity_start_timestamp = 0;
    beentry->st_state_start_timestamp = 0;
    beentry->st_xact_start_timestamp = 0;
    beentry->st_databaseid = MyDatabaseId;
    beentry->st_userid = userid;
    beentry->st_clientaddr = clientaddr;
    beentry->st_clienthostname[0] = '\0';
    beentry->st_waiting = false;
    beentry->st_state = STATE_UNDEFINED;
    beentry->st_appname[0] = '\0';
    beentry->st_activity[0] = '\0';
    /* Also make sure the last byte in each string area is always 0 */
    beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
    beentry->st_appname[NAMEDATALEN - 1] = '\0';
    beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';

    beentry->st_changecount++;
    Assert((beentry->st_changecount & 1) == 0);

    if (MyProcPort && MyProcPort->remote_hostname)
        strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname, NAMEDATALEN);

    /* Update app name to current GUC setting */
    if (application_name)
        pgstat_report_appname(application_name);
}

void pgstat_clear_snapshot ( void   ) 

Definition at line 4370 of file pgstat.c.

References localNumBackends, and MemoryContextDelete().

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

{
    /* Release memory, if any was allocated */
    if (pgStatLocalContext)
        MemoryContextDelete(pgStatLocalContext);

    /* Reset variables */
    pgStatLocalContext = NULL;
    pgStatDBHash = NULL;
    localBackendStatusTable = NULL;
    localNumBackends = 0;
}

void pgstat_count_heap_delete ( Relation  rel  ) 

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

{
    PgStat_TableStatus *pgstat_info = rel->pgstat_info;

    if (pgstat_info != NULL)
    {
        /* We have to log the effect at the proper transactional level */
        int         nest_level = GetCurrentTransactionNestLevel();

        if (pgstat_info->trans == NULL ||
            pgstat_info->trans->nest_level != nest_level)
            add_tabstat_xact_level(pgstat_info, nest_level);

        pgstat_info->trans->tuples_deleted++;
    }
}

void pgstat_count_heap_insert ( Relation  rel,
int  n 
)

Definition at line 1766 of file pgstat.c.

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

Referenced by heap_insert(), and heap_multi_insert().

{
    PgStat_TableStatus *pgstat_info = rel->pgstat_info;

    if (pgstat_info != NULL)
    {
        /* We have to log the effect at the proper transactional level */
        int         nest_level = GetCurrentTransactionNestLevel();

        if (pgstat_info->trans == NULL ||
            pgstat_info->trans->nest_level != nest_level)
            add_tabstat_xact_level(pgstat_info, nest_level);

        pgstat_info->trans->tuples_inserted += n;
    }
}

void pgstat_count_heap_update ( Relation  rel,
bool  hot 
)

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

{
    PgStat_TableStatus *pgstat_info = rel->pgstat_info;

    if (pgstat_info != NULL)
    {
        /* We have to log the effect at the proper transactional level */
        int         nest_level = GetCurrentTransactionNestLevel();

        if (pgstat_info->trans == NULL ||
            pgstat_info->trans->nest_level != nest_level)
            add_tabstat_xact_level(pgstat_info, nest_level);

        pgstat_info->trans->tuples_updated++;

        /* t_tuples_hot_updated is nontransactional, so just advance it */
        if (hot)
            pgstat_info->t_counts.t_tuples_hot_updated++;
    }
}

void pgstat_drop_database ( Oid  databaseid  ) 
void pgstat_end_function_usage ( PgStat_FunctionCallUsage fcu,
bool  finalize 
)

Definition at line 1538 of file pgstat.c.

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

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

{
    PgStat_FunctionCounts *fs = fcu->fs;
    instr_time  f_total;
    instr_time  f_others;
    instr_time  f_self;

    /* stats not wanted? */
    if (fs == NULL)
        return;

    /* total elapsed time in this function call */
    INSTR_TIME_SET_CURRENT(f_total);
    INSTR_TIME_SUBTRACT(f_total, fcu->f_start);

    /* self usage: elapsed minus anything already charged to other calls */
    f_others = total_func_time;
    INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
    f_self = f_total;
    INSTR_TIME_SUBTRACT(f_self, f_others);

    /* update backend-wide total time */
    INSTR_TIME_ADD(total_func_time, f_self);

    /*
     * Compute the new f_total_time as the total elapsed time added to the
     * pre-call value of f_total_time.  This is necessary to avoid
     * double-counting any time taken by recursive calls of myself.  (We do
     * not need any similar kluge for self time, since that already excludes
     * any recursive calls.)
     */
    INSTR_TIME_ADD(f_total, fcu->save_f_total_time);

    /* update counters in function stats table */
    if (finalize)
        fs->f_numcalls++;
    fs->f_total_time = f_total;
    INSTR_TIME_ADD(fs->f_self_time, f_self);

    /* indicate that we have something to send */
    have_function_stats = true;
}

PgStat_GlobalStats* pgstat_fetch_global ( void   ) 
PgBackendStatus* pgstat_fetch_stat_beentry ( int  beid  ) 
PgStat_StatDBEntry* pgstat_fetch_stat_dbentry ( Oid  dbid  ) 
PgStat_StatFuncEntry* pgstat_fetch_stat_funcentry ( Oid  funcid  ) 

Definition at line 2230 of file pgstat.c.

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

{
    PgStat_StatDBEntry *dbentry;
    PgStat_StatFuncEntry *funcentry = NULL;

    /* load the stats file if needed */
    backend_read_statsfile();

    /* Lookup our database, then find the requested function.  */
    dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
    if (dbentry != NULL && dbentry->functions != NULL)
    {
        funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
                                                         (void *) &func_id,
                                                         HASH_FIND, NULL);
    }

    return funcentry;
}

int pgstat_fetch_stat_numbackends ( void   ) 
PgStat_StatTabEntry* pgstat_fetch_stat_tabentry ( Oid  relid  ) 

Definition at line 2174 of file pgstat.c.

References backend_read_statsfile(), hash_search(), 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_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().

{
    Oid         dbid;
    PgStat_StatDBEntry *dbentry;
    PgStat_StatTabEntry *tabentry;

    /*
     * If not done for this transaction, read the statistics collector stats
     * file into some hash tables.
     */
    backend_read_statsfile();

    /*
     * Lookup our database, then look in its table hash table.
     */
    dbid = MyDatabaseId;
    dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
                                                 (void *) &dbid,
                                                 HASH_FIND, NULL);
    if (dbentry != NULL && dbentry->tables != NULL)
    {
        tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
                                                       (void *) &relid,
                                                       HASH_FIND, NULL);
        if (tabentry)
            return tabentry;
    }

    /*
     * If we didn't find it, maybe it's a shared table.
     */
    dbid = InvalidOid;
    dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
                                                 (void *) &dbid,
                                                 HASH_FIND, NULL);
    if (dbentry != NULL && dbentry->tables != NULL)
    {
        tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
                                                       (void *) &relid,
                                                       HASH_FIND, NULL);
        if (tabentry)
            return tabentry;
    }

    return NULL;
}

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 2826 of file pgstat.c.

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

Referenced by DeadLockReport().

{
    PgBackendStatus *beentry;
    int         i;

    beentry = BackendStatusArray;
    for (i = 1; i <= MaxBackends; i++)
    {
        /*
         * Although we expect the target backend's entry to be stable, that
         * doesn't imply that anyone else's is.  To avoid identifying the
         * wrong backend, while we check for a match to the desired PID we
         * must follow the protocol of retrying if st_changecount changes
         * while we examine the entry, or if it's odd.  (This might be
         * unnecessary, since fetching or storing an int is almost certainly
         * atomic, but let's play it safe.)  We use a volatile pointer here to
         * ensure the compiler doesn't try to get cute.
         */
        volatile PgBackendStatus *vbeentry = beentry;
        bool        found;

        for (;;)
        {
            int         save_changecount = vbeentry->st_changecount;

            found = (vbeentry->st_procpid == pid);

            if (save_changecount == vbeentry->st_changecount &&
                (save_changecount & 1) == 0)
                break;

            /* Make sure we can break out of loop if stuck... */
            CHECK_FOR_INTERRUPTS();
        }

        if (found)
        {
            /* Now it is safe to use the non-volatile pointer */
            if (checkUser && !superuser() && beentry->st_userid != GetUserId())
                return "<insufficient privilege>";
            else if (*(beentry->st_activity) == '\0')
                return "<command string not enabled>";
            else
                return beentry->st_activity;
        }

        beentry++;
    }

    /* If we get here, caller is in error ... */
    return "<backend information not available>";
}

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

Definition at line 2896 of file pgstat.c.

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

Referenced by LogChildExit().

{
    volatile PgBackendStatus *beentry;
    int         i;

    beentry = BackendStatusArray;

    /*
     * We probably shouldn't get here before shared memory has been set up,
     * but be safe.
     */
    if (beentry == NULL || BackendActivityBuffer == NULL)
        return NULL;

    for (i = 1; i <= MaxBackends; i++)
    {
        if (beentry->st_procpid == pid)
        {
            /* Read pointer just once, so it can't change after validation */
            const char *activity = beentry->st_activity;
            const char *activity_last;

            /*
             * We mustn't access activity string before we verify that it
             * falls within the BackendActivityBuffer. To make sure that the
             * entire string including its ending is contained within the
             * buffer, subtract one activity length from the buffer size.
             */
            activity_last = BackendActivityBuffer + BackendActivityBufferSize
                - pgstat_track_activity_query_size;

            if (activity < BackendActivityBuffer ||
                activity > activity_last)
                return NULL;

            /* If no string available, no point in a report */
            if (activity[0] == '\0')
                return NULL;

            /*
             * Copy only ASCII-safe characters so we don't run into encoding
             * problems when reporting the message; and be sure not to run off
             * the end of memory.
             */
            ascii_safe_strlcpy(buffer, activity,
                               Min(buflen, pgstat_track_activity_query_size));

            return buffer;
        }

        beentry++;
    }

    /* PID not found */
    return NULL;
}

void pgstat_init ( void   ) 

Definition at line 316 of file pgstat.c.

References addrinfo::ai_next, 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, pgStatAddr, pgStatSock, recv, select, send, SetConfigOption(), socket, and TESTBYTEVAL.

Referenced by PostmasterMain().

{
    ACCEPT_TYPE_ARG3 alen;
    struct addrinfo *addrs = NULL,
               *addr,
                hints;
    int         ret;
    fd_set      rset;
    struct timeval tv;
    char        test_byte;
    int         sel_res;
    int         tries = 0;

#define TESTBYTEVAL ((char) 199)

    /*
     * Create the UDP socket for sending and receiving statistic messages
     */
    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = 0;
    hints.ai_addrlen = 0;
    hints.ai_addr = NULL;
    hints.ai_canonname = NULL;
    hints.ai_next = NULL;
    ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
    if (ret || !addrs)
    {
        ereport(LOG,
                (errmsg("could not resolve \"localhost\": %s",
                        gai_strerror(ret))));
        goto startup_failed;
    }

    /*
     * On some platforms, pg_getaddrinfo_all() may return multiple addresses
     * only one of which will actually work (eg, both IPv6 and IPv4 addresses
     * when kernel will reject IPv6).  Worse, the failure may occur at the
     * bind() or perhaps even connect() stage.  So we must loop through the
     * results till we find a working combination. We will generate LOG
     * messages, but no error, for bogus combinations.
     */
    for (addr = addrs; addr; addr = addr->ai_next)
    {
#ifdef HAVE_UNIX_SOCKETS
        /* Ignore AF_UNIX sockets, if any are returned. */
        if (addr->ai_family == AF_UNIX)
            continue;
#endif

        if (++tries > 1)
            ereport(LOG,
            (errmsg("trying another address for the statistics collector")));

        /*
         * Create the socket.
         */
        if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
        {
            ereport(LOG,
                    (errcode_for_socket_access(),
            errmsg("could not create socket for statistics collector: %m")));
            continue;
        }

        /*
         * Bind it to a kernel assigned port on localhost and get the assigned
         * port via getsockname().
         */
        if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
        {
            ereport(LOG,
                    (errcode_for_socket_access(),
              errmsg("could not bind socket for statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        alen = sizeof(pgStatAddr);
        if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
        {
            ereport(LOG,
                    (errcode_for_socket_access(),
                     errmsg("could not get address of socket for statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        /*
         * Connect the socket to its own address.  This saves a few cycles by
         * not having to respecify the target address on every send. This also
         * provides a kernel-level check that only packets from this same
         * address will be received.
         */
        if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
        {
            ereport(LOG,
                    (errcode_for_socket_access(),
            errmsg("could not connect socket for statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        /*
         * Try to send and receive a one-byte test message on the socket. This
         * is to catch situations where the socket can be created but will not
         * actually pass data (for instance, because kernel packet filtering
         * rules prevent it).
         */
        test_byte = TESTBYTEVAL;

retry1:
        if (send(pgStatSock, &test_byte, 1, 0) != 1)
        {
            if (errno == EINTR)
                goto retry1;    /* if interrupted, just retry */
            ereport(LOG,
                    (errcode_for_socket_access(),
                     errmsg("could not send test message on socket for statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        /*
         * There could possibly be a little delay before the message can be
         * received.  We arbitrarily allow up to half a second before deciding
         * it's broken.
         */
        for (;;)                /* need a loop to handle EINTR */
        {
            FD_ZERO(&rset);
            FD_SET(pgStatSock, &rset);

            tv.tv_sec = 0;
            tv.tv_usec = 500000;
            sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
            if (sel_res >= 0 || errno != EINTR)
                break;
        }
        if (sel_res < 0)
        {
            ereport(LOG,
                    (errcode_for_socket_access(),
                     errmsg("select() failed in statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }
        if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
        {
            /*
             * This is the case we actually think is likely, so take pains to
             * give a specific message for it.
             *
             * errno will not be set meaningfully here, so don't use it.
             */
            ereport(LOG,
                    (errcode(ERRCODE_CONNECTION_FAILURE),
                     errmsg("test message did not get through on socket for statistics collector")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        test_byte++;            /* just make sure variable is changed */

retry2:
        if (recv(pgStatSock, &test_byte, 1, 0) != 1)
        {
            if (errno == EINTR)
                goto retry2;    /* if interrupted, just retry */
            ereport(LOG,
                    (errcode_for_socket_access(),
                     errmsg("could not receive test message on socket for statistics collector: %m")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
        {
            ereport(LOG,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("incorrect test message transmission on socket for statistics collector")));
            closesocket(pgStatSock);
            pgStatSock = PGINVALID_SOCKET;
            continue;
        }

        /* If we get here, we have a working socket */
        break;
    }

    /* Did we find a working address? */
    if (!addr || pgStatSock == PGINVALID_SOCKET)
        goto startup_failed;

    /*
     * Set the socket to non-blocking IO.  This ensures that if the collector
     * falls behind, statistics messages will be discarded; backends won't
     * block waiting to send messages to the collector.
     */
    if (!pg_set_noblock(pgStatSock))
    {
        ereport(LOG,
                (errcode_for_socket_access(),
                 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
        goto startup_failed;
    }

    pg_freeaddrinfo_all(hints.ai_family, addrs);

    return;

startup_failed:
    ereport(LOG,
      (errmsg("disabling statistics collector for lack of working socket")));

    if (addrs)
        pg_freeaddrinfo_all(hints.ai_family, addrs);

    if (pgStatSock != PGINVALID_SOCKET)
        closesocket(pgStatSock);
    pgStatSock = PGINVALID_SOCKET;

    /*
     * Adjust GUC variables to suppress useless activity, and for debugging
     * purposes (seeing track_counts off is a clue that we failed here). We
     * use PGC_S_OVERRIDE because there is no point in trying to turn it back
     * on from postgresql.conf without a restart.
     */
    SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
}

void pgstat_init_function_usage ( FunctionCallInfoData fcinfo,
PgStat_FunctionCallUsage fcu 
)

Definition at line 1465 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, HASHCTL::hash, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FUNCTION, hash_search(), INSTR_TIME_SET_CURRENT, HASHCTL::keysize, MemSet, PGSTAT_FUNCTION_HASH_SIZE, PgStat_FunctionCallUsage::save_f_total_time, PgStat_FunctionCallUsage::save_total, and total_func_time.

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

{
    PgStat_BackendFunctionEntry *htabent;
    bool        found;

    if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
    {
        /* stats not wanted */
        fcu->fs = NULL;
        return;
    }

    if (!pgStatFunctions)
    {
        /* First time through - initialize function stat table */
        HASHCTL     hash_ctl;

        memset(&hash_ctl, 0, sizeof(hash_ctl));
        hash_ctl.keysize = sizeof(Oid);
        hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
        hash_ctl.hash = oid_hash;
        pgStatFunctions = hash_create("Function stat entries",
                                      PGSTAT_FUNCTION_HASH_SIZE,
                                      &hash_ctl,
                                      HASH_ELEM | HASH_FUNCTION);
    }

    /* Get the stats entry for this function, create if necessary */
    htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
                          HASH_ENTER, &found);
    if (!found)
        MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));

    fcu->fs = &htabent->f_counts;

    /* save stats for this function, later used to compensate for recursion */
    fcu->save_f_total_time = htabent->f_counts.f_total_time;

    /* save current backend-wide total time */
    fcu->save_total = total_func_time;

    /* get clock time as of function start */
    INSTR_TIME_SET_CURRENT(fcu->f_start);
}

void pgstat_initialize ( void   ) 

Definition at line 2431 of file pgstat.c.

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

Referenced by InitPostgres().

{
    /* Initialize MyBEEntry */
    Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
    MyBEEntry = &BackendStatusArray[MyBackendId - 1];

    /* Set up a process-exit hook to clean up */
    on_shmem_exit(pgstat_beshutdown_hook, 0);
}

void pgstat_initstats ( Relation  rel  ) 

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

{
    Oid         rel_id = rel->rd_id;
    char        relkind = rel->rd_rel->relkind;

    /* We only count stats for things that have storage */
    if (!(relkind == RELKIND_RELATION ||
          relkind == RELKIND_MATVIEW ||
          relkind == RELKIND_INDEX ||
          relkind == RELKIND_TOASTVALUE ||
          relkind == RELKIND_SEQUENCE))
    {
        rel->pgstat_info = NULL;
        return;
    }

    if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    {
        /* We're not counting at all */
        rel->pgstat_info = NULL;
        return;
    }

    /*
     * If we already set up this relation in the current transaction, nothing
     * to do.
     */
    if (rel->pgstat_info != NULL &&
        rel->pgstat_info->t_id == rel_id)
        return;

    /* Else find or make the PgStat_TableStatus entry, and update link */
    rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
}

void pgstat_ping ( void   ) 
void pgstat_report_activity ( BackendState  state,
const char *  cmd_str 
)

Definition at line 2571 of file pgstat.c.

References Assert, GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), NULL, pg_mbcliplen(), pgstat_track_activities, pgstat_track_activity_query_size, PgBackendStatus::st_activity, PgBackendStatus::st_activity_start_timestamp, PgBackendStatus::st_changecount, PgBackendStatus::st_state, PgBackendStatus::st_state_start_timestamp, PgBackendStatus::st_waiting, PgBackendStatus::st_xact_start_timestamp, and STATE_DISABLED.

Referenced by autovac_report_activity(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), initialize_worker_spi(), PostgresMain(), and worker_spi_main().

{
    volatile PgBackendStatus *beentry = MyBEEntry;
    TimestampTz start_timestamp;
    TimestampTz current_timestamp;
    int         len = 0;

    TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);

    if (!beentry)
        return;

    if (!pgstat_track_activities)
    {
        if (beentry->st_state != STATE_DISABLED)
        {
            /*
             * track_activities is disabled, but we last reported a
             * non-disabled state.  As our final update, change the state and
             * clear fields we will not be updating anymore.
             */
            beentry->st_changecount++;
            beentry->st_state = STATE_DISABLED;
            beentry->st_state_start_timestamp = 0;
            beentry->st_activity[0] = '\0';
            beentry->st_activity_start_timestamp = 0;
            /* st_xact_start_timestamp and st_waiting are also disabled */
            beentry->st_xact_start_timestamp = 0;
            beentry->st_waiting = false;
            beentry->st_changecount++;
            Assert((beentry->st_changecount & 1) == 0);
        }
        return;
    }

    /*
     * To minimize the time spent modifying the entry, fetch all the needed
     * data first.
     */
    start_timestamp = GetCurrentStatementStartTimestamp();
    if (cmd_str != NULL)
    {
        len = pg_mbcliplen(cmd_str, strlen(cmd_str),
                           pgstat_track_activity_query_size - 1);
    }
    current_timestamp = GetCurrentTimestamp();

    /*
     * Now update the status entry
     */
    beentry->st_changecount++;

    beentry->st_state = state;
    beentry->st_state_start_timestamp = current_timestamp;

    if (cmd_str != NULL)
    {
        memcpy((char *) beentry->st_activity, cmd_str, len);
        beentry->st_activity[len] = '\0';
        beentry->st_activity_start_timestamp = start_timestamp;
    }

    beentry->st_changecount++;
    Assert((beentry->st_changecount & 1) == 0);
}

void pgstat_report_analyze ( Relation  rel,
PgStat_Counter  livetuples,
PgStat_Counter  deadtuples 
)

Definition at line 1319 of file pgstat.c.

References GetCurrentTimestamp(), InvalidOid, IsAutoVacuumWorkerProcess(), PgStat_MsgAnalyze::m_analyzetime, PgStat_MsgAnalyze::m_autovacuum, PgStat_MsgAnalyze::m_databaseid, PgStat_MsgAnalyze::m_dead_tuples, PgStat_MsgAnalyze::m_hdr, PgStat_MsgAnalyze::m_live_tuples, PgStat_MsgAnalyze::m_tableoid, Max, MyDatabaseId, NULL, PGINVALID_SOCKET, RelationData::pgstat_info, PGSTAT_MTYPE_ANALYZE, pgstat_send(), pgstat_setheader(), pgstat_track_counts, pgStatSock, RelationData::rd_rel, RelationGetRelid, PgStat_TableStatus::t_counts, PgStat_TableCounts::t_delta_dead_tuples, PgStat_TableStatus::trans, trans, PgStat_TableXactStatus::tuples_deleted, PgStat_TableXactStatus::tuples_inserted, PgStat_TableXactStatus::tuples_updated, and PgStat_TableXactStatus::upper.

Referenced by do_analyze_rel().

{
    PgStat_MsgAnalyze msg;

    if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
        return;

    /*
     * Unlike VACUUM, ANALYZE might be running inside a transaction that has
     * already inserted and/or deleted rows in the target table. ANALYZE will
     * have counted such rows as live or dead respectively. Because we will
     * report our counts of such rows at transaction end, we should subtract
     * off these counts from what we send to the collector now, else they'll
     * be double-counted after commit.  (This approach also ensures that the
     * collector ends up with the right numbers if we abort instead of
     * committing.)
     */
    if (rel->pgstat_info != NULL)
    {
        PgStat_TableXactStatus *trans;

        for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
        {
            livetuples -= trans->tuples_inserted - trans->tuples_deleted;
            deadtuples -= trans->tuples_updated + trans->tuples_deleted;
        }
        /* count stuff inserted by already-aborted subxacts, too */
        deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
        /* Since ANALYZE's counts are estimates, we could have underflowed */
        livetuples = Max(livetuples, 0);
        deadtuples = Max(deadtuples, 0);
    }

    pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
    msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
    msg.m_tableoid = RelationGetRelid(rel);
    msg.m_autovacuum = IsAutoVacuumWorkerProcess();
    msg.m_analyzetime = GetCurrentTimestamp();
    msg.m_live_tuples = livetuples;
    msg.m_dead_tuples = deadtuples;
    pgstat_send(&msg, sizeof(msg));
}

void pgstat_report_appname ( const char *  appname  ) 

Definition at line 2644 of file pgstat.c.

References Assert, NAMEDATALEN, pg_mbcliplen(), PgBackendStatus::st_appname, and PgBackendStatus::st_changecount.

Referenced by assign_application_name(), and pgstat_bestart().

{
    volatile PgBackendStatus *beentry = MyBEEntry;
    int         len;

    if (!beentry)
        return;

    /* This should be unnecessary if GUC did its job, but be safe */
    len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);

    /*
     * Update my status entry, following the protocol of bumping
     * st_changecount before and after.  We use a volatile pointer here to
     * ensure the compiler doesn't try to get cute.
     */
    beentry->st_changecount++;

    memcpy((char *) beentry->st_appname, appname, len);
    beentry->st_appname[len] = '\0';

    beentry->st_changecount++;
    Assert((beentry->st_changecount & 1) == 0);
}

void pgstat_report_autovac ( Oid  dboid  ) 
void pgstat_report_deadlock ( void   ) 
void pgstat_report_recovery_conflict ( int  reason  ) 
void pgstat_report_stat ( bool  force  ) 

Definition at line 713 of file pgstat.c.

References Assert, GetCurrentTransactionStopTimestamp(), have_function_stats, i, PgStat_MsgTabstat::m_databaseid, PgStat_MsgTabstat::m_entry, PgStat_MsgTabstat::m_nentries, memcmp(), MemSet, MyDatabaseId, NULL, PGSTAT_NUM_TABENTRIES, pgstat_send_funcstats(), pgstat_send_tabstat(), PGSTAT_STAT_INTERVAL, pgStatXactCommit, pgStatXactRollback, PgStat_TableEntry::t_counts, PgStat_TableStatus::t_counts, PgStat_TableStatus::t_id, PgStat_TableEntry::t_id, PgStat_TableStatus::t_shared, TimestampDifferenceExceeds(), PgStat_TableStatus::trans, TabStatusArray::tsa_entries, TabStatusArray::tsa_next, and TabStatusArray::tsa_used.

Referenced by pgstat_beshutdown_hook(), and PostgresMain().

{
    /* we assume this inits to all zeroes: */
    static const PgStat_TableCounts all_zeroes;
    static TimestampTz last_report = 0;

    TimestampTz now;
    PgStat_MsgTabstat regular_msg;
    PgStat_MsgTabstat shared_msg;
    TabStatusArray *tsa;
    int         i;

    /* Don't expend a clock check if nothing to do */
    if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
        !have_function_stats && !force)
        return;

    /*
     * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
     * msec since we last sent one, or the caller wants to force stats out.
     */
    now = GetCurrentTransactionStopTimestamp();
    if (!force &&
        !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
        return;
    last_report = now;

    /*
     * Scan through the TabStatusArray struct(s) to find tables that actually
     * have counts, and build messages to send.  We have to separate shared
     * relations from regular ones because the databaseid field in the message
     * header has to depend on that.
     */
    regular_msg.m_databaseid = MyDatabaseId;
    shared_msg.m_databaseid = InvalidOid;
    regular_msg.m_nentries = 0;
    shared_msg.m_nentries = 0;

    for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
    {
        for (i = 0; i < tsa->tsa_used; i++)
        {
            PgStat_TableStatus *entry = &tsa->tsa_entries[i];
            PgStat_MsgTabstat *this_msg;
            PgStat_TableEntry *this_ent;

            /* Shouldn't have any pending transaction-dependent counts */
            Assert(entry->trans == NULL);

            /*
             * Ignore entries that didn't accumulate any actual counts, such
             * as indexes that were opened by the planner but not used.
             */
            if (memcmp(&entry->t_counts, &all_zeroes,
                       sizeof(PgStat_TableCounts)) == 0)
                continue;

            /*
             * OK, insert data into the appropriate message, and send if full.
             */
            this_msg = entry->t_shared ? &shared_msg : &regular_msg;
            this_ent = &this_msg->m_entry[this_msg->m_nentries];
            this_ent->t_id = entry->t_id;
            memcpy(&this_ent->t_counts, &entry->t_counts,
                   sizeof(PgStat_TableCounts));
            if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
            {
                pgstat_send_tabstat(this_msg);
                this_msg->m_nentries = 0;
            }
        }
        /* zero out TableStatus structs after use */
        MemSet(tsa->tsa_entries, 0,
               tsa->tsa_used * sizeof(PgStat_TableStatus));
        tsa->tsa_used = 0;
    }

    /*
     * Send partial messages.  If force is true, make sure that any pending
     * xact commit/abort gets counted, even if no table stats to send.
     */
    if (regular_msg.m_nentries > 0 ||
        (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
        pgstat_send_tabstat(&regular_msg);
    if (shared_msg.m_nentries > 0)
        pgstat_send_tabstat(&shared_msg);

    /* Now, send function statistics */
    pgstat_send_funcstats();
}

void pgstat_report_tempfile ( size_t  filesize  ) 
void pgstat_report_vacuum ( Oid  tableoid,
bool  shared,
PgStat_Counter  tuples 
)
void pgstat_report_waiting ( bool  waiting  ) 

Definition at line 2702 of file pgstat.c.

References pgstat_track_activities, and PgBackendStatus::st_waiting.

Referenced by WaitOnLock().

{
    volatile PgBackendStatus *beentry = MyBEEntry;

    if (!pgstat_track_activities || !beentry)
        return;

    /*
     * Since this is a single-byte field in a struct that only this process
     * may modify, there seems no need to bother with the st_changecount
     * protocol.  The update must appear atomic in any case.
     */
    beentry->st_waiting = waiting;
}

void pgstat_report_xact_timestamp ( TimestampTz  tstamp  ) 

Definition at line 2674 of file pgstat.c.

References Assert, pgstat_track_activities, PgBackendStatus::st_changecount, and PgBackendStatus::st_xact_start_timestamp.

Referenced by AbortTransaction(), CommitTransaction(), and StartTransaction().

{
    volatile PgBackendStatus *beentry = MyBEEntry;

    if (!pgstat_track_activities || !beentry)
        return;

    /*
     * Update my status entry, following the protocol of bumping
     * st_changecount before and after.  We use a volatile pointer here to
     * ensure the compiler doesn't try to get cute.
     */
    beentry->st_changecount++;
    beentry->st_xact_start_timestamp = tstamp;
    beentry->st_changecount++;
    Assert((beentry->st_changecount & 1) == 0);
}

void pgstat_reset_all ( void   ) 
void pgstat_reset_counters ( void   ) 
void pgstat_reset_shared_counters ( const char *   ) 

Definition at line 1214 of file pgstat.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, PgStat_MsgResetsharedcounter::m_hdr, PgStat_MsgResetsharedcounter::m_resettarget, PGINVALID_SOCKET, PGSTAT_MTYPE_RESETSHAREDCOUNTER, pgstat_send(), pgstat_setheader(), pgStatSock, and superuser().

Referenced by pg_stat_reset_shared().

{
    PgStat_MsgResetsharedcounter msg;

    if (pgStatSock == PGINVALID_SOCKET)
        return;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 errmsg("must be superuser to reset statistics counters")));

    if (strcmp(target, "bgwriter") == 0)
        msg.m_resettarget = RESET_BGWRITER;
    else
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("unrecognized reset target: \"%s\"", target),
                 errhint("Target must be \"bgwriter\".")));

    pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
    pgstat_send(&msg, sizeof(msg));
}

void pgstat_reset_single_counter ( Oid  objectid,
PgStat_Single_Reset_Type  type 
)
void pgstat_send_bgwriter ( void   ) 

Definition at line 3009 of file pgstat.c.

References PgStat_MsgBgWriter::m_hdr, memcmp(), MemSet, PGSTAT_MTYPE_BGWRITER, pgstat_send(), and pgstat_setheader().

Referenced by BackgroundWriterMain(), CheckpointerMain(), and CheckpointWriteDelay().

{
    /* We assume this initializes to zeroes */
    static const PgStat_MsgBgWriter all_zeroes;

    /*
     * This function can be called even if nothing at all has happened. In
     * this case, avoid sending a completely empty message to the stats
     * collector.
     */
    if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
        return;

    /*
     * Prepare and send the message
     */
    pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
    pgstat_send(&BgWriterStats, sizeof(BgWriterStats));

    /*
     * Clear out the statistics buffer, so it can be re-used.
     */
    MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
}

int pgstat_start ( void   ) 

Definition at line 629 of file pgstat.c.

References ClosePostmasterPorts(), ereport, errmsg(), fork_process(), last_pgstat_start_time, LOG, NULL, on_exit_reset(), PGINVALID_SOCKET, PGSharedMemoryDetach(), PGSTAT_RESTART_INTERVAL, PgstatCollectorMain(), and pgStatSock.

Referenced by reaper(), ServerLoop(), and sigusr1_handler().

{
    time_t      curtime;
    pid_t       pgStatPid;

    /*
     * Check that the socket is there, else pgstat_init failed and we can do
     * nothing useful.
     */
    if (pgStatSock == PGINVALID_SOCKET)
        return 0;

    /*
     * Do nothing if too soon since last collector start.  This is a safety
     * valve to protect against continuous respawn attempts if the collector
     * is dying immediately at launch.  Note that since we will be re-called
     * from the postmaster main loop, we will get another chance later.
     */
    curtime = time(NULL);
    if ((unsigned int) (curtime - last_pgstat_start_time) <
        (unsigned int) PGSTAT_RESTART_INTERVAL)
        return 0;
    last_pgstat_start_time = curtime;

    /*
     * Okay, fork off the collector.
     */
#ifdef EXEC_BACKEND
    switch ((pgStatPid = pgstat_forkexec()))
#else
    switch ((pgStatPid = fork_process()))
#endif
    {
        case -1:
            ereport(LOG,
                    (errmsg("could not fork statistics collector: %m")));
            return 0;

#ifndef EXEC_BACKEND
        case 0:
            /* in postmaster child ... */
            /* Close the postmaster's sockets */
            ClosePostmasterPorts(false);

            /* Lose the postmaster's on-exit routines */
            on_exit_reset();

            /* Drop our connection to postmaster's shared memory, as well */
            PGSharedMemoryDetach();

            PgstatCollectorMain(0, NULL);
            break;
#endif

        default:
            return (int) pgStatPid;
    }

    /* shouldn't get here */
    return 0;
}

void pgstat_twophase_postabort ( TransactionId  xid,
uint16  info,
void *  recdata,
uint32  len 
)
void pgstat_twophase_postcommit ( TransactionId  xid,
uint16  info,
void *  recdata,
uint32  len 
)
void pgstat_update_heap_dead_tuples ( Relation  rel,
int  delta 
)

Definition at line 1838 of file pgstat.c.

References NULL, RelationData::pgstat_info, PgStat_TableStatus::t_counts, and PgStat_TableCounts::t_delta_dead_tuples.

Referenced by heap_page_prune().

{
    PgStat_TableStatus *pgstat_info = rel->pgstat_info;

    if (pgstat_info != NULL)
        pgstat_info->t_counts.t_delta_dead_tuples -= delta;
}

void pgstat_vacuum_stat ( void   ) 

Definition at line 911 of file pgstat.c.

References backend_read_statsfile(), CHECK_FOR_INTERRUPTS, PgStat_StatDBEntry::databaseid, DatabaseRelationId, PgStat_StatFuncEntry::functionid, PgStat_StatDBEntry::functions, hash_destroy(), HASH_FIND, hash_get_num_entries(), hash_search(), hash_seq_init(), hash_seq_search(), PgStat_MsgFuncpurge::m_databaseid, PgStat_MsgTabpurge::m_databaseid, PgStat_MsgFuncpurge::m_functionid, PgStat_MsgFuncpurge::m_hdr, PgStat_MsgTabpurge::m_hdr, PgStat_MsgFuncpurge::m_nentries, PgStat_MsgTabpurge::m_nentries, PgStat_MsgTabpurge::m_tableid, MyDatabaseId, NULL, offsetof, OidIsValid, PGINVALID_SOCKET, pgstat_collect_oids(), pgstat_drop_database(), PGSTAT_MTYPE_FUNCPURGE, PGSTAT_MTYPE_TABPURGE, PGSTAT_NUM_FUNCPURGE, PGSTAT_NUM_TABPURGE, pgstat_send(), pgstat_setheader(), pgStatSock, ProcedureRelationId, RelationRelationId, PgStat_StatTabEntry::tableid, and PgStat_StatDBEntry::tables.

Referenced by do_autovacuum(), and vacuum().

{
    HTAB       *htab;
    PgStat_MsgTabpurge msg;
    PgStat_MsgFuncpurge f_msg;
    HASH_SEQ_STATUS hstat;
    PgStat_StatDBEntry *dbentry;
    PgStat_StatTabEntry *tabentry;
    PgStat_StatFuncEntry *funcentry;
    int         len;

    if (pgStatSock == PGINVALID_SOCKET)
        return;

    /*
     * If not done for this transaction, read the statistics collector stats
     * file into some hash tables.
     */
    backend_read_statsfile();

    /*
     * Read pg_database and make a list of OIDs of all existing databases
     */
    htab = pgstat_collect_oids(DatabaseRelationId);

    /*
     * Search the database hash table for dead databases and tell the
     * collector to drop them.
     */
    hash_seq_init(&hstat, pgStatDBHash);
    while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
    {
        Oid         dbid = dbentry->databaseid;

        CHECK_FOR_INTERRUPTS();

        /* the DB entry for shared tables (with InvalidOid) is never dropped */
        if (OidIsValid(dbid) &&
            hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
            pgstat_drop_database(dbid);
    }

    /* Clean up */
    hash_destroy(htab);

    /*
     * Lookup our own database entry; if not found, nothing more to do.
     */
    dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
                                                 (void *) &MyDatabaseId,
                                                 HASH_FIND, NULL);
    if (dbentry == NULL || dbentry->tables == NULL)
        return;

    /*
     * Similarly to above, make a list of all known relations in this DB.
     */
    htab = pgstat_collect_oids(RelationRelationId);

    /*
     * Initialize our messages table counter to zero
     */
    msg.m_nentries = 0;

    /*
     * Check for all tables listed in stats hashtable if they still exist.
     */
    hash_seq_init(&hstat, dbentry->tables);
    while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
    {
        Oid         tabid = tabentry->tableid;

        CHECK_FOR_INTERRUPTS();

        if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
            continue;

        /*
         * Not there, so add this table's Oid to the message
         */
        msg.m_tableid[msg.m_nentries++] = tabid;

        /*
         * If the message is full, send it out and reinitialize to empty
         */
        if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
        {
            len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
                +msg.m_nentries * sizeof(Oid);

            pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
            msg.m_databaseid = MyDatabaseId;
            pgstat_send(&msg, len);

            msg.m_nentries = 0;
        }
    }

    /*
     * Send the rest
     */
    if (msg.m_nentries > 0)
    {
        len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
            +msg.m_nentries * sizeof(Oid);

        pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
        msg.m_databaseid = MyDatabaseId;
        pgstat_send(&msg, len);
    }

    /* Clean up */
    hash_destroy(htab);

    /*
     * Now repeat the above steps for functions.  However, we needn't bother
     * in the common case where no function stats are being collected.
     */
    if (dbentry->functions != NULL &&
        hash_get_num_entries(dbentry->functions) > 0)
    {
        htab = pgstat_collect_oids(ProcedureRelationId);

        pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
        f_msg.m_databaseid = MyDatabaseId;
        f_msg.m_nentries = 0;

        hash_seq_init(&hstat, dbentry->functions);
        while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
        {
            Oid         funcid = funcentry->functionid;

            CHECK_FOR_INTERRUPTS();

            if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
                continue;

            /*
             * Not there, so add this function's Oid to the message
             */
            f_msg.m_functionid[f_msg.m_nentries++] = funcid;

            /*
             * If the message is full, send it out and reinitialize to empty
             */
            if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
            {
                len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
                    +f_msg.m_nentries * sizeof(Oid);

                pgstat_send(&f_msg, len);

                f_msg.m_nentries = 0;
            }
        }

        /*
         * Send the rest
         */
        if (f_msg.m_nentries > 0)
        {
            len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
                +f_msg.m_nentries * sizeof(Oid);

            pgstat_send(&f_msg, len);
        }

        hash_destroy(htab);
    }
}

void PostPrepare_PgStat ( void   ) 

Definition at line 2057 of file pgstat.c.

References PgStat_SubXactStatus::first, PgStat_TableXactStatus::next, NULL, PgStat_TableXactStatus::parent, pgstat_clear_snapshot(), PgStat_TableStatus::trans, and trans.

Referenced by PrepareTransaction().

{
    PgStat_SubXactStatus *xact_state;

    /*
     * We don't bother to free any of the transactional state, since it's all
     * in TopTransactionContext and will go away anyway.
     */
    xact_state = pgStatXactStack;
    if (xact_state != NULL)
    {
        PgStat_TableXactStatus *trans;

        for (trans = xact_state->first; trans != NULL; trans = trans->next)
        {
            PgStat_TableStatus *tabstat;

            tabstat = trans->parent;
            tabstat->trans = NULL;
        }
    }
    pgStatXactStack = NULL;

    /* Make sure any stats snapshot is thrown away */
    pgstat_clear_snapshot();
}


Variable Documentation

Definition at line 122 of file pgstat.c.

Referenced by assign_pgstat_temp_directory(), and pgstat_write_statsfiles().

Definition at line 113 of file pgstat.c.

Definition at line 197 of file pgstat.c.

Referenced by pgstat_send_tabstat().

Definition at line 198 of file pgstat.c.

Referenced by pgstat_send_tabstat().