4 * All the statistics collector stuff hacked up in one big, ugly file.
6 * TODO: - Separate collector, postmaster and backend stuff
7 * into different files.
9 * - Add some automatic call for pgstat vacuuming.
11 * - Add a pgstat config column to pg_database, so this
12 * entire thing can be enabled/disabled on a per db basis.
14 * Copyright (c) 2001-2008, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.178 2008/08/05 12:09:30 mha Exp $
23 #include <sys/param.h>
25 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
34 #ifdef HAVE_SYS_POLL_H
40 #include "access/heapam.h"
41 #include "access/transam.h"
42 #include "access/twophase_rmgr.h"
43 #include "access/xact.h"
44 #include "catalog/pg_database.h"
45 #include "catalog/pg_proc.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqsignal.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
52 #include "postmaster/autovacuum.h"
53 #include "postmaster/fork_process.h"
54 #include "postmaster/postmaster.h"
55 #include "storage/backendid.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "storage/pg_shmem.h"
59 #include "storage/pmsignal.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "utils/rel.h"
64 #include "utils/tqual.h"
68 * Paths for the statistics files (relative to installation's $PGDATA).
71 #define PGSTAT_STAT_PERMANENT_FILENAME "global/pgstat.stat"
72 #define PGSTAT_STAT_PERMANENT_TMPFILE "global/pgstat.tmp"
73 #define PGSTAT_STAT_FILENAME "pg_stat_tmp/pgstat.stat"
74 #define PGSTAT_STAT_TMPFILE "pg_stat_tmp/pgstat.tmp"
80 #define PGSTAT_STAT_INTERVAL 500 /* How often to write the status file;
83 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart a
84 * failed statistics collector; in
87 #define PGSTAT_SELECT_TIMEOUT 2 /* How often to check for postmaster
88 * death; in seconds. */
92 * The initial size hints for the hash tables used in the collector.
95 #define PGSTAT_DB_HASH_SIZE 16
96 #define PGSTAT_TAB_HASH_SIZE 512
97 #define PGSTAT_FUNCTION_HASH_SIZE 512
104 bool pgstat_track_activities = false;
105 bool pgstat_track_counts = false;
106 int pgstat_track_functions = TRACK_FUNC_OFF;
107 int pgstat_track_activity_query_size = 1024;
110 * BgWriter global statistics counters (unused in other processes).
111 * Stored directly in a stats message structure so it can be sent
112 * without needing to copy things around. We assume this inits to zeroes.
114 PgStat_MsgBgWriter BgWriterStats;
120 NON_EXEC_STATIC int pgStatSock = -1;
122 static struct sockaddr_storage pgStatAddr;
124 static time_t last_pgstat_start_time;
126 static bool pgStatRunningInCollector = false;
129 * Structures in which backends store per-table info that's waiting to be
130 * sent to the collector.
132 * NOTE: once allocated, TabStatusArray structures are never moved or deleted
133 * for the life of the backend. Also, we zero out the t_id fields of the
134 * contained PgStat_TableStatus structs whenever they are not actively in use.
135 * This allows relcache pgstat_info pointers to be treated as long-lived data,
136 * avoiding repeated searches in pgstat_initstats() when a relation is
137 * repeatedly opened during a transaction.
139 #define TABSTAT_QUANTUM 100 /* we alloc this many at a time */
141 typedef struct TabStatusArray
143 struct TabStatusArray *tsa_next; /* link to next array, if any */
144 int tsa_used; /* # entries currently used */
145 PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */
148 static TabStatusArray *pgStatTabList = NULL;
151 * Backends store per-function info that's waiting to be sent to the collector
152 * in this hash table (indexed by function OID).
154 static HTAB *pgStatFunctions = NULL;
157 * Tuple insertion/deletion counts for an open transaction can't be propagated
158 * into PgStat_TableStatus counters until we know if it is going to commit
159 * or abort. Hence, we keep these counts in per-subxact structs that live
160 * in TopTransactionContext. This data structure is designed on the assumption
161 * that subxacts won't usually modify very many tables.
163 typedef struct PgStat_SubXactStatus
165 int nest_level; /* subtransaction nest level */
166 struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
167 PgStat_TableXactStatus *first; /* head of list for this subxact */
168 } PgStat_SubXactStatus;
170 static PgStat_SubXactStatus *pgStatXactStack = NULL;
172 static int pgStatXactCommit = 0;
173 static int pgStatXactRollback = 0;
175 /* Record that's written to 2PC state file when pgstat state is persisted */
176 typedef struct TwoPhasePgStatRecord
178 PgStat_Counter tuples_inserted; /* tuples inserted in xact */
179 PgStat_Counter tuples_deleted; /* tuples deleted in xact */
180 Oid t_id; /* table's OID */
181 bool t_shared; /* is it a shared catalog? */
182 } TwoPhasePgStatRecord;
185 * Info about current "snapshot" of stats file
187 static MemoryContext pgStatLocalContext = NULL;
188 static HTAB *pgStatDBHash = NULL;
189 static PgBackendStatus *localBackendStatusTable = NULL;
190 static int localNumBackends = 0;
193 * Cluster wide statistics, kept in the stats collector.
194 * Contains statistics that are not collected per database
197 static PgStat_GlobalStats globalStats;
199 static volatile bool need_exit = false;
200 static volatile bool need_statwrite = false;
203 * Total time charged to functions so far in the current backend.
204 * We use this to help separate "self" and "other" time charges.
205 * (We assume this initializes to zero.)
207 static instr_time total_func_time;
211 * Local function forward declarations
215 static pid_t pgstat_forkexec(void);
218 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
219 static void pgstat_exit(SIGNAL_ARGS);
220 static void force_statwrite(SIGNAL_ARGS);
221 static void pgstat_beshutdown_hook(int code, Datum arg);
223 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
224 static void pgstat_write_statsfile(bool permanent);
225 static HTAB *pgstat_read_statsfile(Oid onlydb, bool permanent);
226 static void backend_read_statsfile(void);
227 static void pgstat_read_current_status(void);
229 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
230 static void pgstat_send_funcstats(void);
231 static HTAB *pgstat_collect_oids(Oid catalogid);
233 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
235 static void pgstat_setup_memcxt(void);
237 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
238 static void pgstat_send(void *msg, int len);
240 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
241 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
242 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
243 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
244 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
245 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
246 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
247 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
248 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
249 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
252 /* ------------------------------------------------------------
253 * Public functions called from postmaster follow
254 * ------------------------------------------------------------
260 * Called from postmaster at startup. Create the resources required
261 * by the statistics collector process. If unable to do so, do not
262 * fail --- better to let the postmaster start with stats collection
269 ACCEPT_TYPE_ARG3 alen;
270 struct addrinfo *addrs = NULL,
280 #define TESTBYTEVAL ((char) 199)
283 * Create the UDP socket for sending and receiving statistic messages
285 hints.ai_flags = AI_PASSIVE;
286 hints.ai_family = PF_UNSPEC;
287 hints.ai_socktype = SOCK_DGRAM;
288 hints.ai_protocol = 0;
289 hints.ai_addrlen = 0;
290 hints.ai_addr = NULL;
291 hints.ai_canonname = NULL;
292 hints.ai_next = NULL;
293 ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
297 (errmsg("could not resolve \"localhost\": %s",
298 gai_strerror(ret))));
303 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
304 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
305 * when kernel will reject IPv6). Worse, the failure may occur at the
306 * bind() or perhaps even connect() stage. So we must loop through the
307 * results till we find a working combination. We will generate LOG
308 * messages, but no error, for bogus combinations.
310 for (addr = addrs; addr; addr = addr->ai_next)
312 #ifdef HAVE_UNIX_SOCKETS
313 /* Ignore AF_UNIX sockets, if any are returned. */
314 if (addr->ai_family == AF_UNIX)
320 (errmsg("trying another address for the statistics collector")));
325 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
328 (errcode_for_socket_access(),
329 errmsg("could not create socket for statistics collector: %m")));
334 * Bind it to a kernel assigned port on localhost and get the assigned
335 * port via getsockname().
337 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
340 (errcode_for_socket_access(),
341 errmsg("could not bind socket for statistics collector: %m")));
342 closesocket(pgStatSock);
347 alen = sizeof(pgStatAddr);
348 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
351 (errcode_for_socket_access(),
352 errmsg("could not get address of socket for statistics collector: %m")));
353 closesocket(pgStatSock);
359 * Connect the socket to its own address. This saves a few cycles by
360 * not having to respecify the target address on every send. This also
361 * provides a kernel-level check that only packets from this same
362 * address will be received.
364 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
367 (errcode_for_socket_access(),
368 errmsg("could not connect socket for statistics collector: %m")));
369 closesocket(pgStatSock);
375 * Try to send and receive a one-byte test message on the socket. This
376 * is to catch situations where the socket can be created but will not
377 * actually pass data (for instance, because kernel packet filtering
380 test_byte = TESTBYTEVAL;
383 if (send(pgStatSock, &test_byte, 1, 0) != 1)
386 goto retry1; /* if interrupted, just retry */
388 (errcode_for_socket_access(),
389 errmsg("could not send test message on socket for statistics collector: %m")));
390 closesocket(pgStatSock);
396 * There could possibly be a little delay before the message can be
397 * received. We arbitrarily allow up to half a second before deciding
400 for (;;) /* need a loop to handle EINTR */
403 FD_SET(pgStatSock, &rset);
406 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
407 if (sel_res >= 0 || errno != EINTR)
413 (errcode_for_socket_access(),
414 errmsg("select() failed in statistics collector: %m")));
415 closesocket(pgStatSock);
419 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
422 * This is the case we actually think is likely, so take pains to
423 * give a specific message for it.
425 * errno will not be set meaningfully here, so don't use it.
428 (errcode(ERRCODE_CONNECTION_FAILURE),
429 errmsg("test message did not get through on socket for statistics collector")));
430 closesocket(pgStatSock);
435 test_byte++; /* just make sure variable is changed */
438 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
441 goto retry2; /* if interrupted, just retry */
443 (errcode_for_socket_access(),
444 errmsg("could not receive test message on socket for statistics collector: %m")));
445 closesocket(pgStatSock);
450 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
453 (errcode(ERRCODE_INTERNAL_ERROR),
454 errmsg("incorrect test message transmission on socket for statistics collector")));
455 closesocket(pgStatSock);
460 /* If we get here, we have a working socket */
464 /* Did we find a working address? */
465 if (!addr || pgStatSock < 0)
469 * Set the socket to non-blocking IO. This ensures that if the collector
470 * falls behind, statistics messages will be discarded; backends won't
471 * block waiting to send messages to the collector.
473 if (!pg_set_noblock(pgStatSock))
476 (errcode_for_socket_access(),
477 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
481 pg_freeaddrinfo_all(hints.ai_family, addrs);
487 (errmsg("disabling statistics collector for lack of working socket")));
490 pg_freeaddrinfo_all(hints.ai_family, addrs);
493 closesocket(pgStatSock);
497 * Adjust GUC variables to suppress useless activity, and for debugging
498 * purposes (seeing track_counts off is a clue that we failed here). We
499 * use PGC_S_OVERRIDE because there is no point in trying to turn it back
500 * on from postgresql.conf without a restart.
502 SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
506 * pgstat_reset_all() -
508 * Remove the stats file. This is currently used only if WAL
509 * recovery is needed after a crash.
512 pgstat_reset_all(void)
514 unlink(PGSTAT_STAT_FILENAME);
515 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
521 * pgstat_forkexec() -
523 * Format up the arglist for, then fork and exec, statistics collector process
526 pgstat_forkexec(void)
531 av[ac++] = "postgres";
532 av[ac++] = "--forkcol";
533 av[ac++] = NULL; /* filled in by postmaster_forkexec */
536 Assert(ac < lengthof(av));
538 return postmaster_forkexec(ac, av);
540 #endif /* EXEC_BACKEND */
546 * Called from postmaster at startup or after an existing collector
547 * died. Attempt to fire up a fresh statistics collector.
549 * Returns PID of child process, or 0 if fail.
551 * Note: if fail, we will be called again from the postmaster main loop.
560 * Check that the socket is there, else pgstat_init failed and we can do
567 * Do nothing if too soon since last collector start. This is a safety
568 * valve to protect against continuous respawn attempts if the collector
569 * is dying immediately at launch. Note that since we will be re-called
570 * from the postmaster main loop, we will get another chance later.
572 curtime = time(NULL);
573 if ((unsigned int) (curtime - last_pgstat_start_time) <
574 (unsigned int) PGSTAT_RESTART_INTERVAL)
576 last_pgstat_start_time = curtime;
579 * Okay, fork off the collector.
582 switch ((pgStatPid = pgstat_forkexec()))
584 switch ((pgStatPid = fork_process()))
589 (errmsg("could not fork statistics collector: %m")));
594 /* in postmaster child ... */
595 /* Close the postmaster's sockets */
596 ClosePostmasterPorts(false);
598 /* Lose the postmaster's on-exit routines */
601 /* Drop our connection to postmaster's shared memory, as well */
602 PGSharedMemoryDetach();
604 PgstatCollectorMain(0, NULL);
609 return (int) pgStatPid;
612 /* shouldn't get here */
617 allow_immediate_pgstat_restart(void)
619 last_pgstat_start_time = 0;
622 /* ------------------------------------------------------------
623 * Public functions used by backends follow
624 *------------------------------------------------------------
629 * pgstat_report_stat() -
631 * Called from tcop/postgres.c to send the so far collected per-table
632 * and function usage statistics to the collector. Note that this is
633 * called only when not within a transaction, so it is fair to use
634 * transaction stop time as an approximation of current time.
638 pgstat_report_stat(bool force)
640 /* we assume this inits to all zeroes: */
641 static const PgStat_TableCounts all_zeroes;
642 static TimestampTz last_report = 0;
645 PgStat_MsgTabstat regular_msg;
646 PgStat_MsgTabstat shared_msg;
650 /* Don't expend a clock check if nothing to do */
651 /* Note: we ignore pending function stats in this test ... OK? */
652 if (pgStatTabList == NULL ||
653 pgStatTabList->tsa_used == 0)
657 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
658 * msec since we last sent one, or the caller wants to force stats out.
660 now = GetCurrentTransactionStopTimestamp();
662 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
667 * Scan through the TabStatusArray struct(s) to find tables that actually
668 * have counts, and build messages to send. We have to separate shared
669 * relations from regular ones because the databaseid field in the message
670 * header has to depend on that.
672 regular_msg.m_databaseid = MyDatabaseId;
673 shared_msg.m_databaseid = InvalidOid;
674 regular_msg.m_nentries = 0;
675 shared_msg.m_nentries = 0;
677 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
679 for (i = 0; i < tsa->tsa_used; i++)
681 PgStat_TableStatus *entry = &tsa->tsa_entries[i];
682 PgStat_MsgTabstat *this_msg;
683 PgStat_TableEntry *this_ent;
685 /* Shouldn't have any pending transaction-dependent counts */
686 Assert(entry->trans == NULL);
689 * Ignore entries that didn't accumulate any actual counts, such
690 * as indexes that were opened by the planner but not used.
692 if (memcmp(&entry->t_counts, &all_zeroes,
693 sizeof(PgStat_TableCounts)) == 0)
697 * OK, insert data into the appropriate message, and send if full.
699 this_msg = entry->t_shared ? &shared_msg : ®ular_msg;
700 this_ent = &this_msg->m_entry[this_msg->m_nentries];
701 this_ent->t_id = entry->t_id;
702 memcpy(&this_ent->t_counts, &entry->t_counts,
703 sizeof(PgStat_TableCounts));
704 if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
706 pgstat_send_tabstat(this_msg);
707 this_msg->m_nentries = 0;
710 /* zero out TableStatus structs after use */
711 MemSet(tsa->tsa_entries, 0,
712 tsa->tsa_used * sizeof(PgStat_TableStatus));
717 * Send partial messages. If force is true, make sure that any pending
718 * xact commit/abort gets counted, even if no table stats to send.
720 if (regular_msg.m_nentries > 0 ||
721 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
722 pgstat_send_tabstat(®ular_msg);
723 if (shared_msg.m_nentries > 0)
724 pgstat_send_tabstat(&shared_msg);
726 /* Now, send function statistics */
727 pgstat_send_funcstats();
731 * Subroutine for pgstat_report_stat: finish and send a tabstat message
734 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
739 /* It's unlikely we'd get here with no socket, but maybe not impossible */
744 * Report accumulated xact commit/rollback whenever we send a normal
747 if (OidIsValid(tsmsg->m_databaseid))
749 tsmsg->m_xact_commit = pgStatXactCommit;
750 tsmsg->m_xact_rollback = pgStatXactRollback;
751 pgStatXactCommit = 0;
752 pgStatXactRollback = 0;
756 tsmsg->m_xact_commit = 0;
757 tsmsg->m_xact_rollback = 0;
760 n = tsmsg->m_nentries;
761 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
762 n * sizeof(PgStat_TableEntry);
764 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
765 pgstat_send(tsmsg, len);
769 * Subroutine for pgstat_report_stat: populate and send a function stat message
772 pgstat_send_funcstats(void)
774 /* we assume this inits to all zeroes: */
775 static const PgStat_FunctionCounts all_zeroes;
777 PgStat_MsgFuncstat msg;
778 PgStat_BackendFunctionEntry *entry;
779 HASH_SEQ_STATUS fstat;
781 if (pgStatFunctions == NULL)
784 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
785 msg.m_databaseid = MyDatabaseId;
788 hash_seq_init(&fstat, pgStatFunctions);
789 while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
791 PgStat_FunctionEntry *m_ent;
793 /* Skip it if no counts accumulated since last time */
794 if (memcmp(&entry->f_counts, &all_zeroes,
795 sizeof(PgStat_FunctionCounts)) == 0)
798 /* need to convert format of time accumulators */
799 m_ent = &msg.m_entry[msg.m_nentries];
800 m_ent->f_id = entry->f_id;
801 m_ent->f_numcalls = entry->f_counts.f_numcalls;
802 m_ent->f_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time);
803 m_ent->f_time_self = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time_self);
805 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
807 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
808 msg.m_nentries * sizeof(PgStat_FunctionEntry));
812 /* reset the entry's counts */
813 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
816 if (msg.m_nentries > 0)
817 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
818 msg.m_nentries * sizeof(PgStat_FunctionEntry));
823 * pgstat_vacuum_stat() -
825 * Will tell the collector about objects he can get rid of.
829 pgstat_vacuum_stat(void)
832 PgStat_MsgTabpurge msg;
833 PgStat_MsgFuncpurge f_msg;
834 HASH_SEQ_STATUS hstat;
835 PgStat_StatDBEntry *dbentry;
836 PgStat_StatTabEntry *tabentry;
837 PgStat_StatFuncEntry *funcentry;
844 * If not done for this transaction, read the statistics collector stats
845 * file into some hash tables.
847 backend_read_statsfile();
850 * Read pg_database and make a list of OIDs of all existing databases
852 htab = pgstat_collect_oids(DatabaseRelationId);
855 * Search the database hash table for dead databases and tell the
856 * collector to drop them.
858 hash_seq_init(&hstat, pgStatDBHash);
859 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
861 Oid dbid = dbentry->databaseid;
863 CHECK_FOR_INTERRUPTS();
865 /* the DB entry for shared tables (with InvalidOid) is never dropped */
866 if (OidIsValid(dbid) &&
867 hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
868 pgstat_drop_database(dbid);
875 * Lookup our own database entry; if not found, nothing more to do.
877 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
878 (void *) &MyDatabaseId,
880 if (dbentry == NULL || dbentry->tables == NULL)
884 * Similarly to above, make a list of all known relations in this DB.
886 htab = pgstat_collect_oids(RelationRelationId);
889 * Initialize our messages table counter to zero
894 * Check for all tables listed in stats hashtable if they still exist.
896 hash_seq_init(&hstat, dbentry->tables);
897 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
899 Oid tabid = tabentry->tableid;
901 CHECK_FOR_INTERRUPTS();
903 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
907 * Not there, so add this table's Oid to the message
909 msg.m_tableid[msg.m_nentries++] = tabid;
912 * If the message is full, send it out and reinitialize to empty
914 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
916 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
917 +msg.m_nentries * sizeof(Oid);
919 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
920 msg.m_databaseid = MyDatabaseId;
921 pgstat_send(&msg, len);
930 if (msg.m_nentries > 0)
932 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
933 +msg.m_nentries * sizeof(Oid);
935 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
936 msg.m_databaseid = MyDatabaseId;
937 pgstat_send(&msg, len);
944 * Now repeat the above steps for functions.
946 htab = pgstat_collect_oids(ProcedureRelationId);
948 pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
949 f_msg.m_databaseid = MyDatabaseId;
950 f_msg.m_nentries = 0;
952 hash_seq_init(&hstat, dbentry->functions);
953 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
955 Oid funcid = funcentry->functionid;
957 CHECK_FOR_INTERRUPTS();
959 if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
963 * Not there, so add this function's Oid to the message
965 f_msg.m_functionid[f_msg.m_nentries++] = funcid;
968 * If the message is full, send it out and reinitialize to empty
970 if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
972 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
973 +f_msg.m_nentries * sizeof(Oid);
975 pgstat_send(&f_msg, len);
977 f_msg.m_nentries = 0;
984 if (f_msg.m_nentries > 0)
986 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
987 +f_msg.m_nentries * sizeof(Oid);
989 pgstat_send(&f_msg, len);
997 * pgstat_collect_oids() -
999 * Collect the OIDs of all objects listed in the specified system catalog
1000 * into a temporary hash table. Caller should hash_destroy the result
1001 * when done with it.
1005 pgstat_collect_oids(Oid catalogid)
1013 memset(&hash_ctl, 0, sizeof(hash_ctl));
1014 hash_ctl.keysize = sizeof(Oid);
1015 hash_ctl.entrysize = sizeof(Oid);
1016 hash_ctl.hash = oid_hash;
1017 htab = hash_create("Temporary table of OIDs",
1018 PGSTAT_TAB_HASH_SIZE,
1020 HASH_ELEM | HASH_FUNCTION);
1022 rel = heap_open(catalogid, AccessShareLock);
1023 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1024 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1026 Oid thisoid = HeapTupleGetOid(tup);
1028 CHECK_FOR_INTERRUPTS();
1030 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1033 heap_close(rel, AccessShareLock);
1040 * pgstat_drop_database() -
1042 * Tell the collector that we just dropped a database.
1043 * (If the message gets lost, we will still clean the dead DB eventually
1044 * via future invocations of pgstat_vacuum_stat().)
1048 pgstat_drop_database(Oid databaseid)
1050 PgStat_MsgDropdb msg;
1055 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1056 msg.m_databaseid = databaseid;
1057 pgstat_send(&msg, sizeof(msg));
1062 * pgstat_drop_relation() -
1064 * Tell the collector that we just dropped a relation.
1065 * (If the message gets lost, we will still clean the dead entry eventually
1066 * via future invocations of pgstat_vacuum_stat().)
1068 * Currently not used for lack of any good place to call it; we rely
1069 * entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1074 pgstat_drop_relation(Oid relid)
1076 PgStat_MsgTabpurge msg;
1082 msg.m_tableid[0] = relid;
1085 len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
1087 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1088 msg.m_databaseid = MyDatabaseId;
1089 pgstat_send(&msg, len);
1091 #endif /* NOT_USED */
1095 * pgstat_reset_counters() -
1097 * Tell the statistics collector to reset counters for our database.
1101 pgstat_reset_counters(void)
1103 PgStat_MsgResetcounter msg;
1110 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1111 errmsg("must be superuser to reset statistics counters")));
1113 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1114 msg.m_databaseid = MyDatabaseId;
1115 pgstat_send(&msg, sizeof(msg));
1120 * pgstat_report_autovac() -
1122 * Called from autovacuum.c to report startup of an autovacuum process.
1123 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1124 * the db OID must be passed in, instead.
1128 pgstat_report_autovac(Oid dboid)
1130 PgStat_MsgAutovacStart msg;
1135 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1136 msg.m_databaseid = dboid;
1137 msg.m_start_time = GetCurrentTimestamp();
1139 pgstat_send(&msg, sizeof(msg));
1144 * pgstat_report_vacuum() -
1146 * Tell the collector about the table we just vacuumed.
1150 pgstat_report_vacuum(Oid tableoid, bool shared,
1151 bool analyze, PgStat_Counter tuples)
1153 PgStat_MsgVacuum msg;
1155 if (pgStatSock < 0 || !pgstat_track_counts)
1158 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1159 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1160 msg.m_tableoid = tableoid;
1161 msg.m_analyze = analyze;
1162 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1163 msg.m_vacuumtime = GetCurrentTimestamp();
1164 msg.m_tuples = tuples;
1165 pgstat_send(&msg, sizeof(msg));
1169 * pgstat_report_analyze() -
1171 * Tell the collector about the table we just analyzed.
1175 pgstat_report_analyze(Relation rel, PgStat_Counter livetuples,
1176 PgStat_Counter deadtuples)
1178 PgStat_MsgAnalyze msg;
1180 if (pgStatSock < 0 || !pgstat_track_counts)
1184 * Unlike VACUUM, ANALYZE might be running inside a transaction that
1185 * has already inserted and/or deleted rows in the target table.
1186 * ANALYZE will have counted such rows as live or dead respectively.
1187 * Because we will report our counts of such rows at transaction end,
1188 * we should subtract off these counts from what we send to the collector
1189 * now, else they'll be double-counted after commit. (This approach also
1190 * ensures that the collector ends up with the right numbers if we abort
1191 * instead of committing.)
1193 if (rel->pgstat_info != NULL)
1195 PgStat_TableXactStatus *trans;
1197 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1199 livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1200 deadtuples -= trans->tuples_deleted;
1202 /* count stuff inserted by already-aborted subxacts, too */
1203 deadtuples -= rel->pgstat_info->t_counts.t_new_dead_tuples;
1204 /* Since ANALYZE's counts are estimates, we could have underflowed */
1205 livetuples = Max(livetuples, 0);
1206 deadtuples = Max(deadtuples, 0);
1209 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1210 msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1211 msg.m_tableoid = RelationGetRelid(rel);
1212 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1213 msg.m_analyzetime = GetCurrentTimestamp();
1214 msg.m_live_tuples = livetuples;
1215 msg.m_dead_tuples = deadtuples;
1216 pgstat_send(&msg, sizeof(msg));
1223 * Send some junk data to the collector to increase traffic.
1229 PgStat_MsgDummy msg;
1234 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1235 pgstat_send(&msg, sizeof(msg));
1239 * Initialize function call usage data.
1240 * Called by the executor before invoking a function.
1243 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
1244 PgStat_FunctionCallUsage *fcu)
1246 PgStat_BackendFunctionEntry *htabent;
1249 if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1251 /* stats not wanted */
1256 if (!pgStatFunctions)
1258 /* First time through - initialize function stat table */
1261 memset(&hash_ctl, 0, sizeof(hash_ctl));
1262 hash_ctl.keysize = sizeof(Oid);
1263 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1264 hash_ctl.hash = oid_hash;
1265 pgStatFunctions = hash_create("Function stat entries",
1266 PGSTAT_FUNCTION_HASH_SIZE,
1268 HASH_ELEM | HASH_FUNCTION);
1271 /* Get the stats entry for this function, create if necessary */
1272 htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1273 HASH_ENTER, &found);
1275 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1277 fcu->fs = &htabent->f_counts;
1279 /* save stats for this function, later used to compensate for recursion */
1280 fcu->save_f_time = htabent->f_counts.f_time;
1282 /* save current backend-wide total time */
1283 fcu->save_total = total_func_time;
1285 /* get clock time as of function start */
1286 INSTR_TIME_SET_CURRENT(fcu->f_start);
1290 * Calculate function call usage and update stat counters.
1291 * Called by the executor after invoking a function.
1293 * In the case of a set-returning function that runs in value-per-call mode,
1294 * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1295 * calls for what the user considers a single call of the function. The
1296 * finalize flag should be TRUE on the last call.
1299 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1301 PgStat_FunctionCounts *fs = fcu->fs;
1303 instr_time f_others;
1306 /* stats not wanted? */
1310 /* total elapsed time in this function call */
1311 INSTR_TIME_SET_CURRENT(f_total);
1312 INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1314 /* self usage: elapsed minus anything already charged to other calls */
1315 f_others = total_func_time;
1316 INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1318 INSTR_TIME_SUBTRACT(f_self, f_others);
1320 /* update backend-wide total time */
1321 INSTR_TIME_ADD(total_func_time, f_self);
1324 * Compute the new total f_time as the total elapsed time added to the
1325 * pre-call value of f_time. This is necessary to avoid double-counting
1326 * any time taken by recursive calls of myself. (We do not need any
1327 * similar kluge for self time, since that already excludes any
1330 INSTR_TIME_ADD(f_total, fcu->save_f_time);
1332 /* update counters in function stats table */
1335 fs->f_time = f_total;
1336 INSTR_TIME_ADD(fs->f_time_self, f_self);
1341 * pgstat_initstats() -
1343 * Initialize a relcache entry to count access statistics.
1344 * Called whenever a relation is opened.
1346 * We assume that a relcache entry's pgstat_info field is zeroed by
1347 * relcache.c when the relcache entry is made; thereafter it is long-lived
1348 * data. We can avoid repeated searches of the TabStatus arrays when the
1349 * same relation is touched repeatedly within a transaction.
1353 pgstat_initstats(Relation rel)
1355 Oid rel_id = rel->rd_id;
1356 char relkind = rel->rd_rel->relkind;
1358 /* We only count stats for things that have storage */
1359 if (!(relkind == RELKIND_RELATION ||
1360 relkind == RELKIND_INDEX ||
1361 relkind == RELKIND_TOASTVALUE))
1363 rel->pgstat_info = NULL;
1367 if (pgStatSock < 0 || !pgstat_track_counts)
1369 /* We're not counting at all */
1370 rel->pgstat_info = NULL;
1375 * If we already set up this relation in the current transaction, nothing
1378 if (rel->pgstat_info != NULL &&
1379 rel->pgstat_info->t_id == rel_id)
1382 /* Else find or make the PgStat_TableStatus entry, and update link */
1383 rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1387 * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1389 static PgStat_TableStatus *
1390 get_tabstat_entry(Oid rel_id, bool isshared)
1392 PgStat_TableStatus *entry;
1393 TabStatusArray *tsa;
1394 TabStatusArray *prev_tsa;
1398 * Search the already-used tabstat slots for this relation.
1401 for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1403 for (i = 0; i < tsa->tsa_used; i++)
1405 entry = &tsa->tsa_entries[i];
1406 if (entry->t_id == rel_id)
1410 if (tsa->tsa_used < TABSTAT_QUANTUM)
1413 * It must not be present, but we found a free slot instead. Fine,
1414 * let's use this one. We assume the entry was already zeroed,
1415 * either at creation or after last use.
1417 entry = &tsa->tsa_entries[tsa->tsa_used++];
1418 entry->t_id = rel_id;
1419 entry->t_shared = isshared;
1425 * We ran out of tabstat slots, so allocate more. Be sure they're zeroed.
1427 tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1428 sizeof(TabStatusArray));
1430 prev_tsa->tsa_next = tsa;
1432 pgStatTabList = tsa;
1435 * Use the first entry of the new TabStatusArray.
1437 entry = &tsa->tsa_entries[tsa->tsa_used++];
1438 entry->t_id = rel_id;
1439 entry->t_shared = isshared;
1444 * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1446 static PgStat_SubXactStatus *
1447 get_tabstat_stack_level(int nest_level)
1449 PgStat_SubXactStatus *xact_state;
1451 xact_state = pgStatXactStack;
1452 if (xact_state == NULL || xact_state->nest_level != nest_level)
1454 xact_state = (PgStat_SubXactStatus *)
1455 MemoryContextAlloc(TopTransactionContext,
1456 sizeof(PgStat_SubXactStatus));
1457 xact_state->nest_level = nest_level;
1458 xact_state->prev = pgStatXactStack;
1459 xact_state->first = NULL;
1460 pgStatXactStack = xact_state;
1466 * add_tabstat_xact_level - add a new (sub)transaction state record
1469 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1471 PgStat_SubXactStatus *xact_state;
1472 PgStat_TableXactStatus *trans;
1475 * If this is the first rel to be modified at the current nest level, we
1476 * first have to push a transaction stack entry.
1478 xact_state = get_tabstat_stack_level(nest_level);
1480 /* Now make a per-table stack entry */
1481 trans = (PgStat_TableXactStatus *)
1482 MemoryContextAllocZero(TopTransactionContext,
1483 sizeof(PgStat_TableXactStatus));
1484 trans->nest_level = nest_level;
1485 trans->upper = pgstat_info->trans;
1486 trans->parent = pgstat_info;
1487 trans->next = xact_state->first;
1488 xact_state->first = trans;
1489 pgstat_info->trans = trans;
1493 * pgstat_count_heap_insert - count a tuple insertion
1496 pgstat_count_heap_insert(Relation rel)
1498 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1500 if (pgstat_track_counts && pgstat_info != NULL)
1502 int nest_level = GetCurrentTransactionNestLevel();
1504 /* t_tuples_inserted is nontransactional, so just advance it */
1505 pgstat_info->t_counts.t_tuples_inserted++;
1507 /* We have to log the transactional effect at the proper level */
1508 if (pgstat_info->trans == NULL ||
1509 pgstat_info->trans->nest_level != nest_level)
1510 add_tabstat_xact_level(pgstat_info, nest_level);
1512 pgstat_info->trans->tuples_inserted++;
1517 * pgstat_count_heap_update - count a tuple update
1520 pgstat_count_heap_update(Relation rel, bool hot)
1522 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1524 if (pgstat_track_counts && pgstat_info != NULL)
1526 int nest_level = GetCurrentTransactionNestLevel();
1528 /* t_tuples_updated is nontransactional, so just advance it */
1529 pgstat_info->t_counts.t_tuples_updated++;
1530 /* ditto for the hot_update counter */
1532 pgstat_info->t_counts.t_tuples_hot_updated++;
1534 /* We have to log the transactional effect at the proper level */
1535 if (pgstat_info->trans == NULL ||
1536 pgstat_info->trans->nest_level != nest_level)
1537 add_tabstat_xact_level(pgstat_info, nest_level);
1539 /* An UPDATE both inserts a new tuple and deletes the old */
1540 pgstat_info->trans->tuples_inserted++;
1541 pgstat_info->trans->tuples_deleted++;
1546 * pgstat_count_heap_delete - count a tuple deletion
1549 pgstat_count_heap_delete(Relation rel)
1551 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1553 if (pgstat_track_counts && pgstat_info != NULL)
1555 int nest_level = GetCurrentTransactionNestLevel();
1557 /* t_tuples_deleted is nontransactional, so just advance it */
1558 pgstat_info->t_counts.t_tuples_deleted++;
1560 /* We have to log the transactional effect at the proper level */
1561 if (pgstat_info->trans == NULL ||
1562 pgstat_info->trans->nest_level != nest_level)
1563 add_tabstat_xact_level(pgstat_info, nest_level);
1565 pgstat_info->trans->tuples_deleted++;
1570 * pgstat_update_heap_dead_tuples - update dead-tuples count
1572 * The semantics of this are that we are reporting the nontransactional
1573 * recovery of "delta" dead tuples; so t_new_dead_tuples decreases
1574 * rather than increasing, and the change goes straight into the per-table
1575 * counter, not into transactional state.
1578 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1580 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1582 if (pgstat_track_counts && pgstat_info != NULL)
1583 pgstat_info->t_counts.t_new_dead_tuples -= delta;
1590 * Called from access/transam/xact.c at top-level transaction commit/abort.
1594 AtEOXact_PgStat(bool isCommit)
1596 PgStat_SubXactStatus *xact_state;
1599 * Count transaction commit or abort. (We use counters, not just bools,
1600 * in case the reporting message isn't sent right away.)
1605 pgStatXactRollback++;
1608 * Transfer transactional insert/update counts into the base tabstat
1609 * entries. We don't bother to free any of the transactional state, since
1610 * it's all in TopTransactionContext and will go away anyway.
1612 xact_state = pgStatXactStack;
1613 if (xact_state != NULL)
1615 PgStat_TableXactStatus *trans;
1617 Assert(xact_state->nest_level == 1);
1618 Assert(xact_state->prev == NULL);
1619 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1621 PgStat_TableStatus *tabstat;
1623 Assert(trans->nest_level == 1);
1624 Assert(trans->upper == NULL);
1625 tabstat = trans->parent;
1626 Assert(tabstat->trans == trans);
1629 tabstat->t_counts.t_new_live_tuples +=
1630 trans->tuples_inserted - trans->tuples_deleted;
1631 tabstat->t_counts.t_new_dead_tuples += trans->tuples_deleted;
1635 /* inserted tuples are dead, deleted tuples are unaffected */
1636 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1638 tabstat->trans = NULL;
1641 pgStatXactStack = NULL;
1643 /* Make sure any stats snapshot is thrown away */
1644 pgstat_clear_snapshot();
1648 * AtEOSubXact_PgStat
1650 * Called from access/transam/xact.c at subtransaction commit/abort.
1654 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1656 PgStat_SubXactStatus *xact_state;
1659 * Transfer transactional insert/update counts into the next higher
1660 * subtransaction state.
1662 xact_state = pgStatXactStack;
1663 if (xact_state != NULL &&
1664 xact_state->nest_level >= nestDepth)
1666 PgStat_TableXactStatus *trans;
1667 PgStat_TableXactStatus *next_trans;
1669 /* delink xact_state from stack immediately to simplify reuse case */
1670 pgStatXactStack = xact_state->prev;
1672 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1674 PgStat_TableStatus *tabstat;
1676 next_trans = trans->next;
1677 Assert(trans->nest_level == nestDepth);
1678 tabstat = trans->parent;
1679 Assert(tabstat->trans == trans);
1682 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1684 trans->upper->tuples_inserted += trans->tuples_inserted;
1685 trans->upper->tuples_deleted += trans->tuples_deleted;
1686 tabstat->trans = trans->upper;
1692 * When there isn't an immediate parent state, we can just
1693 * reuse the record instead of going through a
1694 * palloc/pfree pushup (this works since it's all in
1695 * TopTransactionContext anyway). We have to re-link it
1696 * into the parent level, though, and that might mean
1697 * pushing a new entry into the pgStatXactStack.
1699 PgStat_SubXactStatus *upper_xact_state;
1701 upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1702 trans->next = upper_xact_state->first;
1703 upper_xact_state->first = trans;
1704 trans->nest_level = nestDepth - 1;
1710 * On abort, inserted tuples are dead (and can be bounced out
1711 * to the top-level tabstat), deleted tuples are unaffected
1713 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1714 tabstat->trans = trans->upper;
1725 * Save the transactional stats state at 2PC transaction prepare.
1727 * In this phase we just generate 2PC records for all the pending
1728 * transaction-dependent stats work.
1731 AtPrepare_PgStat(void)
1733 PgStat_SubXactStatus *xact_state;
1735 xact_state = pgStatXactStack;
1736 if (xact_state != NULL)
1738 PgStat_TableXactStatus *trans;
1740 Assert(xact_state->nest_level == 1);
1741 Assert(xact_state->prev == NULL);
1742 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1744 PgStat_TableStatus *tabstat;
1745 TwoPhasePgStatRecord record;
1747 Assert(trans->nest_level == 1);
1748 Assert(trans->upper == NULL);
1749 tabstat = trans->parent;
1750 Assert(tabstat->trans == trans);
1752 record.tuples_inserted = trans->tuples_inserted;
1753 record.tuples_deleted = trans->tuples_deleted;
1754 record.t_id = tabstat->t_id;
1755 record.t_shared = tabstat->t_shared;
1757 RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1758 &record, sizeof(TwoPhasePgStatRecord));
1764 * PostPrepare_PgStat
1765 * Clean up after successful PREPARE.
1767 * All we need do here is unlink the transaction stats state from the
1768 * nontransactional state. The nontransactional action counts will be
1769 * reported to the stats collector immediately, while the effects on live
1770 * and dead tuple counts are preserved in the 2PC state file.
1772 * Note: AtEOXact_PgStat is not called during PREPARE.
1775 PostPrepare_PgStat(void)
1777 PgStat_SubXactStatus *xact_state;
1780 * We don't bother to free any of the transactional state, since it's all
1781 * in TopTransactionContext and will go away anyway.
1783 xact_state = pgStatXactStack;
1784 if (xact_state != NULL)
1786 PgStat_TableXactStatus *trans;
1788 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1790 PgStat_TableStatus *tabstat;
1792 tabstat = trans->parent;
1793 tabstat->trans = NULL;
1796 pgStatXactStack = NULL;
1798 /* Make sure any stats snapshot is thrown away */
1799 pgstat_clear_snapshot();
1803 * 2PC processing routine for COMMIT PREPARED case.
1805 * Load the saved counts into our local pgstats state.
1808 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
1809 void *recdata, uint32 len)
1811 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1812 PgStat_TableStatus *pgstat_info;
1814 /* Find or create a tabstat entry for the rel */
1815 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1817 pgstat_info->t_counts.t_new_live_tuples +=
1818 rec->tuples_inserted - rec->tuples_deleted;
1819 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_deleted;
1823 * 2PC processing routine for ROLLBACK PREPARED case.
1825 * Load the saved counts into our local pgstats state, but treat them
1829 pgstat_twophase_postabort(TransactionId xid, uint16 info,
1830 void *recdata, uint32 len)
1832 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1833 PgStat_TableStatus *pgstat_info;
1835 /* Find or create a tabstat entry for the rel */
1836 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1838 /* inserted tuples are dead, deleted tuples are no-ops */
1839 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_inserted;
1844 * pgstat_fetch_stat_dbentry() -
1846 * Support function for the SQL-callable pgstat* functions. Returns
1847 * the collected statistics for one database or NULL. NULL doesn't mean
1848 * that the database doesn't exist, it is just not yet known by the
1849 * collector, so the caller is better off to report ZERO instead.
1852 PgStat_StatDBEntry *
1853 pgstat_fetch_stat_dbentry(Oid dbid)
1856 * If not done for this transaction, read the statistics collector stats
1857 * file into some hash tables.
1859 backend_read_statsfile();
1862 * Lookup the requested database; return NULL if not found
1864 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1871 * pgstat_fetch_stat_tabentry() -
1873 * Support function for the SQL-callable pgstat* functions. Returns
1874 * the collected statistics for one table or NULL. NULL doesn't mean
1875 * that the table doesn't exist, it is just not yet known by the
1876 * collector, so the caller is better off to report ZERO instead.
1879 PgStat_StatTabEntry *
1880 pgstat_fetch_stat_tabentry(Oid relid)
1883 PgStat_StatDBEntry *dbentry;
1884 PgStat_StatTabEntry *tabentry;
1887 * If not done for this transaction, read the statistics collector stats
1888 * file into some hash tables.
1890 backend_read_statsfile();
1893 * Lookup our database, then look in its table hash table.
1895 dbid = MyDatabaseId;
1896 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1899 if (dbentry != NULL && dbentry->tables != NULL)
1901 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1909 * If we didn't find it, maybe it's a shared table.
1912 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1915 if (dbentry != NULL && dbentry->tables != NULL)
1917 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1929 * pgstat_fetch_stat_funcentry() -
1931 * Support function for the SQL-callable pgstat* functions. Returns
1932 * the collected statistics for one function or NULL.
1935 PgStat_StatFuncEntry *
1936 pgstat_fetch_stat_funcentry(Oid func_id)
1938 PgStat_StatDBEntry *dbentry;
1939 PgStat_StatFuncEntry *funcentry = NULL;
1941 /* load the stats file if needed */
1942 backend_read_statsfile();
1944 /* Lookup our database, then find the requested function. */
1945 dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
1946 if (dbentry != NULL && dbentry->functions != NULL)
1948 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
1958 * pgstat_fetch_stat_beentry() -
1960 * Support function for the SQL-callable pgstat* functions. Returns
1961 * our local copy of the current-activity entry for one backend.
1963 * NB: caller is responsible for a check if the user is permitted to see
1964 * this info (especially the querystring).
1968 pgstat_fetch_stat_beentry(int beid)
1970 pgstat_read_current_status();
1972 if (beid < 1 || beid > localNumBackends)
1975 return &localBackendStatusTable[beid - 1];
1980 * pgstat_fetch_stat_numbackends() -
1982 * Support function for the SQL-callable pgstat* functions. Returns
1983 * the maximum current backend id.
1987 pgstat_fetch_stat_numbackends(void)
1989 pgstat_read_current_status();
1991 return localNumBackends;
1996 * pgstat_fetch_global() -
1998 * Support function for the SQL-callable pgstat* functions. Returns
1999 * a pointer to the global statistics struct.
2002 PgStat_GlobalStats *
2003 pgstat_fetch_global(void)
2005 backend_read_statsfile();
2007 return &globalStats;
2011 /* ------------------------------------------------------------
2012 * Functions for management of the shared-memory PgBackendStatus array
2013 * ------------------------------------------------------------
2016 static PgBackendStatus *BackendStatusArray = NULL;
2017 static PgBackendStatus *MyBEEntry = NULL;
2018 static char *BackendActivityBuffer = NULL;
2022 * Report shared-memory space needed by CreateSharedBackendStatus.
2025 BackendStatusShmemSize(void)
2029 size = add_size(mul_size(sizeof(PgBackendStatus), MaxBackends),
2030 mul_size(pgstat_track_activity_query_size, MaxBackends));
2035 * Initialize the shared status array and activity string buffer during
2036 * postmaster startup.
2039 CreateSharedBackendStatus(void)
2046 /* Create or attach to the shared array */
2047 size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2048 BackendStatusArray = (PgBackendStatus *)
2049 ShmemInitStruct("Backend Status Array", size, &found);
2054 * We're the first - initialize.
2056 MemSet(BackendStatusArray, 0, size);
2059 /* Create or attach to the shared activity buffer */
2060 size = mul_size(pgstat_track_activity_query_size, MaxBackends);
2061 BackendActivityBuffer = (char*)
2062 ShmemInitStruct("Backend Activity Buffer", size, &found);
2066 MemSet(BackendActivityBuffer, 0, size);
2068 /* Initialize st_activity pointers. */
2069 buffer = BackendActivityBuffer;
2070 for (i = 0; i < MaxBackends; i++) {
2071 BackendStatusArray[i].st_activity = buffer;
2072 buffer += pgstat_track_activity_query_size;
2079 * pgstat_initialize() -
2081 * Initialize pgstats state, and set up our on-proc-exit hook.
2082 * Called from InitPostgres. MyBackendId must be set,
2083 * but we must not have started any transaction yet (since the
2084 * exit hook must run after the last transaction exit).
2088 pgstat_initialize(void)
2090 /* Initialize MyBEEntry */
2091 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2092 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2094 /* Set up a process-exit hook to clean up */
2095 on_shmem_exit(pgstat_beshutdown_hook, 0);
2099 * pgstat_bestart() -
2101 * Initialize this backend's entry in the PgBackendStatus array.
2102 * Called from InitPostgres. MyDatabaseId and session userid must be set
2103 * (hence, this cannot be combined with pgstat_initialize).
2107 pgstat_bestart(void)
2109 TimestampTz proc_start_timestamp;
2111 SockAddr clientaddr;
2112 volatile PgBackendStatus *beentry;
2115 * To minimize the time spent modifying the PgBackendStatus entry, fetch
2116 * all the needed data first.
2118 * If we have a MyProcPort, use its session start time (for consistency,
2119 * and to save a kernel call).
2122 proc_start_timestamp = MyProcPort->SessionStartTime;
2124 proc_start_timestamp = GetCurrentTimestamp();
2125 userid = GetSessionUserId();
2128 * We may not have a MyProcPort (eg, if this is the autovacuum process).
2129 * If so, use all-zeroes client address, which is dealt with specially in
2130 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2133 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2135 MemSet(&clientaddr, 0, sizeof(clientaddr));
2138 * Initialize my status entry, following the protocol of bumping
2139 * st_changecount before and after; and make sure it's even afterwards. We
2140 * use a volatile pointer here to ensure the compiler doesn't try to get
2143 beentry = MyBEEntry;
2146 beentry->st_changecount++;
2147 } while ((beentry->st_changecount & 1) == 0);
2149 beentry->st_procpid = MyProcPid;
2150 beentry->st_proc_start_timestamp = proc_start_timestamp;
2151 beentry->st_activity_start_timestamp = 0;
2152 beentry->st_xact_start_timestamp = 0;
2153 beentry->st_databaseid = MyDatabaseId;
2154 beentry->st_userid = userid;
2155 beentry->st_clientaddr = clientaddr;
2156 beentry->st_waiting = false;
2157 beentry->st_activity[0] = '\0';
2158 /* Also make sure the last byte in the string area is always 0 */
2159 beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2161 beentry->st_changecount++;
2162 Assert((beentry->st_changecount & 1) == 0);
2166 * Shut down a single backend's statistics reporting at process exit.
2168 * Flush any remaining statistics counts out to the collector.
2169 * Without this, operations triggered during backend exit (such as
2170 * temp table deletions) won't be counted.
2172 * Lastly, clear out our entry in the PgBackendStatus array.
2175 pgstat_beshutdown_hook(int code, Datum arg)
2177 volatile PgBackendStatus *beentry = MyBEEntry;
2179 pgstat_report_stat(true);
2182 * Clear my status entry, following the protocol of bumping st_changecount
2183 * before and after. We use a volatile pointer here to ensure the
2184 * compiler doesn't try to get cute.
2186 beentry->st_changecount++;
2188 beentry->st_procpid = 0; /* mark invalid */
2190 beentry->st_changecount++;
2191 Assert((beentry->st_changecount & 1) == 0);
2196 * pgstat_report_activity() -
2198 * Called from tcop/postgres.c to report what the backend is actually doing
2199 * (usually "<IDLE>" or the start of the query to be executed).
2203 pgstat_report_activity(const char *cmd_str)
2205 volatile PgBackendStatus *beentry = MyBEEntry;
2206 TimestampTz start_timestamp;
2209 TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
2211 if (!pgstat_track_activities || !beentry)
2215 * To minimize the time spent modifying the entry, fetch all the needed
2218 start_timestamp = GetCurrentStatementStartTimestamp();
2220 len = strlen(cmd_str);
2221 len = pg_mbcliplen(cmd_str, len, pgstat_track_activity_query_size - 1);
2224 * Update my status entry, following the protocol of bumping
2225 * st_changecount before and after. We use a volatile pointer here to
2226 * ensure the compiler doesn't try to get cute.
2228 beentry->st_changecount++;
2230 beentry->st_activity_start_timestamp = start_timestamp;
2231 memcpy((char *) beentry->st_activity, cmd_str, len);
2232 beentry->st_activity[len] = '\0';
2234 beentry->st_changecount++;
2235 Assert((beentry->st_changecount & 1) == 0);
2239 * Report current transaction start timestamp as the specified value.
2240 * Zero means there is no active transaction.
2243 pgstat_report_xact_timestamp(TimestampTz tstamp)
2245 volatile PgBackendStatus *beentry = MyBEEntry;
2247 if (!pgstat_track_activities || !beentry)
2251 * Update my status entry, following the protocol of bumping
2252 * st_changecount before and after. We use a volatile pointer here to
2253 * ensure the compiler doesn't try to get cute.
2255 beentry->st_changecount++;
2256 beentry->st_xact_start_timestamp = tstamp;
2257 beentry->st_changecount++;
2258 Assert((beentry->st_changecount & 1) == 0);
2262 * pgstat_report_waiting() -
2264 * Called from lock manager to report beginning or end of a lock wait.
2266 * NB: this *must* be able to survive being called before MyBEEntry has been
2271 pgstat_report_waiting(bool waiting)
2273 volatile PgBackendStatus *beentry = MyBEEntry;
2275 if (!pgstat_track_activities || !beentry)
2279 * Since this is a single-byte field in a struct that only this process
2280 * may modify, there seems no need to bother with the st_changecount
2281 * protocol. The update must appear atomic in any case.
2283 beentry->st_waiting = waiting;
2288 * pgstat_read_current_status() -
2290 * Copy the current contents of the PgBackendStatus array to local memory,
2291 * if not already done in this transaction.
2295 pgstat_read_current_status(void)
2297 volatile PgBackendStatus *beentry;
2298 PgBackendStatus *localtable;
2299 PgBackendStatus *localentry;
2300 char *localactivity;
2303 Assert(!pgStatRunningInCollector);
2304 if (localBackendStatusTable)
2305 return; /* already done */
2307 pgstat_setup_memcxt();
2309 localtable = (PgBackendStatus *)
2310 MemoryContextAlloc(pgStatLocalContext,
2311 sizeof(PgBackendStatus) * MaxBackends);
2312 localactivity = (char *)
2313 MemoryContextAlloc(pgStatLocalContext,
2314 pgstat_track_activity_query_size * MaxBackends);
2315 localNumBackends = 0;
2317 beentry = BackendStatusArray;
2318 localentry = localtable;
2319 for (i = 1; i <= MaxBackends; i++)
2322 * Follow the protocol of retrying if st_changecount changes while we
2323 * copy the entry, or if it's odd. (The check for odd is needed to
2324 * cover the case where we are able to completely copy the entry while
2325 * the source backend is between increment steps.) We use a volatile
2326 * pointer here to ensure the compiler doesn't try to get cute.
2330 int save_changecount = beentry->st_changecount;
2332 localentry->st_procpid = beentry->st_procpid;
2333 if (localentry->st_procpid > 0)
2335 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2337 * strcpy is safe even if the string is modified concurrently,
2338 * because there's always a \0 at the end of the buffer.
2340 strcpy(localactivity, (char *) beentry->st_activity);
2341 localentry->st_activity = localactivity;
2344 if (save_changecount == beentry->st_changecount &&
2345 (save_changecount & 1) == 0)
2348 /* Make sure we can break out of loop if stuck... */
2349 CHECK_FOR_INTERRUPTS();
2353 /* Only valid entries get included into the local array */
2354 if (localentry->st_procpid > 0)
2357 localactivity += pgstat_track_activity_query_size;
2362 /* Set the pointer only after completion of a valid table */
2363 localBackendStatusTable = localtable;
2368 * pgstat_get_backend_current_activity() -
2370 * Return a string representing the current activity of the backend with
2371 * the specified PID. This looks directly at the BackendStatusArray,
2372 * and so will provide current information regardless of the age of our
2373 * transaction's snapshot of the status array.
2375 * It is the caller's responsibility to invoke this only for backends whose
2376 * state is expected to remain stable while the result is in use. The
2377 * only current use is in deadlock reporting, where we can expect that
2378 * the target backend is blocked on a lock. (There are corner cases
2379 * where the target's wait could get aborted while we are looking at it,
2380 * but the very worst consequence is to return a pointer to a string
2381 * that's been changed, so we won't worry too much.)
2383 * Note: return strings for special cases match pg_stat_get_backend_activity.
2387 pgstat_get_backend_current_activity(int pid, bool checkUser)
2389 PgBackendStatus *beentry;
2392 beentry = BackendStatusArray;
2393 for (i = 1; i <= MaxBackends; i++)
2396 * Although we expect the target backend's entry to be stable, that
2397 * doesn't imply that anyone else's is. To avoid identifying the
2398 * wrong backend, while we check for a match to the desired PID we
2399 * must follow the protocol of retrying if st_changecount changes
2400 * while we examine the entry, or if it's odd. (This might be
2401 * unnecessary, since fetching or storing an int is almost certainly
2402 * atomic, but let's play it safe.) We use a volatile pointer here
2403 * to ensure the compiler doesn't try to get cute.
2405 volatile PgBackendStatus *vbeentry = beentry;
2410 int save_changecount = vbeentry->st_changecount;
2412 found = (vbeentry->st_procpid == pid);
2414 if (save_changecount == vbeentry->st_changecount &&
2415 (save_changecount & 1) == 0)
2418 /* Make sure we can break out of loop if stuck... */
2419 CHECK_FOR_INTERRUPTS();
2424 /* Now it is safe to use the non-volatile pointer */
2425 if (checkUser && !superuser() && beentry->st_userid != GetUserId())
2426 return "<insufficient privilege>";
2427 else if (*(beentry->st_activity) == '\0')
2428 return "<command string not enabled>";
2430 return beentry->st_activity;
2436 /* If we get here, caller is in error ... */
2437 return "<backend information not available>";
2441 /* ------------------------------------------------------------
2442 * Local support functions follow
2443 * ------------------------------------------------------------
2448 * pgstat_setheader() -
2450 * Set common header fields in a statistics message
2454 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2456 hdr->m_type = mtype;
2463 * Send out one statistics message to the collector
2467 pgstat_send(void *msg, int len)
2474 ((PgStat_MsgHdr *) msg)->m_size = len;
2476 /* We'll retry after EINTR, but ignore all other failures */
2479 rc = send(pgStatSock, msg, len, 0);
2480 } while (rc < 0 && errno == EINTR);
2482 #ifdef USE_ASSERT_CHECKING
2483 /* In debug builds, log send failures ... */
2485 elog(LOG, "could not send to statistics collector: %m");
2490 * pgstat_send_bgwriter() -
2492 * Send bgwriter statistics to the collector
2496 pgstat_send_bgwriter(void)
2498 /* We assume this initializes to zeroes */
2499 static const PgStat_MsgBgWriter all_zeroes;
2502 * This function can be called even if nothing at all has happened. In
2503 * this case, avoid sending a completely empty message to the stats
2506 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2510 * Prepare and send the message
2512 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2513 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2516 * Clear out the statistics buffer, so it can be re-used.
2518 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2523 * PgstatCollectorMain() -
2525 * Start up the statistics collector process. This is the body of the
2526 * postmaster child process.
2528 * The argc/argv parameters are valid only in EXEC_BACKEND case.
2531 NON_EXEC_STATIC void
2532 PgstatCollectorMain(int argc, char *argv[])
2534 struct itimerval write_timeout;
2535 bool need_timer = false;
2541 struct pollfd input_fd;
2543 struct timeval sel_timeout;
2548 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2550 MyProcPid = getpid(); /* reset MyProcPid */
2552 MyStartTime = time(NULL); /* record Start Time for logging */
2555 * If possible, make this process a group leader, so that the postmaster
2556 * can signal any child processes too. (pgstat probably never has any
2557 * child processes, but for consistency we make all postmaster child
2558 * processes do this.)
2562 elog(FATAL, "setsid() failed: %m");
2566 * Ignore all signals usually bound to some action in the postmaster,
2567 * except SIGQUIT and SIGALRM.
2569 pqsignal(SIGHUP, SIG_IGN);
2570 pqsignal(SIGINT, SIG_IGN);
2571 pqsignal(SIGTERM, SIG_IGN);
2572 pqsignal(SIGQUIT, pgstat_exit);
2573 pqsignal(SIGALRM, force_statwrite);
2574 pqsignal(SIGPIPE, SIG_IGN);
2575 pqsignal(SIGUSR1, SIG_IGN);
2576 pqsignal(SIGUSR2, SIG_IGN);
2577 pqsignal(SIGCHLD, SIG_DFL);
2578 pqsignal(SIGTTIN, SIG_DFL);
2579 pqsignal(SIGTTOU, SIG_DFL);
2580 pqsignal(SIGCONT, SIG_DFL);
2581 pqsignal(SIGWINCH, SIG_DFL);
2582 PG_SETMASK(&UnBlockSig);
2585 * Identify myself via ps
2587 init_ps_display("stats collector process", "", "", "");
2590 * Arrange to write the initial status file right away
2592 need_statwrite = true;
2594 /* Preset the delay between status file writes */
2595 MemSet(&write_timeout, 0, sizeof(struct itimerval));
2596 write_timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
2597 write_timeout.it_value.tv_usec = (PGSTAT_STAT_INTERVAL % 1000) * 1000;
2600 * Read in an existing statistics stats file or initialize the stats to
2603 pgStatRunningInCollector = true;
2604 pgStatDBHash = pgstat_read_statsfile(InvalidOid, true);
2607 * Setup the descriptor set for select(2). Since only one bit in the set
2608 * ever changes, we need not repeat FD_ZERO each time.
2610 #if !defined(HAVE_POLL) && !defined(WIN32)
2615 * Loop to process messages until we get SIGQUIT or detect ungraceful
2616 * death of our parent postmaster.
2618 * For performance reasons, we don't want to do a PostmasterIsAlive() test
2619 * after every message; instead, do it at statwrite time and if
2620 * select()/poll() is interrupted by timeout.
2627 * Quit if we get SIGQUIT from the postmaster.
2633 * If time to write the stats file, do so. Note that the alarm
2634 * interrupt isn't re-enabled immediately, but only after we next
2635 * receive a stats message; so no cycles are wasted when there is
2640 /* Check for postmaster death; if so we'll write file below */
2641 if (!PostmasterIsAlive(true))
2644 pgstat_write_statsfile(false);
2645 need_statwrite = false;
2650 * Wait for a message to arrive; but not for more than
2651 * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2652 * shut down after an ungraceful postmaster termination; so it needn't
2653 * be very fast. However, on some systems SIGQUIT won't interrupt the
2654 * poll/select call, so this also limits speed of response to SIGQUIT,
2655 * which is more important.)
2657 * We use poll(2) if available, otherwise select(2). Win32 has its own
2662 input_fd.fd = pgStatSock;
2663 input_fd.events = POLLIN | POLLERR;
2664 input_fd.revents = 0;
2666 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2671 (errcode_for_socket_access(),
2672 errmsg("poll() failed in statistics collector: %m")));
2675 got_data = (input_fd.revents != 0);
2676 #else /* !HAVE_POLL */
2678 FD_SET(pgStatSock, &rfds);
2681 * timeout struct is modified by select() on some operating systems,
2682 * so re-fill it each time.
2684 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2685 sel_timeout.tv_usec = 0;
2687 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2692 (errcode_for_socket_access(),
2693 errmsg("select() failed in statistics collector: %m")));
2696 got_data = FD_ISSET(pgStatSock, &rfds);
2697 #endif /* HAVE_POLL */
2699 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2700 PGSTAT_SELECT_TIMEOUT * 1000);
2704 * If there is a message on the socket, read it and check for
2709 len = recv(pgStatSock, (char *) &msg,
2710 sizeof(PgStat_Msg), 0);
2716 (errcode_for_socket_access(),
2717 errmsg("could not read statistics message: %m")));
2721 * We ignore messages that are smaller than our common header
2723 if (len < sizeof(PgStat_MsgHdr))
2727 * The received length must match the length in the header
2729 if (msg.msg_hdr.m_size != len)
2733 * O.K. - we accept this message. Process it.
2735 switch (msg.msg_hdr.m_type)
2737 case PGSTAT_MTYPE_DUMMY:
2740 case PGSTAT_MTYPE_TABSTAT:
2741 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
2744 case PGSTAT_MTYPE_TABPURGE:
2745 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
2748 case PGSTAT_MTYPE_DROPDB:
2749 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
2752 case PGSTAT_MTYPE_RESETCOUNTER:
2753 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
2757 case PGSTAT_MTYPE_AUTOVAC_START:
2758 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
2761 case PGSTAT_MTYPE_VACUUM:
2762 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
2765 case PGSTAT_MTYPE_ANALYZE:
2766 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
2769 case PGSTAT_MTYPE_BGWRITER:
2770 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
2773 case PGSTAT_MTYPE_FUNCSTAT:
2774 pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
2777 case PGSTAT_MTYPE_FUNCPURGE:
2778 pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
2786 * If this is the first message after we wrote the stats file the
2787 * last time, enable the alarm interrupt to make it be written
2792 if (setitimer(ITIMER_REAL, &write_timeout, NULL))
2794 (errmsg("could not set statistics collector timer: %m")));
2801 * We can only get here if the select/poll timeout elapsed. Check
2802 * for postmaster death.
2804 if (!PostmasterIsAlive(true))
2807 } /* end of message-processing loop */
2810 * Save the final stats to reuse at next startup.
2812 pgstat_write_statsfile(true);
2818 /* SIGQUIT signal handler for collector process */
2820 pgstat_exit(SIGNAL_ARGS)
2825 /* SIGALRM signal handler for collector process */
2827 force_statwrite(SIGNAL_ARGS)
2829 need_statwrite = true;
2834 * Lookup the hash table entry for the specified database. If no hash
2835 * table entry exists, initialize it, if the create parameter is true.
2836 * Else, return NULL.
2838 static PgStat_StatDBEntry *
2839 pgstat_get_db_entry(Oid databaseid, bool create)
2841 PgStat_StatDBEntry *result;
2843 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
2845 /* Lookup or create the hash table entry for this database */
2846 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2850 if (!create && !found)
2853 /* If not found, initialize the new one. */
2858 result->tables = NULL;
2859 result->functions = NULL;
2860 result->n_xact_commit = 0;
2861 result->n_xact_rollback = 0;
2862 result->n_blocks_fetched = 0;
2863 result->n_blocks_hit = 0;
2864 result->n_tuples_returned = 0;
2865 result->n_tuples_fetched = 0;
2866 result->n_tuples_inserted = 0;
2867 result->n_tuples_updated = 0;
2868 result->n_tuples_deleted = 0;
2869 result->last_autovac_time = 0;
2871 memset(&hash_ctl, 0, sizeof(hash_ctl));
2872 hash_ctl.keysize = sizeof(Oid);
2873 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2874 hash_ctl.hash = oid_hash;
2875 result->tables = hash_create("Per-database table",
2876 PGSTAT_TAB_HASH_SIZE,
2878 HASH_ELEM | HASH_FUNCTION);
2880 hash_ctl.keysize = sizeof(Oid);
2881 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
2882 hash_ctl.hash = oid_hash;
2883 result->functions = hash_create("Per-database function",
2884 PGSTAT_FUNCTION_HASH_SIZE,
2886 HASH_ELEM | HASH_FUNCTION);
2894 * pgstat_write_statsfile() -
2897 * If writing to the permanent file (happens when the collector is
2898 * shutting down only), remove the temporary file so that backends
2899 * starting up under a new postmaster can't read the old data before
2900 * the new collector is ready.
2904 pgstat_write_statsfile(bool permanent)
2906 HASH_SEQ_STATUS hstat;
2907 HASH_SEQ_STATUS tstat;
2908 HASH_SEQ_STATUS fstat;
2909 PgStat_StatDBEntry *dbentry;
2910 PgStat_StatTabEntry *tabentry;
2911 PgStat_StatFuncEntry *funcentry;
2914 const char *tmpfile = permanent?PGSTAT_STAT_PERMANENT_TMPFILE:PGSTAT_STAT_TMPFILE;
2915 const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:PGSTAT_STAT_FILENAME;
2918 * Open the statistics temp file to write out the current values.
2920 fpout = fopen(tmpfile, PG_BINARY_W);
2924 (errcode_for_file_access(),
2925 errmsg("could not open temporary statistics file \"%s\": %m",
2931 * Write the file header --- currently just a format ID.
2933 format_id = PGSTAT_FILE_FORMAT_ID;
2934 fwrite(&format_id, sizeof(format_id), 1, fpout);
2937 * Write global stats struct
2939 fwrite(&globalStats, sizeof(globalStats), 1, fpout);
2942 * Walk through the database table.
2944 hash_seq_init(&hstat, pgStatDBHash);
2945 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2948 * Write out the DB entry including the number of live backends. We
2949 * don't write the tables or functions pointers, since they're of
2950 * no use to any other process.
2953 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2956 * Walk through the database's access stats per table.
2958 hash_seq_init(&tstat, dbentry->tables);
2959 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2962 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2966 * Walk through the database's function stats table.
2968 hash_seq_init(&fstat, dbentry->functions);
2969 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
2972 fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
2976 * Mark the end of this DB
2982 * No more output to be done. Close the temp file and replace the old
2983 * pgstat.stat with it. The ferror() check replaces testing for error
2984 * after each individual fputc or fwrite above.
2991 (errcode_for_file_access(),
2992 errmsg("could not write temporary statistics file \"%s\": %m",
2997 else if (fclose(fpout) < 0)
3000 (errcode_for_file_access(),
3001 errmsg("could not close temporary statistics file \"%s\": %m",
3005 else if (rename(tmpfile, statfile) < 0)
3008 (errcode_for_file_access(),
3009 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
3010 tmpfile, statfile)));
3015 unlink(PGSTAT_STAT_FILENAME);
3020 * pgstat_read_statsfile() -
3022 * Reads in an existing statistics collector file and initializes the
3023 * databases' hash table (whose entries point to the tables' hash tables).
3027 pgstat_read_statsfile(Oid onlydb, bool permanent)
3029 PgStat_StatDBEntry *dbentry;
3030 PgStat_StatDBEntry dbbuf;
3031 PgStat_StatTabEntry *tabentry;
3032 PgStat_StatTabEntry tabbuf;
3033 PgStat_StatFuncEntry funcbuf;
3034 PgStat_StatFuncEntry *funcentry;
3037 HTAB *tabhash = NULL;
3038 HTAB *funchash = NULL;
3042 const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:PGSTAT_STAT_FILENAME;
3045 * The tables will live in pgStatLocalContext.
3047 pgstat_setup_memcxt();
3050 * Create the DB hashtable
3052 memset(&hash_ctl, 0, sizeof(hash_ctl));
3053 hash_ctl.keysize = sizeof(Oid);
3054 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
3055 hash_ctl.hash = oid_hash;
3056 hash_ctl.hcxt = pgStatLocalContext;
3057 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
3058 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3061 * Clear out global statistics so they start from zero in case we can't
3062 * load an existing statsfile.
3064 memset(&globalStats, 0, sizeof(globalStats));
3067 * Try to open the status file. If it doesn't exist, the backends simply
3068 * return zero for anything and the collector simply starts from scratch
3069 * with empty counters.
3071 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3075 * Verify it's of the expected format.
3077 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3078 || format_id != PGSTAT_FILE_FORMAT_ID)
3080 ereport(pgStatRunningInCollector ? LOG : WARNING,
3081 (errmsg("corrupted pgstat.stat file")));
3086 * Read global stats struct
3088 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
3090 ereport(pgStatRunningInCollector ? LOG : WARNING,
3091 (errmsg("corrupted pgstat.stat file")));
3096 * We found an existing collector stats file. Read it and put all the
3097 * hashtable entries into place.
3101 switch (fgetc(fpin))
3104 * 'D' A PgStat_StatDBEntry struct describing a database
3105 * follows. Subsequently, zero to many 'T' and 'F' entries
3106 * will follow until a 'd' is encountered.
3109 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
3110 fpin) != offsetof(PgStat_StatDBEntry, tables))
3112 ereport(pgStatRunningInCollector ? LOG : WARNING,
3113 (errmsg("corrupted pgstat.stat file")));
3118 * Add to the DB hash
3120 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
3121 (void *) &dbbuf.databaseid,
3126 ereport(pgStatRunningInCollector ? LOG : WARNING,
3127 (errmsg("corrupted pgstat.stat file")));
3131 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
3132 dbentry->tables = NULL;
3133 dbentry->functions = NULL;
3136 * Don't collect tables if not the requested DB (or the
3137 * shared-table info)
3139 if (onlydb != InvalidOid)
3141 if (dbbuf.databaseid != onlydb &&
3142 dbbuf.databaseid != InvalidOid)
3146 memset(&hash_ctl, 0, sizeof(hash_ctl));
3147 hash_ctl.keysize = sizeof(Oid);
3148 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3149 hash_ctl.hash = oid_hash;
3150 hash_ctl.hcxt = pgStatLocalContext;
3151 dbentry->tables = hash_create("Per-database table",
3152 PGSTAT_TAB_HASH_SIZE,
3154 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3156 hash_ctl.keysize = sizeof(Oid);
3157 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3158 hash_ctl.hash = oid_hash;
3159 hash_ctl.hcxt = pgStatLocalContext;
3160 dbentry->functions = hash_create("Per-database function",
3161 PGSTAT_FUNCTION_HASH_SIZE,
3163 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3165 * Arrange that following records add entries to this
3166 * database's hash tables.
3168 tabhash = dbentry->tables;
3169 funchash = dbentry->functions;
3173 * 'd' End of this database.
3181 * 'T' A PgStat_StatTabEntry follows.
3184 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
3185 fpin) != sizeof(PgStat_StatTabEntry))
3187 ereport(pgStatRunningInCollector ? LOG : WARNING,
3188 (errmsg("corrupted pgstat.stat file")));
3193 * Skip if table belongs to a not requested database.
3195 if (tabhash == NULL)
3198 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
3199 (void *) &tabbuf.tableid,
3200 HASH_ENTER, &found);
3204 ereport(pgStatRunningInCollector ? LOG : WARNING,
3205 (errmsg("corrupted pgstat.stat file")));
3209 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
3213 * 'F' A PgStat_StatFuncEntry follows.
3216 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
3217 fpin) != sizeof(PgStat_StatFuncEntry))
3219 ereport(pgStatRunningInCollector ? LOG : WARNING,
3220 (errmsg("corrupted pgstat.stat file")));
3225 * Skip if function belongs to a not requested database.
3227 if (funchash == NULL)
3230 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
3231 (void *) &funcbuf.functionid,
3232 HASH_ENTER, &found);
3236 ereport(pgStatRunningInCollector ? LOG : WARNING,
3237 (errmsg("corrupted pgstat.stat file")));
3241 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
3245 * 'E' The EOF marker of a complete stats file.
3251 ereport(pgStatRunningInCollector ? LOG : WARNING,
3252 (errmsg("corrupted pgstat.stat file")));
3261 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
3267 * If not already done, read the statistics collector stats file into
3268 * some hash tables. The results will be kept until pgstat_clear_snapshot()
3269 * is called (typically, at end of transaction).
3272 backend_read_statsfile(void)
3274 /* already read it? */
3277 Assert(!pgStatRunningInCollector);
3279 /* Autovacuum launcher wants stats about all databases */
3280 if (IsAutoVacuumLauncherProcess())
3281 pgStatDBHash = pgstat_read_statsfile(InvalidOid, false);
3283 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId, false);
3288 * pgstat_setup_memcxt() -
3290 * Create pgStatLocalContext, if not already done.
3294 pgstat_setup_memcxt(void)
3296 if (!pgStatLocalContext)
3297 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
3298 "Statistics snapshot",
3299 ALLOCSET_SMALL_MINSIZE,
3300 ALLOCSET_SMALL_INITSIZE,
3301 ALLOCSET_SMALL_MAXSIZE);
3306 * pgstat_clear_snapshot() -
3308 * Discard any data collected in the current transaction. Any subsequent
3309 * request will cause new snapshots to be read.
3311 * This is also invoked during transaction commit or abort to discard
3312 * the no-longer-wanted snapshot.
3316 pgstat_clear_snapshot(void)
3318 /* Release memory, if any was allocated */
3319 if (pgStatLocalContext)
3320 MemoryContextDelete(pgStatLocalContext);
3322 /* Reset variables */
3323 pgStatLocalContext = NULL;
3324 pgStatDBHash = NULL;
3325 localBackendStatusTable = NULL;
3326 localNumBackends = 0;
3331 * pgstat_recv_tabstat() -
3333 * Count what the backend has done.
3337 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
3339 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
3340 PgStat_StatDBEntry *dbentry;
3341 PgStat_StatTabEntry *tabentry;
3345 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3348 * Update database-wide stats.
3350 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
3351 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
3354 * Process all table entries in the message.
3356 for (i = 0; i < msg->m_nentries; i++)
3358 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3359 (void *) &(tabmsg[i].t_id),
3360 HASH_ENTER, &found);
3365 * If it's a new table entry, initialize counters to the values we
3368 tabentry->numscans = tabmsg[i].t_counts.t_numscans;
3369 tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
3370 tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
3371 tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
3372 tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
3373 tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
3374 tabentry->tuples_hot_updated = tabmsg[i].t_counts.t_tuples_hot_updated;
3375 tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
3376 tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
3377 tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
3378 tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
3380 tabentry->last_anl_tuples = 0;
3381 tabentry->vacuum_timestamp = 0;
3382 tabentry->autovac_vacuum_timestamp = 0;
3383 tabentry->analyze_timestamp = 0;
3384 tabentry->autovac_analyze_timestamp = 0;
3389 * Otherwise add the values to the existing entry.
3391 tabentry->numscans += tabmsg[i].t_counts.t_numscans;
3392 tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
3393 tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
3394 tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
3395 tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
3396 tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
3397 tabentry->tuples_hot_updated += tabmsg[i].t_counts.t_tuples_hot_updated;
3398 tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
3399 tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
3400 tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
3401 tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
3404 /* Clamp n_live_tuples in case of negative new_live_tuples */
3405 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
3406 /* Likewise for n_dead_tuples */
3407 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
3410 * Add per-table stats to the per-database entry, too.
3412 dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
3413 dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
3414 dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
3415 dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
3416 dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
3417 dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
3418 dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
3424 * pgstat_recv_tabpurge() -
3426 * Arrange for dead table removal.
3430 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3432 PgStat_StatDBEntry *dbentry;
3435 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3438 * No need to purge if we don't even know the database.
3440 if (!dbentry || !dbentry->tables)
3444 * Process all table entries in the message.
3446 for (i = 0; i < msg->m_nentries; i++)
3448 /* Remove from hashtable if present; we don't care if it's not. */
3449 (void) hash_search(dbentry->tables,
3450 (void *) &(msg->m_tableid[i]),
3457 * pgstat_recv_dropdb() -
3459 * Arrange for dead database removal
3463 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3465 PgStat_StatDBEntry *dbentry;
3468 * Lookup the database in the hashtable.
3470 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3473 * If found, remove it.
3477 if (dbentry->tables != NULL)
3478 hash_destroy(dbentry->tables);
3479 if (dbentry->functions != NULL)
3480 hash_destroy(dbentry->functions);
3482 if (hash_search(pgStatDBHash,
3483 (void *) &(dbentry->databaseid),
3484 HASH_REMOVE, NULL) == NULL)
3486 (errmsg("database hash table corrupted "
3487 "during cleanup --- abort")));
3493 * pgstat_recv_resetcounter() -
3495 * Reset the statistics for the specified database.
3499 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3502 PgStat_StatDBEntry *dbentry;
3505 * Lookup the database in the hashtable. Nothing to do if not there.
3507 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3513 * We simply throw away all the database's table entries by recreating a
3514 * new hash table for them.
3516 if (dbentry->tables != NULL)
3517 hash_destroy(dbentry->tables);
3518 if (dbentry->functions != NULL)
3519 hash_destroy(dbentry->functions);
3521 dbentry->tables = NULL;
3522 dbentry->functions = NULL;
3523 dbentry->n_xact_commit = 0;
3524 dbentry->n_xact_rollback = 0;
3525 dbentry->n_blocks_fetched = 0;
3526 dbentry->n_blocks_hit = 0;
3528 memset(&hash_ctl, 0, sizeof(hash_ctl));
3529 hash_ctl.keysize = sizeof(Oid);
3530 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3531 hash_ctl.hash = oid_hash;
3532 dbentry->tables = hash_create("Per-database table",
3533 PGSTAT_TAB_HASH_SIZE,
3535 HASH_ELEM | HASH_FUNCTION);
3537 hash_ctl.keysize = sizeof(Oid);
3538 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3539 hash_ctl.hash = oid_hash;
3540 dbentry->functions = hash_create("Per-database function",
3541 PGSTAT_FUNCTION_HASH_SIZE,
3543 HASH_ELEM | HASH_FUNCTION);
3547 * pgstat_recv_autovac() -
3549 * Process an autovacuum signalling message.
3553 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
3555 PgStat_StatDBEntry *dbentry;
3558 * Lookup the database in the hashtable. Don't create the entry if it
3559 * doesn't exist, because autovacuum may be processing a template
3560 * database. If this isn't the case, the database is most likely to have
3561 * an entry already. (If it doesn't, not much harm is done anyway --
3562 * it'll get created as soon as somebody actually uses the database.)
3564 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3565 if (dbentry == NULL)
3569 * Store the last autovacuum time in the database entry.
3571 dbentry->last_autovac_time = msg->m_start_time;
3575 * pgstat_recv_vacuum() -
3577 * Process a VACUUM message.
3581 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
3583 PgStat_StatDBEntry *dbentry;
3584 PgStat_StatTabEntry *tabentry;
3587 * Don't create either the database or table entry if it doesn't already
3588 * exist. This avoids bloating the stats with entries for stuff that is
3589 * only touched by vacuum and not by live operations.
3591 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3592 if (dbentry == NULL)
3595 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3597 if (tabentry == NULL)
3600 if (msg->m_autovacuum)
3601 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
3603 tabentry->vacuum_timestamp = msg->m_vacuumtime;
3604 tabentry->n_live_tuples = msg->m_tuples;
3605 /* Resetting dead_tuples to 0 is an approximation ... */
3606 tabentry->n_dead_tuples = 0;
3609 tabentry->last_anl_tuples = msg->m_tuples;
3610 if (msg->m_autovacuum)
3611 tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
3613 tabentry->analyze_timestamp = msg->m_vacuumtime;
3617 /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
3618 tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
3624 * pgstat_recv_analyze() -
3626 * Process an ANALYZE message.
3630 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
3632 PgStat_StatDBEntry *dbentry;
3633 PgStat_StatTabEntry *tabentry;
3636 * Don't create either the database or table entry if it doesn't already
3637 * exist. This avoids bloating the stats with entries for stuff that is
3638 * only touched by analyze and not by live operations.
3640 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3641 if (dbentry == NULL)
3644 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3646 if (tabentry == NULL)
3649 if (msg->m_autovacuum)
3650 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
3652 tabentry->analyze_timestamp = msg->m_analyzetime;
3653 tabentry->n_live_tuples = msg->m_live_tuples;
3654 tabentry->n_dead_tuples = msg->m_dead_tuples;
3655 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
3660 * pgstat_recv_bgwriter() -
3662 * Process a BGWRITER message.
3666 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
3668 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
3669 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
3670 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
3671 globalStats.buf_written_clean += msg->m_buf_written_clean;
3672 globalStats.maxwritten_clean += msg->m_maxwritten_clean;
3673 globalStats.buf_written_backend += msg->m_buf_written_backend;
3674 globalStats.buf_alloc += msg->m_buf_alloc;
3678 * pgstat_recv_funcstat() -
3680 * Count what the backend has done.
3684 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
3686 PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
3687 PgStat_StatDBEntry *dbentry;
3688 PgStat_StatFuncEntry *funcentry;
3692 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3695 * Process all function entries in the message.
3697 for (i = 0; i < msg->m_nentries; i++, funcmsg++)
3699 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
3700 (void *) &(funcmsg->f_id),
3701 HASH_ENTER, &found);
3706 * If it's a new function entry, initialize counters to the values
3709 funcentry->f_numcalls = funcmsg->f_numcalls;
3710 funcentry->f_time = funcmsg->f_time;
3711 funcentry->f_time_self = funcmsg->f_time_self;
3716 * Otherwise add the values to the existing entry.
3718 funcentry->f_numcalls += funcmsg->f_numcalls;
3719 funcentry->f_time += funcmsg->f_time;
3720 funcentry->f_time_self += funcmsg->f_time_self;
3726 * pgstat_recv_funcpurge() -
3728 * Arrange for dead function removal.
3732 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
3734 PgStat_StatDBEntry *dbentry;
3737 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3740 * No need to purge if we don't even know the database.
3742 if (!dbentry || !dbentry->functions)
3746 * Process all function entries in the message.
3748 for (i = 0; i < msg->m_nentries; i++)
3750 /* Remove from hashtable if present; we don't care if it's not. */
3751 (void) hash_search(dbentry->functions,
3752 (void *) &(msg->m_functionid[i]),