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-2007, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.161 2007/07/08 22:23:16 tgl 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"
46 #include "libpq/libpq.h"
47 #include "libpq/pqsignal.h"
48 #include "mb/pg_wchar.h"
49 #include "miscadmin.h"
50 #include "postmaster/autovacuum.h"
51 #include "postmaster/fork_process.h"
52 #include "postmaster/postmaster.h"
53 #include "storage/backendid.h"
54 #include "storage/fd.h"
55 #include "storage/ipc.h"
56 #include "storage/pg_shmem.h"
57 #include "storage/pmsignal.h"
58 #include "utils/memutils.h"
59 #include "utils/ps_status.h"
63 * Paths for the statistics files (relative to installation's $PGDATA).
66 #define PGSTAT_STAT_FILENAME "global/pgstat.stat"
67 #define PGSTAT_STAT_TMPFILE "global/pgstat.tmp"
73 #define PGSTAT_STAT_INTERVAL 500 /* How often to write the status file;
76 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart a
77 * failed statistics collector; in
80 #define PGSTAT_SELECT_TIMEOUT 2 /* How often to check for postmaster
81 * death; in seconds. */
85 * The initial size hints for the hash tables used in the collector.
88 #define PGSTAT_DB_HASH_SIZE 16
89 #define PGSTAT_TAB_HASH_SIZE 512
96 bool pgstat_collect_startcollector = true;
97 bool pgstat_collect_resetonpmstart = false;
98 bool pgstat_collect_tuplelevel = false;
99 bool pgstat_collect_blocklevel = false;
100 bool pgstat_collect_querystring = false;
103 * BgWriter global statistics counters (unused in other processes).
104 * Stored directly in a stats message structure so it can be sent
105 * without needing to copy things around. We assume this inits to zeroes.
107 PgStat_MsgBgWriter BgWriterStats;
113 NON_EXEC_STATIC int pgStatSock = -1;
115 static struct sockaddr_storage pgStatAddr;
117 static time_t last_pgstat_start_time;
119 static bool pgStatRunningInCollector = false;
122 * Structures in which backends store per-table info that's waiting to be
123 * sent to the collector.
125 * NOTE: once allocated, TabStatusArray structures are never moved or deleted
126 * for the life of the backend. Also, we zero out the t_id fields of the
127 * contained PgStat_TableStatus structs whenever they are not actively in use.
128 * This allows relcache pgstat_info pointers to be treated as long-lived data,
129 * avoiding repeated searches in pgstat_initstats() when a relation is
130 * repeatedly opened during a transaction.
132 #define TABSTAT_QUANTUM 100 /* we alloc this many at a time */
134 typedef struct TabStatusArray
136 struct TabStatusArray *tsa_next; /* link to next array, if any */
137 int tsa_used; /* # entries currently used */
138 PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */
141 static TabStatusArray *pgStatTabList = NULL;
144 * Tuple insertion/deletion counts for an open transaction can't be propagated
145 * into PgStat_TableStatus counters until we know if it is going to commit
146 * or abort. Hence, we keep these counts in per-subxact structs that live
147 * in TopTransactionContext. This data structure is designed on the assumption
148 * that subxacts won't usually modify very many tables.
150 typedef struct PgStat_SubXactStatus
152 int nest_level; /* subtransaction nest level */
153 struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
154 PgStat_TableXactStatus *first; /* head of list for this subxact */
155 } PgStat_SubXactStatus;
157 static PgStat_SubXactStatus *pgStatXactStack = NULL;
159 static int pgStatXactCommit = 0;
160 static int pgStatXactRollback = 0;
162 /* Record that's written to 2PC state file when pgstat state is persisted */
163 typedef struct TwoPhasePgStatRecord
165 PgStat_Counter tuples_inserted; /* tuples inserted in xact */
166 PgStat_Counter tuples_deleted; /* tuples deleted in xact */
167 Oid t_id; /* table's OID */
168 bool t_shared; /* is it a shared catalog? */
169 } TwoPhasePgStatRecord;
172 * Info about current "snapshot" of stats file
174 static MemoryContext pgStatLocalContext = NULL;
175 static HTAB *pgStatDBHash = NULL;
176 static PgBackendStatus *localBackendStatusTable = NULL;
177 static int localNumBackends = 0;
180 * Cluster wide statistics, kept in the stats collector.
181 * Contains statistics that are not collected per database
184 static PgStat_GlobalStats globalStats;
186 static volatile bool need_exit = false;
187 static volatile bool need_statwrite = false;
191 * Local function forward declarations
195 static pid_t pgstat_forkexec(void);
198 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
199 static void pgstat_exit(SIGNAL_ARGS);
200 static void force_statwrite(SIGNAL_ARGS);
201 static void pgstat_beshutdown_hook(int code, Datum arg);
203 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
204 static void pgstat_write_statsfile(void);
205 static HTAB *pgstat_read_statsfile(Oid onlydb);
206 static void backend_read_statsfile(void);
207 static void pgstat_read_current_status(void);
209 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
210 static HTAB *pgstat_collect_oids(Oid catalogid);
212 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
214 static void pgstat_setup_memcxt(void);
216 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
217 static void pgstat_send(void *msg, int len);
219 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
220 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
221 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
222 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
223 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
224 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
225 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
226 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
229 /* ------------------------------------------------------------
230 * Public functions called from postmaster follow
231 * ------------------------------------------------------------
237 * Called from postmaster at startup. Create the resources required
238 * by the statistics collector process. If unable to do so, do not
239 * fail --- better to let the postmaster start with stats collection
246 ACCEPT_TYPE_ARG3 alen;
247 struct addrinfo *addrs = NULL,
257 #define TESTBYTEVAL ((char) 199)
260 * Force start of collector daemon if something to collect. Note that
261 * pgstat_collect_querystring is now an independent facility that does not
262 * require the collector daemon.
264 if (pgstat_collect_tuplelevel ||
265 pgstat_collect_blocklevel)
266 pgstat_collect_startcollector = true;
269 * If we don't have to start a collector or should reset the collected
270 * statistics on postmaster start, simply remove the stats file.
272 if (!pgstat_collect_startcollector || pgstat_collect_resetonpmstart)
276 * Nothing else required if collector will not get started
278 if (!pgstat_collect_startcollector)
282 * Create the UDP socket for sending and receiving statistic messages
284 hints.ai_flags = AI_PASSIVE;
285 hints.ai_family = PF_UNSPEC;
286 hints.ai_socktype = SOCK_DGRAM;
287 hints.ai_protocol = 0;
288 hints.ai_addrlen = 0;
289 hints.ai_addr = NULL;
290 hints.ai_canonname = NULL;
291 hints.ai_next = NULL;
292 ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
296 (errmsg("could not resolve \"localhost\": %s",
297 gai_strerror(ret))));
302 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
303 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
304 * when kernel will reject IPv6). Worse, the failure may occur at the
305 * bind() or perhaps even connect() stage. So we must loop through the
306 * results till we find a working combination. We will generate LOG
307 * messages, but no error, for bogus combinations.
309 for (addr = addrs; addr; addr = addr->ai_next)
311 #ifdef HAVE_UNIX_SOCKETS
312 /* Ignore AF_UNIX sockets, if any are returned. */
313 if (addr->ai_family == AF_UNIX)
319 (errmsg("trying another address for the statistics collector")));
324 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
327 (errcode_for_socket_access(),
328 errmsg("could not create socket for statistics collector: %m")));
333 * Bind it to a kernel assigned port on localhost and get the assigned
334 * port via getsockname().
336 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
339 (errcode_for_socket_access(),
340 errmsg("could not bind socket for statistics collector: %m")));
341 closesocket(pgStatSock);
346 alen = sizeof(pgStatAddr);
347 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
350 (errcode_for_socket_access(),
351 errmsg("could not get address of socket for statistics collector: %m")));
352 closesocket(pgStatSock);
358 * Connect the socket to its own address. This saves a few cycles by
359 * not having to respecify the target address on every send. This also
360 * provides a kernel-level check that only packets from this same
361 * address will be received.
363 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
366 (errcode_for_socket_access(),
367 errmsg("could not connect socket for statistics collector: %m")));
368 closesocket(pgStatSock);
374 * Try to send and receive a one-byte test message on the socket. This
375 * is to catch situations where the socket can be created but will not
376 * actually pass data (for instance, because kernel packet filtering
379 test_byte = TESTBYTEVAL;
382 if (send(pgStatSock, &test_byte, 1, 0) != 1)
385 goto retry1; /* if interrupted, just retry */
387 (errcode_for_socket_access(),
388 errmsg("could not send test message on socket for statistics collector: %m")));
389 closesocket(pgStatSock);
395 * There could possibly be a little delay before the message can be
396 * received. We arbitrarily allow up to half a second before deciding
399 for (;;) /* need a loop to handle EINTR */
402 FD_SET(pgStatSock, &rset);
405 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
406 if (sel_res >= 0 || errno != EINTR)
412 (errcode_for_socket_access(),
413 errmsg("select() failed in statistics collector: %m")));
414 closesocket(pgStatSock);
418 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
421 * This is the case we actually think is likely, so take pains to
422 * give a specific message for it.
424 * errno will not be set meaningfully here, so don't use it.
427 (errcode(ERRCODE_CONNECTION_FAILURE),
428 errmsg("test message did not get through on socket for statistics collector")));
429 closesocket(pgStatSock);
434 test_byte++; /* just make sure variable is changed */
437 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
440 goto retry2; /* if interrupted, just retry */
442 (errcode_for_socket_access(),
443 errmsg("could not receive test message on socket for statistics collector: %m")));
444 closesocket(pgStatSock);
449 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
452 (errcode(ERRCODE_INTERNAL_ERROR),
453 errmsg("incorrect test message transmission on socket for statistics collector")));
454 closesocket(pgStatSock);
459 /* If we get here, we have a working socket */
463 /* Did we find a working address? */
464 if (!addr || pgStatSock < 0)
468 * Set the socket to non-blocking IO. This ensures that if the collector
469 * falls behind, statistics messages will be discarded; backends won't
470 * block waiting to send messages to the collector.
472 if (!pg_set_noblock(pgStatSock))
475 (errcode_for_socket_access(),
476 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
480 pg_freeaddrinfo_all(hints.ai_family, addrs);
486 (errmsg("disabling statistics collector for lack of working socket")));
489 pg_freeaddrinfo_all(hints.ai_family, addrs);
492 closesocket(pgStatSock);
495 /* Adjust GUC variables to suppress useless activity */
496 pgstat_collect_startcollector = false;
497 pgstat_collect_tuplelevel = false;
498 pgstat_collect_blocklevel = false;
502 * pgstat_reset_all() -
504 * Remove the stats file. This is used on server start if the
505 * stats_reset_on_server_start feature is enabled, or if WAL
506 * recovery is needed after a crash.
509 pgstat_reset_all(void)
511 unlink(PGSTAT_STAT_FILENAME);
517 * pgstat_forkexec() -
519 * Format up the arglist for, then fork and exec, statistics collector process
522 pgstat_forkexec(void)
527 av[ac++] = "postgres";
528 av[ac++] = "--forkcol";
529 av[ac++] = NULL; /* filled in by postmaster_forkexec */
532 Assert(ac < lengthof(av));
534 return postmaster_forkexec(ac, av);
536 #endif /* EXEC_BACKEND */
542 * Called from postmaster at startup or after an existing collector
543 * died. Attempt to fire up a fresh statistics collector.
545 * Returns PID of child process, or 0 if fail.
547 * Note: if fail, we will be called again from the postmaster main loop.
557 * Do nothing if no collector needed
559 if (!pgstat_collect_startcollector)
563 * Do nothing if too soon since last collector start. This is a safety
564 * valve to protect against continuous respawn attempts if the collector
565 * is dying immediately at launch. Note that since we will be re-called
566 * from the postmaster main loop, we will get another chance later.
568 curtime = time(NULL);
569 if ((unsigned int) (curtime - last_pgstat_start_time) <
570 (unsigned int) PGSTAT_RESTART_INTERVAL)
572 last_pgstat_start_time = curtime;
575 * Check that the socket is there, else pgstat_init failed.
580 (errmsg("statistics collector startup skipped")));
583 * We can only get here if someone tries to manually turn
584 * pgstat_collect_startcollector on after it had been off.
586 pgstat_collect_startcollector = false;
591 * Okay, fork off the collector.
594 switch ((pgStatPid = pgstat_forkexec()))
596 switch ((pgStatPid = fork_process()))
601 (errmsg("could not fork statistics collector: %m")));
606 /* in postmaster child ... */
607 /* Close the postmaster's sockets */
608 ClosePostmasterPorts(false);
610 /* Lose the postmaster's on-exit routines */
613 /* Drop our connection to postmaster's shared memory, as well */
614 PGSharedMemoryDetach();
616 PgstatCollectorMain(0, NULL);
621 return (int) pgStatPid;
624 /* shouldn't get here */
628 void allow_immediate_pgstat_restart(void)
630 last_pgstat_start_time = 0;
633 /* ------------------------------------------------------------
634 * Public functions used by backends follow
635 *------------------------------------------------------------
640 * pgstat_report_tabstat() -
642 * Called from tcop/postgres.c to send the so far collected per-table
643 * access statistics to the collector. Note that this is called only
644 * when not within a transaction, so it is fair to use transaction stop
645 * time as an approximation of current time.
649 pgstat_report_tabstat(bool force)
651 /* we assume this inits to all zeroes: */
652 static const PgStat_TableCounts all_zeroes;
653 static TimestampTz last_report = 0;
656 PgStat_MsgTabstat regular_msg;
657 PgStat_MsgTabstat shared_msg;
661 /* Don't expend a clock check if nothing to do */
662 if (pgStatTabList == NULL ||
663 pgStatTabList->tsa_used == 0)
667 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
668 * msec since we last sent one, or the caller wants to force stats out.
670 now = GetCurrentTransactionStopTimestamp();
672 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
677 * Scan through the TabStatusArray struct(s) to find tables that actually
678 * have counts, and build messages to send. We have to separate shared
679 * relations from regular ones because the databaseid field in the
680 * message header has to depend on that.
682 regular_msg.m_databaseid = MyDatabaseId;
683 shared_msg.m_databaseid = InvalidOid;
684 regular_msg.m_nentries = 0;
685 shared_msg.m_nentries = 0;
687 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
689 for (i = 0; i < tsa->tsa_used; i++)
691 PgStat_TableStatus *entry = &tsa->tsa_entries[i];
692 PgStat_MsgTabstat *this_msg;
693 PgStat_TableEntry *this_ent;
695 /* Shouldn't have any pending transaction-dependent counts */
696 Assert(entry->trans == NULL);
699 * Ignore entries that didn't accumulate any actual counts,
700 * such as indexes that were opened by the planner but not used.
702 if (memcmp(&entry->t_counts, &all_zeroes,
703 sizeof(PgStat_TableCounts)) == 0)
706 * OK, insert data into the appropriate message, and send if full.
708 this_msg = entry->t_shared ? &shared_msg : ®ular_msg;
709 this_ent = &this_msg->m_entry[this_msg->m_nentries];
710 this_ent->t_id = entry->t_id;
711 memcpy(&this_ent->t_counts, &entry->t_counts,
712 sizeof(PgStat_TableCounts));
713 if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
715 pgstat_send_tabstat(this_msg);
716 this_msg->m_nentries = 0;
719 /* zero out TableStatus structs after use */
720 MemSet(tsa->tsa_entries, 0,
721 tsa->tsa_used * sizeof(PgStat_TableStatus));
726 * Send partial messages. If force is true, make sure that any pending
727 * xact commit/abort gets counted, even if no table stats to send.
729 if (regular_msg.m_nentries > 0 ||
730 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
731 pgstat_send_tabstat(®ular_msg);
732 if (shared_msg.m_nentries > 0)
733 pgstat_send_tabstat(&shared_msg);
737 * Subroutine for pgstat_report_tabstat: finish and send a tabstat message
740 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
745 /* It's unlikely we'd get here with no socket, but maybe not impossible */
750 * Report accumulated xact commit/rollback whenever we send a normal
753 if (OidIsValid(tsmsg->m_databaseid))
755 tsmsg->m_xact_commit = pgStatXactCommit;
756 tsmsg->m_xact_rollback = pgStatXactRollback;
757 pgStatXactCommit = 0;
758 pgStatXactRollback = 0;
762 tsmsg->m_xact_commit = 0;
763 tsmsg->m_xact_rollback = 0;
766 n = tsmsg->m_nentries;
767 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
768 n * sizeof(PgStat_TableEntry);
770 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
771 pgstat_send(tsmsg, len);
776 * pgstat_vacuum_tabstat() -
778 * Will tell the collector about objects he can get rid of.
782 pgstat_vacuum_tabstat(void)
785 PgStat_MsgTabpurge msg;
786 HASH_SEQ_STATUS hstat;
787 PgStat_StatDBEntry *dbentry;
788 PgStat_StatTabEntry *tabentry;
795 * If not done for this transaction, read the statistics collector stats
796 * file into some hash tables.
798 backend_read_statsfile();
801 * Read pg_database and make a list of OIDs of all existing databases
803 htab = pgstat_collect_oids(DatabaseRelationId);
806 * Search the database hash table for dead databases and tell the
807 * collector to drop them.
809 hash_seq_init(&hstat, pgStatDBHash);
810 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
812 Oid dbid = dbentry->databaseid;
814 CHECK_FOR_INTERRUPTS();
816 /* the DB entry for shared tables (with InvalidOid) is never dropped */
817 if (OidIsValid(dbid) &&
818 hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
819 pgstat_drop_database(dbid);
826 * Lookup our own database entry; if not found, nothing more to do.
828 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
829 (void *) &MyDatabaseId,
831 if (dbentry == NULL || dbentry->tables == NULL)
835 * Similarly to above, make a list of all known relations in this DB.
837 htab = pgstat_collect_oids(RelationRelationId);
840 * Initialize our messages table counter to zero
845 * Check for all tables listed in stats hashtable if they still exist.
847 hash_seq_init(&hstat, dbentry->tables);
848 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
850 Oid tabid = tabentry->tableid;
852 CHECK_FOR_INTERRUPTS();
854 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
858 * Not there, so add this table's Oid to the message
860 msg.m_tableid[msg.m_nentries++] = tabid;
863 * If the message is full, send it out and reinitialize to empty
865 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
867 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
868 +msg.m_nentries * sizeof(Oid);
870 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
871 msg.m_databaseid = MyDatabaseId;
872 pgstat_send(&msg, len);
881 if (msg.m_nentries > 0)
883 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
884 +msg.m_nentries * sizeof(Oid);
886 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
887 msg.m_databaseid = MyDatabaseId;
888 pgstat_send(&msg, len);
897 * pgstat_collect_oids() -
899 * Collect the OIDs of either all databases or all tables, according to
900 * the parameter, into a temporary hash table. Caller should hash_destroy
901 * the result when done with it.
905 pgstat_collect_oids(Oid catalogid)
913 memset(&hash_ctl, 0, sizeof(hash_ctl));
914 hash_ctl.keysize = sizeof(Oid);
915 hash_ctl.entrysize = sizeof(Oid);
916 hash_ctl.hash = oid_hash;
917 htab = hash_create("Temporary table of OIDs",
918 PGSTAT_TAB_HASH_SIZE,
920 HASH_ELEM | HASH_FUNCTION);
922 rel = heap_open(catalogid, AccessShareLock);
923 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
924 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
926 Oid thisoid = HeapTupleGetOid(tup);
928 CHECK_FOR_INTERRUPTS();
930 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
933 heap_close(rel, AccessShareLock);
940 * pgstat_drop_database() -
942 * Tell the collector that we just dropped a database.
943 * (If the message gets lost, we will still clean the dead DB eventually
944 * via future invocations of pgstat_vacuum_tabstat().)
948 pgstat_drop_database(Oid databaseid)
950 PgStat_MsgDropdb msg;
955 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
956 msg.m_databaseid = databaseid;
957 pgstat_send(&msg, sizeof(msg));
962 * pgstat_drop_relation() -
964 * Tell the collector that we just dropped a relation.
965 * (If the message gets lost, we will still clean the dead entry eventually
966 * via future invocations of pgstat_vacuum_tabstat().)
968 * Currently not used for lack of any good place to call it; we rely
969 * entirely on pgstat_vacuum_tabstat() to clean out stats for dead rels.
974 pgstat_drop_relation(Oid relid)
976 PgStat_MsgTabpurge msg;
982 msg.m_tableid[0] = relid;
985 len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
987 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
988 msg.m_databaseid = MyDatabaseId;
989 pgstat_send(&msg, len);
991 #endif /* NOT_USED */
995 * pgstat_reset_counters() -
997 * Tell the statistics collector to reset counters for our database.
1001 pgstat_reset_counters(void)
1003 PgStat_MsgResetcounter msg;
1010 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1011 errmsg("must be superuser to reset statistics counters")));
1013 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1014 msg.m_databaseid = MyDatabaseId;
1015 pgstat_send(&msg, sizeof(msg));
1020 * pgstat_report_autovac() -
1022 * Called from autovacuum.c to report startup of an autovacuum process.
1023 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1024 * the db OID must be passed in, instead.
1028 pgstat_report_autovac(Oid dboid)
1030 PgStat_MsgAutovacStart msg;
1035 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1036 msg.m_databaseid = dboid;
1037 msg.m_start_time = GetCurrentTimestamp();
1039 pgstat_send(&msg, sizeof(msg));
1044 * pgstat_report_vacuum() -
1046 * Tell the collector about the table we just vacuumed.
1050 pgstat_report_vacuum(Oid tableoid, bool shared,
1051 bool analyze, PgStat_Counter tuples)
1053 PgStat_MsgVacuum msg;
1055 if (pgStatSock < 0 ||
1056 !pgstat_collect_tuplelevel)
1059 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1060 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1061 msg.m_tableoid = tableoid;
1062 msg.m_analyze = analyze;
1063 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1064 msg.m_vacuumtime = GetCurrentTimestamp();
1065 msg.m_tuples = tuples;
1066 pgstat_send(&msg, sizeof(msg));
1070 * pgstat_report_analyze() -
1072 * Tell the collector about the table we just analyzed.
1076 pgstat_report_analyze(Oid tableoid, bool shared, PgStat_Counter livetuples,
1077 PgStat_Counter deadtuples)
1079 PgStat_MsgAnalyze msg;
1081 if (pgStatSock < 0 ||
1082 !pgstat_collect_tuplelevel)
1085 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1086 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1087 msg.m_tableoid = tableoid;
1088 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1089 msg.m_analyzetime = GetCurrentTimestamp();
1090 msg.m_live_tuples = livetuples;
1091 msg.m_dead_tuples = deadtuples;
1092 pgstat_send(&msg, sizeof(msg));
1099 * Send some junk data to the collector to increase traffic.
1105 PgStat_MsgDummy msg;
1110 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1111 pgstat_send(&msg, sizeof(msg));
1116 * pgstat_initstats() -
1118 * Initialize a relcache entry to count access statistics.
1119 * Called whenever a relation is opened.
1121 * We assume that a relcache entry's pgstat_info field is zeroed by
1122 * relcache.c when the relcache entry is made; thereafter it is long-lived
1123 * data. We can avoid repeated searches of the TabStatus arrays when the
1124 * same relation is touched repeatedly within a transaction.
1128 pgstat_initstats(Relation rel)
1130 Oid rel_id = rel->rd_id;
1131 char relkind = rel->rd_rel->relkind;
1133 /* We only count stats for things that have storage */
1134 if (!(relkind == RELKIND_RELATION ||
1135 relkind == RELKIND_INDEX ||
1136 relkind == RELKIND_TOASTVALUE))
1138 rel->pgstat_info = NULL;
1142 if (pgStatSock < 0 ||
1143 !(pgstat_collect_tuplelevel ||
1144 pgstat_collect_blocklevel))
1146 /* We're not counting at all */
1147 rel->pgstat_info = NULL;
1152 * If we already set up this relation in the current transaction,
1155 if (rel->pgstat_info != NULL &&
1156 rel->pgstat_info->t_id == rel_id)
1159 /* Else find or make the PgStat_TableStatus entry, and update link */
1160 rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1164 * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1166 static PgStat_TableStatus *
1167 get_tabstat_entry(Oid rel_id, bool isshared)
1169 PgStat_TableStatus *entry;
1170 TabStatusArray *tsa;
1171 TabStatusArray *prev_tsa;
1175 * Search the already-used tabstat slots for this relation.
1178 for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1180 for (i = 0; i < tsa->tsa_used; i++)
1182 entry = &tsa->tsa_entries[i];
1183 if (entry->t_id == rel_id)
1187 if (tsa->tsa_used < TABSTAT_QUANTUM)
1190 * It must not be present, but we found a free slot instead.
1191 * Fine, let's use this one. We assume the entry was already
1192 * zeroed, either at creation or after last use.
1194 entry = &tsa->tsa_entries[tsa->tsa_used++];
1195 entry->t_id = rel_id;
1196 entry->t_shared = isshared;
1202 * We ran out of tabstat slots, so allocate more. Be sure they're zeroed.
1204 tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1205 sizeof(TabStatusArray));
1207 prev_tsa->tsa_next = tsa;
1209 pgStatTabList = tsa;
1212 * Use the first entry of the new TabStatusArray.
1214 entry = &tsa->tsa_entries[tsa->tsa_used++];
1215 entry->t_id = rel_id;
1216 entry->t_shared = isshared;
1221 * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1223 static PgStat_SubXactStatus *
1224 get_tabstat_stack_level(int nest_level)
1226 PgStat_SubXactStatus *xact_state;
1228 xact_state = pgStatXactStack;
1229 if (xact_state == NULL || xact_state->nest_level != nest_level)
1231 xact_state = (PgStat_SubXactStatus *)
1232 MemoryContextAlloc(TopTransactionContext,
1233 sizeof(PgStat_SubXactStatus));
1234 xact_state->nest_level = nest_level;
1235 xact_state->prev = pgStatXactStack;
1236 xact_state->first = NULL;
1237 pgStatXactStack = xact_state;
1243 * add_tabstat_xact_level - add a new (sub)transaction state record
1246 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1248 PgStat_SubXactStatus *xact_state;
1249 PgStat_TableXactStatus *trans;
1252 * If this is the first rel to be modified at the current nest level,
1253 * we first have to push a transaction stack entry.
1255 xact_state = get_tabstat_stack_level(nest_level);
1257 /* Now make a per-table stack entry */
1258 trans = (PgStat_TableXactStatus *)
1259 MemoryContextAllocZero(TopTransactionContext,
1260 sizeof(PgStat_TableXactStatus));
1261 trans->nest_level = nest_level;
1262 trans->upper = pgstat_info->trans;
1263 trans->parent = pgstat_info;
1264 trans->next = xact_state->first;
1265 xact_state->first = trans;
1266 pgstat_info->trans = trans;
1270 * pgstat_count_heap_insert - count a tuple insertion
1273 pgstat_count_heap_insert(Relation rel)
1275 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1277 if (pgstat_collect_tuplelevel && pgstat_info != NULL)
1279 int nest_level = GetCurrentTransactionNestLevel();
1281 /* t_tuples_inserted is nontransactional, so just advance it */
1282 pgstat_info->t_counts.t_tuples_inserted++;
1284 /* We have to log the transactional effect at the proper level */
1285 if (pgstat_info->trans == NULL ||
1286 pgstat_info->trans->nest_level != nest_level)
1287 add_tabstat_xact_level(pgstat_info, nest_level);
1289 pgstat_info->trans->tuples_inserted++;
1294 * pgstat_count_heap_update - count a tuple update
1297 pgstat_count_heap_update(Relation rel)
1299 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1301 if (pgstat_collect_tuplelevel && pgstat_info != NULL)
1303 int nest_level = GetCurrentTransactionNestLevel();
1305 /* t_tuples_updated is nontransactional, so just advance it */
1306 pgstat_info->t_counts.t_tuples_updated++;
1308 /* We have to log the transactional effect at the proper level */
1309 if (pgstat_info->trans == NULL ||
1310 pgstat_info->trans->nest_level != nest_level)
1311 add_tabstat_xact_level(pgstat_info, nest_level);
1313 /* An UPDATE both inserts a new tuple and deletes the old */
1314 pgstat_info->trans->tuples_inserted++;
1315 pgstat_info->trans->tuples_deleted++;
1320 * pgstat_count_heap_delete - count a tuple deletion
1323 pgstat_count_heap_delete(Relation rel)
1325 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1327 if (pgstat_collect_tuplelevel && pgstat_info != NULL)
1329 int nest_level = GetCurrentTransactionNestLevel();
1331 /* t_tuples_deleted is nontransactional, so just advance it */
1332 pgstat_info->t_counts.t_tuples_deleted++;
1334 /* We have to log the transactional effect at the proper level */
1335 if (pgstat_info->trans == NULL ||
1336 pgstat_info->trans->nest_level != nest_level)
1337 add_tabstat_xact_level(pgstat_info, nest_level);
1339 pgstat_info->trans->tuples_deleted++;
1347 * Called from access/transam/xact.c at top-level transaction commit/abort.
1351 AtEOXact_PgStat(bool isCommit)
1353 PgStat_SubXactStatus *xact_state;
1356 * Count transaction commit or abort. (We use counters, not just bools,
1357 * in case the reporting message isn't sent right away.)
1362 pgStatXactRollback++;
1365 * Transfer transactional insert/update counts into the base tabstat
1366 * entries. We don't bother to free any of the transactional state,
1367 * since it's all in TopTransactionContext and will go away anyway.
1369 xact_state = pgStatXactStack;
1370 if (xact_state != NULL)
1372 PgStat_TableXactStatus *trans;
1374 Assert(xact_state->nest_level == 1);
1375 Assert(xact_state->prev == NULL);
1376 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1378 PgStat_TableStatus *tabstat;
1380 Assert(trans->nest_level == 1);
1381 Assert(trans->upper == NULL);
1382 tabstat = trans->parent;
1383 Assert(tabstat->trans == trans);
1386 tabstat->t_counts.t_new_live_tuples +=
1387 trans->tuples_inserted - trans->tuples_deleted;
1388 tabstat->t_counts.t_new_dead_tuples += trans->tuples_deleted;
1392 /* inserted tuples are dead, deleted tuples are unaffected */
1393 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1395 tabstat->trans = NULL;
1398 pgStatXactStack = NULL;
1400 /* Make sure any stats snapshot is thrown away */
1401 pgstat_clear_snapshot();
1405 * AtEOSubXact_PgStat
1407 * Called from access/transam/xact.c at subtransaction commit/abort.
1411 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1413 PgStat_SubXactStatus *xact_state;
1416 * Transfer transactional insert/update counts into the next higher
1417 * subtransaction state.
1419 xact_state = pgStatXactStack;
1420 if (xact_state != NULL &&
1421 xact_state->nest_level >= nestDepth)
1423 PgStat_TableXactStatus *trans;
1424 PgStat_TableXactStatus *next_trans;
1426 /* delink xact_state from stack immediately to simplify reuse case */
1427 pgStatXactStack = xact_state->prev;
1429 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1431 PgStat_TableStatus *tabstat;
1433 next_trans = trans->next;
1434 Assert(trans->nest_level == nestDepth);
1435 tabstat = trans->parent;
1436 Assert(tabstat->trans == trans);
1439 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1441 trans->upper->tuples_inserted += trans->tuples_inserted;
1442 trans->upper->tuples_deleted += trans->tuples_deleted;
1443 tabstat->trans = trans->upper;
1449 * When there isn't an immediate parent state, we can
1450 * just reuse the record instead of going through a
1451 * palloc/pfree pushup (this works since it's all in
1452 * TopTransactionContext anyway). We have to re-link
1453 * it into the parent level, though, and that might mean
1454 * pushing a new entry into the pgStatXactStack.
1456 PgStat_SubXactStatus *upper_xact_state;
1458 upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1459 trans->next = upper_xact_state->first;
1460 upper_xact_state->first = trans;
1461 trans->nest_level = nestDepth - 1;
1467 * On abort, inserted tuples are dead (and can be bounced out
1468 * to the top-level tabstat), deleted tuples are unaffected
1470 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1471 tabstat->trans = trans->upper;
1482 * Save the transactional stats state at 2PC transaction prepare.
1484 * In this phase we just generate 2PC records for all the pending
1485 * transaction-dependent stats work.
1488 AtPrepare_PgStat(void)
1490 PgStat_SubXactStatus *xact_state;
1492 xact_state = pgStatXactStack;
1493 if (xact_state != NULL)
1495 PgStat_TableXactStatus *trans;
1497 Assert(xact_state->nest_level == 1);
1498 Assert(xact_state->prev == NULL);
1499 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1501 PgStat_TableStatus *tabstat;
1502 TwoPhasePgStatRecord record;
1504 Assert(trans->nest_level == 1);
1505 Assert(trans->upper == NULL);
1506 tabstat = trans->parent;
1507 Assert(tabstat->trans == trans);
1509 record.tuples_inserted = trans->tuples_inserted;
1510 record.tuples_deleted = trans->tuples_deleted;
1511 record.t_id = tabstat->t_id;
1512 record.t_shared = tabstat->t_shared;
1514 RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1515 &record, sizeof(TwoPhasePgStatRecord));
1521 * PostPrepare_PgStat
1522 * Clean up after successful PREPARE.
1524 * All we need do here is unlink the transaction stats state from the
1525 * nontransactional state. The nontransactional action counts will be
1526 * reported to the stats collector immediately, while the effects on live
1527 * and dead tuple counts are preserved in the 2PC state file.
1529 * Note: AtEOXact_PgStat is not called during PREPARE.
1532 PostPrepare_PgStat(void)
1534 PgStat_SubXactStatus *xact_state;
1537 * We don't bother to free any of the transactional state,
1538 * since it's all in TopTransactionContext and will go away anyway.
1540 xact_state = pgStatXactStack;
1541 if (xact_state != NULL)
1543 PgStat_TableXactStatus *trans;
1545 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1547 PgStat_TableStatus *tabstat;
1549 tabstat = trans->parent;
1550 tabstat->trans = NULL;
1553 pgStatXactStack = NULL;
1555 /* Make sure any stats snapshot is thrown away */
1556 pgstat_clear_snapshot();
1560 * 2PC processing routine for COMMIT PREPARED case.
1562 * Load the saved counts into our local pgstats state.
1565 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
1566 void *recdata, uint32 len)
1568 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1569 PgStat_TableStatus *pgstat_info;
1571 /* Find or create a tabstat entry for the rel */
1572 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1574 pgstat_info->t_counts.t_new_live_tuples +=
1575 rec->tuples_inserted - rec->tuples_deleted;
1576 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_deleted;
1580 * 2PC processing routine for ROLLBACK PREPARED case.
1582 * Load the saved counts into our local pgstats state, but treat them
1586 pgstat_twophase_postabort(TransactionId xid, uint16 info,
1587 void *recdata, uint32 len)
1589 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1590 PgStat_TableStatus *pgstat_info;
1592 /* Find or create a tabstat entry for the rel */
1593 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1595 /* inserted tuples are dead, deleted tuples are no-ops */
1596 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_inserted;
1601 * pgstat_fetch_stat_dbentry() -
1603 * Support function for the SQL-callable pgstat* functions. Returns
1604 * the collected statistics for one database or NULL. NULL doesn't mean
1605 * that the database doesn't exist, it is just not yet known by the
1606 * collector, so the caller is better off to report ZERO instead.
1609 PgStat_StatDBEntry *
1610 pgstat_fetch_stat_dbentry(Oid dbid)
1613 * If not done for this transaction, read the statistics collector stats
1614 * file into some hash tables.
1616 backend_read_statsfile();
1619 * Lookup the requested database; return NULL if not found
1621 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1628 * pgstat_fetch_stat_tabentry() -
1630 * Support function for the SQL-callable pgstat* functions. Returns
1631 * the collected statistics for one table or NULL. NULL doesn't mean
1632 * that the table doesn't exist, it is just not yet known by the
1633 * collector, so the caller is better off to report ZERO instead.
1636 PgStat_StatTabEntry *
1637 pgstat_fetch_stat_tabentry(Oid relid)
1640 PgStat_StatDBEntry *dbentry;
1641 PgStat_StatTabEntry *tabentry;
1644 * If not done for this transaction, read the statistics collector stats
1645 * file into some hash tables.
1647 backend_read_statsfile();
1650 * Lookup our database, then look in its table hash table.
1652 dbid = MyDatabaseId;
1653 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1656 if (dbentry != NULL && dbentry->tables != NULL)
1658 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1666 * If we didn't find it, maybe it's a shared table.
1669 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1672 if (dbentry != NULL && dbentry->tables != NULL)
1674 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1686 * pgstat_fetch_stat_beentry() -
1688 * Support function for the SQL-callable pgstat* functions. Returns
1689 * our local copy of the current-activity entry for one backend.
1691 * NB: caller is responsible for a check if the user is permitted to see
1692 * this info (especially the querystring).
1696 pgstat_fetch_stat_beentry(int beid)
1698 pgstat_read_current_status();
1700 if (beid < 1 || beid > localNumBackends)
1703 return &localBackendStatusTable[beid - 1];
1708 * pgstat_fetch_stat_numbackends() -
1710 * Support function for the SQL-callable pgstat* functions. Returns
1711 * the maximum current backend id.
1715 pgstat_fetch_stat_numbackends(void)
1717 pgstat_read_current_status();
1719 return localNumBackends;
1724 * pgstat_fetch_global() -
1726 * Support function for the SQL-callable pgstat* functions. Returns
1727 * a pointer to the global statistics struct.
1730 PgStat_GlobalStats *
1731 pgstat_fetch_global(void)
1733 backend_read_statsfile();
1735 return &globalStats;
1739 /* ------------------------------------------------------------
1740 * Functions for management of the shared-memory PgBackendStatus array
1741 * ------------------------------------------------------------
1744 static PgBackendStatus *BackendStatusArray = NULL;
1745 static PgBackendStatus *MyBEEntry = NULL;
1749 * Report shared-memory space needed by CreateSharedBackendStatus.
1752 BackendStatusShmemSize(void)
1756 size = mul_size(sizeof(PgBackendStatus), MaxBackends);
1761 * Initialize the shared status array during postmaster startup.
1764 CreateSharedBackendStatus(void)
1766 Size size = BackendStatusShmemSize();
1769 /* Create or attach to the shared array */
1770 BackendStatusArray = (PgBackendStatus *)
1771 ShmemInitStruct("Backend Status Array", size, &found);
1776 * We're the first - initialize.
1778 MemSet(BackendStatusArray, 0, size);
1784 * pgstat_initialize() -
1786 * Initialize pgstats state, and set up our on-proc-exit hook.
1787 * Called from InitPostgres. MyBackendId must be set,
1788 * but we must not have started any transaction yet (since the
1789 * exit hook must run after the last transaction exit).
1793 pgstat_initialize(void)
1795 /* Initialize MyBEEntry */
1796 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
1797 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
1799 /* Set up a process-exit hook to clean up */
1800 on_shmem_exit(pgstat_beshutdown_hook, 0);
1804 * pgstat_bestart() -
1806 * Initialize this backend's entry in the PgBackendStatus array.
1807 * Called from InitPostgres. MyDatabaseId and session userid must be set
1808 * (hence, this cannot be combined with pgstat_initialize).
1812 pgstat_bestart(void)
1814 TimestampTz proc_start_timestamp;
1816 SockAddr clientaddr;
1817 volatile PgBackendStatus *beentry;
1820 * To minimize the time spent modifying the PgBackendStatus entry,
1821 * fetch all the needed data first.
1823 * If we have a MyProcPort, use its session start time (for consistency,
1824 * and to save a kernel call).
1827 proc_start_timestamp = MyProcPort->SessionStartTime;
1829 proc_start_timestamp = GetCurrentTimestamp();
1830 userid = GetSessionUserId();
1833 * We may not have a MyProcPort (eg, if this is the autovacuum process).
1834 * If so, use all-zeroes client address, which is dealt with specially in
1835 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
1838 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
1840 MemSet(&clientaddr, 0, sizeof(clientaddr));
1843 * Initialize my status entry, following the protocol of bumping
1844 * st_changecount before and after; and make sure it's even afterwards. We
1845 * use a volatile pointer here to ensure the compiler doesn't try to get
1848 beentry = MyBEEntry;
1851 beentry->st_changecount++;
1852 } while ((beentry->st_changecount & 1) == 0);
1854 beentry->st_procpid = MyProcPid;
1855 beentry->st_proc_start_timestamp = proc_start_timestamp;
1856 beentry->st_activity_start_timestamp = 0;
1857 beentry->st_txn_start_timestamp = 0;
1858 beentry->st_databaseid = MyDatabaseId;
1859 beentry->st_userid = userid;
1860 beentry->st_clientaddr = clientaddr;
1861 beentry->st_waiting = false;
1862 beentry->st_activity[0] = '\0';
1863 /* Also make sure the last byte in the string area is always 0 */
1864 beentry->st_activity[PGBE_ACTIVITY_SIZE - 1] = '\0';
1866 beentry->st_changecount++;
1867 Assert((beentry->st_changecount & 1) == 0);
1871 * Shut down a single backend's statistics reporting at process exit.
1873 * Flush any remaining statistics counts out to the collector.
1874 * Without this, operations triggered during backend exit (such as
1875 * temp table deletions) won't be counted.
1877 * Lastly, clear out our entry in the PgBackendStatus array.
1880 pgstat_beshutdown_hook(int code, Datum arg)
1882 volatile PgBackendStatus *beentry = MyBEEntry;
1884 pgstat_report_tabstat(true);
1887 * Clear my status entry, following the protocol of bumping st_changecount
1888 * before and after. We use a volatile pointer here to ensure the
1889 * compiler doesn't try to get cute.
1891 beentry->st_changecount++;
1893 beentry->st_procpid = 0; /* mark invalid */
1895 beentry->st_changecount++;
1896 Assert((beentry->st_changecount & 1) == 0);
1901 * pgstat_report_activity() -
1903 * Called from tcop/postgres.c to report what the backend is actually doing
1904 * (usually "<IDLE>" or the start of the query to be executed).
1908 pgstat_report_activity(const char *cmd_str)
1910 volatile PgBackendStatus *beentry = MyBEEntry;
1911 TimestampTz start_timestamp;
1914 if (!pgstat_collect_querystring || !beentry)
1918 * To minimize the time spent modifying the entry, fetch all the needed
1921 start_timestamp = GetCurrentStatementStartTimestamp();
1923 len = strlen(cmd_str);
1924 len = pg_mbcliplen(cmd_str, len, PGBE_ACTIVITY_SIZE - 1);
1927 * Update my status entry, following the protocol of bumping
1928 * st_changecount before and after. We use a volatile pointer here to
1929 * ensure the compiler doesn't try to get cute.
1931 beentry->st_changecount++;
1933 beentry->st_activity_start_timestamp = start_timestamp;
1934 memcpy((char *) beentry->st_activity, cmd_str, len);
1935 beentry->st_activity[len] = '\0';
1937 beentry->st_changecount++;
1938 Assert((beentry->st_changecount & 1) == 0);
1942 * Set the current transaction start timestamp to the specified
1943 * value. If there is no current active transaction, this is signified
1947 pgstat_report_txn_timestamp(TimestampTz tstamp)
1949 volatile PgBackendStatus *beentry = MyBEEntry;
1951 if (!pgstat_collect_querystring || !beentry)
1955 * Update my status entry, following the protocol of bumping
1956 * st_changecount before and after. We use a volatile pointer
1957 * here to ensure the compiler doesn't try to get cute.
1959 beentry->st_changecount++;
1960 beentry->st_txn_start_timestamp = tstamp;
1961 beentry->st_changecount++;
1962 Assert((beentry->st_changecount & 1) == 0);
1966 * pgstat_report_waiting() -
1968 * Called from lock manager to report beginning or end of a lock wait.
1970 * NB: this *must* be able to survive being called before MyBEEntry has been
1975 pgstat_report_waiting(bool waiting)
1977 volatile PgBackendStatus *beentry = MyBEEntry;
1979 if (!pgstat_collect_querystring || !beentry)
1983 * Since this is a single-byte field in a struct that only this process
1984 * may modify, there seems no need to bother with the st_changecount
1985 * protocol. The update must appear atomic in any case.
1987 beentry->st_waiting = waiting;
1992 * pgstat_read_current_status() -
1994 * Copy the current contents of the PgBackendStatus array to local memory,
1995 * if not already done in this transaction.
1999 pgstat_read_current_status(void)
2001 volatile PgBackendStatus *beentry;
2002 PgBackendStatus *localtable;
2003 PgBackendStatus *localentry;
2006 Assert(!pgStatRunningInCollector);
2007 if (localBackendStatusTable)
2008 return; /* already done */
2010 pgstat_setup_memcxt();
2012 localtable = (PgBackendStatus *)
2013 MemoryContextAlloc(pgStatLocalContext,
2014 sizeof(PgBackendStatus) * MaxBackends);
2015 localNumBackends = 0;
2017 beentry = BackendStatusArray;
2018 localentry = localtable;
2019 for (i = 1; i <= MaxBackends; i++)
2022 * Follow the protocol of retrying if st_changecount changes while we
2023 * copy the entry, or if it's odd. (The check for odd is needed to
2024 * cover the case where we are able to completely copy the entry while
2025 * the source backend is between increment steps.) We use a volatile
2026 * pointer here to ensure the compiler doesn't try to get cute.
2030 int save_changecount = beentry->st_changecount;
2033 * XXX if PGBE_ACTIVITY_SIZE is really large, it might be best to
2034 * use strcpy not memcpy for copying the activity string?
2036 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2038 if (save_changecount == beentry->st_changecount &&
2039 (save_changecount & 1) == 0)
2042 /* Make sure we can break out of loop if stuck... */
2043 CHECK_FOR_INTERRUPTS();
2047 /* Only valid entries get included into the local array */
2048 if (localentry->st_procpid > 0)
2055 /* Set the pointer only after completion of a valid table */
2056 localBackendStatusTable = localtable;
2060 /* ------------------------------------------------------------
2061 * Local support functions follow
2062 * ------------------------------------------------------------
2067 * pgstat_setheader() -
2069 * Set common header fields in a statistics message
2073 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2075 hdr->m_type = mtype;
2082 * Send out one statistics message to the collector
2086 pgstat_send(void *msg, int len)
2093 ((PgStat_MsgHdr *) msg)->m_size = len;
2095 /* We'll retry after EINTR, but ignore all other failures */
2098 rc = send(pgStatSock, msg, len, 0);
2099 } while (rc < 0 && errno == EINTR);
2101 #ifdef USE_ASSERT_CHECKING
2102 /* In debug builds, log send failures ... */
2104 elog(LOG, "could not send to statistics collector: %m");
2109 * pgstat_send_bgwriter() -
2111 * Send bgwriter statistics to the collector
2115 pgstat_send_bgwriter(void)
2117 /* We assume this initializes to zeroes */
2118 static const PgStat_MsgBgWriter all_zeroes;
2121 * This function can be called even if nothing at all has happened.
2122 * In this case, avoid sending a completely empty message to
2123 * the stats collector.
2125 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2129 * Prepare and send the message
2131 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2132 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2135 * Clear out the statistics buffer, so it can be re-used.
2137 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2142 * PgstatCollectorMain() -
2144 * Start up the statistics collector process. This is the body of the
2145 * postmaster child process.
2147 * The argc/argv parameters are valid only in EXEC_BACKEND case.
2150 NON_EXEC_STATIC void
2151 PgstatCollectorMain(int argc, char *argv[])
2153 struct itimerval write_timeout;
2154 bool need_timer = false;
2160 struct pollfd input_fd;
2162 struct timeval sel_timeout;
2167 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2169 MyProcPid = getpid(); /* reset MyProcPid */
2172 * If possible, make this process a group leader, so that the postmaster
2173 * can signal any child processes too. (pgstat probably never has
2174 * any child processes, but for consistency we make all postmaster
2175 * child processes do this.)
2179 elog(FATAL, "setsid() failed: %m");
2183 * Ignore all signals usually bound to some action in the postmaster,
2184 * except SIGQUIT and SIGALRM.
2186 pqsignal(SIGHUP, SIG_IGN);
2187 pqsignal(SIGINT, SIG_IGN);
2188 pqsignal(SIGTERM, SIG_IGN);
2189 pqsignal(SIGQUIT, pgstat_exit);
2190 pqsignal(SIGALRM, force_statwrite);
2191 pqsignal(SIGPIPE, SIG_IGN);
2192 pqsignal(SIGUSR1, SIG_IGN);
2193 pqsignal(SIGUSR2, SIG_IGN);
2194 pqsignal(SIGCHLD, SIG_DFL);
2195 pqsignal(SIGTTIN, SIG_DFL);
2196 pqsignal(SIGTTOU, SIG_DFL);
2197 pqsignal(SIGCONT, SIG_DFL);
2198 pqsignal(SIGWINCH, SIG_DFL);
2199 PG_SETMASK(&UnBlockSig);
2202 * Identify myself via ps
2204 init_ps_display("stats collector process", "", "", "");
2207 * Arrange to write the initial status file right away
2209 need_statwrite = true;
2211 /* Preset the delay between status file writes */
2212 MemSet(&write_timeout, 0, sizeof(struct itimerval));
2213 write_timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
2214 write_timeout.it_value.tv_usec = (PGSTAT_STAT_INTERVAL % 1000) * 1000;
2217 * Read in an existing statistics stats file or initialize the stats to
2220 pgStatRunningInCollector = true;
2221 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2224 * Setup the descriptor set for select(2). Since only one bit in the set
2225 * ever changes, we need not repeat FD_ZERO each time.
2227 #if !defined(HAVE_POLL) && !defined(WIN32)
2232 * Loop to process messages until we get SIGQUIT or detect ungraceful
2233 * death of our parent postmaster.
2235 * For performance reasons, we don't want to do a PostmasterIsAlive() test
2236 * after every message; instead, do it at statwrite time and if
2237 * select()/poll() is interrupted by timeout.
2244 * Quit if we get SIGQUIT from the postmaster.
2250 * If time to write the stats file, do so. Note that the alarm
2251 * interrupt isn't re-enabled immediately, but only after we next
2252 * receive a stats message; so no cycles are wasted when there is
2257 /* Check for postmaster death; if so we'll write file below */
2258 if (!PostmasterIsAlive(true))
2261 pgstat_write_statsfile();
2262 need_statwrite = false;
2267 * Wait for a message to arrive; but not for more than
2268 * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2269 * shut down after an ungraceful postmaster termination; so it needn't
2270 * be very fast. However, on some systems SIGQUIT won't interrupt the
2271 * poll/select call, so this also limits speed of response to SIGQUIT,
2272 * which is more important.)
2274 * We use poll(2) if available, otherwise select(2).
2275 * Win32 has its own implementation.
2279 input_fd.fd = pgStatSock;
2280 input_fd.events = POLLIN | POLLERR;
2281 input_fd.revents = 0;
2283 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2288 (errcode_for_socket_access(),
2289 errmsg("poll() failed in statistics collector: %m")));
2292 got_data = (input_fd.revents != 0);
2293 #else /* !HAVE_POLL */
2295 FD_SET(pgStatSock, &rfds);
2298 * timeout struct is modified by select() on some operating systems,
2299 * so re-fill it each time.
2301 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2302 sel_timeout.tv_usec = 0;
2304 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2309 (errcode_for_socket_access(),
2310 errmsg("select() failed in statistics collector: %m")));
2313 got_data = FD_ISSET(pgStatSock, &rfds);
2314 #endif /* HAVE_POLL */
2316 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2317 PGSTAT_SELECT_TIMEOUT*1000);
2321 * If there is a message on the socket, read it and check for
2326 len = recv(pgStatSock, (char *) &msg,
2327 sizeof(PgStat_Msg), 0);
2333 (errcode_for_socket_access(),
2334 errmsg("could not read statistics message: %m")));
2338 * We ignore messages that are smaller than our common header
2340 if (len < sizeof(PgStat_MsgHdr))
2344 * The received length must match the length in the header
2346 if (msg.msg_hdr.m_size != len)
2350 * O.K. - we accept this message. Process it.
2352 switch (msg.msg_hdr.m_type)
2354 case PGSTAT_MTYPE_DUMMY:
2357 case PGSTAT_MTYPE_TABSTAT:
2358 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
2361 case PGSTAT_MTYPE_TABPURGE:
2362 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
2365 case PGSTAT_MTYPE_DROPDB:
2366 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
2369 case PGSTAT_MTYPE_RESETCOUNTER:
2370 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
2374 case PGSTAT_MTYPE_AUTOVAC_START:
2375 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
2378 case PGSTAT_MTYPE_VACUUM:
2379 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
2382 case PGSTAT_MTYPE_ANALYZE:
2383 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
2386 case PGSTAT_MTYPE_BGWRITER:
2387 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
2395 * If this is the first message after we wrote the stats file the
2396 * last time, enable the alarm interrupt to make it be written
2401 if (setitimer(ITIMER_REAL, &write_timeout, NULL))
2403 (errmsg("could not set statistics collector timer: %m")));
2410 * We can only get here if the select/poll timeout elapsed. Check
2411 * for postmaster death.
2413 if (!PostmasterIsAlive(true))
2416 } /* end of message-processing loop */
2419 * Save the final stats to reuse at next startup.
2421 pgstat_write_statsfile();
2427 /* SIGQUIT signal handler for collector process */
2429 pgstat_exit(SIGNAL_ARGS)
2434 /* SIGALRM signal handler for collector process */
2436 force_statwrite(SIGNAL_ARGS)
2438 need_statwrite = true;
2443 * Lookup the hash table entry for the specified database. If no hash
2444 * table entry exists, initialize it, if the create parameter is true.
2445 * Else, return NULL.
2447 static PgStat_StatDBEntry *
2448 pgstat_get_db_entry(Oid databaseid, bool create)
2450 PgStat_StatDBEntry *result;
2452 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
2454 /* Lookup or create the hash table entry for this database */
2455 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2459 if (!create && !found)
2462 /* If not found, initialize the new one. */
2467 result->tables = NULL;
2468 result->n_xact_commit = 0;
2469 result->n_xact_rollback = 0;
2470 result->n_blocks_fetched = 0;
2471 result->n_blocks_hit = 0;
2472 result->n_tuples_returned = 0;
2473 result->n_tuples_fetched = 0;
2474 result->n_tuples_inserted = 0;
2475 result->n_tuples_updated = 0;
2476 result->n_tuples_deleted = 0;
2477 result->last_autovac_time = 0;
2479 memset(&hash_ctl, 0, sizeof(hash_ctl));
2480 hash_ctl.keysize = sizeof(Oid);
2481 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2482 hash_ctl.hash = oid_hash;
2483 result->tables = hash_create("Per-database table",
2484 PGSTAT_TAB_HASH_SIZE,
2486 HASH_ELEM | HASH_FUNCTION);
2494 * pgstat_write_statsfile() -
2500 pgstat_write_statsfile(void)
2502 HASH_SEQ_STATUS hstat;
2503 HASH_SEQ_STATUS tstat;
2504 PgStat_StatDBEntry *dbentry;
2505 PgStat_StatTabEntry *tabentry;
2510 * Open the statistics temp file to write out the current values.
2512 fpout = fopen(PGSTAT_STAT_TMPFILE, PG_BINARY_W);
2516 (errcode_for_file_access(),
2517 errmsg("could not open temporary statistics file \"%s\": %m",
2518 PGSTAT_STAT_TMPFILE)));
2523 * Write the file header --- currently just a format ID.
2525 format_id = PGSTAT_FILE_FORMAT_ID;
2526 fwrite(&format_id, sizeof(format_id), 1, fpout);
2529 * Write global stats struct
2531 fwrite(&globalStats, sizeof(globalStats), 1, fpout);
2534 * Walk through the database table.
2536 hash_seq_init(&hstat, pgStatDBHash);
2537 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2540 * Write out the DB entry including the number of live backends. We
2541 * don't write the tables pointer since it's of no use to any other
2545 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2548 * Walk through the database's access stats per table.
2550 hash_seq_init(&tstat, dbentry->tables);
2551 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2554 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2558 * Mark the end of this DB
2564 * No more output to be done. Close the temp file and replace the old
2565 * pgstat.stat with it. The ferror() check replaces testing for error
2566 * after each individual fputc or fwrite above.
2573 (errcode_for_file_access(),
2574 errmsg("could not write temporary statistics file \"%s\": %m",
2575 PGSTAT_STAT_TMPFILE)));
2577 unlink(PGSTAT_STAT_TMPFILE);
2579 else if (fclose(fpout) < 0)
2582 (errcode_for_file_access(),
2583 errmsg("could not close temporary statistics file \"%s\": %m",
2584 PGSTAT_STAT_TMPFILE)));
2585 unlink(PGSTAT_STAT_TMPFILE);
2587 else if (rename(PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME) < 0)
2590 (errcode_for_file_access(),
2591 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2592 PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME)));
2593 unlink(PGSTAT_STAT_TMPFILE);
2599 * pgstat_read_statsfile() -
2601 * Reads in an existing statistics collector file and initializes the
2602 * databases' hash table (whose entries point to the tables' hash tables).
2606 pgstat_read_statsfile(Oid onlydb)
2608 PgStat_StatDBEntry *dbentry;
2609 PgStat_StatDBEntry dbbuf;
2610 PgStat_StatTabEntry *tabentry;
2611 PgStat_StatTabEntry tabbuf;
2614 HTAB *tabhash = NULL;
2620 * The tables will live in pgStatLocalContext.
2622 pgstat_setup_memcxt();
2625 * Create the DB hashtable
2627 memset(&hash_ctl, 0, sizeof(hash_ctl));
2628 hash_ctl.keysize = sizeof(Oid);
2629 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2630 hash_ctl.hash = oid_hash;
2631 hash_ctl.hcxt = pgStatLocalContext;
2632 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2633 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2636 * Clear out global statistics so they start from zero in case we can't
2637 * load an existing statsfile.
2639 memset(&globalStats, 0, sizeof(globalStats));
2642 * Try to open the status file. If it doesn't exist, the backends simply
2643 * return zero for anything and the collector simply starts from scratch
2644 * with empty counters.
2646 if ((fpin = AllocateFile(PGSTAT_STAT_FILENAME, PG_BINARY_R)) == NULL)
2650 * Verify it's of the expected format.
2652 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
2653 || format_id != PGSTAT_FILE_FORMAT_ID)
2655 ereport(pgStatRunningInCollector ? LOG : WARNING,
2656 (errmsg("corrupted pgstat.stat file")));
2661 * Read global stats struct
2663 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
2665 ereport(pgStatRunningInCollector ? LOG : WARNING,
2666 (errmsg("corrupted pgstat.stat file")));
2671 * We found an existing collector stats file. Read it and put all the
2672 * hashtable entries into place.
2676 switch (fgetc(fpin))
2679 * 'D' A PgStat_StatDBEntry struct describing a database
2680 * follows. Subsequently, zero to many 'T' entries will follow
2681 * until a 'd' is encountered.
2684 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
2685 fpin) != offsetof(PgStat_StatDBEntry, tables))
2687 ereport(pgStatRunningInCollector ? LOG : WARNING,
2688 (errmsg("corrupted pgstat.stat file")));
2693 * Add to the DB hash
2695 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
2696 (void *) &dbbuf.databaseid,
2701 ereport(pgStatRunningInCollector ? LOG : WARNING,
2702 (errmsg("corrupted pgstat.stat file")));
2706 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2707 dbentry->tables = NULL;
2710 * Don't collect tables if not the requested DB (or the
2711 * shared-table info)
2713 if (onlydb != InvalidOid)
2715 if (dbbuf.databaseid != onlydb &&
2716 dbbuf.databaseid != InvalidOid)
2720 memset(&hash_ctl, 0, sizeof(hash_ctl));
2721 hash_ctl.keysize = sizeof(Oid);
2722 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2723 hash_ctl.hash = oid_hash;
2724 hash_ctl.hcxt = pgStatLocalContext;
2725 dbentry->tables = hash_create("Per-database table",
2726 PGSTAT_TAB_HASH_SIZE,
2728 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2731 * Arrange that following 'T's add entries to this database's
2732 * tables hash table.
2734 tabhash = dbentry->tables;
2738 * 'd' End of this database.
2745 * 'T' A PgStat_StatTabEntry follows.
2748 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
2749 fpin) != sizeof(PgStat_StatTabEntry))
2751 ereport(pgStatRunningInCollector ? LOG : WARNING,
2752 (errmsg("corrupted pgstat.stat file")));
2757 * Skip if table belongs to a not requested database.
2759 if (tabhash == NULL)
2762 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2763 (void *) &tabbuf.tableid,
2764 HASH_ENTER, &found);
2768 ereport(pgStatRunningInCollector ? LOG : WARNING,
2769 (errmsg("corrupted pgstat.stat file")));
2773 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2777 * 'E' The EOF marker of a complete stats file.
2783 ereport(pgStatRunningInCollector ? LOG : WARNING,
2784 (errmsg("corrupted pgstat.stat file")));
2796 * If not already done, read the statistics collector stats file into
2797 * some hash tables. The results will be kept until pgstat_clear_snapshot()
2798 * is called (typically, at end of transaction).
2801 backend_read_statsfile(void)
2803 /* already read it? */
2806 Assert(!pgStatRunningInCollector);
2808 /* Autovacuum launcher wants stats about all databases */
2809 if (IsAutoVacuumLauncherProcess())
2810 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2812 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId);
2817 * pgstat_setup_memcxt() -
2819 * Create pgStatLocalContext, if not already done.
2823 pgstat_setup_memcxt(void)
2825 if (!pgStatLocalContext)
2826 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
2827 "Statistics snapshot",
2828 ALLOCSET_SMALL_MINSIZE,
2829 ALLOCSET_SMALL_INITSIZE,
2830 ALLOCSET_SMALL_MAXSIZE);
2835 * pgstat_clear_snapshot() -
2837 * Discard any data collected in the current transaction. Any subsequent
2838 * request will cause new snapshots to be read.
2840 * This is also invoked during transaction commit or abort to discard
2841 * the no-longer-wanted snapshot.
2845 pgstat_clear_snapshot(void)
2847 /* Release memory, if any was allocated */
2848 if (pgStatLocalContext)
2849 MemoryContextDelete(pgStatLocalContext);
2851 /* Reset variables */
2852 pgStatLocalContext = NULL;
2853 pgStatDBHash = NULL;
2854 localBackendStatusTable = NULL;
2855 localNumBackends = 0;
2860 * pgstat_recv_tabstat() -
2862 * Count what the backend has done.
2866 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
2868 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
2869 PgStat_StatDBEntry *dbentry;
2870 PgStat_StatTabEntry *tabentry;
2874 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
2877 * Update database-wide stats.
2879 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
2880 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2883 * Process all table entries in the message.
2885 for (i = 0; i < msg->m_nentries; i++)
2887 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2888 (void *) &(tabmsg[i].t_id),
2889 HASH_ENTER, &found);
2894 * If it's a new table entry, initialize counters to the values we
2897 tabentry->numscans = tabmsg[i].t_counts.t_numscans;
2898 tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
2899 tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
2900 tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
2901 tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
2902 tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
2903 tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
2904 tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
2905 tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
2906 tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
2908 tabentry->last_anl_tuples = 0;
2909 tabentry->vacuum_timestamp = 0;
2910 tabentry->autovac_vacuum_timestamp = 0;
2911 tabentry->analyze_timestamp = 0;
2912 tabentry->autovac_analyze_timestamp = 0;
2917 * Otherwise add the values to the existing entry.
2919 tabentry->numscans += tabmsg[i].t_counts.t_numscans;
2920 tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2921 tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2922 tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2923 tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
2924 tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
2925 tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
2926 tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
2927 tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
2928 tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
2931 /* Clamp n_live_tuples in case of negative new_live_tuples */
2932 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
2935 * Add per-table stats to the per-database entry, too.
2937 dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2938 dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2939 dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2940 dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
2941 dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
2942 dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
2943 dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
2949 * pgstat_recv_tabpurge() -
2951 * Arrange for dead table removal.
2955 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
2957 PgStat_StatDBEntry *dbentry;
2960 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2963 * No need to purge if we don't even know the database.
2965 if (!dbentry || !dbentry->tables)
2969 * Process all table entries in the message.
2971 for (i = 0; i < msg->m_nentries; i++)
2973 /* Remove from hashtable if present; we don't care if it's not. */
2974 (void) hash_search(dbentry->tables,
2975 (void *) &(msg->m_tableid[i]),
2982 * pgstat_recv_dropdb() -
2984 * Arrange for dead database removal
2988 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
2990 PgStat_StatDBEntry *dbentry;
2993 * Lookup the database in the hashtable.
2995 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2998 * If found, remove it.
3002 if (dbentry->tables != NULL)
3003 hash_destroy(dbentry->tables);
3005 if (hash_search(pgStatDBHash,
3006 (void *) &(dbentry->databaseid),
3007 HASH_REMOVE, NULL) == NULL)
3009 (errmsg("database hash table corrupted "
3010 "during cleanup --- abort")));
3016 * pgstat_recv_resetcounter() -
3018 * Reset the statistics for the specified database.
3022 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3025 PgStat_StatDBEntry *dbentry;
3028 * Lookup the database in the hashtable. Nothing to do if not there.
3030 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3036 * We simply throw away all the database's table entries by recreating a
3037 * new hash table for them.
3039 if (dbentry->tables != NULL)
3040 hash_destroy(dbentry->tables);
3042 dbentry->tables = NULL;
3043 dbentry->n_xact_commit = 0;
3044 dbentry->n_xact_rollback = 0;
3045 dbentry->n_blocks_fetched = 0;
3046 dbentry->n_blocks_hit = 0;
3048 memset(&hash_ctl, 0, sizeof(hash_ctl));
3049 hash_ctl.keysize = sizeof(Oid);
3050 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3051 hash_ctl.hash = oid_hash;
3052 dbentry->tables = hash_create("Per-database table",
3053 PGSTAT_TAB_HASH_SIZE,
3055 HASH_ELEM | HASH_FUNCTION);
3059 * pgstat_recv_autovac() -
3061 * Process an autovacuum signalling message.
3065 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
3067 PgStat_StatDBEntry *dbentry;
3070 * Lookup the database in the hashtable. Don't create the entry if it
3071 * doesn't exist, because autovacuum may be processing a template
3072 * database. If this isn't the case, the database is most likely to have
3073 * an entry already. (If it doesn't, not much harm is done anyway --
3074 * it'll get created as soon as somebody actually uses the database.)
3076 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3077 if (dbentry == NULL)
3081 * Store the last autovacuum time in the database entry.
3083 dbentry->last_autovac_time = msg->m_start_time;
3087 * pgstat_recv_vacuum() -
3089 * Process a VACUUM message.
3093 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
3095 PgStat_StatDBEntry *dbentry;
3096 PgStat_StatTabEntry *tabentry;
3099 * Don't create either the database or table entry if it doesn't already
3100 * exist. This avoids bloating the stats with entries for stuff that is
3101 * only touched by vacuum and not by live operations.
3103 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3104 if (dbentry == NULL)
3107 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3109 if (tabentry == NULL)
3112 if (msg->m_autovacuum)
3113 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
3115 tabentry->vacuum_timestamp = msg->m_vacuumtime;
3116 tabentry->n_live_tuples = msg->m_tuples;
3117 tabentry->n_dead_tuples = 0;
3120 tabentry->last_anl_tuples = msg->m_tuples;
3121 if (msg->m_autovacuum)
3122 tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
3124 tabentry->analyze_timestamp = msg->m_vacuumtime;
3128 /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
3129 tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
3135 * pgstat_recv_analyze() -
3137 * Process an ANALYZE message.
3141 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
3143 PgStat_StatDBEntry *dbentry;
3144 PgStat_StatTabEntry *tabentry;
3147 * Don't create either the database or table entry if it doesn't already
3148 * exist. This avoids bloating the stats with entries for stuff that is
3149 * only touched by analyze and not by live operations.
3151 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3152 if (dbentry == NULL)
3155 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3157 if (tabentry == NULL)
3160 if (msg->m_autovacuum)
3161 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
3163 tabentry->analyze_timestamp = msg->m_analyzetime;
3164 tabentry->n_live_tuples = msg->m_live_tuples;
3165 tabentry->n_dead_tuples = msg->m_dead_tuples;
3166 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
3171 * pgstat_recv_bgwriter() -
3173 * Process a BGWRITER message.
3177 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
3179 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
3180 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
3181 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
3182 globalStats.buf_written_clean += msg->m_buf_written_clean;
3183 globalStats.maxwritten_clean += msg->m_maxwritten_clean;