Header And Logo

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

pgstat.c

Go to the documentation of this file.
00001 /* ----------
00002  * pgstat.c
00003  *
00004  *  All the statistics collector stuff hacked up in one big, ugly file.
00005  *
00006  *  TODO:   - Separate collector, postmaster and backend stuff
00007  *            into different files.
00008  *
00009  *          - Add some automatic call for pgstat vacuuming.
00010  *
00011  *          - Add a pgstat config column to pg_database, so this
00012  *            entire thing can be enabled/disabled on a per db basis.
00013  *
00014  *  Copyright (c) 2001-2013, PostgreSQL Global Development Group
00015  *
00016  *  src/backend/postmaster/pgstat.c
00017  * ----------
00018  */
00019 #include "postgres.h"
00020 
00021 #include <unistd.h>
00022 #include <fcntl.h>
00023 #include <sys/param.h>
00024 #include <sys/time.h>
00025 #include <sys/socket.h>
00026 #include <netdb.h>
00027 #include <netinet/in.h>
00028 #include <arpa/inet.h>
00029 #include <signal.h>
00030 #include <time.h>
00031 
00032 #include "pgstat.h"
00033 
00034 #include "access/heapam.h"
00035 #include "access/htup_details.h"
00036 #include "access/transam.h"
00037 #include "access/twophase_rmgr.h"
00038 #include "access/xact.h"
00039 #include "catalog/pg_database.h"
00040 #include "catalog/pg_proc.h"
00041 #include "lib/ilist.h"
00042 #include "libpq/ip.h"
00043 #include "libpq/libpq.h"
00044 #include "libpq/pqsignal.h"
00045 #include "mb/pg_wchar.h"
00046 #include "miscadmin.h"
00047 #include "pg_trace.h"
00048 #include "postmaster/autovacuum.h"
00049 #include "postmaster/fork_process.h"
00050 #include "postmaster/postmaster.h"
00051 #include "storage/backendid.h"
00052 #include "storage/fd.h"
00053 #include "storage/ipc.h"
00054 #include "storage/latch.h"
00055 #include "storage/pg_shmem.h"
00056 #include "storage/procsignal.h"
00057 #include "utils/ascii.h"
00058 #include "utils/guc.h"
00059 #include "utils/memutils.h"
00060 #include "utils/ps_status.h"
00061 #include "utils/rel.h"
00062 #include "utils/timestamp.h"
00063 #include "utils/tqual.h"
00064 
00065 
00066 /* ----------
00067  * Paths for the statistics files (relative to installation's $PGDATA).
00068  * ----------
00069  */
00070 #define PGSTAT_STAT_PERMANENT_DIRECTORY     "pg_stat"
00071 #define PGSTAT_STAT_PERMANENT_FILENAME      "pg_stat/global.stat"
00072 #define PGSTAT_STAT_PERMANENT_TMPFILE       "pg_stat/global.tmp"
00073 
00074 /* ----------
00075  * Timer definitions.
00076  * ----------
00077  */
00078 #define PGSTAT_STAT_INTERVAL    500     /* Minimum time between stats file
00079                                          * updates; in milliseconds. */
00080 
00081 #define PGSTAT_RETRY_DELAY      10      /* How long to wait between checks for
00082                                          * a new file; in milliseconds. */
00083 
00084 #define PGSTAT_MAX_WAIT_TIME    10000   /* Maximum time to wait for a stats
00085                                          * file update; in milliseconds. */
00086 
00087 #define PGSTAT_INQ_INTERVAL     640     /* How often to ping the collector for
00088                                          * a new file; in milliseconds. */
00089 
00090 #define PGSTAT_RESTART_INTERVAL 60      /* How often to attempt to restart a
00091                                          * failed statistics collector; in
00092                                          * seconds. */
00093 
00094 #define PGSTAT_POLL_LOOP_COUNT  (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
00095 #define PGSTAT_INQ_LOOP_COUNT   (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
00096 
00097 
00098 /* ----------
00099  * The initial size hints for the hash tables used in the collector.
00100  * ----------
00101  */
00102 #define PGSTAT_DB_HASH_SIZE     16
00103 #define PGSTAT_TAB_HASH_SIZE    512
00104 #define PGSTAT_FUNCTION_HASH_SIZE   512
00105 
00106 
00107 /* ----------
00108  * GUC parameters
00109  * ----------
00110  */
00111 bool        pgstat_track_activities = false;
00112 bool        pgstat_track_counts = false;
00113 int         pgstat_track_functions = TRACK_FUNC_OFF;
00114 int         pgstat_track_activity_query_size = 1024;
00115 
00116 /* ----------
00117  * Built from GUC parameter
00118  * ----------
00119  */
00120 char       *pgstat_stat_directory = NULL;
00121 char       *pgstat_stat_filename = NULL;
00122 char       *pgstat_stat_tmpname = NULL;
00123 
00124 /*
00125  * BgWriter global statistics counters (unused in other processes).
00126  * Stored directly in a stats message structure so it can be sent
00127  * without needing to copy things around.  We assume this inits to zeroes.
00128  */
00129 PgStat_MsgBgWriter BgWriterStats;
00130 
00131 /* ----------
00132  * Local data
00133  * ----------
00134  */
00135 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
00136 
00137 static Latch pgStatLatch;
00138 
00139 static struct sockaddr_storage pgStatAddr;
00140 
00141 static time_t last_pgstat_start_time;
00142 
00143 static bool pgStatRunningInCollector = false;
00144 
00145 /*
00146  * Structures in which backends store per-table info that's waiting to be
00147  * sent to the collector.
00148  *
00149  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
00150  * for the life of the backend.  Also, we zero out the t_id fields of the
00151  * contained PgStat_TableStatus structs whenever they are not actively in use.
00152  * This allows relcache pgstat_info pointers to be treated as long-lived data,
00153  * avoiding repeated searches in pgstat_initstats() when a relation is
00154  * repeatedly opened during a transaction.
00155  */
00156 #define TABSTAT_QUANTUM     100 /* we alloc this many at a time */
00157 
00158 typedef struct TabStatusArray
00159 {
00160     struct TabStatusArray *tsa_next;    /* link to next array, if any */
00161     int         tsa_used;       /* # entries currently used */
00162     PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];    /* per-table data */
00163 } TabStatusArray;
00164 
00165 static TabStatusArray *pgStatTabList = NULL;
00166 
00167 /*
00168  * Backends store per-function info that's waiting to be sent to the collector
00169  * in this hash table (indexed by function OID).
00170  */
00171 static HTAB *pgStatFunctions = NULL;
00172 
00173 /*
00174  * Indicates if backend has some function stats that it hasn't yet
00175  * sent to the collector.
00176  */
00177 static bool have_function_stats = false;
00178 
00179 /*
00180  * Tuple insertion/deletion counts for an open transaction can't be propagated
00181  * into PgStat_TableStatus counters until we know if it is going to commit
00182  * or abort.  Hence, we keep these counts in per-subxact structs that live
00183  * in TopTransactionContext.  This data structure is designed on the assumption
00184  * that subxacts won't usually modify very many tables.
00185  */
00186 typedef struct PgStat_SubXactStatus
00187 {
00188     int         nest_level;     /* subtransaction nest level */
00189     struct PgStat_SubXactStatus *prev;  /* higher-level subxact if any */
00190     PgStat_TableXactStatus *first;      /* head of list for this subxact */
00191 } PgStat_SubXactStatus;
00192 
00193 static PgStat_SubXactStatus *pgStatXactStack = NULL;
00194 
00195 static int  pgStatXactCommit = 0;
00196 static int  pgStatXactRollback = 0;
00197 PgStat_Counter pgStatBlockReadTime = 0;
00198 PgStat_Counter pgStatBlockWriteTime = 0;
00199 
00200 /* Record that's written to 2PC state file when pgstat state is persisted */
00201 typedef struct TwoPhasePgStatRecord
00202 {
00203     PgStat_Counter tuples_inserted;     /* tuples inserted in xact */
00204     PgStat_Counter tuples_updated;      /* tuples updated in xact */
00205     PgStat_Counter tuples_deleted;      /* tuples deleted in xact */
00206     Oid         t_id;           /* table's OID */
00207     bool        t_shared;       /* is it a shared catalog? */
00208 } TwoPhasePgStatRecord;
00209 
00210 /*
00211  * Info about current "snapshot" of stats file
00212  */
00213 static MemoryContext pgStatLocalContext = NULL;
00214 static HTAB *pgStatDBHash = NULL;
00215 static PgBackendStatus *localBackendStatusTable = NULL;
00216 static int  localNumBackends = 0;
00217 
00218 /*
00219  * Cluster wide statistics, kept in the stats collector.
00220  * Contains statistics that are not collected per database
00221  * or per table.
00222  */
00223 static PgStat_GlobalStats globalStats;
00224 
00225 /* Write request info for each database */
00226 typedef struct DBWriteRequest
00227 {
00228     Oid         databaseid;     /* OID of the database to write */
00229     TimestampTz request_time;   /* timestamp of the last write request */
00230     slist_node  next;
00231 } DBWriteRequest;
00232 
00233 /* Latest statistics request times from backends */
00234 static slist_head last_statrequests = SLIST_STATIC_INIT(last_statrequests);
00235 
00236 static volatile bool need_exit = false;
00237 static volatile bool got_SIGHUP = false;
00238 
00239 /*
00240  * Total time charged to functions so far in the current backend.
00241  * We use this to help separate "self" and "other" time charges.
00242  * (We assume this initializes to zero.)
00243  */
00244 static instr_time total_func_time;
00245 
00246 
00247 /* ----------
00248  * Local function forward declarations
00249  * ----------
00250  */
00251 #ifdef EXEC_BACKEND
00252 static pid_t pgstat_forkexec(void);
00253 #endif
00254 
00255 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) __attribute__((noreturn));
00256 static void pgstat_exit(SIGNAL_ARGS);
00257 static void pgstat_beshutdown_hook(int code, Datum arg);
00258 static void pgstat_sighup_handler(SIGNAL_ARGS);
00259 
00260 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
00261 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
00262                      Oid tableoid, bool create);
00263 static void pgstat_write_statsfiles(bool permanent, bool allDbs);
00264 static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
00265 static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
00266 static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
00267 static void backend_read_statsfile(void);
00268 static void pgstat_read_current_status(void);
00269 
00270 static bool pgstat_write_statsfile_needed(void);
00271 static bool pgstat_db_requested(Oid databaseid);
00272 
00273 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
00274 static void pgstat_send_funcstats(void);
00275 static HTAB *pgstat_collect_oids(Oid catalogid);
00276 
00277 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
00278 
00279 static void pgstat_setup_memcxt(void);
00280 
00281 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
00282 static void pgstat_send(void *msg, int len);
00283 
00284 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
00285 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
00286 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
00287 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
00288 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
00289 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
00290 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
00291 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
00292 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
00293 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
00294 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
00295 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
00296 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
00297 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
00298 static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
00299 static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
00300 
00301 /* ------------------------------------------------------------
00302  * Public functions called from postmaster follow
00303  * ------------------------------------------------------------
00304  */
00305 
00306 /* ----------
00307  * pgstat_init() -
00308  *
00309  *  Called from postmaster at startup. Create the resources required
00310  *  by the statistics collector process.  If unable to do so, do not
00311  *  fail --- better to let the postmaster start with stats collection
00312  *  disabled.
00313  * ----------
00314  */
00315 void
00316 pgstat_init(void)
00317 {
00318     ACCEPT_TYPE_ARG3 alen;
00319     struct addrinfo *addrs = NULL,
00320                *addr,
00321                 hints;
00322     int         ret;
00323     fd_set      rset;
00324     struct timeval tv;
00325     char        test_byte;
00326     int         sel_res;
00327     int         tries = 0;
00328 
00329 #define TESTBYTEVAL ((char) 199)
00330 
00331     /*
00332      * Create the UDP socket for sending and receiving statistic messages
00333      */
00334     hints.ai_flags = AI_PASSIVE;
00335     hints.ai_family = PF_UNSPEC;
00336     hints.ai_socktype = SOCK_DGRAM;
00337     hints.ai_protocol = 0;
00338     hints.ai_addrlen = 0;
00339     hints.ai_addr = NULL;
00340     hints.ai_canonname = NULL;
00341     hints.ai_next = NULL;
00342     ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
00343     if (ret || !addrs)
00344     {
00345         ereport(LOG,
00346                 (errmsg("could not resolve \"localhost\": %s",
00347                         gai_strerror(ret))));
00348         goto startup_failed;
00349     }
00350 
00351     /*
00352      * On some platforms, pg_getaddrinfo_all() may return multiple addresses
00353      * only one of which will actually work (eg, both IPv6 and IPv4 addresses
00354      * when kernel will reject IPv6).  Worse, the failure may occur at the
00355      * bind() or perhaps even connect() stage.  So we must loop through the
00356      * results till we find a working combination. We will generate LOG
00357      * messages, but no error, for bogus combinations.
00358      */
00359     for (addr = addrs; addr; addr = addr->ai_next)
00360     {
00361 #ifdef HAVE_UNIX_SOCKETS
00362         /* Ignore AF_UNIX sockets, if any are returned. */
00363         if (addr->ai_family == AF_UNIX)
00364             continue;
00365 #endif
00366 
00367         if (++tries > 1)
00368             ereport(LOG,
00369             (errmsg("trying another address for the statistics collector")));
00370 
00371         /*
00372          * Create the socket.
00373          */
00374         if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
00375         {
00376             ereport(LOG,
00377                     (errcode_for_socket_access(),
00378             errmsg("could not create socket for statistics collector: %m")));
00379             continue;
00380         }
00381 
00382         /*
00383          * Bind it to a kernel assigned port on localhost and get the assigned
00384          * port via getsockname().
00385          */
00386         if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
00387         {
00388             ereport(LOG,
00389                     (errcode_for_socket_access(),
00390               errmsg("could not bind socket for statistics collector: %m")));
00391             closesocket(pgStatSock);
00392             pgStatSock = PGINVALID_SOCKET;
00393             continue;
00394         }
00395 
00396         alen = sizeof(pgStatAddr);
00397         if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
00398         {
00399             ereport(LOG,
00400                     (errcode_for_socket_access(),
00401                      errmsg("could not get address of socket for statistics collector: %m")));
00402             closesocket(pgStatSock);
00403             pgStatSock = PGINVALID_SOCKET;
00404             continue;
00405         }
00406 
00407         /*
00408          * Connect the socket to its own address.  This saves a few cycles by
00409          * not having to respecify the target address on every send. This also
00410          * provides a kernel-level check that only packets from this same
00411          * address will be received.
00412          */
00413         if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
00414         {
00415             ereport(LOG,
00416                     (errcode_for_socket_access(),
00417             errmsg("could not connect socket for statistics collector: %m")));
00418             closesocket(pgStatSock);
00419             pgStatSock = PGINVALID_SOCKET;
00420             continue;
00421         }
00422 
00423         /*
00424          * Try to send and receive a one-byte test message on the socket. This
00425          * is to catch situations where the socket can be created but will not
00426          * actually pass data (for instance, because kernel packet filtering
00427          * rules prevent it).
00428          */
00429         test_byte = TESTBYTEVAL;
00430 
00431 retry1:
00432         if (send(pgStatSock, &test_byte, 1, 0) != 1)
00433         {
00434             if (errno == EINTR)
00435                 goto retry1;    /* if interrupted, just retry */
00436             ereport(LOG,
00437                     (errcode_for_socket_access(),
00438                      errmsg("could not send test message on socket for statistics collector: %m")));
00439             closesocket(pgStatSock);
00440             pgStatSock = PGINVALID_SOCKET;
00441             continue;
00442         }
00443 
00444         /*
00445          * There could possibly be a little delay before the message can be
00446          * received.  We arbitrarily allow up to half a second before deciding
00447          * it's broken.
00448          */
00449         for (;;)                /* need a loop to handle EINTR */
00450         {
00451             FD_ZERO(&rset);
00452             FD_SET(pgStatSock, &rset);
00453 
00454             tv.tv_sec = 0;
00455             tv.tv_usec = 500000;
00456             sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
00457             if (sel_res >= 0 || errno != EINTR)
00458                 break;
00459         }
00460         if (sel_res < 0)
00461         {
00462             ereport(LOG,
00463                     (errcode_for_socket_access(),
00464                      errmsg("select() failed in statistics collector: %m")));
00465             closesocket(pgStatSock);
00466             pgStatSock = PGINVALID_SOCKET;
00467             continue;
00468         }
00469         if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
00470         {
00471             /*
00472              * This is the case we actually think is likely, so take pains to
00473              * give a specific message for it.
00474              *
00475              * errno will not be set meaningfully here, so don't use it.
00476              */
00477             ereport(LOG,
00478                     (errcode(ERRCODE_CONNECTION_FAILURE),
00479                      errmsg("test message did not get through on socket for statistics collector")));
00480             closesocket(pgStatSock);
00481             pgStatSock = PGINVALID_SOCKET;
00482             continue;
00483         }
00484 
00485         test_byte++;            /* just make sure variable is changed */
00486 
00487 retry2:
00488         if (recv(pgStatSock, &test_byte, 1, 0) != 1)
00489         {
00490             if (errno == EINTR)
00491                 goto retry2;    /* if interrupted, just retry */
00492             ereport(LOG,
00493                     (errcode_for_socket_access(),
00494                      errmsg("could not receive test message on socket for statistics collector: %m")));
00495             closesocket(pgStatSock);
00496             pgStatSock = PGINVALID_SOCKET;
00497             continue;
00498         }
00499 
00500         if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
00501         {
00502             ereport(LOG,
00503                     (errcode(ERRCODE_INTERNAL_ERROR),
00504                      errmsg("incorrect test message transmission on socket for statistics collector")));
00505             closesocket(pgStatSock);
00506             pgStatSock = PGINVALID_SOCKET;
00507             continue;
00508         }
00509 
00510         /* If we get here, we have a working socket */
00511         break;
00512     }
00513 
00514     /* Did we find a working address? */
00515     if (!addr || pgStatSock == PGINVALID_SOCKET)
00516         goto startup_failed;
00517 
00518     /*
00519      * Set the socket to non-blocking IO.  This ensures that if the collector
00520      * falls behind, statistics messages will be discarded; backends won't
00521      * block waiting to send messages to the collector.
00522      */
00523     if (!pg_set_noblock(pgStatSock))
00524     {
00525         ereport(LOG,
00526                 (errcode_for_socket_access(),
00527                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
00528         goto startup_failed;
00529     }
00530 
00531     pg_freeaddrinfo_all(hints.ai_family, addrs);
00532 
00533     return;
00534 
00535 startup_failed:
00536     ereport(LOG,
00537       (errmsg("disabling statistics collector for lack of working socket")));
00538 
00539     if (addrs)
00540         pg_freeaddrinfo_all(hints.ai_family, addrs);
00541 
00542     if (pgStatSock != PGINVALID_SOCKET)
00543         closesocket(pgStatSock);
00544     pgStatSock = PGINVALID_SOCKET;
00545 
00546     /*
00547      * Adjust GUC variables to suppress useless activity, and for debugging
00548      * purposes (seeing track_counts off is a clue that we failed here). We
00549      * use PGC_S_OVERRIDE because there is no point in trying to turn it back
00550      * on from postgresql.conf without a restart.
00551      */
00552     SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
00553 }
00554 
00555 /*
00556  * subroutine for pgstat_reset_all
00557  */
00558 static void
00559 pgstat_reset_remove_files(const char *directory)
00560 {
00561     DIR        *dir;
00562     struct dirent *entry;
00563     char        fname[MAXPGPATH];
00564 
00565     dir = AllocateDir(pgstat_stat_directory);
00566     while ((entry = ReadDir(dir, pgstat_stat_directory)) != NULL)
00567     {
00568         if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
00569             continue;
00570 
00571         /* XXX should we try to ignore files other than the ones we write? */
00572 
00573         snprintf(fname, MAXPGPATH, "%s/%s", pgstat_stat_directory,
00574                  entry->d_name);
00575         unlink(fname);
00576     }
00577     FreeDir(dir);
00578 }
00579 
00580 /*
00581  * pgstat_reset_all() -
00582  *
00583  * Remove the stats files.  This is currently used only if WAL
00584  * recovery is needed after a crash.
00585  */
00586 void
00587 pgstat_reset_all(void)
00588 {
00589     pgstat_reset_remove_files(pgstat_stat_directory);
00590     pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
00591 }
00592 
00593 #ifdef EXEC_BACKEND
00594 
00595 /*
00596  * pgstat_forkexec() -
00597  *
00598  * Format up the arglist for, then fork and exec, statistics collector process
00599  */
00600 static pid_t
00601 pgstat_forkexec(void)
00602 {
00603     char       *av[10];
00604     int         ac = 0;
00605 
00606     av[ac++] = "postgres";
00607     av[ac++] = "--forkcol";
00608     av[ac++] = NULL;            /* filled in by postmaster_forkexec */
00609 
00610     av[ac] = NULL;
00611     Assert(ac < lengthof(av));
00612 
00613     return postmaster_forkexec(ac, av);
00614 }
00615 #endif   /* EXEC_BACKEND */
00616 
00617 
00618 /*
00619  * pgstat_start() -
00620  *
00621  *  Called from postmaster at startup or after an existing collector
00622  *  died.  Attempt to fire up a fresh statistics collector.
00623  *
00624  *  Returns PID of child process, or 0 if fail.
00625  *
00626  *  Note: if fail, we will be called again from the postmaster main loop.
00627  */
00628 int
00629 pgstat_start(void)
00630 {
00631     time_t      curtime;
00632     pid_t       pgStatPid;
00633 
00634     /*
00635      * Check that the socket is there, else pgstat_init failed and we can do
00636      * nothing useful.
00637      */
00638     if (pgStatSock == PGINVALID_SOCKET)
00639         return 0;
00640 
00641     /*
00642      * Do nothing if too soon since last collector start.  This is a safety
00643      * valve to protect against continuous respawn attempts if the collector
00644      * is dying immediately at launch.  Note that since we will be re-called
00645      * from the postmaster main loop, we will get another chance later.
00646      */
00647     curtime = time(NULL);
00648     if ((unsigned int) (curtime - last_pgstat_start_time) <
00649         (unsigned int) PGSTAT_RESTART_INTERVAL)
00650         return 0;
00651     last_pgstat_start_time = curtime;
00652 
00653     /*
00654      * Okay, fork off the collector.
00655      */
00656 #ifdef EXEC_BACKEND
00657     switch ((pgStatPid = pgstat_forkexec()))
00658 #else
00659     switch ((pgStatPid = fork_process()))
00660 #endif
00661     {
00662         case -1:
00663             ereport(LOG,
00664                     (errmsg("could not fork statistics collector: %m")));
00665             return 0;
00666 
00667 #ifndef EXEC_BACKEND
00668         case 0:
00669             /* in postmaster child ... */
00670             /* Close the postmaster's sockets */
00671             ClosePostmasterPorts(false);
00672 
00673             /* Lose the postmaster's on-exit routines */
00674             on_exit_reset();
00675 
00676             /* Drop our connection to postmaster's shared memory, as well */
00677             PGSharedMemoryDetach();
00678 
00679             PgstatCollectorMain(0, NULL);
00680             break;
00681 #endif
00682 
00683         default:
00684             return (int) pgStatPid;
00685     }
00686 
00687     /* shouldn't get here */
00688     return 0;
00689 }
00690 
00691 void
00692 allow_immediate_pgstat_restart(void)
00693 {
00694     last_pgstat_start_time = 0;
00695 }
00696 
00697 /* ------------------------------------------------------------
00698  * Public functions used by backends follow
00699  *------------------------------------------------------------
00700  */
00701 
00702 
00703 /* ----------
00704  * pgstat_report_stat() -
00705  *
00706  *  Called from tcop/postgres.c to send the so far collected per-table
00707  *  and function usage statistics to the collector.  Note that this is
00708  *  called only when not within a transaction, so it is fair to use
00709  *  transaction stop time as an approximation of current time.
00710  * ----------
00711  */
00712 void
00713 pgstat_report_stat(bool force)
00714 {
00715     /* we assume this inits to all zeroes: */
00716     static const PgStat_TableCounts all_zeroes;
00717     static TimestampTz last_report = 0;
00718 
00719     TimestampTz now;
00720     PgStat_MsgTabstat regular_msg;
00721     PgStat_MsgTabstat shared_msg;
00722     TabStatusArray *tsa;
00723     int         i;
00724 
00725     /* Don't expend a clock check if nothing to do */
00726     if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
00727         !have_function_stats && !force)
00728         return;
00729 
00730     /*
00731      * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
00732      * msec since we last sent one, or the caller wants to force stats out.
00733      */
00734     now = GetCurrentTransactionStopTimestamp();
00735     if (!force &&
00736         !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
00737         return;
00738     last_report = now;
00739 
00740     /*
00741      * Scan through the TabStatusArray struct(s) to find tables that actually
00742      * have counts, and build messages to send.  We have to separate shared
00743      * relations from regular ones because the databaseid field in the message
00744      * header has to depend on that.
00745      */
00746     regular_msg.m_databaseid = MyDatabaseId;
00747     shared_msg.m_databaseid = InvalidOid;
00748     regular_msg.m_nentries = 0;
00749     shared_msg.m_nentries = 0;
00750 
00751     for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
00752     {
00753         for (i = 0; i < tsa->tsa_used; i++)
00754         {
00755             PgStat_TableStatus *entry = &tsa->tsa_entries[i];
00756             PgStat_MsgTabstat *this_msg;
00757             PgStat_TableEntry *this_ent;
00758 
00759             /* Shouldn't have any pending transaction-dependent counts */
00760             Assert(entry->trans == NULL);
00761 
00762             /*
00763              * Ignore entries that didn't accumulate any actual counts, such
00764              * as indexes that were opened by the planner but not used.
00765              */
00766             if (memcmp(&entry->t_counts, &all_zeroes,
00767                        sizeof(PgStat_TableCounts)) == 0)
00768                 continue;
00769 
00770             /*
00771              * OK, insert data into the appropriate message, and send if full.
00772              */
00773             this_msg = entry->t_shared ? &shared_msg : &regular_msg;
00774             this_ent = &this_msg->m_entry[this_msg->m_nentries];
00775             this_ent->t_id = entry->t_id;
00776             memcpy(&this_ent->t_counts, &entry->t_counts,
00777                    sizeof(PgStat_TableCounts));
00778             if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
00779             {
00780                 pgstat_send_tabstat(this_msg);
00781                 this_msg->m_nentries = 0;
00782             }
00783         }
00784         /* zero out TableStatus structs after use */
00785         MemSet(tsa->tsa_entries, 0,
00786                tsa->tsa_used * sizeof(PgStat_TableStatus));
00787         tsa->tsa_used = 0;
00788     }
00789 
00790     /*
00791      * Send partial messages.  If force is true, make sure that any pending
00792      * xact commit/abort gets counted, even if no table stats to send.
00793      */
00794     if (regular_msg.m_nentries > 0 ||
00795         (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
00796         pgstat_send_tabstat(&regular_msg);
00797     if (shared_msg.m_nentries > 0)
00798         pgstat_send_tabstat(&shared_msg);
00799 
00800     /* Now, send function statistics */
00801     pgstat_send_funcstats();
00802 }
00803 
00804 /*
00805  * Subroutine for pgstat_report_stat: finish and send a tabstat message
00806  */
00807 static void
00808 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
00809 {
00810     int         n;
00811     int         len;
00812 
00813     /* It's unlikely we'd get here with no socket, but maybe not impossible */
00814     if (pgStatSock == PGINVALID_SOCKET)
00815         return;
00816 
00817     /*
00818      * Report and reset accumulated xact commit/rollback and I/O timings
00819      * whenever we send a normal tabstat message
00820      */
00821     if (OidIsValid(tsmsg->m_databaseid))
00822     {
00823         tsmsg->m_xact_commit = pgStatXactCommit;
00824         tsmsg->m_xact_rollback = pgStatXactRollback;
00825         tsmsg->m_block_read_time = pgStatBlockReadTime;
00826         tsmsg->m_block_write_time = pgStatBlockWriteTime;
00827         pgStatXactCommit = 0;
00828         pgStatXactRollback = 0;
00829         pgStatBlockReadTime = 0;
00830         pgStatBlockWriteTime = 0;
00831     }
00832     else
00833     {
00834         tsmsg->m_xact_commit = 0;
00835         tsmsg->m_xact_rollback = 0;
00836         tsmsg->m_block_read_time = 0;
00837         tsmsg->m_block_write_time = 0;
00838     }
00839 
00840     n = tsmsg->m_nentries;
00841     len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
00842         n * sizeof(PgStat_TableEntry);
00843 
00844     pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
00845     pgstat_send(tsmsg, len);
00846 }
00847 
00848 /*
00849  * Subroutine for pgstat_report_stat: populate and send a function stat message
00850  */
00851 static void
00852 pgstat_send_funcstats(void)
00853 {
00854     /* we assume this inits to all zeroes: */
00855     static const PgStat_FunctionCounts all_zeroes;
00856 
00857     PgStat_MsgFuncstat msg;
00858     PgStat_BackendFunctionEntry *entry;
00859     HASH_SEQ_STATUS fstat;
00860 
00861     if (pgStatFunctions == NULL)
00862         return;
00863 
00864     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
00865     msg.m_databaseid = MyDatabaseId;
00866     msg.m_nentries = 0;
00867 
00868     hash_seq_init(&fstat, pgStatFunctions);
00869     while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
00870     {
00871         PgStat_FunctionEntry *m_ent;
00872 
00873         /* Skip it if no counts accumulated since last time */
00874         if (memcmp(&entry->f_counts, &all_zeroes,
00875                    sizeof(PgStat_FunctionCounts)) == 0)
00876             continue;
00877 
00878         /* need to convert format of time accumulators */
00879         m_ent = &msg.m_entry[msg.m_nentries];
00880         m_ent->f_id = entry->f_id;
00881         m_ent->f_numcalls = entry->f_counts.f_numcalls;
00882         m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
00883         m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
00884 
00885         if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
00886         {
00887             pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
00888                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
00889             msg.m_nentries = 0;
00890         }
00891 
00892         /* reset the entry's counts */
00893         MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
00894     }
00895 
00896     if (msg.m_nentries > 0)
00897         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
00898                     msg.m_nentries * sizeof(PgStat_FunctionEntry));
00899 
00900     have_function_stats = false;
00901 }
00902 
00903 
00904 /* ----------
00905  * pgstat_vacuum_stat() -
00906  *
00907  *  Will tell the collector about objects he can get rid of.
00908  * ----------
00909  */
00910 void
00911 pgstat_vacuum_stat(void)
00912 {
00913     HTAB       *htab;
00914     PgStat_MsgTabpurge msg;
00915     PgStat_MsgFuncpurge f_msg;
00916     HASH_SEQ_STATUS hstat;
00917     PgStat_StatDBEntry *dbentry;
00918     PgStat_StatTabEntry *tabentry;
00919     PgStat_StatFuncEntry *funcentry;
00920     int         len;
00921 
00922     if (pgStatSock == PGINVALID_SOCKET)
00923         return;
00924 
00925     /*
00926      * If not done for this transaction, read the statistics collector stats
00927      * file into some hash tables.
00928      */
00929     backend_read_statsfile();
00930 
00931     /*
00932      * Read pg_database and make a list of OIDs of all existing databases
00933      */
00934     htab = pgstat_collect_oids(DatabaseRelationId);
00935 
00936     /*
00937      * Search the database hash table for dead databases and tell the
00938      * collector to drop them.
00939      */
00940     hash_seq_init(&hstat, pgStatDBHash);
00941     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
00942     {
00943         Oid         dbid = dbentry->databaseid;
00944 
00945         CHECK_FOR_INTERRUPTS();
00946 
00947         /* the DB entry for shared tables (with InvalidOid) is never dropped */
00948         if (OidIsValid(dbid) &&
00949             hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
00950             pgstat_drop_database(dbid);
00951     }
00952 
00953     /* Clean up */
00954     hash_destroy(htab);
00955 
00956     /*
00957      * Lookup our own database entry; if not found, nothing more to do.
00958      */
00959     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
00960                                                  (void *) &MyDatabaseId,
00961                                                  HASH_FIND, NULL);
00962     if (dbentry == NULL || dbentry->tables == NULL)
00963         return;
00964 
00965     /*
00966      * Similarly to above, make a list of all known relations in this DB.
00967      */
00968     htab = pgstat_collect_oids(RelationRelationId);
00969 
00970     /*
00971      * Initialize our messages table counter to zero
00972      */
00973     msg.m_nentries = 0;
00974 
00975     /*
00976      * Check for all tables listed in stats hashtable if they still exist.
00977      */
00978     hash_seq_init(&hstat, dbentry->tables);
00979     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
00980     {
00981         Oid         tabid = tabentry->tableid;
00982 
00983         CHECK_FOR_INTERRUPTS();
00984 
00985         if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
00986             continue;
00987 
00988         /*
00989          * Not there, so add this table's Oid to the message
00990          */
00991         msg.m_tableid[msg.m_nentries++] = tabid;
00992 
00993         /*
00994          * If the message is full, send it out and reinitialize to empty
00995          */
00996         if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
00997         {
00998             len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
00999                 +msg.m_nentries * sizeof(Oid);
01000 
01001             pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
01002             msg.m_databaseid = MyDatabaseId;
01003             pgstat_send(&msg, len);
01004 
01005             msg.m_nentries = 0;
01006         }
01007     }
01008 
01009     /*
01010      * Send the rest
01011      */
01012     if (msg.m_nentries > 0)
01013     {
01014         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
01015             +msg.m_nentries * sizeof(Oid);
01016 
01017         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
01018         msg.m_databaseid = MyDatabaseId;
01019         pgstat_send(&msg, len);
01020     }
01021 
01022     /* Clean up */
01023     hash_destroy(htab);
01024 
01025     /*
01026      * Now repeat the above steps for functions.  However, we needn't bother
01027      * in the common case where no function stats are being collected.
01028      */
01029     if (dbentry->functions != NULL &&
01030         hash_get_num_entries(dbentry->functions) > 0)
01031     {
01032         htab = pgstat_collect_oids(ProcedureRelationId);
01033 
01034         pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
01035         f_msg.m_databaseid = MyDatabaseId;
01036         f_msg.m_nentries = 0;
01037 
01038         hash_seq_init(&hstat, dbentry->functions);
01039         while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
01040         {
01041             Oid         funcid = funcentry->functionid;
01042 
01043             CHECK_FOR_INTERRUPTS();
01044 
01045             if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
01046                 continue;
01047 
01048             /*
01049              * Not there, so add this function's Oid to the message
01050              */
01051             f_msg.m_functionid[f_msg.m_nentries++] = funcid;
01052 
01053             /*
01054              * If the message is full, send it out and reinitialize to empty
01055              */
01056             if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
01057             {
01058                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
01059                     +f_msg.m_nentries * sizeof(Oid);
01060 
01061                 pgstat_send(&f_msg, len);
01062 
01063                 f_msg.m_nentries = 0;
01064             }
01065         }
01066 
01067         /*
01068          * Send the rest
01069          */
01070         if (f_msg.m_nentries > 0)
01071         {
01072             len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
01073                 +f_msg.m_nentries * sizeof(Oid);
01074 
01075             pgstat_send(&f_msg, len);
01076         }
01077 
01078         hash_destroy(htab);
01079     }
01080 }
01081 
01082 
01083 /* ----------
01084  * pgstat_collect_oids() -
01085  *
01086  *  Collect the OIDs of all objects listed in the specified system catalog
01087  *  into a temporary hash table.  Caller should hash_destroy the result
01088  *  when done with it.  (However, we make the table in CurrentMemoryContext
01089  *  so that it will be freed properly in event of an error.)
01090  * ----------
01091  */
01092 static HTAB *
01093 pgstat_collect_oids(Oid catalogid)
01094 {
01095     HTAB       *htab;
01096     HASHCTL     hash_ctl;
01097     Relation    rel;
01098     HeapScanDesc scan;
01099     HeapTuple   tup;
01100 
01101     memset(&hash_ctl, 0, sizeof(hash_ctl));
01102     hash_ctl.keysize = sizeof(Oid);
01103     hash_ctl.entrysize = sizeof(Oid);
01104     hash_ctl.hash = oid_hash;
01105     hash_ctl.hcxt = CurrentMemoryContext;
01106     htab = hash_create("Temporary table of OIDs",
01107                        PGSTAT_TAB_HASH_SIZE,
01108                        &hash_ctl,
01109                        HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
01110 
01111     rel = heap_open(catalogid, AccessShareLock);
01112     scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
01113     while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
01114     {
01115         Oid         thisoid = HeapTupleGetOid(tup);
01116 
01117         CHECK_FOR_INTERRUPTS();
01118 
01119         (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
01120     }
01121     heap_endscan(scan);
01122     heap_close(rel, AccessShareLock);
01123 
01124     return htab;
01125 }
01126 
01127 
01128 /* ----------
01129  * pgstat_drop_database() -
01130  *
01131  *  Tell the collector that we just dropped a database.
01132  *  (If the message gets lost, we will still clean the dead DB eventually
01133  *  via future invocations of pgstat_vacuum_stat().)
01134  * ----------
01135  */
01136 void
01137 pgstat_drop_database(Oid databaseid)
01138 {
01139     PgStat_MsgDropdb msg;
01140 
01141     if (pgStatSock == PGINVALID_SOCKET)
01142         return;
01143 
01144     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
01145     msg.m_databaseid = databaseid;
01146     pgstat_send(&msg, sizeof(msg));
01147 }
01148 
01149 
01150 /* ----------
01151  * pgstat_drop_relation() -
01152  *
01153  *  Tell the collector that we just dropped a relation.
01154  *  (If the message gets lost, we will still clean the dead entry eventually
01155  *  via future invocations of pgstat_vacuum_stat().)
01156  *
01157  *  Currently not used for lack of any good place to call it; we rely
01158  *  entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
01159  * ----------
01160  */
01161 #ifdef NOT_USED
01162 void
01163 pgstat_drop_relation(Oid relid)
01164 {
01165     PgStat_MsgTabpurge msg;
01166     int         len;
01167 
01168     if (pgStatSock == PGINVALID_SOCKET)
01169         return;
01170 
01171     msg.m_tableid[0] = relid;
01172     msg.m_nentries = 1;
01173 
01174     len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
01175 
01176     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
01177     msg.m_databaseid = MyDatabaseId;
01178     pgstat_send(&msg, len);
01179 }
01180 #endif   /* NOT_USED */
01181 
01182 
01183 /* ----------
01184  * pgstat_reset_counters() -
01185  *
01186  *  Tell the statistics collector to reset counters for our database.
01187  * ----------
01188  */
01189 void
01190 pgstat_reset_counters(void)
01191 {
01192     PgStat_MsgResetcounter msg;
01193 
01194     if (pgStatSock == PGINVALID_SOCKET)
01195         return;
01196 
01197     if (!superuser())
01198         ereport(ERROR,
01199                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
01200                  errmsg("must be superuser to reset statistics counters")));
01201 
01202     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
01203     msg.m_databaseid = MyDatabaseId;
01204     pgstat_send(&msg, sizeof(msg));
01205 }
01206 
01207 /* ----------
01208  * pgstat_reset_shared_counters() -
01209  *
01210  *  Tell the statistics collector to reset cluster-wide shared counters.
01211  * ----------
01212  */
01213 void
01214 pgstat_reset_shared_counters(const char *target)
01215 {
01216     PgStat_MsgResetsharedcounter msg;
01217 
01218     if (pgStatSock == PGINVALID_SOCKET)
01219         return;
01220 
01221     if (!superuser())
01222         ereport(ERROR,
01223                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
01224                  errmsg("must be superuser to reset statistics counters")));
01225 
01226     if (strcmp(target, "bgwriter") == 0)
01227         msg.m_resettarget = RESET_BGWRITER;
01228     else
01229         ereport(ERROR,
01230                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
01231                  errmsg("unrecognized reset target: \"%s\"", target),
01232                  errhint("Target must be \"bgwriter\".")));
01233 
01234     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
01235     pgstat_send(&msg, sizeof(msg));
01236 }
01237 
01238 /* ----------
01239  * pgstat_reset_single_counter() -
01240  *
01241  *  Tell the statistics collector to reset a single counter.
01242  * ----------
01243  */
01244 void
01245 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
01246 {
01247     PgStat_MsgResetsinglecounter msg;
01248 
01249     if (pgStatSock == PGINVALID_SOCKET)
01250         return;
01251 
01252     if (!superuser())
01253         ereport(ERROR,
01254                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
01255                  errmsg("must be superuser to reset statistics counters")));
01256 
01257     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
01258     msg.m_databaseid = MyDatabaseId;
01259     msg.m_resettype = type;
01260     msg.m_objectid = objoid;
01261 
01262     pgstat_send(&msg, sizeof(msg));
01263 }
01264 
01265 /* ----------
01266  * pgstat_report_autovac() -
01267  *
01268  *  Called from autovacuum.c to report startup of an autovacuum process.
01269  *  We are called before InitPostgres is done, so can't rely on MyDatabaseId;
01270  *  the db OID must be passed in, instead.
01271  * ----------
01272  */
01273 void
01274 pgstat_report_autovac(Oid dboid)
01275 {
01276     PgStat_MsgAutovacStart msg;
01277 
01278     if (pgStatSock == PGINVALID_SOCKET)
01279         return;
01280 
01281     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
01282     msg.m_databaseid = dboid;
01283     msg.m_start_time = GetCurrentTimestamp();
01284 
01285     pgstat_send(&msg, sizeof(msg));
01286 }
01287 
01288 
01289 /* ---------
01290  * pgstat_report_vacuum() -
01291  *
01292  *  Tell the collector about the table we just vacuumed.
01293  * ---------
01294  */
01295 void
01296 pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter tuples)
01297 {
01298     PgStat_MsgVacuum msg;
01299 
01300     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01301         return;
01302 
01303     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
01304     msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
01305     msg.m_tableoid = tableoid;
01306     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
01307     msg.m_vacuumtime = GetCurrentTimestamp();
01308     msg.m_tuples = tuples;
01309     pgstat_send(&msg, sizeof(msg));
01310 }
01311 
01312 /* --------
01313  * pgstat_report_analyze() -
01314  *
01315  *  Tell the collector about the table we just analyzed.
01316  * --------
01317  */
01318 void
01319 pgstat_report_analyze(Relation rel,
01320                       PgStat_Counter livetuples, PgStat_Counter deadtuples)
01321 {
01322     PgStat_MsgAnalyze msg;
01323 
01324     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01325         return;
01326 
01327     /*
01328      * Unlike VACUUM, ANALYZE might be running inside a transaction that has
01329      * already inserted and/or deleted rows in the target table. ANALYZE will
01330      * have counted such rows as live or dead respectively. Because we will
01331      * report our counts of such rows at transaction end, we should subtract
01332      * off these counts from what we send to the collector now, else they'll
01333      * be double-counted after commit.  (This approach also ensures that the
01334      * collector ends up with the right numbers if we abort instead of
01335      * committing.)
01336      */
01337     if (rel->pgstat_info != NULL)
01338     {
01339         PgStat_TableXactStatus *trans;
01340 
01341         for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
01342         {
01343             livetuples -= trans->tuples_inserted - trans->tuples_deleted;
01344             deadtuples -= trans->tuples_updated + trans->tuples_deleted;
01345         }
01346         /* count stuff inserted by already-aborted subxacts, too */
01347         deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
01348         /* Since ANALYZE's counts are estimates, we could have underflowed */
01349         livetuples = Max(livetuples, 0);
01350         deadtuples = Max(deadtuples, 0);
01351     }
01352 
01353     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
01354     msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
01355     msg.m_tableoid = RelationGetRelid(rel);
01356     msg.m_autovacuum = IsAutoVacuumWorkerProcess();
01357     msg.m_analyzetime = GetCurrentTimestamp();
01358     msg.m_live_tuples = livetuples;
01359     msg.m_dead_tuples = deadtuples;
01360     pgstat_send(&msg, sizeof(msg));
01361 }
01362 
01363 /* --------
01364  * pgstat_report_recovery_conflict() -
01365  *
01366  *  Tell the collector about a Hot Standby recovery conflict.
01367  * --------
01368  */
01369 void
01370 pgstat_report_recovery_conflict(int reason)
01371 {
01372     PgStat_MsgRecoveryConflict msg;
01373 
01374     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01375         return;
01376 
01377     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
01378     msg.m_databaseid = MyDatabaseId;
01379     msg.m_reason = reason;
01380     pgstat_send(&msg, sizeof(msg));
01381 }
01382 
01383 /* --------
01384  * pgstat_report_deadlock() -
01385  *
01386  *  Tell the collector about a deadlock detected.
01387  * --------
01388  */
01389 void
01390 pgstat_report_deadlock(void)
01391 {
01392     PgStat_MsgDeadlock msg;
01393 
01394     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01395         return;
01396 
01397     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
01398     msg.m_databaseid = MyDatabaseId;
01399     pgstat_send(&msg, sizeof(msg));
01400 }
01401 
01402 /* --------
01403  * pgstat_report_tempfile() -
01404  *
01405  *  Tell the collector about a temporary file.
01406  * --------
01407  */
01408 void
01409 pgstat_report_tempfile(size_t filesize)
01410 {
01411     PgStat_MsgTempFile msg;
01412 
01413     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01414         return;
01415 
01416     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
01417     msg.m_databaseid = MyDatabaseId;
01418     msg.m_filesize = filesize;
01419     pgstat_send(&msg, sizeof(msg));
01420 }
01421 
01422 
01423 /* ----------
01424  * pgstat_ping() -
01425  *
01426  *  Send some junk data to the collector to increase traffic.
01427  * ----------
01428  */
01429 void
01430 pgstat_ping(void)
01431 {
01432     PgStat_MsgDummy msg;
01433 
01434     if (pgStatSock == PGINVALID_SOCKET)
01435         return;
01436 
01437     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
01438     pgstat_send(&msg, sizeof(msg));
01439 }
01440 
01441 /* ----------
01442  * pgstat_send_inquiry() -
01443  *
01444  *  Notify collector that we need fresh data.
01445  * ----------
01446  */
01447 static void
01448 pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
01449 {
01450     PgStat_MsgInquiry msg;
01451 
01452     pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
01453     msg.clock_time = clock_time;
01454     msg.cutoff_time = cutoff_time;
01455     msg.databaseid = databaseid;
01456     pgstat_send(&msg, sizeof(msg));
01457 }
01458 
01459 
01460 /*
01461  * Initialize function call usage data.
01462  * Called by the executor before invoking a function.
01463  */
01464 void
01465 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
01466                            PgStat_FunctionCallUsage *fcu)
01467 {
01468     PgStat_BackendFunctionEntry *htabent;
01469     bool        found;
01470 
01471     if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
01472     {
01473         /* stats not wanted */
01474         fcu->fs = NULL;
01475         return;
01476     }
01477 
01478     if (!pgStatFunctions)
01479     {
01480         /* First time through - initialize function stat table */
01481         HASHCTL     hash_ctl;
01482 
01483         memset(&hash_ctl, 0, sizeof(hash_ctl));
01484         hash_ctl.keysize = sizeof(Oid);
01485         hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
01486         hash_ctl.hash = oid_hash;
01487         pgStatFunctions = hash_create("Function stat entries",
01488                                       PGSTAT_FUNCTION_HASH_SIZE,
01489                                       &hash_ctl,
01490                                       HASH_ELEM | HASH_FUNCTION);
01491     }
01492 
01493     /* Get the stats entry for this function, create if necessary */
01494     htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
01495                           HASH_ENTER, &found);
01496     if (!found)
01497         MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
01498 
01499     fcu->fs = &htabent->f_counts;
01500 
01501     /* save stats for this function, later used to compensate for recursion */
01502     fcu->save_f_total_time = htabent->f_counts.f_total_time;
01503 
01504     /* save current backend-wide total time */
01505     fcu->save_total = total_func_time;
01506 
01507     /* get clock time as of function start */
01508     INSTR_TIME_SET_CURRENT(fcu->f_start);
01509 }
01510 
01511 /*
01512  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
01513  *      for specified function
01514  *
01515  * If no entry, return NULL, don't create a new one
01516  */
01517 PgStat_BackendFunctionEntry *
01518 find_funcstat_entry(Oid func_id)
01519 {
01520     if (pgStatFunctions == NULL)
01521         return NULL;
01522 
01523     return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
01524                                                        (void *) &func_id,
01525                                                        HASH_FIND, NULL);
01526 }
01527 
01528 /*
01529  * Calculate function call usage and update stat counters.
01530  * Called by the executor after invoking a function.
01531  *
01532  * In the case of a set-returning function that runs in value-per-call mode,
01533  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
01534  * calls for what the user considers a single call of the function.  The
01535  * finalize flag should be TRUE on the last call.
01536  */
01537 void
01538 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
01539 {
01540     PgStat_FunctionCounts *fs = fcu->fs;
01541     instr_time  f_total;
01542     instr_time  f_others;
01543     instr_time  f_self;
01544 
01545     /* stats not wanted? */
01546     if (fs == NULL)
01547         return;
01548 
01549     /* total elapsed time in this function call */
01550     INSTR_TIME_SET_CURRENT(f_total);
01551     INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
01552 
01553     /* self usage: elapsed minus anything already charged to other calls */
01554     f_others = total_func_time;
01555     INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
01556     f_self = f_total;
01557     INSTR_TIME_SUBTRACT(f_self, f_others);
01558 
01559     /* update backend-wide total time */
01560     INSTR_TIME_ADD(total_func_time, f_self);
01561 
01562     /*
01563      * Compute the new f_total_time as the total elapsed time added to the
01564      * pre-call value of f_total_time.  This is necessary to avoid
01565      * double-counting any time taken by recursive calls of myself.  (We do
01566      * not need any similar kluge for self time, since that already excludes
01567      * any recursive calls.)
01568      */
01569     INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
01570 
01571     /* update counters in function stats table */
01572     if (finalize)
01573         fs->f_numcalls++;
01574     fs->f_total_time = f_total;
01575     INSTR_TIME_ADD(fs->f_self_time, f_self);
01576 
01577     /* indicate that we have something to send */
01578     have_function_stats = true;
01579 }
01580 
01581 
01582 /* ----------
01583  * pgstat_initstats() -
01584  *
01585  *  Initialize a relcache entry to count access statistics.
01586  *  Called whenever a relation is opened.
01587  *
01588  *  We assume that a relcache entry's pgstat_info field is zeroed by
01589  *  relcache.c when the relcache entry is made; thereafter it is long-lived
01590  *  data.  We can avoid repeated searches of the TabStatus arrays when the
01591  *  same relation is touched repeatedly within a transaction.
01592  * ----------
01593  */
01594 void
01595 pgstat_initstats(Relation rel)
01596 {
01597     Oid         rel_id = rel->rd_id;
01598     char        relkind = rel->rd_rel->relkind;
01599 
01600     /* We only count stats for things that have storage */
01601     if (!(relkind == RELKIND_RELATION ||
01602           relkind == RELKIND_MATVIEW ||
01603           relkind == RELKIND_INDEX ||
01604           relkind == RELKIND_TOASTVALUE ||
01605           relkind == RELKIND_SEQUENCE))
01606     {
01607         rel->pgstat_info = NULL;
01608         return;
01609     }
01610 
01611     if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
01612     {
01613         /* We're not counting at all */
01614         rel->pgstat_info = NULL;
01615         return;
01616     }
01617 
01618     /*
01619      * If we already set up this relation in the current transaction, nothing
01620      * to do.
01621      */
01622     if (rel->pgstat_info != NULL &&
01623         rel->pgstat_info->t_id == rel_id)
01624         return;
01625 
01626     /* Else find or make the PgStat_TableStatus entry, and update link */
01627     rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
01628 }
01629 
01630 /*
01631  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
01632  */
01633 static PgStat_TableStatus *
01634 get_tabstat_entry(Oid rel_id, bool isshared)
01635 {
01636     PgStat_TableStatus *entry;
01637     TabStatusArray *tsa;
01638     TabStatusArray *prev_tsa;
01639     int         i;
01640 
01641     /*
01642      * Search the already-used tabstat slots for this relation.
01643      */
01644     prev_tsa = NULL;
01645     for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
01646     {
01647         for (i = 0; i < tsa->tsa_used; i++)
01648         {
01649             entry = &tsa->tsa_entries[i];
01650             if (entry->t_id == rel_id)
01651                 return entry;
01652         }
01653 
01654         if (tsa->tsa_used < TABSTAT_QUANTUM)
01655         {
01656             /*
01657              * It must not be present, but we found a free slot instead. Fine,
01658              * let's use this one.  We assume the entry was already zeroed,
01659              * either at creation or after last use.
01660              */
01661             entry = &tsa->tsa_entries[tsa->tsa_used++];
01662             entry->t_id = rel_id;
01663             entry->t_shared = isshared;
01664             return entry;
01665         }
01666     }
01667 
01668     /*
01669      * We ran out of tabstat slots, so allocate more.  Be sure they're zeroed.
01670      */
01671     tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
01672                                                     sizeof(TabStatusArray));
01673     if (prev_tsa)
01674         prev_tsa->tsa_next = tsa;
01675     else
01676         pgStatTabList = tsa;
01677 
01678     /*
01679      * Use the first entry of the new TabStatusArray.
01680      */
01681     entry = &tsa->tsa_entries[tsa->tsa_used++];
01682     entry->t_id = rel_id;
01683     entry->t_shared = isshared;
01684     return entry;
01685 }
01686 
01687 /*
01688  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
01689  *
01690  * If no entry, return NULL, don't create a new one
01691  */
01692 PgStat_TableStatus *
01693 find_tabstat_entry(Oid rel_id)
01694 {
01695     PgStat_TableStatus *entry;
01696     TabStatusArray *tsa;
01697     int         i;
01698 
01699     for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
01700     {
01701         for (i = 0; i < tsa->tsa_used; i++)
01702         {
01703             entry = &tsa->tsa_entries[i];
01704             if (entry->t_id == rel_id)
01705                 return entry;
01706         }
01707     }
01708 
01709     /* Not present */
01710     return NULL;
01711 }
01712 
01713 /*
01714  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
01715  */
01716 static PgStat_SubXactStatus *
01717 get_tabstat_stack_level(int nest_level)
01718 {
01719     PgStat_SubXactStatus *xact_state;
01720 
01721     xact_state = pgStatXactStack;
01722     if (xact_state == NULL || xact_state->nest_level != nest_level)
01723     {
01724         xact_state = (PgStat_SubXactStatus *)
01725             MemoryContextAlloc(TopTransactionContext,
01726                                sizeof(PgStat_SubXactStatus));
01727         xact_state->nest_level = nest_level;
01728         xact_state->prev = pgStatXactStack;
01729         xact_state->first = NULL;
01730         pgStatXactStack = xact_state;
01731     }
01732     return xact_state;
01733 }
01734 
01735 /*
01736  * add_tabstat_xact_level - add a new (sub)transaction state record
01737  */
01738 static void
01739 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
01740 {
01741     PgStat_SubXactStatus *xact_state;
01742     PgStat_TableXactStatus *trans;
01743 
01744     /*
01745      * If this is the first rel to be modified at the current nest level, we
01746      * first have to push a transaction stack entry.
01747      */
01748     xact_state = get_tabstat_stack_level(nest_level);
01749 
01750     /* Now make a per-table stack entry */
01751     trans = (PgStat_TableXactStatus *)
01752         MemoryContextAllocZero(TopTransactionContext,
01753                                sizeof(PgStat_TableXactStatus));
01754     trans->nest_level = nest_level;
01755     trans->upper = pgstat_info->trans;
01756     trans->parent = pgstat_info;
01757     trans->next = xact_state->first;
01758     xact_state->first = trans;
01759     pgstat_info->trans = trans;
01760 }
01761 
01762 /*
01763  * pgstat_count_heap_insert - count a tuple insertion of n tuples
01764  */
01765 void
01766 pgstat_count_heap_insert(Relation rel, int n)
01767 {
01768     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
01769 
01770     if (pgstat_info != NULL)
01771     {
01772         /* We have to log the effect at the proper transactional level */
01773         int         nest_level = GetCurrentTransactionNestLevel();
01774 
01775         if (pgstat_info->trans == NULL ||
01776             pgstat_info->trans->nest_level != nest_level)
01777             add_tabstat_xact_level(pgstat_info, nest_level);
01778 
01779         pgstat_info->trans->tuples_inserted += n;
01780     }
01781 }
01782 
01783 /*
01784  * pgstat_count_heap_update - count a tuple update
01785  */
01786 void
01787 pgstat_count_heap_update(Relation rel, bool hot)
01788 {
01789     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
01790 
01791     if (pgstat_info != NULL)
01792     {
01793         /* We have to log the effect at the proper transactional level */
01794         int         nest_level = GetCurrentTransactionNestLevel();
01795 
01796         if (pgstat_info->trans == NULL ||
01797             pgstat_info->trans->nest_level != nest_level)
01798             add_tabstat_xact_level(pgstat_info, nest_level);
01799 
01800         pgstat_info->trans->tuples_updated++;
01801 
01802         /* t_tuples_hot_updated is nontransactional, so just advance it */
01803         if (hot)
01804             pgstat_info->t_counts.t_tuples_hot_updated++;
01805     }
01806 }
01807 
01808 /*
01809  * pgstat_count_heap_delete - count a tuple deletion
01810  */
01811 void
01812 pgstat_count_heap_delete(Relation rel)
01813 {
01814     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
01815 
01816     if (pgstat_info != NULL)
01817     {
01818         /* We have to log the effect at the proper transactional level */
01819         int         nest_level = GetCurrentTransactionNestLevel();
01820 
01821         if (pgstat_info->trans == NULL ||
01822             pgstat_info->trans->nest_level != nest_level)
01823             add_tabstat_xact_level(pgstat_info, nest_level);
01824 
01825         pgstat_info->trans->tuples_deleted++;
01826     }
01827 }
01828 
01829 /*
01830  * pgstat_update_heap_dead_tuples - update dead-tuples count
01831  *
01832  * The semantics of this are that we are reporting the nontransactional
01833  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
01834  * rather than increasing, and the change goes straight into the per-table
01835  * counter, not into transactional state.
01836  */
01837 void
01838 pgstat_update_heap_dead_tuples(Relation rel, int delta)
01839 {
01840     PgStat_TableStatus *pgstat_info = rel->pgstat_info;
01841 
01842     if (pgstat_info != NULL)
01843         pgstat_info->t_counts.t_delta_dead_tuples -= delta;
01844 }
01845 
01846 
01847 /* ----------
01848  * AtEOXact_PgStat
01849  *
01850  *  Called from access/transam/xact.c at top-level transaction commit/abort.
01851  * ----------
01852  */
01853 void
01854 AtEOXact_PgStat(bool isCommit)
01855 {
01856     PgStat_SubXactStatus *xact_state;
01857 
01858     /*
01859      * Count transaction commit or abort.  (We use counters, not just bools,
01860      * in case the reporting message isn't sent right away.)
01861      */
01862     if (isCommit)
01863         pgStatXactCommit++;
01864     else
01865         pgStatXactRollback++;
01866 
01867     /*
01868      * Transfer transactional insert/update counts into the base tabstat
01869      * entries.  We don't bother to free any of the transactional state, since
01870      * it's all in TopTransactionContext and will go away anyway.
01871      */
01872     xact_state = pgStatXactStack;
01873     if (xact_state != NULL)
01874     {
01875         PgStat_TableXactStatus *trans;
01876 
01877         Assert(xact_state->nest_level == 1);
01878         Assert(xact_state->prev == NULL);
01879         for (trans = xact_state->first; trans != NULL; trans = trans->next)
01880         {
01881             PgStat_TableStatus *tabstat;
01882 
01883             Assert(trans->nest_level == 1);
01884             Assert(trans->upper == NULL);
01885             tabstat = trans->parent;
01886             Assert(tabstat->trans == trans);
01887             /* count attempted actions regardless of commit/abort */
01888             tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
01889             tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
01890             tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
01891             if (isCommit)
01892             {
01893                 /* insert adds a live tuple, delete removes one */
01894                 tabstat->t_counts.t_delta_live_tuples +=
01895                     trans->tuples_inserted - trans->tuples_deleted;
01896                 /* update and delete each create a dead tuple */
01897                 tabstat->t_counts.t_delta_dead_tuples +=
01898                     trans->tuples_updated + trans->tuples_deleted;
01899                 /* insert, update, delete each count as one change event */
01900                 tabstat->t_counts.t_changed_tuples +=
01901                     trans->tuples_inserted + trans->tuples_updated +
01902                     trans->tuples_deleted;
01903             }
01904             else
01905             {
01906                 /* inserted tuples are dead, deleted tuples are unaffected */
01907                 tabstat->t_counts.t_delta_dead_tuples +=
01908                     trans->tuples_inserted + trans->tuples_updated;
01909                 /* an aborted xact generates no changed_tuple events */
01910             }
01911             tabstat->trans = NULL;
01912         }
01913     }
01914     pgStatXactStack = NULL;
01915 
01916     /* Make sure any stats snapshot is thrown away */
01917     pgstat_clear_snapshot();
01918 }
01919 
01920 /* ----------
01921  * AtEOSubXact_PgStat
01922  *
01923  *  Called from access/transam/xact.c at subtransaction commit/abort.
01924  * ----------
01925  */
01926 void
01927 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
01928 {
01929     PgStat_SubXactStatus *xact_state;
01930 
01931     /*
01932      * Transfer transactional insert/update counts into the next higher
01933      * subtransaction state.
01934      */
01935     xact_state = pgStatXactStack;
01936     if (xact_state != NULL &&
01937         xact_state->nest_level >= nestDepth)
01938     {
01939         PgStat_TableXactStatus *trans;
01940         PgStat_TableXactStatus *next_trans;
01941 
01942         /* delink xact_state from stack immediately to simplify reuse case */
01943         pgStatXactStack = xact_state->prev;
01944 
01945         for (trans = xact_state->first; trans != NULL; trans = next_trans)
01946         {
01947             PgStat_TableStatus *tabstat;
01948 
01949             next_trans = trans->next;
01950             Assert(trans->nest_level == nestDepth);
01951             tabstat = trans->parent;
01952             Assert(tabstat->trans == trans);
01953             if (isCommit)
01954             {
01955                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
01956                 {
01957                     trans->upper->tuples_inserted += trans->tuples_inserted;
01958                     trans->upper->tuples_updated += trans->tuples_updated;
01959                     trans->upper->tuples_deleted += trans->tuples_deleted;
01960                     tabstat->trans = trans->upper;
01961                     pfree(trans);
01962                 }
01963                 else
01964                 {
01965                     /*
01966                      * When there isn't an immediate parent state, we can just
01967                      * reuse the record instead of going through a
01968                      * palloc/pfree pushup (this works since it's all in
01969                      * TopTransactionContext anyway).  We have to re-link it
01970                      * into the parent level, though, and that might mean
01971                      * pushing a new entry into the pgStatXactStack.
01972                      */
01973                     PgStat_SubXactStatus *upper_xact_state;
01974 
01975                     upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
01976                     trans->next = upper_xact_state->first;
01977                     upper_xact_state->first = trans;
01978                     trans->nest_level = nestDepth - 1;
01979                 }
01980             }
01981             else
01982             {
01983                 /*
01984                  * On abort, update top-level tabstat counts, then forget the
01985                  * subtransaction
01986                  */
01987 
01988                 /* count attempted actions regardless of commit/abort */
01989                 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
01990                 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
01991                 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
01992                 /* inserted tuples are dead, deleted tuples are unaffected */
01993                 tabstat->t_counts.t_delta_dead_tuples +=
01994                     trans->tuples_inserted + trans->tuples_updated;
01995                 tabstat->trans = trans->upper;
01996                 pfree(trans);
01997             }
01998         }
01999         pfree(xact_state);
02000     }
02001 }
02002 
02003 
02004 /*
02005  * AtPrepare_PgStat
02006  *      Save the transactional stats state at 2PC transaction prepare.
02007  *
02008  * In this phase we just generate 2PC records for all the pending
02009  * transaction-dependent stats work.
02010  */
02011 void
02012 AtPrepare_PgStat(void)
02013 {
02014     PgStat_SubXactStatus *xact_state;
02015 
02016     xact_state = pgStatXactStack;
02017     if (xact_state != NULL)
02018     {
02019         PgStat_TableXactStatus *trans;
02020 
02021         Assert(xact_state->nest_level == 1);
02022         Assert(xact_state->prev == NULL);
02023         for (trans = xact_state->first; trans != NULL; trans = trans->next)
02024         {
02025             PgStat_TableStatus *tabstat;
02026             TwoPhasePgStatRecord record;
02027 
02028             Assert(trans->nest_level == 1);
02029             Assert(trans->upper == NULL);
02030             tabstat = trans->parent;
02031             Assert(tabstat->trans == trans);
02032 
02033             record.tuples_inserted = trans->tuples_inserted;
02034             record.tuples_updated = trans->tuples_updated;
02035             record.tuples_deleted = trans->tuples_deleted;
02036             record.t_id = tabstat->t_id;
02037             record.t_shared = tabstat->t_shared;
02038 
02039             RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
02040                                    &record, sizeof(TwoPhasePgStatRecord));
02041         }
02042     }
02043 }
02044 
02045 /*
02046  * PostPrepare_PgStat
02047  *      Clean up after successful PREPARE.
02048  *
02049  * All we need do here is unlink the transaction stats state from the
02050  * nontransactional state.  The nontransactional action counts will be
02051  * reported to the stats collector immediately, while the effects on live
02052  * and dead tuple counts are preserved in the 2PC state file.
02053  *
02054  * Note: AtEOXact_PgStat is not called during PREPARE.
02055  */
02056 void
02057 PostPrepare_PgStat(void)
02058 {
02059     PgStat_SubXactStatus *xact_state;
02060 
02061     /*
02062      * We don't bother to free any of the transactional state, since it's all
02063      * in TopTransactionContext and will go away anyway.
02064      */
02065     xact_state = pgStatXactStack;
02066     if (xact_state != NULL)
02067     {
02068         PgStat_TableXactStatus *trans;
02069 
02070         for (trans = xact_state->first; trans != NULL; trans = trans->next)
02071         {
02072             PgStat_TableStatus *tabstat;
02073 
02074             tabstat = trans->parent;
02075             tabstat->trans = NULL;
02076         }
02077     }
02078     pgStatXactStack = NULL;
02079 
02080     /* Make sure any stats snapshot is thrown away */
02081     pgstat_clear_snapshot();
02082 }
02083 
02084 /*
02085  * 2PC processing routine for COMMIT PREPARED case.
02086  *
02087  * Load the saved counts into our local pgstats state.
02088  */
02089 void
02090 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
02091                            void *recdata, uint32 len)
02092 {
02093     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
02094     PgStat_TableStatus *pgstat_info;
02095 
02096     /* Find or create a tabstat entry for the rel */
02097     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
02098 
02099     /* Same math as in AtEOXact_PgStat, commit case */
02100     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
02101     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
02102     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
02103     pgstat_info->t_counts.t_delta_live_tuples +=
02104         rec->tuples_inserted - rec->tuples_deleted;
02105     pgstat_info->t_counts.t_delta_dead_tuples +=
02106         rec->tuples_updated + rec->tuples_deleted;
02107     pgstat_info->t_counts.t_changed_tuples +=
02108         rec->tuples_inserted + rec->tuples_updated +
02109         rec->tuples_deleted;
02110 }
02111 
02112 /*
02113  * 2PC processing routine for ROLLBACK PREPARED case.
02114  *
02115  * Load the saved counts into our local pgstats state, but treat them
02116  * as aborted.
02117  */
02118 void
02119 pgstat_twophase_postabort(TransactionId xid, uint16 info,
02120                           void *recdata, uint32 len)
02121 {
02122     TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
02123     PgStat_TableStatus *pgstat_info;
02124 
02125     /* Find or create a tabstat entry for the rel */
02126     pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
02127 
02128     /* Same math as in AtEOXact_PgStat, abort case */
02129     pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
02130     pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
02131     pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
02132     pgstat_info->t_counts.t_delta_dead_tuples +=
02133         rec->tuples_inserted + rec->tuples_updated;
02134 }
02135 
02136 
02137 /* ----------
02138  * pgstat_fetch_stat_dbentry() -
02139  *
02140  *  Support function for the SQL-callable pgstat* functions. Returns
02141  *  the collected statistics for one database or NULL. NULL doesn't mean
02142  *  that the database doesn't exist, it is just not yet known by the
02143  *  collector, so the caller is better off to report ZERO instead.
02144  * ----------
02145  */
02146 PgStat_StatDBEntry *
02147 pgstat_fetch_stat_dbentry(Oid dbid)
02148 {
02149     /*
02150      * If not done for this transaction, read the statistics collector stats
02151      * file into some hash tables.
02152      */
02153     backend_read_statsfile();
02154 
02155     /*
02156      * Lookup the requested database; return NULL if not found
02157      */
02158     return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
02159                                               (void *) &dbid,
02160                                               HASH_FIND, NULL);
02161 }
02162 
02163 
02164 /* ----------
02165  * pgstat_fetch_stat_tabentry() -
02166  *
02167  *  Support function for the SQL-callable pgstat* functions. Returns
02168  *  the collected statistics for one table or NULL. NULL doesn't mean
02169  *  that the table doesn't exist, it is just not yet known by the
02170  *  collector, so the caller is better off to report ZERO instead.
02171  * ----------
02172  */
02173 PgStat_StatTabEntry *
02174 pgstat_fetch_stat_tabentry(Oid relid)
02175 {
02176     Oid         dbid;
02177     PgStat_StatDBEntry *dbentry;
02178     PgStat_StatTabEntry *tabentry;
02179 
02180     /*
02181      * If not done for this transaction, read the statistics collector stats
02182      * file into some hash tables.
02183      */
02184     backend_read_statsfile();
02185 
02186     /*
02187      * Lookup our database, then look in its table hash table.
02188      */
02189     dbid = MyDatabaseId;
02190     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
02191                                                  (void *) &dbid,
02192                                                  HASH_FIND, NULL);
02193     if (dbentry != NULL && dbentry->tables != NULL)
02194     {
02195         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
02196                                                        (void *) &relid,
02197                                                        HASH_FIND, NULL);
02198         if (tabentry)
02199             return tabentry;
02200     }
02201 
02202     /*
02203      * If we didn't find it, maybe it's a shared table.
02204      */
02205     dbid = InvalidOid;
02206     dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
02207                                                  (void *) &dbid,
02208                                                  HASH_FIND, NULL);
02209     if (dbentry != NULL && dbentry->tables != NULL)
02210     {
02211         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
02212                                                        (void *) &relid,
02213                                                        HASH_FIND, NULL);
02214         if (tabentry)
02215             return tabentry;
02216     }
02217 
02218     return NULL;
02219 }
02220 
02221 
02222 /* ----------
02223  * pgstat_fetch_stat_funcentry() -
02224  *
02225  *  Support function for the SQL-callable pgstat* functions. Returns
02226  *  the collected statistics for one function or NULL.
02227  * ----------
02228  */
02229 PgStat_StatFuncEntry *
02230 pgstat_fetch_stat_funcentry(Oid func_id)
02231 {
02232     PgStat_StatDBEntry *dbentry;
02233     PgStat_StatFuncEntry *funcentry = NULL;
02234 
02235     /* load the stats file if needed */
02236     backend_read_statsfile();
02237 
02238     /* Lookup our database, then find the requested function.  */
02239     dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
02240     if (dbentry != NULL && dbentry->functions != NULL)
02241     {
02242         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
02243                                                          (void *) &func_id,
02244                                                          HASH_FIND, NULL);
02245     }
02246 
02247     return funcentry;
02248 }
02249 
02250 
02251 /* ----------
02252  * pgstat_fetch_stat_beentry() -
02253  *
02254  *  Support function for the SQL-callable pgstat* functions. Returns
02255  *  our local copy of the current-activity entry for one backend.
02256  *
02257  *  NB: caller is responsible for a check if the user is permitted to see
02258  *  this info (especially the querystring).
02259  * ----------
02260  */
02261 PgBackendStatus *
02262 pgstat_fetch_stat_beentry(int beid)
02263 {
02264     pgstat_read_current_status();
02265 
02266     if (beid < 1 || beid > localNumBackends)
02267         return NULL;
02268 
02269     return &localBackendStatusTable[beid - 1];
02270 }
02271 
02272 
02273 /* ----------
02274  * pgstat_fetch_stat_numbackends() -
02275  *
02276  *  Support function for the SQL-callable pgstat* functions. Returns
02277  *  the maximum current backend id.
02278  * ----------
02279  */
02280 int
02281 pgstat_fetch_stat_numbackends(void)
02282 {
02283     pgstat_read_current_status();
02284 
02285     return localNumBackends;
02286 }
02287 
02288 /*
02289  * ---------
02290  * pgstat_fetch_global() -
02291  *
02292  *  Support function for the SQL-callable pgstat* functions. Returns
02293  *  a pointer to the global statistics struct.
02294  * ---------
02295  */
02296 PgStat_GlobalStats *
02297 pgstat_fetch_global(void)
02298 {
02299     backend_read_statsfile();
02300 
02301     return &globalStats;
02302 }
02303 
02304 
02305 /* ------------------------------------------------------------
02306  * Functions for management of the shared-memory PgBackendStatus array
02307  * ------------------------------------------------------------
02308  */
02309 
02310 static PgBackendStatus *BackendStatusArray = NULL;
02311 static PgBackendStatus *MyBEEntry = NULL;
02312 static char *BackendClientHostnameBuffer = NULL;
02313 static char *BackendAppnameBuffer = NULL;
02314 static char *BackendActivityBuffer = NULL;
02315 static Size BackendActivityBufferSize = 0;
02316 
02317 
02318 /*
02319  * Report shared-memory space needed by CreateSharedBackendStatus.
02320  */
02321 Size
02322 BackendStatusShmemSize(void)
02323 {
02324     Size        size;
02325 
02326     size = mul_size(sizeof(PgBackendStatus), MaxBackends);
02327     size = add_size(size,
02328                     mul_size(NAMEDATALEN, MaxBackends));
02329     size = add_size(size,
02330                     mul_size(pgstat_track_activity_query_size, MaxBackends));
02331     size = add_size(size,
02332                     mul_size(NAMEDATALEN, MaxBackends));
02333     return size;
02334 }
02335 
02336 /*
02337  * Initialize the shared status array and several string buffers
02338  * during postmaster startup.
02339  */
02340 void
02341 CreateSharedBackendStatus(void)
02342 {
02343     Size        size;
02344     bool        found;
02345     int         i;
02346     char       *buffer;
02347 
02348     /* Create or attach to the shared array */
02349     size = mul_size(sizeof(PgBackendStatus), MaxBackends);
02350     BackendStatusArray = (PgBackendStatus *)
02351         ShmemInitStruct("Backend Status Array", size, &found);
02352 
02353     if (!found)
02354     {
02355         /*
02356          * We're the first - initialize.
02357          */
02358         MemSet(BackendStatusArray, 0, size);
02359     }
02360 
02361     /* Create or attach to the shared appname buffer */
02362     size = mul_size(NAMEDATALEN, MaxBackends);
02363     BackendAppnameBuffer = (char *)
02364         ShmemInitStruct("Backend Application Name Buffer", size, &found);
02365 
02366     if (!found)
02367     {
02368         MemSet(BackendAppnameBuffer, 0, size);
02369 
02370         /* Initialize st_appname pointers. */
02371         buffer = BackendAppnameBuffer;
02372         for (i = 0; i < MaxBackends; i++)
02373         {
02374             BackendStatusArray[i].st_appname = buffer;
02375             buffer += NAMEDATALEN;
02376         }
02377     }
02378 
02379     /* Create or attach to the shared client hostname buffer */
02380     size = mul_size(NAMEDATALEN, MaxBackends);
02381     BackendClientHostnameBuffer = (char *)
02382         ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
02383 
02384     if (!found)
02385     {
02386         MemSet(BackendClientHostnameBuffer, 0, size);
02387 
02388         /* Initialize st_clienthostname pointers. */
02389         buffer = BackendClientHostnameBuffer;
02390         for (i = 0; i < MaxBackends; i++)
02391         {
02392             BackendStatusArray[i].st_clienthostname = buffer;
02393             buffer += NAMEDATALEN;
02394         }
02395     }
02396 
02397     /* Create or attach to the shared activity buffer */
02398     BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
02399                                          MaxBackends);
02400     BackendActivityBuffer = (char *)
02401         ShmemInitStruct("Backend Activity Buffer",
02402                         BackendActivityBufferSize,
02403                         &found);
02404 
02405     if (!found)
02406     {
02407         MemSet(BackendActivityBuffer, 0, size);
02408 
02409         /* Initialize st_activity pointers. */
02410         buffer = BackendActivityBuffer;
02411         for (i = 0; i < MaxBackends; i++)
02412         {
02413             BackendStatusArray[i].st_activity = buffer;
02414             buffer += pgstat_track_activity_query_size;
02415         }
02416     }
02417 }
02418 
02419 
02420 /* ----------
02421  * pgstat_initialize() -
02422  *
02423  *  Initialize pgstats state, and set up our on-proc-exit hook.
02424  *  Called from InitPostgres.  MyBackendId must be set,
02425  *  but we must not have started any transaction yet (since the
02426  *  exit hook must run after the last transaction exit).
02427  *  NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
02428  * ----------
02429  */
02430 void
02431 pgstat_initialize(void)
02432 {
02433     /* Initialize MyBEEntry */
02434     Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
02435     MyBEEntry = &BackendStatusArray[MyBackendId - 1];
02436 
02437     /* Set up a process-exit hook to clean up */
02438     on_shmem_exit(pgstat_beshutdown_hook, 0);
02439 }
02440 
02441 /* ----------
02442  * pgstat_bestart() -
02443  *
02444  *  Initialize this backend's entry in the PgBackendStatus array.
02445  *  Called from InitPostgres.
02446  *  MyDatabaseId, session userid, and application_name must be set
02447  *  (hence, this cannot be combined with pgstat_initialize).
02448  * ----------
02449  */
02450 void
02451 pgstat_bestart(void)
02452 {
02453     TimestampTz proc_start_timestamp;
02454     Oid         userid;
02455     SockAddr    clientaddr;
02456     volatile PgBackendStatus *beentry;
02457 
02458     /*
02459      * To minimize the time spent modifying the PgBackendStatus entry, fetch
02460      * all the needed data first.
02461      *
02462      * If we have a MyProcPort, use its session start time (for consistency,
02463      * and to save a kernel call).
02464      */
02465     if (MyProcPort)
02466         proc_start_timestamp = MyProcPort->SessionStartTime;
02467     else
02468         proc_start_timestamp = GetCurrentTimestamp();
02469     userid = GetSessionUserId();
02470 
02471     /*
02472      * We may not have a MyProcPort (eg, if this is the autovacuum process).
02473      * If so, use all-zeroes client address, which is dealt with specially in
02474      * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
02475      */
02476     if (MyProcPort)
02477         memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
02478     else
02479         MemSet(&clientaddr, 0, sizeof(clientaddr));
02480 
02481     /*
02482      * Initialize my status entry, following the protocol of bumping
02483      * st_changecount before and after; and make sure it's even afterwards. We
02484      * use a volatile pointer here to ensure the compiler doesn't try to get
02485      * cute.
02486      */
02487     beentry = MyBEEntry;
02488     do
02489     {
02490         beentry->st_changecount++;
02491     } while ((beentry->st_changecount & 1) == 0);
02492 
02493     beentry->st_procpid = MyProcPid;
02494     beentry->st_proc_start_timestamp = proc_start_timestamp;
02495     beentry->st_activity_start_timestamp = 0;
02496     beentry->st_state_start_timestamp = 0;
02497     beentry->st_xact_start_timestamp = 0;
02498     beentry->st_databaseid = MyDatabaseId;
02499     beentry->st_userid = userid;
02500     beentry->st_clientaddr = clientaddr;
02501     beentry->st_clienthostname[0] = '\0';
02502     beentry->st_waiting = false;
02503     beentry->st_state = STATE_UNDEFINED;
02504     beentry->st_appname[0] = '\0';
02505     beentry->st_activity[0] = '\0';
02506     /* Also make sure the last byte in each string area is always 0 */
02507     beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
02508     beentry->st_appname[NAMEDATALEN - 1] = '\0';
02509     beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
02510 
02511     beentry->st_changecount++;
02512     Assert((beentry->st_changecount & 1) == 0);
02513 
02514     if (MyProcPort && MyProcPort->remote_hostname)
02515         strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname, NAMEDATALEN);
02516 
02517     /* Update app name to current GUC setting */
02518     if (application_name)
02519         pgstat_report_appname(application_name);
02520 }
02521 
02522 /*
02523  * Shut down a single backend's statistics reporting at process exit.
02524  *
02525  * Flush any remaining statistics counts out to the collector.
02526  * Without this, operations triggered during backend exit (such as
02527  * temp table deletions) won't be counted.
02528  *
02529  * Lastly, clear out our entry in the PgBackendStatus array.
02530  */
02531 static void
02532 pgstat_beshutdown_hook(int code, Datum arg)
02533 {
02534     volatile PgBackendStatus *beentry = MyBEEntry;
02535 
02536     /*
02537      * If we got as far as discovering our own database ID, we can report what
02538      * we did to the collector.  Otherwise, we'd be sending an invalid
02539      * database ID, so forget it.  (This means that accesses to pg_database
02540      * during failed backend starts might never get counted.)
02541      */
02542     if (OidIsValid(MyDatabaseId))
02543         pgstat_report_stat(true);
02544 
02545     /*
02546      * Clear my status entry, following the protocol of bumping st_changecount
02547      * before and after.  We use a volatile pointer here to ensure the
02548      * compiler doesn't try to get cute.
02549      */
02550     beentry->st_changecount++;
02551 
02552     beentry->st_procpid = 0;    /* mark invalid */
02553 
02554     beentry->st_changecount++;
02555     Assert((beentry->st_changecount & 1) == 0);
02556 }
02557 
02558 
02559 /* ----------
02560  * pgstat_report_activity() -
02561  *
02562  *  Called from tcop/postgres.c to report what the backend is actually doing
02563  *  (but note cmd_str can be NULL for certain cases).
02564  *
02565  * All updates of the status entry follow the protocol of bumping
02566  * st_changecount before and after.  We use a volatile pointer here to
02567  * ensure the compiler doesn't try to get cute.
02568  * ----------
02569  */
02570 void
02571 pgstat_report_activity(BackendState state, const char *cmd_str)
02572 {
02573     volatile PgBackendStatus *beentry = MyBEEntry;
02574     TimestampTz start_timestamp;
02575     TimestampTz current_timestamp;
02576     int         len = 0;
02577 
02578     TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
02579 
02580     if (!beentry)
02581         return;
02582 
02583     if (!pgstat_track_activities)
02584     {
02585         if (beentry->st_state != STATE_DISABLED)
02586         {
02587             /*
02588              * track_activities is disabled, but we last reported a
02589              * non-disabled state.  As our final update, change the state and
02590              * clear fields we will not be updating anymore.
02591              */
02592             beentry->st_changecount++;
02593             beentry->st_state = STATE_DISABLED;
02594             beentry->st_state_start_timestamp = 0;
02595             beentry->st_activity[0] = '\0';
02596             beentry->st_activity_start_timestamp = 0;
02597             /* st_xact_start_timestamp and st_waiting are also disabled */
02598             beentry->st_xact_start_timestamp = 0;
02599             beentry->st_waiting = false;
02600             beentry->st_changecount++;
02601             Assert((beentry->st_changecount & 1) == 0);
02602         }
02603         return;
02604     }
02605 
02606     /*
02607      * To minimize the time spent modifying the entry, fetch all the needed
02608      * data first.
02609      */
02610     start_timestamp = GetCurrentStatementStartTimestamp();
02611     if (cmd_str != NULL)
02612     {
02613         len = pg_mbcliplen(cmd_str, strlen(cmd_str),
02614                            pgstat_track_activity_query_size - 1);
02615     }
02616     current_timestamp = GetCurrentTimestamp();
02617 
02618     /*
02619      * Now update the status entry
02620      */
02621     beentry->st_changecount++;
02622 
02623     beentry->st_state = state;
02624     beentry->st_state_start_timestamp = current_timestamp;
02625 
02626     if (cmd_str != NULL)
02627     {
02628         memcpy((char *) beentry->st_activity, cmd_str, len);
02629         beentry->st_activity[len] = '\0';
02630         beentry->st_activity_start_timestamp = start_timestamp;
02631     }
02632 
02633     beentry->st_changecount++;
02634     Assert((beentry->st_changecount & 1) == 0);
02635 }
02636 
02637 /* ----------
02638  * pgstat_report_appname() -
02639  *
02640  *  Called to update our application name.
02641  * ----------
02642  */
02643 void
02644 pgstat_report_appname(const char *appname)
02645 {
02646     volatile PgBackendStatus *beentry = MyBEEntry;
02647     int         len;
02648 
02649     if (!beentry)
02650         return;
02651 
02652     /* This should be unnecessary if GUC did its job, but be safe */
02653     len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
02654 
02655     /*
02656      * Update my status entry, following the protocol of bumping
02657      * st_changecount before and after.  We use a volatile pointer here to
02658      * ensure the compiler doesn't try to get cute.
02659      */
02660     beentry->st_changecount++;
02661 
02662     memcpy((char *) beentry->st_appname, appname, len);
02663     beentry->st_appname[len] = '\0';
02664 
02665     beentry->st_changecount++;
02666     Assert((beentry->st_changecount & 1) == 0);
02667 }
02668 
02669 /*
02670  * Report current transaction start timestamp as the specified value.
02671  * Zero means there is no active transaction.
02672  */
02673 void
02674 pgstat_report_xact_timestamp(TimestampTz tstamp)
02675 {
02676     volatile PgBackendStatus *beentry = MyBEEntry;
02677 
02678     if (!pgstat_track_activities || !beentry)
02679         return;
02680 
02681     /*
02682      * Update my status entry, following the protocol of bumping
02683      * st_changecount before and after.  We use a volatile pointer here to
02684      * ensure the compiler doesn't try to get cute.
02685      */
02686     beentry->st_changecount++;
02687     beentry->st_xact_start_timestamp = tstamp;
02688     beentry->st_changecount++;
02689     Assert((beentry->st_changecount & 1) == 0);
02690 }
02691 
02692 /* ----------
02693  * pgstat_report_waiting() -
02694  *
02695  *  Called from lock manager to report beginning or end of a lock wait.
02696  *
02697  * NB: this *must* be able to survive being called before MyBEEntry has been
02698  * initialized.
02699  * ----------
02700  */
02701 void
02702 pgstat_report_waiting(bool waiting)
02703 {
02704     volatile PgBackendStatus *beentry = MyBEEntry;
02705 
02706     if (!pgstat_track_activities || !beentry)
02707         return;
02708 
02709     /*
02710      * Since this is a single-byte field in a struct that only this process
02711      * may modify, there seems no need to bother with the st_changecount
02712      * protocol.  The update must appear atomic in any case.
02713      */
02714     beentry->st_waiting = waiting;
02715 }
02716 
02717 
02718 /* ----------
02719  * pgstat_read_current_status() -
02720  *
02721  *  Copy the current contents of the PgBackendStatus array to local memory,
02722  *  if not already done in this transaction.
02723  * ----------
02724  */
02725 static void
02726 pgstat_read_current_status(void)
02727 {
02728     volatile PgBackendStatus *beentry;
02729     PgBackendStatus *localtable;
02730     PgBackendStatus *localentry;
02731     char       *localappname,
02732                *localactivity;
02733     int         i;
02734 
02735     Assert(!pgStatRunningInCollector);
02736     if (localBackendStatusTable)
02737         return;                 /* already done */
02738 
02739     pgstat_setup_memcxt();
02740 
02741     localtable = (PgBackendStatus *)
02742         MemoryContextAlloc(pgStatLocalContext,
02743                            sizeof(PgBackendStatus) * MaxBackends);
02744     localappname = (char *)
02745         MemoryContextAlloc(pgStatLocalContext,
02746                            NAMEDATALEN * MaxBackends);
02747     localactivity = (char *)
02748         MemoryContextAlloc(pgStatLocalContext,
02749                            pgstat_track_activity_query_size * MaxBackends);
02750     localNumBackends = 0;
02751 
02752     beentry = BackendStatusArray;
02753     localentry = localtable;
02754     for (i = 1; i <= MaxBackends; i++)
02755     {
02756         /*
02757          * Follow the protocol of retrying if st_changecount changes while we
02758          * copy the entry, or if it's odd.  (The check for odd is needed to
02759          * cover the case where we are able to completely copy the entry while
02760          * the source backend is between increment steps.)  We use a volatile
02761          * pointer here to ensure the compiler doesn't try to get cute.
02762          */
02763         for (;;)
02764         {
02765             int         save_changecount = beentry->st_changecount;
02766 
02767             localentry->st_procpid = beentry->st_procpid;
02768             if (localentry->st_procpid > 0)
02769             {
02770                 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
02771 
02772                 /*
02773                  * strcpy is safe even if the string is modified concurrently,
02774                  * because there's always a \0 at the end of the buffer.
02775                  */
02776                 strcpy(localappname, (char *) beentry->st_appname);
02777                 localentry->st_appname = localappname;
02778                 strcpy(localactivity, (char *) beentry->st_activity);
02779                 localentry->st_activity = localactivity;
02780             }
02781 
02782             if (save_changecount == beentry->st_changecount &&
02783                 (save_changecount & 1) == 0)
02784                 break;
02785 
02786             /* Make sure we can break out of loop if stuck... */
02787             CHECK_FOR_INTERRUPTS();
02788         }
02789 
02790         beentry++;
02791         /* Only valid entries get included into the local array */
02792         if (localentry->st_procpid > 0)
02793         {
02794             localentry++;
02795             localappname += NAMEDATALEN;
02796             localactivity += pgstat_track_activity_query_size;
02797             localNumBackends++;
02798         }
02799     }
02800 
02801     /* Set the pointer only after completion of a valid table */
02802     localBackendStatusTable = localtable;
02803 }
02804 
02805 
02806 /* ----------
02807  * pgstat_get_backend_current_activity() -
02808  *
02809  *  Return a string representing the current activity of the backend with
02810  *  the specified PID.  This looks directly at the BackendStatusArray,
02811  *  and so will provide current information regardless of the age of our
02812  *  transaction's snapshot of the status array.
02813  *
02814  *  It is the caller's responsibility to invoke this only for backends whose
02815  *  state is expected to remain stable while the result is in use.  The
02816  *  only current use is in deadlock reporting, where we can expect that
02817  *  the target backend is blocked on a lock.  (There are corner cases
02818  *  where the target's wait could get aborted while we are looking at it,
02819  *  but the very worst consequence is to return a pointer to a string
02820  *  that's been changed, so we won't worry too much.)
02821  *
02822  *  Note: return strings for special cases match pg_stat_get_backend_activity.
02823  * ----------
02824  */
02825 const char *
02826 pgstat_get_backend_current_activity(int pid, bool checkUser)
02827 {
02828     PgBackendStatus *beentry;
02829     int         i;
02830 
02831     beentry = BackendStatusArray;
02832     for (i = 1; i <= MaxBackends; i++)
02833     {
02834         /*
02835          * Although we expect the target backend's entry to be stable, that
02836          * doesn't imply that anyone else's is.  To avoid identifying the
02837          * wrong backend, while we check for a match to the desired PID we
02838          * must follow the protocol of retrying if st_changecount changes
02839          * while we examine the entry, or if it's odd.  (This might be
02840          * unnecessary, since fetching or storing an int is almost certainly
02841          * atomic, but let's play it safe.)  We use a volatile pointer here to
02842          * ensure the compiler doesn't try to get cute.
02843          */
02844         volatile PgBackendStatus *vbeentry = beentry;
02845         bool        found;
02846 
02847         for (;;)
02848         {
02849             int         save_changecount = vbeentry->st_changecount;
02850 
02851             found = (vbeentry->st_procpid == pid);
02852 
02853             if (save_changecount == vbeentry->st_changecount &&
02854                 (save_changecount & 1) == 0)
02855                 break;
02856 
02857             /* Make sure we can break out of loop if stuck... */
02858             CHECK_FOR_INTERRUPTS();
02859         }
02860 
02861         if (found)
02862         {
02863             /* Now it is safe to use the non-volatile pointer */
02864             if (checkUser && !superuser() && beentry->st_userid != GetUserId())
02865                 return "<insufficient privilege>";
02866             else if (*(beentry->st_activity) == '\0')
02867                 return "<command string not enabled>";
02868             else
02869                 return beentry->st_activity;
02870         }
02871 
02872         beentry++;
02873     }
02874 
02875     /* If we get here, caller is in error ... */
02876     return "<backend information not available>";
02877 }
02878 
02879 /* ----------
02880  * pgstat_get_crashed_backend_activity() -
02881  *
02882  *  Return a string representing the current activity of the backend with
02883  *  the specified PID.  Like the function above, but reads shared memory with
02884  *  the expectation that it may be corrupt.  On success, copy the string
02885  *  into the "buffer" argument and return that pointer.  On failure,
02886  *  return NULL.
02887  *
02888  *  This function is only intended to be used by the postmaster to report the
02889  *  query that crashed a backend.  In particular, no attempt is made to
02890  *  follow the correct concurrency protocol when accessing the
02891  *  BackendStatusArray.  But that's OK, in the worst case we'll return a
02892  *  corrupted message.  We also must take care not to trip on ereport(ERROR).
02893  * ----------
02894  */
02895 const char *
02896 pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
02897 {
02898     volatile PgBackendStatus *beentry;
02899     int         i;
02900 
02901     beentry = BackendStatusArray;
02902 
02903     /*
02904      * We probably shouldn't get here before shared memory has been set up,
02905      * but be safe.
02906      */
02907     if (beentry == NULL || BackendActivityBuffer == NULL)
02908         return NULL;
02909 
02910     for (i = 1; i <= MaxBackends; i++)
02911     {
02912         if (beentry->st_procpid == pid)
02913         {
02914             /* Read pointer just once, so it can't change after validation */
02915             const char *activity = beentry->st_activity;
02916             const char *activity_last;
02917 
02918             /*
02919              * We mustn't access activity string before we verify that it
02920              * falls within the BackendActivityBuffer. To make sure that the
02921              * entire string including its ending is contained within the
02922              * buffer, subtract one activity length from the buffer size.
02923              */
02924             activity_last = BackendActivityBuffer + BackendActivityBufferSize
02925                 - pgstat_track_activity_query_size;
02926 
02927             if (activity < BackendActivityBuffer ||
02928                 activity > activity_last)
02929                 return NULL;
02930 
02931             /* If no string available, no point in a report */
02932             if (activity[0] == '\0')
02933                 return NULL;
02934 
02935             /*
02936              * Copy only ASCII-safe characters so we don't run into encoding
02937              * problems when reporting the message; and be sure not to run off
02938              * the end of memory.
02939              */
02940             ascii_safe_strlcpy(buffer, activity,
02941                                Min(buflen, pgstat_track_activity_query_size));
02942 
02943             return buffer;
02944         }
02945 
02946         beentry++;
02947     }
02948 
02949     /* PID not found */
02950     return NULL;
02951 }
02952 
02953 
02954 /* ------------------------------------------------------------
02955  * Local support functions follow
02956  * ------------------------------------------------------------
02957  */
02958 
02959 
02960 /* ----------
02961  * pgstat_setheader() -
02962  *
02963  *      Set common header fields in a statistics message
02964  * ----------
02965  */
02966 static void
02967 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
02968 {
02969     hdr->m_type = mtype;
02970 }
02971 
02972 
02973 /* ----------
02974  * pgstat_send() -
02975  *
02976  *      Send out one statistics message to the collector
02977  * ----------
02978  */
02979 static void
02980 pgstat_send(void *msg, int len)
02981 {
02982     int         rc;
02983 
02984     if (pgStatSock == PGINVALID_SOCKET)
02985         return;
02986 
02987     ((PgStat_MsgHdr *) msg)->m_size = len;
02988 
02989     /* We'll retry after EINTR, but ignore all other failures */
02990     do
02991     {
02992         rc = send(pgStatSock, msg, len, 0);
02993     } while (rc < 0 && errno == EINTR);
02994 
02995 #ifdef USE_ASSERT_CHECKING
02996     /* In debug builds, log send failures ... */
02997     if (rc < 0)
02998         elog(LOG, "could not send to statistics collector: %m");
02999 #endif
03000 }
03001 
03002 /* ----------
03003  * pgstat_send_bgwriter() -
03004  *
03005  *      Send bgwriter statistics to the collector
03006  * ----------
03007  */
03008 void
03009 pgstat_send_bgwriter(void)
03010 {
03011     /* We assume this initializes to zeroes */
03012     static const PgStat_MsgBgWriter all_zeroes;
03013 
03014     /*
03015      * This function can be called even if nothing at all has happened. In
03016      * this case, avoid sending a completely empty message to the stats
03017      * collector.
03018      */
03019     if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
03020         return;
03021 
03022     /*
03023      * Prepare and send the message
03024      */
03025     pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
03026     pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
03027 
03028     /*
03029      * Clear out the statistics buffer, so it can be re-used.
03030      */
03031     MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
03032 }
03033 
03034 
03035 /* ----------
03036  * PgstatCollectorMain() -
03037  *
03038  *  Start up the statistics collector process.  This is the body of the
03039  *  postmaster child process.
03040  *
03041  *  The argc/argv parameters are valid only in EXEC_BACKEND case.
03042  * ----------
03043  */
03044 NON_EXEC_STATIC void
03045 PgstatCollectorMain(int argc, char *argv[])
03046 {
03047     int         len;
03048     PgStat_Msg  msg;
03049     int         wr;
03050 
03051     IsUnderPostmaster = true;   /* we are a postmaster subprocess now */
03052 
03053     MyProcPid = getpid();       /* reset MyProcPid */
03054 
03055     MyStartTime = time(NULL);   /* record Start Time for logging */
03056 
03057     /*
03058      * If possible, make this process a group leader, so that the postmaster
03059      * can signal any child processes too.  (pgstat probably never has any
03060      * child processes, but for consistency we make all postmaster child
03061      * processes do this.)
03062      */
03063 #ifdef HAVE_SETSID
03064     if (setsid() < 0)
03065         elog(FATAL, "setsid() failed: %m");
03066 #endif
03067 
03068     InitializeLatchSupport();   /* needed for latch waits */
03069 
03070     /* Initialize private latch for use by signal handlers */
03071     InitLatch(&pgStatLatch);
03072 
03073     /*
03074      * Ignore all signals usually bound to some action in the postmaster,
03075      * except SIGHUP and SIGQUIT.  Note we don't need a SIGUSR1 handler to
03076      * support latch operations, because pgStatLatch is local not shared.
03077      */
03078     pqsignal(SIGHUP, pgstat_sighup_handler);
03079     pqsignal(SIGINT, SIG_IGN);
03080     pqsignal(SIGTERM, SIG_IGN);
03081     pqsignal(SIGQUIT, pgstat_exit);
03082     pqsignal(SIGALRM, SIG_IGN);
03083     pqsignal(SIGPIPE, SIG_IGN);
03084     pqsignal(SIGUSR1, SIG_IGN);
03085     pqsignal(SIGUSR2, SIG_IGN);
03086     pqsignal(SIGCHLD, SIG_DFL);
03087     pqsignal(SIGTTIN, SIG_DFL);
03088     pqsignal(SIGTTOU, SIG_DFL);
03089     pqsignal(SIGCONT, SIG_DFL);
03090     pqsignal(SIGWINCH, SIG_DFL);
03091     PG_SETMASK(&UnBlockSig);
03092 
03093     /*
03094      * Identify myself via ps
03095      */
03096     init_ps_display("stats collector process", "", "", "");
03097 
03098     /*
03099      * Read in an existing statistics stats file or initialize the stats to
03100      * zero.
03101      */
03102     pgStatRunningInCollector = true;
03103     pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
03104 
03105     /*
03106      * Loop to process messages until we get SIGQUIT or detect ungraceful
03107      * death of our parent postmaster.
03108      *
03109      * For performance reasons, we don't want to do ResetLatch/WaitLatch after
03110      * every message; instead, do that only after a recv() fails to obtain a
03111      * message.  (This effectively means that if backends are sending us stuff
03112      * like mad, we won't notice postmaster death until things slack off a
03113      * bit; which seems fine.)  To do that, we have an inner loop that
03114      * iterates as long as recv() succeeds.  We do recognize got_SIGHUP inside
03115      * the inner loop, which means that such interrupts will get serviced but
03116      * the latch won't get cleared until next time there is a break in the
03117      * action.
03118      */
03119     for (;;)
03120     {
03121         /* Clear any already-pending wakeups */
03122         ResetLatch(&pgStatLatch);
03123 
03124         /*
03125          * Quit if we get SIGQUIT from the postmaster.
03126          */
03127         if (need_exit)
03128             break;
03129 
03130         /*
03131          * Inner loop iterates as long as we keep getting messages, or until
03132          * need_exit becomes set.
03133          */
03134         while (!need_exit)
03135         {
03136             /*
03137              * Reload configuration if we got SIGHUP from the postmaster.
03138              */
03139             if (got_SIGHUP)
03140             {
03141                 got_SIGHUP = false;
03142                 ProcessConfigFile(PGC_SIGHUP);
03143             }
03144 
03145             /*
03146              * Write the stats file if a new request has arrived that is not
03147              * satisfied by existing file.
03148              */
03149             if (pgstat_write_statsfile_needed())
03150                 pgstat_write_statsfiles(false, false);
03151 
03152             /*
03153              * Try to receive and process a message.  This will not block,
03154              * since the socket is set to non-blocking mode.
03155              *
03156              * XXX On Windows, we have to force pgwin32_recv to cooperate,
03157              * despite the previous use of pg_set_noblock() on the socket.
03158              * This is extremely broken and should be fixed someday.
03159              */
03160 #ifdef WIN32
03161             pgwin32_noblock = 1;
03162 #endif
03163 
03164             len = recv(pgStatSock, (char *) &msg,
03165                        sizeof(PgStat_Msg), 0);
03166 
03167 #ifdef WIN32
03168             pgwin32_noblock = 0;
03169 #endif
03170 
03171             if (len < 0)
03172             {
03173                 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
03174                     break;      /* out of inner loop */
03175                 ereport(ERROR,
03176                         (errcode_for_socket_access(),
03177                          errmsg("could not read statistics message: %m")));
03178             }
03179 
03180             /*
03181              * We ignore messages that are smaller than our common header
03182              */
03183             if (len < sizeof(PgStat_MsgHdr))
03184                 continue;
03185 
03186             /*
03187              * The received length must match the length in the header
03188              */
03189             if (msg.msg_hdr.m_size != len)
03190                 continue;
03191 
03192             /*
03193              * O.K. - we accept this message.  Process it.
03194              */
03195             switch (msg.msg_hdr.m_type)
03196             {
03197                 case PGSTAT_MTYPE_DUMMY:
03198                     break;
03199 
03200                 case PGSTAT_MTYPE_INQUIRY:
03201                     pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
03202                     break;
03203 
03204                 case PGSTAT_MTYPE_TABSTAT:
03205                     pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
03206                     break;
03207 
03208                 case PGSTAT_MTYPE_TABPURGE:
03209                     pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
03210                     break;
03211 
03212                 case PGSTAT_MTYPE_DROPDB:
03213                     pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
03214                     break;
03215 
03216                 case PGSTAT_MTYPE_RESETCOUNTER:
03217                     pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
03218                                              len);
03219                     break;
03220 
03221                 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
03222                     pgstat_recv_resetsharedcounter(
03223                                        (PgStat_MsgResetsharedcounter *) &msg,
03224                                                    len);
03225                     break;
03226 
03227                 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
03228                     pgstat_recv_resetsinglecounter(
03229                                        (PgStat_MsgResetsinglecounter *) &msg,
03230                                                    len);
03231                     break;
03232 
03233                 case PGSTAT_MTYPE_AUTOVAC_START:
03234                     pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
03235                     break;
03236 
03237                 case PGSTAT_MTYPE_VACUUM:
03238                     pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
03239                     break;
03240 
03241                 case PGSTAT_MTYPE_ANALYZE:
03242                     pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
03243                     break;
03244 
03245                 case PGSTAT_MTYPE_BGWRITER:
03246                     pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
03247                     break;
03248 
03249                 case PGSTAT_MTYPE_FUNCSTAT:
03250                     pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
03251                     break;
03252 
03253                 case PGSTAT_MTYPE_FUNCPURGE:
03254                     pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
03255                     break;
03256 
03257                 case PGSTAT_MTYPE_RECOVERYCONFLICT:
03258                     pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
03259                     break;
03260 
03261                 case PGSTAT_MTYPE_DEADLOCK:
03262                     pgstat_recv_deadlock((PgStat_MsgDeadlock *) &msg, len);
03263                     break;
03264 
03265                 case PGSTAT_MTYPE_TEMPFILE:
03266                     pgstat_recv_tempfile((PgStat_MsgTempFile *) &msg, len);
03267                     break;
03268 
03269                 default:
03270                     break;
03271             }
03272         }                       /* end of inner message-processing loop */
03273 
03274         /* Sleep until there's something to do */
03275 #ifndef WIN32
03276         wr = WaitLatchOrSocket(&pgStatLatch,
03277                      WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
03278                                pgStatSock,
03279                                -1L);
03280 #else
03281 
03282         /*
03283          * Windows, at least in its Windows Server 2003 R2 incarnation,
03284          * sometimes loses FD_READ events.  Waking up and retrying the recv()
03285          * fixes that, so don't sleep indefinitely.  This is a crock of the
03286          * first water, but until somebody wants to debug exactly what's
03287          * happening there, this is the best we can do.  The two-second
03288          * timeout matches our pre-9.2 behavior, and needs to be short enough
03289          * to not provoke "pgstat wait timeout" complaints from
03290          * backend_read_statsfile.
03291          */
03292         wr = WaitLatchOrSocket(&pgStatLatch,
03293         WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
03294                                pgStatSock,
03295                                2 * 1000L /* msec */ );
03296 #endif
03297 
03298         /*
03299          * Emergency bailout if postmaster has died.  This is to avoid the
03300          * necessity for manual cleanup of all postmaster children.
03301          */
03302         if (wr & WL_POSTMASTER_DEATH)
03303             break;
03304     }                           /* end of outer loop */
03305 
03306     /*
03307      * Save the final stats to reuse at next startup.
03308      */
03309     pgstat_write_statsfiles(true, true);
03310 
03311     exit(0);
03312 }
03313 
03314 
03315 /* SIGQUIT signal handler for collector process */
03316 static void
03317 pgstat_exit(SIGNAL_ARGS)
03318 {
03319     int         save_errno = errno;
03320 
03321     need_exit = true;
03322     SetLatch(&pgStatLatch);
03323 
03324     errno = save_errno;
03325 }
03326 
03327 /* SIGHUP handler for collector process */
03328 static void
03329 pgstat_sighup_handler(SIGNAL_ARGS)
03330 {
03331     int         save_errno = errno;
03332 
03333     got_SIGHUP = true;
03334     SetLatch(&pgStatLatch);
03335 
03336     errno = save_errno;
03337 }
03338 
03339 /*
03340  * Subroutine to clear stats in a database entry
03341  *
03342  * Tables and functions hashes are initialized to empty.
03343  */
03344 static void
03345 reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
03346 {
03347     HASHCTL     hash_ctl;
03348 
03349     dbentry->n_xact_commit = 0;
03350     dbentry->n_xact_rollback = 0;
03351     dbentry->n_blocks_fetched = 0;
03352     dbentry->n_blocks_hit = 0;
03353     dbentry->n_tuples_returned = 0;
03354     dbentry->n_tuples_fetched = 0;
03355     dbentry->n_tuples_inserted = 0;
03356     dbentry->n_tuples_updated = 0;
03357     dbentry->n_tuples_deleted = 0;
03358     dbentry->last_autovac_time = 0;
03359     dbentry->n_conflict_tablespace = 0;
03360     dbentry->n_conflict_lock = 0;
03361     dbentry->n_conflict_snapshot = 0;
03362     dbentry->n_conflict_bufferpin = 0;
03363     dbentry->n_conflict_startup_deadlock = 0;
03364     dbentry->n_temp_files = 0;
03365     dbentry->n_temp_bytes = 0;
03366     dbentry->n_deadlocks = 0;
03367     dbentry->n_block_read_time = 0;
03368     dbentry->n_block_write_time = 0;
03369 
03370     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
03371     dbentry->stats_timestamp = 0;
03372 
03373     memset(&hash_ctl, 0, sizeof(hash_ctl));
03374     hash_ctl.keysize = sizeof(Oid);
03375     hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
03376     hash_ctl.hash = oid_hash;
03377     dbentry->tables = hash_create("Per-database table",
03378                                   PGSTAT_TAB_HASH_SIZE,
03379                                   &hash_ctl,
03380                                   HASH_ELEM | HASH_FUNCTION);
03381 
03382     hash_ctl.keysize = sizeof(Oid);
03383     hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
03384     hash_ctl.hash = oid_hash;
03385     dbentry->functions = hash_create("Per-database function",
03386                                      PGSTAT_FUNCTION_HASH_SIZE,
03387                                      &hash_ctl,
03388                                      HASH_ELEM | HASH_FUNCTION);
03389 }
03390 
03391 /*
03392  * Lookup the hash table entry for the specified database. If no hash
03393  * table entry exists, initialize it, if the create parameter is true.
03394  * Else, return NULL.
03395  */
03396 static PgStat_StatDBEntry *
03397 pgstat_get_db_entry(Oid databaseid, bool create)
03398 {
03399     PgStat_StatDBEntry *result;
03400     bool        found;
03401     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
03402 
03403     /* Lookup or create the hash table entry for this database */
03404     result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
03405                                                 &databaseid,
03406                                                 action, &found);
03407 
03408     if (!create && !found)
03409         return NULL;
03410 
03411     /*
03412      * If not found, initialize the new one.  This creates empty hash tables
03413      * for tables and functions, too.
03414      */
03415     if (!found)
03416         reset_dbentry_counters(result);
03417 
03418     return result;
03419 }
03420 
03421 
03422 /*
03423  * Lookup the hash table entry for the specified table. If no hash
03424  * table entry exists, initialize it, if the create parameter is true.
03425  * Else, return NULL.
03426  */
03427 static PgStat_StatTabEntry *
03428 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
03429 {
03430     PgStat_StatTabEntry *result;
03431     bool        found;
03432     HASHACTION  action = (create ? HASH_ENTER : HASH_FIND);
03433 
03434     /* Lookup or create the hash table entry for this table */
03435     result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
03436                                                  &tableoid,
03437                                                  action, &found);
03438 
03439     if (!create && !found)
03440         return NULL;
03441 
03442     /* If not found, initialize the new one. */
03443     if (!found)
03444     {
03445         result->numscans = 0;
03446         result->tuples_returned = 0;
03447         result->tuples_fetched = 0;
03448         result->tuples_inserted = 0;
03449         result->tuples_updated = 0;
03450         result->tuples_deleted = 0;
03451         result->tuples_hot_updated = 0;
03452         result->n_live_tuples = 0;
03453         result->n_dead_tuples = 0;
03454         result->changes_since_analyze = 0;
03455         result->blocks_fetched = 0;
03456         result->blocks_hit = 0;
03457         result->vacuum_timestamp = 0;
03458         result->vacuum_count = 0;
03459         result->autovac_vacuum_timestamp = 0;
03460         result->autovac_vacuum_count = 0;
03461         result->analyze_timestamp = 0;
03462         result->analyze_count = 0;
03463         result->autovac_analyze_timestamp = 0;
03464         result->autovac_analyze_count = 0;
03465     }
03466 
03467     return result;
03468 }
03469 
03470 
03471 /* ----------
03472  * pgstat_write_statsfiles() -
03473  *      Write the global statistics file, as well as requested DB files.
03474  *
03475  *  If writing to the permanent files (happens when the collector is
03476  *  shutting down only), remove the temporary files so that backends
03477  *  starting up under a new postmaster can't read the old data before
03478  *  the new collector is ready.
03479  *
03480  *  When 'allDbs' is false, only the requested databases (listed in
03481  *  last_statrequests) will be written; otherwise, all databases will be
03482  *  written.
03483  * ----------
03484  */
03485 static void
03486 pgstat_write_statsfiles(bool permanent, bool allDbs)
03487 {
03488     HASH_SEQ_STATUS hstat;
03489     PgStat_StatDBEntry *dbentry;
03490     FILE       *fpout;
03491     int32       format_id;
03492     const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
03493     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
03494     int         rc;
03495 
03496     elog(DEBUG2, "writing statsfile '%s'", statfile);
03497 
03498     /*
03499      * Open the statistics temp file to write out the current values.
03500      */
03501     fpout = AllocateFile(tmpfile, PG_BINARY_W);
03502     if (fpout == NULL)
03503     {
03504         ereport(LOG,
03505                 (errcode_for_file_access(),
03506                  errmsg("could not open temporary statistics file \"%s\": %m",
03507                         tmpfile)));
03508         return;
03509     }
03510 
03511     /*
03512      * Set the timestamp of the stats file.
03513      */
03514     globalStats.stats_timestamp = GetCurrentTimestamp();
03515 
03516     /*
03517      * Write the file header --- currently just a format ID.
03518      */
03519     format_id = PGSTAT_FILE_FORMAT_ID;
03520     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
03521     (void) rc;                  /* we'll check for error with ferror */
03522 
03523     /*
03524      * Write global stats struct
03525      */
03526     rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
03527     (void) rc;                  /* we'll check for error with ferror */
03528 
03529     /*
03530      * Walk through the database table.
03531      */
03532     hash_seq_init(&hstat, pgStatDBHash);
03533     while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
03534     {
03535         /*
03536          * Write out the tables and functions into the DB stat file, if
03537          * required.
03538          *
03539          * We need to do this before the dbentry write, to ensure the
03540          * timestamps written to both are consistent.
03541          */
03542         if (allDbs || pgstat_db_requested(dbentry->databaseid))
03543         {
03544             dbentry->stats_timestamp = globalStats.stats_timestamp;
03545             pgstat_write_db_statsfile(dbentry, permanent);
03546         }
03547 
03548         /*
03549          * Write out the DB entry. We don't write the tables or functions
03550          * pointers, since they're of no use to any other process.
03551          */
03552         fputc('D', fpout);
03553         rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
03554         (void) rc;              /* we'll check for error with ferror */
03555     }
03556 
03557     /*
03558      * No more output to be done. Close the temp file and replace the old
03559      * pgstat.stat with it.  The ferror() check replaces testing for error
03560      * after each individual fputc or fwrite above.
03561      */
03562     fputc('E', fpout);
03563 
03564     if (ferror(fpout))
03565     {
03566         ereport(LOG,
03567                 (errcode_for_file_access(),
03568                errmsg("could not write temporary statistics file \"%s\": %m",
03569                       tmpfile)));
03570         FreeFile(fpout);
03571         unlink(tmpfile);
03572     }
03573     else if (FreeFile(fpout) < 0)
03574     {
03575         ereport(LOG,
03576                 (errcode_for_file_access(),
03577                errmsg("could not close temporary statistics file \"%s\": %m",
03578                       tmpfile)));
03579         unlink(tmpfile);
03580     }
03581     else if (rename(tmpfile, statfile) < 0)
03582     {
03583         ereport(LOG,
03584                 (errcode_for_file_access(),
03585                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
03586                         tmpfile, statfile)));
03587         unlink(tmpfile);
03588     }
03589 
03590     if (permanent)
03591         unlink(pgstat_stat_filename);
03592 
03593     /*
03594      * Now throw away the list of requests.  Note that requests sent after we
03595      * started the write are still waiting on the network socket.
03596      */
03597     if (!slist_is_empty(&last_statrequests))
03598     {
03599         slist_mutable_iter iter;
03600 
03601         slist_foreach_modify(iter, &last_statrequests)
03602         {
03603             DBWriteRequest *req;
03604 
03605             req = slist_container(DBWriteRequest, next, iter.cur);
03606             pfree(req);
03607         }
03608 
03609         slist_init(&last_statrequests);
03610     }
03611 }
03612 
03613 /*
03614  * return the filename for a DB stat file; filename is the output buffer,
03615  * of length len.
03616  */
03617 static void
03618 get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
03619                     char *filename, int len)
03620 {
03621     int         printed;
03622 
03623     printed = snprintf(filename, len, "%s/db_%u.%s",
03624                        permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
03625                        pgstat_stat_directory,
03626                        databaseid,
03627                        tempname ? "tmp" : "stat");
03628     if (printed > len)
03629         elog(ERROR, "overlength pgstat path");
03630 }
03631 
03632 /* ----------
03633  * pgstat_write_db_statsfile() -
03634  *      Write the stat file for a single database.
03635  *
03636  *  If writing to the permanent file (happens when the collector is
03637  *  shutting down only), remove the temporary file so that backends
03638  *  starting up under a new postmaster can't read the old data before
03639  *  the new collector is ready.
03640  * ----------
03641  */
03642 static void
03643 pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
03644 {
03645     HASH_SEQ_STATUS tstat;
03646     HASH_SEQ_STATUS fstat;
03647     PgStat_StatTabEntry *tabentry;
03648     PgStat_StatFuncEntry *funcentry;
03649     FILE       *fpout;
03650     int32       format_id;
03651     Oid         dbid = dbentry->databaseid;
03652     int         rc;
03653     char        tmpfile[MAXPGPATH];
03654     char        statfile[MAXPGPATH];
03655 
03656     get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
03657     get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
03658 
03659     elog(DEBUG2, "writing statsfile '%s'", statfile);
03660 
03661     /*
03662      * Open the statistics temp file to write out the current values.
03663      */
03664     fpout = AllocateFile(tmpfile, PG_BINARY_W);
03665     if (fpout == NULL)
03666     {
03667         ereport(LOG,
03668                 (errcode_for_file_access(),
03669                  errmsg("could not open temporary statistics file \"%s\": %m",
03670                         tmpfile)));
03671         return;
03672     }
03673 
03674     /*
03675      * Write the file header --- currently just a format ID.
03676      */
03677     format_id = PGSTAT_FILE_FORMAT_ID;
03678     rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
03679     (void) rc;                  /* we'll check for error with ferror */
03680 
03681     /*
03682      * Walk through the database's access stats per table.
03683      */
03684     hash_seq_init(&tstat, dbentry->tables);
03685     while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
03686     {
03687         fputc('T', fpout);
03688         rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
03689         (void) rc;              /* we'll check for error with ferror */
03690     }
03691 
03692     /*
03693      * Walk through the database's function stats table.
03694      */
03695     hash_seq_init(&fstat, dbentry->functions);
03696     while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
03697     {
03698         fputc('F', fpout);
03699         rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
03700         (void) rc;              /* we'll check for error with ferror */
03701     }
03702 
03703     /*
03704      * No more output to be done. Close the temp file and replace the old
03705      * pgstat.stat with it.  The ferror() check replaces testing for error
03706      * after each individual fputc or fwrite above.
03707      */
03708     fputc('E', fpout);
03709 
03710     if (ferror(fpout))
03711     {
03712         ereport(LOG,
03713                 (errcode_for_file_access(),
03714                errmsg("could not write temporary statistics file \"%s\": %m",
03715                       tmpfile)));
03716         FreeFile(fpout);
03717         unlink(tmpfile);
03718     }
03719     else if (FreeFile(fpout) < 0)
03720     {
03721         ereport(LOG,
03722                 (errcode_for_file_access(),
03723                errmsg("could not close temporary statistics file \"%s\": %m",
03724                       tmpfile)));
03725         unlink(tmpfile);
03726     }
03727     else if (rename(tmpfile, statfile) < 0)
03728     {
03729         ereport(LOG,
03730                 (errcode_for_file_access(),
03731                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
03732                         tmpfile, statfile)));
03733         unlink(tmpfile);
03734     }
03735 
03736     if (permanent)
03737     {
03738         get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
03739 
03740         elog(DEBUG2, "removing temporary stat file '%s'", statfile);
03741         unlink(statfile);
03742     }
03743 }
03744 
03745 /* ----------
03746  * pgstat_read_statsfiles() -
03747  *
03748  *  Reads in the existing statistics collector files and initializes the
03749  *  databases' hash table.  If the permanent file name is requested (which
03750  *  only happens in the stats collector itself), also remove the file after
03751  *  reading; the in-memory status is now authoritative, and the permanent file
03752  *  would be out of date in case somebody else reads it.
03753  *
03754  *  If a deep read is requested, table/function stats are read also, otherwise
03755  *  the table/function hash tables remain empty.
03756  * ----------
03757  */
03758 static HTAB *
03759 pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
03760 {
03761     PgStat_StatDBEntry *dbentry;
03762     PgStat_StatDBEntry dbbuf;
03763     HASHCTL     hash_ctl;
03764     HTAB       *dbhash;
03765     FILE       *fpin;
03766     int32       format_id;
03767     bool        found;
03768     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
03769 
03770     /*
03771      * The tables will live in pgStatLocalContext.
03772      */
03773     pgstat_setup_memcxt();
03774 
03775     /*
03776      * Create the DB hashtable
03777      */
03778     memset(&hash_ctl, 0, sizeof(hash_ctl));
03779     hash_ctl.keysize = sizeof(Oid);
03780     hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
03781     hash_ctl.hash = oid_hash;
03782     hash_ctl.hcxt = pgStatLocalContext;
03783     dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
03784                          HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
03785 
03786     /*
03787      * Clear out global statistics so they start from zero in case we can't
03788      * load an existing statsfile.
03789      */
03790     memset(&globalStats, 0, sizeof(globalStats));
03791 
03792     /*
03793      * Set the current timestamp (will be kept only in case we can't load an
03794      * existing statsfile).
03795      */
03796     globalStats.stat_reset_timestamp = GetCurrentTimestamp();
03797 
03798     /*
03799      * Try to open the stats file. If it doesn't exist, the backends simply
03800      * return zero for anything and the collector simply starts from scratch
03801      * with empty counters.
03802      *
03803      * ENOENT is a possibility if the stats collector is not running or has
03804      * not yet written the stats file the first time.  Any other failure
03805      * condition is suspicious.
03806      */
03807     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
03808     {
03809         if (errno != ENOENT)
03810             ereport(pgStatRunningInCollector ? LOG : WARNING,
03811                     (errcode_for_file_access(),
03812                      errmsg("could not open statistics file \"%s\": %m",
03813                             statfile)));
03814         return dbhash;
03815     }
03816 
03817     /*
03818      * Verify it's of the expected format.
03819      */
03820     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
03821         format_id != PGSTAT_FILE_FORMAT_ID)
03822     {
03823         ereport(pgStatRunningInCollector ? LOG : WARNING,
03824                 (errmsg("corrupted statistics file \"%s\"", statfile)));
03825         goto done;
03826     }
03827 
03828     /*
03829      * Read global stats struct
03830      */
03831     if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
03832     {
03833         ereport(pgStatRunningInCollector ? LOG : WARNING,
03834                 (errmsg("corrupted statistics file \"%s\"", statfile)));
03835         goto done;
03836     }
03837 
03838     /*
03839      * We found an existing collector stats file. Read it and put all the
03840      * hashtable entries into place.
03841      */
03842     for (;;)
03843     {
03844         switch (fgetc(fpin))
03845         {
03846                 /*
03847                  * 'D'  A PgStat_StatDBEntry struct describing a database
03848                  * follows.
03849                  */
03850             case 'D':
03851                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
03852                           fpin) != offsetof(PgStat_StatDBEntry, tables))
03853                 {
03854                     ereport(pgStatRunningInCollector ? LOG : WARNING,
03855                             (errmsg("corrupted statistics file \"%s\"",
03856                                     statfile)));
03857                     goto done;
03858                 }
03859 
03860                 /*
03861                  * Add to the DB hash
03862                  */
03863                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
03864                                                   (void *) &dbbuf.databaseid,
03865                                                              HASH_ENTER,
03866                                                              &found);
03867                 if (found)
03868                 {
03869                     ereport(pgStatRunningInCollector ? LOG : WARNING,
03870                             (errmsg("corrupted statistics file \"%s\"",
03871                                     statfile)));
03872                     goto done;
03873                 }
03874 
03875                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
03876                 dbentry->tables = NULL;
03877                 dbentry->functions = NULL;
03878 
03879                 /*
03880                  * Don't collect tables if not the requested DB (or the
03881                  * shared-table info)
03882                  */
03883                 if (onlydb != InvalidOid)
03884                 {
03885                     if (dbbuf.databaseid != onlydb &&
03886                         dbbuf.databaseid != InvalidOid)
03887                         break;
03888                 }
03889 
03890                 memset(&hash_ctl, 0, sizeof(hash_ctl));
03891                 hash_ctl.keysize = sizeof(Oid);
03892                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
03893                 hash_ctl.hash = oid_hash;
03894                 hash_ctl.hcxt = pgStatLocalContext;
03895                 dbentry->tables = hash_create("Per-database table",
03896                                               PGSTAT_TAB_HASH_SIZE,
03897                                               &hash_ctl,
03898                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
03899 
03900                 hash_ctl.keysize = sizeof(Oid);
03901                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
03902                 hash_ctl.hash = oid_hash;
03903                 hash_ctl.hcxt = pgStatLocalContext;
03904                 dbentry->functions = hash_create("Per-database function",
03905                                                  PGSTAT_FUNCTION_HASH_SIZE,
03906                                                  &hash_ctl,
03907                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
03908 
03909                 /*
03910                  * If requested, read the data from the database-specific
03911                  * file. If there was onlydb specified (!= InvalidOid), we
03912                  * would not get here because of a break above. So we don't
03913                  * need to recheck.
03914                  */
03915                 if (deep)
03916                     pgstat_read_db_statsfile(dbentry->databaseid,
03917                                              dbentry->tables,
03918                                              dbentry->functions,
03919                                              permanent);
03920 
03921                 break;
03922 
03923             case 'E':
03924                 goto done;
03925 
03926             default:
03927                 ereport(pgStatRunningInCollector ? LOG : WARNING,
03928                         (errmsg("corrupted statistics file \"%s\"",
03929                                 statfile)));
03930                 goto done;
03931         }
03932     }
03933 
03934 done:
03935     FreeFile(fpin);
03936 
03937     /* If requested to read the permanent file, also get rid of it. */
03938     if (permanent)
03939     {
03940         elog(DEBUG2, "removing permanent stats file '%s'", statfile);
03941         unlink(statfile);
03942     }
03943 
03944     return dbhash;
03945 }
03946 
03947 
03948 /* ----------
03949  * pgstat_read_db_statsfile() -
03950  *
03951  *  Reads in the existing statistics collector file for the given database,
03952  *  and initializes the tables and functions hash tables.
03953  *
03954  *  As pgstat_read_statsfiles, if the permanent file is requested, it is
03955  *  removed after reading.
03956  * ----------
03957  */
03958 static void
03959 pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
03960                          bool permanent)
03961 {
03962     PgStat_StatTabEntry *tabentry;
03963     PgStat_StatTabEntry tabbuf;
03964     PgStat_StatFuncEntry funcbuf;
03965     PgStat_StatFuncEntry *funcentry;
03966     FILE       *fpin;
03967     int32       format_id;
03968     bool        found;
03969     char        statfile[MAXPGPATH];
03970 
03971     get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
03972 
03973     /*
03974      * Try to open the stats file. If it doesn't exist, the backends simply
03975      * return zero for anything and the collector simply starts from scratch
03976      * with empty counters.
03977      *
03978      * ENOENT is a possibility if the stats collector is not running or has
03979      * not yet written the stats file the first time.  Any other failure
03980      * condition is suspicious.
03981      */
03982     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
03983     {
03984         if (errno != ENOENT)
03985             ereport(pgStatRunningInCollector ? LOG : WARNING,
03986                     (errcode_for_file_access(),
03987                      errmsg("could not open statistics file \"%s\": %m",
03988                             statfile)));
03989         return;
03990     }
03991 
03992     /*
03993      * Verify it's of the expected format.
03994      */
03995     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
03996         format_id != PGSTAT_FILE_FORMAT_ID)
03997     {
03998         ereport(pgStatRunningInCollector ? LOG : WARNING,
03999                 (errmsg("corrupted statistics file \"%s\"", statfile)));
04000         goto done;
04001     }
04002 
04003     /*
04004      * We found an existing collector stats file. Read it and put all the
04005      * hashtable entries into place.
04006      */
04007     for (;;)
04008     {
04009         switch (fgetc(fpin))
04010         {
04011                 /*
04012                  * 'T'  A PgStat_StatTabEntry follows.
04013                  */
04014             case 'T':
04015                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
04016                           fpin) != sizeof(PgStat_StatTabEntry))
04017                 {
04018                     ereport(pgStatRunningInCollector ? LOG : WARNING,
04019                             (errmsg("corrupted statistics file \"%s\"",
04020                                     statfile)));
04021                     goto done;
04022                 }
04023 
04024                 /*
04025                  * Skip if table belongs to a not requested database.
04026                  */
04027                 if (tabhash == NULL)
04028                     break;
04029 
04030                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
04031                                                     (void *) &tabbuf.tableid,
04032                                                          HASH_ENTER, &found);
04033 
04034                 if (found)
04035                 {
04036                     ereport(pgStatRunningInCollector ? LOG : WARNING,
04037                             (errmsg("corrupted statistics file \"%s\"",
04038                                     statfile)));
04039                     goto done;
04040                 }
04041 
04042                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
04043                 break;
04044 
04045                 /*
04046                  * 'F'  A PgStat_StatFuncEntry follows.
04047                  */
04048             case 'F':
04049                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
04050                           fpin) != sizeof(PgStat_StatFuncEntry))
04051                 {
04052                     ereport(pgStatRunningInCollector ? LOG : WARNING,
04053                             (errmsg("corrupted statistics file \"%s\"",
04054                                     statfile)));
04055                     goto done;
04056                 }
04057 
04058                 /*
04059                  * Skip if function belongs to a not requested database.
04060                  */
04061                 if (funchash == NULL)
04062                     break;
04063 
04064                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
04065                                                 (void *) &funcbuf.functionid,
04066                                                          HASH_ENTER, &found);
04067 
04068                 if (found)
04069                 {
04070                     ereport(pgStatRunningInCollector ? LOG : WARNING,
04071                             (errmsg("corrupted statistics file \"%s\"",
04072                                     statfile)));
04073                     goto done;
04074                 }
04075 
04076                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
04077                 break;
04078 
04079                 /*
04080                  * 'E'  The EOF marker of a complete stats file.
04081                  */
04082             case 'E':
04083                 goto done;
04084 
04085             default:
04086                 ereport(pgStatRunningInCollector ? LOG : WARNING,
04087                         (errmsg("corrupted statistics file \"%s\"",
04088                                 statfile)));
04089                 goto done;
04090         }
04091     }
04092 
04093 done:
04094     FreeFile(fpin);
04095 
04096     if (permanent)
04097     {
04098         elog(DEBUG2, "removing permanent stats file '%s'", statfile);
04099         unlink(statfile);
04100     }
04101 
04102     return;
04103 }
04104 
04105 /* ----------
04106  * pgstat_read_db_statsfile_timestamp() -
04107  *
04108  *  Attempt to determine the timestamp of the last db statfile write.
04109  *  Returns TRUE if successful; the timestamp is stored in *ts.
04110  *
04111  *  This needs to be careful about handling databases for which no stats file
04112  *  exists, such as databases without a stat entry or those not yet written:
04113  *
04114  *  - if there's a database entry in the global file, return the corresponding
04115  *  stats_timestamp value.
04116  *
04117  *  - if there's no db stat entry (e.g. for a new or inactive database),
04118  *  there's no stat_timestamp value, but also nothing to write so we return
04119  *  the timestamp of the global statfile.
04120  * ----------
04121  */
04122 static bool
04123 pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
04124                                    TimestampTz *ts)
04125 {
04126     PgStat_StatDBEntry dbentry;
04127     PgStat_GlobalStats myGlobalStats;
04128     FILE       *fpin;
04129     int32       format_id;
04130     const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
04131 
04132     /*
04133      * Try to open the stats file.  As above, anything but ENOENT is worthy of
04134      * complaining about.
04135      */
04136     if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
04137     {
04138         if (errno != ENOENT)
04139             ereport(pgStatRunningInCollector ? LOG : WARNING,
04140                     (errcode_for_file_access(),
04141                      errmsg("could not open statistics file \"%s\": %m",
04142                             statfile)));
04143         return false;
04144     }
04145 
04146     /*
04147      * Verify it's of the expected format.
04148      */
04149     if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
04150         format_id != PGSTAT_FILE_FORMAT_ID)
04151     {
04152         ereport(pgStatRunningInCollector ? LOG : WARNING,
04153                 (errmsg("corrupted statistics file \"%s\"", statfile)));
04154         FreeFile(fpin);
04155         return false;
04156     }
04157 
04158     /*
04159      * Read global stats struct
04160      */
04161     if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
04162               fpin) != sizeof(myGlobalStats))
04163     {
04164         ereport(pgStatRunningInCollector ? LOG : WARNING,
04165                 (errmsg("corrupted statistics file \"%s\"", statfile)));
04166         FreeFile(fpin);
04167         return false;
04168     }
04169 
04170     /* By default, we're going to return the timestamp of the global file. */
04171     *ts = myGlobalStats.stats_timestamp;
04172 
04173     /*
04174      * We found an existing collector stats file.  Read it and look for a
04175      * record for the requested database.  If found, use its timestamp.
04176      */
04177     for (;;)
04178     {
04179         switch (fgetc(fpin))
04180         {
04181                 /*
04182                  * 'D'  A PgStat_StatDBEntry struct describing a database
04183                  * follows.
04184                  */
04185             case 'D':
04186                 if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
04187                           fpin) != offsetof(PgStat_StatDBEntry, tables))
04188                 {
04189                     ereport(pgStatRunningInCollector ? LOG : WARNING,
04190                             (errmsg("corrupted statistics file \"%s\"",
04191                                     statfile)));
04192                     goto done;
04193                 }
04194 
04195                 /*
04196                  * If this is the DB we're looking for, save its timestamp and
04197                  * we're done.
04198                  */
04199                 if (dbentry.databaseid == databaseid)
04200                 {
04201                     *ts = dbentry.stats_timestamp;
04202                     goto done;
04203                 }
04204 
04205                 break;
04206 
04207             case 'E':
04208                 goto done;
04209 
04210             default:
04211                 ereport(pgStatRunningInCollector ? LOG : WARNING,
04212                         (errmsg("corrupted statistics file \"%s\"",
04213                                 statfile)));
04214                 goto done;
04215         }
04216     }
04217 
04218 done:
04219     FreeFile(fpin);
04220     return true;
04221 }
04222 
04223 /*
04224  * If not already done, read the statistics collector stats file into
04225  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
04226  * is called (typically, at end of transaction).
04227  */
04228 static void
04229 backend_read_statsfile(void)
04230 {
04231     TimestampTz min_ts = 0;
04232     TimestampTz ref_ts = 0;
04233     int         count;
04234 
04235     /* already read it? */
04236     if (pgStatDBHash)
04237         return;
04238     Assert(!pgStatRunningInCollector);
04239 
04240     /*
04241      * Loop until fresh enough stats file is available or we ran out of time.
04242      * The stats inquiry message is sent repeatedly in case collector drops
04243      * it; but not every single time, as that just swamps the collector.
04244      */
04245     for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
04246     {
04247         bool        ok;
04248         TimestampTz file_ts = 0;
04249         TimestampTz cur_ts;
04250 
04251         CHECK_FOR_INTERRUPTS();
04252 
04253         ok = pgstat_read_db_statsfile_timestamp(MyDatabaseId, false, &file_ts);
04254 
04255         cur_ts = GetCurrentTimestamp();
04256         /* Calculate min acceptable timestamp, if we didn't already */
04257         if (count == 0 || cur_ts < ref_ts)
04258         {
04259             /*
04260              * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
04261              * msec before now.  This indirectly ensures that the collector
04262              * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
04263              * an autovacuum worker, however, we want a lower delay to avoid
04264              * using stale data, so we use PGSTAT_RETRY_DELAY (since the
04265              * number of workers is low, this shouldn't be a problem).
04266              *
04267              * We don't recompute min_ts after sleeping, except in the
04268              * unlikely case that cur_ts went backwards.  So we might end up
04269              * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In
04270              * practice that shouldn't happen, though, as long as the sleep
04271              * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
04272              * tell the collector that our cutoff time is less than what we'd
04273              * actually accept.
04274              */
04275             ref_ts = cur_ts;
04276             if (IsAutoVacuumWorkerProcess())
04277                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
04278                                                      -PGSTAT_RETRY_DELAY);
04279             else
04280                 min_ts = TimestampTzPlusMilliseconds(ref_ts,
04281                                                      -PGSTAT_STAT_INTERVAL);
04282         }
04283 
04284         /*
04285          * If the file timestamp is actually newer than cur_ts, we must have
04286          * had a clock glitch (system time went backwards) or there is clock
04287          * skew between our processor and the stats collector's processor.
04288          * Accept the file, but send an inquiry message anyway to make
04289          * pgstat_recv_inquiry do a sanity check on the collector's time.
04290          */
04291         if (ok && file_ts > cur_ts)
04292         {
04293             /*
04294              * A small amount of clock skew between processors isn't terribly
04295              * surprising, but a large difference is worth logging.  We
04296              * arbitrarily define "large" as 1000 msec.
04297              */
04298             if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
04299             {
04300                 char       *filetime;
04301                 char       *mytime;
04302 
04303                 /* Copy because timestamptz_to_str returns a static buffer */
04304                 filetime = pstrdup(timestamptz_to_str(file_ts));
04305                 mytime = pstrdup(timestamptz_to_str(cur_ts));
04306                 elog(LOG, "stats collector's time %s is later than backend local time %s",
04307                      filetime, mytime);
04308                 pfree(filetime);
04309                 pfree(mytime);
04310             }
04311 
04312             pgstat_send_inquiry(cur_ts, min_ts, MyDatabaseId);
04313             break;
04314         }
04315 
04316         /* Normal acceptance case: file is not older than cutoff time */
04317         if (ok && file_ts >= min_ts)
04318             break;
04319 
04320         /* Not there or too old, so kick the collector and wait a bit */
04321         if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
04322             pgstat_send_inquiry(cur_ts, min_ts, MyDatabaseId);
04323 
04324         pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
04325     }
04326 
04327     if (count >= PGSTAT_POLL_LOOP_COUNT)
04328         elog(WARNING, "pgstat wait timeout");
04329 
04330     /*
04331      * Autovacuum launcher wants stats about all databases, but a shallow read
04332      * is sufficient.
04333      */
04334     if (IsAutoVacuumLauncherProcess())
04335         pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
04336     else
04337         pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
04338 }
04339 
04340 
04341 /* ----------
04342  * pgstat_setup_memcxt() -
04343  *
04344  *  Create pgStatLocalContext, if not already done.
04345  * ----------
04346  */
04347 static void
04348 pgstat_setup_memcxt(void)
04349 {
04350     if (!pgStatLocalContext)
04351         pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
04352                                                    "Statistics snapshot",
04353                                                    ALLOCSET_SMALL_MINSIZE,
04354                                                    ALLOCSET_SMALL_INITSIZE,
04355                                                    ALLOCSET_SMALL_MAXSIZE);
04356 }
04357 
04358 
04359 /* ----------
04360  * pgstat_clear_snapshot() -
04361  *
04362  *  Discard any data collected in the current transaction.  Any subsequent
04363  *  request will cause new snapshots to be read.
04364  *
04365  *  This is also invoked during transaction commit or abort to discard
04366  *  the no-longer-wanted snapshot.
04367  * ----------
04368  */
04369 void
04370 pgstat_clear_snapshot(void)
04371 {
04372     /* Release memory, if any was allocated */
04373     if (pgStatLocalContext)
04374         MemoryContextDelete(pgStatLocalContext);
04375 
04376     /* Reset variables */
04377     pgStatLocalContext = NULL;
04378     pgStatDBHash = NULL;
04379     localBackendStatusTable = NULL;
04380     localNumBackends = 0;
04381 }
04382 
04383 
04384 /* ----------
04385  * pgstat_recv_inquiry() -
04386  *
04387  *  Process stat inquiry requests.
04388  * ----------
04389  */
04390 static void
04391 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
04392 {
04393     slist_iter  iter;
04394     DBWriteRequest *newreq;
04395     PgStat_StatDBEntry *dbentry;
04396 
04397     elog(DEBUG2, "received inquiry for %d", msg->databaseid);
04398 
04399     /*
04400      * Find the last write request for this DB.  If it's older than the
04401      * request's cutoff time, update it; otherwise there's nothing to do.
04402      *
04403      * Note that if a request is found, we return early and skip the below
04404      * check for clock skew.  This is okay, since the only way for a DB request
04405      * to be present in the list is that we have been here since the last write
04406      * round.
04407      */
04408     slist_foreach(iter, &last_statrequests)
04409     {
04410         DBWriteRequest *req = slist_container(DBWriteRequest, next, iter.cur);
04411 
04412         if (req->databaseid != msg->databaseid)
04413             continue;
04414 
04415         if (msg->cutoff_time > req->request_time)
04416             req->request_time = msg->cutoff_time;
04417         return;
04418     }
04419 
04420     /*
04421      * There's no request for this DB yet, so create one.
04422      */
04423     newreq = palloc(sizeof(DBWriteRequest));
04424 
04425     newreq->databaseid = msg->databaseid;
04426     newreq->request_time = msg->clock_time;
04427     slist_push_head(&last_statrequests, &newreq->next);
04428 
04429     /*
04430      * If the requestor's local clock time is older than stats_timestamp, we
04431      * should suspect a clock glitch, ie system time going backwards; though
04432      * the more likely explanation is just delayed message receipt.  It is
04433      * worth expending a GetCurrentTimestamp call to be sure, since a large
04434      * retreat in the system clock reading could otherwise cause us to neglect
04435      * to update the stats file for a long time.
04436      */
04437     dbentry = pgstat_get_db_entry(msg->databaseid, false);
04438     if ((dbentry != NULL) && (msg->clock_time < dbentry->stats_timestamp))
04439     {
04440         TimestampTz cur_ts = GetCurrentTimestamp();
04441 
04442         if (cur_ts < dbentry->stats_timestamp)
04443         {
04444             /*
04445              * Sure enough, time went backwards.  Force a new stats file write
04446              * to get back in sync; but first, log a complaint.
04447              */
04448             char       *writetime;
04449             char       *mytime;
04450 
04451             /* Copy because timestamptz_to_str returns a static buffer */
04452             writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
04453             mytime = pstrdup(timestamptz_to_str(cur_ts));
04454             elog(LOG,
04455             "stats_timestamp %s is later than collector's time %s for db %d",
04456                  writetime, mytime, dbentry->databaseid);
04457             pfree(writetime);
04458             pfree(mytime);
04459 
04460             newreq->request_time = cur_ts;
04461             dbentry->stats_timestamp = cur_ts - 1;
04462         }
04463     }
04464 }
04465 
04466 
04467 /* ----------
04468  * pgstat_recv_tabstat() -
04469  *
04470  *  Count what the backend has done.
04471  * ----------
04472  */
04473 static void
04474 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
04475 {
04476     PgStat_StatDBEntry *dbentry;
04477     PgStat_StatTabEntry *tabentry;
04478     int         i;
04479     bool        found;
04480 
04481     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04482 
04483     /*
04484      * Update database-wide stats.
04485      */
04486     dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
04487     dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
04488     dbentry->n_block_read_time += msg->m_block_read_time;
04489     dbentry->n_block_write_time += msg->m_block_write_time;
04490 
04491     /*
04492      * Process all table entries in the message.
04493      */
04494     for (i = 0; i < msg->m_nentries; i++)
04495     {
04496         PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
04497 
04498         tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
04499                                                     (void *) &(tabmsg->t_id),
04500                                                        HASH_ENTER, &found);
04501 
04502         if (!found)
04503         {
04504             /*
04505              * If it's a new table entry, initialize counters to the values we
04506              * just got.
04507              */
04508             tabentry->numscans = tabmsg->t_counts.t_numscans;
04509             tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
04510             tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
04511             tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
04512             tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
04513             tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
04514             tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
04515             tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
04516             tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
04517             tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
04518             tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
04519             tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
04520 
04521             tabentry->vacuum_timestamp = 0;
04522             tabentry->vacuum_count = 0;
04523             tabentry->autovac_vacuum_timestamp = 0;
04524             tabentry->autovac_vacuum_count = 0;
04525             tabentry->analyze_timestamp = 0;
04526             tabentry->analyze_count = 0;
04527             tabentry->autovac_analyze_timestamp = 0;
04528             tabentry->autovac_analyze_count = 0;
04529         }
04530         else
04531         {
04532             /*
04533              * Otherwise add the values to the existing entry.
04534              */
04535             tabentry->numscans += tabmsg->t_counts.t_numscans;
04536             tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
04537             tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
04538             tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
04539             tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
04540             tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
04541             tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
04542             tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
04543             tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
04544             tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
04545             tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
04546             tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
04547         }
04548 
04549         /* Clamp n_live_tuples in case of negative delta_live_tuples */
04550         tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
04551         /* Likewise for n_dead_tuples */
04552         tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
04553 
04554         /*
04555          * Add per-table stats to the per-database entry, too.
04556          */
04557         dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
04558         dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
04559         dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
04560         dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
04561         dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
04562         dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
04563         dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
04564     }
04565 }
04566 
04567 
04568 /* ----------
04569  * pgstat_recv_tabpurge() -
04570  *
04571  *  Arrange for dead table removal.
04572  * ----------
04573  */
04574 static void
04575 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
04576 {
04577     PgStat_StatDBEntry *dbentry;
04578     int         i;
04579 
04580     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
04581 
04582     /*
04583      * No need to purge if we don't even know the database.
04584      */
04585     if (!dbentry || !dbentry->tables)
04586         return;
04587 
04588     /*
04589      * Process all table entries in the message.
04590      */
04591     for (i = 0; i < msg->m_nentries; i++)
04592     {
04593         /* Remove from hashtable if present; we don't care if it's not. */
04594         (void) hash_search(dbentry->tables,
04595                            (void *) &(msg->m_tableid[i]),
04596                            HASH_REMOVE, NULL);
04597     }
04598 }
04599 
04600 
04601 /* ----------
04602  * pgstat_recv_dropdb() -
04603  *
04604  *  Arrange for dead database removal
04605  * ----------
04606  */
04607 static void
04608 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
04609 {
04610     Oid         dbid = msg->m_databaseid;
04611     PgStat_StatDBEntry *dbentry;
04612 
04613     /*
04614      * Lookup the database in the hashtable.
04615      */
04616     dbentry = pgstat_get_db_entry(dbid, false);
04617 
04618     /*
04619      * If found, remove it (along with the db statfile).
04620      */
04621     if (dbentry)
04622     {
04623         char        statfile[MAXPGPATH];
04624 
04625         get_dbstat_filename(true, false, dbid, statfile, MAXPGPATH);
04626 
04627         elog(DEBUG2, "removing %s", statfile);
04628         unlink(statfile);
04629 
04630         if (dbentry->tables != NULL)
04631             hash_destroy(dbentry->tables);
04632         if (dbentry->functions != NULL)
04633             hash_destroy(dbentry->functions);
04634 
04635         if (hash_search(pgStatDBHash,
04636                         (void *) &dbid,
04637                         HASH_REMOVE, NULL) == NULL)
04638             ereport(ERROR,
04639                     (errmsg("database hash table corrupted during cleanup --- abort")));
04640     }
04641 }
04642 
04643 
04644 /* ----------
04645  * pgstat_recv_resetcounter() -
04646  *
04647  *  Reset the statistics for the specified database.
04648  * ----------
04649  */
04650 static void
04651 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
04652 {
04653     PgStat_StatDBEntry *dbentry;
04654 
04655     /*
04656      * Lookup the database in the hashtable.  Nothing to do if not there.
04657      */
04658     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
04659 
04660     if (!dbentry)
04661         return;
04662 
04663     /*
04664      * We simply throw away all the database's table entries by recreating a
04665      * new hash table for them.
04666      */
04667     if (dbentry->tables != NULL)
04668         hash_destroy(dbentry->tables);
04669     if (dbentry->functions != NULL)
04670         hash_destroy(dbentry->functions);
04671 
04672     dbentry->tables = NULL;
04673     dbentry->functions = NULL;
04674 
04675     /*
04676      * Reset database-level stats, too.  This creates empty hash tables for
04677      * tables and functions.
04678      */
04679     reset_dbentry_counters(dbentry);
04680 }
04681 
04682 /* ----------
04683  * pgstat_recv_resetshared() -
04684  *
04685  *  Reset some shared statistics of the cluster.
04686  * ----------
04687  */
04688 static void
04689 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
04690 {
04691     if (msg->m_resettarget == RESET_BGWRITER)
04692     {
04693         /* Reset the global background writer statistics for the cluster. */
04694         memset(&globalStats, 0, sizeof(globalStats));
04695         globalStats.stat_reset_timestamp = GetCurrentTimestamp();
04696     }
04697 
04698     /*
04699      * Presumably the sender of this message validated the target, don't
04700      * complain here if it's not valid
04701      */
04702 }
04703 
04704 /* ----------
04705  * pgstat_recv_resetsinglecounter() -
04706  *
04707  *  Reset a statistics for a single object
04708  * ----------
04709  */
04710 static void
04711 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
04712 {
04713     PgStat_StatDBEntry *dbentry;
04714 
04715     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
04716 
04717     if (!dbentry)
04718         return;
04719 
04720     /* Set the reset timestamp for the whole database */
04721     dbentry->stat_reset_timestamp = GetCurrentTimestamp();
04722 
04723     /* Remove object if it exists, ignore it if not */
04724     if (msg->m_resettype == RESET_TABLE)
04725         (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
04726                            HASH_REMOVE, NULL);
04727     else if (msg->m_resettype == RESET_FUNCTION)
04728         (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
04729                            HASH_REMOVE, NULL);
04730 }
04731 
04732 /* ----------
04733  * pgstat_recv_autovac() -
04734  *
04735  *  Process an autovacuum signalling message.
04736  * ----------
04737  */
04738 static void
04739 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
04740 {
04741     PgStat_StatDBEntry *dbentry;
04742 
04743     /*
04744      * Store the last autovacuum time in the database's hashtable entry.
04745      */
04746     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04747 
04748     dbentry->last_autovac_time = msg->m_start_time;
04749 }
04750 
04751 /* ----------
04752  * pgstat_recv_vacuum() -
04753  *
04754  *  Process a VACUUM message.
04755  * ----------
04756  */
04757 static void
04758 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
04759 {
04760     PgStat_StatDBEntry *dbentry;
04761     PgStat_StatTabEntry *tabentry;
04762 
04763     /*
04764      * Store the data in the table's hashtable entry.
04765      */
04766     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04767 
04768     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
04769 
04770     tabentry->n_live_tuples = msg->m_tuples;
04771     /* Resetting dead_tuples to 0 is an approximation ... */
04772     tabentry->n_dead_tuples = 0;
04773 
04774     if (msg->m_autovacuum)
04775     {
04776         tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
04777         tabentry->autovac_vacuum_count++;
04778     }
04779     else
04780     {
04781         tabentry->vacuum_timestamp = msg->m_vacuumtime;
04782         tabentry->vacuum_count++;
04783     }
04784 }
04785 
04786 /* ----------
04787  * pgstat_recv_analyze() -
04788  *
04789  *  Process an ANALYZE message.
04790  * ----------
04791  */
04792 static void
04793 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
04794 {
04795     PgStat_StatDBEntry *dbentry;
04796     PgStat_StatTabEntry *tabentry;
04797 
04798     /*
04799      * Store the data in the table's hashtable entry.
04800      */
04801     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04802 
04803     tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
04804 
04805     tabentry->n_live_tuples = msg->m_live_tuples;
04806     tabentry->n_dead_tuples = msg->m_dead_tuples;
04807 
04808     /*
04809      * We reset changes_since_analyze to zero, forgetting any changes that
04810      * occurred while the ANALYZE was in progress.
04811      */
04812     tabentry->changes_since_analyze = 0;
04813 
04814     if (msg->m_autovacuum)
04815     {
04816         tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
04817         tabentry->autovac_analyze_count++;
04818     }
04819     else
04820     {
04821         tabentry->analyze_timestamp = msg->m_analyzetime;
04822         tabentry->analyze_count++;
04823     }
04824 }
04825 
04826 
04827 /* ----------
04828  * pgstat_recv_bgwriter() -
04829  *
04830  *  Process a BGWRITER message.
04831  * ----------
04832  */
04833 static void
04834 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
04835 {
04836     globalStats.timed_checkpoints += msg->m_timed_checkpoints;
04837     globalStats.requested_checkpoints += msg->m_requested_checkpoints;
04838     globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
04839     globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
04840     globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
04841     globalStats.buf_written_clean += msg->m_buf_written_clean;
04842     globalStats.maxwritten_clean += msg->m_maxwritten_clean;
04843     globalStats.buf_written_backend += msg->m_buf_written_backend;
04844     globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
04845     globalStats.buf_alloc += msg->m_buf_alloc;
04846 }
04847 
04848 /* ----------
04849  * pgstat_recv_recoveryconflict() -
04850  *
04851  *  Process a RECOVERYCONFLICT message.
04852  * ----------
04853  */
04854 static void
04855 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
04856 {
04857     PgStat_StatDBEntry *dbentry;
04858 
04859     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04860 
04861     switch (msg->m_reason)
04862     {
04863         case PROCSIG_RECOVERY_CONFLICT_DATABASE:
04864 
04865             /*
04866              * Since we drop the information about the database as soon as it
04867              * replicates, there is no point in counting these conflicts.
04868              */
04869             break;
04870         case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
04871             dbentry->n_conflict_tablespace++;
04872             break;
04873         case PROCSIG_RECOVERY_CONFLICT_LOCK:
04874             dbentry->n_conflict_lock++;
04875             break;
04876         case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
04877             dbentry->n_conflict_snapshot++;
04878             break;
04879         case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
04880             dbentry->n_conflict_bufferpin++;
04881             break;
04882         case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
04883             dbentry->n_conflict_startup_deadlock++;
04884             break;
04885     }
04886 }
04887 
04888 /* ----------
04889  * pgstat_recv_deadlock() -
04890  *
04891  *  Process a DEADLOCK message.
04892  * ----------
04893  */
04894 static void
04895 pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
04896 {
04897     PgStat_StatDBEntry *dbentry;
04898 
04899     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04900 
04901     dbentry->n_deadlocks++;
04902 }
04903 
04904 /* ----------
04905  * pgstat_recv_tempfile() -
04906  *
04907  *  Process a TEMPFILE message.
04908  * ----------
04909  */
04910 static void
04911 pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
04912 {
04913     PgStat_StatDBEntry *dbentry;
04914 
04915     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04916 
04917     dbentry->n_temp_bytes += msg->m_filesize;
04918     dbentry->n_temp_files += 1;
04919 }
04920 
04921 /* ----------
04922  * pgstat_recv_funcstat() -
04923  *
04924  *  Count what the backend has done.
04925  * ----------
04926  */
04927 static void
04928 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
04929 {
04930     PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
04931     PgStat_StatDBEntry *dbentry;
04932     PgStat_StatFuncEntry *funcentry;
04933     int         i;
04934     bool        found;
04935 
04936     dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
04937 
04938     /*
04939      * Process all function entries in the message.
04940      */
04941     for (i = 0; i < msg->m_nentries; i++, funcmsg++)
04942     {
04943         funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
04944                                                    (void *) &(funcmsg->f_id),
04945                                                          HASH_ENTER, &found);
04946 
04947         if (!found)
04948         {
04949             /*
04950              * If it's a new function entry, initialize counters to the values
04951              * we just got.
04952              */
04953             funcentry->f_numcalls = funcmsg->f_numcalls;
04954             funcentry->f_total_time = funcmsg->f_total_time;
04955             funcentry->f_self_time = funcmsg->f_self_time;
04956         }
04957         else
04958         {
04959             /*
04960              * Otherwise add the values to the existing entry.
04961              */
04962             funcentry->f_numcalls += funcmsg->f_numcalls;
04963             funcentry->f_total_time += funcmsg->f_total_time;
04964             funcentry->f_self_time += funcmsg->f_self_time;
04965         }
04966     }
04967 }
04968 
04969 /* ----------
04970  * pgstat_recv_funcpurge() -
04971  *
04972  *  Arrange for dead function removal.
04973  * ----------
04974  */
04975 static void
04976 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
04977 {
04978     PgStat_StatDBEntry *dbentry;
04979     int         i;
04980 
04981     dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
04982 
04983     /*
04984      * No need to purge if we don't even know the database.
04985      */
04986     if (!dbentry || !dbentry->functions)
04987         return;
04988 
04989     /*
04990      * Process all function entries in the message.
04991      */
04992     for (i = 0; i < msg->m_nentries; i++)
04993     {
04994         /* Remove from hashtable if present; we don't care if it's not. */
04995         (void) hash_search(dbentry->functions,
04996                            (void *) &(msg->m_functionid[i]),
04997                            HASH_REMOVE, NULL);
04998     }
04999 }
05000 
05001 /* ----------
05002  * pgstat_write_statsfile_needed() -
05003  *
05004  *  Do we need to write out the files?
05005  * ----------
05006  */
05007 static bool
05008 pgstat_write_statsfile_needed(void)
05009 {
05010     if (!slist_is_empty(&last_statrequests))
05011         return true;
05012 
05013     /* Everything was written recently */
05014     return false;
05015 }
05016 
05017 /* ----------
05018  * pgstat_db_requested() -
05019  *
05020  *  Checks whether stats for a particular DB need to be written to a file.
05021  * ----------
05022  */
05023 static bool
05024 pgstat_db_requested(Oid databaseid)
05025 {
05026     slist_iter  iter;
05027 
05028     /* Check the databases if they need to refresh the stats. */
05029     slist_foreach(iter, &last_statrequests)
05030     {
05031         DBWriteRequest *req = slist_container(DBWriteRequest, next, iter.cur);
05032 
05033         if (req->databaseid == databaseid)
05034             return true;
05035     }
05036 
05037     return false;
05038 }