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.163 2007/09/11 03:28:05 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_xact_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 * Report current transaction start timestamp as the specified value.
1943 * Zero means there is no active transaction.
1946 pgstat_report_xact_timestamp(TimestampTz tstamp)
1948 volatile PgBackendStatus *beentry = MyBEEntry;
1950 if (!pgstat_collect_querystring || !beentry)
1954 * Update my status entry, following the protocol of bumping
1955 * st_changecount before and after. We use a volatile pointer
1956 * here to ensure the compiler doesn't try to get cute.
1958 beentry->st_changecount++;
1959 beentry->st_xact_start_timestamp = tstamp;
1960 beentry->st_changecount++;
1961 Assert((beentry->st_changecount & 1) == 0);
1965 * pgstat_report_waiting() -
1967 * Called from lock manager to report beginning or end of a lock wait.
1969 * NB: this *must* be able to survive being called before MyBEEntry has been
1974 pgstat_report_waiting(bool waiting)
1976 volatile PgBackendStatus *beentry = MyBEEntry;
1978 if (!pgstat_collect_querystring || !beentry)
1982 * Since this is a single-byte field in a struct that only this process
1983 * may modify, there seems no need to bother with the st_changecount
1984 * protocol. The update must appear atomic in any case.
1986 beentry->st_waiting = waiting;
1991 * pgstat_read_current_status() -
1993 * Copy the current contents of the PgBackendStatus array to local memory,
1994 * if not already done in this transaction.
1998 pgstat_read_current_status(void)
2000 volatile PgBackendStatus *beentry;
2001 PgBackendStatus *localtable;
2002 PgBackendStatus *localentry;
2005 Assert(!pgStatRunningInCollector);
2006 if (localBackendStatusTable)
2007 return; /* already done */
2009 pgstat_setup_memcxt();
2011 localtable = (PgBackendStatus *)
2012 MemoryContextAlloc(pgStatLocalContext,
2013 sizeof(PgBackendStatus) * MaxBackends);
2014 localNumBackends = 0;
2016 beentry = BackendStatusArray;
2017 localentry = localtable;
2018 for (i = 1; i <= MaxBackends; i++)
2021 * Follow the protocol of retrying if st_changecount changes while we
2022 * copy the entry, or if it's odd. (The check for odd is needed to
2023 * cover the case where we are able to completely copy the entry while
2024 * the source backend is between increment steps.) We use a volatile
2025 * pointer here to ensure the compiler doesn't try to get cute.
2029 int save_changecount = beentry->st_changecount;
2032 * XXX if PGBE_ACTIVITY_SIZE is really large, it might be best to
2033 * use strcpy not memcpy for copying the activity string?
2035 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2037 if (save_changecount == beentry->st_changecount &&
2038 (save_changecount & 1) == 0)
2041 /* Make sure we can break out of loop if stuck... */
2042 CHECK_FOR_INTERRUPTS();
2046 /* Only valid entries get included into the local array */
2047 if (localentry->st_procpid > 0)
2054 /* Set the pointer only after completion of a valid table */
2055 localBackendStatusTable = localtable;
2059 /* ------------------------------------------------------------
2060 * Local support functions follow
2061 * ------------------------------------------------------------
2066 * pgstat_setheader() -
2068 * Set common header fields in a statistics message
2072 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2074 hdr->m_type = mtype;
2081 * Send out one statistics message to the collector
2085 pgstat_send(void *msg, int len)
2092 ((PgStat_MsgHdr *) msg)->m_size = len;
2094 /* We'll retry after EINTR, but ignore all other failures */
2097 rc = send(pgStatSock, msg, len, 0);
2098 } while (rc < 0 && errno == EINTR);
2100 #ifdef USE_ASSERT_CHECKING
2101 /* In debug builds, log send failures ... */
2103 elog(LOG, "could not send to statistics collector: %m");
2108 * pgstat_send_bgwriter() -
2110 * Send bgwriter statistics to the collector
2114 pgstat_send_bgwriter(void)
2116 /* We assume this initializes to zeroes */
2117 static const PgStat_MsgBgWriter all_zeroes;
2120 * This function can be called even if nothing at all has happened.
2121 * In this case, avoid sending a completely empty message to
2122 * the stats collector.
2124 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2128 * Prepare and send the message
2130 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2131 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2134 * Clear out the statistics buffer, so it can be re-used.
2136 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2141 * PgstatCollectorMain() -
2143 * Start up the statistics collector process. This is the body of the
2144 * postmaster child process.
2146 * The argc/argv parameters are valid only in EXEC_BACKEND case.
2149 NON_EXEC_STATIC void
2150 PgstatCollectorMain(int argc, char *argv[])
2152 struct itimerval write_timeout;
2153 bool need_timer = false;
2159 struct pollfd input_fd;
2161 struct timeval sel_timeout;
2166 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2168 MyProcPid = getpid(); /* reset MyProcPid */
2170 MyStartTime = time(NULL); /* record Start Time for logging */
2173 * If possible, make this process a group leader, so that the postmaster
2174 * can signal any child processes too. (pgstat probably never has
2175 * any child processes, but for consistency we make all postmaster
2176 * child processes do this.)
2180 elog(FATAL, "setsid() failed: %m");
2184 * Ignore all signals usually bound to some action in the postmaster,
2185 * except SIGQUIT and SIGALRM.
2187 pqsignal(SIGHUP, SIG_IGN);
2188 pqsignal(SIGINT, SIG_IGN);
2189 pqsignal(SIGTERM, SIG_IGN);
2190 pqsignal(SIGQUIT, pgstat_exit);
2191 pqsignal(SIGALRM, force_statwrite);
2192 pqsignal(SIGPIPE, SIG_IGN);
2193 pqsignal(SIGUSR1, SIG_IGN);
2194 pqsignal(SIGUSR2, SIG_IGN);
2195 pqsignal(SIGCHLD, SIG_DFL);
2196 pqsignal(SIGTTIN, SIG_DFL);
2197 pqsignal(SIGTTOU, SIG_DFL);
2198 pqsignal(SIGCONT, SIG_DFL);
2199 pqsignal(SIGWINCH, SIG_DFL);
2200 PG_SETMASK(&UnBlockSig);
2203 * Identify myself via ps
2205 init_ps_display("stats collector process", "", "", "");
2208 * Arrange to write the initial status file right away
2210 need_statwrite = true;
2212 /* Preset the delay between status file writes */
2213 MemSet(&write_timeout, 0, sizeof(struct itimerval));
2214 write_timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
2215 write_timeout.it_value.tv_usec = (PGSTAT_STAT_INTERVAL % 1000) * 1000;
2218 * Read in an existing statistics stats file or initialize the stats to
2221 pgStatRunningInCollector = true;
2222 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2225 * Setup the descriptor set for select(2). Since only one bit in the set
2226 * ever changes, we need not repeat FD_ZERO each time.
2228 #if !defined(HAVE_POLL) && !defined(WIN32)
2233 * Loop to process messages until we get SIGQUIT or detect ungraceful
2234 * death of our parent postmaster.
2236 * For performance reasons, we don't want to do a PostmasterIsAlive() test
2237 * after every message; instead, do it at statwrite time and if
2238 * select()/poll() is interrupted by timeout.
2245 * Quit if we get SIGQUIT from the postmaster.
2251 * If time to write the stats file, do so. Note that the alarm
2252 * interrupt isn't re-enabled immediately, but only after we next
2253 * receive a stats message; so no cycles are wasted when there is
2258 /* Check for postmaster death; if so we'll write file below */
2259 if (!PostmasterIsAlive(true))
2262 pgstat_write_statsfile();
2263 need_statwrite = false;
2268 * Wait for a message to arrive; but not for more than
2269 * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2270 * shut down after an ungraceful postmaster termination; so it needn't
2271 * be very fast. However, on some systems SIGQUIT won't interrupt the
2272 * poll/select call, so this also limits speed of response to SIGQUIT,
2273 * which is more important.)
2275 * We use poll(2) if available, otherwise select(2).
2276 * Win32 has its own implementation.
2280 input_fd.fd = pgStatSock;
2281 input_fd.events = POLLIN | POLLERR;
2282 input_fd.revents = 0;
2284 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2289 (errcode_for_socket_access(),
2290 errmsg("poll() failed in statistics collector: %m")));
2293 got_data = (input_fd.revents != 0);
2294 #else /* !HAVE_POLL */
2296 FD_SET(pgStatSock, &rfds);
2299 * timeout struct is modified by select() on some operating systems,
2300 * so re-fill it each time.
2302 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2303 sel_timeout.tv_usec = 0;
2305 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2310 (errcode_for_socket_access(),
2311 errmsg("select() failed in statistics collector: %m")));
2314 got_data = FD_ISSET(pgStatSock, &rfds);
2315 #endif /* HAVE_POLL */
2317 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2318 PGSTAT_SELECT_TIMEOUT*1000);
2322 * If there is a message on the socket, read it and check for
2327 len = recv(pgStatSock, (char *) &msg,
2328 sizeof(PgStat_Msg), 0);
2334 (errcode_for_socket_access(),
2335 errmsg("could not read statistics message: %m")));
2339 * We ignore messages that are smaller than our common header
2341 if (len < sizeof(PgStat_MsgHdr))
2345 * The received length must match the length in the header
2347 if (msg.msg_hdr.m_size != len)
2351 * O.K. - we accept this message. Process it.
2353 switch (msg.msg_hdr.m_type)
2355 case PGSTAT_MTYPE_DUMMY:
2358 case PGSTAT_MTYPE_TABSTAT:
2359 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
2362 case PGSTAT_MTYPE_TABPURGE:
2363 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
2366 case PGSTAT_MTYPE_DROPDB:
2367 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
2370 case PGSTAT_MTYPE_RESETCOUNTER:
2371 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
2375 case PGSTAT_MTYPE_AUTOVAC_START:
2376 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
2379 case PGSTAT_MTYPE_VACUUM:
2380 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
2383 case PGSTAT_MTYPE_ANALYZE:
2384 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
2387 case PGSTAT_MTYPE_BGWRITER:
2388 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
2396 * If this is the first message after we wrote the stats file the
2397 * last time, enable the alarm interrupt to make it be written
2402 if (setitimer(ITIMER_REAL, &write_timeout, NULL))
2404 (errmsg("could not set statistics collector timer: %m")));
2411 * We can only get here if the select/poll timeout elapsed. Check
2412 * for postmaster death.
2414 if (!PostmasterIsAlive(true))
2417 } /* end of message-processing loop */
2420 * Save the final stats to reuse at next startup.
2422 pgstat_write_statsfile();
2428 /* SIGQUIT signal handler for collector process */
2430 pgstat_exit(SIGNAL_ARGS)
2435 /* SIGALRM signal handler for collector process */
2437 force_statwrite(SIGNAL_ARGS)
2439 need_statwrite = true;
2444 * Lookup the hash table entry for the specified database. If no hash
2445 * table entry exists, initialize it, if the create parameter is true.
2446 * Else, return NULL.
2448 static PgStat_StatDBEntry *
2449 pgstat_get_db_entry(Oid databaseid, bool create)
2451 PgStat_StatDBEntry *result;
2453 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
2455 /* Lookup or create the hash table entry for this database */
2456 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2460 if (!create && !found)
2463 /* If not found, initialize the new one. */
2468 result->tables = NULL;
2469 result->n_xact_commit = 0;
2470 result->n_xact_rollback = 0;
2471 result->n_blocks_fetched = 0;
2472 result->n_blocks_hit = 0;
2473 result->n_tuples_returned = 0;
2474 result->n_tuples_fetched = 0;
2475 result->n_tuples_inserted = 0;
2476 result->n_tuples_updated = 0;
2477 result->n_tuples_deleted = 0;
2478 result->last_autovac_time = 0;
2480 memset(&hash_ctl, 0, sizeof(hash_ctl));
2481 hash_ctl.keysize = sizeof(Oid);
2482 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2483 hash_ctl.hash = oid_hash;
2484 result->tables = hash_create("Per-database table",
2485 PGSTAT_TAB_HASH_SIZE,
2487 HASH_ELEM | HASH_FUNCTION);
2495 * pgstat_write_statsfile() -
2501 pgstat_write_statsfile(void)
2503 HASH_SEQ_STATUS hstat;
2504 HASH_SEQ_STATUS tstat;
2505 PgStat_StatDBEntry *dbentry;
2506 PgStat_StatTabEntry *tabentry;
2511 * Open the statistics temp file to write out the current values.
2513 fpout = fopen(PGSTAT_STAT_TMPFILE, PG_BINARY_W);
2517 (errcode_for_file_access(),
2518 errmsg("could not open temporary statistics file \"%s\": %m",
2519 PGSTAT_STAT_TMPFILE)));
2524 * Write the file header --- currently just a format ID.
2526 format_id = PGSTAT_FILE_FORMAT_ID;
2527 fwrite(&format_id, sizeof(format_id), 1, fpout);
2530 * Write global stats struct
2532 fwrite(&globalStats, sizeof(globalStats), 1, fpout);
2535 * Walk through the database table.
2537 hash_seq_init(&hstat, pgStatDBHash);
2538 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2541 * Write out the DB entry including the number of live backends. We
2542 * don't write the tables pointer since it's of no use to any other
2546 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2549 * Walk through the database's access stats per table.
2551 hash_seq_init(&tstat, dbentry->tables);
2552 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2555 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2559 * Mark the end of this DB
2565 * No more output to be done. Close the temp file and replace the old
2566 * pgstat.stat with it. The ferror() check replaces testing for error
2567 * after each individual fputc or fwrite above.
2574 (errcode_for_file_access(),
2575 errmsg("could not write temporary statistics file \"%s\": %m",
2576 PGSTAT_STAT_TMPFILE)));
2578 unlink(PGSTAT_STAT_TMPFILE);
2580 else if (fclose(fpout) < 0)
2583 (errcode_for_file_access(),
2584 errmsg("could not close temporary statistics file \"%s\": %m",
2585 PGSTAT_STAT_TMPFILE)));
2586 unlink(PGSTAT_STAT_TMPFILE);
2588 else if (rename(PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME) < 0)
2591 (errcode_for_file_access(),
2592 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2593 PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME)));
2594 unlink(PGSTAT_STAT_TMPFILE);
2600 * pgstat_read_statsfile() -
2602 * Reads in an existing statistics collector file and initializes the
2603 * databases' hash table (whose entries point to the tables' hash tables).
2607 pgstat_read_statsfile(Oid onlydb)
2609 PgStat_StatDBEntry *dbentry;
2610 PgStat_StatDBEntry dbbuf;
2611 PgStat_StatTabEntry *tabentry;
2612 PgStat_StatTabEntry tabbuf;
2615 HTAB *tabhash = NULL;
2621 * The tables will live in pgStatLocalContext.
2623 pgstat_setup_memcxt();
2626 * Create the DB hashtable
2628 memset(&hash_ctl, 0, sizeof(hash_ctl));
2629 hash_ctl.keysize = sizeof(Oid);
2630 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2631 hash_ctl.hash = oid_hash;
2632 hash_ctl.hcxt = pgStatLocalContext;
2633 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2634 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2637 * Clear out global statistics so they start from zero in case we can't
2638 * load an existing statsfile.
2640 memset(&globalStats, 0, sizeof(globalStats));
2643 * Try to open the status file. If it doesn't exist, the backends simply
2644 * return zero for anything and the collector simply starts from scratch
2645 * with empty counters.
2647 if ((fpin = AllocateFile(PGSTAT_STAT_FILENAME, PG_BINARY_R)) == NULL)
2651 * Verify it's of the expected format.
2653 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
2654 || format_id != PGSTAT_FILE_FORMAT_ID)
2656 ereport(pgStatRunningInCollector ? LOG : WARNING,
2657 (errmsg("corrupted pgstat.stat file")));
2662 * Read global stats struct
2664 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
2666 ereport(pgStatRunningInCollector ? LOG : WARNING,
2667 (errmsg("corrupted pgstat.stat file")));
2672 * We found an existing collector stats file. Read it and put all the
2673 * hashtable entries into place.
2677 switch (fgetc(fpin))
2680 * 'D' A PgStat_StatDBEntry struct describing a database
2681 * follows. Subsequently, zero to many 'T' entries will follow
2682 * until a 'd' is encountered.
2685 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
2686 fpin) != offsetof(PgStat_StatDBEntry, tables))
2688 ereport(pgStatRunningInCollector ? LOG : WARNING,
2689 (errmsg("corrupted pgstat.stat file")));
2694 * Add to the DB hash
2696 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
2697 (void *) &dbbuf.databaseid,
2702 ereport(pgStatRunningInCollector ? LOG : WARNING,
2703 (errmsg("corrupted pgstat.stat file")));
2707 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2708 dbentry->tables = NULL;
2711 * Don't collect tables if not the requested DB (or the
2712 * shared-table info)
2714 if (onlydb != InvalidOid)
2716 if (dbbuf.databaseid != onlydb &&
2717 dbbuf.databaseid != InvalidOid)
2721 memset(&hash_ctl, 0, sizeof(hash_ctl));
2722 hash_ctl.keysize = sizeof(Oid);
2723 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2724 hash_ctl.hash = oid_hash;
2725 hash_ctl.hcxt = pgStatLocalContext;
2726 dbentry->tables = hash_create("Per-database table",
2727 PGSTAT_TAB_HASH_SIZE,
2729 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2732 * Arrange that following 'T's add entries to this database's
2733 * tables hash table.
2735 tabhash = dbentry->tables;
2739 * 'd' End of this database.
2746 * 'T' A PgStat_StatTabEntry follows.
2749 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
2750 fpin) != sizeof(PgStat_StatTabEntry))
2752 ereport(pgStatRunningInCollector ? LOG : WARNING,
2753 (errmsg("corrupted pgstat.stat file")));
2758 * Skip if table belongs to a not requested database.
2760 if (tabhash == NULL)
2763 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2764 (void *) &tabbuf.tableid,
2765 HASH_ENTER, &found);
2769 ereport(pgStatRunningInCollector ? LOG : WARNING,
2770 (errmsg("corrupted pgstat.stat file")));
2774 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2778 * 'E' The EOF marker of a complete stats file.
2784 ereport(pgStatRunningInCollector ? LOG : WARNING,
2785 (errmsg("corrupted pgstat.stat file")));
2797 * If not already done, read the statistics collector stats file into
2798 * some hash tables. The results will be kept until pgstat_clear_snapshot()
2799 * is called (typically, at end of transaction).
2802 backend_read_statsfile(void)
2804 /* already read it? */
2807 Assert(!pgStatRunningInCollector);
2809 /* Autovacuum launcher wants stats about all databases */
2810 if (IsAutoVacuumLauncherProcess())
2811 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2813 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId);
2818 * pgstat_setup_memcxt() -
2820 * Create pgStatLocalContext, if not already done.
2824 pgstat_setup_memcxt(void)
2826 if (!pgStatLocalContext)
2827 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
2828 "Statistics snapshot",
2829 ALLOCSET_SMALL_MINSIZE,
2830 ALLOCSET_SMALL_INITSIZE,
2831 ALLOCSET_SMALL_MAXSIZE);
2836 * pgstat_clear_snapshot() -
2838 * Discard any data collected in the current transaction. Any subsequent
2839 * request will cause new snapshots to be read.
2841 * This is also invoked during transaction commit or abort to discard
2842 * the no-longer-wanted snapshot.
2846 pgstat_clear_snapshot(void)
2848 /* Release memory, if any was allocated */
2849 if (pgStatLocalContext)
2850 MemoryContextDelete(pgStatLocalContext);
2852 /* Reset variables */
2853 pgStatLocalContext = NULL;
2854 pgStatDBHash = NULL;
2855 localBackendStatusTable = NULL;
2856 localNumBackends = 0;
2861 * pgstat_recv_tabstat() -
2863 * Count what the backend has done.
2867 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
2869 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
2870 PgStat_StatDBEntry *dbentry;
2871 PgStat_StatTabEntry *tabentry;
2875 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
2878 * Update database-wide stats.
2880 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
2881 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2884 * Process all table entries in the message.
2886 for (i = 0; i < msg->m_nentries; i++)
2888 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2889 (void *) &(tabmsg[i].t_id),
2890 HASH_ENTER, &found);
2895 * If it's a new table entry, initialize counters to the values we
2898 tabentry->numscans = tabmsg[i].t_counts.t_numscans;
2899 tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
2900 tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
2901 tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
2902 tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
2903 tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
2904 tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
2905 tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
2906 tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
2907 tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
2909 tabentry->last_anl_tuples = 0;
2910 tabentry->vacuum_timestamp = 0;
2911 tabentry->autovac_vacuum_timestamp = 0;
2912 tabentry->analyze_timestamp = 0;
2913 tabentry->autovac_analyze_timestamp = 0;
2918 * Otherwise add the values to the existing entry.
2920 tabentry->numscans += tabmsg[i].t_counts.t_numscans;
2921 tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2922 tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2923 tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2924 tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
2925 tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
2926 tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
2927 tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
2928 tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
2929 tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
2932 /* Clamp n_live_tuples in case of negative new_live_tuples */
2933 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
2936 * Add per-table stats to the per-database entry, too.
2938 dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2939 dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2940 dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2941 dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
2942 dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
2943 dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
2944 dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
2950 * pgstat_recv_tabpurge() -
2952 * Arrange for dead table removal.
2956 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
2958 PgStat_StatDBEntry *dbentry;
2961 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2964 * No need to purge if we don't even know the database.
2966 if (!dbentry || !dbentry->tables)
2970 * Process all table entries in the message.
2972 for (i = 0; i < msg->m_nentries; i++)
2974 /* Remove from hashtable if present; we don't care if it's not. */
2975 (void) hash_search(dbentry->tables,
2976 (void *) &(msg->m_tableid[i]),
2983 * pgstat_recv_dropdb() -
2985 * Arrange for dead database removal
2989 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
2991 PgStat_StatDBEntry *dbentry;
2994 * Lookup the database in the hashtable.
2996 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2999 * If found, remove it.
3003 if (dbentry->tables != NULL)
3004 hash_destroy(dbentry->tables);
3006 if (hash_search(pgStatDBHash,
3007 (void *) &(dbentry->databaseid),
3008 HASH_REMOVE, NULL) == NULL)
3010 (errmsg("database hash table corrupted "
3011 "during cleanup --- abort")));
3017 * pgstat_recv_resetcounter() -
3019 * Reset the statistics for the specified database.
3023 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3026 PgStat_StatDBEntry *dbentry;
3029 * Lookup the database in the hashtable. Nothing to do if not there.
3031 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3037 * We simply throw away all the database's table entries by recreating a
3038 * new hash table for them.
3040 if (dbentry->tables != NULL)
3041 hash_destroy(dbentry->tables);
3043 dbentry->tables = NULL;
3044 dbentry->n_xact_commit = 0;
3045 dbentry->n_xact_rollback = 0;
3046 dbentry->n_blocks_fetched = 0;
3047 dbentry->n_blocks_hit = 0;
3049 memset(&hash_ctl, 0, sizeof(hash_ctl));
3050 hash_ctl.keysize = sizeof(Oid);
3051 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3052 hash_ctl.hash = oid_hash;
3053 dbentry->tables = hash_create("Per-database table",
3054 PGSTAT_TAB_HASH_SIZE,
3056 HASH_ELEM | HASH_FUNCTION);
3060 * pgstat_recv_autovac() -
3062 * Process an autovacuum signalling message.
3066 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
3068 PgStat_StatDBEntry *dbentry;
3071 * Lookup the database in the hashtable. Don't create the entry if it
3072 * doesn't exist, because autovacuum may be processing a template
3073 * database. If this isn't the case, the database is most likely to have
3074 * an entry already. (If it doesn't, not much harm is done anyway --
3075 * it'll get created as soon as somebody actually uses the database.)
3077 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3078 if (dbentry == NULL)
3082 * Store the last autovacuum time in the database entry.
3084 dbentry->last_autovac_time = msg->m_start_time;
3088 * pgstat_recv_vacuum() -
3090 * Process a VACUUM message.
3094 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
3096 PgStat_StatDBEntry *dbentry;
3097 PgStat_StatTabEntry *tabentry;
3100 * Don't create either the database or table entry if it doesn't already
3101 * exist. This avoids bloating the stats with entries for stuff that is
3102 * only touched by vacuum and not by live operations.
3104 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3105 if (dbentry == NULL)
3108 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3110 if (tabentry == NULL)
3113 if (msg->m_autovacuum)
3114 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
3116 tabentry->vacuum_timestamp = msg->m_vacuumtime;
3117 tabentry->n_live_tuples = msg->m_tuples;
3118 tabentry->n_dead_tuples = 0;
3121 tabentry->last_anl_tuples = msg->m_tuples;
3122 if (msg->m_autovacuum)
3123 tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
3125 tabentry->analyze_timestamp = msg->m_vacuumtime;
3129 /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
3130 tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
3136 * pgstat_recv_analyze() -
3138 * Process an ANALYZE message.
3142 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
3144 PgStat_StatDBEntry *dbentry;
3145 PgStat_StatTabEntry *tabentry;
3148 * Don't create either the database or table entry if it doesn't already
3149 * exist. This avoids bloating the stats with entries for stuff that is
3150 * only touched by analyze and not by live operations.
3152 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3153 if (dbentry == NULL)
3156 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3158 if (tabentry == NULL)
3161 if (msg->m_autovacuum)
3162 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
3164 tabentry->analyze_timestamp = msg->m_analyzetime;
3165 tabentry->n_live_tuples = msg->m_live_tuples;
3166 tabentry->n_dead_tuples = msg->m_dead_tuples;
3167 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
3172 * pgstat_recv_bgwriter() -
3174 * Process a BGWRITER message.
3178 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
3180 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
3181 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
3182 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
3183 globalStats.buf_written_clean += msg->m_buf_written_clean;
3184 globalStats.maxwritten_clean += msg->m_maxwritten_clean;