4 * All the statistics collector stuff hacked up in one big, ugly file.
6 * TODO: - Separate collector, postmaster and backend stuff
7 * into different files.
9 * - Add some automatic call for pgstat vacuuming.
11 * - Add a pgstat config column to pg_database, so this
12 * entire thing can be enabled/disabled on a per db basis.
14 * Copyright (c) 2001-2008, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.170 2008/03/21 21:08:31 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/guc.h"
59 #include "utils/memutils.h"
60 #include "utils/ps_status.h"
64 * Paths for the statistics files (relative to installation's $PGDATA).
67 #define PGSTAT_STAT_FILENAME "global/pgstat.stat"
68 #define PGSTAT_STAT_TMPFILE "global/pgstat.tmp"
74 #define PGSTAT_STAT_INTERVAL 500 /* How often to write the status file;
77 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart a
78 * failed statistics collector; in
81 #define PGSTAT_SELECT_TIMEOUT 2 /* How often to check for postmaster
82 * death; in seconds. */
86 * The initial size hints for the hash tables used in the collector.
89 #define PGSTAT_DB_HASH_SIZE 16
90 #define PGSTAT_TAB_HASH_SIZE 512
97 bool pgstat_track_activities = false;
98 bool pgstat_track_counts = false;
101 * BgWriter global statistics counters (unused in other processes).
102 * Stored directly in a stats message structure so it can be sent
103 * without needing to copy things around. We assume this inits to zeroes.
105 PgStat_MsgBgWriter BgWriterStats;
111 NON_EXEC_STATIC int pgStatSock = -1;
113 static struct sockaddr_storage pgStatAddr;
115 static time_t last_pgstat_start_time;
117 static bool pgStatRunningInCollector = false;
120 * Structures in which backends store per-table info that's waiting to be
121 * sent to the collector.
123 * NOTE: once allocated, TabStatusArray structures are never moved or deleted
124 * for the life of the backend. Also, we zero out the t_id fields of the
125 * contained PgStat_TableStatus structs whenever they are not actively in use.
126 * This allows relcache pgstat_info pointers to be treated as long-lived data,
127 * avoiding repeated searches in pgstat_initstats() when a relation is
128 * repeatedly opened during a transaction.
130 #define TABSTAT_QUANTUM 100 /* we alloc this many at a time */
132 typedef struct TabStatusArray
134 struct TabStatusArray *tsa_next; /* link to next array, if any */
135 int tsa_used; /* # entries currently used */
136 PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */
139 static TabStatusArray *pgStatTabList = NULL;
142 * Tuple insertion/deletion counts for an open transaction can't be propagated
143 * into PgStat_TableStatus counters until we know if it is going to commit
144 * or abort. Hence, we keep these counts in per-subxact structs that live
145 * in TopTransactionContext. This data structure is designed on the assumption
146 * that subxacts won't usually modify very many tables.
148 typedef struct PgStat_SubXactStatus
150 int nest_level; /* subtransaction nest level */
151 struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
152 PgStat_TableXactStatus *first; /* head of list for this subxact */
153 } PgStat_SubXactStatus;
155 static PgStat_SubXactStatus *pgStatXactStack = NULL;
157 static int pgStatXactCommit = 0;
158 static int pgStatXactRollback = 0;
160 /* Record that's written to 2PC state file when pgstat state is persisted */
161 typedef struct TwoPhasePgStatRecord
163 PgStat_Counter tuples_inserted; /* tuples inserted in xact */
164 PgStat_Counter tuples_deleted; /* tuples deleted in xact */
165 Oid t_id; /* table's OID */
166 bool t_shared; /* is it a shared catalog? */
167 } TwoPhasePgStatRecord;
170 * Info about current "snapshot" of stats file
172 static MemoryContext pgStatLocalContext = NULL;
173 static HTAB *pgStatDBHash = NULL;
174 static PgBackendStatus *localBackendStatusTable = NULL;
175 static int localNumBackends = 0;
178 * Cluster wide statistics, kept in the stats collector.
179 * Contains statistics that are not collected per database
182 static PgStat_GlobalStats globalStats;
184 static volatile bool need_exit = false;
185 static volatile bool need_statwrite = false;
189 * Local function forward declarations
193 static pid_t pgstat_forkexec(void);
196 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
197 static void pgstat_exit(SIGNAL_ARGS);
198 static void force_statwrite(SIGNAL_ARGS);
199 static void pgstat_beshutdown_hook(int code, Datum arg);
201 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
202 static void pgstat_write_statsfile(void);
203 static HTAB *pgstat_read_statsfile(Oid onlydb);
204 static void backend_read_statsfile(void);
205 static void pgstat_read_current_status(void);
207 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
208 static HTAB *pgstat_collect_oids(Oid catalogid);
210 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
212 static void pgstat_setup_memcxt(void);
214 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
215 static void pgstat_send(void *msg, int len);
217 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
218 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
219 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
220 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
221 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
222 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
223 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
224 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
227 /* ------------------------------------------------------------
228 * Public functions called from postmaster follow
229 * ------------------------------------------------------------
235 * Called from postmaster at startup. Create the resources required
236 * by the statistics collector process. If unable to do so, do not
237 * fail --- better to let the postmaster start with stats collection
244 ACCEPT_TYPE_ARG3 alen;
245 struct addrinfo *addrs = NULL,
255 #define TESTBYTEVAL ((char) 199)
258 * Create the UDP socket for sending and receiving statistic messages
260 hints.ai_flags = AI_PASSIVE;
261 hints.ai_family = PF_UNSPEC;
262 hints.ai_socktype = SOCK_DGRAM;
263 hints.ai_protocol = 0;
264 hints.ai_addrlen = 0;
265 hints.ai_addr = NULL;
266 hints.ai_canonname = NULL;
267 hints.ai_next = NULL;
268 ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
272 (errmsg("could not resolve \"localhost\": %s",
273 gai_strerror(ret))));
278 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
279 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
280 * when kernel will reject IPv6). Worse, the failure may occur at the
281 * bind() or perhaps even connect() stage. So we must loop through the
282 * results till we find a working combination. We will generate LOG
283 * messages, but no error, for bogus combinations.
285 for (addr = addrs; addr; addr = addr->ai_next)
287 #ifdef HAVE_UNIX_SOCKETS
288 /* Ignore AF_UNIX sockets, if any are returned. */
289 if (addr->ai_family == AF_UNIX)
295 (errmsg("trying another address for the statistics collector")));
300 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
303 (errcode_for_socket_access(),
304 errmsg("could not create socket for statistics collector: %m")));
309 * Bind it to a kernel assigned port on localhost and get the assigned
310 * port via getsockname().
312 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
315 (errcode_for_socket_access(),
316 errmsg("could not bind socket for statistics collector: %m")));
317 closesocket(pgStatSock);
322 alen = sizeof(pgStatAddr);
323 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
326 (errcode_for_socket_access(),
327 errmsg("could not get address of socket for statistics collector: %m")));
328 closesocket(pgStatSock);
334 * Connect the socket to its own address. This saves a few cycles by
335 * not having to respecify the target address on every send. This also
336 * provides a kernel-level check that only packets from this same
337 * address will be received.
339 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
342 (errcode_for_socket_access(),
343 errmsg("could not connect socket for statistics collector: %m")));
344 closesocket(pgStatSock);
350 * Try to send and receive a one-byte test message on the socket. This
351 * is to catch situations where the socket can be created but will not
352 * actually pass data (for instance, because kernel packet filtering
355 test_byte = TESTBYTEVAL;
358 if (send(pgStatSock, &test_byte, 1, 0) != 1)
361 goto retry1; /* if interrupted, just retry */
363 (errcode_for_socket_access(),
364 errmsg("could not send test message on socket for statistics collector: %m")));
365 closesocket(pgStatSock);
371 * There could possibly be a little delay before the message can be
372 * received. We arbitrarily allow up to half a second before deciding
375 for (;;) /* need a loop to handle EINTR */
378 FD_SET(pgStatSock, &rset);
381 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
382 if (sel_res >= 0 || errno != EINTR)
388 (errcode_for_socket_access(),
389 errmsg("select() failed in statistics collector: %m")));
390 closesocket(pgStatSock);
394 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
397 * This is the case we actually think is likely, so take pains to
398 * give a specific message for it.
400 * errno will not be set meaningfully here, so don't use it.
403 (errcode(ERRCODE_CONNECTION_FAILURE),
404 errmsg("test message did not get through on socket for statistics collector")));
405 closesocket(pgStatSock);
410 test_byte++; /* just make sure variable is changed */
413 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
416 goto retry2; /* if interrupted, just retry */
418 (errcode_for_socket_access(),
419 errmsg("could not receive test message on socket for statistics collector: %m")));
420 closesocket(pgStatSock);
425 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
428 (errcode(ERRCODE_INTERNAL_ERROR),
429 errmsg("incorrect test message transmission on socket for statistics collector")));
430 closesocket(pgStatSock);
435 /* If we get here, we have a working socket */
439 /* Did we find a working address? */
440 if (!addr || pgStatSock < 0)
444 * Set the socket to non-blocking IO. This ensures that if the collector
445 * falls behind, statistics messages will be discarded; backends won't
446 * block waiting to send messages to the collector.
448 if (!pg_set_noblock(pgStatSock))
451 (errcode_for_socket_access(),
452 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
456 pg_freeaddrinfo_all(hints.ai_family, addrs);
462 (errmsg("disabling statistics collector for lack of working socket")));
465 pg_freeaddrinfo_all(hints.ai_family, addrs);
468 closesocket(pgStatSock);
472 * Adjust GUC variables to suppress useless activity, and for debugging
473 * purposes (seeing track_counts off is a clue that we failed here). We
474 * use PGC_S_OVERRIDE because there is no point in trying to turn it back
475 * on from postgresql.conf without a restart.
477 SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
481 * pgstat_reset_all() -
483 * Remove the stats file. This is currently used only if WAL
484 * recovery is needed after a crash.
487 pgstat_reset_all(void)
489 unlink(PGSTAT_STAT_FILENAME);
495 * pgstat_forkexec() -
497 * Format up the arglist for, then fork and exec, statistics collector process
500 pgstat_forkexec(void)
505 av[ac++] = "postgres";
506 av[ac++] = "--forkcol";
507 av[ac++] = NULL; /* filled in by postmaster_forkexec */
510 Assert(ac < lengthof(av));
512 return postmaster_forkexec(ac, av);
514 #endif /* EXEC_BACKEND */
520 * Called from postmaster at startup or after an existing collector
521 * died. Attempt to fire up a fresh statistics collector.
523 * Returns PID of child process, or 0 if fail.
525 * Note: if fail, we will be called again from the postmaster main loop.
534 * Check that the socket is there, else pgstat_init failed and we can do
541 * Do nothing if too soon since last collector start. This is a safety
542 * valve to protect against continuous respawn attempts if the collector
543 * is dying immediately at launch. Note that since we will be re-called
544 * from the postmaster main loop, we will get another chance later.
546 curtime = time(NULL);
547 if ((unsigned int) (curtime - last_pgstat_start_time) <
548 (unsigned int) PGSTAT_RESTART_INTERVAL)
550 last_pgstat_start_time = curtime;
553 * Okay, fork off the collector.
556 switch ((pgStatPid = pgstat_forkexec()))
558 switch ((pgStatPid = fork_process()))
563 (errmsg("could not fork statistics collector: %m")));
568 /* in postmaster child ... */
569 /* Close the postmaster's sockets */
570 ClosePostmasterPorts(false);
572 /* Lose the postmaster's on-exit routines */
575 /* Drop our connection to postmaster's shared memory, as well */
576 PGSharedMemoryDetach();
578 PgstatCollectorMain(0, NULL);
583 return (int) pgStatPid;
586 /* shouldn't get here */
591 allow_immediate_pgstat_restart(void)
593 last_pgstat_start_time = 0;
596 /* ------------------------------------------------------------
597 * Public functions used by backends follow
598 *------------------------------------------------------------
603 * pgstat_report_tabstat() -
605 * Called from tcop/postgres.c to send the so far collected per-table
606 * access statistics to the collector. Note that this is called only
607 * when not within a transaction, so it is fair to use transaction stop
608 * time as an approximation of current time.
612 pgstat_report_tabstat(bool force)
614 /* we assume this inits to all zeroes: */
615 static const PgStat_TableCounts all_zeroes;
616 static TimestampTz last_report = 0;
619 PgStat_MsgTabstat regular_msg;
620 PgStat_MsgTabstat shared_msg;
624 /* Don't expend a clock check if nothing to do */
625 if (pgStatTabList == NULL ||
626 pgStatTabList->tsa_used == 0)
630 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
631 * msec since we last sent one, or the caller wants to force stats out.
633 now = GetCurrentTransactionStopTimestamp();
635 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
640 * Scan through the TabStatusArray struct(s) to find tables that actually
641 * have counts, and build messages to send. We have to separate shared
642 * relations from regular ones because the databaseid field in the message
643 * header has to depend on that.
645 regular_msg.m_databaseid = MyDatabaseId;
646 shared_msg.m_databaseid = InvalidOid;
647 regular_msg.m_nentries = 0;
648 shared_msg.m_nentries = 0;
650 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
652 for (i = 0; i < tsa->tsa_used; i++)
654 PgStat_TableStatus *entry = &tsa->tsa_entries[i];
655 PgStat_MsgTabstat *this_msg;
656 PgStat_TableEntry *this_ent;
658 /* Shouldn't have any pending transaction-dependent counts */
659 Assert(entry->trans == NULL);
662 * Ignore entries that didn't accumulate any actual counts, such
663 * as indexes that were opened by the planner but not used.
665 if (memcmp(&entry->t_counts, &all_zeroes,
666 sizeof(PgStat_TableCounts)) == 0)
670 * OK, insert data into the appropriate message, and send if full.
672 this_msg = entry->t_shared ? &shared_msg : ®ular_msg;
673 this_ent = &this_msg->m_entry[this_msg->m_nentries];
674 this_ent->t_id = entry->t_id;
675 memcpy(&this_ent->t_counts, &entry->t_counts,
676 sizeof(PgStat_TableCounts));
677 if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
679 pgstat_send_tabstat(this_msg);
680 this_msg->m_nentries = 0;
683 /* zero out TableStatus structs after use */
684 MemSet(tsa->tsa_entries, 0,
685 tsa->tsa_used * sizeof(PgStat_TableStatus));
690 * Send partial messages. If force is true, make sure that any pending
691 * xact commit/abort gets counted, even if no table stats to send.
693 if (regular_msg.m_nentries > 0 ||
694 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
695 pgstat_send_tabstat(®ular_msg);
696 if (shared_msg.m_nentries > 0)
697 pgstat_send_tabstat(&shared_msg);
701 * Subroutine for pgstat_report_tabstat: finish and send a tabstat message
704 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
709 /* It's unlikely we'd get here with no socket, but maybe not impossible */
714 * Report accumulated xact commit/rollback whenever we send a normal
717 if (OidIsValid(tsmsg->m_databaseid))
719 tsmsg->m_xact_commit = pgStatXactCommit;
720 tsmsg->m_xact_rollback = pgStatXactRollback;
721 pgStatXactCommit = 0;
722 pgStatXactRollback = 0;
726 tsmsg->m_xact_commit = 0;
727 tsmsg->m_xact_rollback = 0;
730 n = tsmsg->m_nentries;
731 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
732 n * sizeof(PgStat_TableEntry);
734 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
735 pgstat_send(tsmsg, len);
740 * pgstat_vacuum_tabstat() -
742 * Will tell the collector about objects he can get rid of.
746 pgstat_vacuum_tabstat(void)
749 PgStat_MsgTabpurge msg;
750 HASH_SEQ_STATUS hstat;
751 PgStat_StatDBEntry *dbentry;
752 PgStat_StatTabEntry *tabentry;
759 * If not done for this transaction, read the statistics collector stats
760 * file into some hash tables.
762 backend_read_statsfile();
765 * Read pg_database and make a list of OIDs of all existing databases
767 htab = pgstat_collect_oids(DatabaseRelationId);
770 * Search the database hash table for dead databases and tell the
771 * collector to drop them.
773 hash_seq_init(&hstat, pgStatDBHash);
774 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
776 Oid dbid = dbentry->databaseid;
778 CHECK_FOR_INTERRUPTS();
780 /* the DB entry for shared tables (with InvalidOid) is never dropped */
781 if (OidIsValid(dbid) &&
782 hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
783 pgstat_drop_database(dbid);
790 * Lookup our own database entry; if not found, nothing more to do.
792 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
793 (void *) &MyDatabaseId,
795 if (dbentry == NULL || dbentry->tables == NULL)
799 * Similarly to above, make a list of all known relations in this DB.
801 htab = pgstat_collect_oids(RelationRelationId);
804 * Initialize our messages table counter to zero
809 * Check for all tables listed in stats hashtable if they still exist.
811 hash_seq_init(&hstat, dbentry->tables);
812 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
814 Oid tabid = tabentry->tableid;
816 CHECK_FOR_INTERRUPTS();
818 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
822 * Not there, so add this table's Oid to the message
824 msg.m_tableid[msg.m_nentries++] = tabid;
827 * If the message is full, send it out and reinitialize to empty
829 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
831 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
832 +msg.m_nentries * sizeof(Oid);
834 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
835 msg.m_databaseid = MyDatabaseId;
836 pgstat_send(&msg, len);
845 if (msg.m_nentries > 0)
847 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
848 +msg.m_nentries * sizeof(Oid);
850 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
851 msg.m_databaseid = MyDatabaseId;
852 pgstat_send(&msg, len);
861 * pgstat_collect_oids() -
863 * Collect the OIDs of either all databases or all tables, according to
864 * the parameter, into a temporary hash table. Caller should hash_destroy
865 * the result when done with it.
869 pgstat_collect_oids(Oid catalogid)
877 memset(&hash_ctl, 0, sizeof(hash_ctl));
878 hash_ctl.keysize = sizeof(Oid);
879 hash_ctl.entrysize = sizeof(Oid);
880 hash_ctl.hash = oid_hash;
881 htab = hash_create("Temporary table of OIDs",
882 PGSTAT_TAB_HASH_SIZE,
884 HASH_ELEM | HASH_FUNCTION);
886 rel = heap_open(catalogid, AccessShareLock);
887 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
888 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
890 Oid thisoid = HeapTupleGetOid(tup);
892 CHECK_FOR_INTERRUPTS();
894 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
897 heap_close(rel, AccessShareLock);
904 * pgstat_drop_database() -
906 * Tell the collector that we just dropped a database.
907 * (If the message gets lost, we will still clean the dead DB eventually
908 * via future invocations of pgstat_vacuum_tabstat().)
912 pgstat_drop_database(Oid databaseid)
914 PgStat_MsgDropdb msg;
919 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
920 msg.m_databaseid = databaseid;
921 pgstat_send(&msg, sizeof(msg));
926 * pgstat_drop_relation() -
928 * Tell the collector that we just dropped a relation.
929 * (If the message gets lost, we will still clean the dead entry eventually
930 * via future invocations of pgstat_vacuum_tabstat().)
932 * Currently not used for lack of any good place to call it; we rely
933 * entirely on pgstat_vacuum_tabstat() to clean out stats for dead rels.
938 pgstat_drop_relation(Oid relid)
940 PgStat_MsgTabpurge msg;
946 msg.m_tableid[0] = relid;
949 len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
951 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
952 msg.m_databaseid = MyDatabaseId;
953 pgstat_send(&msg, len);
955 #endif /* NOT_USED */
959 * pgstat_reset_counters() -
961 * Tell the statistics collector to reset counters for our database.
965 pgstat_reset_counters(void)
967 PgStat_MsgResetcounter msg;
974 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
975 errmsg("must be superuser to reset statistics counters")));
977 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
978 msg.m_databaseid = MyDatabaseId;
979 pgstat_send(&msg, sizeof(msg));
984 * pgstat_report_autovac() -
986 * Called from autovacuum.c to report startup of an autovacuum process.
987 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
988 * the db OID must be passed in, instead.
992 pgstat_report_autovac(Oid dboid)
994 PgStat_MsgAutovacStart msg;
999 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1000 msg.m_databaseid = dboid;
1001 msg.m_start_time = GetCurrentTimestamp();
1003 pgstat_send(&msg, sizeof(msg));
1008 * pgstat_report_vacuum() -
1010 * Tell the collector about the table we just vacuumed.
1014 pgstat_report_vacuum(Oid tableoid, bool shared,
1015 bool analyze, PgStat_Counter tuples)
1017 PgStat_MsgVacuum msg;
1019 if (pgStatSock < 0 || !pgstat_track_counts)
1022 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1023 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1024 msg.m_tableoid = tableoid;
1025 msg.m_analyze = analyze;
1026 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1027 msg.m_vacuumtime = GetCurrentTimestamp();
1028 msg.m_tuples = tuples;
1029 pgstat_send(&msg, sizeof(msg));
1033 * pgstat_report_analyze() -
1035 * Tell the collector about the table we just analyzed.
1039 pgstat_report_analyze(Oid tableoid, bool shared, PgStat_Counter livetuples,
1040 PgStat_Counter deadtuples)
1042 PgStat_MsgAnalyze msg;
1044 if (pgStatSock < 0 || !pgstat_track_counts)
1047 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1048 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1049 msg.m_tableoid = tableoid;
1050 msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1051 msg.m_analyzetime = GetCurrentTimestamp();
1052 msg.m_live_tuples = livetuples;
1053 msg.m_dead_tuples = deadtuples;
1054 pgstat_send(&msg, sizeof(msg));
1061 * Send some junk data to the collector to increase traffic.
1067 PgStat_MsgDummy msg;
1072 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1073 pgstat_send(&msg, sizeof(msg));
1078 * pgstat_initstats() -
1080 * Initialize a relcache entry to count access statistics.
1081 * Called whenever a relation is opened.
1083 * We assume that a relcache entry's pgstat_info field is zeroed by
1084 * relcache.c when the relcache entry is made; thereafter it is long-lived
1085 * data. We can avoid repeated searches of the TabStatus arrays when the
1086 * same relation is touched repeatedly within a transaction.
1090 pgstat_initstats(Relation rel)
1092 Oid rel_id = rel->rd_id;
1093 char relkind = rel->rd_rel->relkind;
1095 /* We only count stats for things that have storage */
1096 if (!(relkind == RELKIND_RELATION ||
1097 relkind == RELKIND_INDEX ||
1098 relkind == RELKIND_TOASTVALUE))
1100 rel->pgstat_info = NULL;
1104 if (pgStatSock < 0 || !pgstat_track_counts)
1106 /* We're not counting at all */
1107 rel->pgstat_info = NULL;
1112 * If we already set up this relation in the current transaction, nothing
1115 if (rel->pgstat_info != NULL &&
1116 rel->pgstat_info->t_id == rel_id)
1119 /* Else find or make the PgStat_TableStatus entry, and update link */
1120 rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1124 * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1126 static PgStat_TableStatus *
1127 get_tabstat_entry(Oid rel_id, bool isshared)
1129 PgStat_TableStatus *entry;
1130 TabStatusArray *tsa;
1131 TabStatusArray *prev_tsa;
1135 * Search the already-used tabstat slots for this relation.
1138 for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1140 for (i = 0; i < tsa->tsa_used; i++)
1142 entry = &tsa->tsa_entries[i];
1143 if (entry->t_id == rel_id)
1147 if (tsa->tsa_used < TABSTAT_QUANTUM)
1150 * It must not be present, but we found a free slot instead. Fine,
1151 * let's use this one. We assume the entry was already zeroed,
1152 * either at creation or after last use.
1154 entry = &tsa->tsa_entries[tsa->tsa_used++];
1155 entry->t_id = rel_id;
1156 entry->t_shared = isshared;
1162 * We ran out of tabstat slots, so allocate more. Be sure they're zeroed.
1164 tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1165 sizeof(TabStatusArray));
1167 prev_tsa->tsa_next = tsa;
1169 pgStatTabList = tsa;
1172 * Use the first entry of the new TabStatusArray.
1174 entry = &tsa->tsa_entries[tsa->tsa_used++];
1175 entry->t_id = rel_id;
1176 entry->t_shared = isshared;
1181 * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1183 static PgStat_SubXactStatus *
1184 get_tabstat_stack_level(int nest_level)
1186 PgStat_SubXactStatus *xact_state;
1188 xact_state = pgStatXactStack;
1189 if (xact_state == NULL || xact_state->nest_level != nest_level)
1191 xact_state = (PgStat_SubXactStatus *)
1192 MemoryContextAlloc(TopTransactionContext,
1193 sizeof(PgStat_SubXactStatus));
1194 xact_state->nest_level = nest_level;
1195 xact_state->prev = pgStatXactStack;
1196 xact_state->first = NULL;
1197 pgStatXactStack = xact_state;
1203 * add_tabstat_xact_level - add a new (sub)transaction state record
1206 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1208 PgStat_SubXactStatus *xact_state;
1209 PgStat_TableXactStatus *trans;
1212 * If this is the first rel to be modified at the current nest level, we
1213 * first have to push a transaction stack entry.
1215 xact_state = get_tabstat_stack_level(nest_level);
1217 /* Now make a per-table stack entry */
1218 trans = (PgStat_TableXactStatus *)
1219 MemoryContextAllocZero(TopTransactionContext,
1220 sizeof(PgStat_TableXactStatus));
1221 trans->nest_level = nest_level;
1222 trans->upper = pgstat_info->trans;
1223 trans->parent = pgstat_info;
1224 trans->next = xact_state->first;
1225 xact_state->first = trans;
1226 pgstat_info->trans = trans;
1230 * pgstat_count_heap_insert - count a tuple insertion
1233 pgstat_count_heap_insert(Relation rel)
1235 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1237 if (pgstat_track_counts && pgstat_info != NULL)
1239 int nest_level = GetCurrentTransactionNestLevel();
1241 /* t_tuples_inserted is nontransactional, so just advance it */
1242 pgstat_info->t_counts.t_tuples_inserted++;
1244 /* We have to log the transactional effect at the proper level */
1245 if (pgstat_info->trans == NULL ||
1246 pgstat_info->trans->nest_level != nest_level)
1247 add_tabstat_xact_level(pgstat_info, nest_level);
1249 pgstat_info->trans->tuples_inserted++;
1254 * pgstat_count_heap_update - count a tuple update
1257 pgstat_count_heap_update(Relation rel, bool hot)
1259 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1261 if (pgstat_track_counts && pgstat_info != NULL)
1263 int nest_level = GetCurrentTransactionNestLevel();
1265 /* t_tuples_updated is nontransactional, so just advance it */
1266 pgstat_info->t_counts.t_tuples_updated++;
1267 /* ditto for the hot_update counter */
1269 pgstat_info->t_counts.t_tuples_hot_updated++;
1271 /* We have to log the transactional effect at the proper level */
1272 if (pgstat_info->trans == NULL ||
1273 pgstat_info->trans->nest_level != nest_level)
1274 add_tabstat_xact_level(pgstat_info, nest_level);
1276 /* An UPDATE both inserts a new tuple and deletes the old */
1277 pgstat_info->trans->tuples_inserted++;
1278 pgstat_info->trans->tuples_deleted++;
1283 * pgstat_count_heap_delete - count a tuple deletion
1286 pgstat_count_heap_delete(Relation rel)
1288 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1290 if (pgstat_track_counts && pgstat_info != NULL)
1292 int nest_level = GetCurrentTransactionNestLevel();
1294 /* t_tuples_deleted is nontransactional, so just advance it */
1295 pgstat_info->t_counts.t_tuples_deleted++;
1297 /* We have to log the transactional effect at the proper level */
1298 if (pgstat_info->trans == NULL ||
1299 pgstat_info->trans->nest_level != nest_level)
1300 add_tabstat_xact_level(pgstat_info, nest_level);
1302 pgstat_info->trans->tuples_deleted++;
1307 * pgstat_update_heap_dead_tuples - update dead-tuples count
1309 * The semantics of this are that we are reporting the nontransactional
1310 * recovery of "delta" dead tuples; so t_new_dead_tuples decreases
1311 * rather than increasing, and the change goes straight into the per-table
1312 * counter, not into transactional state.
1315 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1317 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1319 if (pgstat_track_counts && pgstat_info != NULL)
1320 pgstat_info->t_counts.t_new_dead_tuples -= delta;
1327 * Called from access/transam/xact.c at top-level transaction commit/abort.
1331 AtEOXact_PgStat(bool isCommit)
1333 PgStat_SubXactStatus *xact_state;
1336 * Count transaction commit or abort. (We use counters, not just bools,
1337 * in case the reporting message isn't sent right away.)
1342 pgStatXactRollback++;
1345 * Transfer transactional insert/update counts into the base tabstat
1346 * entries. We don't bother to free any of the transactional state, since
1347 * it's all in TopTransactionContext and will go away anyway.
1349 xact_state = pgStatXactStack;
1350 if (xact_state != NULL)
1352 PgStat_TableXactStatus *trans;
1354 Assert(xact_state->nest_level == 1);
1355 Assert(xact_state->prev == NULL);
1356 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1358 PgStat_TableStatus *tabstat;
1360 Assert(trans->nest_level == 1);
1361 Assert(trans->upper == NULL);
1362 tabstat = trans->parent;
1363 Assert(tabstat->trans == trans);
1366 tabstat->t_counts.t_new_live_tuples +=
1367 trans->tuples_inserted - trans->tuples_deleted;
1368 tabstat->t_counts.t_new_dead_tuples += trans->tuples_deleted;
1372 /* inserted tuples are dead, deleted tuples are unaffected */
1373 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1375 tabstat->trans = NULL;
1378 pgStatXactStack = NULL;
1380 /* Make sure any stats snapshot is thrown away */
1381 pgstat_clear_snapshot();
1385 * AtEOSubXact_PgStat
1387 * Called from access/transam/xact.c at subtransaction commit/abort.
1391 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1393 PgStat_SubXactStatus *xact_state;
1396 * Transfer transactional insert/update counts into the next higher
1397 * subtransaction state.
1399 xact_state = pgStatXactStack;
1400 if (xact_state != NULL &&
1401 xact_state->nest_level >= nestDepth)
1403 PgStat_TableXactStatus *trans;
1404 PgStat_TableXactStatus *next_trans;
1406 /* delink xact_state from stack immediately to simplify reuse case */
1407 pgStatXactStack = xact_state->prev;
1409 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1411 PgStat_TableStatus *tabstat;
1413 next_trans = trans->next;
1414 Assert(trans->nest_level == nestDepth);
1415 tabstat = trans->parent;
1416 Assert(tabstat->trans == trans);
1419 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1421 trans->upper->tuples_inserted += trans->tuples_inserted;
1422 trans->upper->tuples_deleted += trans->tuples_deleted;
1423 tabstat->trans = trans->upper;
1429 * When there isn't an immediate parent state, we can just
1430 * reuse the record instead of going through a
1431 * palloc/pfree pushup (this works since it's all in
1432 * TopTransactionContext anyway). We have to re-link it
1433 * into the parent level, though, and that might mean
1434 * pushing a new entry into the pgStatXactStack.
1436 PgStat_SubXactStatus *upper_xact_state;
1438 upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1439 trans->next = upper_xact_state->first;
1440 upper_xact_state->first = trans;
1441 trans->nest_level = nestDepth - 1;
1447 * On abort, inserted tuples are dead (and can be bounced out
1448 * to the top-level tabstat), deleted tuples are unaffected
1450 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1451 tabstat->trans = trans->upper;
1462 * Save the transactional stats state at 2PC transaction prepare.
1464 * In this phase we just generate 2PC records for all the pending
1465 * transaction-dependent stats work.
1468 AtPrepare_PgStat(void)
1470 PgStat_SubXactStatus *xact_state;
1472 xact_state = pgStatXactStack;
1473 if (xact_state != NULL)
1475 PgStat_TableXactStatus *trans;
1477 Assert(xact_state->nest_level == 1);
1478 Assert(xact_state->prev == NULL);
1479 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1481 PgStat_TableStatus *tabstat;
1482 TwoPhasePgStatRecord record;
1484 Assert(trans->nest_level == 1);
1485 Assert(trans->upper == NULL);
1486 tabstat = trans->parent;
1487 Assert(tabstat->trans == trans);
1489 record.tuples_inserted = trans->tuples_inserted;
1490 record.tuples_deleted = trans->tuples_deleted;
1491 record.t_id = tabstat->t_id;
1492 record.t_shared = tabstat->t_shared;
1494 RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1495 &record, sizeof(TwoPhasePgStatRecord));
1501 * PostPrepare_PgStat
1502 * Clean up after successful PREPARE.
1504 * All we need do here is unlink the transaction stats state from the
1505 * nontransactional state. The nontransactional action counts will be
1506 * reported to the stats collector immediately, while the effects on live
1507 * and dead tuple counts are preserved in the 2PC state file.
1509 * Note: AtEOXact_PgStat is not called during PREPARE.
1512 PostPrepare_PgStat(void)
1514 PgStat_SubXactStatus *xact_state;
1517 * We don't bother to free any of the transactional state, since it's all
1518 * in TopTransactionContext and will go away anyway.
1520 xact_state = pgStatXactStack;
1521 if (xact_state != NULL)
1523 PgStat_TableXactStatus *trans;
1525 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1527 PgStat_TableStatus *tabstat;
1529 tabstat = trans->parent;
1530 tabstat->trans = NULL;
1533 pgStatXactStack = NULL;
1535 /* Make sure any stats snapshot is thrown away */
1536 pgstat_clear_snapshot();
1540 * 2PC processing routine for COMMIT PREPARED case.
1542 * Load the saved counts into our local pgstats state.
1545 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
1546 void *recdata, uint32 len)
1548 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1549 PgStat_TableStatus *pgstat_info;
1551 /* Find or create a tabstat entry for the rel */
1552 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1554 pgstat_info->t_counts.t_new_live_tuples +=
1555 rec->tuples_inserted - rec->tuples_deleted;
1556 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_deleted;
1560 * 2PC processing routine for ROLLBACK PREPARED case.
1562 * Load the saved counts into our local pgstats state, but treat them
1566 pgstat_twophase_postabort(TransactionId xid, uint16 info,
1567 void *recdata, uint32 len)
1569 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1570 PgStat_TableStatus *pgstat_info;
1572 /* Find or create a tabstat entry for the rel */
1573 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1575 /* inserted tuples are dead, deleted tuples are no-ops */
1576 pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_inserted;
1581 * pgstat_fetch_stat_dbentry() -
1583 * Support function for the SQL-callable pgstat* functions. Returns
1584 * the collected statistics for one database or NULL. NULL doesn't mean
1585 * that the database doesn't exist, it is just not yet known by the
1586 * collector, so the caller is better off to report ZERO instead.
1589 PgStat_StatDBEntry *
1590 pgstat_fetch_stat_dbentry(Oid dbid)
1593 * If not done for this transaction, read the statistics collector stats
1594 * file into some hash tables.
1596 backend_read_statsfile();
1599 * Lookup the requested database; return NULL if not found
1601 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1608 * pgstat_fetch_stat_tabentry() -
1610 * Support function for the SQL-callable pgstat* functions. Returns
1611 * the collected statistics for one table or NULL. NULL doesn't mean
1612 * that the table doesn't exist, it is just not yet known by the
1613 * collector, so the caller is better off to report ZERO instead.
1616 PgStat_StatTabEntry *
1617 pgstat_fetch_stat_tabentry(Oid relid)
1620 PgStat_StatDBEntry *dbentry;
1621 PgStat_StatTabEntry *tabentry;
1624 * If not done for this transaction, read the statistics collector stats
1625 * file into some hash tables.
1627 backend_read_statsfile();
1630 * Lookup our database, then look in its table hash table.
1632 dbid = MyDatabaseId;
1633 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1636 if (dbentry != NULL && dbentry->tables != NULL)
1638 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1646 * If we didn't find it, maybe it's a shared table.
1649 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1652 if (dbentry != NULL && dbentry->tables != NULL)
1654 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1666 * pgstat_fetch_stat_beentry() -
1668 * Support function for the SQL-callable pgstat* functions. Returns
1669 * our local copy of the current-activity entry for one backend.
1671 * NB: caller is responsible for a check if the user is permitted to see
1672 * this info (especially the querystring).
1676 pgstat_fetch_stat_beentry(int beid)
1678 pgstat_read_current_status();
1680 if (beid < 1 || beid > localNumBackends)
1683 return &localBackendStatusTable[beid - 1];
1688 * pgstat_fetch_stat_numbackends() -
1690 * Support function for the SQL-callable pgstat* functions. Returns
1691 * the maximum current backend id.
1695 pgstat_fetch_stat_numbackends(void)
1697 pgstat_read_current_status();
1699 return localNumBackends;
1704 * pgstat_fetch_global() -
1706 * Support function for the SQL-callable pgstat* functions. Returns
1707 * a pointer to the global statistics struct.
1710 PgStat_GlobalStats *
1711 pgstat_fetch_global(void)
1713 backend_read_statsfile();
1715 return &globalStats;
1719 /* ------------------------------------------------------------
1720 * Functions for management of the shared-memory PgBackendStatus array
1721 * ------------------------------------------------------------
1724 static PgBackendStatus *BackendStatusArray = NULL;
1725 static PgBackendStatus *MyBEEntry = NULL;
1729 * Report shared-memory space needed by CreateSharedBackendStatus.
1732 BackendStatusShmemSize(void)
1736 size = mul_size(sizeof(PgBackendStatus), MaxBackends);
1741 * Initialize the shared status array during postmaster startup.
1744 CreateSharedBackendStatus(void)
1746 Size size = BackendStatusShmemSize();
1749 /* Create or attach to the shared array */
1750 BackendStatusArray = (PgBackendStatus *)
1751 ShmemInitStruct("Backend Status Array", size, &found);
1756 * We're the first - initialize.
1758 MemSet(BackendStatusArray, 0, size);
1764 * pgstat_initialize() -
1766 * Initialize pgstats state, and set up our on-proc-exit hook.
1767 * Called from InitPostgres. MyBackendId must be set,
1768 * but we must not have started any transaction yet (since the
1769 * exit hook must run after the last transaction exit).
1773 pgstat_initialize(void)
1775 /* Initialize MyBEEntry */
1776 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
1777 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
1779 /* Set up a process-exit hook to clean up */
1780 on_shmem_exit(pgstat_beshutdown_hook, 0);
1784 * pgstat_bestart() -
1786 * Initialize this backend's entry in the PgBackendStatus array.
1787 * Called from InitPostgres. MyDatabaseId and session userid must be set
1788 * (hence, this cannot be combined with pgstat_initialize).
1792 pgstat_bestart(void)
1794 TimestampTz proc_start_timestamp;
1796 SockAddr clientaddr;
1797 volatile PgBackendStatus *beentry;
1800 * To minimize the time spent modifying the PgBackendStatus entry, fetch
1801 * all the needed data first.
1803 * If we have a MyProcPort, use its session start time (for consistency,
1804 * and to save a kernel call).
1807 proc_start_timestamp = MyProcPort->SessionStartTime;
1809 proc_start_timestamp = GetCurrentTimestamp();
1810 userid = GetSessionUserId();
1813 * We may not have a MyProcPort (eg, if this is the autovacuum process).
1814 * If so, use all-zeroes client address, which is dealt with specially in
1815 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
1818 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
1820 MemSet(&clientaddr, 0, sizeof(clientaddr));
1823 * Initialize my status entry, following the protocol of bumping
1824 * st_changecount before and after; and make sure it's even afterwards. We
1825 * use a volatile pointer here to ensure the compiler doesn't try to get
1828 beentry = MyBEEntry;
1831 beentry->st_changecount++;
1832 } while ((beentry->st_changecount & 1) == 0);
1834 beentry->st_procpid = MyProcPid;
1835 beentry->st_proc_start_timestamp = proc_start_timestamp;
1836 beentry->st_activity_start_timestamp = 0;
1837 beentry->st_xact_start_timestamp = 0;
1838 beentry->st_databaseid = MyDatabaseId;
1839 beentry->st_userid = userid;
1840 beentry->st_clientaddr = clientaddr;
1841 beentry->st_waiting = false;
1842 beentry->st_activity[0] = '\0';
1843 /* Also make sure the last byte in the string area is always 0 */
1844 beentry->st_activity[PGBE_ACTIVITY_SIZE - 1] = '\0';
1846 beentry->st_changecount++;
1847 Assert((beentry->st_changecount & 1) == 0);
1851 * Shut down a single backend's statistics reporting at process exit.
1853 * Flush any remaining statistics counts out to the collector.
1854 * Without this, operations triggered during backend exit (such as
1855 * temp table deletions) won't be counted.
1857 * Lastly, clear out our entry in the PgBackendStatus array.
1860 pgstat_beshutdown_hook(int code, Datum arg)
1862 volatile PgBackendStatus *beentry = MyBEEntry;
1864 pgstat_report_tabstat(true);
1867 * Clear my status entry, following the protocol of bumping st_changecount
1868 * before and after. We use a volatile pointer here to ensure the
1869 * compiler doesn't try to get cute.
1871 beentry->st_changecount++;
1873 beentry->st_procpid = 0; /* mark invalid */
1875 beentry->st_changecount++;
1876 Assert((beentry->st_changecount & 1) == 0);
1881 * pgstat_report_activity() -
1883 * Called from tcop/postgres.c to report what the backend is actually doing
1884 * (usually "<IDLE>" or the start of the query to be executed).
1888 pgstat_report_activity(const char *cmd_str)
1890 volatile PgBackendStatus *beentry = MyBEEntry;
1891 TimestampTz start_timestamp;
1894 if (!pgstat_track_activities || !beentry)
1898 * To minimize the time spent modifying the entry, fetch all the needed
1901 start_timestamp = GetCurrentStatementStartTimestamp();
1903 len = strlen(cmd_str);
1904 len = pg_mbcliplen(cmd_str, len, PGBE_ACTIVITY_SIZE - 1);
1907 * Update my status entry, following the protocol of bumping
1908 * st_changecount before and after. We use a volatile pointer here to
1909 * ensure the compiler doesn't try to get cute.
1911 beentry->st_changecount++;
1913 beentry->st_activity_start_timestamp = start_timestamp;
1914 memcpy((char *) beentry->st_activity, cmd_str, len);
1915 beentry->st_activity[len] = '\0';
1917 beentry->st_changecount++;
1918 Assert((beentry->st_changecount & 1) == 0);
1922 * Report current transaction start timestamp as the specified value.
1923 * Zero means there is no active transaction.
1926 pgstat_report_xact_timestamp(TimestampTz tstamp)
1928 volatile PgBackendStatus *beentry = MyBEEntry;
1930 if (!pgstat_track_activities || !beentry)
1934 * Update my status entry, following the protocol of bumping
1935 * st_changecount before and after. We use a volatile pointer here to
1936 * ensure the compiler doesn't try to get cute.
1938 beentry->st_changecount++;
1939 beentry->st_xact_start_timestamp = tstamp;
1940 beentry->st_changecount++;
1941 Assert((beentry->st_changecount & 1) == 0);
1945 * pgstat_report_waiting() -
1947 * Called from lock manager to report beginning or end of a lock wait.
1949 * NB: this *must* be able to survive being called before MyBEEntry has been
1954 pgstat_report_waiting(bool waiting)
1956 volatile PgBackendStatus *beentry = MyBEEntry;
1958 if (!pgstat_track_activities || !beentry)
1962 * Since this is a single-byte field in a struct that only this process
1963 * may modify, there seems no need to bother with the st_changecount
1964 * protocol. The update must appear atomic in any case.
1966 beentry->st_waiting = waiting;
1971 * pgstat_read_current_status() -
1973 * Copy the current contents of the PgBackendStatus array to local memory,
1974 * if not already done in this transaction.
1978 pgstat_read_current_status(void)
1980 volatile PgBackendStatus *beentry;
1981 PgBackendStatus *localtable;
1982 PgBackendStatus *localentry;
1985 Assert(!pgStatRunningInCollector);
1986 if (localBackendStatusTable)
1987 return; /* already done */
1989 pgstat_setup_memcxt();
1991 localtable = (PgBackendStatus *)
1992 MemoryContextAlloc(pgStatLocalContext,
1993 sizeof(PgBackendStatus) * MaxBackends);
1994 localNumBackends = 0;
1996 beentry = BackendStatusArray;
1997 localentry = localtable;
1998 for (i = 1; i <= MaxBackends; i++)
2001 * Follow the protocol of retrying if st_changecount changes while we
2002 * copy the entry, or if it's odd. (The check for odd is needed to
2003 * cover the case where we are able to completely copy the entry while
2004 * the source backend is between increment steps.) We use a volatile
2005 * pointer here to ensure the compiler doesn't try to get cute.
2009 int save_changecount = beentry->st_changecount;
2012 * XXX if PGBE_ACTIVITY_SIZE is really large, it might be best to
2013 * use strcpy not memcpy for copying the activity string?
2015 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2017 if (save_changecount == beentry->st_changecount &&
2018 (save_changecount & 1) == 0)
2021 /* Make sure we can break out of loop if stuck... */
2022 CHECK_FOR_INTERRUPTS();
2026 /* Only valid entries get included into the local array */
2027 if (localentry->st_procpid > 0)
2034 /* Set the pointer only after completion of a valid table */
2035 localBackendStatusTable = localtable;
2040 * pgstat_get_backend_current_activity() -
2042 * Return a string representing the current activity of the backend with
2043 * the specified PID. This looks directly at the BackendStatusArray,
2044 * and so will provide current information regardless of the age of our
2045 * transaction's snapshot of the status array.
2047 * It is the caller's responsibility to invoke this only for backends whose
2048 * state is expected to remain stable while the result is in use. The
2049 * only current use is in deadlock reporting, where we can expect that
2050 * the target backend is blocked on a lock. (There are corner cases
2051 * where the target's wait could get aborted while we are looking at it,
2052 * but the very worst consequence is to return a pointer to a string
2053 * that's been changed, so we won't worry too much.)
2055 * Note: return strings for special cases match pg_stat_get_backend_activity.
2059 pgstat_get_backend_current_activity(int pid)
2061 PgBackendStatus *beentry;
2064 beentry = BackendStatusArray;
2065 for (i = 1; i <= MaxBackends; i++)
2068 * Although we expect the target backend's entry to be stable, that
2069 * doesn't imply that anyone else's is. To avoid identifying the
2070 * wrong backend, while we check for a match to the desired PID we
2071 * must follow the protocol of retrying if st_changecount changes
2072 * while we examine the entry, or if it's odd. (This might be
2073 * unnecessary, since fetching or storing an int is almost certainly
2074 * atomic, but let's play it safe.) We use a volatile pointer here
2075 * to ensure the compiler doesn't try to get cute.
2077 volatile PgBackendStatus *vbeentry = beentry;
2082 int save_changecount = vbeentry->st_changecount;
2084 found = (vbeentry->st_procpid == pid);
2086 if (save_changecount == vbeentry->st_changecount &&
2087 (save_changecount & 1) == 0)
2090 /* Make sure we can break out of loop if stuck... */
2091 CHECK_FOR_INTERRUPTS();
2096 /* Now it is safe to use the non-volatile pointer */
2097 if (!superuser() && beentry->st_userid != GetUserId())
2098 return "<insufficient privilege>";
2099 else if (*(beentry->st_activity) == '\0')
2100 return "<command string not enabled>";
2102 return beentry->st_activity;
2108 /* If we get here, caller is in error ... */
2109 return "<backend information not available>";
2113 /* ------------------------------------------------------------
2114 * Local support functions follow
2115 * ------------------------------------------------------------
2120 * pgstat_setheader() -
2122 * Set common header fields in a statistics message
2126 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2128 hdr->m_type = mtype;
2135 * Send out one statistics message to the collector
2139 pgstat_send(void *msg, int len)
2146 ((PgStat_MsgHdr *) msg)->m_size = len;
2148 /* We'll retry after EINTR, but ignore all other failures */
2151 rc = send(pgStatSock, msg, len, 0);
2152 } while (rc < 0 && errno == EINTR);
2154 #ifdef USE_ASSERT_CHECKING
2155 /* In debug builds, log send failures ... */
2157 elog(LOG, "could not send to statistics collector: %m");
2162 * pgstat_send_bgwriter() -
2164 * Send bgwriter statistics to the collector
2168 pgstat_send_bgwriter(void)
2170 /* We assume this initializes to zeroes */
2171 static const PgStat_MsgBgWriter all_zeroes;
2174 * This function can be called even if nothing at all has happened. In
2175 * this case, avoid sending a completely empty message to the stats
2178 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2182 * Prepare and send the message
2184 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2185 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2188 * Clear out the statistics buffer, so it can be re-used.
2190 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2195 * PgstatCollectorMain() -
2197 * Start up the statistics collector process. This is the body of the
2198 * postmaster child process.
2200 * The argc/argv parameters are valid only in EXEC_BACKEND case.
2203 NON_EXEC_STATIC void
2204 PgstatCollectorMain(int argc, char *argv[])
2206 struct itimerval write_timeout;
2207 bool need_timer = false;
2213 struct pollfd input_fd;
2215 struct timeval sel_timeout;
2220 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2222 MyProcPid = getpid(); /* reset MyProcPid */
2224 MyStartTime = time(NULL); /* record Start Time for logging */
2227 * If possible, make this process a group leader, so that the postmaster
2228 * can signal any child processes too. (pgstat probably never has any
2229 * child processes, but for consistency we make all postmaster child
2230 * processes do this.)
2234 elog(FATAL, "setsid() failed: %m");
2238 * Ignore all signals usually bound to some action in the postmaster,
2239 * except SIGQUIT and SIGALRM.
2241 pqsignal(SIGHUP, SIG_IGN);
2242 pqsignal(SIGINT, SIG_IGN);
2243 pqsignal(SIGTERM, SIG_IGN);
2244 pqsignal(SIGQUIT, pgstat_exit);
2245 pqsignal(SIGALRM, force_statwrite);
2246 pqsignal(SIGPIPE, SIG_IGN);
2247 pqsignal(SIGUSR1, SIG_IGN);
2248 pqsignal(SIGUSR2, SIG_IGN);
2249 pqsignal(SIGCHLD, SIG_DFL);
2250 pqsignal(SIGTTIN, SIG_DFL);
2251 pqsignal(SIGTTOU, SIG_DFL);
2252 pqsignal(SIGCONT, SIG_DFL);
2253 pqsignal(SIGWINCH, SIG_DFL);
2254 PG_SETMASK(&UnBlockSig);
2257 * Identify myself via ps
2259 init_ps_display("stats collector process", "", "", "");
2262 * Arrange to write the initial status file right away
2264 need_statwrite = true;
2266 /* Preset the delay between status file writes */
2267 MemSet(&write_timeout, 0, sizeof(struct itimerval));
2268 write_timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
2269 write_timeout.it_value.tv_usec = (PGSTAT_STAT_INTERVAL % 1000) * 1000;
2272 * Read in an existing statistics stats file or initialize the stats to
2275 pgStatRunningInCollector = true;
2276 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2279 * Setup the descriptor set for select(2). Since only one bit in the set
2280 * ever changes, we need not repeat FD_ZERO each time.
2282 #if !defined(HAVE_POLL) && !defined(WIN32)
2287 * Loop to process messages until we get SIGQUIT or detect ungraceful
2288 * death of our parent postmaster.
2290 * For performance reasons, we don't want to do a PostmasterIsAlive() test
2291 * after every message; instead, do it at statwrite time and if
2292 * select()/poll() is interrupted by timeout.
2299 * Quit if we get SIGQUIT from the postmaster.
2305 * If time to write the stats file, do so. Note that the alarm
2306 * interrupt isn't re-enabled immediately, but only after we next
2307 * receive a stats message; so no cycles are wasted when there is
2312 /* Check for postmaster death; if so we'll write file below */
2313 if (!PostmasterIsAlive(true))
2316 pgstat_write_statsfile();
2317 need_statwrite = false;
2322 * Wait for a message to arrive; but not for more than
2323 * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2324 * shut down after an ungraceful postmaster termination; so it needn't
2325 * be very fast. However, on some systems SIGQUIT won't interrupt the
2326 * poll/select call, so this also limits speed of response to SIGQUIT,
2327 * which is more important.)
2329 * We use poll(2) if available, otherwise select(2). Win32 has its own
2334 input_fd.fd = pgStatSock;
2335 input_fd.events = POLLIN | POLLERR;
2336 input_fd.revents = 0;
2338 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2343 (errcode_for_socket_access(),
2344 errmsg("poll() failed in statistics collector: %m")));
2347 got_data = (input_fd.revents != 0);
2348 #else /* !HAVE_POLL */
2350 FD_SET(pgStatSock, &rfds);
2353 * timeout struct is modified by select() on some operating systems,
2354 * so re-fill it each time.
2356 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2357 sel_timeout.tv_usec = 0;
2359 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2364 (errcode_for_socket_access(),
2365 errmsg("select() failed in statistics collector: %m")));
2368 got_data = FD_ISSET(pgStatSock, &rfds);
2369 #endif /* HAVE_POLL */
2371 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2372 PGSTAT_SELECT_TIMEOUT * 1000);
2376 * If there is a message on the socket, read it and check for
2381 len = recv(pgStatSock, (char *) &msg,
2382 sizeof(PgStat_Msg), 0);
2388 (errcode_for_socket_access(),
2389 errmsg("could not read statistics message: %m")));
2393 * We ignore messages that are smaller than our common header
2395 if (len < sizeof(PgStat_MsgHdr))
2399 * The received length must match the length in the header
2401 if (msg.msg_hdr.m_size != len)
2405 * O.K. - we accept this message. Process it.
2407 switch (msg.msg_hdr.m_type)
2409 case PGSTAT_MTYPE_DUMMY:
2412 case PGSTAT_MTYPE_TABSTAT:
2413 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
2416 case PGSTAT_MTYPE_TABPURGE:
2417 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
2420 case PGSTAT_MTYPE_DROPDB:
2421 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
2424 case PGSTAT_MTYPE_RESETCOUNTER:
2425 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
2429 case PGSTAT_MTYPE_AUTOVAC_START:
2430 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
2433 case PGSTAT_MTYPE_VACUUM:
2434 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
2437 case PGSTAT_MTYPE_ANALYZE:
2438 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
2441 case PGSTAT_MTYPE_BGWRITER:
2442 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
2450 * If this is the first message after we wrote the stats file the
2451 * last time, enable the alarm interrupt to make it be written
2456 if (setitimer(ITIMER_REAL, &write_timeout, NULL))
2458 (errmsg("could not set statistics collector timer: %m")));
2465 * We can only get here if the select/poll timeout elapsed. Check
2466 * for postmaster death.
2468 if (!PostmasterIsAlive(true))
2471 } /* end of message-processing loop */
2474 * Save the final stats to reuse at next startup.
2476 pgstat_write_statsfile();
2482 /* SIGQUIT signal handler for collector process */
2484 pgstat_exit(SIGNAL_ARGS)
2489 /* SIGALRM signal handler for collector process */
2491 force_statwrite(SIGNAL_ARGS)
2493 need_statwrite = true;
2498 * Lookup the hash table entry for the specified database. If no hash
2499 * table entry exists, initialize it, if the create parameter is true.
2500 * Else, return NULL.
2502 static PgStat_StatDBEntry *
2503 pgstat_get_db_entry(Oid databaseid, bool create)
2505 PgStat_StatDBEntry *result;
2507 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
2509 /* Lookup or create the hash table entry for this database */
2510 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2514 if (!create && !found)
2517 /* If not found, initialize the new one. */
2522 result->tables = NULL;
2523 result->n_xact_commit = 0;
2524 result->n_xact_rollback = 0;
2525 result->n_blocks_fetched = 0;
2526 result->n_blocks_hit = 0;
2527 result->n_tuples_returned = 0;
2528 result->n_tuples_fetched = 0;
2529 result->n_tuples_inserted = 0;
2530 result->n_tuples_updated = 0;
2531 result->n_tuples_deleted = 0;
2532 result->last_autovac_time = 0;
2534 memset(&hash_ctl, 0, sizeof(hash_ctl));
2535 hash_ctl.keysize = sizeof(Oid);
2536 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2537 hash_ctl.hash = oid_hash;
2538 result->tables = hash_create("Per-database table",
2539 PGSTAT_TAB_HASH_SIZE,
2541 HASH_ELEM | HASH_FUNCTION);
2549 * pgstat_write_statsfile() -
2555 pgstat_write_statsfile(void)
2557 HASH_SEQ_STATUS hstat;
2558 HASH_SEQ_STATUS tstat;
2559 PgStat_StatDBEntry *dbentry;
2560 PgStat_StatTabEntry *tabentry;
2565 * Open the statistics temp file to write out the current values.
2567 fpout = fopen(PGSTAT_STAT_TMPFILE, PG_BINARY_W);
2571 (errcode_for_file_access(),
2572 errmsg("could not open temporary statistics file \"%s\": %m",
2573 PGSTAT_STAT_TMPFILE)));
2578 * Write the file header --- currently just a format ID.
2580 format_id = PGSTAT_FILE_FORMAT_ID;
2581 fwrite(&format_id, sizeof(format_id), 1, fpout);
2584 * Write global stats struct
2586 fwrite(&globalStats, sizeof(globalStats), 1, fpout);
2589 * Walk through the database table.
2591 hash_seq_init(&hstat, pgStatDBHash);
2592 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2595 * Write out the DB entry including the number of live backends. We
2596 * don't write the tables pointer since it's of no use to any other
2600 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2603 * Walk through the database's access stats per table.
2605 hash_seq_init(&tstat, dbentry->tables);
2606 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2609 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2613 * Mark the end of this DB
2619 * No more output to be done. Close the temp file and replace the old
2620 * pgstat.stat with it. The ferror() check replaces testing for error
2621 * after each individual fputc or fwrite above.
2628 (errcode_for_file_access(),
2629 errmsg("could not write temporary statistics file \"%s\": %m",
2630 PGSTAT_STAT_TMPFILE)));
2632 unlink(PGSTAT_STAT_TMPFILE);
2634 else if (fclose(fpout) < 0)
2637 (errcode_for_file_access(),
2638 errmsg("could not close temporary statistics file \"%s\": %m",
2639 PGSTAT_STAT_TMPFILE)));
2640 unlink(PGSTAT_STAT_TMPFILE);
2642 else if (rename(PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME) < 0)
2645 (errcode_for_file_access(),
2646 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2647 PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME)));
2648 unlink(PGSTAT_STAT_TMPFILE);
2654 * pgstat_read_statsfile() -
2656 * Reads in an existing statistics collector file and initializes the
2657 * databases' hash table (whose entries point to the tables' hash tables).
2661 pgstat_read_statsfile(Oid onlydb)
2663 PgStat_StatDBEntry *dbentry;
2664 PgStat_StatDBEntry dbbuf;
2665 PgStat_StatTabEntry *tabentry;
2666 PgStat_StatTabEntry tabbuf;
2669 HTAB *tabhash = NULL;
2675 * The tables will live in pgStatLocalContext.
2677 pgstat_setup_memcxt();
2680 * Create the DB hashtable
2682 memset(&hash_ctl, 0, sizeof(hash_ctl));
2683 hash_ctl.keysize = sizeof(Oid);
2684 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2685 hash_ctl.hash = oid_hash;
2686 hash_ctl.hcxt = pgStatLocalContext;
2687 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2688 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2691 * Clear out global statistics so they start from zero in case we can't
2692 * load an existing statsfile.
2694 memset(&globalStats, 0, sizeof(globalStats));
2697 * Try to open the status file. If it doesn't exist, the backends simply
2698 * return zero for anything and the collector simply starts from scratch
2699 * with empty counters.
2701 if ((fpin = AllocateFile(PGSTAT_STAT_FILENAME, PG_BINARY_R)) == NULL)
2705 * Verify it's of the expected format.
2707 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
2708 || format_id != PGSTAT_FILE_FORMAT_ID)
2710 ereport(pgStatRunningInCollector ? LOG : WARNING,
2711 (errmsg("corrupted pgstat.stat file")));
2716 * Read global stats struct
2718 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
2720 ereport(pgStatRunningInCollector ? LOG : WARNING,
2721 (errmsg("corrupted pgstat.stat file")));
2726 * We found an existing collector stats file. Read it and put all the
2727 * hashtable entries into place.
2731 switch (fgetc(fpin))
2734 * 'D' A PgStat_StatDBEntry struct describing a database
2735 * follows. Subsequently, zero to many 'T' entries will follow
2736 * until a 'd' is encountered.
2739 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
2740 fpin) != offsetof(PgStat_StatDBEntry, tables))
2742 ereport(pgStatRunningInCollector ? LOG : WARNING,
2743 (errmsg("corrupted pgstat.stat file")));
2748 * Add to the DB hash
2750 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
2751 (void *) &dbbuf.databaseid,
2756 ereport(pgStatRunningInCollector ? LOG : WARNING,
2757 (errmsg("corrupted pgstat.stat file")));
2761 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2762 dbentry->tables = NULL;
2765 * Don't collect tables if not the requested DB (or the
2766 * shared-table info)
2768 if (onlydb != InvalidOid)
2770 if (dbbuf.databaseid != onlydb &&
2771 dbbuf.databaseid != InvalidOid)
2775 memset(&hash_ctl, 0, sizeof(hash_ctl));
2776 hash_ctl.keysize = sizeof(Oid);
2777 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2778 hash_ctl.hash = oid_hash;
2779 hash_ctl.hcxt = pgStatLocalContext;
2780 dbentry->tables = hash_create("Per-database table",
2781 PGSTAT_TAB_HASH_SIZE,
2783 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
2786 * Arrange that following 'T's add entries to this database's
2787 * tables hash table.
2789 tabhash = dbentry->tables;
2793 * 'd' End of this database.
2800 * 'T' A PgStat_StatTabEntry follows.
2803 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
2804 fpin) != sizeof(PgStat_StatTabEntry))
2806 ereport(pgStatRunningInCollector ? LOG : WARNING,
2807 (errmsg("corrupted pgstat.stat file")));
2812 * Skip if table belongs to a not requested database.
2814 if (tabhash == NULL)
2817 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2818 (void *) &tabbuf.tableid,
2819 HASH_ENTER, &found);
2823 ereport(pgStatRunningInCollector ? LOG : WARNING,
2824 (errmsg("corrupted pgstat.stat file")));
2828 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2832 * 'E' The EOF marker of a complete stats file.
2838 ereport(pgStatRunningInCollector ? LOG : WARNING,
2839 (errmsg("corrupted pgstat.stat file")));
2851 * If not already done, read the statistics collector stats file into
2852 * some hash tables. The results will be kept until pgstat_clear_snapshot()
2853 * is called (typically, at end of transaction).
2856 backend_read_statsfile(void)
2858 /* already read it? */
2861 Assert(!pgStatRunningInCollector);
2863 /* Autovacuum launcher wants stats about all databases */
2864 if (IsAutoVacuumLauncherProcess())
2865 pgStatDBHash = pgstat_read_statsfile(InvalidOid);
2867 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId);
2872 * pgstat_setup_memcxt() -
2874 * Create pgStatLocalContext, if not already done.
2878 pgstat_setup_memcxt(void)
2880 if (!pgStatLocalContext)
2881 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
2882 "Statistics snapshot",
2883 ALLOCSET_SMALL_MINSIZE,
2884 ALLOCSET_SMALL_INITSIZE,
2885 ALLOCSET_SMALL_MAXSIZE);
2890 * pgstat_clear_snapshot() -
2892 * Discard any data collected in the current transaction. Any subsequent
2893 * request will cause new snapshots to be read.
2895 * This is also invoked during transaction commit or abort to discard
2896 * the no-longer-wanted snapshot.
2900 pgstat_clear_snapshot(void)
2902 /* Release memory, if any was allocated */
2903 if (pgStatLocalContext)
2904 MemoryContextDelete(pgStatLocalContext);
2906 /* Reset variables */
2907 pgStatLocalContext = NULL;
2908 pgStatDBHash = NULL;
2909 localBackendStatusTable = NULL;
2910 localNumBackends = 0;
2915 * pgstat_recv_tabstat() -
2917 * Count what the backend has done.
2921 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
2923 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
2924 PgStat_StatDBEntry *dbentry;
2925 PgStat_StatTabEntry *tabentry;
2929 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
2932 * Update database-wide stats.
2934 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
2935 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2938 * Process all table entries in the message.
2940 for (i = 0; i < msg->m_nentries; i++)
2942 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2943 (void *) &(tabmsg[i].t_id),
2944 HASH_ENTER, &found);
2949 * If it's a new table entry, initialize counters to the values we
2952 tabentry->numscans = tabmsg[i].t_counts.t_numscans;
2953 tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
2954 tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
2955 tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
2956 tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
2957 tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
2958 tabentry->tuples_hot_updated = tabmsg[i].t_counts.t_tuples_hot_updated;
2959 tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
2960 tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
2961 tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
2962 tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
2964 tabentry->last_anl_tuples = 0;
2965 tabentry->vacuum_timestamp = 0;
2966 tabentry->autovac_vacuum_timestamp = 0;
2967 tabentry->analyze_timestamp = 0;
2968 tabentry->autovac_analyze_timestamp = 0;
2973 * Otherwise add the values to the existing entry.
2975 tabentry->numscans += tabmsg[i].t_counts.t_numscans;
2976 tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2977 tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2978 tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2979 tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
2980 tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
2981 tabentry->tuples_hot_updated += tabmsg[i].t_counts.t_tuples_hot_updated;
2982 tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
2983 tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
2984 tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
2985 tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
2988 /* Clamp n_live_tuples in case of negative new_live_tuples */
2989 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
2990 /* Likewise for n_dead_tuples */
2991 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
2994 * Add per-table stats to the per-database entry, too.
2996 dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
2997 dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
2998 dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
2999 dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
3000 dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
3001 dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
3002 dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
3008 * pgstat_recv_tabpurge() -
3010 * Arrange for dead table removal.
3014 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3016 PgStat_StatDBEntry *dbentry;
3019 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3022 * No need to purge if we don't even know the database.
3024 if (!dbentry || !dbentry->tables)
3028 * Process all table entries in the message.
3030 for (i = 0; i < msg->m_nentries; i++)
3032 /* Remove from hashtable if present; we don't care if it's not. */
3033 (void) hash_search(dbentry->tables,
3034 (void *) &(msg->m_tableid[i]),
3041 * pgstat_recv_dropdb() -
3043 * Arrange for dead database removal
3047 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3049 PgStat_StatDBEntry *dbentry;
3052 * Lookup the database in the hashtable.
3054 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3057 * If found, remove it.
3061 if (dbentry->tables != NULL)
3062 hash_destroy(dbentry->tables);
3064 if (hash_search(pgStatDBHash,
3065 (void *) &(dbentry->databaseid),
3066 HASH_REMOVE, NULL) == NULL)
3068 (errmsg("database hash table corrupted "
3069 "during cleanup --- abort")));
3075 * pgstat_recv_resetcounter() -
3077 * Reset the statistics for the specified database.
3081 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3084 PgStat_StatDBEntry *dbentry;
3087 * Lookup the database in the hashtable. Nothing to do if not there.
3089 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3095 * We simply throw away all the database's table entries by recreating a
3096 * new hash table for them.
3098 if (dbentry->tables != NULL)
3099 hash_destroy(dbentry->tables);
3101 dbentry->tables = NULL;
3102 dbentry->n_xact_commit = 0;
3103 dbentry->n_xact_rollback = 0;
3104 dbentry->n_blocks_fetched = 0;
3105 dbentry->n_blocks_hit = 0;
3107 memset(&hash_ctl, 0, sizeof(hash_ctl));
3108 hash_ctl.keysize = sizeof(Oid);
3109 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3110 hash_ctl.hash = oid_hash;
3111 dbentry->tables = hash_create("Per-database table",
3112 PGSTAT_TAB_HASH_SIZE,
3114 HASH_ELEM | HASH_FUNCTION);
3118 * pgstat_recv_autovac() -
3120 * Process an autovacuum signalling message.
3124 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
3126 PgStat_StatDBEntry *dbentry;
3129 * Lookup the database in the hashtable. Don't create the entry if it
3130 * doesn't exist, because autovacuum may be processing a template
3131 * database. If this isn't the case, the database is most likely to have
3132 * an entry already. (If it doesn't, not much harm is done anyway --
3133 * it'll get created as soon as somebody actually uses the database.)
3135 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3136 if (dbentry == NULL)
3140 * Store the last autovacuum time in the database entry.
3142 dbentry->last_autovac_time = msg->m_start_time;
3146 * pgstat_recv_vacuum() -
3148 * Process a VACUUM message.
3152 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
3154 PgStat_StatDBEntry *dbentry;
3155 PgStat_StatTabEntry *tabentry;
3158 * Don't create either the database or table entry if it doesn't already
3159 * exist. This avoids bloating the stats with entries for stuff that is
3160 * only touched by vacuum and not by live operations.
3162 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3163 if (dbentry == NULL)
3166 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3168 if (tabentry == NULL)
3171 if (msg->m_autovacuum)
3172 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
3174 tabentry->vacuum_timestamp = msg->m_vacuumtime;
3175 tabentry->n_live_tuples = msg->m_tuples;
3176 /* Resetting dead_tuples to 0 is an approximation ... */
3177 tabentry->n_dead_tuples = 0;
3180 tabentry->last_anl_tuples = msg->m_tuples;
3181 if (msg->m_autovacuum)
3182 tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
3184 tabentry->analyze_timestamp = msg->m_vacuumtime;
3188 /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
3189 tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
3195 * pgstat_recv_analyze() -
3197 * Process an ANALYZE message.
3201 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
3203 PgStat_StatDBEntry *dbentry;
3204 PgStat_StatTabEntry *tabentry;
3207 * Don't create either the database or table entry if it doesn't already
3208 * exist. This avoids bloating the stats with entries for stuff that is
3209 * only touched by analyze and not by live operations.
3211 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3212 if (dbentry == NULL)
3215 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3217 if (tabentry == NULL)
3220 if (msg->m_autovacuum)
3221 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
3223 tabentry->analyze_timestamp = msg->m_analyzetime;
3224 tabentry->n_live_tuples = msg->m_live_tuples;
3225 tabentry->n_dead_tuples = msg->m_dead_tuples;
3226 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
3231 * pgstat_recv_bgwriter() -
3233 * Process a BGWRITER message.
3237 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
3239 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
3240 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
3241 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
3242 globalStats.buf_written_clean += msg->m_buf_written_clean;
3243 globalStats.maxwritten_clean += msg->m_maxwritten_clean;
3244 globalStats.buf_written_backend += msg->m_buf_written_backend;
3245 globalStats.buf_alloc += msg->m_buf_alloc;