LCOV - code coverage report
Current view: top level - src/backend/postmaster - pgstat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1456 2332 62.4 %
Date: 2020-06-01 08:06:25 Functions: 106 128 82.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* ----------
       2             :  * pgstat.c
       3             :  *
       4             :  *  All the statistics collector stuff hacked up in one big, ugly file.
       5             :  *
       6             :  *  TODO:   - Separate collector, postmaster and backend stuff
       7             :  *            into different files.
       8             :  *
       9             :  *          - Add some automatic call for pgstat vacuuming.
      10             :  *
      11             :  *          - Add a pgstat config column to pg_database, so this
      12             :  *            entire thing can be enabled/disabled on a per db basis.
      13             :  *
      14             :  *  Copyright (c) 2001-2020, PostgreSQL Global Development Group
      15             :  *
      16             :  *  src/backend/postmaster/pgstat.c
      17             :  * ----------
      18             :  */
      19             : #include "postgres.h"
      20             : 
      21             : #include <unistd.h>
      22             : #include <fcntl.h>
      23             : #include <sys/param.h>
      24             : #include <sys/time.h>
      25             : #include <sys/socket.h>
      26             : #include <netdb.h>
      27             : #include <netinet/in.h>
      28             : #include <arpa/inet.h>
      29             : #include <signal.h>
      30             : #include <time.h>
      31             : #ifdef HAVE_SYS_SELECT_H
      32             : #include <sys/select.h>
      33             : #endif
      34             : 
      35             : #include "access/heapam.h"
      36             : #include "access/htup_details.h"
      37             : #include "access/tableam.h"
      38             : #include "access/transam.h"
      39             : #include "access/twophase_rmgr.h"
      40             : #include "access/xact.h"
      41             : #include "catalog/pg_database.h"
      42             : #include "catalog/pg_proc.h"
      43             : #include "common/ip.h"
      44             : #include "libpq/libpq.h"
      45             : #include "libpq/pqsignal.h"
      46             : #include "mb/pg_wchar.h"
      47             : #include "miscadmin.h"
      48             : #include "pg_trace.h"
      49             : #include "pgstat.h"
      50             : #include "postmaster/autovacuum.h"
      51             : #include "postmaster/fork_process.h"
      52             : #include "postmaster/interrupt.h"
      53             : #include "postmaster/postmaster.h"
      54             : #include "replication/walsender.h"
      55             : #include "storage/backendid.h"
      56             : #include "storage/dsm.h"
      57             : #include "storage/fd.h"
      58             : #include "storage/ipc.h"
      59             : #include "storage/latch.h"
      60             : #include "storage/lmgr.h"
      61             : #include "storage/pg_shmem.h"
      62             : #include "storage/procsignal.h"
      63             : #include "storage/sinvaladt.h"
      64             : #include "utils/ascii.h"
      65             : #include "utils/guc.h"
      66             : #include "utils/memutils.h"
      67             : #include "utils/ps_status.h"
      68             : #include "utils/rel.h"
      69             : #include "utils/snapmgr.h"
      70             : #include "utils/timestamp.h"
      71             : 
      72             : /* ----------
      73             :  * Timer definitions.
      74             :  * ----------
      75             :  */
      76             : #define PGSTAT_STAT_INTERVAL    500 /* Minimum time between stats file
      77             :                                      * updates; in milliseconds. */
      78             : 
      79             : #define PGSTAT_RETRY_DELAY      10  /* How long to wait between checks for a
      80             :                                      * new file; in milliseconds. */
      81             : 
      82             : #define PGSTAT_MAX_WAIT_TIME    10000   /* Maximum time to wait for a stats
      83             :                                          * file update; in milliseconds. */
      84             : 
      85             : #define PGSTAT_INQ_INTERVAL     640 /* How often to ping the collector for a
      86             :                                      * new file; in milliseconds. */
      87             : 
      88             : #define PGSTAT_RESTART_INTERVAL 60  /* How often to attempt to restart a
      89             :                                      * failed statistics collector; in
      90             :                                      * seconds. */
      91             : 
      92             : #define PGSTAT_POLL_LOOP_COUNT  (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
      93             : #define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
      94             : 
      95             : /* Minimum receive buffer size for the collector's socket. */
      96             : #define PGSTAT_MIN_RCVBUF       (100 * 1024)
      97             : 
      98             : 
      99             : /* ----------
     100             :  * The initial size hints for the hash tables used in the collector.
     101             :  * ----------
     102             :  */
     103             : #define PGSTAT_DB_HASH_SIZE     16
     104             : #define PGSTAT_TAB_HASH_SIZE    512
     105             : #define PGSTAT_FUNCTION_HASH_SIZE   512
     106             : 
     107             : 
     108             : /* ----------
     109             :  * Total number of backends including auxiliary
     110             :  *
     111             :  * We reserve a slot for each possible BackendId, plus one for each
     112             :  * possible auxiliary process type.  (This scheme assumes there is not
     113             :  * more than one of any auxiliary process type at a time.) MaxBackends
     114             :  * includes autovacuum workers and background workers as well.
     115             :  * ----------
     116             :  */
     117             : #define NumBackendStatSlots (MaxBackends + NUM_AUXPROCTYPES)
     118             : 
     119             : 
     120             : /* ----------
     121             :  * GUC parameters
     122             :  * ----------
     123             :  */
     124             : bool        pgstat_track_activities = false;
     125             : bool        pgstat_track_counts = false;
     126             : int         pgstat_track_functions = TRACK_FUNC_OFF;
     127             : int         pgstat_track_activity_query_size = 1024;
     128             : 
     129             : /* ----------
     130             :  * Built from GUC parameter
     131             :  * ----------
     132             :  */
     133             : char       *pgstat_stat_directory = NULL;
     134             : char       *pgstat_stat_filename = NULL;
     135             : char       *pgstat_stat_tmpname = NULL;
     136             : 
     137             : /*
     138             :  * BgWriter global statistics counters (unused in other processes).
     139             :  * Stored directly in a stats message structure so it can be sent
     140             :  * without needing to copy things around.  We assume this inits to zeroes.
     141             :  */
     142             : PgStat_MsgBgWriter BgWriterStats;
     143             : 
     144             : /*
     145             :  * List of SLRU names that we keep stats for.  There is no central registry of
     146             :  * SLRUs, so we use this fixed list instead.  The "other" entry is used for
     147             :  * all SLRUs without an explicit entry (e.g. SLRUs in extensions).
     148             :  */
     149             : static const char *const slru_names[] = {
     150             :     "CommitTs",
     151             :     "MultiXactMember",
     152             :     "MultiXactOffset",
     153             :     "Notify",
     154             :     "Serial",
     155             :     "Subtrans",
     156             :     "Xact",
     157             :     "other"                       /* has to be last */
     158             : };
     159             : 
     160             : #define SLRU_NUM_ELEMENTS   lengthof(slru_names)
     161             : 
     162             : /*
     163             :  * SLRU statistics counts waiting to be sent to the collector.  These are
     164             :  * stored directly in stats message format so they can be sent without needing
     165             :  * to copy things around.  We assume this variable inits to zeroes.  Entries
     166             :  * are one-to-one with slru_names[].
     167             :  */
     168             : static PgStat_MsgSLRU SLRUStats[SLRU_NUM_ELEMENTS];
     169             : 
     170             : /* ----------
     171             :  * Local data
     172             :  * ----------
     173             :  */
     174             : NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
     175             : 
     176             : static struct sockaddr_storage pgStatAddr;
     177             : 
     178             : static time_t last_pgstat_start_time;
     179             : 
     180             : static bool pgStatRunningInCollector = false;
     181             : 
     182             : /*
     183             :  * Structures in which backends store per-table info that's waiting to be
     184             :  * sent to the collector.
     185             :  *
     186             :  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
     187             :  * for the life of the backend.  Also, we zero out the t_id fields of the
     188             :  * contained PgStat_TableStatus structs whenever they are not actively in use.
     189             :  * This allows relcache pgstat_info pointers to be treated as long-lived data,
     190             :  * avoiding repeated searches in pgstat_initstats() when a relation is
     191             :  * repeatedly opened during a transaction.
     192             :  */
     193             : #define TABSTAT_QUANTUM     100 /* we alloc this many at a time */
     194             : 
     195             : typedef struct TabStatusArray
     196             : {
     197             :     struct TabStatusArray *tsa_next;    /* link to next array, if any */
     198             :     int         tsa_used;       /* # entries currently used */
     199             :     PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];    /* per-table data */
     200             : } TabStatusArray;
     201             : 
     202             : static TabStatusArray *pgStatTabList = NULL;
     203             : 
     204             : /*
     205             :  * pgStatTabHash entry: map from relation OID to PgStat_TableStatus pointer
     206             :  */
     207             : typedef struct TabStatHashEntry
     208             : {
     209             :     Oid         t_id;
     210             :     PgStat_TableStatus *tsa_entry;
     211             : } TabStatHashEntry;
     212             : 
     213             : /*
     214             :  * Hash table for O(1) t_id -> tsa_entry lookup
     215             :  */
     216             : static HTAB *pgStatTabHash = NULL;
     217             : 
     218             : /*
     219             :  * Backends store per-function info that's waiting to be sent to the collector
     220             :  * in this hash table (indexed by function OID).
     221             :  */
     222             : static HTAB *pgStatFunctions = NULL;
     223             : 
     224             : /*
     225             :  * Indicates if backend has some function stats that it hasn't yet
     226             :  * sent to the collector.
     227             :  */
     228             : static bool have_function_stats = false;
     229             : 
     230             : /*
     231             :  * Tuple insertion/deletion counts for an open transaction can't be propagated
     232             :  * into PgStat_TableStatus counters until we know if it is going to commit
     233             :  * or abort.  Hence, we keep these counts in per-subxact structs that live
     234             :  * in TopTransactionContext.  This data structure is designed on the assumption
     235             :  * that subxacts won't usually modify very many tables.
     236             :  */
     237             : typedef struct PgStat_SubXactStatus
     238             : {
     239             :     int         nest_level;     /* subtransaction nest level */
     240             :     struct PgStat_SubXactStatus *prev;  /* higher-level subxact if any */
     241             :     PgStat_TableXactStatus *first;  /* head of list for this subxact */
     242             : } PgStat_SubXactStatus;
     243             : 
     244             : static PgStat_SubXactStatus *pgStatXactStack = NULL;
     245             : 
     246             : static int  pgStatXactCommit = 0;
     247             : static int  pgStatXactRollback = 0;
     248             : PgStat_Counter pgStatBlockReadTime = 0;
     249             : PgStat_Counter pgStatBlockWriteTime = 0;
     250             : 
     251             : /* Record that's written to 2PC state file when pgstat state is persisted */
     252             : typedef struct TwoPhasePgStatRecord
     253             : {
     254             :     PgStat_Counter tuples_inserted; /* tuples inserted in xact */
     255             :     PgStat_Counter tuples_updated;  /* tuples updated in xact */
     256             :     PgStat_Counter tuples_deleted;  /* tuples deleted in xact */
     257             :     PgStat_Counter inserted_pre_trunc;  /* tuples inserted prior to truncate */
     258             :     PgStat_Counter updated_pre_trunc;   /* tuples updated prior to truncate */
     259             :     PgStat_Counter deleted_pre_trunc;   /* tuples deleted prior to truncate */
     260             :     Oid         t_id;           /* table's OID */
     261             :     bool        t_shared;       /* is it a shared catalog? */
     262             :     bool        t_truncated;    /* was the relation truncated? */
     263             : } TwoPhasePgStatRecord;
     264             : 
     265             : /*
     266             :  * Info about current "snapshot" of stats file
     267             :  */
     268             : static MemoryContext pgStatLocalContext = NULL;
     269             : static HTAB *pgStatDBHash = NULL;
     270             : 
     271             : /* Status for backends including auxiliary */
     272             : static LocalPgBackendStatus *localBackendStatusTable = NULL;
     273             : 
     274             : /* Total number of backends including auxiliary */
     275             : static int  localNumBackends = 0;
     276             : 
     277             : /*
     278             :  * Cluster wide statistics, kept in the stats collector.
     279             :  * Contains statistics that are not collected per database
     280             :  * or per table.
     281             :  */
     282             : static PgStat_ArchiverStats archiverStats;
     283             : static PgStat_GlobalStats globalStats;
     284             : static PgStat_SLRUStats slruStats[SLRU_NUM_ELEMENTS];
     285             : 
     286             : /*
     287             :  * List of OIDs of databases we need to write out.  If an entry is InvalidOid,
     288             :  * it means to write only the shared-catalog stats ("DB 0"); otherwise, we
     289             :  * will write both that DB's data and the shared stats.
     290             :  */
     291             : static List *pending_write_requests = NIL;
     292             : 
     293             : /*
     294             :  * Total time charged to functions so far in the current backend.
     295             :  * We use this to help separate "self" and "other" time charges.
     296             :  * (We assume this initializes to zero.)
     297             :  */
     298             : static instr_time total_func_time;
     299             : 
     300             : 
     301             : /* ----------
     302             :  * Local function forward declarations
     303             :  * ----------
     304             :  */
     305             : #ifdef EXEC_BACKEND
     306             : static pid_t pgstat_forkexec(void);
     307             : #endif
     308             : 
     309             : NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) pg_attribute_noreturn();
     310             : static void pgstat_beshutdown_hook(int code, Datum arg);
     311             : 
     312             : static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
     313             : static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
     314             :                                                  Oid tableoid, bool create);
     315             : static void pgstat_write_statsfiles(bool permanent, bool allDbs);
     316             : static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
     317             : static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
     318             : static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
     319             : static void backend_read_statsfile(void);
     320             : static void pgstat_read_current_status(void);
     321             : 
     322             : static bool pgstat_write_statsfile_needed(void);
     323             : static bool pgstat_db_requested(Oid databaseid);
     324             : 
     325             : static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
     326             : static void pgstat_send_funcstats(void);
     327             : static void pgstat_send_slru(void);
     328             : static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);
     329             : 
     330             : static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
     331             : 
     332             : static void pgstat_setup_memcxt(void);
     333             : 
     334             : static const char *pgstat_get_wait_activity(WaitEventActivity w);
     335             : static const char *pgstat_get_wait_client(WaitEventClient w);
     336             : static const char *pgstat_get_wait_ipc(WaitEventIPC w);
     337             : static const char *pgstat_get_wait_timeout(WaitEventTimeout w);
     338             : static const char *pgstat_get_wait_io(WaitEventIO w);
     339             : 
     340             : static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
     341             : static void pgstat_send(void *msg, int len);
     342             : 
     343             : static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
     344             : static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
     345             : static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
     346             : static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
     347             : static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
     348             : static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
     349             : static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
     350             : static void pgstat_recv_resetslrucounter(PgStat_MsgResetslrucounter *msg, int len);
     351             : static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
     352             : static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
     353             : static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
     354             : static void pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len);
     355             : static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
     356             : static void pgstat_recv_slru(PgStat_MsgSLRU *msg, int len);
     357             : static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
     358             : static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
     359             : static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
     360             : static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
     361             : static void pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len);
     362             : static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
     363             : 
     364             : /* ------------------------------------------------------------
     365             :  * Public functions called from postmaster follow
     366             :  * ------------------------------------------------------------
     367             :  */
     368             : 
     369             : /* ----------
     370             :  * pgstat_init() -
     371             :  *
     372             :  *  Called from postmaster at startup. Create the resources required
     373             :  *  by the statistics collector process.  If unable to do so, do not
     374             :  *  fail --- better to let the postmaster start with stats collection
     375             :  *  disabled.
     376             :  * ----------
     377             :  */
     378             : void
     379         716 : pgstat_init(void)
     380             : {
     381             :     ACCEPT_TYPE_ARG3 alen;
     382         716 :     struct addrinfo *addrs = NULL,
     383             :                *addr,
     384             :                 hints;
     385             :     int         ret;
     386             :     fd_set      rset;
     387             :     struct timeval tv;
     388             :     char        test_byte;
     389             :     int         sel_res;
     390         716 :     int         tries = 0;
     391             : 
     392             : #define TESTBYTEVAL ((char) 199)
     393             : 
     394             :     /*
     395             :      * This static assertion verifies that we didn't mess up the calculations
     396             :      * involved in selecting maximum payload sizes for our UDP messages.
     397             :      * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
     398             :      * be silent performance loss from fragmentation, it seems worth having a
     399             :      * compile-time cross-check that we didn't.
     400             :      */
     401             :     StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,
     402             :                      "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
     403             : 
     404             :     /*
     405             :      * Create the UDP socket for sending and receiving statistic messages
     406             :      */
     407         716 :     hints.ai_flags = AI_PASSIVE;
     408         716 :     hints.ai_family = AF_UNSPEC;
     409         716 :     hints.ai_socktype = SOCK_DGRAM;
     410         716 :     hints.ai_protocol = 0;
     411         716 :     hints.ai_addrlen = 0;
     412         716 :     hints.ai_addr = NULL;
     413         716 :     hints.ai_canonname = NULL;
     414         716 :     hints.ai_next = NULL;
     415         716 :     ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
     416         716 :     if (ret || !addrs)
     417             :     {
     418           0 :         ereport(LOG,
     419             :                 (errmsg("could not resolve \"localhost\": %s",
     420             :                         gai_strerror(ret))));
     421           0 :         goto startup_failed;
     422             :     }
     423             : 
     424             :     /*
     425             :      * On some platforms, pg_getaddrinfo_all() may return multiple addresses
     426             :      * only one of which will actually work (eg, both IPv6 and IPv4 addresses
     427             :      * when kernel will reject IPv6).  Worse, the failure may occur at the
     428             :      * bind() or perhaps even connect() stage.  So we must loop through the
     429             :      * results till we find a working combination. We will generate LOG
     430             :      * messages, but no error, for bogus combinations.
     431             :      */
     432         716 :     for (addr = addrs; addr; addr = addr->ai_next)
     433             :     {
     434             : #ifdef HAVE_UNIX_SOCKETS
     435             :         /* Ignore AF_UNIX sockets, if any are returned. */
     436         716 :         if (addr->ai_family == AF_UNIX)
     437           0 :             continue;
     438             : #endif
     439             : 
     440         716 :         if (++tries > 1)
     441           0 :             ereport(LOG,
     442             :                     (errmsg("trying another address for the statistics collector")));
     443             : 
     444             :         /*
     445             :          * Create the socket.
     446             :          */
     447         716 :         if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
     448             :         {
     449           0 :             ereport(LOG,
     450             :                     (errcode_for_socket_access(),
     451             :                      errmsg("could not create socket for statistics collector: %m")));
     452           0 :             continue;
     453             :         }
     454             : 
     455             :         /*
     456             :          * Bind it to a kernel assigned port on localhost and get the assigned
     457             :          * port via getsockname().
     458             :          */
     459         716 :         if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
     460             :         {
     461           0 :             ereport(LOG,
     462             :                     (errcode_for_socket_access(),
     463             :                      errmsg("could not bind socket for statistics collector: %m")));
     464           0 :             closesocket(pgStatSock);
     465           0 :             pgStatSock = PGINVALID_SOCKET;
     466           0 :             continue;
     467             :         }
     468             : 
     469         716 :         alen = sizeof(pgStatAddr);
     470         716 :         if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
     471             :         {
     472           0 :             ereport(LOG,
     473             :                     (errcode_for_socket_access(),
     474             :                      errmsg("could not get address of socket for statistics collector: %m")));
     475           0 :             closesocket(pgStatSock);
     476           0 :             pgStatSock = PGINVALID_SOCKET;
     477           0 :             continue;
     478             :         }
     479             : 
     480             :         /*
     481             :          * Connect the socket to its own address.  This saves a few cycles by
     482             :          * not having to respecify the target address on every send. This also
     483             :          * provides a kernel-level check that only packets from this same
     484             :          * address will be received.
     485             :          */
     486         716 :         if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
     487             :         {
     488           0 :             ereport(LOG,
     489             :                     (errcode_for_socket_access(),
     490             :                      errmsg("could not connect socket for statistics collector: %m")));
     491           0 :             closesocket(pgStatSock);
     492           0 :             pgStatSock = PGINVALID_SOCKET;
     493           0 :             continue;
     494             :         }
     495             : 
     496             :         /*
     497             :          * Try to send and receive a one-byte test message on the socket. This
     498             :          * is to catch situations where the socket can be created but will not
     499             :          * actually pass data (for instance, because kernel packet filtering
     500             :          * rules prevent it).
     501             :          */
     502         716 :         test_byte = TESTBYTEVAL;
     503             : 
     504         716 : retry1:
     505         716 :         if (send(pgStatSock, &test_byte, 1, 0) != 1)
     506             :         {
     507           0 :             if (errno == EINTR)
     508           0 :                 goto retry1;    /* if interrupted, just retry */
     509           0 :             ereport(LOG,
     510             :                     (errcode_for_socket_access(),
     511             :                      errmsg("could not send test message on socket for statistics collector: %m")));
     512           0 :             closesocket(pgStatSock);
     513           0 :             pgStatSock = PGINVALID_SOCKET;
     514           0 :             continue;
     515             :         }
     516             : 
     517             :         /*
     518             :          * There could possibly be a little delay before the message can be
     519             :          * received.  We arbitrarily allow up to half a second before deciding
     520             :          * it's broken.
     521             :          */
     522             :         for (;;)                /* need a loop to handle EINTR */
     523             :         {
     524         716 :             FD_ZERO(&rset);
     525         716 :             FD_SET(pgStatSock, &rset);
     526             : 
     527         716 :             tv.tv_sec = 0;
     528         716 :             tv.tv_usec = 500000;
     529         716 :             sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
     530         716 :             if (sel_res >= 0 || errno != EINTR)
     531             :                 break;
     532             :         }
     533         716 :         if (sel_res < 0)
     534             :         {
     535           0 :             ereport(LOG,
     536             :                     (errcode_for_socket_access(),
     537             :                      errmsg("select() failed in statistics collector: %m")));
     538           0 :             closesocket(pgStatSock);
     539           0 :             pgStatSock = PGINVALID_SOCKET;
     540           0 :             continue;
     541             :         }
     542         716 :         if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
     543             :         {
     544             :             /*
     545             :              * This is the case we actually think is likely, so take pains to
     546             :              * give a specific message for it.
     547             :              *
     548             :              * errno will not be set meaningfully here, so don't use it.
     549             :              */
     550           0 :             ereport(LOG,
     551             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     552             :                      errmsg("test message did not get through on socket for statistics collector")));
     553           0 :             closesocket(pgStatSock);
     554           0 :             pgStatSock = PGINVALID_SOCKET;
     555           0 :             continue;
     556             :         }
     557             : 
     558         716 :         test_byte++;            /* just make sure variable is changed */
     559             : 
     560         716 : retry2:
     561         716 :         if (recv(pgStatSock, &test_byte, 1, 0) != 1)
     562             :         {
     563           0 :             if (errno == EINTR)
     564           0 :                 goto retry2;    /* if interrupted, just retry */
     565           0 :             ereport(LOG,
     566             :                     (errcode_for_socket_access(),
     567             :                      errmsg("could not receive test message on socket for statistics collector: %m")));
     568           0 :             closesocket(pgStatSock);
     569           0 :             pgStatSock = PGINVALID_SOCKET;
     570           0 :             continue;
     571             :         }
     572             : 
     573         716 :         if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
     574             :         {
     575           0 :             ereport(LOG,
     576             :                     (errcode(ERRCODE_INTERNAL_ERROR),
     577             :                      errmsg("incorrect test message transmission on socket for statistics collector")));
     578           0 :             closesocket(pgStatSock);
     579           0 :             pgStatSock = PGINVALID_SOCKET;
     580           0 :             continue;
     581             :         }
     582             : 
     583             :         /* If we get here, we have a working socket */
     584         716 :         break;
     585             :     }
     586             : 
     587             :     /* Did we find a working address? */
     588         716 :     if (!addr || pgStatSock == PGINVALID_SOCKET)
     589           0 :         goto startup_failed;
     590             : 
     591             :     /*
     592             :      * Set the socket to non-blocking IO.  This ensures that if the collector
     593             :      * falls behind, statistics messages will be discarded; backends won't
     594             :      * block waiting to send messages to the collector.
     595             :      */
     596         716 :     if (!pg_set_noblock(pgStatSock))
     597             :     {
     598           0 :         ereport(LOG,
     599             :                 (errcode_for_socket_access(),
     600             :                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
     601           0 :         goto startup_failed;
     602             :     }
     603             : 
     604             :     /*
     605             :      * Try to ensure that the socket's receive buffer is at least
     606             :      * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
     607             :      * data.  Use of UDP protocol means that we are willing to lose data under
     608             :      * heavy load, but we don't want it to happen just because of ridiculously
     609             :      * small default buffer sizes (such as 8KB on older Windows versions).
     610             :      */
     611             :     {
     612             :         int         old_rcvbuf;
     613             :         int         new_rcvbuf;
     614         716 :         ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
     615             : 
     616         716 :         if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
     617             :                        (char *) &old_rcvbuf, &rcvbufsize) < 0)
     618             :         {
     619           0 :             elog(LOG, "getsockopt(SO_RCVBUF) failed: %m");
     620             :             /* if we can't get existing size, always try to set it */
     621           0 :             old_rcvbuf = 0;
     622             :         }
     623             : 
     624         716 :         new_rcvbuf = PGSTAT_MIN_RCVBUF;
     625         716 :         if (old_rcvbuf < new_rcvbuf)
     626             :         {
     627           0 :             if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
     628             :                            (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
     629           0 :                 elog(LOG, "setsockopt(SO_RCVBUF) failed: %m");
     630             :         }
     631             :     }
     632             : 
     633         716 :     pg_freeaddrinfo_all(hints.ai_family, addrs);
     634             : 
     635             :     /* Now that we have a long-lived socket, tell fd.c about it. */
     636         716 :     ReserveExternalFD();
     637             : 
     638         716 :     return;
     639             : 
     640           0 : startup_failed:
     641           0 :     ereport(LOG,
     642             :             (errmsg("disabling statistics collector for lack of working socket")));
     643             : 
     644           0 :     if (addrs)
     645           0 :         pg_freeaddrinfo_all(hints.ai_family, addrs);
     646             : 
     647           0 :     if (pgStatSock != PGINVALID_SOCKET)
     648           0 :         closesocket(pgStatSock);
     649           0 :     pgStatSock = PGINVALID_SOCKET;
     650             : 
     651             :     /*
     652             :      * Adjust GUC variables to suppress useless activity, and for debugging
     653             :      * purposes (seeing track_counts off is a clue that we failed here). We
     654             :      * use PGC_S_OVERRIDE because there is no point in trying to turn it back
     655             :      * on from postgresql.conf without a restart.
     656             :      */
     657           0 :     SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
     658             : }
     659             : 
     660             : /*
     661             :  * subroutine for pgstat_reset_all
     662             :  */
     663             : static void
     664         392 : pgstat_reset_remove_files(const char *directory)
     665             : {
     666             :     DIR        *dir;
     667             :     struct dirent *entry;
     668             :     char        fname[MAXPGPATH * 2];
     669             : 
     670         392 :     dir = AllocateDir(directory);
     671        1568 :     while ((entry = ReadDir(dir, directory)) != NULL)
     672             :     {
     673             :         int         nchars;
     674             :         Oid         tmp_oid;
     675             : 
     676             :         /*
     677             :          * Skip directory entries that don't match the file names we write.
     678             :          * See get_dbstat_filename for the database-specific pattern.
     679             :          */
     680        1176 :         if (strncmp(entry->d_name, "global.", 7) == 0)
     681         140 :             nchars = 7;
     682             :         else
     683             :         {
     684        1036 :             nchars = 0;
     685        1036 :             (void) sscanf(entry->d_name, "db_%u.%n",
     686             :                           &tmp_oid, &nchars);
     687        1036 :             if (nchars <= 0)
     688         784 :                 continue;
     689             :             /* %u allows leading whitespace, so reject that */
     690         252 :             if (strchr("0123456789", entry->d_name[3]) == NULL)
     691           0 :                 continue;
     692             :         }
     693             : 
     694         392 :         if (strcmp(entry->d_name + nchars, "tmp") != 0 &&
     695         392 :             strcmp(entry->d_name + nchars, "stat") != 0)
     696           0 :             continue;
     697             : 
     698         392 :         snprintf(fname, sizeof(fname), "%s/%s", directory,
     699         392 :                  entry->d_name);
     700         392 :         unlink(fname);
     701             :     }
     702         392 :     FreeDir(dir);
     703         392 : }
     704             : 
     705             : /*
     706             :  * pgstat_reset_all() -
     707             :  *
     708             :  * Remove the stats files.  This is currently used only if WAL
     709             :  * recovery is needed after a crash.
     710             :  */
     711             : void
     712         196 : pgstat_reset_all(void)
     713             : {
     714         196 :     pgstat_reset_remove_files(pgstat_stat_directory);
     715         196 :     pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
     716         196 : }
     717             : 
     718             : #ifdef EXEC_BACKEND
     719             : 
     720             : /*
     721             :  * pgstat_forkexec() -
     722             :  *
     723             :  * Format up the arglist for, then fork and exec, statistics collector process
     724             :  */
     725             : static pid_t
     726             : pgstat_forkexec(void)
     727             : {
     728             :     char       *av[10];
     729             :     int         ac = 0;
     730             : 
     731             :     av[ac++] = "postgres";
     732             :     av[ac++] = "--forkcol";
     733             :     av[ac++] = NULL;            /* filled in by postmaster_forkexec */
     734             : 
     735             :     av[ac] = NULL;
     736             :     Assert(ac < lengthof(av));
     737             : 
     738             :     return postmaster_forkexec(ac, av);
     739             : }
     740             : #endif                          /* EXEC_BACKEND */
     741             : 
     742             : 
     743             : /*
     744             :  * pgstat_start() -
     745             :  *
     746             :  *  Called from postmaster at startup or after an existing collector
     747             :  *  died.  Attempt to fire up a fresh statistics collector.
     748             :  *
     749             :  *  Returns PID of child process, or 0 if fail.
     750             :  *
     751             :  *  Note: if fail, we will be called again from the postmaster main loop.
     752             :  */
     753             : int
     754         720 : pgstat_start(void)
     755             : {
     756             :     time_t      curtime;
     757             :     pid_t       pgStatPid;
     758             : 
     759             :     /*
     760             :      * Check that the socket is there, else pgstat_init failed and we can do
     761             :      * nothing useful.
     762             :      */
     763         720 :     if (pgStatSock == PGINVALID_SOCKET)
     764           0 :         return 0;
     765             : 
     766             :     /*
     767             :      * Do nothing if too soon since last collector start.  This is a safety
     768             :      * valve to protect against continuous respawn attempts if the collector
     769             :      * is dying immediately at launch.  Note that since we will be re-called
     770             :      * from the postmaster main loop, we will get another chance later.
     771             :      */
     772         720 :     curtime = time(NULL);
     773         720 :     if ((unsigned int) (curtime - last_pgstat_start_time) <
     774             :         (unsigned int) PGSTAT_RESTART_INTERVAL)
     775           0 :         return 0;
     776         720 :     last_pgstat_start_time = curtime;
     777             : 
     778             :     /*
     779             :      * Okay, fork off the collector.
     780             :      */
     781             : #ifdef EXEC_BACKEND
     782             :     switch ((pgStatPid = pgstat_forkexec()))
     783             : #else
     784         720 :     switch ((pgStatPid = fork_process()))
     785             : #endif
     786             :     {
     787           0 :         case -1:
     788           0 :             ereport(LOG,
     789             :                     (errmsg("could not fork statistics collector: %m")));
     790           0 :             return 0;
     791             : 
     792             : #ifndef EXEC_BACKEND
     793         720 :         case 0:
     794             :             /* in postmaster child ... */
     795         720 :             InitPostmasterChild();
     796             : 
     797             :             /* Close the postmaster's sockets */
     798         720 :             ClosePostmasterPorts(false);
     799             : 
     800             :             /* Drop our connection to postmaster's shared memory, as well */
     801         720 :             dsm_detach_all();
     802         720 :             PGSharedMemoryDetach();
     803             : 
     804         720 :             PgstatCollectorMain(0, NULL);
     805             :             break;
     806             : #endif
     807             : 
     808         720 :         default:
     809         720 :             return (int) pgStatPid;
     810             :     }
     811             : 
     812             :     /* shouldn't get here */
     813             :     return 0;
     814             : }
     815             : 
     816             : void
     817           6 : allow_immediate_pgstat_restart(void)
     818             : {
     819           6 :     last_pgstat_start_time = 0;
     820           6 : }
     821             : 
     822             : /* ------------------------------------------------------------
     823             :  * Public functions used by backends follow
     824             :  *------------------------------------------------------------
     825             :  */
     826             : 
     827             : 
     828             : /* ----------
     829             :  * pgstat_report_stat() -
     830             :  *
     831             :  *  Must be called by processes that performs DML: tcop/postgres.c, logical
     832             :  *  receiver processes, SPI worker, etc. to send the so far collected
     833             :  *  per-table and function usage statistics to the collector.  Note that this
     834             :  *  is called only when not within a transaction, so it is fair to use
     835             :  *  transaction stop time as an approximation of current time.
     836             :  * ----------
     837             :  */
     838             : void
     839      411458 : pgstat_report_stat(bool force)
     840             : {
     841             :     /* we assume this inits to all zeroes: */
     842             :     static const PgStat_TableCounts all_zeroes;
     843             :     static TimestampTz last_report = 0;
     844             : 
     845             :     TimestampTz now;
     846             :     PgStat_MsgTabstat regular_msg;
     847             :     PgStat_MsgTabstat shared_msg;
     848             :     TabStatusArray *tsa;
     849             :     int         i;
     850             : 
     851             :     /* Don't expend a clock check if nothing to do */
     852      411458 :     if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
     853      181548 :         pgStatXactCommit == 0 && pgStatXactRollback == 0 &&
     854         546 :         !have_function_stats)
     855      391564 :         return;
     856             : 
     857             :     /*
     858             :      * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
     859             :      * msec since we last sent one, or the caller wants to force stats out.
     860             :      */
     861      410912 :     now = GetCurrentTransactionStopTimestamp();
     862      410912 :     if (!force &&
     863      401926 :         !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
     864      391018 :         return;
     865       19894 :     last_report = now;
     866             : 
     867             :     /*
     868             :      * Destroy pgStatTabHash before we start invalidating PgStat_TableEntry
     869             :      * entries it points to.  (Should we fail partway through the loop below,
     870             :      * it's okay to have removed the hashtable already --- the only
     871             :      * consequence is we'd get multiple entries for the same table in the
     872             :      * pgStatTabList, and that's safe.)
     873             :      */
     874       19894 :     if (pgStatTabHash)
     875       17974 :         hash_destroy(pgStatTabHash);
     876       19894 :     pgStatTabHash = NULL;
     877             : 
     878             :     /*
     879             :      * Scan through the TabStatusArray struct(s) to find tables that actually
     880             :      * have counts, and build messages to send.  We have to separate shared
     881             :      * relations from regular ones because the databaseid field in the message
     882             :      * header has to depend on that.
     883             :      */
     884       19894 :     regular_msg.m_databaseid = MyDatabaseId;
     885       19894 :     shared_msg.m_databaseid = InvalidOid;
     886       19894 :     regular_msg.m_nentries = 0;
     887       19894 :     shared_msg.m_nentries = 0;
     888             : 
     889       41574 :     for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
     890             :     {
     891      764796 :         for (i = 0; i < tsa->tsa_used; i++)
     892             :         {
     893      743116 :             PgStat_TableStatus *entry = &tsa->tsa_entries[i];
     894             :             PgStat_MsgTabstat *this_msg;
     895             :             PgStat_TableEntry *this_ent;
     896             : 
     897             :             /* Shouldn't have any pending transaction-dependent counts */
     898             :             Assert(entry->trans == NULL);
     899             : 
     900             :             /*
     901             :              * Ignore entries that didn't accumulate any actual counts, such
     902             :              * as indexes that were opened by the planner but not used.
     903             :              */
     904      743116 :             if (memcmp(&entry->t_counts, &all_zeroes,
     905             :                        sizeof(PgStat_TableCounts)) == 0)
     906      189672 :                 continue;
     907             : 
     908             :             /*
     909             :              * OK, insert data into the appropriate message, and send if full.
     910             :              */
     911      553444 :             this_msg = entry->t_shared ? &shared_msg : &regular_msg;
     912      553444 :             this_ent = &this_msg->m_entry[this_msg->m_nentries];
     913      553444 :             this_ent->t_id = entry->t_id;
     914      553444 :             memcpy(&this_ent->t_counts, &entry->t_counts,
     915             :                    sizeof(PgStat_TableCounts));
     916      553444 :             if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
     917             :             {
     918       55274 :                 pgstat_send_tabstat(this_msg);
     919       55274 :                 this_msg->m_nentries = 0;
     920             :             }
     921             :         }
     922             :         /* zero out PgStat_TableStatus structs after use */
     923       87860 :         MemSet(tsa->tsa_entries, 0,
     924             :                tsa->tsa_used * sizeof(PgStat_TableStatus));
     925       21680 :         tsa->tsa_used = 0;
     926             :     }
     927             : 
     928             :     /*
     929             :      * Send partial messages.  Make sure that any pending xact commit/abort
     930             :      * gets counted, even if there are no table stats to send.
     931             :      */
     932       19894 :     if (regular_msg.m_nentries > 0 ||
     933        3484 :         pgStatXactCommit > 0 || pgStatXactRollback > 0)
     934       18738 :         pgstat_send_tabstat(&regular_msg);
     935       19894 :     if (shared_msg.m_nentries > 0)
     936       11432 :         pgstat_send_tabstat(&shared_msg);
     937             : 
     938             :     /* Now, send function statistics */
     939       19894 :     pgstat_send_funcstats();
     940             : 
     941             :     /* Finally send SLRU statistics */
     942       19894 :     pgstat_send_slru();
     943             : }
     944             : 
     945             : /*
     946             :  * Subroutine for pgstat_report_stat: finish and send a tabstat message
     947             :  */
     948             : static void
     949       85444 : pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
     950             : {
     951             :     int         n;
     952             :     int         len;
     953             : 
     954             :     /* It's unlikely we'd get here with no socket, but maybe not impossible */
     955       85444 :     if (pgStatSock == PGINVALID_SOCKET)
     956        1490 :         return;
     957             : 
     958             :     /*
     959             :      * Report and reset accumulated xact commit/rollback and I/O timings
     960             :      * whenever we send a normal tabstat message
     961             :      */
     962       83954 :     if (OidIsValid(tsmsg->m_databaseid))
     963             :     {
     964       66862 :         tsmsg->m_xact_commit = pgStatXactCommit;
     965       66862 :         tsmsg->m_xact_rollback = pgStatXactRollback;
     966       66862 :         tsmsg->m_block_read_time = pgStatBlockReadTime;
     967       66862 :         tsmsg->m_block_write_time = pgStatBlockWriteTime;
     968       66862 :         pgStatXactCommit = 0;
     969       66862 :         pgStatXactRollback = 0;
     970       66862 :         pgStatBlockReadTime = 0;
     971       66862 :         pgStatBlockWriteTime = 0;
     972             :     }
     973             :     else
     974             :     {
     975       17092 :         tsmsg->m_xact_commit = 0;
     976       17092 :         tsmsg->m_xact_rollback = 0;
     977       17092 :         tsmsg->m_block_read_time = 0;
     978       17092 :         tsmsg->m_block_write_time = 0;
     979             :     }
     980             : 
     981       83954 :     n = tsmsg->m_nentries;
     982       83954 :     len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
     983             :         n * sizeof(PgStat_TableEntry);
     984             : 
     985       83954 :     pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
     986       83954 :     pgstat_send(tsmsg, len);
     987             : }
     988             : 
     989             : /*
     990             :  * Subroutine for pgstat_report_stat: populate and send a function stat message
     991             :  */
     992             : static void
     993       19894 : pgstat_send_funcstats(void)
     994             : {
     995             :     /* we assume this inits to all zeroes: */
     996             :     static const PgStat_FunctionCounts all_zeroes;
     997             : 
     998             :     PgStat_MsgFuncstat msg;
     999             :     PgStat_BackendFunctionEntry *entry;
    1000             :     HASH_SEQ_STATUS fstat;
    1001             : 
    1002       19894 :     if (pgStatFunctions == NULL)
    1003       19894 :         return;
    1004             : 
    1005           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
    1006           0 :     msg.m_databaseid = MyDatabaseId;
    1007           0 :     msg.m_nentries = 0;
    1008             : 
    1009           0 :     hash_seq_init(&fstat, pgStatFunctions);
    1010           0 :     while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
    1011             :     {
    1012             :         PgStat_FunctionEntry *m_ent;
    1013             : 
    1014             :         /* Skip it if no counts accumulated since last time */
    1015           0 :         if (memcmp(&entry->f_counts, &all_zeroes,
    1016             :                    sizeof(PgStat_FunctionCounts)) == 0)
    1017           0 :             continue;
    1018             : 
    1019             :         /* need to convert format of time accumulators */
    1020           0 :         m_ent = &msg.m_entry[msg.m_nentries];
    1021           0 :         m_ent->f_id = entry->f_id;
    1022           0 :         m_ent->f_numcalls = entry->f_counts.f_numcalls;
    1023           0 :         m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
    1024           0 :         m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
    1025             : 
    1026           0 :         if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
    1027             :         {
    1028           0 :             pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
    1029           0 :                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
    1030           0 :             msg.m_nentries = 0;
    1031             :         }
    1032             : 
    1033             :         /* reset the entry's counts */
    1034           0 :         MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
    1035             :     }
    1036             : 
    1037           0 :     if (msg.m_nentries > 0)
    1038           0 :         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
    1039           0 :                     msg.m_nentries * sizeof(PgStat_FunctionEntry));
    1040             : 
    1041           0 :     have_function_stats = false;
    1042             : }
    1043             : 
    1044             : 
    1045             : /* ----------
    1046             :  * pgstat_vacuum_stat() -
    1047             :  *
    1048             :  *  Will tell the collector about objects he can get rid of.
    1049             :  * ----------
    1050             :  */
    1051             : void
    1052        4006 : pgstat_vacuum_stat(void)
    1053             : {
    1054             :     HTAB       *htab;
    1055             :     PgStat_MsgTabpurge msg;
    1056             :     PgStat_MsgFuncpurge f_msg;
    1057             :     HASH_SEQ_STATUS hstat;
    1058             :     PgStat_StatDBEntry *dbentry;
    1059             :     PgStat_StatTabEntry *tabentry;
    1060             :     PgStat_StatFuncEntry *funcentry;
    1061             :     int         len;
    1062             : 
    1063        4006 :     if (pgStatSock == PGINVALID_SOCKET)
    1064        1914 :         return;
    1065             : 
    1066             :     /*
    1067             :      * If not done for this transaction, read the statistics collector stats
    1068             :      * file into some hash tables.
    1069             :      */
    1070        2574 :     backend_read_statsfile();
    1071             : 
    1072             :     /*
    1073             :      * Read pg_database and make a list of OIDs of all existing databases
    1074             :      */
    1075        2574 :     htab = pgstat_collect_oids(DatabaseRelationId, Anum_pg_database_oid);
    1076             : 
    1077             :     /*
    1078             :      * Search the database hash table for dead databases and tell the
    1079             :      * collector to drop them.
    1080             :      */
    1081        2574 :     hash_seq_init(&hstat, pgStatDBHash);
    1082        7952 :     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
    1083             :     {
    1084        5378 :         Oid         dbid = dbentry->databaseid;
    1085             : 
    1086        5378 :         CHECK_FOR_INTERRUPTS();
    1087             : 
    1088             :         /* the DB entry for shared tables (with InvalidOid) is never dropped */
    1089        8664 :         if (OidIsValid(dbid) &&
    1090        3286 :             hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
    1091           0 :             pgstat_drop_database(dbid);
    1092             :     }
    1093             : 
    1094             :     /* Clean up */
    1095        2574 :     hash_destroy(htab);
    1096             : 
    1097             :     /*
    1098             :      * Lookup our own database entry; if not found, nothing more to do.
    1099             :      */
    1100        2574 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    1101             :                                                  (void *) &MyDatabaseId,
    1102             :                                                  HASH_FIND, NULL);
    1103        2574 :     if (dbentry == NULL || dbentry->tables == NULL)
    1104         482 :         return;
    1105             : 
    1106             :     /*
    1107             :      * Similarly to above, make a list of all known relations in this DB.
    1108             :      */
    1109        2092 :     htab = pgstat_collect_oids(RelationRelationId, Anum_pg_class_oid);
    1110             : 
    1111             :     /*
    1112             :      * Initialize our messages table counter to zero
    1113             :      */
    1114        2092 :     msg.m_nentries = 0;
    1115             : 
    1116             :     /*
    1117             :      * Check for all tables listed in stats hashtable if they still exist.
    1118             :      */
    1119        2092 :     hash_seq_init(&hstat, dbentry->tables);
    1120      480424 :     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
    1121             :     {
    1122      478332 :         Oid         tabid = tabentry->tableid;
    1123             : 
    1124      478332 :         CHECK_FOR_INTERRUPTS();
    1125             : 
    1126      478332 :         if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
    1127      395256 :             continue;
    1128             : 
    1129             :         /*
    1130             :          * Not there, so add this table's Oid to the message
    1131             :          */
    1132       83076 :         msg.m_tableid[msg.m_nentries++] = tabid;
    1133             : 
    1134             :         /*
    1135             :          * If the message is full, send it out and reinitialize to empty
    1136             :          */
    1137       83076 :         if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
    1138             :         {
    1139         194 :             len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
    1140         194 :                 + msg.m_nentries * sizeof(Oid);
    1141             : 
    1142         194 :             pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1143         194 :             msg.m_databaseid = MyDatabaseId;
    1144         194 :             pgstat_send(&msg, len);
    1145             : 
    1146         194 :             msg.m_nentries = 0;
    1147             :         }
    1148             :     }
    1149             : 
    1150             :     /*
    1151             :      * Send the rest
    1152             :      */
    1153        2092 :     if (msg.m_nentries > 0)
    1154             :     {
    1155         608 :         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
    1156         608 :             + msg.m_nentries * sizeof(Oid);
    1157             : 
    1158         608 :         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1159         608 :         msg.m_databaseid = MyDatabaseId;
    1160         608 :         pgstat_send(&msg, len);
    1161             :     }
    1162             : 
    1163             :     /* Clean up */
    1164        2092 :     hash_destroy(htab);
    1165             : 
    1166             :     /*
    1167             :      * Now repeat the above steps for functions.  However, we needn't bother
    1168             :      * in the common case where no function stats are being collected.
    1169             :      */
    1170        4184 :     if (dbentry->functions != NULL &&
    1171        2092 :         hash_get_num_entries(dbentry->functions) > 0)
    1172             :     {
    1173           0 :         htab = pgstat_collect_oids(ProcedureRelationId, Anum_pg_proc_oid);
    1174             : 
    1175           0 :         pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
    1176           0 :         f_msg.m_databaseid = MyDatabaseId;
    1177           0 :         f_msg.m_nentries = 0;
    1178             : 
    1179           0 :         hash_seq_init(&hstat, dbentry->functions);
    1180           0 :         while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
    1181             :         {
    1182           0 :             Oid         funcid = funcentry->functionid;
    1183             : 
    1184           0 :             CHECK_FOR_INTERRUPTS();
    1185             : 
    1186           0 :             if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
    1187           0 :                 continue;
    1188             : 
    1189             :             /*
    1190             :              * Not there, so add this function's Oid to the message
    1191             :              */
    1192           0 :             f_msg.m_functionid[f_msg.m_nentries++] = funcid;
    1193             : 
    1194             :             /*
    1195             :              * If the message is full, send it out and reinitialize to empty
    1196             :              */
    1197           0 :             if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
    1198             :             {
    1199           0 :                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
    1200           0 :                     + f_msg.m_nentries * sizeof(Oid);
    1201             : 
    1202           0 :                 pgstat_send(&f_msg, len);
    1203             : 
    1204           0 :                 f_msg.m_nentries = 0;
    1205             :             }
    1206             :         }
    1207             : 
    1208             :         /*
    1209             :          * Send the rest
    1210             :          */
    1211           0 :         if (f_msg.m_nentries > 0)
    1212             :         {
    1213           0 :             len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
    1214           0 :                 + f_msg.m_nentries * sizeof(Oid);
    1215             : 
    1216           0 :             pgstat_send(&f_msg, len);
    1217             :         }
    1218             : 
    1219           0 :         hash_destroy(htab);
    1220             :     }
    1221             : }
    1222             : 
    1223             : 
    1224             : /* ----------
    1225             :  * pgstat_collect_oids() -
    1226             :  *
    1227             :  *  Collect the OIDs of all objects listed in the specified system catalog
    1228             :  *  into a temporary hash table.  Caller should hash_destroy the result
    1229             :  *  when done with it.  (However, we make the table in CurrentMemoryContext
    1230             :  *  so that it will be freed properly in event of an error.)
    1231             :  * ----------
    1232             :  */
    1233             : static HTAB *
    1234        4666 : pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid)
    1235             : {
    1236             :     HTAB       *htab;
    1237             :     HASHCTL     hash_ctl;
    1238             :     Relation    rel;
    1239             :     TableScanDesc scan;
    1240             :     HeapTuple   tup;
    1241             :     Snapshot    snapshot;
    1242             : 
    1243        4666 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    1244        4666 :     hash_ctl.keysize = sizeof(Oid);
    1245        4666 :     hash_ctl.entrysize = sizeof(Oid);
    1246        4666 :     hash_ctl.hcxt = CurrentMemoryContext;
    1247        4666 :     htab = hash_create("Temporary table of OIDs",
    1248             :                        PGSTAT_TAB_HASH_SIZE,
    1249             :                        &hash_ctl,
    1250             :                        HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    1251             : 
    1252        4666 :     rel = table_open(catalogid, AccessShareLock);
    1253        4666 :     snapshot = RegisterSnapshot(GetLatestSnapshot());
    1254        4666 :     scan = table_beginscan(rel, snapshot, 0, NULL);
    1255      984822 :     while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
    1256             :     {
    1257             :         Oid         thisoid;
    1258             :         bool        isnull;
    1259             : 
    1260      980156 :         thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
    1261             :         Assert(!isnull);
    1262             : 
    1263      980156 :         CHECK_FOR_INTERRUPTS();
    1264             : 
    1265      980156 :         (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
    1266             :     }
    1267        4666 :     table_endscan(scan);
    1268        4666 :     UnregisterSnapshot(snapshot);
    1269        4666 :     table_close(rel, AccessShareLock);
    1270             : 
    1271        4666 :     return htab;
    1272             : }
    1273             : 
    1274             : 
    1275             : /* ----------
    1276             :  * pgstat_drop_database() -
    1277             :  *
    1278             :  *  Tell the collector that we just dropped a database.
    1279             :  *  (If the message gets lost, we will still clean the dead DB eventually
    1280             :  *  via future invocations of pgstat_vacuum_stat().)
    1281             :  * ----------
    1282             :  */
    1283             : void
    1284          18 : pgstat_drop_database(Oid databaseid)
    1285             : {
    1286             :     PgStat_MsgDropdb msg;
    1287             : 
    1288          18 :     if (pgStatSock == PGINVALID_SOCKET)
    1289           0 :         return;
    1290             : 
    1291          18 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
    1292          18 :     msg.m_databaseid = databaseid;
    1293          18 :     pgstat_send(&msg, sizeof(msg));
    1294             : }
    1295             : 
    1296             : 
    1297             : /* ----------
    1298             :  * pgstat_drop_relation() -
    1299             :  *
    1300             :  *  Tell the collector that we just dropped a relation.
    1301             :  *  (If the message gets lost, we will still clean the dead entry eventually
    1302             :  *  via future invocations of pgstat_vacuum_stat().)
    1303             :  *
    1304             :  *  Currently not used for lack of any good place to call it; we rely
    1305             :  *  entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
    1306             :  * ----------
    1307             :  */
    1308             : #ifdef NOT_USED
    1309             : void
    1310             : pgstat_drop_relation(Oid relid)
    1311             : {
    1312             :     PgStat_MsgTabpurge msg;
    1313             :     int         len;
    1314             : 
    1315             :     if (pgStatSock == PGINVALID_SOCKET)
    1316             :         return;
    1317             : 
    1318             :     msg.m_tableid[0] = relid;
    1319             :     msg.m_nentries = 1;
    1320             : 
    1321             :     len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) + sizeof(Oid);
    1322             : 
    1323             :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
    1324             :     msg.m_databaseid = MyDatabaseId;
    1325             :     pgstat_send(&msg, len);
    1326             : }
    1327             : #endif                          /* NOT_USED */
    1328             : 
    1329             : 
    1330             : /* ----------
    1331             :  * pgstat_reset_counters() -
    1332             :  *
    1333             :  *  Tell the statistics collector to reset counters for our database.
    1334             :  *
    1335             :  *  Permission checking for this function is managed through the normal
    1336             :  *  GRANT system.
    1337             :  * ----------
    1338             :  */
    1339             : void
    1340           0 : pgstat_reset_counters(void)
    1341             : {
    1342             :     PgStat_MsgResetcounter msg;
    1343             : 
    1344           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1345           0 :         return;
    1346             : 
    1347           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
    1348           0 :     msg.m_databaseid = MyDatabaseId;
    1349           0 :     pgstat_send(&msg, sizeof(msg));
    1350             : }
    1351             : 
    1352             : /* ----------
    1353             :  * pgstat_reset_shared_counters() -
    1354             :  *
    1355             :  *  Tell the statistics collector to reset cluster-wide shared counters.
    1356             :  *
    1357             :  *  Permission checking for this function is managed through the normal
    1358             :  *  GRANT system.
    1359             :  * ----------
    1360             :  */
    1361             : void
    1362           0 : pgstat_reset_shared_counters(const char *target)
    1363             : {
    1364             :     PgStat_MsgResetsharedcounter msg;
    1365             : 
    1366           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1367           0 :         return;
    1368             : 
    1369           0 :     if (strcmp(target, "archiver") == 0)
    1370           0 :         msg.m_resettarget = RESET_ARCHIVER;
    1371           0 :     else if (strcmp(target, "bgwriter") == 0)
    1372           0 :         msg.m_resettarget = RESET_BGWRITER;
    1373             :     else
    1374           0 :         ereport(ERROR,
    1375             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1376             :                  errmsg("unrecognized reset target: \"%s\"", target),
    1377             :                  errhint("Target must be \"archiver\" or \"bgwriter\".")));
    1378             : 
    1379           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
    1380           0 :     pgstat_send(&msg, sizeof(msg));
    1381             : }
    1382             : 
    1383             : /* ----------
    1384             :  * pgstat_reset_single_counter() -
    1385             :  *
    1386             :  *  Tell the statistics collector to reset a single counter.
    1387             :  *
    1388             :  *  Permission checking for this function is managed through the normal
    1389             :  *  GRANT system.
    1390             :  * ----------
    1391             :  */
    1392             : void
    1393           0 : pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
    1394             : {
    1395             :     PgStat_MsgResetsinglecounter msg;
    1396             : 
    1397           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1398           0 :         return;
    1399             : 
    1400           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
    1401           0 :     msg.m_databaseid = MyDatabaseId;
    1402           0 :     msg.m_resettype = type;
    1403           0 :     msg.m_objectid = objoid;
    1404             : 
    1405           0 :     pgstat_send(&msg, sizeof(msg));
    1406             : }
    1407             : 
    1408             : /* ----------
    1409             :  * pgstat_reset_slru_counter() -
    1410             :  *
    1411             :  *  Tell the statistics collector to reset a single SLRU counter, or all
    1412             :  *  SLRU counters (when name is null).
    1413             :  *
    1414             :  *  Permission checking for this function is managed through the normal
    1415             :  *  GRANT system.
    1416             :  * ----------
    1417             :  */
    1418             : void
    1419           0 : pgstat_reset_slru_counter(const char *name)
    1420             : {
    1421             :     PgStat_MsgResetslrucounter msg;
    1422             : 
    1423           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1424           0 :         return;
    1425             : 
    1426           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSLRUCOUNTER);
    1427           0 :     msg.m_index = (name) ? pgstat_slru_index(name) : -1;
    1428             : 
    1429           0 :     pgstat_send(&msg, sizeof(msg));
    1430             : }
    1431             : 
    1432             : /* ----------
    1433             :  * pgstat_report_autovac() -
    1434             :  *
    1435             :  *  Called from autovacuum.c to report startup of an autovacuum process.
    1436             :  *  We are called before InitPostgres is done, so can't rely on MyDatabaseId;
    1437             :  *  the db OID must be passed in, instead.
    1438             :  * ----------
    1439             :  */
    1440             : void
    1441          60 : pgstat_report_autovac(Oid dboid)
    1442             : {
    1443             :     PgStat_MsgAutovacStart msg;
    1444             : 
    1445          60 :     if (pgStatSock == PGINVALID_SOCKET)
    1446           0 :         return;
    1447             : 
    1448          60 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
    1449          60 :     msg.m_databaseid = dboid;
    1450          60 :     msg.m_start_time = GetCurrentTimestamp();
    1451             : 
    1452          60 :     pgstat_send(&msg, sizeof(msg));
    1453             : }
    1454             : 
    1455             : 
    1456             : /* ---------
    1457             :  * pgstat_report_vacuum() -
    1458             :  *
    1459             :  *  Tell the collector about the table we just vacuumed.
    1460             :  * ---------
    1461             :  */
    1462             : void
    1463       43424 : pgstat_report_vacuum(Oid tableoid, bool shared,
    1464             :                      PgStat_Counter livetuples, PgStat_Counter deadtuples)
    1465             : {
    1466             :     PgStat_MsgVacuum msg;
    1467             : 
    1468       43424 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1469       38664 :         return;
    1470             : 
    1471        4760 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
    1472        4760 :     msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
    1473        4760 :     msg.m_tableoid = tableoid;
    1474        4760 :     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
    1475        4760 :     msg.m_vacuumtime = GetCurrentTimestamp();
    1476        4760 :     msg.m_live_tuples = livetuples;
    1477        4760 :     msg.m_dead_tuples = deadtuples;
    1478        4760 :     pgstat_send(&msg, sizeof(msg));
    1479             : }
    1480             : 
    1481             : /* --------
    1482             :  * pgstat_report_analyze() -
    1483             :  *
    1484             :  *  Tell the collector about the table we just analyzed.
    1485             :  *
    1486             :  * Caller must provide new live- and dead-tuples estimates, as well as a
    1487             :  * flag indicating whether to reset the changes_since_analyze counter.
    1488             :  * --------
    1489             :  */
    1490             : void
    1491       33248 : pgstat_report_analyze(Relation rel,
    1492             :                       PgStat_Counter livetuples, PgStat_Counter deadtuples,
    1493             :                       bool resetcounter)
    1494             : {
    1495             :     PgStat_MsgAnalyze msg;
    1496             : 
    1497       33248 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1498       23270 :         return;
    1499             : 
    1500             :     /*
    1501             :      * Unlike VACUUM, ANALYZE might be running inside a transaction that has
    1502             :      * already inserted and/or deleted rows in the target table. ANALYZE will
    1503             :      * have counted such rows as live or dead respectively. Because we will
    1504             :      * report our counts of such rows at transaction end, we should subtract
    1505             :      * off these counts from what we send to the collector now, else they'll
    1506             :      * be double-counted after commit.  (This approach also ensures that the
    1507             :      * collector ends up with the right numbers if we abort instead of
    1508             :      * committing.)
    1509             :      */
    1510        9978 :     if (rel->pgstat_info != NULL)
    1511             :     {
    1512             :         PgStat_TableXactStatus *trans;
    1513             : 
    1514       10008 :         for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
    1515             :         {
    1516          62 :             livetuples -= trans->tuples_inserted - trans->tuples_deleted;
    1517          62 :             deadtuples -= trans->tuples_updated + trans->tuples_deleted;
    1518             :         }
    1519             :         /* count stuff inserted by already-aborted subxacts, too */
    1520        9946 :         deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
    1521             :         /* Since ANALYZE's counts are estimates, we could have underflowed */
    1522        9946 :         livetuples = Max(livetuples, 0);
    1523        9946 :         deadtuples = Max(deadtuples, 0);
    1524             :     }
    1525             : 
    1526        9978 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
    1527        9978 :     msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
    1528        9978 :     msg.m_tableoid = RelationGetRelid(rel);
    1529        9978 :     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
    1530        9978 :     msg.m_resetcounter = resetcounter;
    1531        9978 :     msg.m_analyzetime = GetCurrentTimestamp();
    1532        9978 :     msg.m_live_tuples = livetuples;
    1533        9978 :     msg.m_dead_tuples = deadtuples;
    1534        9978 :     pgstat_send(&msg, sizeof(msg));
    1535             : }
    1536             : 
    1537             : /* --------
    1538             :  * pgstat_report_recovery_conflict() -
    1539             :  *
    1540             :  *  Tell the collector about a Hot Standby recovery conflict.
    1541             :  * --------
    1542             :  */
    1543             : void
    1544           0 : pgstat_report_recovery_conflict(int reason)
    1545             : {
    1546             :     PgStat_MsgRecoveryConflict msg;
    1547             : 
    1548           0 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1549           0 :         return;
    1550             : 
    1551           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
    1552           0 :     msg.m_databaseid = MyDatabaseId;
    1553           0 :     msg.m_reason = reason;
    1554           0 :     pgstat_send(&msg, sizeof(msg));
    1555             : }
    1556             : 
    1557             : /* --------
    1558             :  * pgstat_report_deadlock() -
    1559             :  *
    1560             :  *  Tell the collector about a deadlock detected.
    1561             :  * --------
    1562             :  */
    1563             : void
    1564           4 : pgstat_report_deadlock(void)
    1565             : {
    1566             :     PgStat_MsgDeadlock msg;
    1567             : 
    1568           4 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1569           0 :         return;
    1570             : 
    1571           4 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
    1572           4 :     msg.m_databaseid = MyDatabaseId;
    1573           4 :     pgstat_send(&msg, sizeof(msg));
    1574             : }
    1575             : 
    1576             : 
    1577             : 
    1578             : /* --------
    1579             :  * pgstat_report_checksum_failures_in_db() -
    1580             :  *
    1581             :  *  Tell the collector about one or more checksum failures.
    1582             :  * --------
    1583             :  */
    1584             : void
    1585           4 : pgstat_report_checksum_failures_in_db(Oid dboid, int failurecount)
    1586             : {
    1587             :     PgStat_MsgChecksumFailure msg;
    1588             : 
    1589           4 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1590           0 :         return;
    1591             : 
    1592           4 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_CHECKSUMFAILURE);
    1593           4 :     msg.m_databaseid = dboid;
    1594           4 :     msg.m_failurecount = failurecount;
    1595           4 :     msg.m_failure_time = GetCurrentTimestamp();
    1596             : 
    1597           4 :     pgstat_send(&msg, sizeof(msg));
    1598             : }
    1599             : 
    1600             : /* --------
    1601             :  * pgstat_report_checksum_failure() -
    1602             :  *
    1603             :  *  Tell the collector about a checksum failure.
    1604             :  * --------
    1605             :  */
    1606             : void
    1607           0 : pgstat_report_checksum_failure(void)
    1608             : {
    1609           0 :     pgstat_report_checksum_failures_in_db(MyDatabaseId, 1);
    1610           0 : }
    1611             : 
    1612             : /* --------
    1613             :  * pgstat_report_tempfile() -
    1614             :  *
    1615             :  *  Tell the collector about a temporary file.
    1616             :  * --------
    1617             :  */
    1618             : void
    1619        3632 : pgstat_report_tempfile(size_t filesize)
    1620             : {
    1621             :     PgStat_MsgTempFile msg;
    1622             : 
    1623        3632 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1624           0 :         return;
    1625             : 
    1626        3632 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
    1627        3632 :     msg.m_databaseid = MyDatabaseId;
    1628        3632 :     msg.m_filesize = filesize;
    1629        3632 :     pgstat_send(&msg, sizeof(msg));
    1630             : }
    1631             : 
    1632             : 
    1633             : /* ----------
    1634             :  * pgstat_ping() -
    1635             :  *
    1636             :  *  Send some junk data to the collector to increase traffic.
    1637             :  * ----------
    1638             :  */
    1639             : void
    1640           0 : pgstat_ping(void)
    1641             : {
    1642             :     PgStat_MsgDummy msg;
    1643             : 
    1644           0 :     if (pgStatSock == PGINVALID_SOCKET)
    1645           0 :         return;
    1646             : 
    1647           0 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
    1648           0 :     pgstat_send(&msg, sizeof(msg));
    1649             : }
    1650             : 
    1651             : /* ----------
    1652             :  * pgstat_send_inquiry() -
    1653             :  *
    1654             :  *  Notify collector that we need fresh data.
    1655             :  * ----------
    1656             :  */
    1657             : static void
    1658         912 : pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
    1659             : {
    1660             :     PgStat_MsgInquiry msg;
    1661             : 
    1662         912 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
    1663         912 :     msg.clock_time = clock_time;
    1664         912 :     msg.cutoff_time = cutoff_time;
    1665         912 :     msg.databaseid = databaseid;
    1666         912 :     pgstat_send(&msg, sizeof(msg));
    1667         912 : }
    1668             : 
    1669             : 
    1670             : /*
    1671             :  * Initialize function call usage data.
    1672             :  * Called by the executor before invoking a function.
    1673             :  */
    1674             : void
    1675    15106252 : pgstat_init_function_usage(FunctionCallInfo fcinfo,
    1676             :                            PgStat_FunctionCallUsage *fcu)
    1677             : {
    1678             :     PgStat_BackendFunctionEntry *htabent;
    1679             :     bool        found;
    1680             : 
    1681    15106252 :     if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
    1682             :     {
    1683             :         /* stats not wanted */
    1684    15106252 :         fcu->fs = NULL;
    1685    15106252 :         return;
    1686             :     }
    1687             : 
    1688           0 :     if (!pgStatFunctions)
    1689             :     {
    1690             :         /* First time through - initialize function stat table */
    1691             :         HASHCTL     hash_ctl;
    1692             : 
    1693           0 :         memset(&hash_ctl, 0, sizeof(hash_ctl));
    1694           0 :         hash_ctl.keysize = sizeof(Oid);
    1695           0 :         hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
    1696           0 :         pgStatFunctions = hash_create("Function stat entries",
    1697             :                                       PGSTAT_FUNCTION_HASH_SIZE,
    1698             :                                       &hash_ctl,
    1699             :                                       HASH_ELEM | HASH_BLOBS);
    1700             :     }
    1701             : 
    1702             :     /* Get the stats entry for this function, create if necessary */
    1703           0 :     htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
    1704             :                           HASH_ENTER, &found);
    1705           0 :     if (!found)
    1706           0 :         MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
    1707             : 
    1708           0 :     fcu->fs = &htabent->f_counts;
    1709             : 
    1710             :     /* save stats for this function, later used to compensate for recursion */
    1711           0 :     fcu->save_f_total_time = htabent->f_counts.f_total_time;
    1712             : 
    1713             :     /* save current backend-wide total time */
    1714           0 :     fcu->save_total = total_func_time;
    1715             : 
    1716             :     /* get clock time as of function start */
    1717           0 :     INSTR_TIME_SET_CURRENT(fcu->f_start);
    1718             : }
    1719             : 
    1720             : /*
    1721             :  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
    1722             :  *      for specified function
    1723             :  *
    1724             :  * If no entry, return NULL, don't create a new one
    1725             :  */
    1726             : PgStat_BackendFunctionEntry *
    1727           0 : find_funcstat_entry(Oid func_id)
    1728             : {
    1729           0 :     if (pgStatFunctions == NULL)
    1730           0 :         return NULL;
    1731             : 
    1732           0 :     return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
    1733             :                                                        (void *) &func_id,
    1734             :                                                        HASH_FIND, NULL);
    1735             : }
    1736             : 
    1737             : /*
    1738             :  * Calculate function call usage and update stat counters.
    1739             :  * Called by the executor after invoking a function.
    1740             :  *
    1741             :  * In the case of a set-returning function that runs in value-per-call mode,
    1742             :  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
    1743             :  * calls for what the user considers a single call of the function.  The
    1744             :  * finalize flag should be TRUE on the last call.
    1745             :  */
    1746             : void
    1747    15104584 : pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
    1748             : {
    1749    15104584 :     PgStat_FunctionCounts *fs = fcu->fs;
    1750             :     instr_time  f_total;
    1751             :     instr_time  f_others;
    1752             :     instr_time  f_self;
    1753             : 
    1754             :     /* stats not wanted? */
    1755    15104584 :     if (fs == NULL)
    1756    15104584 :         return;
    1757             : 
    1758             :     /* total elapsed time in this function call */
    1759           0 :     INSTR_TIME_SET_CURRENT(f_total);
    1760           0 :     INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
    1761             : 
    1762             :     /* self usage: elapsed minus anything already charged to other calls */
    1763           0 :     f_others = total_func_time;
    1764           0 :     INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
    1765           0 :     f_self = f_total;
    1766           0 :     INSTR_TIME_SUBTRACT(f_self, f_others);
    1767             : 
    1768             :     /* update backend-wide total time */
    1769           0 :     INSTR_TIME_ADD(total_func_time, f_self);
    1770             : 
    1771             :     /*
    1772             :      * Compute the new f_total_time as the total elapsed time added to the
    1773             :      * pre-call value of f_total_time.  This is necessary to avoid
    1774             :      * double-counting any time taken by recursive calls of myself.  (We do
    1775             :      * not need any similar kluge for self time, since that already excludes
    1776             :      * any recursive calls.)
    1777             :      */
    1778           0 :     INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
    1779             : 
    1780             :     /* update counters in function stats table */
    1781           0 :     if (finalize)
    1782           0 :         fs->f_numcalls++;
    1783           0 :     fs->f_total_time = f_total;
    1784           0 :     INSTR_TIME_ADD(fs->f_self_time, f_self);
    1785             : 
    1786             :     /* indicate that we have something to send */
    1787           0 :     have_function_stats = true;
    1788             : }
    1789             : 
    1790             : 
    1791             : /* ----------
    1792             :  * pgstat_initstats() -
    1793             :  *
    1794             :  *  Initialize a relcache entry to count access statistics.
    1795             :  *  Called whenever a relation is opened.
    1796             :  *
    1797             :  *  We assume that a relcache entry's pgstat_info field is zeroed by
    1798             :  *  relcache.c when the relcache entry is made; thereafter it is long-lived
    1799             :  *  data.  We can avoid repeated searches of the TabStatus arrays when the
    1800             :  *  same relation is touched repeatedly within a transaction.
    1801             :  * ----------
    1802             :  */
    1803             : void
    1804    29806464 : pgstat_initstats(Relation rel)
    1805             : {
    1806    29806464 :     Oid         rel_id = rel->rd_id;
    1807    29806464 :     char        relkind = rel->rd_rel->relkind;
    1808             : 
    1809             :     /* We only count stats for things that have storage */
    1810    30326966 :     if (!(relkind == RELKIND_RELATION ||
    1811    16400872 :           relkind == RELKIND_MATVIEW ||
    1812      680144 :           relkind == RELKIND_INDEX ||
    1813             :           relkind == RELKIND_TOASTVALUE ||
    1814             :           relkind == RELKIND_SEQUENCE))
    1815             :     {
    1816      374022 :         rel->pgstat_info = NULL;
    1817      374022 :         return;
    1818             :     }
    1819             : 
    1820    29432442 :     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
    1821             :     {
    1822             :         /* We're not counting at all */
    1823    13415878 :         rel->pgstat_info = NULL;
    1824    13415878 :         return;
    1825             :     }
    1826             : 
    1827             :     /*
    1828             :      * If we already set up this relation in the current transaction, nothing
    1829             :      * to do.
    1830             :      */
    1831    16016564 :     if (rel->pgstat_info != NULL &&
    1832    15332572 :         rel->pgstat_info->t_id == rel_id)
    1833    15185490 :         return;
    1834             : 
    1835             :     /* Else find or make the PgStat_TableStatus entry, and update link */
    1836      831074 :     rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
    1837             : }
    1838             : 
    1839             : /*
    1840             :  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
    1841             :  */
    1842             : static PgStat_TableStatus *
    1843      831214 : get_tabstat_entry(Oid rel_id, bool isshared)
    1844             : {
    1845             :     TabStatHashEntry *hash_entry;
    1846             :     PgStat_TableStatus *entry;
    1847             :     TabStatusArray *tsa;
    1848             :     bool        found;
    1849             : 
    1850             :     /*
    1851             :      * Create hash table if we don't have it already.
    1852             :      */
    1853      831214 :     if (pgStatTabHash == NULL)
    1854             :     {
    1855             :         HASHCTL     ctl;
    1856             : 
    1857       18766 :         memset(&ctl, 0, sizeof(ctl));
    1858       18766 :         ctl.keysize = sizeof(Oid);
    1859       18766 :         ctl.entrysize = sizeof(TabStatHashEntry);
    1860             : 
    1861       18766 :         pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
    1862             :                                     TABSTAT_QUANTUM,
    1863             :                                     &ctl,
    1864             :                                     HASH_ELEM | HASH_BLOBS);
    1865             :     }
    1866             : 
    1867             :     /*
    1868             :      * Find an entry or create a new one.
    1869             :      */
    1870      831214 :     hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
    1871      831214 :     if (!found)
    1872             :     {
    1873             :         /* initialize new entry with null pointer */
    1874      744014 :         hash_entry->tsa_entry = NULL;
    1875             :     }
    1876             : 
    1877             :     /*
    1878             :      * If entry is already valid, we're done.
    1879             :      */
    1880      831214 :     if (hash_entry->tsa_entry)
    1881       87200 :         return hash_entry->tsa_entry;
    1882             : 
    1883             :     /*
    1884             :      * Locate the first pgStatTabList entry with free space, making a new list
    1885             :      * entry if needed.  Note that we could get an OOM failure here, but if so
    1886             :      * we have left the hashtable and the list in a consistent state.
    1887             :      */
    1888      744014 :     if (pgStatTabList == NULL)
    1889             :     {
    1890             :         /* Set up first pgStatTabList entry */
    1891       10324 :         pgStatTabList = (TabStatusArray *)
    1892       10324 :             MemoryContextAllocZero(TopMemoryContext,
    1893             :                                    sizeof(TabStatusArray));
    1894             :     }
    1895             : 
    1896      744014 :     tsa = pgStatTabList;
    1897      862558 :     while (tsa->tsa_used >= TABSTAT_QUANTUM)
    1898             :     {
    1899      118544 :         if (tsa->tsa_next == NULL)
    1900        1752 :             tsa->tsa_next = (TabStatusArray *)
    1901        1752 :                 MemoryContextAllocZero(TopMemoryContext,
    1902             :                                        sizeof(TabStatusArray));
    1903      118544 :         tsa = tsa->tsa_next;
    1904             :     }
    1905             : 
    1906             :     /*
    1907             :      * Allocate a PgStat_TableStatus entry within this list entry.  We assume
    1908             :      * the entry was already zeroed, either at creation or after last use.
    1909             :      */
    1910      744014 :     entry = &tsa->tsa_entries[tsa->tsa_used++];
    1911      744014 :     entry->t_id = rel_id;
    1912      744014 :     entry->t_shared = isshared;
    1913             : 
    1914             :     /*
    1915             :      * Now we can fill the entry in pgStatTabHash.
    1916             :      */
    1917      744014 :     hash_entry->tsa_entry = entry;
    1918             : 
    1919      744014 :     return entry;
    1920             : }
    1921             : 
    1922             : /*
    1923             :  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
    1924             :  *
    1925             :  * If no entry, return NULL, don't create a new one
    1926             :  *
    1927             :  * Note: if we got an error in the most recent execution of pgstat_report_stat,
    1928             :  * it's possible that an entry exists but there's no hashtable entry for it.
    1929             :  * That's okay, we'll treat this case as "doesn't exist".
    1930             :  */
    1931             : PgStat_TableStatus *
    1932           0 : find_tabstat_entry(Oid rel_id)
    1933             : {
    1934             :     TabStatHashEntry *hash_entry;
    1935             : 
    1936             :     /* If hashtable doesn't exist, there are no entries at all */
    1937           0 :     if (!pgStatTabHash)
    1938           0 :         return NULL;
    1939             : 
    1940           0 :     hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
    1941           0 :     if (!hash_entry)
    1942           0 :         return NULL;
    1943             : 
    1944             :     /* Note that this step could also return NULL, but that's correct */
    1945           0 :     return hash_entry->tsa_entry;
    1946             : }
    1947             : 
    1948             : /*
    1949             :  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
    1950             :  */
    1951             : static PgStat_SubXactStatus *
    1952      274366 : get_tabstat_stack_level(int nest_level)
    1953             : {
    1954             :     PgStat_SubXactStatus *xact_state;
    1955             : 
    1956      274366 :     xact_state = pgStatXactStack;
    1957      274366 :     if (xact_state == NULL || xact_state->nest_level != nest_level)
    1958             :     {
    1959             :         xact_state = (PgStat_SubXactStatus *)
    1960       96034 :             MemoryContextAlloc(TopTransactionContext,
    1961             :                                sizeof(PgStat_SubXactStatus));
    1962       96034 :         xact_state->nest_level = nest_level;
    1963       96034 :         xact_state->prev = pgStatXactStack;
    1964       96034 :         xact_state->first = NULL;
    1965       96034 :         pgStatXactStack = xact_state;
    1966             :     }
    1967      274366 :     return xact_state;
    1968             : }
    1969             : 
    1970             : /*
    1971             :  * add_tabstat_xact_level - add a new (sub)transaction state record
    1972             :  */
    1973             : static void
    1974      273730 : add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
    1975             : {
    1976             :     PgStat_SubXactStatus *xact_state;
    1977             :     PgStat_TableXactStatus *trans;
    1978             : 
    1979             :     /*
    1980             :      * If this is the first rel to be modified at the current nest level, we
    1981             :      * first have to push a transaction stack entry.
    1982             :      */
    1983      273730 :     xact_state = get_tabstat_stack_level(nest_level);
    1984             : 
    1985             :     /* Now make a per-table stack entry */
    1986             :     trans = (PgStat_TableXactStatus *)
    1987      273730 :         MemoryContextAllocZero(TopTransactionContext,
    1988             :                                sizeof(PgStat_TableXactStatus));
    1989      273730 :     trans->nest_level = nest_level;
    1990      273730 :     trans->upper = pgstat_info->trans;
    1991      273730 :     trans->parent = pgstat_info;
    1992      273730 :     trans->next = xact_state->first;
    1993      273730 :     xact_state->first = trans;
    1994      273730 :     pgstat_info->trans = trans;
    1995      273730 : }
    1996             : 
    1997             : /*
    1998             :  * pgstat_count_heap_insert - count a tuple insertion of n tuples
    1999             :  */
    2000             : void
    2001    18839624 : pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
    2002             : {
    2003    18839624 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2004             : 
    2005    18839624 :     if (pgstat_info != NULL)
    2006             :     {
    2007             :         /* We have to log the effect at the proper transactional level */
    2008    10610278 :         int         nest_level = GetCurrentTransactionNestLevel();
    2009             : 
    2010    10610278 :         if (pgstat_info->trans == NULL ||
    2011    10431838 :             pgstat_info->trans->nest_level != nest_level)
    2012      181872 :             add_tabstat_xact_level(pgstat_info, nest_level);
    2013             : 
    2014    10610278 :         pgstat_info->trans->tuples_inserted += n;
    2015             :     }
    2016    18839624 : }
    2017             : 
    2018             : /*
    2019             :  * pgstat_count_heap_update - count a tuple update
    2020             :  */
    2021             : void
    2022      338274 : pgstat_count_heap_update(Relation rel, bool hot)
    2023             : {
    2024      338274 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2025             : 
    2026      338274 :     if (pgstat_info != NULL)
    2027             :     {
    2028             :         /* We have to log the effect at the proper transactional level */
    2029      189704 :         int         nest_level = GetCurrentTransactionNestLevel();
    2030             : 
    2031      189704 :         if (pgstat_info->trans == NULL ||
    2032      162728 :             pgstat_info->trans->nest_level != nest_level)
    2033       27036 :             add_tabstat_xact_level(pgstat_info, nest_level);
    2034             : 
    2035      189704 :         pgstat_info->trans->tuples_updated++;
    2036             : 
    2037             :         /* t_tuples_hot_updated is nontransactional, so just advance it */
    2038      189704 :         if (hot)
    2039      117792 :             pgstat_info->t_counts.t_tuples_hot_updated++;
    2040             :     }
    2041      338274 : }
    2042             : 
    2043             : /*
    2044             :  * pgstat_count_heap_delete - count a tuple deletion
    2045             :  */
    2046             : void
    2047     1619714 : pgstat_count_heap_delete(Relation rel)
    2048             : {
    2049     1619714 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2050             : 
    2051     1619714 :     if (pgstat_info != NULL)
    2052             :     {
    2053             :         /* We have to log the effect at the proper transactional level */
    2054     1611838 :         int         nest_level = GetCurrentTransactionNestLevel();
    2055             : 
    2056     1611838 :         if (pgstat_info->trans == NULL ||
    2057     1548646 :             pgstat_info->trans->nest_level != nest_level)
    2058       63320 :             add_tabstat_xact_level(pgstat_info, nest_level);
    2059             : 
    2060     1611838 :         pgstat_info->trans->tuples_deleted++;
    2061             :     }
    2062     1619714 : }
    2063             : 
    2064             : /*
    2065             :  * pgstat_truncate_save_counters
    2066             :  *
    2067             :  * Whenever a table is truncated, we save its i/u/d counters so that they can
    2068             :  * be cleared, and if the (sub)xact that executed the truncate later aborts,
    2069             :  * the counters can be restored to the saved (pre-truncate) values.  Note we do
    2070             :  * this on the first truncate in any particular subxact level only.
    2071             :  */
    2072             : static void
    2073        1610 : pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
    2074             : {
    2075        1610 :     if (!trans->truncated)
    2076             :     {
    2077        1526 :         trans->inserted_pre_trunc = trans->tuples_inserted;
    2078        1526 :         trans->updated_pre_trunc = trans->tuples_updated;
    2079        1526 :         trans->deleted_pre_trunc = trans->tuples_deleted;
    2080        1526 :         trans->truncated = true;
    2081             :     }
    2082        1610 : }
    2083             : 
    2084             : /*
    2085             :  * pgstat_truncate_restore_counters - restore counters when a truncate aborts
    2086             :  */
    2087             : static void
    2088        9990 : pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
    2089             : {
    2090        9990 :     if (trans->truncated)
    2091             :     {
    2092          74 :         trans->tuples_inserted = trans->inserted_pre_trunc;
    2093          74 :         trans->tuples_updated = trans->updated_pre_trunc;
    2094          74 :         trans->tuples_deleted = trans->deleted_pre_trunc;
    2095             :     }
    2096        9990 : }
    2097             : 
    2098             : /*
    2099             :  * pgstat_count_truncate - update tuple counters due to truncate
    2100             :  */
    2101             : void
    2102        1594 : pgstat_count_truncate(Relation rel)
    2103             : {
    2104        1594 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2105             : 
    2106        1594 :     if (pgstat_info != NULL)
    2107             :     {
    2108             :         /* We have to log the effect at the proper transactional level */
    2109        1594 :         int         nest_level = GetCurrentTransactionNestLevel();
    2110             : 
    2111        1594 :         if (pgstat_info->trans == NULL ||
    2112         108 :             pgstat_info->trans->nest_level != nest_level)
    2113        1502 :             add_tabstat_xact_level(pgstat_info, nest_level);
    2114             : 
    2115        1594 :         pgstat_truncate_save_counters(pgstat_info->trans);
    2116        1594 :         pgstat_info->trans->tuples_inserted = 0;
    2117        1594 :         pgstat_info->trans->tuples_updated = 0;
    2118        1594 :         pgstat_info->trans->tuples_deleted = 0;
    2119             :     }
    2120        1594 : }
    2121             : 
    2122             : /*
    2123             :  * pgstat_update_heap_dead_tuples - update dead-tuples count
    2124             :  *
    2125             :  * The semantics of this are that we are reporting the nontransactional
    2126             :  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
    2127             :  * rather than increasing, and the change goes straight into the per-table
    2128             :  * counter, not into transactional state.
    2129             :  */
    2130             : void
    2131       35518 : pgstat_update_heap_dead_tuples(Relation rel, int delta)
    2132             : {
    2133       35518 :     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
    2134             : 
    2135       35518 :     if (pgstat_info != NULL)
    2136       12606 :         pgstat_info->t_counts.t_delta_dead_tuples -= delta;
    2137       35518 : }
    2138             : 
    2139             : 
    2140             : /* ----------
    2141             :  * AtEOXact_PgStat
    2142             :  *
    2143             :  *  Called from access/transam/xact.c at top-level transaction commit/abort.
    2144             :  * ----------
    2145             :  */
    2146             : void
    2147      494706 : AtEOXact_PgStat(bool isCommit, bool parallel)
    2148             : {
    2149             :     PgStat_SubXactStatus *xact_state;
    2150             : 
    2151             :     /* Don't count parallel worker transaction stats */
    2152      494706 :     if (!parallel)
    2153             :     {
    2154             :         /*
    2155             :          * Count transaction commit or abort.  (We use counters, not just
    2156             :          * bools, in case the reporting message isn't sent right away.)
    2157             :          */
    2158      493136 :         if (isCommit)
    2159      472734 :             pgStatXactCommit++;
    2160             :         else
    2161       20402 :             pgStatXactRollback++;
    2162             :     }
    2163             : 
    2164             :     /*
    2165             :      * Transfer transactional insert/update counts into the base tabstat
    2166             :      * entries.  We don't bother to free any of the transactional state, since
    2167             :      * it's all in TopTransactionContext and will go away anyway.
    2168             :      */
    2169      494706 :     xact_state = pgStatXactStack;
    2170      494706 :     if (xact_state != NULL)
    2171             :     {
    2172             :         PgStat_TableXactStatus *trans;
    2173             : 
    2174             :         Assert(xact_state->nest_level == 1);
    2175             :         Assert(xact_state->prev == NULL);
    2176      361560 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2177             :         {
    2178             :             PgStat_TableStatus *tabstat;
    2179             : 
    2180             :             Assert(trans->nest_level == 1);
    2181             :             Assert(trans->upper == NULL);
    2182      269734 :             tabstat = trans->parent;
    2183             :             Assert(tabstat->trans == trans);
    2184             :             /* restore pre-truncate stats (if any) in case of aborted xact */
    2185      269734 :             if (!isCommit)
    2186        9472 :                 pgstat_truncate_restore_counters(trans);
    2187             :             /* count attempted actions regardless of commit/abort */
    2188      269734 :             tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
    2189      269734 :             tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
    2190      269734 :             tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
    2191      269734 :             if (isCommit)
    2192             :             {
    2193      260262 :                 tabstat->t_counts.t_truncated = trans->truncated;
    2194      260262 :                 if (trans->truncated)
    2195             :                 {
    2196             :                     /* forget live/dead stats seen by backend thus far */
    2197        1436 :                     tabstat->t_counts.t_delta_live_tuples = 0;
    2198        1436 :                     tabstat->t_counts.t_delta_dead_tuples = 0;
    2199             :                 }
    2200             :                 /* insert adds a live tuple, delete removes one */
    2201      520524 :                 tabstat->t_counts.t_delta_live_tuples +=
    2202      260262 :                     trans->tuples_inserted - trans->tuples_deleted;
    2203             :                 /* update and delete each create a dead tuple */
    2204      520524 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2205      260262 :                     trans->tuples_updated + trans->tuples_deleted;
    2206             :                 /* insert, update, delete each count as one change event */
    2207      520524 :                 tabstat->t_counts.t_changed_tuples +=
    2208      520524 :                     trans->tuples_inserted + trans->tuples_updated +
    2209      260262 :                     trans->tuples_deleted;
    2210             :             }
    2211             :             else
    2212             :             {
    2213             :                 /* inserted tuples are dead, deleted tuples are unaffected */
    2214       18944 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2215        9472 :                     trans->tuples_inserted + trans->tuples_updated;
    2216             :                 /* an aborted xact generates no changed_tuple events */
    2217             :             }
    2218      269734 :             tabstat->trans = NULL;
    2219             :         }
    2220             :     }
    2221      494706 :     pgStatXactStack = NULL;
    2222             : 
    2223             :     /* Make sure any stats snapshot is thrown away */
    2224      494706 :     pgstat_clear_snapshot();
    2225      494706 : }
    2226             : 
    2227             : /* ----------
    2228             :  * AtEOSubXact_PgStat
    2229             :  *
    2230             :  *  Called from access/transam/xact.c at subtransaction commit/abort.
    2231             :  * ----------
    2232             :  */
    2233             : void
    2234        7638 : AtEOSubXact_PgStat(bool isCommit, int nestDepth)
    2235             : {
    2236             :     PgStat_SubXactStatus *xact_state;
    2237             : 
    2238             :     /*
    2239             :      * Transfer transactional insert/update counts into the next higher
    2240             :      * subtransaction state.
    2241             :      */
    2242        7638 :     xact_state = pgStatXactStack;
    2243        7638 :     if (xact_state != NULL &&
    2244        4590 :         xact_state->nest_level >= nestDepth)
    2245             :     {
    2246             :         PgStat_TableXactStatus *trans;
    2247             :         PgStat_TableXactStatus *next_trans;
    2248             : 
    2249             :         /* delink xact_state from stack immediately to simplify reuse case */
    2250        4144 :         pgStatXactStack = xact_state->prev;
    2251             : 
    2252        8636 :         for (trans = xact_state->first; trans != NULL; trans = next_trans)
    2253             :         {
    2254             :             PgStat_TableStatus *tabstat;
    2255             : 
    2256        4492 :             next_trans = trans->next;
    2257             :             Assert(trans->nest_level == nestDepth);
    2258        4492 :             tabstat = trans->parent;
    2259             :             Assert(tabstat->trans == trans);
    2260        4492 :             if (isCommit)
    2261             :             {
    2262        3974 :                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
    2263             :                 {
    2264        3338 :                     if (trans->truncated)
    2265             :                     {
    2266             :                         /* propagate the truncate status one level up */
    2267          16 :                         pgstat_truncate_save_counters(trans->upper);
    2268             :                         /* replace upper xact stats with ours */
    2269          16 :                         trans->upper->tuples_inserted = trans->tuples_inserted;
    2270          16 :                         trans->upper->tuples_updated = trans->tuples_updated;
    2271          16 :                         trans->upper->tuples_deleted = trans->tuples_deleted;
    2272             :                     }
    2273             :                     else
    2274             :                     {
    2275        3322 :                         trans->upper->tuples_inserted += trans->tuples_inserted;
    2276        3322 :                         trans->upper->tuples_updated += trans->tuples_updated;
    2277        3322 :                         trans->upper->tuples_deleted += trans->tuples_deleted;
    2278             :                     }
    2279        3338 :                     tabstat->trans = trans->upper;
    2280        3338 :                     pfree(trans);
    2281             :                 }
    2282             :                 else
    2283             :                 {
    2284             :                     /*
    2285             :                      * When there isn't an immediate parent state, we can just
    2286             :                      * reuse the record instead of going through a
    2287             :                      * palloc/pfree pushup (this works since it's all in
    2288             :                      * TopTransactionContext anyway).  We have to re-link it
    2289             :                      * into the parent level, though, and that might mean
    2290             :                      * pushing a new entry into the pgStatXactStack.
    2291             :                      */
    2292             :                     PgStat_SubXactStatus *upper_xact_state;
    2293             : 
    2294         636 :                     upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
    2295         636 :                     trans->next = upper_xact_state->first;
    2296         636 :                     upper_xact_state->first = trans;
    2297         636 :                     trans->nest_level = nestDepth - 1;
    2298             :                 }
    2299             :             }
    2300             :             else
    2301             :             {
    2302             :                 /*
    2303             :                  * On abort, update top-level tabstat counts, then forget the
    2304             :                  * subtransaction
    2305             :                  */
    2306             : 
    2307             :                 /* first restore values obliterated by truncate */
    2308         518 :                 pgstat_truncate_restore_counters(trans);
    2309             :                 /* count attempted actions regardless of commit/abort */
    2310         518 :                 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
    2311         518 :                 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
    2312         518 :                 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
    2313             :                 /* inserted tuples are dead, deleted tuples are unaffected */
    2314        1036 :                 tabstat->t_counts.t_delta_dead_tuples +=
    2315         518 :                     trans->tuples_inserted + trans->tuples_updated;
    2316         518 :                 tabstat->trans = trans->upper;
    2317         518 :                 pfree(trans);
    2318             :             }
    2319             :         }
    2320        4144 :         pfree(xact_state);
    2321             :     }
    2322        7638 : }
    2323             : 
    2324             : 
    2325             : /*
    2326             :  * AtPrepare_PgStat
    2327             :  *      Save the transactional stats state at 2PC transaction prepare.
    2328             :  *
    2329             :  * In this phase we just generate 2PC records for all the pending
    2330             :  * transaction-dependent stats work.
    2331             :  */
    2332             : void
    2333          66 : AtPrepare_PgStat(void)
    2334             : {
    2335             :     PgStat_SubXactStatus *xact_state;
    2336             : 
    2337          66 :     xact_state = pgStatXactStack;
    2338          66 :     if (xact_state != NULL)
    2339             :     {
    2340             :         PgStat_TableXactStatus *trans;
    2341             : 
    2342             :         Assert(xact_state->nest_level == 1);
    2343             :         Assert(xact_state->prev == NULL);
    2344         204 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2345             :         {
    2346             :             PgStat_TableStatus *tabstat;
    2347             :             TwoPhasePgStatRecord record;
    2348             : 
    2349             :             Assert(trans->nest_level == 1);
    2350             :             Assert(trans->upper == NULL);
    2351         140 :             tabstat = trans->parent;
    2352             :             Assert(tabstat->trans == trans);
    2353             : 
    2354         140 :             record.tuples_inserted = trans->tuples_inserted;
    2355         140 :             record.tuples_updated = trans->tuples_updated;
    2356         140 :             record.tuples_deleted = trans->tuples_deleted;
    2357         140 :             record.inserted_pre_trunc = trans->inserted_pre_trunc;
    2358         140 :             record.updated_pre_trunc = trans->updated_pre_trunc;
    2359         140 :             record.deleted_pre_trunc = trans->deleted_pre_trunc;
    2360         140 :             record.t_id = tabstat->t_id;
    2361         140 :             record.t_shared = tabstat->t_shared;
    2362         140 :             record.t_truncated = trans->truncated;
    2363             : 
    2364         140 :             RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
    2365             :                                    &record, sizeof(TwoPhasePgStatRecord));
    2366             :         }
    2367             :     }
    2368          66 : }
    2369             : 
    2370             : /*
    2371             :  * PostPrepare_PgStat
    2372             :  *      Clean up after successful PREPARE.
    2373             :  *
    2374             :  * All we need do here is unlink the transaction stats state from the
    2375             :  * nontransactional state.  The nontransactional action counts will be
    2376             :  * reported to the stats collector immediately, while the effects on live
    2377             :  * and dead tuple counts are preserved in the 2PC state file.
    2378             :  *
    2379             :  * Note: AtEOXact_PgStat is not called during PREPARE.
    2380             :  */
    2381             : void
    2382          66 : PostPrepare_PgStat(void)
    2383             : {
    2384             :     PgStat_SubXactStatus *xact_state;
    2385             : 
    2386             :     /*
    2387             :      * We don't bother to free any of the transactional state, since it's all
    2388             :      * in TopTransactionContext and will go away anyway.
    2389             :      */
    2390          66 :     xact_state = pgStatXactStack;
    2391          66 :     if (xact_state != NULL)
    2392             :     {
    2393             :         PgStat_TableXactStatus *trans;
    2394             : 
    2395         204 :         for (trans = xact_state->first; trans != NULL; trans = trans->next)
    2396             :         {
    2397             :             PgStat_TableStatus *tabstat;
    2398             : 
    2399         140 :             tabstat = trans->parent;
    2400         140 :             tabstat->trans = NULL;
    2401             :         }
    2402             :     }
    2403          66 :     pgStatXactStack = NULL;
    2404             : 
    2405             :     /* Make sure any stats snapshot is thrown away */
    2406          66 :     pgstat_clear_snapshot();
    2407          66 : }
    2408             : 
    2409             : /*
    2410             :  * 2PC processing routine for COMMIT PREPARED case.
    2411             :  *
    2412             :  * Load the saved counts into our local pgstats state.
    2413             :  */
    2414             : void
    2415         102 : pgstat_twophase_postcommit(TransactionId xid, uint16 info,
    2416             :                            void *recdata, uint32 len)
    2417             : {
    2418         102 :     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
    2419             :     PgStat_TableStatus *pgstat_info;
    2420             : 
    2421             :     /* Find or create a tabstat entry for the rel */
    2422         102 :     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
    2423             : 
    2424             :     /* Same math as in AtEOXact_PgStat, commit case */
    2425         102 :     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
    2426         102 :     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
    2427         102 :     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
    2428         102 :     pgstat_info->t_counts.t_truncated = rec->t_truncated;
    2429         102 :     if (rec->t_truncated)
    2430             :     {
    2431             :         /* forget live/dead stats seen by backend thus far */
    2432           0 :         pgstat_info->t_counts.t_delta_live_tuples = 0;
    2433           0 :         pgstat_info->t_counts.t_delta_dead_tuples = 0;
    2434             :     }
    2435         204 :     pgstat_info->t_counts.t_delta_live_tuples +=
    2436         102 :         rec->tuples_inserted - rec->tuples_deleted;
    2437         204 :     pgstat_info->t_counts.t_delta_dead_tuples +=
    2438         102 :         rec->tuples_updated + rec->tuples_deleted;
    2439         204 :     pgstat_info->t_counts.t_changed_tuples +=
    2440         204 :         rec->tuples_inserted + rec->tuples_updated +
    2441         102 :         rec->tuples_deleted;
    2442         102 : }
    2443             : 
    2444             : /*
    2445             :  * 2PC processing routine for ROLLBACK PREPARED case.
    2446             :  *
    2447             :  * Load the saved counts into our local pgstats state, but treat them
    2448             :  * as aborted.
    2449             :  */
    2450             : void
    2451          38 : pgstat_twophase_postabort(TransactionId xid, uint16 info,
    2452             :                           void *recdata, uint32 len)
    2453             : {
    2454          38 :     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
    2455             :     PgStat_TableStatus *pgstat_info;
    2456             : 
    2457             :     /* Find or create a tabstat entry for the rel */
    2458          38 :     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
    2459             : 
    2460             :     /* Same math as in AtEOXact_PgStat, abort case */
    2461          38 :     if (rec->t_truncated)
    2462             :     {
    2463           0 :         rec->tuples_inserted = rec->inserted_pre_trunc;
    2464           0 :         rec->tuples_updated = rec->updated_pre_trunc;
    2465           0 :         rec->tuples_deleted = rec->deleted_pre_trunc;
    2466             :     }
    2467          38 :     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
    2468          38 :     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
    2469          38 :     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
    2470          76 :     pgstat_info->t_counts.t_delta_dead_tuples +=
    2471          38 :         rec->tuples_inserted + rec->tuples_updated;
    2472          38 : }
    2473             : 
    2474             : 
    2475             : /* ----------
    2476             :  * pgstat_fetch_stat_dbentry() -
    2477             :  *
    2478             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2479             :  *  the collected statistics for one database or NULL. NULL doesn't mean
    2480             :  *  that the database doesn't exist, it is just not yet known by the
    2481             :  *  collector, so the caller is better off to report ZERO instead.
    2482             :  * ----------
    2483             :  */
    2484             : PgStat_StatDBEntry *
    2485        3062 : pgstat_fetch_stat_dbentry(Oid dbid)
    2486             : {
    2487             :     /*
    2488             :      * If not done for this transaction, read the statistics collector stats
    2489             :      * file into some hash tables.
    2490             :      */
    2491        3062 :     backend_read_statsfile();
    2492             : 
    2493             :     /*
    2494             :      * Lookup the requested database; return NULL if not found
    2495             :      */
    2496        3062 :     return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2497             :                                               (void *) &dbid,
    2498             :                                               HASH_FIND, NULL);
    2499             : }
    2500             : 
    2501             : 
    2502             : /* ----------
    2503             :  * pgstat_fetch_stat_tabentry() -
    2504             :  *
    2505             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2506             :  *  the collected statistics for one table or NULL. NULL doesn't mean
    2507             :  *  that the table doesn't exist, it is just not yet known by the
    2508             :  *  collector, so the caller is better off to report ZERO instead.
    2509             :  * ----------
    2510             :  */
    2511             : PgStat_StatTabEntry *
    2512         500 : pgstat_fetch_stat_tabentry(Oid relid)
    2513             : {
    2514             :     Oid         dbid;
    2515             :     PgStat_StatDBEntry *dbentry;
    2516             :     PgStat_StatTabEntry *tabentry;
    2517             : 
    2518             :     /*
    2519             :      * If not done for this transaction, read the statistics collector stats
    2520             :      * file into some hash tables.
    2521             :      */
    2522         500 :     backend_read_statsfile();
    2523             : 
    2524             :     /*
    2525             :      * Lookup our database, then look in its table hash table.
    2526             :      */
    2527         500 :     dbid = MyDatabaseId;
    2528         500 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2529             :                                                  (void *) &dbid,
    2530             :                                                  HASH_FIND, NULL);
    2531         500 :     if (dbentry != NULL && dbentry->tables != NULL)
    2532             :     {
    2533         500 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    2534             :                                                        (void *) &relid,
    2535             :                                                        HASH_FIND, NULL);
    2536         500 :         if (tabentry)
    2537         360 :             return tabentry;
    2538             :     }
    2539             : 
    2540             :     /*
    2541             :      * If we didn't find it, maybe it's a shared table.
    2542             :      */
    2543         140 :     dbid = InvalidOid;
    2544         140 :     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    2545             :                                                  (void *) &dbid,
    2546             :                                                  HASH_FIND, NULL);
    2547         140 :     if (dbentry != NULL && dbentry->tables != NULL)
    2548             :     {
    2549         140 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    2550             :                                                        (void *) &relid,
    2551             :                                                        HASH_FIND, NULL);
    2552         140 :         if (tabentry)
    2553           0 :             return tabentry;
    2554             :     }
    2555             : 
    2556         140 :     return NULL;
    2557             : }
    2558             : 
    2559             : 
    2560             : /* ----------
    2561             :  * pgstat_fetch_stat_funcentry() -
    2562             :  *
    2563             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2564             :  *  the collected statistics for one function or NULL.
    2565             :  * ----------
    2566             :  */
    2567             : PgStat_StatFuncEntry *
    2568           0 : pgstat_fetch_stat_funcentry(Oid func_id)
    2569             : {
    2570             :     PgStat_StatDBEntry *dbentry;
    2571           0 :     PgStat_StatFuncEntry *funcentry = NULL;
    2572             : 
    2573             :     /* load the stats file if needed */
    2574           0 :     backend_read_statsfile();
    2575             : 
    2576             :     /* Lookup our database, then find the requested function.  */
    2577           0 :     dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
    2578           0 :     if (dbentry != NULL && dbentry->functions != NULL)
    2579             :     {
    2580           0 :         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
    2581             :                                                          (void *) &func_id,
    2582             :                                                          HASH_FIND, NULL);
    2583             :     }
    2584             : 
    2585           0 :     return funcentry;
    2586             : }
    2587             : 
    2588             : 
    2589             : /* ----------
    2590             :  * pgstat_fetch_stat_beentry() -
    2591             :  *
    2592             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2593             :  *  our local copy of the current-activity entry for one backend.
    2594             :  *
    2595             :  *  NB: caller is responsible for a check if the user is permitted to see
    2596             :  *  this info (especially the querystring).
    2597             :  * ----------
    2598             :  */
    2599             : PgBackendStatus *
    2600           0 : pgstat_fetch_stat_beentry(int beid)
    2601             : {
    2602           0 :     pgstat_read_current_status();
    2603             : 
    2604           0 :     if (beid < 1 || beid > localNumBackends)
    2605           0 :         return NULL;
    2606             : 
    2607           0 :     return &localBackendStatusTable[beid - 1].backendStatus;
    2608             : }
    2609             : 
    2610             : 
    2611             : /* ----------
    2612             :  * pgstat_fetch_stat_local_beentry() -
    2613             :  *
    2614             :  *  Like pgstat_fetch_stat_beentry() but with locally computed additions (like
    2615             :  *  xid and xmin values of the backend)
    2616             :  *
    2617             :  *  NB: caller is responsible for a check if the user is permitted to see
    2618             :  *  this info (especially the querystring).
    2619             :  * ----------
    2620             :  */
    2621             : LocalPgBackendStatus *
    2622        2234 : pgstat_fetch_stat_local_beentry(int beid)
    2623             : {
    2624        2234 :     pgstat_read_current_status();
    2625             : 
    2626        2234 :     if (beid < 1 || beid > localNumBackends)
    2627           0 :         return NULL;
    2628             : 
    2629        2234 :     return &localBackendStatusTable[beid - 1];
    2630             : }
    2631             : 
    2632             : 
    2633             : /* ----------
    2634             :  * pgstat_fetch_stat_numbackends() -
    2635             :  *
    2636             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2637             :  *  the maximum current backend id.
    2638             :  * ----------
    2639             :  */
    2640             : int
    2641         300 : pgstat_fetch_stat_numbackends(void)
    2642             : {
    2643         300 :     pgstat_read_current_status();
    2644             : 
    2645         300 :     return localNumBackends;
    2646             : }
    2647             : 
    2648             : /*
    2649             :  * ---------
    2650             :  * pgstat_fetch_stat_archiver() -
    2651             :  *
    2652             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2653             :  *  a pointer to the archiver statistics struct.
    2654             :  * ---------
    2655             :  */
    2656             : PgStat_ArchiverStats *
    2657          26 : pgstat_fetch_stat_archiver(void)
    2658             : {
    2659          26 :     backend_read_statsfile();
    2660             : 
    2661          26 :     return &archiverStats;
    2662             : }
    2663             : 
    2664             : 
    2665             : /*
    2666             :  * ---------
    2667             :  * pgstat_fetch_global() -
    2668             :  *
    2669             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2670             :  *  a pointer to the global statistics struct.
    2671             :  * ---------
    2672             :  */
    2673             : PgStat_GlobalStats *
    2674          28 : pgstat_fetch_global(void)
    2675             : {
    2676          28 :     backend_read_statsfile();
    2677             : 
    2678          28 :     return &globalStats;
    2679             : }
    2680             : 
    2681             : 
    2682             : /*
    2683             :  * ---------
    2684             :  * pgstat_fetch_slru() -
    2685             :  *
    2686             :  *  Support function for the SQL-callable pgstat* functions. Returns
    2687             :  *  a pointer to the slru statistics struct.
    2688             :  * ---------
    2689             :  */
    2690             : PgStat_SLRUStats *
    2691           0 : pgstat_fetch_slru(void)
    2692             : {
    2693           0 :     backend_read_statsfile();
    2694             : 
    2695           0 :     return slruStats;
    2696             : }
    2697             : 
    2698             : 
    2699             : /* ------------------------------------------------------------
    2700             :  * Functions for management of the shared-memory PgBackendStatus array
    2701             :  * ------------------------------------------------------------
    2702             :  */
    2703             : 
    2704             : static PgBackendStatus *BackendStatusArray = NULL;
    2705             : static PgBackendStatus *MyBEEntry = NULL;
    2706             : static char *BackendAppnameBuffer = NULL;
    2707             : static char *BackendClientHostnameBuffer = NULL;
    2708             : static char *BackendActivityBuffer = NULL;
    2709             : static Size BackendActivityBufferSize = 0;
    2710             : #ifdef USE_SSL
    2711             : static PgBackendSSLStatus *BackendSslStatusBuffer = NULL;
    2712             : #endif
    2713             : #ifdef ENABLE_GSS
    2714             : static PgBackendGSSStatus *BackendGssStatusBuffer = NULL;
    2715             : #endif
    2716             : 
    2717             : 
    2718             : /*
    2719             :  * Report shared-memory space needed by CreateSharedBackendStatus.
    2720             :  */
    2721             : Size
    2722        2174 : BackendStatusShmemSize(void)
    2723             : {
    2724             :     Size        size;
    2725             : 
    2726             :     /* BackendStatusArray: */
    2727        2174 :     size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
    2728             :     /* BackendAppnameBuffer: */
    2729        2174 :     size = add_size(size,
    2730        2174 :                     mul_size(NAMEDATALEN, NumBackendStatSlots));
    2731             :     /* BackendClientHostnameBuffer: */
    2732        2174 :     size = add_size(size,
    2733        2174 :                     mul_size(NAMEDATALEN, NumBackendStatSlots));
    2734             :     /* BackendActivityBuffer: */
    2735        2174 :     size = add_size(size,
    2736        2174 :                     mul_size(pgstat_track_activity_query_size, NumBackendStatSlots));
    2737             : #ifdef USE_SSL
    2738             :     /* BackendSslStatusBuffer: */
    2739        2174 :     size = add_size(size,
    2740        2174 :                     mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots));
    2741             : #endif
    2742        2174 :     return size;
    2743             : }
    2744             : 
    2745             : /*
    2746             :  * Initialize the shared status array and several string buffers
    2747             :  * during postmaster startup.
    2748             :  */
    2749             : void
    2750        2170 : CreateSharedBackendStatus(void)
    2751             : {
    2752             :     Size        size;
    2753             :     bool        found;
    2754             :     int         i;
    2755             :     char       *buffer;
    2756             : 
    2757             :     /* Create or attach to the shared array */
    2758        2170 :     size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
    2759        2170 :     BackendStatusArray = (PgBackendStatus *)
    2760        2170 :         ShmemInitStruct("Backend Status Array", size, &found);
    2761             : 
    2762        2170 :     if (!found)
    2763             :     {
    2764             :         /*
    2765             :          * We're the first - initialize.
    2766             :          */
    2767        2170 :         MemSet(BackendStatusArray, 0, size);
    2768             :     }
    2769             : 
    2770             :     /* Create or attach to the shared appname buffer */
    2771        2170 :     size = mul_size(NAMEDATALEN, NumBackendStatSlots);
    2772        2170 :     BackendAppnameBuffer = (char *)
    2773        2170 :         ShmemInitStruct("Backend Application Name Buffer", size, &found);
    2774             : 
    2775        2170 :     if (!found)
    2776             :     {
    2777        2170 :         MemSet(BackendAppnameBuffer, 0, size);
    2778             : 
    2779             :         /* Initialize st_appname pointers. */
    2780        2170 :         buffer = BackendAppnameBuffer;
    2781      245556 :         for (i = 0; i < NumBackendStatSlots; i++)
    2782             :         {
    2783      243386 :             BackendStatusArray[i].st_appname = buffer;
    2784      243386 :             buffer += NAMEDATALEN;
    2785             :         }
    2786             :     }
    2787             : 
    2788             :     /* Create or attach to the shared client hostname buffer */
    2789        2170 :     size = mul_size(NAMEDATALEN, NumBackendStatSlots);
    2790        2170 :     BackendClientHostnameBuffer = (char *)
    2791        2170 :         ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
    2792             : 
    2793        2170 :     if (!found)
    2794             :     {
    2795        2170 :         MemSet(BackendClientHostnameBuffer, 0, size);
    2796             : 
    2797             :         /* Initialize st_clienthostname pointers. */
    2798        2170 :         buffer = BackendClientHostnameBuffer;
    2799      245556 :         for (i = 0; i < NumBackendStatSlots; i++)
    2800             :         {
    2801      243386 :             BackendStatusArray[i].st_clienthostname = buffer;
    2802      243386 :             buffer += NAMEDATALEN;
    2803             :         }
    2804             :     }
    2805             : 
    2806             :     /* Create or attach to the shared activity buffer */
    2807        4340 :     BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
    2808        2170 :                                          NumBackendStatSlots);
    2809        2170 :     BackendActivityBuffer = (char *)
    2810        2170 :         ShmemInitStruct("Backend Activity Buffer",
    2811             :                         BackendActivityBufferSize,
    2812             :                         &found);
    2813             : 
    2814        2170 :     if (!found)
    2815             :     {
    2816        2170 :         MemSet(BackendActivityBuffer, 0, BackendActivityBufferSize);
    2817             : 
    2818             :         /* Initialize st_activity pointers. */
    2819        2170 :         buffer = BackendActivityBuffer;
    2820      245556 :         for (i = 0; i < NumBackendStatSlots; i++)
    2821             :         {
    2822      243386 :             BackendStatusArray[i].st_activity_raw = buffer;
    2823      243386 :             buffer += pgstat_track_activity_query_size;
    2824             :         }
    2825             :     }
    2826             : 
    2827             : #ifdef USE_SSL
    2828             :     /* Create or attach to the shared SSL status buffer */
    2829        2170 :     size = mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots);
    2830        2170 :     BackendSslStatusBuffer = (PgBackendSSLStatus *)
    2831        2170 :         ShmemInitStruct("Backend SSL Status Buffer", size, &found);
    2832             : 
    2833        2170 :     if (!found)
    2834             :     {
    2835             :         PgBackendSSLStatus *ptr;
    2836             : 
    2837        2170 :         MemSet(BackendSslStatusBuffer, 0, size);
    2838             : 
    2839             :         /* Initialize st_sslstatus pointers. */
    2840        2170 :         ptr = BackendSslStatusBuffer;
    2841      245556 :         for (i = 0; i < NumBackendStatSlots; i++)
    2842             :         {
    2843      243386 :             BackendStatusArray[i].st_sslstatus = ptr;
    2844      243386 :             ptr++;
    2845             :         }
    2846             :     }
    2847             : #endif
    2848             : 
    2849             : #ifdef ENABLE_GSS
    2850             :     /* Create or attach to the shared GSSAPI status buffer */
    2851             :     size = mul_size(sizeof(PgBackendGSSStatus), NumBackendStatSlots);
    2852             :     BackendGssStatusBuffer = (PgBackendGSSStatus *)
    2853             :         ShmemInitStruct("Backend GSS Status Buffer", size, &found);
    2854             : 
    2855             :     if (!found)
    2856             :     {
    2857             :         PgBackendGSSStatus *ptr;
    2858             : 
    2859             :         MemSet(BackendGssStatusBuffer, 0, size);
    2860             : 
    2861             :         /* Initialize st_gssstatus pointers. */
    2862             :         ptr = BackendGssStatusBuffer;
    2863             :         for (i = 0; i < NumBackendStatSlots; i++)
    2864             :         {
    2865             :             BackendStatusArray[i].st_gssstatus = ptr;
    2866             :             ptr++;
    2867             :         }
    2868             :     }
    2869             : #endif
    2870        2170 : }
    2871             : 
    2872             : 
    2873             : /* ----------
    2874             :  * pgstat_initialize() -
    2875             :  *
    2876             :  *  Initialize pgstats state, and set up our on-proc-exit hook.
    2877             :  *  Called from InitPostgres and AuxiliaryProcessMain. For auxiliary process,
    2878             :  *  MyBackendId is invalid. Otherwise, MyBackendId must be set,
    2879             :  *  but we must not have started any transaction yet (since the
    2880             :  *  exit hook must run after the last transaction exit).
    2881             :  *  NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
    2882             :  * ----------
    2883             :  */
    2884             : void
    2885       12742 : pgstat_initialize(void)
    2886             : {
    2887             :     /* Initialize MyBEEntry */
    2888       12742 :     if (MyBackendId != InvalidBackendId)
    2889             :     {
    2890             :         Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
    2891       10700 :         MyBEEntry = &BackendStatusArray[MyBackendId - 1];
    2892             :     }
    2893             :     else
    2894             :     {
    2895             :         /* Must be an auxiliary process */
    2896             :         Assert(MyAuxProcType != NotAnAuxProcess);
    2897             : 
    2898             :         /*
    2899             :          * Assign the MyBEEntry for an auxiliary process.  Since it doesn't
    2900             :          * have a BackendId, the slot is statically allocated based on the
    2901             :          * auxiliary process type (MyAuxProcType).  Backends use slots indexed
    2902             :          * in the range from 1 to MaxBackends (inclusive), so we use
    2903             :          * MaxBackends + AuxBackendType + 1 as the index of the slot for an
    2904             :          * auxiliary process.
    2905             :          */
    2906        2042 :         MyBEEntry = &BackendStatusArray[MaxBackends + MyAuxProcType];
    2907             :     }
    2908             : 
    2909             :     /* Set up a process-exit hook to clean up */
    2910       12742 :     on_shmem_exit(pgstat_beshutdown_hook, 0);
    2911       12742 : }
    2912             : 
    2913             : /* ----------
    2914             :  * pgstat_bestart() -
    2915             :  *
    2916             :  *  Initialize this backend's entry in the PgBackendStatus array.
    2917             :  *  Called from InitPostgres.
    2918             :  *
    2919             :  *  Apart from auxiliary processes, MyBackendId, MyDatabaseId,
    2920             :  *  session userid, and application_name must be set for a
    2921             :  *  backend (hence, this cannot be combined with pgstat_initialize).
    2922             :  *  Note also that we must be inside a transaction if this isn't an aux
    2923             :  *  process, as we may need to do encoding conversion on some strings.
    2924             :  * ----------
    2925             :  */
    2926             : void
    2927       12674 : pgstat_bestart(void)
    2928             : {
    2929       12674 :     volatile PgBackendStatus *vbeentry = MyBEEntry;
    2930             :     PgBackendStatus lbeentry;
    2931             : #ifdef USE_SSL
    2932             :     PgBackendSSLStatus lsslstatus;
    2933             : #endif
    2934             : #ifdef ENABLE_GSS
    2935             :     PgBackendGSSStatus lgssstatus;
    2936             : #endif
    2937             : 
    2938             :     /* pgstats state must be initialized from pgstat_initialize() */
    2939             :     Assert(vbeentry != NULL);
    2940             : 
    2941             :     /*
    2942             :      * To minimize the time spent modifying the PgBackendStatus entry, and
    2943             :      * avoid risk of errors inside the critical section, we first copy the
    2944             :      * shared-memory struct to a local variable, then modify the data in the
    2945             :      * local variable, then copy the local variable back to shared memory.
    2946             :      * Only the last step has to be inside the critical section.
    2947             :      *
    2948             :      * Most of the data we copy from shared memory is just going to be
    2949             :      * overwritten, but the struct's not so large that it's worth the
    2950             :      * maintenance hassle to copy only the needful fields.
    2951             :      */
    2952       12674 :     memcpy(&lbeentry,
    2953       12674 :            unvolatize(PgBackendStatus *, vbeentry),
    2954             :            sizeof(PgBackendStatus));
    2955             : 
    2956             :     /* These structs can just start from zeroes each time, though */
    2957             : #ifdef USE_SSL
    2958       12674 :     memset(&lsslstatus, 0, sizeof(lsslstatus));
    2959             : #endif
    2960             : #ifdef ENABLE_GSS
    2961             :     memset(&lgssstatus, 0, sizeof(lgssstatus));
    2962             : #endif
    2963             : 
    2964             :     /*
    2965             :      * Now fill in all the fields of lbeentry, except for strings that are
    2966             :      * out-of-line data.  Those have to be handled separately, below.
    2967             :      */
    2968       12674 :     lbeentry.st_procpid = MyProcPid;
    2969       12674 :     lbeentry.st_backendType = MyBackendType;
    2970       12674 :     lbeentry.st_proc_start_timestamp = MyStartTimestamp;
    2971       12674 :     lbeentry.st_activity_start_timestamp = 0;
    2972       12674 :     lbeentry.st_state_start_timestamp = 0;
    2973       12674 :     lbeentry.st_xact_start_timestamp = 0;
    2974       12674 :     lbeentry.st_databaseid = MyDatabaseId;
    2975             : 
    2976             :     /* We have userid for client-backends, wal-sender and bgworker processes */
    2977       12674 :     if (lbeentry.st_backendType == B_BACKEND
    2978        5546 :         || lbeentry.st_backendType == B_WAL_SENDER
    2979        4928 :         || lbeentry.st_backendType == B_BG_WORKER)
    2980        9842 :         lbeentry.st_userid = GetSessionUserId();
    2981             :     else
    2982        2832 :         lbeentry.st_userid = InvalidOid;
    2983             : 
    2984             :     /*
    2985             :      * We may not have a MyProcPort (eg, if this is the autovacuum process).
    2986             :      * If so, use all-zeroes client address, which is dealt with specially in
    2987             :      * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
    2988             :      */
    2989       12674 :     if (MyProcPort)
    2990        7746 :         memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
    2991             :                sizeof(lbeentry.st_clientaddr));
    2992             :     else
    2993       88704 :         MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
    2994             : 
    2995             : #ifdef USE_SSL
    2996       12674 :     if (MyProcPort && MyProcPort->ssl != NULL)
    2997             :     {
    2998          62 :         lbeentry.st_ssl = true;
    2999          62 :         lsslstatus.ssl_bits = be_tls_get_cipher_bits(MyProcPort);
    3000          62 :         lsslstatus.ssl_compression = be_tls_get_compression(MyProcPort);
    3001          62 :         strlcpy(lsslstatus.ssl_version, be_tls_get_version(MyProcPort), NAMEDATALEN);
    3002          62 :         strlcpy(lsslstatus.ssl_cipher, be_tls_get_cipher(MyProcPort), NAMEDATALEN);
    3003          62 :         be_tls_get_peer_subject_name(MyProcPort, lsslstatus.ssl_client_dn, NAMEDATALEN);
    3004          62 :         be_tls_get_peer_serial(MyProcPort, lsslstatus.ssl_client_serial, NAMEDATALEN);
    3005          62 :         be_tls_get_peer_issuer_name(MyProcPort, lsslstatus.ssl_issuer_dn, NAMEDATALEN);
    3006             :     }
    3007             :     else
    3008             :     {
    3009       12612 :         lbeentry.st_ssl = false;
    3010             :     }
    3011             : #else
    3012             :     lbeentry.st_ssl = false;
    3013             : #endif
    3014             : 
    3015             : #ifdef ENABLE_GSS
    3016             :     if (MyProcPort && MyProcPort->gss != NULL)
    3017             :     {
    3018             :         lbeentry.st_gss = true;
    3019             :         lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
    3020             :         lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
    3021             : 
    3022             :         if (lgssstatus.gss_auth)
    3023             :             strlcpy(lgssstatus.gss_princ, be_gssapi_get_princ(MyProcPort), NAMEDATALEN);
    3024             :     }
    3025             :     else
    3026             :     {
    3027             :         lbeentry.st_gss = false;
    3028             :     }
    3029             : #else
    3030       12674 :     lbeentry.st_gss = false;
    3031             : #endif
    3032             : 
    3033       12674 :     lbeentry.st_state = STATE_UNDEFINED;
    3034       12674 :     lbeentry.st_progress_command = PROGRESS_COMMAND_INVALID;
    3035       12674 :     lbeentry.st_progress_command_target = InvalidOid;
    3036             : 
    3037             :     /*
    3038             :      * we don't zero st_progress_param here to save cycles; nobody should
    3039             :      * examine it until st_progress_command has been set to something other
    3040             :      * than PROGRESS_COMMAND_INVALID
    3041             :      */
    3042             : 
    3043             :     /*
    3044             :      * We're ready to enter the critical section that fills the shared-memory
    3045             :      * status entry.  We follow the protocol of bumping st_changecount before
    3046             :      * and after; and make sure it's even afterwards.  We use a volatile
    3047             :      * pointer here to ensure the compiler doesn't try to get cute.
    3048             :      */
    3049       12674 :     PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
    3050             : 
    3051             :     /* make sure we'll memcpy the same st_changecount back */
    3052       12674 :     lbeentry.st_changecount = vbeentry->st_changecount;
    3053             : 
    3054       12674 :     memcpy(unvolatize(PgBackendStatus *, vbeentry),
    3055             :            &lbeentry,
    3056             :            sizeof(PgBackendStatus));
    3057             : 
    3058             :     /*
    3059             :      * We can write the out-of-line strings and structs using the pointers
    3060             :      * that are in lbeentry; this saves some de-volatilizing messiness.
    3061             :      */
    3062       12674 :     lbeentry.st_appname[0] = '\0';
    3063       12674 :     if (MyProcPort && MyProcPort->remote_hostname)
    3064          62 :         strlcpy(lbeentry.st_clienthostname, MyProcPort->remote_hostname,
    3065             :                 NAMEDATALEN);
    3066             :     else
    3067       12612 :         lbeentry.st_clienthostname[0] = '\0';
    3068       12674 :     lbeentry.st_activity_raw[0] = '\0';
    3069             :     /* Also make sure the last byte in each string area is always 0 */
    3070       12674 :     lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
    3071       12674 :     lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
    3072       12674 :     lbeentry.st_activity_raw[pgstat_track_activity_query_size - 1] = '\0';
    3073             : 
    3074             : #ifdef USE_SSL
    3075       12674 :     memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
    3076             : #endif
    3077             : #ifdef ENABLE_GSS
    3078             :     memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
    3079             : #endif
    3080             : 
    3081       12674 :     PGSTAT_END_WRITE_ACTIVITY(vbeentry);
    3082             : 
    3083             :     /* Update app name to current GUC setting */
    3084       12674 :     if (application_name)
    3085       12674 :         pgstat_report_appname(application_name);
    3086       12674 : }
    3087             : 
    3088             : /*
    3089             :  * Shut down a single backend's statistics reporting at process exit.
    3090             :  *
    3091             :  * Flush any remaining statistics counts out to the collector.
    3092             :  * Without this, operations triggered during backend exit (such as
    3093             :  * temp table deletions) won't be counted.
    3094             :  *
    3095             :  * Lastly, clear out our entry in the PgBackendStatus array.
    3096             :  */
    3097             : static void
    3098       12742 : pgstat_beshutdown_hook(int code, Datum arg)
    3099             : {
    3100       12742 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3101             : 
    3102             :     /*
    3103             :      * If we got as far as discovering our own database ID, we can report what
    3104             :      * we did to the collector.  Otherwise, we'd be sending an invalid
    3105             :      * database ID, so forget it.  (This means that accesses to pg_database
    3106             :      * during failed backend starts might never get counted.)
    3107             :      */
    3108       12742 :     if (OidIsValid(MyDatabaseId))
    3109        9516 :         pgstat_report_stat(true);
    3110             : 
    3111             :     /*
    3112             :      * Clear my status entry, following the protocol of bumping st_changecount
    3113             :      * before and after.  We use a volatile pointer here to ensure the
    3114             :      * compiler doesn't try to get cute.
    3115             :      */
    3116       12742 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3117             : 
    3118       12742 :     beentry->st_procpid = 0; /* mark invalid */
    3119             : 
    3120       12742 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3121       12742 : }
    3122             : 
    3123             : 
    3124             : /* ----------
    3125             :  * pgstat_report_activity() -
    3126             :  *
    3127             :  *  Called from tcop/postgres.c to report what the backend is actually doing
    3128             :  *  (but note cmd_str can be NULL for certain cases).
    3129             :  *
    3130             :  * All updates of the status entry follow the protocol of bumping
    3131             :  * st_changecount before and after.  We use a volatile pointer here to
    3132             :  * ensure the compiler doesn't try to get cute.
    3133             :  * ----------
    3134             :  */
    3135             : void
    3136     1015536 : pgstat_report_activity(BackendState state, const char *cmd_str)
    3137             : {
    3138     1015536 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3139             :     TimestampTz start_timestamp;
    3140             :     TimestampTz current_timestamp;
    3141     1015536 :     int         len = 0;
    3142             : 
    3143             :     TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
    3144             : 
    3145     1015536 :     if (!beentry)
    3146           0 :         return;
    3147             : 
    3148     1015536 :     if (!pgstat_track_activities)
    3149             :     {
    3150           0 :         if (beentry->st_state != STATE_DISABLED)
    3151             :         {
    3152           0 :             volatile PGPROC *proc = MyProc;
    3153             : 
    3154             :             /*
    3155             :              * track_activities is disabled, but we last reported a
    3156             :              * non-disabled state.  As our final update, change the state and
    3157             :              * clear fields we will not be updating anymore.
    3158             :              */
    3159           0 :             PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3160           0 :             beentry->st_state = STATE_DISABLED;
    3161           0 :             beentry->st_state_start_timestamp = 0;
    3162           0 :             beentry->st_activity_raw[0] = '\0';
    3163           0 :             beentry->st_activity_start_timestamp = 0;
    3164             :             /* st_xact_start_timestamp and wait_event_info are also disabled */
    3165           0 :             beentry->st_xact_start_timestamp = 0;
    3166           0 :             proc->wait_event_info = 0;
    3167           0 :             PGSTAT_END_WRITE_ACTIVITY(beentry);
    3168             :         }
    3169           0 :         return;
    3170             :     }
    3171             : 
    3172             :     /*
    3173             :      * To minimize the time spent modifying the entry, and avoid risk of
    3174             :      * errors inside the critical section, fetch all the needed data first.
    3175             :      */
    3176     1015536 :     start_timestamp = GetCurrentStatementStartTimestamp();
    3177     1015536 :     if (cmd_str != NULL)
    3178             :     {
    3179             :         /*
    3180             :          * Compute length of to-be-stored string unaware of multi-byte
    3181             :          * characters. For speed reasons that'll get corrected on read, rather
    3182             :          * than computed every write.
    3183             :          */
    3184      515142 :         len = Min(strlen(cmd_str), pgstat_track_activity_query_size - 1);
    3185             :     }
    3186     1015536 :     current_timestamp = GetCurrentTimestamp();
    3187             : 
    3188             :     /*
    3189             :      * Now update the status entry
    3190             :      */
    3191     1015536 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3192             : 
    3193     1015536 :     beentry->st_state = state;
    3194     1015536 :     beentry->st_state_start_timestamp = current_timestamp;
    3195             : 
    3196     1015536 :     if (cmd_str != NULL)
    3197             :     {
    3198      515142 :         memcpy((char *) beentry->st_activity_raw, cmd_str, len);
    3199      515142 :         beentry->st_activity_raw[len] = '\0';
    3200      515142 :         beentry->st_activity_start_timestamp = start_timestamp;
    3201             :     }
    3202             : 
    3203     1015536 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3204             : }
    3205             : 
    3206             : /*-----------
    3207             :  * pgstat_progress_start_command() -
    3208             :  *
    3209             :  * Set st_progress_command (and st_progress_command_target) in own backend
    3210             :  * entry.  Also, zero-initialize st_progress_param array.
    3211             :  *-----------
    3212             :  */
    3213             : void
    3214      132364 : pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
    3215             : {
    3216      132364 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3217             : 
    3218      132364 :     if (!beentry || !pgstat_track_activities)
    3219       41528 :         return;
    3220             : 
    3221       90836 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3222       90836 :     beentry->st_progress_command = cmdtype;
    3223       90836 :     beentry->st_progress_command_target = relid;
    3224     1907556 :     MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
    3225       90836 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3226             : }
    3227             : 
    3228             : /*-----------
    3229             :  * pgstat_progress_update_param() -
    3230             :  *
    3231             :  * Update index'th member in st_progress_param[] of own backend entry.
    3232             :  *-----------
    3233             :  */
    3234             : void
    3235    19532784 : pgstat_progress_update_param(int index, int64 val)
    3236             : {
    3237    19532784 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3238             : 
    3239             :     Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
    3240             : 
    3241    19532784 :     if (!beentry || !pgstat_track_activities)
    3242     7739244 :         return;
    3243             : 
    3244    11793540 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3245    11793540 :     beentry->st_progress_param[index] = val;
    3246    11793540 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3247             : }
    3248             : 
    3249             : /*-----------
    3250             :  * pgstat_progress_update_multi_param() -
    3251             :  *
    3252             :  * Update multiple members in st_progress_param[] of own backend entry.
    3253             :  * This is atomic; readers won't see intermediate states.
    3254             :  *-----------
    3255             :  */
    3256             : void
    3257      613346 : pgstat_progress_update_multi_param(int nparam, const int *index,
    3258             :                                    const int64 *val)
    3259             : {
    3260      613346 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3261             :     int         i;
    3262             : 
    3263      613346 :     if (!beentry || !pgstat_track_activities || nparam == 0)
    3264      107400 :         return;
    3265             : 
    3266      505946 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3267             : 
    3268     1383658 :     for (i = 0; i < nparam; ++i)
    3269             :     {
    3270             :         Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
    3271             : 
    3272      877712 :         beentry->st_progress_param[index[i]] = val[i];
    3273             :     }
    3274             : 
    3275      505946 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3276             : }
    3277             : 
    3278             : /*-----------
    3279             :  * pgstat_progress_end_command() -
    3280             :  *
    3281             :  * Reset st_progress_command (and st_progress_command_target) in own backend
    3282             :  * entry.  This signals the end of the command.
    3283             :  *-----------
    3284             :  */
    3285             : void
    3286      155294 : pgstat_progress_end_command(void)
    3287             : {
    3288      155294 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3289             : 
    3290      155294 :     if (!beentry || !pgstat_track_activities)
    3291       41528 :         return;
    3292             : 
    3293      113766 :     if (beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
    3294       22986 :         return;
    3295             : 
    3296       90780 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3297       90780 :     beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
    3298       90780 :     beentry->st_progress_command_target = InvalidOid;
    3299       90780 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3300             : }
    3301             : 
    3302             : /* ----------
    3303             :  * pgstat_report_appname() -
    3304             :  *
    3305             :  *  Called to update our application name.
    3306             :  * ----------
    3307             :  */
    3308             : void
    3309       24116 : pgstat_report_appname(const char *appname)
    3310             : {
    3311       24116 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3312             :     int         len;
    3313             : 
    3314       24116 :     if (!beentry)
    3315        2184 :         return;
    3316             : 
    3317             :     /* This should be unnecessary if GUC did its job, but be safe */
    3318       21932 :     len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
    3319             : 
    3320             :     /*
    3321             :      * Update my status entry, following the protocol of bumping
    3322             :      * st_changecount before and after.  We use a volatile pointer here to
    3323             :      * ensure the compiler doesn't try to get cute.
    3324             :      */
    3325       21932 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3326             : 
    3327       21932 :     memcpy((char *) beentry->st_appname, appname, len);
    3328       21932 :     beentry->st_appname[len] = '\0';
    3329             : 
    3330       21932 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3331             : }
    3332             : 
    3333             : /*
    3334             :  * Report current transaction start timestamp as the specified value.
    3335             :  * Zero means there is no active transaction.
    3336             :  */
    3337             : void
    3338      989412 : pgstat_report_xact_timestamp(TimestampTz tstamp)
    3339             : {
    3340      989412 :     volatile PgBackendStatus *beentry = MyBEEntry;
    3341             : 
    3342      989412 :     if (!pgstat_track_activities || !beentry)
    3343         716 :         return;
    3344             : 
    3345             :     /*
    3346             :      * Update my status entry, following the protocol of bumping
    3347             :      * st_changecount before and after.  We use a volatile pointer here to
    3348             :      * ensure the compiler doesn't try to get cute.
    3349             :      */
    3350      988696 :     PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
    3351             : 
    3352      988696 :     beentry->st_xact_start_timestamp = tstamp;
    3353             : 
    3354      988696 :     PGSTAT_END_WRITE_ACTIVITY(beentry);
    3355             : }
    3356             : 
    3357             : /* ----------
    3358             :  * pgstat_read_current_status() -
    3359             :  *
    3360             :  *  Copy the current contents of the PgBackendStatus array to local memory,
    3361             :  *  if not already done in this transaction.
    3362             :  * ----------
    3363             :  */
    3364             : static void
    3365        2534 : pgstat_read_current_status(void)
    3366             : {
    3367             :     volatile PgBackendStatus *beentry;
    3368             :     LocalPgBackendStatus *localtable;
    3369             :     LocalPgBackendStatus *localentry;
    3370             :     char       *localappname,
    3371             :                *localclienthostname,
    3372             :                *localactivity;
    3373             : #ifdef USE_SSL
    3374             :     PgBackendSSLStatus *localsslstatus;
    3375             : #endif
    3376             : #ifdef ENABLE_GSS
    3377             :     PgBackendGSSStatus *localgssstatus;
    3378             : #endif
    3379             :     int         i;
    3380             : 
    3381             :     Assert(!pgStatRunningInCollector);
    3382        2534 :     if (localBackendStatusTable)
    3383        2234 :         return;                 /* already done */
    3384             : 
    3385         300 :     pgstat_setup_memcxt();
    3386             : 
    3387             :     /*
    3388             :      * Allocate storage for local copy of state data.  We can presume that
    3389             :      * none of these requests overflow size_t, because we already calculated
    3390             :      * the same values using mul_size during shmem setup.  However, with
    3391             :      * probably-silly values of pgstat_track_activity_query_size and
    3392             :      * max_connections, the localactivity buffer could exceed 1GB, so use
    3393             :      * "huge" allocation for that one.
    3394             :      */
    3395             :     localtable = (LocalPgBackendStatus *)
    3396         300 :         MemoryContextAlloc(pgStatLocalContext,
    3397         300 :                            sizeof(LocalPgBackendStatus) * NumBackendStatSlots);
    3398             :     localappname = (char *)
    3399         300 :         MemoryContextAlloc(pgStatLocalContext,
    3400         300 :                            NAMEDATALEN * NumBackendStatSlots);
    3401             :     localclienthostname = (char *)
    3402         300 :         MemoryContextAlloc(pgStatLocalContext,
    3403         300 :                            NAMEDATALEN * NumBackendStatSlots);
    3404             :     localactivity = (char *)
    3405         300 :         MemoryContextAllocHuge(pgStatLocalContext,
    3406         300 :                                pgstat_track_activity_query_size * NumBackendStatSlots);
    3407             : #ifdef USE_SSL
    3408             :     localsslstatus = (PgBackendSSLStatus *)
    3409         300 :         MemoryContextAlloc(pgStatLocalContext,
    3410         300 :                            sizeof(PgBackendSSLStatus) * NumBackendStatSlots);
    3411             : #endif
    3412             : #ifdef ENABLE_GSS
    3413             :     localgssstatus = (PgBackendGSSStatus *)
    3414             :         MemoryContextAlloc(pgStatLocalContext,
    3415             :                            sizeof(PgBackendGSSStatus) * NumBackendStatSlots);
    3416             : #endif
    3417             : 
    3418         300 :     localNumBackends = 0;
    3419             : 
    3420         300 :     beentry = BackendStatusArray;
    3421         300 :     localentry = localtable;
    3422       12314 :     for (i = 1; i <= NumBackendStatSlots; i++)
    3423             :     {
    3424             :         /*
    3425             :          * Follow the protocol of retrying if st_changecount changes while we
    3426             :          * copy the entry, or if it's odd.  (The check for odd is needed to
    3427             :          * cover the case where we are able to completely copy the entry while
    3428             :          * the source backend is between increment steps.)  We use a volatile
    3429             :          * pointer here to ensure the compiler doesn't try to get cute.
    3430             :          */
    3431             :         for (;;)
    3432           0 :         {
    3433             :             int         before_changecount;
    3434             :             int         after_changecount;
    3435             : 
    3436       12014 :             pgstat_begin_read_activity(beentry, before_changecount);
    3437             : 
    3438       12014 :             localentry->backendStatus.st_procpid = beentry->st_procpid;
    3439             :             /* Skip all the data-copying work if entry is not in use */
    3440       12014 :             if (localentry->backendStatus.st_procpid > 0)
    3441             :             {
    3442        2234 :                 memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
    3443             : 
    3444             :                 /*
    3445             :                  * For each PgBackendStatus field that is a pointer, copy the
    3446             :                  * pointed-to data, then adjust the local copy of the pointer
    3447             :                  * field to point at the local copy of the data.
    3448             :                  *
    3449             :                  * strcpy is safe even if the string is modified concurrently,
    3450             :                  * because there's always a \0 at the end of the buffer.
    3451             :                  */
    3452        2234 :                 strcpy(localappname, (char *) beentry->st_appname);
    3453        2234 :                 localentry->backendStatus.st_appname = localappname;
    3454        2234 :                 strcpy(localclienthostname, (char *) beentry->st_clienthostname);
    3455        2234 :                 localentry->backendStatus.st_clienthostname = localclienthostname;
    3456        2234 :                 strcpy(localactivity, (char *) beentry->st_activity_raw);
    3457        2234 :                 localentry->backendStatus.st_activity_raw = localactivity;
    3458             : #ifdef USE_SSL
    3459        2234 :                 if (beentry->st_ssl)
    3460             :                 {
    3461           4 :                     memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
    3462           4 :                     localentry->backendStatus.st_sslstatus = localsslstatus;
    3463             :                 }
    3464             : #endif
    3465             : #ifdef ENABLE_GSS
    3466             :                 if (beentry->st_gss)
    3467             :                 {
    3468             :                     memcpy(localgssstatus, beentry->st_gssstatus, sizeof(PgBackendGSSStatus));
    3469             :                     localentry->backendStatus.st_gssstatus = localgssstatus;
    3470             :                 }
    3471             : #endif
    3472             :             }
    3473             : 
    3474       12014 :             pgstat_end_read_activity(beentry, after_changecount);
    3475             : 
    3476       12014 :             if (pgstat_read_activity_complete(before_changecount,
    3477             :                                               after_changecount))
    3478       12014 :                 break;
    3479             : 
    3480             :             /* Make sure we can break out of loop if stuck... */
    3481           0 :             CHECK_FOR_INTERRUPTS();
    3482             :         }
    3483             : 
    3484       12014 :         beentry++;
    3485             :         /* Only valid entries get included into the local array */
    3486       12014 :         if (localentry->backendStatus.st_procpid > 0)
    3487             :         {
    3488        2234 :             BackendIdGetTransactionIds(i,
    3489             :                                        &localentry->backend_xid,
    3490             :                                        &localentry->backend_xmin);
    3491             : 
    3492        2234 :             localentry++;
    3493        2234 :             localappname += NAMEDATALEN;
    3494        2234 :             localclienthostname += NAMEDATALEN;
    3495        2234 :             localactivity += pgstat_track_activity_query_size;
    3496             : #ifdef USE_SSL
    3497        2234 :             localsslstatus++;
    3498             : #endif
    3499             : #ifdef ENABLE_GSS
    3500             :             localgssstatus++;
    3501             : #endif
    3502        2234 :             localNumBackends++;
    3503             :         }
    3504             :     }
    3505             : 
    3506             :     /* Set the pointer only after completion of a valid table */
    3507         300 :     localBackendStatusTable = localtable;
    3508             : }
    3509             : 
    3510             : /* ----------
    3511             :  * pgstat_get_wait_event_type() -
    3512             :  *
    3513             :  *  Return a string representing the current wait event type, backend is
    3514             :  *  waiting on.
    3515             :  */
    3516             : const char *
    3517        2202 : pgstat_get_wait_event_type(uint32 wait_event_info)
    3518             : {
    3519             :     uint32      classId;
    3520             :     const char *event_type;
    3521             : 
    3522             :     /* report process as not waiting. */
    3523        2202 :     if (wait_event_info == 0)
    3524         308 :         return NULL;
    3525             : 
    3526        1894 :     classId = wait_event_info & 0xFF000000;
    3527             : 
    3528        1894 :     switch (classId)
    3529             :     {
    3530           0 :         case PG_WAIT_LWLOCK:
    3531           0 :             event_type = "LWLock";
    3532           0 :             break;
    3533           6 :         case PG_WAIT_LOCK:
    3534           6 :             event_type = "Lock";
    3535           6 :             break;
    3536           0 :         case PG_WAIT_BUFFER_PIN:
    3537           0 :             event_type = "BufferPin";
    3538           0 :             break;
    3539        1628 :         case PG_WAIT_ACTIVITY:
    3540        1628 :             event_type = "Activity";
    3541        1628 :             break;
    3542         260 :         case PG_WAIT_CLIENT:
    3543         260 :             event_type = "Client";
    3544         260 :             break;
    3545           0 :         case PG_WAIT_EXTENSION:
    3546           0 :             event_type = "Extension";
    3547           0 :             break;
    3548           0 :         case PG_WAIT_IPC:
    3549           0 :             event_type = "IPC";
    3550           0 :             break;
    3551           0 :         case PG_WAIT_TIMEOUT:
    3552           0 :             event_type = "Timeout";
    3553           0 :             break;
    3554           0 :         case PG_WAIT_IO:
    3555           0 :             event_type = "IO";
    3556           0 :             break;
    3557           0 :         default:
    3558           0 :             event_type = "???";
    3559           0 :             break;
    3560             :     }
    3561             : 
    3562        1894 :     return event_type;
    3563             : }
    3564             : 
    3565             : /* ----------
    3566             :  * pgstat_get_wait_event() -
    3567             :  *
    3568             :  *  Return a string representing the current wait event, backend is
    3569             :  *  waiting on.
    3570             :  */
    3571             : const char *
    3572        2202 : pgstat_get_wait_event(uint32 wait_event_info)
    3573             : {
    3574             :     uint32      classId;
    3575             :     uint16      eventId;
    3576             :     const char *event_name;
    3577             : 
    3578             :     /* report process as not waiting. */
    3579        2202 :     if (wait_event_info == 0)
    3580         308 :         return NULL;
    3581             : 
    3582        1894 :     classId = wait_event_info & 0xFF000000;
    3583        1894 :     eventId = wait_event_info & 0x0000FFFF;
    3584             : 
    3585        1894 :     switch (classId)
    3586             :     {
    3587           0 :         case PG_WAIT_LWLOCK:
    3588           0 :             event_name = GetLWLockIdentifier(classId, eventId);
    3589           0 :             break;
    3590           6 :         case PG_WAIT_LOCK:
    3591           6 :             event_name = GetLockNameFromTagType(eventId);
    3592           6 :             break;
    3593           0 :         case PG_WAIT_BUFFER_PIN:
    3594           0 :             event_name = "BufferPin";
    3595           0 :             break;
    3596        1628 :         case PG_WAIT_ACTIVITY:
    3597             :             {
    3598        1628 :                 WaitEventActivity w = (WaitEventActivity) wait_event_info;
    3599             : 
    3600        1628 :                 event_name = pgstat_get_wait_activity(w);
    3601        1628 :                 break;
    3602             :             }
    3603         260 :         case PG_WAIT_CLIENT:
    3604             :             {
    3605         260 :                 WaitEventClient w = (WaitEventClient) wait_event_info;
    3606             : 
    3607         260 :                 event_name = pgstat_get_wait_client(w);
    3608         260 :                 break;
    3609             :             }
    3610           0 :         case PG_WAIT_EXTENSION:
    3611           0 :             event_name = "Extension";
    3612           0 :             break;
    3613           0 :         case PG_WAIT_IPC:
    3614             :             {
    3615           0 :                 WaitEventIPC w = (WaitEventIPC) wait_event_info;
    3616             : 
    3617           0 :                 event_name = pgstat_get_wait_ipc(w);
    3618           0 :                 break;
    3619             :             }
    3620           0 :         case PG_WAIT_TIMEOUT:
    3621             :             {
    3622           0 :                 WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
    3623             : 
    3624           0 :                 event_name = pgstat_get_wait_timeout(w);
    3625           0 :                 break;
    3626             :             }
    3627           0 :         case PG_WAIT_IO:
    3628             :             {
    3629           0 :                 WaitEventIO w = (WaitEventIO) wait_event_info;
    3630             : 
    3631           0 :                 event_name = pgstat_get_wait_io(w);
    3632           0 :                 break;
    3633             :             }
    3634           0 :         default:
    3635           0 :             event_name = "unknown wait event";
    3636           0 :             break;
    3637             :     }
    3638             : 
    3639        1894 :     return event_name;
    3640             : }
    3641             : 
    3642             : /* ----------
    3643             :  * pgstat_get_wait_activity() -
    3644             :  *
    3645             :  * Convert WaitEventActivity to string.
    3646             :  * ----------
    3647             :  */
    3648             : static const char *
    3649        1628 : pgstat_get_wait_activity(WaitEventActivity w)
    3650             : {
    3651        1628 :     const char *event_name = "unknown wait event";
    3652             : 
    3653        1628 :     switch (w)
    3654             :     {
    3655           0 :         case WAIT_EVENT_ARCHIVER_MAIN:
    3656           0 :             event_name = "ArchiverMain";
    3657           0 :             break;
    3658         282 :         case WAIT_EVENT_AUTOVACUUM_MAIN:
    3659         282 :             event_name = "AutoVacuumMain";
    3660         282 :             break;
    3661          30 :         case WAIT_EVENT_BGWRITER_HIBERNATE:
    3662          30 :             event_name = "BgWriterHibernate";
    3663          30 :             break;
    3664         264 :         case WAIT_EVENT_BGWRITER_MAIN:
    3665         264 :             event_name = "BgWriterMain";
    3666         264 :             break;
    3667         288 :         case WAIT_EVENT_CHECKPOINTER_MAIN:
    3668         288 :             event_name = "CheckpointerMain";
    3669         288 :             break;
    3670           0 :         case WAIT_EVENT_LOGICAL_APPLY_MAIN:
    3671           0 :             event_name = "LogicalApplyMain";
    3672           0 :             break;
    3673         286 :         case WAIT_EVENT_LOGICAL_LAUNCHER_MAIN:
    3674         286 :             event_name = "LogicalLauncherMain";
    3675         286 :             break;
    3676           0 :         case WAIT_EVENT_PGSTAT_MAIN:
    3677           0 :             event_name = "PgStatMain";
    3678           0 :             break;
    3679           8 :         case WAIT_EVENT_RECOVERY_WAL_STREAM:
    3680           8 :             event_name = "RecoveryWalStream";
    3681           8 :             break;
    3682           0 :         case WAIT_EVENT_SYSLOGGER_MAIN:
    3683           0 :             event_name = "SysLoggerMain";
    3684           0 :             break;
    3685           8 :         case WAIT_EVENT_WAL_RECEIVER_MAIN:
    3686           8 :             event_name = "WalReceiverMain";
    3687           8 :             break;
    3688         176 :         case WAIT_EVENT_WAL_SENDER_MAIN:
    3689         176 :             event_name = "WalSenderMain";
    3690         176 :             break;
    3691         286 :         case WAIT_EVENT_WAL_WRITER_MAIN:
    3692         286 :             event_name = "WalWriterMain";
    3693         286 :             break;
    3694             :             /* no default case, so that compiler will warn */
    3695             :     }
    3696             : 
    3697        1628 :     return event_name;
    3698             : }
    3699             : 
    3700             : /* ----------
    3701             :  * pgstat_get_wait_client() -
    3702             :  *
    3703             :  * Convert WaitEventClient to string.
    3704             :  * ----------
    3705             :  */
    3706             : static const char *
    3707         260 : pgstat_get_wait_client(WaitEventClient w)
    3708             : {
    3709         260 :     const char *event_name = "unknown wait event";
    3710             : 
    3711         260 :     switch (w)
    3712             :     {
    3713          12 :         case WAIT_EVENT_CLIENT_READ:
    3714          12 :             event_name = "ClientRead";
    3715          12 :             break;
    3716           0 :         case WAIT_EVENT_CLIENT_WRITE:
    3717           0 :             event_name = "ClientWrite";
    3718           0 :             break;
    3719           0 :         case WAIT_EVENT_GSS_OPEN_SERVER:
    3720           0 :             event_name = "GSSOpenServer";
    3721           0 :             break;
    3722           0 :         case WAIT_EVENT_LIBPQWALRECEIVER_CONNECT:
    3723           0 :             event_name = "LibPQWalReceiverConnect";
    3724           0 :             break;
    3725           0 :         case WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE:
    3726           0 :             event_name = "LibPQWalReceiverReceive";
    3727           0 :             break;
    3728           0 :         case WAIT_EVENT_SSL_OPEN_SERVER:
    3729           0 :             event_name = "SSLOpenServer";
    3730           0 :             break;
    3731           0 :         case WAIT_EVENT_WAL_RECEIVER_WAIT_START:
    3732           0 :             event_name = "WalReceiverWaitStart";
    3733           0 :             break;
    3734         248 :         case WAIT_EVENT_WAL_SENDER_WAIT_WAL:
    3735         248 :             event_name = "WalSenderWaitForWAL";
    3736         248 :             break;
    3737           0 :         case WAIT_EVENT_WAL_SENDER_WRITE_DATA:
    3738           0 :             event_name = "WalSenderWriteData";
    3739           0 :             break;
    3740             :             /* no default case, so that compiler will warn */
    3741             :     }
    3742             : 
    3743         260 :     return event_name;
    3744             : }
    3745             : 
    3746             : /* ----------
    3747             :  * pgstat_get_wait_ipc() -
    3748             :  *
    3749             :  * Convert WaitEventIPC to string.
    3750             :  * ----------
    3751             :  */
    3752             : static const char *
    3753           0 : pgstat_get_wait_ipc(WaitEventIPC w)
    3754             : {
    3755           0 :     const char *event_name = "unknown wait event";
    3756             : 
    3757           0 :     switch (w)
    3758             :     {
    3759           0 :         case WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE:
    3760           0 :             event_name = "BackupWaitWalArchive";
    3761           0 :             break;
    3762           0 :         case WAIT_EVENT_BGWORKER_SHUTDOWN:
    3763           0 :             event_name = "BgWorkerShutdown";
    3764           0 :             break;
    3765           0 :         case WAIT_EVENT_BGWORKER_STARTUP:
    3766           0 :             event_name = "BgWorkerStartup";
    3767           0 :             break;
    3768           0 :         case WAIT_EVENT_BTREE_PAGE:
    3769           0 :             event_name = "BtreePage";
    3770           0 :             break;
    3771           0 :         case WAIT_EVENT_CHECKPOINT_DONE:
    3772           0 :             event_name = "CheckpointDone";
    3773           0 :             break;
    3774           0 :         case WAIT_EVENT_CHECKPOINT_START:
    3775           0 :             event_name = "CheckpointStart";
    3776           0 :             break;
    3777           0 :         case WAIT_EVENT_EXECUTE_GATHER:
    3778           0 :             event_name = "ExecuteGather";
    3779           0 :             break;
    3780           0 :         case WAIT_EVENT_HASH_BATCH_ALLOCATE:
    3781           0 :             event_name = "HashBatchAllocate";
    3782           0 :             break;
    3783           0 :         case WAIT_EVENT_HASH_BATCH_ELECT:
    3784           0 :             event_name = "HashBatchElect";
    3785           0 :             break;
    3786           0 :         case WAIT_EVENT_HASH_BATCH_LOAD:
    3787           0 :             event_name = "HashBatchLoad";
    3788           0 :             break;
    3789           0 :         case WAIT_EVENT_HASH_BUILD_ALLOCATE:
    3790           0 :             event_name = "HashBuildAllocate";
    3791           0 :             break;
    3792           0 :         case WAIT_EVENT_HASH_BUILD_ELECT:
    3793           0 :             event_name = "HashBuildElect";
    3794           0 :             break;
    3795           0 :         case WAIT_EVENT_HASH_BUILD_HASH_INNER:
    3796           0 :             event_name = "HashBuildHashInner";
    3797           0 :             break;
    3798           0 :         case WAIT_EVENT_HASH_BUILD_HASH_OUTER:
    3799           0 :             event_name = "HashBuildHashOuter";
    3800           0 :             break;
    3801           0 :         case WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATE:
    3802           0 :             event_name = "HashGrowBatchesAllocate";
    3803           0 :             break;
    3804           0 :         case WAIT_EVENT_HASH_GROW_BATCHES_DECIDE:
    3805           0 :             event_name = "HashGrowBatchesDecide";
    3806           0 :             break;
    3807           0 :         case WAIT_EVENT_HASH_GROW_BATCHES_ELECT:
    3808           0 :             event_name = "HashGrowBatchesElect";
    3809           0 :             break;
    3810           0 :         case WAIT_EVENT_HASH_GROW_BATCHES_FINISH:
    3811           0 :             event_name = "HashGrowBatchesFinish";
    3812           0 :             break;
    3813           0 :         case WAIT_EVENT_HASH_GROW_BATCHES_REPARTITION:
    3814           0 :             event_name = "HashGrowBatchesRepartition";
    3815           0 :             break;
    3816           0 :         case WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATE:
    3817           0 :             event_name = "HashGrowBucketsAllocate";
    3818           0 :             break;
    3819           0 :         case WAIT_EVENT_HASH_GROW_BUCKETS_ELECT:
    3820           0 :             event_name = "HashGrowBucketsElect";
    3821           0 :             break;
    3822           0 :         case WAIT_EVENT_HASH_GROW_BUCKETS_REINSERT:
    3823           0 :             event_name = "HashGrowBucketsReinsert";
    3824           0 :             break;
    3825           0 :         case WAIT_EVENT_LOGICAL_SYNC_DATA:
    3826           0 :             event_name = "LogicalSyncData";
    3827           0 :             break;
    3828           0 :         case WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE:
    3829           0 :             event_name = "LogicalSyncStateChange";
    3830           0 :             break;
    3831           0 :         case WAIT_EVENT_MQ_INTERNAL:
    3832           0 :             event_name = "MessageQueueInternal";
    3833           0 :             break;
    3834           0 :         case WAIT_EVENT_MQ_PUT_MESSAGE:
    3835           0 :             event_name = "MessageQueuePutMessage";
    3836           0 :             break;
    3837           0 :         case WAIT_EVENT_MQ_RECEIVE:
    3838           0 :             event_name = "MessageQueueReceive";
    3839           0 :             break;
    3840           0 :         case WAIT_EVENT_MQ_SEND:
    3841           0 :             event_name = "MessageQueueSend";
    3842           0 :             break;
    3843           0 :         case WAIT_EVENT_PARALLEL_BITMAP_SCAN:
    3844           0 :             event_name = "ParallelBitmapScan";
    3845           0 :             break;
    3846           0 :         case WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN:
    3847           0 :             event_name = "ParallelCreateIndexScan";
    3848           0 :             break;
    3849           0 :         case WAIT_EVENT_PARALLEL_FINISH:
    3850           0 :             event_name = "ParallelFinish";
    3851           0 :             break;
    3852           0 :         case WAIT_EVENT_PROCARRAY_GROUP_UPDATE:
    3853           0 :             event_name = "ProcArrayGroupUpdate";
    3854           0 :             break;
    3855           0 :         case WAIT_EVENT_PROC_SIGNAL_BARRIER:
    3856           0 :             event_name = "ProcSignalBarrier";
    3857           0 :             break;
    3858           0 :         case WAIT_EVENT_PROMOTE:
    3859           0 :             event_name = "Promote";
    3860           0 :             break;
    3861           0 :         case WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT:
    3862           0 :             event_name = "RecoveryConflictSnapshot";
    3863           0 :             break;
    3864           0 :         case WAIT_EVENT_RECOVERY_CONFLICT_TABLESPACE:
    3865           0 :             event_name = "RecoveryConflictTablespace";
    3866           0 :             break;
    3867           0 :         case WAIT_EVENT_RECOVERY_PAUSE:
    3868           0 :             event_name = "RecoveryPause";
    3869           0 :             break;
    3870           0 :         case WAIT_EVENT_REPLICATION_ORIGIN_DROP:
    3871           0 :             event_name = "ReplicationOriginDrop";
    3872           0 :             break;
    3873           0 :         case WAIT_EVENT_REPLICATION_SLOT_DROP:
    3874           0 :             event_name = "ReplicationSlotDrop";
    3875           0 :             break;
    3876           0 :         case WAIT_EVENT_SAFE_SNAPSHOT:
    3877           0 :             event_name = "SafeSnapshot";
    3878           0 :             break;
    3879           0 :         case WAIT_EVENT_SYNC_REP:
    3880           0 :             event_name = "SyncRep";
    3881           0 :             break;
    3882           0 :         case WAIT_EVENT_XACT_GROUP_UPDATE:
    3883           0 :             event_name = "XactGroupUpdate";
    3884           0 :             break;
    3885             :             /* no default case, so that compiler will warn */
    3886             :     }
    3887             : 
    3888           0 :     return event_name;
    3889             : }
    3890             : 
    3891             : /* ----------
    3892             :  * pgstat_get_wait_timeout() -
    3893             :  *
    3894             :  * Convert WaitEventTimeout to string.
    3895             :  * ----------
    3896             :  */
    3897             : static const char *
    3898           0 : pgstat_get_wait_timeout(WaitEventTimeout w)
    3899             : {
    3900           0 :     const char *event_name = "unknown wait event";
    3901             : 
    3902           0 :     switch (w)
    3903             :     {
    3904           0 :         case WAIT_EVENT_BASE_BACKUP_THROTTLE:
    3905           0 :             event_name = "BaseBackupThrottle";
    3906           0 :             break;
    3907           0 :         case WAIT_EVENT_PG_SLEEP:
    3908           0 :             event_name = "PgSleep";
    3909           0 :             break;
    3910           0 :         case WAIT_EVENT_RECOVERY_APPLY_DELAY:
    3911           0 :             event_name = "RecoveryApplyDelay";
    3912           0 :             break;
    3913           0 :         case WAIT_EVENT_RECOVERY_RETRIEVE_RETRY_INTERVAL:
    3914           0 :             event_name = "RecoveryRetrieveRetryInterval";
    3915           0 :             break;
    3916           0 :         case WAIT_EVENT_VACUUM_DELAY:
    3917           0 :             event_name = "VacuumDelay";
    3918           0 :             break;
    3919             :             /* no default case, so that compiler will warn */
    3920             :     }
    3921             : 
    3922           0 :     return event_name;
    3923             : }
    3924             : 
    3925             : /* ----------
    3926             :  * pgstat_get_wait_io() -
    3927             :  *
    3928             :  * Convert WaitEventIO to string.
    3929             :  * ----------
    3930             :  */
    3931             : static const char *
    3932           0 : pgstat_get_wait_io(WaitEventIO w)
    3933             : {
    3934           0 :     const char *event_name = "unknown wait event";
    3935             : 
    3936           0 :     switch (w)
    3937             :     {
    3938           0 :         case WAIT_EVENT_BUFFILE_READ:
    3939           0 :             event_name = "BufFileRead";
    3940           0 :             break;
    3941           0 :         case WAIT_EVENT_BUFFILE_WRITE:
    3942           0 :             event_name = "BufFileWrite";
    3943           0 :             break;
    3944           0 :         case WAIT_EVENT_CONTROL_FILE_READ:
    3945           0 :             event_name = "ControlFileRead";
    3946           0 :             break;
    3947           0 :         case WAIT_EVENT_CONTROL_FILE_SYNC:
    3948           0 :             event_name = "ControlFileSync";
    3949           0 :             break;
    3950           0 :         case WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE:
    3951           0 :             event_name = "ControlFileSyncUpdate";
    3952           0 :             break;
    3953           0 :         case WAIT_EVENT_CONTROL_FILE_WRITE:
    3954           0 :             event_name = "ControlFileWrite";
    3955           0 :             break;
    3956           0 :         case WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE:
    3957           0 :             event_name = "ControlFileWriteUpdate";
    3958           0 :             break;
    3959           0 :         case WAIT_EVENT_COPY_FILE_READ:
    3960           0 :             event_name = "CopyFileRead";
    3961           0 :             break;
    3962           0 :         case WAIT_EVENT_COPY_FILE_WRITE:
    3963           0 :             event_name = "CopyFileWrite";
    3964           0 :             break;
    3965           0 :         case WAIT_EVENT_DATA_FILE_EXTEND:
    3966           0 :             event_name = "DataFileExtend";
    3967           0 :             break;
    3968           0 :         case WAIT_EVENT_DATA_FILE_FLUSH:
    3969           0 :             event_name = "DataFileFlush";
    3970           0 :             break;
    3971           0 :         case WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC:
    3972           0 :             event_name = "DataFileImmediateSync";
    3973           0 :             break;
    3974           0 :         case WAIT_EVENT_DATA_FILE_PREFETCH:
    3975           0 :             event_name = "DataFilePrefetch";
    3976           0 :             break;
    3977           0 :         case WAIT_EVENT_DATA_FILE_READ:
    3978           0 :             event_name = "DataFileRead";
    3979           0 :             break;
    3980           0 :         case WAIT_EVENT_DATA_FILE_SYNC:
    3981           0 :             event_name = "DataFileSync";
    3982           0 :             break;
    3983           0 :         case WAIT_EVENT_DATA_FILE_TRUNCATE:
    3984           0 :             event_name = "DataFileTruncate";
    3985           0 :             break;
    3986           0 :         case WAIT_EVENT_DATA_FILE_WRITE:
    3987           0 :             event_name = "DataFileWrite";
    3988           0 :             break;
    3989           0 :         case WAIT_EVENT_DSM_FILL_ZERO_WRITE:
    3990           0 :             event_name = "DSMFillZeroWrite";
    3991           0 :             break;
    3992           0 :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ:
    3993           0 :             event_name = "LockFileAddToDataDirRead";
    3994           0 :             break;
    3995           0 :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC:
    3996           0 :             event_name = "LockFileAddToDataDirSync";
    3997           0 :             break;
    3998           0 :         case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE:
    3999           0 :             event_name = "LockFileAddToDataDirWrite";
    4000           0 :             break;
    4001           0 :         case WAIT_EVENT_LOCK_FILE_CREATE_READ:
    4002           0 :             event_name = "LockFileCreateRead";
    4003           0 :             break;
    4004           0 :         case WAIT_EVENT_LOCK_FILE_CREATE_SYNC:
    4005           0 :             event_name = "LockFileCreateSync";
    4006           0 :             break;
    4007           0 :         case WAIT_EVENT_LOCK_FILE_CREATE_WRITE:
    4008           0 :             event_name = "LockFileCreateWrite";
    4009           0 :             break;
    4010           0 :         case WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ:
    4011           0 :             event_name = "LockFileReCheckDataDirRead";
    4012           0 :             break;
    4013           0 :         case WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC:
    4014           0 :             event_name = "LogicalRewriteCheckpointSync";
    4015           0 :             break;
    4016           0 :         case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC:
    4017           0 :             event_name = "LogicalRewriteMappingSync";
    4018           0 :             break;
    4019           0 :         case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE:
    4020           0 :             event_name = "LogicalRewriteMappingWrite";
    4021           0 :             break;
    4022           0 :         case WAIT_EVENT_LOGICAL_REWRITE_SYNC:
    4023           0 :             event_name = "LogicalRewriteSync";
    4024           0 :             break;
    4025           0 :         case WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE:
    4026           0 :             event_name = "LogicalRewriteTruncate";
    4027           0 :             break;
    4028           0 :         case WAIT_EVENT_LOGICAL_REWRITE_WRITE:
    4029           0 :             event_name = "LogicalRewriteWrite";
    4030           0 :             break;
    4031           0 :         case WAIT_EVENT_RELATION_MAP_READ:
    4032           0 :             event_name = "RelationMapRead";
    4033           0 :             break;
    4034           0 :         case WAIT_EVENT_RELATION_MAP_SYNC:
    4035           0 :             event_name = "RelationMapSync";
    4036           0 :             break;
    4037           0 :         case WAIT_EVENT_RELATION_MAP_WRITE:
    4038           0 :             event_name = "RelationMapWrite";
    4039           0 :             break;
    4040           0 :         case WAIT_EVENT_REORDER_BUFFER_READ:
    4041           0 :             event_name = "ReorderBufferRead";
    4042           0 :             break;
    4043           0 :         case WAIT_EVENT_REORDER_BUFFER_WRITE:
    4044           0 :             event_name = "ReorderBufferWrite";
    4045           0 :             break;
    4046           0 :         case WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ:
    4047           0 :             event_name = "ReorderLogicalMappingRead";
    4048           0 :             break;
    4049           0 :         case WAIT_EVENT_REPLICATION_SLOT_READ:
    4050           0 :             event_name = "ReplicationSlotRead";
    4051           0 :             break;
    4052           0 :         case WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC:
    4053           0 :             event_name = "ReplicationSlotRestoreSync";
    4054           0 :             break;
    4055           0 :         case WAIT_EVENT_REPLICATION_SLOT_SYNC:
    4056           0 :             event_name = "ReplicationSlotSync";
    4057           0 :             break;
    4058           0 :         case WAIT_EVENT_REPLICATION_SLOT_WRITE:
    4059           0 :             event_name = "ReplicationSlotWrite";
    4060           0 :             break;
    4061           0 :         case WAIT_EVENT_SLRU_FLUSH_SYNC:
    4062           0 :             event_name = "SLRUFlushSync";
    4063           0 :             break;
    4064           0 :         case WAIT_EVENT_SLRU_READ:
    4065           0 :             event_name = "SLRURead";
    4066           0 :             break;
    4067           0 :         case WAIT_EVENT_SLRU_SYNC:
    4068           0 :             event_name = "SLRUSync";
    4069           0 :             break;
    4070           0 :         case WAIT_EVENT_SLRU_WRITE:
    4071           0 :             event_name = "SLRUWrite";
    4072           0 :             break;
    4073           0 :         case WAIT_EVENT_SNAPBUILD_READ:
    4074           0 :             event_name = "SnapbuildRead";
    4075           0 :             break;
    4076           0 :         case WAIT_EVENT_SNAPBUILD_SYNC:
    4077           0 :             event_name = "SnapbuildSync";
    4078           0 :             break;
    4079           0 :         case WAIT_EVENT_SNAPBUILD_WRITE:
    4080           0 :             event_name = "SnapbuildWrite";
    4081           0 :             break;
    4082           0 :         case WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC:
    4083           0 :             event_name = "TimelineHistoryFileSync";
    4084           0 :             break;
    4085           0 :         case WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE:
    4086           0 :             event_name = "TimelineHistoryFileWrite";
    4087           0 :             break;
    4088           0 :         case WAIT_EVENT_TIMELINE_HISTORY_READ:
    4089           0 :             event_name = "TimelineHistoryRead";
    4090           0 :             break;
    4091           0 :         case WAIT_EVENT_TIMELINE_HISTORY_SYNC:
    4092           0 :             event_name = "TimelineHistorySync";
    4093           0 :             break;
    4094           0 :         case WAIT_EVENT_TIMELINE_HISTORY_WRITE:
    4095           0 :             event_name = "TimelineHistoryWrite";
    4096           0 :             break;
    4097           0 :         case WAIT_EVENT_TWOPHASE_FILE_READ:
    4098           0 :             event_name = "TwophaseFileRead";
    4099           0 :             break;
    4100           0 :         case WAIT_EVENT_TWOPHASE_FILE_SYNC:
    4101           0 :             event_name = "TwophaseFileSync";
    4102           0 :             break;
    4103           0 :         case WAIT_EVENT_TWOPHASE_FILE_WRITE:
    4104           0 :             event_name = "TwophaseFileWrite";
    4105           0 :             break;
    4106           0 :         case WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ:
    4107           0 :             event_name = "WALSenderTimelineHistoryRead";
    4108           0 :             break;
    4109           0 :         case WAIT_EVENT_WAL_BOOTSTRAP_SYNC:
    4110           0 :             event_name = "WALBootstrapSync";
    4111           0 :             break;
    4112           0 :         case WAIT_EVENT_WAL_BOOTSTRAP_WRITE:
    4113           0 :             event_name = "WALBootstrapWrite";
    4114           0 :             break;
    4115           0 :         case WAIT_EVENT_WAL_COPY_READ:
    4116           0 :             event_name = "WALCopyRead";
    4117           0 :             break;
    4118           0 :         case WAIT_EVENT_WAL_COPY_SYNC:
    4119           0 :             event_name = "WALCopySync";
    4120           0 :             break;
    4121           0 :         case WAIT_EVENT_WAL_COPY_WRITE:
    4122           0 :             event_name = "WALCopyWrite";
    4123           0 :             break;
    4124           0 :         case WAIT_EVENT_WAL_INIT_SYNC:
    4125           0 :             event_name = "WALInitSync";
    4126           0 :             break;
    4127           0 :         case WAIT_EVENT_WAL_INIT_WRITE:
    4128           0 :             event_name = "WALInitWrite";
    4129           0 :             break;
    4130           0 :         case WAIT_EVENT_WAL_READ:
    4131           0 :             event_name = "WALRead";
    4132           0 :             break;
    4133           0 :         case WAIT_EVENT_WAL_SYNC:
    4134           0 :             event_name = "WALSync";
    4135           0 :             break;
    4136           0 :         case WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN:
    4137           0 :             event_name = "WALSyncMethodAssign";
    4138           0 :             break;
    4139           0 :         case WAIT_EVENT_WAL_WRITE:
    4140           0 :             event_name = "WALWrite";
    4141           0 :             break;
    4142             : 
    4143             :             /* no default case, so that compiler will warn */
    4144             :     }
    4145             : 
    4146           0 :     return event_name;
    4147             : }
    4148             : 
    4149             : 
    4150             : /* ----------
    4151             :  * pgstat_get_backend_current_activity() -
    4152             :  *
    4153             :  *  Return a string representing the current activity of the backend with
    4154             :  *  the specified PID.  This looks directly at the BackendStatusArray,
    4155             :  *  and so will provide current information regardless of the age of our
    4156             :  *  transaction's snapshot of the status array.
    4157             :  *
    4158             :  *  It is the caller's responsibility to invoke this only for backends whose
    4159             :  *  state is expected to remain stable while the result is in use.  The
    4160             :  *  only current use is in deadlock reporting, where we can expect that
    4161             :  *  the target backend is blocked on a lock.  (There are corner cases
    4162             :  *  where the target's wait could get aborted while we are looking at it,
    4163             :  *  but the very worst consequence is to return a pointer to a string
    4164             :  *  that's been changed, so we won't worry too much.)
    4165             :  *
    4166             :  *  Note: return strings for special cases match pg_stat_get_backend_activity.
    4167             :  * ----------
    4168             :  */
    4169             : const char *
    4170          20 : pgstat_get_backend_current_activity(int pid, bool checkUser)
    4171             : {
    4172             :     PgBackendStatus *beentry;
    4173             :     int         i;
    4174             : 
    4175          20 :     beentry = BackendStatusArray;
    4176         138 :     for (i = 1; i <= MaxBackends; i++)
    4177             :     {
    4178             :         /*
    4179             :          * Although we expect the target backend's entry to be stable, that
    4180             :          * doesn't imply that anyone else's is.  To avoid identifying the
    4181             :          * wrong backend, while we check for a match to the desired PID we
    4182             :          * must follow the protocol of retrying if st_changecount changes
    4183             :          * while we examine the entry, or if it's odd.  (This might be
    4184             :          * unnecessary, since fetching or storing an int is almost certainly
    4185             :          * atomic, but let's play it safe.)  We use a volatile pointer here to
    4186             :          * ensure the compiler doesn't try to get cute.
    4187             :          */
    4188         138 :         volatile PgBackendStatus *vbeentry = beentry;
    4189             :         bool        found;
    4190             : 
    4191             :         for (;;)
    4192           0 :         {
    4193             :             int         before_changecount;
    4194             :             int         after_changecount;
    4195             : 
    4196         138 :             pgstat_begin_read_activity(vbeentry, before_changecount);
    4197             : 
    4198         138 :             found = (vbeentry->st_procpid == pid);
    4199             : 
    4200         138 :             pgstat_end_read_activity(vbeentry, after_changecount);
    4201             : 
    4202         138 :             if (pgstat_read_activity_complete(before_changecount,
    4203             :                                               after_changecount))
    4204         138 :                 break;
    4205             : 
    4206             :             /* Make sure we can break out of loop if stuck... */
    4207           0 :             CHECK_FOR_INTERRUPTS();
    4208             :         }
    4209             : 
    4210         138 :         if (found)
    4211             :         {
    4212             :             /* Now it is safe to use the non-volatile pointer */
    4213          20 :             if (checkUser && !superuser() && beentry->st_userid != GetUserId())
    4214           0 :                 return "<insufficient privilege>";
    4215          20 :             else if (*(beentry->st_activity_raw) == '\0')
    4216           0 :                 return "<command string not enabled>";
    4217             :             else
    4218             :             {
    4219             :                 /* this'll leak a bit of memory, but that seems acceptable */
    4220          20 :                 return pgstat_clip_activity(beentry->st_activity_raw);
    4221             :             }
    4222             :         }
    4223             : 
    4224         118 :         beentry++;
    4225             :     }
    4226             : 
    4227             :     /* If we get here, caller is in error ... */
    4228           0 :     return "<backend information not available>";
    4229             : }
    4230             : 
    4231             : /* ----------
    4232             :  * pgstat_get_crashed_backend_activity() -
    4233             :  *
    4234             :  *  Return a string representing the current activity of the backend with
    4235             :  *  the specified PID.  Like the function above, but reads shared memory with
    4236             :  *  the expectation that it may be corrupt.  On success, copy the string
    4237             :  *  into the "buffer" argument and return that pointer.  On failure,
    4238             :  *  return NULL.
    4239             :  *
    4240             :  *  This function is only intended to be used by the postmaster to report the
    4241             :  *  query that crashed a backend.  In particular, no attempt is made to
    4242             :  *  follow the correct concurrency protocol when accessing the
    4243             :  *  BackendStatusArray.  But that's OK, in the worst case we'll return a
    4244             :  *  corrupted message.  We also must take care not to trip on ereport(ERROR).
    4245             :  * ----------
    4246             :  */
    4247             : const char *
    4248         824 : pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
    4249             : {
    4250             :     volatile PgBackendStatus *beentry;
    4251             :     int         i;
    4252             : 
    4253         824 :     beentry = BackendStatusArray;
    4254             : 
    4255             :     /*
    4256             :      * We probably shouldn't get here before shared memory has been set up,
    4257             :      * but be safe.
    4258             :      */
    4259         824 :     if (beentry == NULL || BackendActivityBuffer == NULL)
    4260           0 :         return NULL;
    4261             : 
    4262       66288 :     for (i = 1; i <= MaxBackends; i++)
    4263             :     {
    4264       65526 :         if (beentry->st_procpid == pid)
    4265             :         {
    4266             :             /* Read pointer just once, so it can't change after validation */
    4267          62 :             const char *activity = beentry->st_activity_raw;
    4268             :             const char *activity_last;
    4269             : 
    4270             :             /*
    4271             :              * We mustn't access activity string before we verify that it
    4272             :              * falls within the BackendActivityBuffer. To make sure that the
    4273             :              * entire string including its ending is contained within the
    4274             :              * buffer, subtract one activity length from the buffer size.
    4275             :              */
    4276          62 :             activity_last = BackendActivityBuffer + BackendActivityBufferSize
    4277          62 :                 - pgstat_track_activity_query_size;
    4278             : 
    4279          62 :             if (activity < BackendActivityBuffer ||
    4280             :                 activity > activity_last)
    4281           0 :                 return NULL;
    4282             : 
    4283             :             /* If no string available, no point in a report */
    4284          62 :             if (activity[0] == '\0')
    4285          46 :                 return NULL;
    4286             : 
    4287             :             /*
    4288             :              * Copy only ASCII-safe characters so we don't run into encoding
    4289             :              * problems when reporting the message; and be sure not to run off
    4290             :              * the end of memory.  As only ASCII characters are reported, it
    4291             :              * doesn't seem necessary to perform multibyte aware clipping.
    4292             :              */
    4293          16 :             ascii_safe_strlcpy(buffer, activity,
    4294          16 :                                Min(buflen, pgstat_track_activity_query_size));
    4295             : 
    4296          16 :             return buffer;
    4297             :         }
    4298             : 
    4299       65464 :         beentry++;
    4300             :     }
    4301             : 
    4302             :     /* PID not found */
    4303         762 :     return NULL;
    4304             : }
    4305             : 
    4306             : /* ------------------------------------------------------------
    4307             :  * Local support functions follow
    4308             :  * ------------------------------------------------------------
    4309             :  */
    4310             : 
    4311             : 
    4312             : /* ----------
    4313             :  * pgstat_setheader() -
    4314             :  *
    4315             :  *      Set common header fields in a statistics message
    4316             :  * ----------
    4317             :  */
    4318             : static void
    4319      123320 : pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
    4320             : {
    4321      123320 :     hdr->m_type = mtype;
    4322      123320 : }
    4323             : 
    4324             : 
    4325             : /* ----------
    4326             :  * pgstat_send() -
    4327             :  *
    4328             :  *      Send out one statistics message to the collector
    4329             :  * ----------
    4330             :  */
    4331             : static void
    4332      123320 : pgstat_send(void *msg, int len)
    4333             : {
    4334             :     int         rc;
    4335             : 
    4336      123320 :     if (pgStatSock == PGINVALID_SOCKET)
    4337        4090 :         return;
    4338             : 
    4339      119230 :     ((PgStat_MsgHdr *) msg)->m_size = len;
    4340             : 
    4341             :     /* We'll retry after EINTR, but ignore all other failures */
    4342             :     do
    4343             :     {
    4344      119230 :         rc = send(pgStatSock, msg, len, 0);
    4345      119230 :     } while (rc < 0 && errno == EINTR);
    4346             : 
    4347             : #ifdef USE_ASSERT_CHECKING
    4348             :     /* In debug builds, log send failures ... */
    4349             :     if (rc < 0)
    4350             :         elog(LOG, "could not send to statistics collector: %m");
    4351             : #endif
    4352             : }
    4353             : 
    4354             : /* ----------
    4355             :  * pgstat_send_archiver() -
    4356             :  *
    4357             :  *  Tell the collector about the WAL file that we successfully
    4358             :  *  archived or failed to archive.
    4359             :  * ----------
    4360             :  */
    4361             : void
    4362          48 : pgstat_send_archiver(const char *xlog, bool failed)
    4363             : {
    4364             :     PgStat_MsgArchiver msg;
    4365             : 
    4366             :     /*
    4367             :      * Prepare and send the message
    4368             :      */
    4369          48 :     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ARCHIVER);
    4370          48 :     msg.m_failed = failed;
    4371          48 :     StrNCpy(msg.m_xlog, xlog, sizeof(msg.m_xlog));
    4372          48 :     msg.m_timestamp = GetCurrentTimestamp();
    4373          48 :     pgstat_send(&msg, sizeof(msg));
    4374          48 : }
    4375             : 
    4376             : /* ----------
    4377             :  * pgstat_send_bgwriter() -
    4378             :  *
    4379             :  *      Send bgwriter statistics to the collector
    4380             :  * ----------
    4381             :  */
    4382             : void
    4383       11774 : pgstat_send_bgwriter(void)
    4384             : {
    4385             :     /* We assume this initializes to zeroes */
    4386             :     static const PgStat_MsgBgWriter all_zeroes;
    4387             : 
    4388             :     /*
    4389             :      * This function can be called even if nothing at all has happened. In
    4390             :      * this case, avoid sending a completely empty message to the stats
    4391             :      * collector.
    4392             :      */
    4393       11774 :     if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
    4394        5144 :         return;
    4395             : 
    4396             :     /*
    4397             :      * Prepare and send the message
    4398             :      */
    4399        6630 :     pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
    4400        6630 :     pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
    4401             : 
    4402             :     /*
    4403             :      * Clear out the statistics buffer, so it can be re-used.
    4404             :      */
    4405       79560 :     MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
    4406             : }
    4407             : 
    4408             : /* ----------
    4409             :  * pgstat_send_slru() -
    4410             :  *
    4411             :  *      Send SLRU statistics to the collector
    4412             :  * ----------
    4413             :  */
    4414             : static void
    4415       19894 : pgstat_send_slru(void)
    4416             : {
    4417             :     /* We assume this initializes to zeroes */
    4418             :     static const PgStat_MsgSLRU all_zeroes;
    4419             : 
    4420      179046 :     for (int i = 0; i < SLRU_NUM_ELEMENTS; i++)
    4421             :     {
    4422             :         /*
    4423             :          * This function can be called even if nothing at all has happened. In
    4424             :          * this case, avoid sending a completely empty message to the stats
    4425             :          * collector.
    4426             :          */
    4427      159152 :         if (memcmp(&SLRUStats[i], &all_zeroes, sizeof(PgStat_MsgSLRU)) == 0)
    4428      146634 :             continue;
    4429             : 
    4430             :         /* set the SLRU type before each send */
    4431       12518 :         SLRUStats[i].m_index = i;
    4432             : 
    4433             :         /*
    4434             :          * Prepare and send the message
    4435             :          */
    4436       12518 :         pgstat_setheader(&SLRUStats[i].m_hdr, PGSTAT_MTYPE_SLRU);
    4437       12518 :         pgstat_send(&SLRUStats[i], sizeof(PgStat_MsgSLRU));
    4438             : 
    4439             :         /*
    4440             :          * Clear out the statistics buffer, so it can be re-used.
    4441             :          */
    4442      125180 :         MemSet(&SLRUStats[i], 0, sizeof(PgStat_MsgSLRU));
    4443             :     }
    4444       19894 : }
    4445             : 
    4446             : 
    4447             : /* ----------
    4448             :  * PgstatCollectorMain() -
    4449             :  *
    4450             :  *  Start up the statistics collector process.  This is the body of the
    4451             :  *  postmaster child process.
    4452             :  *
    4453             :  *  The argc/argv parameters are valid only in EXEC_BACKEND case.
    4454             :  * ----------
    4455             :  */
    4456             : NON_EXEC_STATIC void
    4457         720 : PgstatCollectorMain(int argc, char *argv[])
    4458             : {
    4459             :     int         len;
    4460             :     PgStat_Msg  msg;
    4461             :     int         wr;
    4462             : 
    4463             :     /*
    4464             :      * Ignore all signals usually bound to some action in the postmaster,
    4465             :      * except SIGHUP and SIGQUIT.  Note we don't need a SIGUSR1 handler to
    4466             :      * support latch operations, because we only use a local latch.
    4467             :      */
    4468         720 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
    4469         720 :     pqsignal(SIGINT, SIG_IGN);
    4470         720 :     pqsignal(SIGTERM, SIG_IGN);
    4471         720 :     pqsignal(SIGQUIT, SignalHandlerForShutdownRequest);
    4472         720 :     pqsignal(SIGALRM, SIG_IGN);
    4473         720 :     pqsignal(SIGPIPE, SIG_IGN);
    4474         720 :     pqsignal(SIGUSR1, SIG_IGN);
    4475         720 :     pqsignal(SIGUSR2, SIG_IGN);
    4476             :     /* Reset some signals that are accepted by postmaster but not here */
    4477         720 :     pqsignal(SIGCHLD, SIG_DFL);
    4478         720 :     PG_SETMASK(&UnBlockSig);
    4479             : 
    4480         720 :     MyBackendType = B_STATS_COLLECTOR;
    4481         720 :     init_ps_display(NULL);
    4482             : 
    4483             :     /*
    4484             :      * Read in existing stats files or initialize the stats to zero.
    4485             :      */
    4486         720 :     pgStatRunningInCollector = true;
    4487         720 :     pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
    4488             : 
    4489             :     /*
    4490             :      * Loop to process messages until we get SIGQUIT or detect ungraceful
    4491             :      * death of our parent postmaster.
    4492             :      *
    4493             :      * For performance reasons, we don't want to do ResetLatch/WaitLatch after
    4494             :      * every message; instead, do that only after a recv() fails to obtain a
    4495             :      * message.  (This effectively means that if backends are sending us stuff
    4496             :      * like mad, we won't notice postmaster death until things slack off a
    4497             :      * bit; which seems fine.)  To do that, we have an inner loop that
    4498             :      * iterates as long as recv() succeeds.  We do check ConfigReloadPending
    4499             :      * inside the inner loop, which means that such interrupts will get
    4500             :      * serviced but the latch won't get cleared until next time there is a
    4501             :      * break in the action.
    4502             :      */
    4503             :     for (;;)
    4504             :     {
    4505             :         /* Clear any already-pending wakeups */
    4506       77446 :         ResetLatch(MyLatch);
    4507             : 
    4508             :         /*
    4509             :          * Quit if we get SIGQUIT from the postmaster.
    4510             :          */
    4511       77446 :         if (ShutdownRequestPending)
    4512         714 :             break;
    4513             : 
    4514             :         /*
    4515             :          * Inner loop iterates as long as we keep getting messages, or until
    4516             :          * ShutdownRequestPending becomes set.
    4517             :          */
    4518      199996 :         while (!ShutdownRequestPending)
    4519             :         {
    4520             :             /*
    4521             :              * Reload configuration if we got SIGHUP from the postmaster.
    4522             :              */
    4523      199996 :             if (ConfigReloadPending)
    4524             :             {
    4525          78 :                 ConfigReloadPending = false;
    4526          78 :                 ProcessConfigFile(PGC_SIGHUP);
    4527             :             }
    4528             : 
    4529             :             /*
    4530             :              * Write the stats file(s) if a new request has arrived that is
    4531             :              * not satisfied by existing file(s).
    4532             :              */
    4533      199996 :             if (pgstat_write_statsfile_needed())
    4534        1184 :                 pgstat_write_statsfiles(false, false);
    4535             : 
    4536             :             /*
    4537             :              * Try to receive and process a message.  This will not block,
    4538             :              * since the socket is set to non-blocking mode.
    4539             :              *
    4540             :              * XXX On Windows, we have to force pgwin32_recv to cooperate,
    4541             :              * despite the previous use of pg_set_noblock() on the socket.
    4542             :              * This is extremely broken and should be fixed someday.
    4543             :              */
    4544             : #ifdef WIN32
    4545             :             pgwin32_noblock = 1;
    4546             : #endif
    4547             : 
    4548      199996 :             len = recv(pgStatSock, (char *) &msg,
    4549             :                        sizeof(PgStat_Msg), 0);
    4550             : 
    4551             : #ifdef WIN32
    4552             :             pgwin32_noblock = 0;
    4553             : #endif
    4554             : 
    4555      199996 :             if (len < 0)
    4556             :             {
    4557       76732 :                 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
    4558             :                     break;      /* out of inner loop */
    4559           0 :                 ereport(ERROR,
    4560             :                         (errcode_for_socket_access(),
    4561             :                          errmsg("could not read statistics message: %m")));
    4562             :             }
    4563             : 
    4564             :             /*
    4565             :              * We ignore messages that are smaller than our common header
    4566             :              */
    4567      123264 :             if (len < sizeof(PgStat_MsgHdr))
    4568           0 :                 continue;
    4569             : 
    4570             :             /*
    4571             :              * The received length must match the length in the header
    4572             :              */
    4573      123264 :             if (msg.msg_hdr.m_size != len)
    4574           0 :                 continue;
    4575             : 
    4576             :             /*
    4577             :              * O.K. - we accept this message.  Process it.
    4578             :              */
    4579      123264 :             switch (msg.msg_hdr.m_type)
    4580             :             {
    4581           0 :                 case PGSTAT_MTYPE_DUMMY:
    4582           0 :                     break;
    4583             : 
    4584        1184 :                 case PGSTAT_MTYPE_INQUIRY:
    4585        1184 :                     pgstat_recv_inquiry(&msg.msg_inquiry, len);
    4586        1184 :                     break;
    4587             : 
    4588       85056 :                 case PGSTAT_MTYPE_TABSTAT:
    4589       85056 :                     pgstat_recv_tabstat(&msg.msg_tabstat, len);
    4590       85056 :                     break;
    4591             : 
    4592         802 :                 case PGSTAT_MTYPE_TABPURGE:
    4593         802 :                     pgstat_recv_tabpurge(&msg.msg_tabpurge, len);
    4594         802 :                     break;
    4595             : 
    4596          18 :                 case PGSTAT_MTYPE_DROPDB:
    4597          18 :                     pgstat_recv_dropdb(&msg.msg_dropdb, len);
    4598          18 :                     break;
    4599             : 
    4600           0 :                 case PGSTAT_MTYPE_RESETCOUNTER:
    4601           0 :                     pgstat_recv_resetcounter(&msg.msg_resetcounter, len);
    4602           0 :                     break;
    4603             : 
    4604           2 :                 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
    4605           2 :                     pgstat_recv_resetsharedcounter(&msg.msg_resetsharedcounter,
    4606             :                                                    len);
    4607           2 :                     break;
    4608             : 
    4609           0 :                 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
    4610           0 :                     pgstat_recv_resetsinglecounter(&msg.msg_resetsinglecounter,
    4611             :                                                    len);
    4612           0 :                     break;
    4613             : 
    4614           0 :                 case PGSTAT_MTYPE_RESETSLRUCOUNTER:
    4615           0 :                     pgstat_recv_resetslrucounter(&msg.msg_resetslrucounter,
    4616             :                                                  len);
    4617           0 :                     break;
    4618             : 
    4619          60 :                 case PGSTAT_MTYPE_AUTOVAC_START:
    4620          60 :                     pgstat_recv_autovac(&msg.msg_autovacuum_start, len);
    4621          60 :                     break;
    4622             : 
    4623        4760 :                 case PGSTAT_MTYPE_VACUUM:
    4624        4760 :                     pgstat_recv_vacuum(&msg.msg_vacuum, len);
    4625        4760 :                     break;
    4626             : 
    4627        9978 :                 case PGSTAT_MTYPE_ANALYZE:
    4628        9978 :                     pgstat_recv_analyze(&msg.msg_analyze, len);
    4629        9978 :                     break;
    4630             : 
    4631          48 :                 case PGSTAT_MTYPE_ARCHIVER:
    4632          48 :                     pgstat_recv_archiver(&msg.msg_archiver, len);
    4633          48 :                     break;
    4634             : 
    4635        9176 :                 case PGSTAT_MTYPE_BGWRITER:
    4636        9176 :                     pgstat_recv_bgwriter(&msg.msg_bgwriter, len);
    4637        9176 :                     break;
    4638             : 
    4639        8540 :                 case PGSTAT_MTYPE_SLRU:
    4640        8540 :                     pgstat_recv_slru(&msg.msg_slru, len);
    4641        8540 :                     break;
    4642             : 
    4643           0 :                 case PGSTAT_MTYPE_FUNCSTAT:
    4644           0 :                     pgstat_recv_funcstat(&msg.msg_funcstat, len);
    4645           0 :                     break;
    4646             : 
    4647           0 :                 case PGSTAT_MTYPE_FUNCPURGE:
    4648           0 :                     pgstat_recv_funcpurge(&msg.msg_funcpurge, len);
    4649           0 :                     break;
    4650             : 
    4651           0 :                 case PGSTAT_MTYPE_RECOVERYCONFLICT:
    4652           0 :                     pgstat_recv_recoveryconflict(&msg.msg_recoveryconflict,
    4653             :                                                  len);
    4654           0 :                     break;
    4655             : 
    4656           4 :                 case PGSTAT_MTYPE_DEADLOCK:
    4657           4 :                     pgstat_recv_deadlock(&msg.msg_deadlock, len);
    4658           4 :                     break;
    4659             : 
    4660        3632 :                 case PGSTAT_MTYPE_TEMPFILE:
    4661        3632 :                     pgstat_recv_tempfile(&msg.msg_tempfile, len);
    4662        3632 :                     break;
    4663             : 
    4664           4 :                 case PGSTAT_MTYPE_CHECKSUMFAILURE:
    4665           4 :                     pgstat_recv_checksum_failure(&msg.msg_checksumfailure,
    4666             :                                                  len);
    4667           4 :                     break;
    4668             : 
    4669           0 :                 default:
    4670           0 :                     break;
    4671             :             }
    4672             :         }                       /* end of inner message-processing loop */
    4673             : 
    4674             :         /* Sleep until there's something to do */
    4675             : #ifndef WIN32
    4676       76732 :         wr = WaitLatchOrSocket(MyLatch,
    4677             :                                WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
    4678             :                                pgStatSock, -1L,
    4679             :                                WAIT_EVENT_PGSTAT_MAIN);
    4680             : #else
    4681             : 
    4682             :         /*
    4683             :          * Windows, at least in its Windows Server 2003 R2 incarnation,
    4684             :          * sometimes loses FD_READ events.  Waking up and retrying the recv()
    4685             :          * fixes that, so don't sleep indefinitely.  This is a crock of the
    4686             :          * first water, but until somebody wants to debug exactly what's
    4687             :          * happening there, this is the best we can do.  The two-second
    4688             :          * timeout matches our pre-9.2 behavior, and needs to be short enough
    4689             :          * to not provoke "using stale statistics" complaints from
    4690             :          * backend_read_statsfile.
    4691             :          */
    4692             :         wr = WaitLatchOrSocket(MyLatch,
    4693             :                                WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
    4694             :                                pgStatSock,
    4695             :                                2 * 1000L /* msec */ ,
    4696             :                                WAIT_EVENT_PGSTAT_MAIN);
    4697             : #endif
    4698             : 
    4699             :         /*
    4700             :          * Emergency bailout if postmaster has died.  This is to avoid the
    4701             :          * necessity for manual cleanup of all postmaster children.
    4702             :          */
    4703       76732 :         if (wr & WL_POSTMASTER_DEATH)
    4704           6 :             break;
    4705             :     }                           /* end of outer loop */
    4706             : 
    4707             :     /*
    4708             :      * Save the final stats to reuse at next startup.
    4709             :      */
    4710         720 :     pgstat_write_statsfiles(true, true);
    4711             : 
    4712         720 :     exit(0);
    4713             : }
    4714             : 
    4715             : /*
    4716             :  * Subroutine to clear stats in a database entry
    4717             :  *
    4718             :  * Tables and functions hashes are initialized to empty.
    4719             :  */
    4720             : static void
    4721        1304 : reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
    4722             : {
    4723             :     HASHCTL     hash_ctl;
    4724             : 
    4725        1304 :     dbentry->n_xact_commit = 0;
    4726        1304 :     dbentry->n_xact_rollback = 0;
    4727        1304 :     dbentry->n_blocks_fetched = 0;
    4728        1304 :     dbentry->n_blocks_hit = 0;
    4729        1304 :     dbentry->n_tuples_returned = 0;
    4730        1304 :     dbentry->n_tuples_fetched = 0;
    4731        1304 :     dbentry->n_tuples_inserted = 0;
    4732        1304 :     dbentry->n_tuples_updated = 0;
    4733        1304 :     dbentry->n_tuples_deleted = 0;
    4734        1304 :     dbentry->last_autovac_time = 0;
    4735        1304 :     dbentry->n_conflict_tablespace = 0;
    4736        1304 :     dbentry->n_conflict_lock = 0;
    4737        1304 :     dbentry->n_conflict_snapshot = 0;
    4738        1304 :     dbentry->n_conflict_bufferpin = 0;
    4739        1304 :     dbentry->n_conflict_startup_deadlock = 0;
    4740        1304 :     dbentry->n_temp_files = 0;
    4741        1304 :     dbentry->n_temp_bytes = 0;
    4742        1304 :     dbentry->n_deadlocks = 0;
    4743        1304 :     dbentry->n_checksum_failures = 0;
    4744        1304 :     dbentry->last_checksum_failure = 0;
    4745        1304 :     dbentry->n_block_read_time = 0;
    4746        1304 :     dbentry->n_block_write_time = 0;
    4747             : 
    4748        1304 :     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
    4749        1304 :     dbentry->stats_timestamp = 0;
    4750             : 
    4751        1304 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    4752        1304 :     hash_ctl.keysize = sizeof(Oid);
    4753        1304 :     hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
    4754        1304 :     dbentry->tables = hash_create("Per-database table",
    4755             :                                   PGSTAT_TAB_HASH_SIZE,
    4756             :                                   &hash_ctl,
    4757             :                                   HASH_ELEM | HASH_BLOBS);
    4758             : 
    4759        1304 :     hash_ctl.keysize = sizeof(Oid);
    4760        1304 :     hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
    4761        1304 :     dbentry->functions = hash_create("Per-database function",
    4762             :                                      PGSTAT_FUNCTION_HASH_SIZE,
    4763             :                                      &hash_ctl,
    4764             :                                      HASH_ELEM | HASH_BLOBS);
    4765        1304 : }
    4766             : 
    4767             : /*
    4768             :  * Lookup the hash table entry for the specified database. If no hash
    4769             :  * table entry exists, initialize it, if the create parameter is true.
    4770             :  * Else, return NULL.
    4771             :  */
    4772             : static PgStat_StatDBEntry *
    4773      105498 : pgstat_get_db_entry(Oid databaseid, bool create)
    4774             : {
    4775             :     PgStat_StatDBEntry *result;
    4776             :     bool        found;
    4777      105498 :     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
    4778             : 
    4779             :     /* Lookup or create the hash table entry for this database */
    4780      105498 :     result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
    4781             :                                                 &databaseid,
    4782             :                                                 action, &found);
    4783             : 
    4784      105498 :     if (!create && !found)
    4785         476 :         return NULL;
    4786             : 
    4787             :     /*
    4788             :      * If not found, initialize the new one.  This creates empty hash tables
    4789             :      * for tables and functions, too.
    4790             :      */
    4791      105022 :     if (!found)
    4792        1304 :         reset_dbentry_counters(result);
    4793             : 
    4794      105022 :     return result;
    4795             : }
    4796             : 
    4797             : 
    4798             : /*
    4799             :  * Lookup the hash table entry for the specified table. If no hash
    4800             :  * table entry exists, initialize it, if the create parameter is true.
    4801             :  * Else, return NULL.
    4802             :  */
    4803             : static PgStat_StatTabEntry *
    4804       14738 : pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
    4805             : {
    4806             :     PgStat_StatTabEntry *result;
    4807             :     bool        found;
    4808       14738 :     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
    4809             : 
    4810             :     /* Lookup or create the hash table entry for this table */
    4811       14738 :     result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    4812             :                                                  &tableoid,
    4813             :                                                  action, &found);
    4814             : 
    4815       14738 :     if (!create && !found)
    4816           0 :         return NULL;
    4817             : 
    4818             :     /* If not found, initialize the new one. */
    4819       14738 :     if (!found)
    4820             :     {
    4821        4116 :         result->numscans = 0;
    4822        4116 :         result->tuples_returned = 0;
    4823        4116 :         result->tuples_fetched = 0;
    4824        4116 :         result->tuples_inserted = 0;
    4825        4116 :         result->tuples_updated = 0;
    4826        4116 :         result->tuples_deleted = 0;
    4827        4116 :         result->tuples_hot_updated = 0;
    4828        4116 :         result->n_live_tuples = 0;
    4829        4116 :         result->n_dead_tuples = 0;
    4830        4116 :         result->changes_since_analyze = 0;
    4831        4116 :         result->inserts_since_vacuum = 0;
    4832        4116 :         result->blocks_fetched = 0;
    4833        4116 :         result->blocks_hit = 0;
    4834        4116 :         result->vacuum_timestamp = 0;
    4835        4116 :         result->vacuum_count = 0;
    4836        4116 :         result->autovac_vacuum_timestamp = 0;
    4837        4116 :         result->autovac_vacuum_count = 0;
    4838        4116 :         result->analyze_timestamp = 0;
    4839        4116 :         result->analyze_count = 0;
    4840        4116 :         result->autovac_analyze_timestamp = 0;
    4841        4116 :         result->autovac_analyze_count = 0;
    4842             :     }
    4843             : 
    4844       14738 :     return result;
    4845             : }
    4846             : 
    4847             : 
    4848             : /* ----------
    4849             :  * pgstat_write_statsfiles() -
    4850             :  *      Write the global statistics file, as well as requested DB files.
    4851             :  *
    4852             :  *  'permanent' specifies writing to the permanent files not temporary ones.
    4853             :  *  When true (happens only when the collector is shutting down), also remove
    4854             :  *  the temporary files so that backends starting up under a new postmaster
    4855             :  *  can't read old data before the new collector is ready.
    4856             :  *
    4857             :  *  When 'allDbs' is false, only the requested databases (listed in
    4858             :  *  pending_write_requests) will be written; otherwise, all databases
    4859             :  *  will be written.
    4860             :  * ----------
    4861             :  */
    4862             : static void
    4863        1904 : pgstat_write_statsfiles(bool permanent, bool allDbs)
    4864             : {
    4865             :     HASH_SEQ_STATUS hstat;
    4866             :     PgStat_StatDBEntry *dbentry;
    4867             :     FILE       *fpout;
    4868             :     int32       format_id;
    4869        1904 :     const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
    4870        1904 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    4871             :     int         rc;
    4872             : 
    4873        1904 :     elog(DEBUG2, "writing stats file \"%s\"", statfile);
    4874             : 
    4875             :     /*
    4876             :      * Open the statistics temp file to write out the current values.
    4877             :      */
    4878        1904 :     fpout = AllocateFile(tmpfile, PG_BINARY_W);
    4879        1904 :     if (fpout == NULL)
    4880             :     {
    4881           0 :         ereport(LOG,
    4882             :                 (errcode_for_file_access(),
    4883             :                  errmsg("could not open temporary statistics file \"%s\": %m",
    4884             :                         tmpfile)));
    4885           0 :         return;
    4886             :     }
    4887             : 
    4888             :     /*
    4889             :      * Set the timestamp of the stats file.
    4890             :      */
    4891        1904 :     globalStats.stats_timestamp = GetCurrentTimestamp();
    4892             : 
    4893             :     /*
    4894             :      * Write the file header --- currently just a format ID.
    4895             :      */
    4896        1904 :     format_id = PGSTAT_FILE_FORMAT_ID;
    4897        1904 :     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
    4898             :     (void) rc;                  /* we'll check for error with ferror */
    4899             : 
    4900             :     /*
    4901             :      * Write global stats struct
    4902             :      */
    4903        1904 :     rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
    4904             :     (void) rc;                  /* we'll check for error with ferror */
    4905             : 
    4906             :     /*
    4907             :      * Write archiver stats struct
    4908             :      */
    4909        1904 :     rc = fwrite(&archiverStats, sizeof(archiverStats), 1, fpout);
    4910             :     (void) rc;                  /* we'll check for error with ferror */
    4911             : 
    4912             :     /*
    4913             :      * Write SLRU stats struct
    4914             :      */
    4915        1904 :     rc = fwrite(slruStats, sizeof(slruStats), 1, fpout);
    4916             :     (void) rc;                  /* we'll check for error with ferror */
    4917             : 
    4918             :     /*
    4919             :      * Walk through the database table.
    4920             :      */
    4921        1904 :     hash_seq_init(&hstat, pgStatDBHash);
    4922        5488 :     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
    4923             :     {
    4924             :         /*
    4925             :          * Write out the table and function stats for this DB into the
    4926             :          * appropriate per-DB stat file, if required.
    4927             :          */
    4928        3584 :         if (allDbs || pgstat_db_requested(dbentry->databaseid))
    4929             :         {
    4930             :             /* Make DB's timestamp consistent with the global stats */
    4931        2802 :             dbentry->stats_timestamp = globalStats.stats_timestamp;
    4932             : 
    4933        2802 :             pgstat_write_db_statsfile(dbentry, permanent);
    4934             :         }
    4935             : 
    4936             :         /*
    4937             :          * Write out the DB entry. We don't write the tables or functions
    4938             :          * pointers, since they're of no use to any other process.
    4939             :          */
    4940        3584 :         fputc('D', fpout);
    4941        3584 :         rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
    4942             :         (void) rc;              /* we'll check for error with ferror */
    4943             :     }
    4944             : 
    4945             :     /*
    4946             :      * No more output to be done. Close the temp file and replace the old
    4947             :      * pgstat.stat with it.  The ferror() check replaces testing for error
    4948             :      * after each individual fputc or fwrite above.
    4949             :      */
    4950        1904 :     fputc('E', fpout);
    4951             : 
    4952        1904 :     if (ferror(fpout))
    4953             :     {
    4954           0 :         ereport(LOG,
    4955             :                 (errcode_for_file_access(),
    4956             :                  errmsg("could not write temporary statistics file \"%s\": %m",
    4957             :                         tmpfile)));
    4958           0 :         FreeFile(fpout);
    4959           0 :         unlink(tmpfile);
    4960             :     }
    4961        1904 :     else if (FreeFile(fpout) < 0)
    4962             :     {
    4963           0 :         ereport(LOG,
    4964             :                 (errcode_for_file_access(),
    4965             :                  errmsg("could not close temporary statistics file \"%s\": %m",
    4966             :                         tmpfile)));
    4967           0 :         unlink(tmpfile);
    4968             :     }
    4969        1904 :     else if (rename(tmpfile, statfile) < 0)
    4970             :     {
    4971           0 :         ereport(LOG,
    4972             :                 (errcode_for_file_access(),
    4973             :                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
    4974             :                         tmpfile, statfile)));
    4975           0 :         unlink(tmpfile);
    4976             :     }
    4977             : 
    4978        1904 :     if (permanent)
    4979         720 :         unlink(pgstat_stat_filename);
    4980             : 
    4981             :     /*
    4982             :      * Now throw away the list of requests.  Note that requests sent after we
    4983             :      * started the write are still waiting on the network socket.
    4984             :      */
    4985        1904 :     list_free(pending_write_requests);
    4986        1904 :     pending_write_requests = NIL;
    4987             : }
    4988             : 
    4989             : /*
    4990             :  * return the filename for a DB stat file; filename is the output buffer,
    4991             :  * of length len.
    4992             :  */
    4993             : static void
    4994       12500 : get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
    4995             :                     char *filename, int len)
    4996             : {
    4997             :     int         printed;
    4998             : 
    4999             :     /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
    5000       12500 :     printed = snprintf(filename, len, "%s/db_%u.%s",
    5001             :                        permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
    5002             :                        pgstat_stat_directory,
    5003             :                        databaseid,
    5004             :                        tempname ? "tmp" : "stat");
    5005       12500 :     if (printed >= len)
    5006           0 :         elog(ERROR, "overlength pgstat path");
    5007       12500 : }
    5008             : 
    5009             : /* ----------
    5010             :  * pgstat_write_db_statsfile() -
    5011             :  *      Write the stat file for a single database.
    5012             :  *
    5013             :  *  If writing to the permanent file (happens when the collector is
    5014             :  *  shutting down only), remove the temporary file so that backends
    5015             :  *  starting up under a new postmaster can't read the old data before
    5016             :  *  the new collector is ready.
    5017             :  * ----------
    5018             :  */
    5019             : static void
    5020        2802 : pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
    5021             : {
    5022             :     HASH_SEQ_STATUS tstat;
    5023             :     HASH_SEQ_STATUS fstat;
    5024             :     PgStat_StatTabEntry *tabentry;
    5025             :     PgStat_StatFuncEntry *funcentry;
    5026             :     FILE       *fpout;
    5027             :     int32       format_id;
    5028        2802 :     Oid         dbid = dbentry->databaseid;
    5029             :     int         rc;
    5030             :     char        tmpfile[MAXPGPATH];
    5031             :     char        statfile[MAXPGPATH];
    5032             : 
    5033        2802 :     get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
    5034        2802 :     get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
    5035             : 
    5036        2802 :     elog(DEBUG2, "writing stats file \"%s\"", statfile);
    5037             : 
    5038             :     /*
    5039             :      * Open the statistics temp file to write out the current values.
    5040             :      */
    5041        2802 :     fpout = AllocateFile(tmpfile, PG_BINARY_W);
    5042        2802 :     if (fpout == NULL)
    5043             :     {
    5044           0 :         ereport(LOG,
    5045             :                 (errcode_for_file_access(),
    5046             :                  errmsg("could not open temporary statistics file \"%s\": %m",
    5047             :                         tmpfile)));
    5048           0 :         return;
    5049             :     }
    5050             : 
    5051             :     /*
    5052             :      * Write the file header --- currently just a format ID.
    5053             :      */
    5054        2802 :     format_id = PGSTAT_FILE_FORMAT_ID;
    5055        2802 :     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
    5056             :     (void) rc;                  /* we'll check for error with ferror */
    5057             : 
    5058             :     /*
    5059             :      * Walk through the database's access stats per table.
    5060             :      */
    5061        2802 :     hash_seq_init(&tstat, dbentry->tables);
    5062      318212 :     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
    5063             :     {
    5064      315410 :         fputc('T', fpout);
    5065      315410 :         rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
    5066             :         (void) rc;              /* we'll check for error with ferror */
    5067             :     }
    5068             : 
    5069             :     /*
    5070             :      * Walk through the database's function stats table.
    5071             :      */
    5072        2802 :     hash_seq_init(&fstat, dbentry->functions);
    5073        2802 :     while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
    5074             :     {
    5075           0 :         fputc('F', fpout);
    5076           0 :         rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
    5077             :         (void) rc;              /* we'll check for error with ferror */
    5078             :     }
    5079             : 
    5080             :     /*
    5081             :      * No more output to be done. Close the temp file and replace the old
    5082             :      * pgstat.stat with it.  The ferror() check replaces testing for error
    5083             :      * after each individual fputc or fwrite above.
    5084             :      */
    5085        2802 :     fputc('E', fpout);
    5086             : 
    5087        2802 :     if (ferror(fpout))
    5088             :     {
    5089           0 :         ereport(LOG,
    5090             :                 (errcode_for_file_access(),
    5091             :                  errmsg("could not write temporary statistics file \"%s\": %m",
    5092             :                         tmpfile)));
    5093           0 :         FreeFile(fpout);
    5094           0 :         unlink(tmpfile);
    5095             :     }
    5096        2802 :     else if (FreeFile(fpout) < 0)
    5097             :     {
    5098           0 :         ereport(LOG,
    5099             :                 (errcode_for_file_access(),
    5100             :                  errmsg("could not close temporary statistics file \"%s\": %m",
    5101             :                         tmpfile)));
    5102           0 :         unlink(tmpfile);
    5103             :     }
    5104        2802 :     else if (rename(tmpfile, statfile) < 0)
    5105             :     {
    5106           0 :         ereport(LOG,
    5107             :                 (errcode_for_file_access(),
    5108             :                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
    5109             :                         tmpfile, statfile)));
    5110           0 :         unlink(tmpfile);
    5111             :     }
    5112             : 
    5113        2802 :     if (permanent)
    5114             :     {
    5115        1576 :         get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
    5116             : 
    5117        1576 :         elog(DEBUG2, "removing temporary stats file \"%s\"", statfile);
    5118        1576 :         unlink(statfile);
    5119             :     }
    5120             : }
    5121             : 
    5122             : /* ----------
    5123             :  * pgstat_read_statsfiles() -
    5124             :  *
    5125             :  *  Reads in some existing statistics collector files and returns the
    5126             :  *  databases hash table that is the top level of the data.
    5127             :  *
    5128             :  *  If 'onlydb' is not InvalidOid, it means we only want data for that DB
    5129             :  *  plus the shared catalogs ("DB 0").  We'll still populate the DB hash
    5130             :  *  table for all databases, but we don't bother even creating table/function
    5131             :  *  hash tables for other databases.
    5132             :  *
    5133             :  *  'permanent' specifies reading from the permanent files not temporary ones.
    5134             :  *  When true (happens only when the collector is starting up), remove the
    5135             :  *  files after reading; the in-memory status is now authoritative, and the
    5136             :  *  files would be out of date in case somebody else reads them.
    5137             :  *
    5138             :  *  If a 'deep' read is requested, table/function stats are read, otherwise
    5139             :  *  the table/function hash tables remain empty.
    5140             :  * ----------
    5141             :  */
    5142             : static HTAB *
    5143        4442 : pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
    5144             : {
    5145             :     PgStat_StatDBEntry *dbentry;
    5146             :     PgStat_StatDBEntry dbbuf;
    5147             :     HASHCTL     hash_ctl;
    5148             :     HTAB       *dbhash;
    5149             :     FILE       *fpin;
    5150             :     int32       format_id;
    5151             :     bool        found;
    5152        4442 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    5153             :     int         i;
    5154             : 
    5155             :     /*
    5156             :      * The tables will live in pgStatLocalContext.
    5157             :      */
    5158        4442 :     pgstat_setup_memcxt();
    5159             : 
    5160             :     /*
    5161             :      * Create the DB hashtable
    5162             :      */
    5163        4442 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
    5164        4442 :     hash_ctl.keysize = sizeof(Oid);
    5165        4442 :     hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
    5166        4442 :     hash_ctl.hcxt = pgStatLocalContext;
    5167        4442 :     dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
    5168             :                          HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5169             : 
    5170             :     /*
    5171             :      * Clear out global and archiver statistics so they start from zero in
    5172             :      * case we can't load an existing statsfile.
    5173             :      */
    5174        4442 :     memset(&globalStats, 0, sizeof(globalStats));
    5175        4442 :     memset(&archiverStats, 0, sizeof(archiverStats));
    5176        4442 :     memset(&slruStats, 0, sizeof(slruStats));
    5177             : 
    5178             :     /*
    5179             :      * Set the current timestamp (will be kept only in case we can't load an
    5180             :      * existing statsfile).
    5181             :      */
    5182        4442 :     globalStats.stat_reset_timestamp = GetCurrentTimestamp();
    5183        4442 :     archiverStats.stat_reset_timestamp = globalStats.stat_reset_timestamp;
    5184             : 
    5185             :     /*
    5186             :      * Set the same reset timestamp for all SLRU items too.
    5187             :      */
    5188       39978 :     for (i = 0; i < SLRU_NUM_ELEMENTS; i++)
    5189       35536 :         slruStats[i].stat_reset_timestamp = globalStats.stat_reset_timestamp;
    5190             : 
    5191             :     /*
    5192             :      * Try to open the stats file. If it doesn't exist, the backends simply
    5193             :      * return zero for anything and the collector simply starts from scratch
    5194             :      * with empty counters.
    5195             :      *
    5196             :      * ENOENT is a possibility if the stats collector is not running or has
    5197             :      * not yet written the stats file the first time.  Any other failure
    5198             :      * condition is suspicious.
    5199             :      */
    5200        4442 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    5201             :     {
    5202         590 :         if (errno != ENOENT)
    5203           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5204             :                     (errcode_for_file_access(),
    5205             :                      errmsg("could not open statistics file \"%s\": %m",
    5206             :                             statfile)));
    5207         590 :         return dbhash;
    5208             :     }
    5209             : 
    5210             :     /*
    5211             :      * Verify it's of the expected format.
    5212             :      */
    5213        3852 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5214        3852 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5215             :     {
    5216           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5217             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5218           0 :         goto done;
    5219             :     }
    5220             : 
    5221             :     /*
    5222             :      * Read global stats struct
    5223             :      */
    5224        3852 :     if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
    5225             :     {
    5226           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5227             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5228           0 :         memset(&globalStats, 0, sizeof(globalStats));
    5229           0 :         goto done;
    5230             :     }
    5231             : 
    5232             :     /*
    5233             :      * In the collector, disregard the timestamp we read from the permanent
    5234             :      * stats file; we should be willing to write a temp stats file immediately
    5235             :      * upon the first request from any backend.  This only matters if the old
    5236             :      * file's timestamp is less than PGSTAT_STAT_INTERVAL ago, but that's not
    5237             :      * an unusual scenario.
    5238             :      */
    5239        3852 :     if (pgStatRunningInCollector)
    5240         130 :         globalStats.stats_timestamp = 0;
    5241             : 
    5242             :     /*
    5243             :      * Read archiver stats struct
    5244             :      */
    5245        3852 :     if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
    5246             :     {
    5247           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5248             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5249           0 :         memset(&archiverStats, 0, sizeof(archiverStats));
    5250           0 :         goto done;
    5251             :     }
    5252             : 
    5253             :     /*
    5254             :      * Read SLRU stats struct
    5255             :      */
    5256        3852 :     if (fread(slruStats, 1, sizeof(slruStats), fpin) != sizeof(slruStats))
    5257             :     {
    5258           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5259             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5260           0 :         memset(&slruStats, 0, sizeof(slruStats));
    5261           0 :         goto done;
    5262             :     }
    5263             : 
    5264             :     /*
    5265             :      * We found an existing collector stats file. Read it and put all the
    5266             :      * hashtable entries into place.
    5267             :      */
    5268             :     for (;;)
    5269             :     {
    5270       11254 :         switch (fgetc(fpin))
    5271             :         {
    5272             :                 /*
    5273             :                  * 'D'  A PgStat_StatDBEntry struct describing a database
    5274             :                  * follows.
    5275             :                  */
    5276        7402 :             case 'D':
    5277        7402 :                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
    5278             :                           fpin) != offsetof(PgStat_StatDBEntry, tables))
    5279             :                 {
    5280           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5281             :                             (errmsg("corrupted statistics file \"%s\"",
    5282             :                                     statfile)));
    5283           0 :                     goto done;
    5284             :                 }
    5285             : 
    5286             :                 /*
    5287             :                  * Add to the DB hash
    5288             :                  */
    5289        7402 :                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
    5290             :                                                              (void *) &dbbuf.databaseid,
    5291             :                                                              HASH_ENTER,
    5292             :                                                              &found);
    5293        7402 :                 if (found)
    5294             :                 {
    5295           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5296             :                             (errmsg("corrupted statistics file \"%s\"",
    5297             :                                     statfile)));
    5298           0 :                     goto done;
    5299             :                 }
    5300             : 
    5301        7402 :                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
    5302        7402 :                 dbentry->tables = NULL;
    5303        7402 :                 dbentry->functions = NULL;
    5304             : 
    5305             :                 /*
    5306             :                  * In the collector, disregard the timestamp we read from the
    5307             :                  * permanent stats file; we should be willing to write a temp
    5308             :                  * stats file immediately upon the first request from any
    5309             :                  * backend.
    5310             :                  */
    5311        7402 :                 if (pgStatRunningInCollector)
    5312         282 :                     dbentry->stats_timestamp = 0;
    5313             : 
    5314             :                 /*
    5315             :                  * Don't create tables/functions hashtables for uninteresting
    5316             :                  * databases.
    5317             :                  */
    5318        7402 :                 if (onlydb != InvalidOid)
    5319             :                 {
    5320        6614 :                     if (dbbuf.databaseid != onlydb &&
    5321        4100 :                         dbbuf.databaseid != InvalidOid)
    5322        1586 :                         break;
    5323             :                 }
    5324             : 
    5325        5816 :                 memset(&hash_ctl, 0, sizeof(hash_ctl));
    5326        5816 :                 hash_ctl.keysize = sizeof(Oid);
    5327        5816 :                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
    5328        5816 :                 hash_ctl.hcxt = pgStatLocalContext;
    5329        5816 :                 dbentry->tables = hash_create("Per-database table",
    5330             :                                               PGSTAT_TAB_HASH_SIZE,
    5331             :                                               &hash_ctl,
    5332             :                                               HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5333             : 
    5334        5816 :                 hash_ctl.keysize = sizeof(Oid);
    5335        5816 :                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
    5336        5816 :                 hash_ctl.hcxt = pgStatLocalContext;
    5337        5816 :                 dbentry->functions = hash_create("Per-database function",
    5338             :                                                  PGSTAT_FUNCTION_HASH_SIZE,
    5339             :                                                  &hash_ctl,
    5340             :                                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5341             : 
    5342             :                 /*
    5343             :                  * If requested, read the data from the database-specific
    5344             :                  * file.  Otherwise we just leave the hashtables empty.
    5345             :                  */
    5346        5816 :                 if (deep)
    5347        5310 :                     pgstat_read_db_statsfile(dbentry->databaseid,
    5348             :                                              dbentry->tables,
    5349             :                                              dbentry->functions,
    5350             :                                              permanent);
    5351             : 
    5352        5816 :                 break;
    5353             : 
    5354        3852 :             case 'E':
    5355        3852 :                 goto done;
    5356             : 
    5357           0 :             default:
    5358           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5359             :                         (errmsg("corrupted statistics file \"%s\"",
    5360             :                                 statfile)));
    5361           0 :                 goto done;
    5362             :         }
    5363             :     }
    5364             : 
    5365        3852 : done:
    5366        3852 :     FreeFile(fpin);
    5367             : 
    5368             :     /* If requested to read the permanent file, also get rid of it. */
    5369        3852 :     if (permanent)
    5370             :     {
    5371         130 :         elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
    5372         130 :         unlink(statfile);
    5373             :     }
    5374             : 
    5375        3852 :     return dbhash;
    5376             : }
    5377             : 
    5378             : 
    5379             : /* ----------
    5380             :  * pgstat_read_db_statsfile() -
    5381             :  *
    5382             :  *  Reads in the existing statistics collector file for the given database,
    5383             :  *  filling the passed-in tables and functions hash tables.
    5384             :  *
    5385             :  *  As in pgstat_read_statsfiles, if the permanent file is requested, it is
    5386             :  *  removed after reading.
    5387             :  *
    5388             :  *  Note: this code has the ability to skip storing per-table or per-function
    5389             :  *  data, if NULL is passed for the corresponding hashtable.  That's not used
    5390             :  *  at the moment though.
    5391             :  * ----------
    5392             :  */
    5393             : static void
    5394        5310 : pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
    5395             :                          bool permanent)
    5396             : {
    5397             :     PgStat_StatTabEntry *tabentry;
    5398             :     PgStat_StatTabEntry tabbuf;
    5399             :     PgStat_StatFuncEntry funcbuf;
    5400             :     PgStat_StatFuncEntry *funcentry;
    5401             :     FILE       *fpin;
    5402             :     int32       format_id;
    5403             :     bool        found;
    5404             :     char        statfile[MAXPGPATH];
    5405             : 
    5406        5310 :     get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
    5407             : 
    5408             :     /*
    5409             :      * Try to open the stats file. If it doesn't exist, the backends simply
    5410             :      * return zero for anything and the collector simply starts from scratch
    5411             :      * with empty counters.
    5412             :      *
    5413             :      * ENOENT is a possibility if the stats collector is not running or has
    5414             :      * not yet written the stats file the first time.  Any other failure
    5415             :      * condition is suspicious.
    5416             :      */
    5417        5310 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    5418             :     {
    5419           0 :         if (errno != ENOENT)
    5420           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5421             :                     (errcode_for_file_access(),
    5422             :                      errmsg("could not open statistics file \"%s\": %m",
    5423             :                             statfile)));
    5424           0 :         return;
    5425             :     }
    5426             : 
    5427             :     /*
    5428             :      * Verify it's of the expected format.
    5429             :      */
    5430        5310 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5431        5310 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5432             :     {
    5433           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5434             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5435           0 :         goto done;
    5436             :     }
    5437             : 
    5438             :     /*
    5439             :      * We found an existing collector stats file. Read it and put all the
    5440             :      * hashtable entries into place.
    5441             :      */
    5442             :     for (;;)
    5443             :     {
    5444      830544 :         switch (fgetc(fpin))
    5445             :         {
    5446             :                 /*
    5447             :                  * 'T'  A PgStat_StatTabEntry follows.
    5448             :                  */
    5449      825234 :             case 'T':
    5450      825234 :                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
    5451             :                           fpin) != sizeof(PgStat_StatTabEntry))
    5452             :                 {
    5453           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5454             :                             (errmsg("corrupted statistics file \"%s\"",
    5455             :                                     statfile)));
    5456           0 :                     goto done;
    5457             :                 }
    5458             : 
    5459             :                 /*
    5460             :                  * Skip if table data not wanted.
    5461             :                  */
    5462      825234 :                 if (tabhash == NULL)
    5463           0 :                     break;
    5464             : 
    5465      825234 :                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
    5466             :                                                                (void *) &tabbuf.tableid,
    5467             :                                                                HASH_ENTER, &found);
    5468             : 
    5469      825234 :                 if (found)
    5470             :                 {
    5471           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5472             :                             (errmsg("corrupted statistics file \"%s\"",
    5473             :                                     statfile)));
    5474           0 :                     goto done;
    5475             :                 }
    5476             : 
    5477      825234 :                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
    5478      825234 :                 break;
    5479             : 
    5480             :                 /*
    5481             :                  * 'F'  A PgStat_StatFuncEntry follows.
    5482             :                  */
    5483           0 :             case 'F':
    5484           0 :                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
    5485             :                           fpin) != sizeof(PgStat_StatFuncEntry))
    5486             :                 {
    5487           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5488             :                             (errmsg("corrupted statistics file \"%s\"",
    5489             :                                     statfile)));
    5490           0 :                     goto done;
    5491             :                 }
    5492             : 
    5493             :                 /*
    5494             :                  * Skip if function data not wanted.
    5495             :                  */
    5496           0 :                 if (funchash == NULL)
    5497           0 :                     break;
    5498             : 
    5499           0 :                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
    5500             :                                                                  (void *) &funcbuf.functionid,
    5501             :                                                                  HASH_ENTER, &found);
    5502             : 
    5503           0 :                 if (found)
    5504             :                 {
    5505           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5506             :                             (errmsg("corrupted statistics file \"%s\"",
    5507             :                                     statfile)));
    5508           0 :                     goto done;
    5509             :                 }
    5510             : 
    5511           0 :                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
    5512           0 :                 break;
    5513             : 
    5514             :                 /*
    5515             :                  * 'E'  The EOF marker of a complete stats file.
    5516             :                  */
    5517        5310 :             case 'E':
    5518        5310 :                 goto done;
    5519             : 
    5520           0 :             default:
    5521           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5522             :                         (errmsg("corrupted statistics file \"%s\"",
    5523             :                                 statfile)));
    5524           0 :                 goto done;
    5525             :         }
    5526             :     }
    5527             : 
    5528        5310 : done:
    5529        5310 :     FreeFile(fpin);
    5530             : 
    5531        5310 :     if (permanent)
    5532             :     {
    5533         282 :         elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
    5534         282 :         unlink(statfile);
    5535             :     }
    5536             : }
    5537             : 
    5538             : /* ----------
    5539             :  * pgstat_read_db_statsfile_timestamp() -
    5540             :  *
    5541             :  *  Attempt to determine the timestamp of the last db statfile write.
    5542             :  *  Returns true if successful; the timestamp is stored in *ts.
    5543             :  *
    5544             :  *  This needs to be careful about handling databases for which no stats file
    5545             :  *  exists, such as databases without a stat entry or those not yet written:
    5546             :  *
    5547             :  *  - if there's a database entry in the global file, return the corresponding
    5548             :  *  stats_timestamp value.
    5549             :  *
    5550             :  *  - if there's no db stat entry (e.g. for a new or inactive database),
    5551             :  *  there's no stats_timestamp value, but also nothing to write so we return
    5552             :  *  the timestamp of the global statfile.
    5553             :  * ----------
    5554             :  */
    5555             : static bool
    5556        5834 : pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
    5557             :                                    TimestampTz *ts)
    5558             : {
    5559             :     PgStat_StatDBEntry dbentry;
    5560             :     PgStat_GlobalStats myGlobalStats;
    5561             :     PgStat_ArchiverStats myArchiverStats;
    5562             :     PgStat_SLRUStats mySLRUStats[SLRU_NUM_ELEMENTS];
    5563             :     FILE       *fpin;
    5564             :     int32       format_id;
    5565        5834 :     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
    5566             : 
    5567             :     /*
    5568             :      * Try to open the stats file.  As above, anything but ENOENT is worthy of
    5569             :      * complaining about.
    5570             :      */
    5571        5834 :     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
    5572             :     {
    5573        1564 :         if (errno != ENOENT)
    5574           0 :             ereport(pgStatRunningInCollector ? LOG : WARNING,
    5575             :                     (errcode_for_file_access(),
    5576             :                      errmsg("could not open statistics file \"%s\": %m",
    5577             :                             statfile)));
    5578        1564 :         return false;
    5579             :     }
    5580             : 
    5581             :     /*
    5582             :      * Verify it's of the expected format.
    5583             :      */
    5584        4270 :     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
    5585        4270 :         format_id != PGSTAT_FILE_FORMAT_ID)
    5586             :     {
    5587           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5588             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5589           0 :         FreeFile(fpin);
    5590           0 :         return false;
    5591             :     }
    5592             : 
    5593             :     /*
    5594             :      * Read global stats struct
    5595             :      */
    5596        4270 :     if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
    5597             :               fpin) != sizeof(myGlobalStats))
    5598             :     {
    5599           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5600             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5601           0 :         FreeFile(fpin);
    5602           0 :         return false;
    5603             :     }
    5604             : 
    5605             :     /*
    5606             :      * Read archiver stats struct
    5607             :      */
    5608        4270 :     if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
    5609             :               fpin) != sizeof(myArchiverStats))
    5610             :     {
    5611           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5612             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5613           0 :         FreeFile(fpin);
    5614           0 :         return false;
    5615             :     }
    5616             : 
    5617             :     /*
    5618             :      * Read SLRU stats struct
    5619             :      */
    5620        4270 :     if (fread(mySLRUStats, 1, sizeof(mySLRUStats), fpin) != sizeof(mySLRUStats))
    5621             :     {
    5622           0 :         ereport(pgStatRunningInCollector ? LOG : WARNING,
    5623             :                 (errmsg("corrupted statistics file \"%s\"", statfile)));
    5624           0 :         FreeFile(fpin);
    5625           0 :         return false;
    5626             :     }
    5627             : 
    5628             :     /* By default, we're going to return the timestamp of the global file. */
    5629        4270 :     *ts = myGlobalStats.stats_timestamp;
    5630             : 
    5631             :     /*
    5632             :      * We found an existing collector stats file.  Read it and look for a
    5633             :      * record for the requested database.  If found, use its timestamp.
    5634             :      */
    5635             :     for (;;)
    5636             :     {
    5637        6252 :         switch (fgetc(fpin))
    5638             :         {
    5639             :                 /*
    5640             :                  * 'D'  A PgStat_StatDBEntry struct describing a database
    5641             :                  * follows.
    5642             :                  */
    5643        5180 :             case 'D':
    5644        5180 :                 if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
    5645             :                           fpin) != offsetof(PgStat_StatDBEntry, tables))
    5646             :                 {
    5647           0 :                     ereport(pgStatRunningInCollector ? LOG : WARNING,
    5648             :                             (errmsg("corrupted statistics file \"%s\"",
    5649             :                                     statfile)));
    5650           0 :                     goto done;
    5651             :                 }
    5652             : 
    5653             :                 /*
    5654             :                  * If this is the DB we're looking for, save its timestamp and
    5655             :                  * we're done.
    5656             :                  */
    5657        5180 :                 if (dbentry.databaseid == databaseid)
    5658             :                 {
    5659        3198 :                     *ts = dbentry.stats_timestamp;
    5660        3198 :                     goto done;
    5661             :                 }
    5662             : 
    5663        1982 :                 break;
    5664             : 
    5665        1072 :             case 'E':
    5666        1072 :                 goto done;
    5667             : 
    5668           0 :             default:
    5669           0 :                 ereport(pgStatRunningInCollector ? LOG : WARNING,
    5670             :                         (errmsg("corrupted statistics file \"%s\"",
    5671             :                                 statfile)));
    5672           0 :                 goto done;
    5673             :         }
    5674             :     }
    5675             : 
    5676        4270 : done:
    5677        4270 :     FreeFile(fpin);
    5678        4270 :     return true;
    5679             : }
    5680             : 
    5681             : /*
    5682             :  * If not already done, read the statistics collector stats file into
    5683             :  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
    5684             :  * is called (typically, at end of transaction).
    5685             :  */
    5686             : static void
    5687        6190 : backend_read_statsfile(void)
    5688             : {
    5689        6190 :     TimestampTz min_ts = 0;
    5690        6190 :     TimestampTz ref_ts = 0;
    5691             :     Oid         inquiry_db;
    5692             :     int         count;
    5693             : 
    5694             :     /* already read it? */
    5695        6190 :     if (pgStatDBHash)
    5696        2468 :         return;
    5697             :     Assert(!pgStatRunningInCollector);
    5698             : 
    5699             :     /*
    5700             :      * In a normal backend, we check staleness of the data for our own DB, and
    5701             :      * so we send MyDatabaseId in inquiry messages.  In the autovac launcher,
    5702             :      * check staleness of the shared-catalog data, and send InvalidOid in
    5703             :      * inquiry messages so as not to force writing unnecessary data.
    5704             :      */
    5705        3722 :     if (IsAutoVacuumLauncherProcess())
    5706         726 :         inquiry_db = InvalidOid;
    5707             :     else
    5708        2996 :         inquiry_db = MyDatabaseId;
    5709             : 
    5710             :     /*
    5711             :      * Loop until fresh enough stats file is available or we ran out of time.
    5712             :      * The stats inquiry message is sent repeatedly in case collector drops
    5713             :      * it; but not every single time, as that just swamps the collector.
    5714             :      */
    5715        5834 :     for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
    5716             :     {
    5717             :         bool        ok;
    5718        5834 :         TimestampTz file_ts = 0;
    5719             :         TimestampTz cur_ts;
    5720             : 
    5721        5834 :         CHECK_FOR_INTERRUPTS();
    5722             : 
    5723        5834 :         ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
    5724             : 
    5725        5834 :         cur_ts = GetCurrentTimestamp();
    5726             :         /* Calculate min acceptable timestamp, if we didn't already */
    5727        5834 :         if (count == 0 || cur_ts < ref_ts)
    5728             :         {
    5729             :             /*
    5730             :              * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
    5731             :              * msec before now.  This indirectly ensures that the collector
    5732             :              * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
    5733             :              * an autovacuum worker, however, we want a lower delay to avoid
    5734             :              * using stale data, so we use PGSTAT_RETRY_DELAY (since the
    5735             :              * number of workers is low, this shouldn't be a problem).
    5736             :              *
    5737             :              * We don't recompute min_ts after sleeping, except in the
    5738             :              * unlikely case that cur_ts went backwards.  So we might end up
    5739             :              * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In
    5740             :              * practice that shouldn't happen, though, as long as the sleep
    5741             :              * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
    5742             :              * tell the collector that our cutoff time is less than what we'd
    5743             :              * actually accept.
    5744             :              */
    5745        3722 :             ref_ts = cur_ts;
    5746        3722 :             if (IsAutoVacuumWorkerProcess())
    5747         328 :                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
    5748             :                                                      -PGSTAT_RETRY_DELAY);
    5749             :             else
    5750        3394 :                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
    5751             :                                                      -PGSTAT_STAT_INTERVAL);
    5752             :         }
    5753             : 
    5754             :         /*
    5755             :          * If the file timestamp is actually newer than cur_ts, we must have
    5756             :          * had a clock glitch (system time went backwards) or there is clock
    5757             :          * skew between our processor and the stats collector's processor.
    5758             :          * Accept the file, but send an inquiry message anyway to make
    5759             :          * pgstat_recv_inquiry do a sanity check on the collector's time.
    5760             :          */
    5761        5834 :         if (ok && file_ts > cur_ts)
    5762             :         {
    5763             :             /*
    5764             :              * A small amount of clock skew between processors isn't terribly
    5765             :              * surprising, but a large difference is worth logging.  We
    5766             :              * arbitrarily define "large" as 1000 msec.
    5767             :              */
    5768           0 :             if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
    5769             :             {
    5770             :                 char       *filetime;
    5771             :                 char       *mytime;
    5772             : 
    5773             :                 /* Copy because timestamptz_to_str returns a static buffer */
    5774           0 :                 filetime = pstrdup(timestamptz_to_str(file_ts));
    5775           0 :                 mytime = pstrdup(timestamptz_to_str(cur_ts));
    5776           0 :                 elog(LOG, "stats collector's time %s is later than backend local time %s",
    5777             :                      filetime, mytime);
    5778           0 :                 pfree(filetime);
    5779           0 :                 pfree(mytime);
    5780             :             }
    5781             : 
    5782           0 :             pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
    5783        3722 :             break;
    5784             :         }
    5785             : 
    5786             :         /* Normal acceptance case: file is not older than cutoff time */
    5787        5834 :         if (ok && file_ts >= min_ts)
    5788        3722 :             break;
    5789             : 
    5790             :         /* Not there or too old, so kick the collector and wait a bit */
    5791        2112 :         if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
    5792         912 :             pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
    5793             : 
    5794        2112 :         pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
    5795             :     }
    5796             : 
    5797        3722 :     if (count >= PGSTAT_POLL_LOOP_COUNT)
    5798           0 :         ereport(LOG,
    5799             :                 (errmsg("using stale statistics instead of current ones "
    5800             :                         "because stats collector is not responding")));
    5801             : 
    5802             :     /*
    5803             :      * Autovacuum launcher wants stats about all databases, but a shallow read
    5804             :      * is sufficient.  Regular backends want a deep read for just the tables
    5805             :      * they can see (MyDatabaseId + shared catalogs).
    5806             :      */
    5807        3722 :     if (IsAutoVacuumLauncherProcess())
    5808         726 :         pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
    5809             :     else
    5810        2996 :         pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
    5811             : }
    5812             : 
    5813             : 
    5814             : /* ----------
    5815             :  * pgstat_setup_memcxt() -
    5816             :  *
    5817             :  *  Create pgStatLocalContext, if not already done.
    5818             :  * ----------
    5819             :  */
    5820             : static void
    5821        4742 : pgstat_setup_memcxt(void)
    5822             : {
    5823        4742 :     if (!pgStatLocalContext)
    5824        4742 :         pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
    5825             :                                                    "Statistics snapshot",
    5826             :                                                    ALLOCSET_SMALL_SIZES);
    5827        4742 : }
    5828             : 
    5829             : 
    5830             : /* ----------
    5831             :  * pgstat_clear_snapshot() -
    5832             :  *
    5833             :  *  Discard any data collected in the current transaction.  Any subsequent
    5834             :  *  request will cause new snapshots to be read.
    5835             :  *
    5836             :  *  This is also invoked during transaction commit or abort to discard
    5837             :  *  the no-longer-wanted snapshot.
    5838             :  * ----------
    5839             :  */
    5840             : void
    5841      495466 : pgstat_clear_snapshot(void)
    5842             : {
    5843             :     /* Release memory, if any was allocated */
    5844      495466 :     if (pgStatLocalContext)
    5845        3680 :         MemoryContextDelete(pgStatLocalContext);
    5846             : 
    5847             :     /* Reset variables */
    5848      495466 :     pgStatLocalContext = NULL;
    5849      495466 :     pgStatDBHash = NULL;
    5850      495466 :     localBackendStatusTable = NULL;
    5851      495466 :     localNumBackends = 0;
    5852      495466 : }
    5853             : 
    5854             : 
    5855             : /* ----------
    5856             :  * pgstat_recv_inquiry() -
    5857             :  *
    5858             :  *  Process stat inquiry requests.
    5859             :  * ----------
    5860             :  */
    5861             : static void
    5862        1184 : pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
    5863             : {
    5864             :     PgStat_StatDBEntry *dbentry;
    5865             : 
    5866        1184 :     elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
    5867             : 
    5868             :     /*
    5869             :      * If there's already a write request for this DB, there's nothing to do.
    5870             :      *
    5871             :      * Note that if a request is found, we return early and skip the below
    5872             :      * check for clock skew.  This is okay, since the only way for a DB
    5873             :      * request to be present in the list is that we have been here since the
    5874             :      * last write round.  It seems sufficient to check for clock skew once per
    5875             :      * write round.
    5876             :      */
    5877        1184 :     if (list_member_oid(pending_write_requests, msg->databaseid))
    5878           0 :         return;
    5879             : 
    5880             :     /*
    5881             :      * Check to see if we last wrote this database at a time >= the requested
    5882             :      * cutoff time.  If so, this is a stale request that was generated before
    5883             :      * we updated the DB file, and we don't need to do so again.
    5884             :      *
    5885             :      * If the requestor's local clock time is older than stats_timestamp, we
    5886             :      * should suspect a clock glitch, ie system time going backwards; though
    5887             :      * the more likely explanation is just delayed message receipt.  It is
    5888             :      * worth expending a GetCurrentTimestamp call to be sure, since a large
    5889             :      * retreat in the system clock reading could otherwise cause us to neglect
    5890             :      * to update the stats file for a long time.
    5891             :      */
    5892        1184 :     dbentry = pgstat_get_db_entry(msg->databaseid, false);
    5893        1184 :     if (dbentry == NULL)
    5894             :     {
    5895             :         /*
    5896             :          * We have no data for this DB.  Enter a write request anyway so that
    5897             :          * the global stats will get updated.  This is needed to prevent
    5898             :          * backend_read_statsfile from waiting for data that we cannot supply,
    5899             :          * in the case of a new DB that nobody has yet reported any stats for.
    5900             :          * See the behavior of pgstat_read_db_statsfile_timestamp.
    5901             :          */
    5902             :     }
    5903         716 :     else if (msg->clock_time < dbentry->stats_timestamp)
    5904             :     {
    5905           0 :         TimestampTz cur_ts = GetCurrentTimestamp();
    5906             : 
    5907           0 :         if (cur_ts < dbentry->stats_timestamp)
    5908             :         {
    5909             :             /*
    5910             :              * Sure enough, time went backwards.  Force a new stats file write
    5911             :              * to get back in sync; but first, log a complaint.
    5912             :              */
    5913             :             char       *writetime;
    5914             :             char       *mytime;
    5915             : 
    5916             :             /* Copy because timestamptz_to_str returns a static buffer */
    5917           0 :             writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
    5918           0 :             mytime = pstrdup(timestamptz_to_str(cur_ts));
    5919           0 :             elog(LOG,
    5920             :                  "stats_timestamp %s is later than collector's time %s for database %u",
    5921             :                  writetime, mytime, dbentry->databaseid);
    5922           0 :             pfree(writetime);
    5923           0 :             pfree(mytime);
    5924             :         }
    5925             :         else
    5926             :         {
    5927             :             /*
    5928             :              * Nope, it's just an old request.  Assuming msg's clock_time is
    5929             :              * >= its cutoff_time, it must be stale, so we can ignore it.
    5930             :              */
    5931           0 :             return;
    5932             :         }
    5933             :     }
    5934         716 :     else if (msg->cutoff_time <= dbentry->stats_timestamp)
    5935             :     {
    5936             :         /* Stale request, ignore it */
    5937           0 :         return;
    5938             :     }
    5939             : 
    5940             :     /*
    5941             :      * We need to write this DB, so create a request.
    5942             :      */
    5943        1184 :     pending_write_requests = lappend_oid(pending_write_requests,
    5944             :                                          msg->databaseid);
    5945             : }
    5946             : 
    5947             : 
    5948             : /* ----------
    5949             :  * pgstat_recv_tabstat() -
    5950             :  *
    5951             :  *  Count what the backend has done.
    5952             :  * ----------
    5953             :  */
    5954             : static void
    5955       85056 : pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
    5956             : {
    5957             :     PgStat_StatDBEntry *dbentry;
    5958             :     PgStat_StatTabEntry *tabentry;
    5959             :     int         i;
    5960             :     bool        found;
    5961             : 
    5962       85056 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    5963             : 
    5964             :     /*
    5965             :      * Update database-wide stats.
    5966             :      */
    5967       85056 :     dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
    5968       85056 :     dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
    5969       85056 :     dbentry->n_block_read_time += msg->m_block_read_time;
    5970       85056 :     dbentry->n_block_write_time += msg->m_block_write_time;
    5971             : 
    5972             :     /*
    5973             :      * Process all table entries in the message.
    5974             :      */
    5975      645228 :     for (i = 0; i < msg->m_nentries; i++)
    5976             :     {
    5977      560172 :         PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
    5978             : 
    5979      560172 :         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
    5980      560172 :                                                        (void *) &(tabmsg->t_id),
    5981             :                                                        HASH_ENTER, &found);
    5982             : 
    5983      560172 :         if (!found)
    5984             :         {
    5985             :             /*
    5986             :              * If it's a new table entry, initialize counters to the values we
    5987             :              * just got.
    5988             :              */
    5989       69958 :             tabentry->numscans = tabmsg->t_counts.t_numscans;
    5990       69958 :             tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
    5991       69958 :             tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
    5992       69958 :             tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
    5993       69958 :             tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
    5994       69958 :             tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
    5995       69958 :             tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
    5996       69958 :             tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
    5997       69958 :             tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
    5998       69958 :             tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
    5999       69958 :             tabentry->inserts_since_vacuum = tabmsg->t_counts.t_tuples_inserted;
    6000       69958 :             tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
    6001       69958 :             tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
    6002             : 
    6003       69958 :             tabentry->vacuum_timestamp = 0;
    6004       69958 :             tabentry->vacuum_count = 0;
    6005       69958 :             tabentry->autovac_vacuum_timestamp = 0;
    6006       69958 :             tabentry->autovac_vacuum_count = 0;
    6007       69958 :             tabentry->analyze_timestamp = 0;
    6008       69958 :             tabentry->analyze_count = 0;
    6009       69958 :             tabentry->autovac_analyze_timestamp = 0;
    6010       69958 :             tabentry->autovac_analyze_count = 0;
    6011             :         }
    6012             :         else
    6013             :         {
    6014             :             /*
    6015             :              * Otherwise add the values to the existing entry.
    6016             :              */
    6017      490214 :             tabentry->numscans += tabmsg->t_counts.t_numscans;
    6018      490214 :             tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
    6019      490214 :             tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
    6020      490214 :             tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
    6021      490214 :             tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
    6022      490214 :             tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
    6023      490214 :             tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
    6024             :             /* If table was truncated, first reset the live/dead counters */
    6025      490214 :             if (tabmsg->t_counts.t_truncated)
    6026             :             {
    6027         192 :                 tabentry->n_live_tuples = 0;
    6028         192 :                 tabentry->n_dead_tuples = 0;
    6029         192 :                 tabentry->inserts_since_vacuum = 0;
    6030             :             }
    6031      490214 :             tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
    6032      490214 :             tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
    6033      490214 :             tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
    6034      490214 :             tabentry->inserts_since_vacuum += tabmsg->t_counts.t_tuples_inserted;
    6035      490214 :             tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
    6036      490214 :             tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
    6037             :         }
    6038             : 
    6039             :         /* Clamp n_live_tuples in case of negative delta_live_tuples */
    6040      560172 :         tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
    6041             :         /* Likewise for n_dead_tuples */
    6042      560172 :         tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
    6043             : 
    6044             :         /*
    6045             :          * Add per-table stats to the per-database entry, too.
    6046             :          */
    6047      560172 :         dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
    6048      560172 :         dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
    6049      560172 :         dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
    6050      560172 :         dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
    6051      560172 :         dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
    6052      560172 :         dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
    6053      560172 :         dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
    6054             :     }
    6055       85056 : }
    6056             : 
    6057             : 
    6058             : /* ----------
    6059             :  * pgstat_recv_tabpurge() -
    6060             :  *
    6061             :  *  Arrange for dead table removal.
    6062             :  * ----------
    6063             :  */
    6064             : static void
    6065         802 : pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
    6066             : {
    6067             :     PgStat_StatDBEntry *dbentry;
    6068             :     int         i;
    6069             : 
    6070         802 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    6071             : 
    6072             :     /*
    6073             :      * No need to purge if we don't even know the database.
    6074             :      */
    6075         802 :     if (!dbentry || !dbentry->tables)
    6076           0 :         return;
    6077             : 
    6078             :     /*
    6079             :      * Process all table entries in the message.
    6080             :      */
    6081       83878 :     for (i = 0; i < msg->m_nentries; i++)
    6082             :     {
    6083             :         /* Remove from hashtable if present; we don't care if it's not. */
    6084       83076 :         (void) hash_search(dbentry->tables,
    6085       83076 :                            (void *) &(msg->m_tableid[i]),
    6086             :                            HASH_REMOVE, NULL);
    6087             :     }
    6088             : }
    6089             : 
    6090             : 
    6091             : /* ----------
    6092             :  * pgstat_recv_dropdb() -
    6093             :  *
    6094             :  *  Arrange for dead database removal
    6095             :  * ----------
    6096             :  */
    6097             : static void
    6098          18 : pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
    6099             : {
    6100          18 :     Oid         dbid = msg->m_databaseid;
    6101             :     PgStat_StatDBEntry *dbentry;
    6102             : 
    6103             :     /*
    6104             :      * Lookup the database in the hashtable.
    6105             :      */
    6106          18 :     dbentry = pgstat_get_db_entry(dbid, false);
    6107             : 
    6108             :     /*
    6109             :      * If found, remove it (along with the db statfile).
    6110             :      */
    6111          18 :     if (dbentry)
    6112             :     {
    6113             :         char        statfile[MAXPGPATH];
    6114             : 
    6115          10 :         get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
    6116             : 
    6117          10 :         elog(DEBUG2, "removing stats file \"%s\"", statfile);
    6118          10 :         unlink(statfile);
    6119             : 
    6120          10 :         if (dbentry->tables != NULL)
    6121          10 :             hash_destroy(dbentry->tables);
    6122          10 :         if (dbentry->functions != NULL)
    6123          10 :             hash_destroy(dbentry->functions);
    6124             : 
    6125          10 :         if (hash_search(pgStatDBHash,
    6126             :                         (void *) &dbid,
    6127             :                         HASH_REMOVE, NULL) == NULL)
    6128           0 :             ereport(ERROR,
    6129             :                     (errmsg("database hash table corrupted during cleanup --- abort")));
    6130             :     }
    6131          18 : }
    6132             : 
    6133             : 
    6134             : /* ----------
    6135             :  * pgstat_recv_resetcounter() -
    6136             :  *
    6137             :  *  Reset the statistics for the specified database.
    6138             :  * ----------
    6139             :  */
    6140             : static void
    6141           0 : pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
    6142             : {
    6143             :     PgStat_StatDBEntry *dbentry;
    6144             : 
    6145             :     /*
    6146             :      * Lookup the database in the hashtable.  Nothing to do if not there.
    6147             :      */
    6148           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    6149             : 
    6150           0 :     if (!dbentry)
    6151           0 :         return;
    6152             : 
    6153             :     /*
    6154             :      * We simply throw away all the database's table entries by recreating a
    6155             :      * new hash table for them.
    6156             :      */
    6157           0 :     if (dbentry->tables != NULL)
    6158           0 :         hash_destroy(dbentry->tables);
    6159           0 :     if (dbentry->functions != NULL)
    6160           0 :         hash_destroy(dbentry->functions);
    6161             : 
    6162           0 :     dbentry->tables = NULL;
    6163           0 :     dbentry->functions = NULL;
    6164             : 
    6165             :     /*
    6166             :      * Reset database-level stats, too.  This creates empty hash tables for
    6167             :      * tables and functions.
    6168             :      */
    6169           0 :     reset_dbentry_counters(dbentry);
    6170             : }
    6171             : 
    6172             : /* ----------
    6173             :  * pgstat_recv_resetsharedcounter() -
    6174             :  *
    6175             :  *  Reset some shared statistics of the cluster.
    6176             :  * ----------
    6177             :  */
    6178             : static void
    6179           2 : pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
    6180             : {
    6181           2 :     if (msg->m_resettarget == RESET_BGWRITER)
    6182             :     {
    6183             :         /* Reset the global background writer statistics for the cluster. */
    6184           0 :         memset(&globalStats, 0, sizeof(globalStats));
    6185           0 :         globalStats.stat_reset_timestamp = GetCurrentTimestamp();
    6186             :     }
    6187           2 :     else if (msg->m_resettarget == RESET_ARCHIVER)
    6188             :     {
    6189             :         /* Reset the archiver statistics for the cluster. */
    6190           2 :         memset(&archiverStats, 0, sizeof(archiverStats));
    6191           2 :         archiverStats.stat_reset_timestamp = GetCurrentTimestamp();
    6192             :     }
    6193             : 
    6194             :     /*
    6195             :      * Presumably the sender of this message validated the target, don't
    6196             :      * complain here if it's not valid
    6197             :      */
    6198           2 : }
    6199             : 
    6200             : /* ----------
    6201             :  * pgstat_recv_resetsinglecounter() -
    6202             :  *
    6203             :  *  Reset a statistics for a single object
    6204             :  * ----------
    6205             :  */
    6206             : static void
    6207           0 : pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
    6208             : {
    6209             :     PgStat_StatDBEntry *dbentry;
    6210             : 
    6211           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    6212             : 
    6213           0 :     if (!dbentry)
    6214           0 :         return;
    6215             : 
    6216             :     /* Set the reset timestamp for the whole database */
    6217           0 :     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
    6218             : 
    6219             :     /* Remove object if it exists, ignore it if not */
    6220           0 :     if (msg->m_resettype == RESET_TABLE)
    6221           0 :         (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
    6222             :                            HASH_REMOVE, NULL);
    6223           0 :     else if (msg->m_resettype == RESET_FUNCTION)
    6224           0 :         (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
    6225             :                            HASH_REMOVE, NULL);
    6226             : }
    6227             : 
    6228             : /* ----------
    6229             :  * pgstat_recv_resetslrucounter() -
    6230             :  *
    6231             :  *  Reset some SLRU statistics of the cluster.
    6232             :  * ----------
    6233             :  */
    6234             : static void
    6235           0 : pgstat_recv_resetslrucounter(PgStat_MsgResetslrucounter *msg, int len)
    6236             : {
    6237             :     int         i;
    6238           0 :     TimestampTz ts = GetCurrentTimestamp();
    6239             : 
    6240           0 :     for (i = 0; i < SLRU_NUM_ELEMENTS; i++)
    6241             :     {
    6242             :         /* reset entry with the given index, or all entries (index is -1) */
    6243           0 :         if ((msg->m_index == -1) || (msg->m_index == i))
    6244             :         {
    6245           0 :             memset(&slruStats[i], 0, sizeof(slruStats[i]));
    6246           0 :             slruStats[i].stat_reset_timestamp = ts;
    6247             :         }
    6248             :     }
    6249           0 : }
    6250             : 
    6251             : /* ----------
    6252             :  * pgstat_recv_autovac() -
    6253             :  *
    6254             :  *  Process an autovacuum signalling message.
    6255             :  * ----------
    6256             :  */
    6257             : static void
    6258          60 : pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
    6259             : {
    6260             :     PgStat_StatDBEntry *dbentry;
    6261             : 
    6262             :     /*
    6263             :      * Store the last autovacuum time in the database's hashtable entry.
    6264             :      */
    6265          60 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6266             : 
    6267          60 :     dbentry->last_autovac_time = msg->m_start_time;
    6268          60 : }
    6269             : 
    6270             : /* ----------
    6271             :  * pgstat_recv_vacuum() -
    6272             :  *
    6273             :  *  Process a VACUUM message.
    6274             :  * ----------
    6275             :  */
    6276             : static void
    6277        4760 : pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
    6278             : {
    6279             :     PgStat_StatDBEntry *dbentry;
    6280             :     PgStat_StatTabEntry *tabentry;
    6281             : 
    6282             :     /*
    6283             :      * Store the data in the table's hashtable entry.
    6284             :      */
    6285        4760 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6286             : 
    6287        4760 :     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
    6288             : 
    6289        4760 :     tabentry->n_live_tuples = msg->m_live_tuples;
    6290        4760 :     tabentry->n_dead_tuples = msg->m_dead_tuples;
    6291             : 
    6292             :     /*
    6293             :      * It is quite possible that a non-aggressive VACUUM ended up skipping
    6294             :      * various pages, however, we'll zero the insert counter here regardless.
    6295             :      * It's currently used only to track when we need to perform an "insert"
    6296             :      * autovacuum, which are mainly intended to freeze newly inserted tuples.
    6297             :      * Zeroing this may just mean we'll not try to vacuum the table again
    6298             :      * until enough tuples have been inserted to trigger another insert
    6299             :      * autovacuum.  An anti-wraparound autovacuum will catch any persistent
    6300             :      * stragglers.
    6301             :      */
    6302        4760 :     tabentry->inserts_since_vacuum = 0;
    6303             : 
    6304        4760 :     if (msg->m_autovacuum)
    6305             :     {
    6306         118 :         tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
    6307         118 :         tabentry->autovac_vacuum_count++;
    6308             :     }
    6309             :     else
    6310             :     {
    6311        4642 :         tabentry->vacuum_timestamp = msg->m_vacuumtime;
    6312        4642 :         tabentry->vacuum_count++;
    6313             :     }
    6314        4760 : }
    6315             : 
    6316             : /* ----------
    6317             :  * pgstat_recv_analyze() -
    6318             :  *
    6319             :  *  Process an ANALYZE message.
    6320             :  * ----------
    6321             :  */
    6322             : static void
    6323        9978 : pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
    6324             : {
    6325             :     PgStat_StatDBEntry *dbentry;
    6326             :     PgStat_StatTabEntry *tabentry;
    6327             : 
    6328             :     /*
    6329             :      * Store the data in the table's hashtable entry.
    6330             :      */
    6331        9978 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6332             : 
    6333        9978 :     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
    6334             : 
    6335        9978 :     tabentry->n_live_tuples = msg->m_live_tuples;
    6336        9978 :     tabentry->n_dead_tuples = msg->m_dead_tuples;
    6337             : 
    6338             :     /*
    6339             :      * If commanded, reset changes_since_analyze to zero.  This forgets any
    6340             :      * changes that were committed while the ANALYZE was in progress, but we
    6341             :      * have no good way to estimate how many of those there were.
    6342             :      */
    6343        9978 :     if (msg->m_resetcounter)
    6344        9954 :         tabentry->changes_since_analyze = 0;
    6345             : 
    6346        9978 :     if (msg->m_autovacuum)
    6347             :     {
    6348         250 :         tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
    6349         250 :         tabentry->autovac_analyze_count++;
    6350             :     }
    6351             :     else
    6352             :     {
    6353        9728 :         tabentry->analyze_timestamp = msg->m_analyzetime;
    6354        9728 :         tabentry->analyze_count++;
    6355             :     }
    6356        9978 : }
    6357             : 
    6358             : 
    6359             : /* ----------
    6360             :  * pgstat_recv_archiver() -
    6361             :  *
    6362             :  *  Process a ARCHIVER message.
    6363             :  * ----------
    6364             :  */
    6365             : static void
    6366          48 : pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len)
    6367             : {
    6368          48 :     if (msg->m_failed)
    6369             :     {
    6370             :         /* Failed archival attempt */
    6371          10 :         ++archiverStats.failed_count;
    6372          10 :         memcpy(archiverStats.last_failed_wal, msg->m_xlog,
    6373             :                sizeof(archiverStats.last_failed_wal));
    6374          10 :         archiverStats.last_failed_timestamp = msg->m_timestamp;
    6375             :     }
    6376             :     else
    6377             :     {
    6378             :         /* Successful archival operation */
    6379          38 :         ++archiverStats.archived_count;
    6380          38 :         memcpy(archiverStats.last_archived_wal, msg->m_xlog,
    6381             :                sizeof(archiverStats.last_archived_wal));
    6382          38 :         archiverStats.last_archived_timestamp = msg->m_timestamp;
    6383             :     }
    6384          48 : }
    6385             : 
    6386             : /* ----------
    6387             :  * pgstat_recv_bgwriter() -
    6388             :  *
    6389             :  *  Process a BGWRITER message.
    6390             :  * ----------
    6391             :  */
    6392             : static void
    6393        9176 : pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
    6394             : {
    6395        9176 :     globalStats.timed_checkpoints += msg->m_timed_checkpoints;
    6396        9176 :     globalStats.requested_checkpoints += msg->m_requested_checkpoints;
    6397        9176 :     globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
    6398        9176 :     globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
    6399        9176 :     globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
    6400        9176 :     globalStats.buf_written_clean += msg->m_buf_written_clean;
    6401        9176 :     globalStats.maxwritten_clean += msg->m_maxwritten_clean;
    6402        9176 :     globalStats.buf_written_backend += msg->m_buf_written_backend;
    6403        9176 :     globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
    6404        9176 :     globalStats.buf_alloc += msg->m_buf_alloc;
    6405        9176 : }
    6406             : 
    6407             : /* ----------
    6408             :  * pgstat_recv_slru() -
    6409             :  *
    6410             :  *  Process a SLRU message.
    6411             :  * ----------
    6412             :  */
    6413             : static void
    6414        8540 : pgstat_recv_slru(PgStat_MsgSLRU *msg, int len)
    6415             : {
    6416        8540 :     slruStats[msg->m_index].blocks_zeroed += msg->m_blocks_zeroed;
    6417        8540 :     slruStats[msg->m_index].blocks_hit += msg->m_blocks_hit;
    6418        8540 :     slruStats[msg->m_index].blocks_read += msg->m_blocks_read;
    6419        8540 :     slruStats[msg->m_index].blocks_written += msg->m_blocks_written;
    6420        8540 :     slruStats[msg->m_index].blocks_exists += msg->m_blocks_exists;
    6421        8540 :     slruStats[msg->m_index].flush += msg->m_flush;
    6422        8540 :     slruStats[msg->m_index].truncate += msg->m_truncate;
    6423        8540 : }
    6424             : 
    6425             : /* ----------
    6426             :  * pgstat_recv_recoveryconflict() -
    6427             :  *
    6428             :  *  Process a RECOVERYCONFLICT message.
    6429             :  * ----------
    6430             :  */
    6431             : static void
    6432           0 : pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
    6433             : {
    6434             :     PgStat_StatDBEntry *dbentry;
    6435             : 
    6436           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6437             : 
    6438           0 :     switch (msg->m_reason)
    6439             :     {
    6440           0 :         case PROCSIG_RECOVERY_CONFLICT_DATABASE:
    6441             : 
    6442             :             /*
    6443             :              * Since we drop the information about the database as soon as it
    6444             :              * replicates, there is no point in counting these conflicts.
    6445             :              */
    6446           0 :             break;
    6447           0 :         case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
    6448           0 :             dbentry->n_conflict_tablespace++;
    6449           0 :             break;
    6450           0 :         case PROCSIG_RECOVERY_CONFLICT_LOCK:
    6451           0 :             dbentry->n_conflict_lock++;
    6452           0 :             break;
    6453           0 :         case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
    6454           0 :             dbentry->n_conflict_snapshot++;
    6455           0 :             break;
    6456           0 :         case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
    6457           0 :             dbentry->n_conflict_bufferpin++;
    6458           0 :             break;
    6459           0 :         case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
    6460           0 :             dbentry->n_conflict_startup_deadlock++;
    6461           0 :             break;
    6462             :     }
    6463           0 : }
    6464             : 
    6465             : /* ----------
    6466             :  * pgstat_recv_deadlock() -
    6467             :  *
    6468             :  *  Process a DEADLOCK message.
    6469             :  * ----------
    6470             :  */
    6471             : static void
    6472           4 : pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
    6473             : {
    6474             :     PgStat_StatDBEntry *dbentry;
    6475             : 
    6476           4 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6477             : 
    6478           4 :     dbentry->n_deadlocks++;
    6479           4 : }
    6480             : 
    6481             : /* ----------
    6482             :  * pgstat_recv_checksum_failure() -
    6483             :  *
    6484             :  *  Process a CHECKSUMFAILURE message.
    6485             :  * ----------
    6486             :  */
    6487             : static void
    6488           4 : pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len)
    6489             : {
    6490             :     PgStat_StatDBEntry *dbentry;
    6491             : 
    6492           4 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6493             : 
    6494           4 :     dbentry->n_checksum_failures += msg->m_failurecount;
    6495           4 :     dbentry->last_checksum_failure = msg->m_failure_time;
    6496           4 : }
    6497             : 
    6498             : /* ----------
    6499             :  * pgstat_recv_tempfile() -
    6500             :  *
    6501             :  *  Process a TEMPFILE message.
    6502             :  * ----------
    6503             :  */
    6504             : static void
    6505        3632 : pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
    6506             : {
    6507             :     PgStat_StatDBEntry *dbentry;
    6508             : 
    6509        3632 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6510             : 
    6511        3632 :     dbentry->n_temp_bytes += msg->m_filesize;
    6512        3632 :     dbentry->n_temp_files += 1;
    6513        3632 : }
    6514             : 
    6515             : /* ----------
    6516             :  * pgstat_recv_funcstat() -
    6517             :  *
    6518             :  *  Count what the backend has done.
    6519             :  * ----------
    6520             :  */
    6521             : static void
    6522           0 : pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
    6523             : {
    6524           0 :     PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
    6525             :     PgStat_StatDBEntry *dbentry;
    6526             :     PgStat_StatFuncEntry *funcentry;
    6527             :     int         i;
    6528             :     bool        found;
    6529             : 
    6530           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
    6531             : 
    6532             :     /*
    6533             :      * Process all function entries in the message.
    6534             :      */
    6535           0 :     for (i = 0; i < msg->m_nentries; i++, funcmsg++)
    6536             :     {
    6537           0 :         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
    6538           0 :                                                          (void *) &(funcmsg->f_id),
    6539             :                                                          HASH_ENTER, &found);
    6540             : 
    6541           0 :         if (!found)
    6542             :         {
    6543             :             /*
    6544             :              * If it's a new function entry, initialize counters to the values
    6545             :              * we just got.
    6546             :              */
    6547           0 :             funcentry->f_numcalls = funcmsg->f_numcalls;
    6548           0 :             funcentry->f_total_time = funcmsg->f_total_time;
    6549           0 :             funcentry->f_self_time = funcmsg->f_self_time;
    6550             :         }
    6551             :         else
    6552             :         {
    6553             :             /*
    6554             :              * Otherwise add the values to the existing entry.
    6555             :              */
    6556           0 :             funcentry->f_numcalls += funcmsg->f_numcalls;
    6557           0 :             funcentry->f_total_time += funcmsg->f_total_time;
    6558           0 :             funcentry->f_self_time += funcmsg->f_self_time;
    6559             :         }
    6560             :     }
    6561           0 : }
    6562             : 
    6563             : /* ----------
    6564             :  * pgstat_recv_funcpurge() -
    6565             :  *
    6566             :  *  Arrange for dead function removal.
    6567             :  * ----------
    6568             :  */
    6569             : static void
    6570           0 : pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
    6571             : {
    6572             :     PgStat_StatDBEntry *dbentry;
    6573             :     int         i;
    6574             : 
    6575           0 :     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
    6576             : 
    6577             :     /*
    6578             :      * No need to purge if we don't even know the database.
    6579             :      */
    6580           0 :     if (!dbentry || !dbentry->functions)
    6581           0 :         return;
    6582             : 
    6583             :     /*
    6584             :      * Process all function entries in the message.
    6585             :      */
    6586           0 :     for (i = 0; i < msg->m_nentries; i++)
    6587             :     {
    6588             :         /* Remove from hashtable if present; we don't care if it's not. */
    6589           0 :         (void) hash_search(dbentry->functions,
    6590           0 :                            (void *) &(msg->m_functionid[i]),
    6591             :                            HASH_REMOVE, NULL);
    6592             :     }
    6593             : }
    6594             : 
    6595             : /* ----------
    6596             :  * pgstat_write_statsfile_needed() -
    6597             :  *
    6598             :  *  Do we need to write out any stats files?
    6599             :  * ----------
    6600             :  */
    6601             : static bool
    6602      199996 : pgstat_write_statsfile_needed(void)
    6603             : {
    6604      199996 :     if (pending_write_requests != NIL)
    6605        1184 :         return true;
    6606             : 
    6607             :     /* Everything was written recently */
    6608      198812 :     return false;
    6609             : }
    6610             : 
    6611             : /* ----------
    6612             :  * pgstat_db_requested() -
    6613             :  *
    6614             :  *  Checks whether stats for a particular DB need to be written to a file.
    6615             :  * ----------
    6616             :  */
    6617             : static bool
    6618        2008 : pgstat_db_requested(Oid databaseid)
    6619             : {
    6620             :     /*
    6621             :      * If any requests are outstanding at all, we should write the stats for
    6622             :      * shared catalogs (the "database" with OID 0).  This ensures that
    6623             :      * backends will see up-to-date stats for shared catalogs, even though
    6624             :      * they send inquiry messages mentioning only their own DB.
    6625             :      */
    6626        2008 :     if (databaseid == InvalidOid && pending_write_requests != NIL)
    6627         716 :         return true;
    6628             : 
    6629             :     /* Search to see if there's an open request to write this database. */
    6630        1292 :     if (list_member_oid(pending_write_requests, databaseid))
    6631         510 :         return true;
    6632             : 
    6633         782 :     return false;
    6634             : }
    6635             : 
    6636             : /*
    6637             :  * Convert a potentially unsafely truncated activity string (see
    6638             :  * PgBackendStatus.st_activity_raw's documentation) into a correctly truncated
    6639             :  * one.
    6640             :  *
    6641             :  * The returned string is allocated in the caller's memory context and may be
    6642             :  * freed.
    6643             :  */
    6644             : char *
    6645        2222 : pgstat_clip_activity(const char *raw_activity)
    6646             : {
    6647             :     char       *activity;
    6648             :     int         rawlen;
    6649             :     int         cliplen;
    6650             : 
    6651             :     /*
    6652             :      * Some callers, like pgstat_get_backend_current_activity(), do not
    6653             :      * guarantee that the buffer isn't concurrently modified. We try to take
    6654             :      * care that the buffer is always terminated by a NUL byte regardless, but
    6655             :      * let's still be paranoid about the string's length. In those cases the
    6656             :      * underlying buffer is guaranteed to be pgstat_track_activity_query_size
    6657             :      * large.
    6658             :      */
    6659        2222 :     activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
    6660             : 
    6661             :     /* now double-guaranteed to be NUL terminated */
    6662        2222 :     rawlen = strlen(activity);
    6663             : 
    6664             :     /*
    6665             :      * All supported server-encodings make it possible to determine the length
    6666             :      * of a multi-byte character from its first byte (this is not the case for
    6667             :      * client encodings, see GB18030). As st_activity is always stored using
    6668             :      * server encoding, this allows us to perform multi-byte aware truncation,
    6669             :      * even if the string earlier was truncated in the middle of a multi-byte
    6670             :      * character.
    6671             :      */
    6672        2222 :     cliplen = pg_mbcliplen(activity, rawlen,
    6673             :                            pgstat_track_activity_query_size - 1);
    6674             : 
    6675        2222 :     activity[cliplen] = '\0';
    6676             : 
    6677        2222 :     return activity;
    6678             : }
    6679             : 
    6680             : /*
    6681             :  * pgstat_slru_index
    6682             :  *
    6683             :  * Determine index of entry for a SLRU with a given name. If there's no exact
    6684             :  * match, returns index of the last "other" entry used for SLRUs defined in
    6685             :  * external proejcts.
    6686             :  */
    6687             : int
    6688       15190 : pgstat_slru_index(const char *name)
    6689             : {
    6690             :     int         i;
    6691             : 
    6692       60760 :     for (i = 0; i < SLRU_NUM_ELEMENTS; i++)
    6693             :     {
    6694       60760 :         if (strcmp(slru_names[i], name) == 0)
    6695       15190 :             return i;
    6696             :     }
    6697             : 
    6698             :     /* return index of the last entry (which is the "other" one) */
    6699           0 :     return (SLRU_NUM_ELEMENTS - 1);
    6700             : }
    6701             : 
    6702             : /*
    6703             :  * pgstat_slru_name
    6704             :  *
    6705             :  * Returns SLRU name for an index. The index may be above SLRU_NUM_ELEMENTS,
    6706             :  * in which case this returns NULL. This allows writing code that does not
    6707             :  * know the number of entries in advance.
    6708             :  */
    6709             : const char *
    6710           0 : pgstat_slru_name(int slru_idx)
    6711             : {
    6712           0 :     if (slru_idx < 0 || slru_idx >= SLRU_NUM_ELEMENTS)
    6713           0 :         return NULL;
    6714             : 
    6715           0 :     return slru_names[slru_idx];
    6716             : }
    6717             : 
    6718             : /*
    6719             :  * slru_entry
    6720             :  *
    6721             :  * Returns pointer to entry with counters for given SLRU (based on the name
    6722             :  * stored in SlruCtl as lwlock tranche name).
    6723             :  */
    6724             : static inline PgStat_MsgSLRU *
    6725     1520890 : slru_entry(int slru_idx)
    6726             : {
    6727             :     /*
    6728             :      * The postmaster should never register any SLRU statistics counts; if it
    6729             :      * did, the counts would be duplicated into child processes via fork().
    6730             :      */
    6731             :     Assert(IsUnderPostmaster || !IsPostmasterEnvironment);
    6732             : 
    6733             :     Assert((slru_idx >= 0) && (slru_idx < SLRU_NUM_ELEMENTS));
    6734             : 
    6735     1520890 :     return &SLRUStats[slru_idx];
    6736             : }
    6737             : 
    6738             : /*
    6739             :  * SLRU statistics count accumulation functions --- called from slru.c
    6740             :  */
    6741             : 
    6742             : void
    6743        3630 : pgstat_count_slru_page_zeroed(int slru_idx)
    6744             : {
    6745        3630 :     slru_entry(slru_idx)->m_blocks_zeroed += 1;
    6746        3630 : }
    6747             : 
    6748             : void
    6749     1484602 : pgstat_count_slru_page_hit(int slru_idx)
    6750             : {
    6751     1484602 :     slru_entry(slru_idx)->m_blocks_hit += 1;
    6752     1484602 : }
    6753             : 
    6754             : void
    6755          52 : pgstat_count_slru_page_exists(int slru_idx)
    6756             : {
    6757          52 :     slru_entry(slru_idx)->m_blocks_exists += 1;
    6758          52 : }
    6759             : 
    6760             : void
    6761        2040 : pgstat_count_slru_page_read(int slru_idx)
    6762             : {
    6763        2040 :     slru_entry(slru_idx)->m_blocks_read += 1;
    6764        2040 : }
    6765             : 
    6766             : void
    6767        5986 : pgstat_count_slru_page_written(int slru_idx)
    6768             : {
    6769        5986 :     slru_entry(slru_idx)->m_blocks_written += 1;
    6770        5986 : }
    6771             : 
    6772             : void
    6773       21520 : pgstat_count_slru_flush(int slru_idx)
    6774             : {
    6775       21520 :     slru_entry(slru_idx)->m_flush += 1;
    6776       21520 : }
    6777             : 
    6778             : void
    6779        3060 : pgstat_count_slru_truncate(int slru_idx)
    6780             : {
    6781        3060 :     slru_entry(slru_idx)->m_truncate += 1;
    6782        3060 : }

Generated by: LCOV version 1.13