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

Generated by: LCOV version 1.13