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-2011, PostgreSQL Global Development Group
16 * src/backend/postmaster/pgstat.c
23 #include <sys/param.h>
25 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
34 #ifdef HAVE_SYS_POLL_H
40 #include "access/heapam.h"
41 #include "access/transam.h"
42 #include "access/twophase_rmgr.h"
43 #include "access/xact.h"
44 #include "catalog/pg_database.h"
45 #include "catalog/pg_proc.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqsignal.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
52 #include "postmaster/autovacuum.h"
53 #include "postmaster/fork_process.h"
54 #include "postmaster/postmaster.h"
55 #include "storage/backendid.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "storage/pg_shmem.h"
59 #include "storage/pmsignal.h"
60 #include "storage/procsignal.h"
61 #include "utils/guc.h"
62 #include "utils/memutils.h"
63 #include "utils/ps_status.h"
64 #include "utils/rel.h"
65 #include "utils/tqual.h"
69 * Paths for the statistics files (relative to installation's $PGDATA).
72 #define PGSTAT_STAT_PERMANENT_FILENAME "global/pgstat.stat"
73 #define PGSTAT_STAT_PERMANENT_TMPFILE "global/pgstat.tmp"
79 #define PGSTAT_STAT_INTERVAL 500 /* Minimum time between stats file
80 * updates; in milliseconds. */
82 #define PGSTAT_RETRY_DELAY 10 /* How long to wait between statistics
83 * update requests; in milliseconds. */
85 #define PGSTAT_MAX_WAIT_TIME 5000 /* Maximum time to wait for a stats
86 * file update; in milliseconds. */
88 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart a
89 * failed statistics collector; in
92 #define PGSTAT_SELECT_TIMEOUT 2 /* How often to check for postmaster
93 * death; in seconds. */
95 #define PGSTAT_POLL_LOOP_COUNT (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
99 * The initial size hints for the hash tables used in the collector.
102 #define PGSTAT_DB_HASH_SIZE 16
103 #define PGSTAT_TAB_HASH_SIZE 512
104 #define PGSTAT_FUNCTION_HASH_SIZE 512
111 bool pgstat_track_activities = false;
112 bool pgstat_track_counts = false;
113 int pgstat_track_functions = TRACK_FUNC_OFF;
114 int pgstat_track_activity_query_size = 1024;
117 * Built from GUC parameter
120 char *pgstat_stat_filename = NULL;
121 char *pgstat_stat_tmpname = NULL;
124 * BgWriter global statistics counters (unused in other processes).
125 * Stored directly in a stats message structure so it can be sent
126 * without needing to copy things around. We assume this inits to zeroes.
128 PgStat_MsgBgWriter BgWriterStats;
134 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
136 static struct sockaddr_storage pgStatAddr;
138 static time_t last_pgstat_start_time;
140 static bool pgStatRunningInCollector = false;
143 * Structures in which backends store per-table info that's waiting to be
144 * sent to the collector.
146 * NOTE: once allocated, TabStatusArray structures are never moved or deleted
147 * for the life of the backend. Also, we zero out the t_id fields of the
148 * contained PgStat_TableStatus structs whenever they are not actively in use.
149 * This allows relcache pgstat_info pointers to be treated as long-lived data,
150 * avoiding repeated searches in pgstat_initstats() when a relation is
151 * repeatedly opened during a transaction.
153 #define TABSTAT_QUANTUM 100 /* we alloc this many at a time */
155 typedef struct TabStatusArray
157 struct TabStatusArray *tsa_next; /* link to next array, if any */
158 int tsa_used; /* # entries currently used */
159 PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */
162 static TabStatusArray *pgStatTabList = NULL;
165 * Backends store per-function info that's waiting to be sent to the collector
166 * in this hash table (indexed by function OID).
168 static HTAB *pgStatFunctions = NULL;
171 * Indicates if backend has some function stats that it hasn't yet
172 * sent to the collector.
174 static bool have_function_stats = false;
177 * Tuple insertion/deletion counts for an open transaction can't be propagated
178 * into PgStat_TableStatus counters until we know if it is going to commit
179 * or abort. Hence, we keep these counts in per-subxact structs that live
180 * in TopTransactionContext. This data structure is designed on the assumption
181 * that subxacts won't usually modify very many tables.
183 typedef struct PgStat_SubXactStatus
185 int nest_level; /* subtransaction nest level */
186 struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
187 PgStat_TableXactStatus *first; /* head of list for this subxact */
188 } PgStat_SubXactStatus;
190 static PgStat_SubXactStatus *pgStatXactStack = NULL;
192 static int pgStatXactCommit = 0;
193 static int pgStatXactRollback = 0;
195 /* Record that's written to 2PC state file when pgstat state is persisted */
196 typedef struct TwoPhasePgStatRecord
198 PgStat_Counter tuples_inserted; /* tuples inserted in xact */
199 PgStat_Counter tuples_updated; /* tuples updated in xact */
200 PgStat_Counter tuples_deleted; /* tuples deleted in xact */
201 Oid t_id; /* table's OID */
202 bool t_shared; /* is it a shared catalog? */
203 } TwoPhasePgStatRecord;
206 * Info about current "snapshot" of stats file
208 static MemoryContext pgStatLocalContext = NULL;
209 static HTAB *pgStatDBHash = NULL;
210 static PgBackendStatus *localBackendStatusTable = NULL;
211 static int localNumBackends = 0;
214 * Cluster wide statistics, kept in the stats collector.
215 * Contains statistics that are not collected per database
218 static PgStat_GlobalStats globalStats;
220 /* Last time the collector successfully wrote the stats file */
221 static TimestampTz last_statwrite;
223 /* Latest statistics request time from backends */
224 static TimestampTz last_statrequest;
226 static volatile bool need_exit = false;
227 static volatile bool got_SIGHUP = false;
230 * Total time charged to functions so far in the current backend.
231 * We use this to help separate "self" and "other" time charges.
232 * (We assume this initializes to zero.)
234 static instr_time total_func_time;
238 * Local function forward declarations
242 static pid_t pgstat_forkexec(void);
245 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
246 static void pgstat_exit(SIGNAL_ARGS);
247 static void pgstat_beshutdown_hook(int code, Datum arg);
248 static void pgstat_sighup_handler(SIGNAL_ARGS);
250 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
251 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
252 Oid tableoid, bool create);
253 static void pgstat_write_statsfile(bool permanent);
254 static HTAB *pgstat_read_statsfile(Oid onlydb, bool permanent);
255 static void backend_read_statsfile(void);
256 static void pgstat_read_current_status(void);
258 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
259 static void pgstat_send_funcstats(void);
260 static HTAB *pgstat_collect_oids(Oid catalogid);
262 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
264 static void pgstat_setup_memcxt(void);
266 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
267 static void pgstat_send(void *msg, int len);
269 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
270 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
271 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
272 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
273 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
274 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
275 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
276 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
277 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
278 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
279 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
280 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
281 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
282 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
285 /* ------------------------------------------------------------
286 * Public functions called from postmaster follow
287 * ------------------------------------------------------------
293 * Called from postmaster at startup. Create the resources required
294 * by the statistics collector process. If unable to do so, do not
295 * fail --- better to let the postmaster start with stats collection
302 ACCEPT_TYPE_ARG3 alen;
303 struct addrinfo *addrs = NULL,
313 #define TESTBYTEVAL ((char) 199)
316 * Create the UDP socket for sending and receiving statistic messages
318 hints.ai_flags = AI_PASSIVE;
319 hints.ai_family = PF_UNSPEC;
320 hints.ai_socktype = SOCK_DGRAM;
321 hints.ai_protocol = 0;
322 hints.ai_addrlen = 0;
323 hints.ai_addr = NULL;
324 hints.ai_canonname = NULL;
325 hints.ai_next = NULL;
326 ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
330 (errmsg("could not resolve \"localhost\": %s",
331 gai_strerror(ret))));
336 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
337 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
338 * when kernel will reject IPv6). Worse, the failure may occur at the
339 * bind() or perhaps even connect() stage. So we must loop through the
340 * results till we find a working combination. We will generate LOG
341 * messages, but no error, for bogus combinations.
343 for (addr = addrs; addr; addr = addr->ai_next)
345 #ifdef HAVE_UNIX_SOCKETS
346 /* Ignore AF_UNIX sockets, if any are returned. */
347 if (addr->ai_family == AF_UNIX)
353 (errmsg("trying another address for the statistics collector")));
358 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
361 (errcode_for_socket_access(),
362 errmsg("could not create socket for statistics collector: %m")));
367 * Bind it to a kernel assigned port on localhost and get the assigned
368 * port via getsockname().
370 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
373 (errcode_for_socket_access(),
374 errmsg("could not bind socket for statistics collector: %m")));
375 closesocket(pgStatSock);
376 pgStatSock = PGINVALID_SOCKET;
380 alen = sizeof(pgStatAddr);
381 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
384 (errcode_for_socket_access(),
385 errmsg("could not get address of socket for statistics collector: %m")));
386 closesocket(pgStatSock);
387 pgStatSock = PGINVALID_SOCKET;
392 * Connect the socket to its own address. This saves a few cycles by
393 * not having to respecify the target address on every send. This also
394 * provides a kernel-level check that only packets from this same
395 * address will be received.
397 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
400 (errcode_for_socket_access(),
401 errmsg("could not connect socket for statistics collector: %m")));
402 closesocket(pgStatSock);
403 pgStatSock = PGINVALID_SOCKET;
408 * Try to send and receive a one-byte test message on the socket. This
409 * is to catch situations where the socket can be created but will not
410 * actually pass data (for instance, because kernel packet filtering
413 test_byte = TESTBYTEVAL;
416 if (send(pgStatSock, &test_byte, 1, 0) != 1)
419 goto retry1; /* if interrupted, just retry */
421 (errcode_for_socket_access(),
422 errmsg("could not send test message on socket for statistics collector: %m")));
423 closesocket(pgStatSock);
424 pgStatSock = PGINVALID_SOCKET;
429 * There could possibly be a little delay before the message can be
430 * received. We arbitrarily allow up to half a second before deciding
433 for (;;) /* need a loop to handle EINTR */
436 FD_SET(pgStatSock, &rset);
440 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
441 if (sel_res >= 0 || errno != EINTR)
447 (errcode_for_socket_access(),
448 errmsg("select() failed in statistics collector: %m")));
449 closesocket(pgStatSock);
450 pgStatSock = PGINVALID_SOCKET;
453 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
456 * This is the case we actually think is likely, so take pains to
457 * give a specific message for it.
459 * errno will not be set meaningfully here, so don't use it.
462 (errcode(ERRCODE_CONNECTION_FAILURE),
463 errmsg("test message did not get through on socket for statistics collector")));
464 closesocket(pgStatSock);
465 pgStatSock = PGINVALID_SOCKET;
469 test_byte++; /* just make sure variable is changed */
472 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
475 goto retry2; /* if interrupted, just retry */
477 (errcode_for_socket_access(),
478 errmsg("could not receive test message on socket for statistics collector: %m")));
479 closesocket(pgStatSock);
480 pgStatSock = PGINVALID_SOCKET;
484 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
487 (errcode(ERRCODE_INTERNAL_ERROR),
488 errmsg("incorrect test message transmission on socket for statistics collector")));
489 closesocket(pgStatSock);
490 pgStatSock = PGINVALID_SOCKET;
494 /* If we get here, we have a working socket */
498 /* Did we find a working address? */
499 if (!addr || pgStatSock == PGINVALID_SOCKET)
503 * Set the socket to non-blocking IO. This ensures that if the collector
504 * falls behind, statistics messages will be discarded; backends won't
505 * block waiting to send messages to the collector.
507 if (!pg_set_noblock(pgStatSock))
510 (errcode_for_socket_access(),
511 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
515 pg_freeaddrinfo_all(hints.ai_family, addrs);
521 (errmsg("disabling statistics collector for lack of working socket")));
524 pg_freeaddrinfo_all(hints.ai_family, addrs);
526 if (pgStatSock != PGINVALID_SOCKET)
527 closesocket(pgStatSock);
528 pgStatSock = PGINVALID_SOCKET;
531 * Adjust GUC variables to suppress useless activity, and for debugging
532 * purposes (seeing track_counts off is a clue that we failed here). We
533 * use PGC_S_OVERRIDE because there is no point in trying to turn it back
534 * on from postgresql.conf without a restart.
536 SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
540 * pgstat_reset_all() -
542 * Remove the stats file. This is currently used only if WAL
543 * recovery is needed after a crash.
546 pgstat_reset_all(void)
548 unlink(pgstat_stat_filename);
549 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
555 * pgstat_forkexec() -
557 * Format up the arglist for, then fork and exec, statistics collector process
560 pgstat_forkexec(void)
565 av[ac++] = "postgres";
566 av[ac++] = "--forkcol";
567 av[ac++] = NULL; /* filled in by postmaster_forkexec */
570 Assert(ac < lengthof(av));
572 return postmaster_forkexec(ac, av);
574 #endif /* EXEC_BACKEND */
580 * Called from postmaster at startup or after an existing collector
581 * died. Attempt to fire up a fresh statistics collector.
583 * Returns PID of child process, or 0 if fail.
585 * Note: if fail, we will be called again from the postmaster main loop.
594 * Check that the socket is there, else pgstat_init failed and we can do
597 if (pgStatSock == PGINVALID_SOCKET)
601 * Do nothing if too soon since last collector start. This is a safety
602 * valve to protect against continuous respawn attempts if the collector
603 * is dying immediately at launch. Note that since we will be re-called
604 * from the postmaster main loop, we will get another chance later.
606 curtime = time(NULL);
607 if ((unsigned int) (curtime - last_pgstat_start_time) <
608 (unsigned int) PGSTAT_RESTART_INTERVAL)
610 last_pgstat_start_time = curtime;
613 * Okay, fork off the collector.
616 switch ((pgStatPid = pgstat_forkexec()))
618 switch ((pgStatPid = fork_process()))
623 (errmsg("could not fork statistics collector: %m")));
628 /* in postmaster child ... */
629 /* Close the postmaster's sockets */
630 ClosePostmasterPorts(false);
632 /* Lose the postmaster's on-exit routines */
635 /* Drop our connection to postmaster's shared memory, as well */
636 PGSharedMemoryDetach();
638 PgstatCollectorMain(0, NULL);
643 return (int) pgStatPid;
646 /* shouldn't get here */
651 allow_immediate_pgstat_restart(void)
653 last_pgstat_start_time = 0;
656 /* ------------------------------------------------------------
657 * Public functions used by backends follow
658 *------------------------------------------------------------
663 * pgstat_report_stat() -
665 * Called from tcop/postgres.c to send the so far collected per-table
666 * and function usage statistics to the collector. Note that this is
667 * called only when not within a transaction, so it is fair to use
668 * transaction stop time as an approximation of current time.
672 pgstat_report_stat(bool force)
674 /* we assume this inits to all zeroes: */
675 static const PgStat_TableCounts all_zeroes;
676 static TimestampTz last_report = 0;
679 PgStat_MsgTabstat regular_msg;
680 PgStat_MsgTabstat shared_msg;
684 /* Don't expend a clock check if nothing to do */
685 if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0)
686 && !have_function_stats)
690 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
691 * msec since we last sent one, or the caller wants to force stats out.
693 now = GetCurrentTransactionStopTimestamp();
695 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
700 * Scan through the TabStatusArray struct(s) to find tables that actually
701 * have counts, and build messages to send. We have to separate shared
702 * relations from regular ones because the databaseid field in the message
703 * header has to depend on that.
705 regular_msg.m_databaseid = MyDatabaseId;
706 shared_msg.m_databaseid = InvalidOid;
707 regular_msg.m_nentries = 0;
708 shared_msg.m_nentries = 0;
710 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
712 for (i = 0; i < tsa->tsa_used; i++)
714 PgStat_TableStatus *entry = &tsa->tsa_entries[i];
715 PgStat_MsgTabstat *this_msg;
716 PgStat_TableEntry *this_ent;
718 /* Shouldn't have any pending transaction-dependent counts */
719 Assert(entry->trans == NULL);
722 * Ignore entries that didn't accumulate any actual counts, such
723 * as indexes that were opened by the planner but not used.
725 if (memcmp(&entry->t_counts, &all_zeroes,
726 sizeof(PgStat_TableCounts)) == 0)
730 * OK, insert data into the appropriate message, and send if full.
732 this_msg = entry->t_shared ? &shared_msg : ®ular_msg;
733 this_ent = &this_msg->m_entry[this_msg->m_nentries];
734 this_ent->t_id = entry->t_id;
735 memcpy(&this_ent->t_counts, &entry->t_counts,
736 sizeof(PgStat_TableCounts));
737 if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
739 pgstat_send_tabstat(this_msg);
740 this_msg->m_nentries = 0;
743 /* zero out TableStatus structs after use */
744 MemSet(tsa->tsa_entries, 0,
745 tsa->tsa_used * sizeof(PgStat_TableStatus));
750 * Send partial messages. If force is true, make sure that any pending
751 * xact commit/abort gets counted, even if no table stats to send.
753 if (regular_msg.m_nentries > 0 ||
754 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
755 pgstat_send_tabstat(®ular_msg);
756 if (shared_msg.m_nentries > 0)
757 pgstat_send_tabstat(&shared_msg);
759 /* Now, send function statistics */
760 pgstat_send_funcstats();
764 * Subroutine for pgstat_report_stat: finish and send a tabstat message
767 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
772 /* It's unlikely we'd get here with no socket, but maybe not impossible */
773 if (pgStatSock == PGINVALID_SOCKET)
777 * Report accumulated xact commit/rollback whenever we send a normal
780 if (OidIsValid(tsmsg->m_databaseid))
782 tsmsg->m_xact_commit = pgStatXactCommit;
783 tsmsg->m_xact_rollback = pgStatXactRollback;
784 pgStatXactCommit = 0;
785 pgStatXactRollback = 0;
789 tsmsg->m_xact_commit = 0;
790 tsmsg->m_xact_rollback = 0;
793 n = tsmsg->m_nentries;
794 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
795 n * sizeof(PgStat_TableEntry);
797 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
798 pgstat_send(tsmsg, len);
802 * Subroutine for pgstat_report_stat: populate and send a function stat message
805 pgstat_send_funcstats(void)
807 /* we assume this inits to all zeroes: */
808 static const PgStat_FunctionCounts all_zeroes;
810 PgStat_MsgFuncstat msg;
811 PgStat_BackendFunctionEntry *entry;
812 HASH_SEQ_STATUS fstat;
814 if (pgStatFunctions == NULL)
817 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
818 msg.m_databaseid = MyDatabaseId;
821 hash_seq_init(&fstat, pgStatFunctions);
822 while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
824 PgStat_FunctionEntry *m_ent;
826 /* Skip it if no counts accumulated since last time */
827 if (memcmp(&entry->f_counts, &all_zeroes,
828 sizeof(PgStat_FunctionCounts)) == 0)
831 /* need to convert format of time accumulators */
832 m_ent = &msg.m_entry[msg.m_nentries];
833 m_ent->f_id = entry->f_id;
834 m_ent->f_numcalls = entry->f_counts.f_numcalls;
835 m_ent->f_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time);
836 m_ent->f_time_self = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time_self);
838 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
840 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
841 msg.m_nentries * sizeof(PgStat_FunctionEntry));
845 /* reset the entry's counts */
846 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
849 if (msg.m_nentries > 0)
850 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
851 msg.m_nentries * sizeof(PgStat_FunctionEntry));
853 have_function_stats = false;
858 * pgstat_vacuum_stat() -
860 * Will tell the collector about objects he can get rid of.
864 pgstat_vacuum_stat(void)
867 PgStat_MsgTabpurge msg;
868 PgStat_MsgFuncpurge f_msg;
869 HASH_SEQ_STATUS hstat;
870 PgStat_StatDBEntry *dbentry;
871 PgStat_StatTabEntry *tabentry;
872 PgStat_StatFuncEntry *funcentry;
875 if (pgStatSock == PGINVALID_SOCKET)
879 * If not done for this transaction, read the statistics collector stats
880 * file into some hash tables.
882 backend_read_statsfile();
885 * Read pg_database and make a list of OIDs of all existing databases
887 htab = pgstat_collect_oids(DatabaseRelationId);
890 * Search the database hash table for dead databases and tell the
891 * collector to drop them.
893 hash_seq_init(&hstat, pgStatDBHash);
894 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
896 Oid dbid = dbentry->databaseid;
898 CHECK_FOR_INTERRUPTS();
900 /* the DB entry for shared tables (with InvalidOid) is never dropped */
901 if (OidIsValid(dbid) &&
902 hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
903 pgstat_drop_database(dbid);
910 * Lookup our own database entry; if not found, nothing more to do.
912 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
913 (void *) &MyDatabaseId,
915 if (dbentry == NULL || dbentry->tables == NULL)
919 * Similarly to above, make a list of all known relations in this DB.
921 htab = pgstat_collect_oids(RelationRelationId);
924 * Initialize our messages table counter to zero
929 * Check for all tables listed in stats hashtable if they still exist.
931 hash_seq_init(&hstat, dbentry->tables);
932 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
934 Oid tabid = tabentry->tableid;
936 CHECK_FOR_INTERRUPTS();
938 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
942 * Not there, so add this table's Oid to the message
944 msg.m_tableid[msg.m_nentries++] = tabid;
947 * If the message is full, send it out and reinitialize to empty
949 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
951 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
952 +msg.m_nentries * sizeof(Oid);
954 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
955 msg.m_databaseid = MyDatabaseId;
956 pgstat_send(&msg, len);
965 if (msg.m_nentries > 0)
967 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
968 +msg.m_nentries * sizeof(Oid);
970 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
971 msg.m_databaseid = MyDatabaseId;
972 pgstat_send(&msg, len);
979 * Now repeat the above steps for functions. However, we needn't bother
980 * in the common case where no function stats are being collected.
982 if (dbentry->functions != NULL &&
983 hash_get_num_entries(dbentry->functions) > 0)
985 htab = pgstat_collect_oids(ProcedureRelationId);
987 pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
988 f_msg.m_databaseid = MyDatabaseId;
989 f_msg.m_nentries = 0;
991 hash_seq_init(&hstat, dbentry->functions);
992 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
994 Oid funcid = funcentry->functionid;
996 CHECK_FOR_INTERRUPTS();
998 if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
1002 * Not there, so add this function's Oid to the message
1004 f_msg.m_functionid[f_msg.m_nentries++] = funcid;
1007 * If the message is full, send it out and reinitialize to empty
1009 if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
1011 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1012 +f_msg.m_nentries * sizeof(Oid);
1014 pgstat_send(&f_msg, len);
1016 f_msg.m_nentries = 0;
1023 if (f_msg.m_nentries > 0)
1025 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1026 +f_msg.m_nentries * sizeof(Oid);
1028 pgstat_send(&f_msg, len);
1037 * pgstat_collect_oids() -
1039 * Collect the OIDs of all objects listed in the specified system catalog
1040 * into a temporary hash table. Caller should hash_destroy the result
1041 * when done with it. (However, we make the table in CurrentMemoryContext
1042 * so that it will be freed properly in event of an error.)
1046 pgstat_collect_oids(Oid catalogid)
1054 memset(&hash_ctl, 0, sizeof(hash_ctl));
1055 hash_ctl.keysize = sizeof(Oid);
1056 hash_ctl.entrysize = sizeof(Oid);
1057 hash_ctl.hash = oid_hash;
1058 hash_ctl.hcxt = CurrentMemoryContext;
1059 htab = hash_create("Temporary table of OIDs",
1060 PGSTAT_TAB_HASH_SIZE,
1062 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
1064 rel = heap_open(catalogid, AccessShareLock);
1065 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1066 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1068 Oid thisoid = HeapTupleGetOid(tup);
1070 CHECK_FOR_INTERRUPTS();
1072 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1075 heap_close(rel, AccessShareLock);
1082 * pgstat_drop_database() -
1084 * Tell the collector that we just dropped a database.
1085 * (If the message gets lost, we will still clean the dead DB eventually
1086 * via future invocations of pgstat_vacuum_stat().)
1090 pgstat_drop_database(Oid databaseid)
1092 PgStat_MsgDropdb msg;
1094 if (pgStatSock == PGINVALID_SOCKET)
1097 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1098 msg.m_databaseid = databaseid;
1099 pgstat_send(&msg, sizeof(msg));
1104 * pgstat_drop_relation() -
1106 * Tell the collector that we just dropped a relation.
1107 * (If the message gets lost, we will still clean the dead entry eventually
1108 * via future invocations of pgstat_vacuum_stat().)
1110 * Currently not used for lack of any good place to call it; we rely
1111 * entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1116 pgstat_drop_relation(Oid relid)
1118 PgStat_MsgTabpurge msg;
1121 if (pgStatSock == PGINVALID_SOCKET)
1124 msg.m_tableid[0] = relid;
1127 len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
1129 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1130 msg.m_databaseid = MyDatabaseId;
1131 pgstat_send(&msg, len);
1133 #endif /* NOT_USED */
1137 * pgstat_reset_counters() -
1139 * Tell the statistics collector to reset counters for our database.
1143 pgstat_reset_counters(void)
1145 PgStat_MsgResetcounter msg;
1147 if (pgStatSock == PGINVALID_SOCKET)
1152 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1153 errmsg("must be superuser to reset statistics counters")));
1155 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1156 msg.m_databaseid = MyDatabaseId;
1157 pgstat_send(&msg, sizeof(msg));
1161 * pgstat_reset_shared_counters() -
1163 * Tell the statistics collector to reset cluster-wide shared counters.
1167 pgstat_reset_shared_counters(const char *target)
1169 PgStat_MsgResetsharedcounter msg;
1171 if (pgStatSock == PGINVALID_SOCKET)
1176 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1177 errmsg("must be superuser to reset statistics counters")));
1179 if (strcmp(target, "bgwriter") == 0)
1180 msg.m_resettarget = RESET_BGWRITER;
1183 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1184 errmsg("unrecognized reset target: \"%s\"", target),
1185 errhint("Target must be \"bgwriter\".")));
1187 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
1188 pgstat_send(&msg, sizeof(msg));
1192 * pgstat_reset_single_counter() -
1194 * Tell the statistics collector to reset a single counter.
1198 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
1200 PgStat_MsgResetsinglecounter msg;
1202 if (pgStatSock == PGINVALID_SOCKET)
1207 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1208 errmsg("must be superuser to reset statistics counters")));
1210 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
1211 msg.m_databaseid = MyDatabaseId;
1212 msg.m_resettype = type;
1213 msg.m_objectid = objoid;
1215 pgstat_send(&msg, sizeof(msg));
1219 * pgstat_report_autovac() -
1221 * Called from autovacuum.c to report startup of an autovacuum process.
1222 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1223 * the db OID must be passed in, instead.
1227 pgstat_report_autovac(Oid dboid)
1229 PgStat_MsgAutovacStart msg;
1231 if (pgStatSock == PGINVALID_SOCKET)
1234 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1235 msg.m_databaseid = dboid;
1236 msg.m_start_time = GetCurrentTimestamp();
1238 pgstat_send(&msg, sizeof(msg));
1243 * pgstat_report_vacuum() -
1245 * Tell the collector about the table we just vacuumed.
1249 pgstat_report_vacuum(Oid tableoid, bool shared, bool adopt_counts,
1250 PgStat_Counter tuples)
1252 PgStat_MsgVacuum msg;
1254 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1257 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1258 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1259 msg.m_tableoid = tableoid;
1260 msg.m_adopt_counts = adopt_counts;
1261 msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1262 msg.m_vacuumtime = GetCurrentTimestamp();
1263 msg.m_tuples = tuples;
1264 pgstat_send(&msg, sizeof(msg));
1268 * pgstat_report_analyze() -
1270 * Tell the collector about the table we just analyzed.
1274 pgstat_report_analyze(Relation rel, bool adopt_counts,
1275 PgStat_Counter livetuples, PgStat_Counter deadtuples)
1277 PgStat_MsgAnalyze msg;
1279 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1283 * Unlike VACUUM, ANALYZE might be running inside a transaction that has
1284 * already inserted and/or deleted rows in the target table. ANALYZE will
1285 * have counted such rows as live or dead respectively. Because we will
1286 * report our counts of such rows at transaction end, we should subtract
1287 * off these counts from what we send to the collector now, else they'll
1288 * be double-counted after commit. (This approach also ensures that the
1289 * collector ends up with the right numbers if we abort instead of
1292 if (rel->pgstat_info != NULL)
1294 PgStat_TableXactStatus *trans;
1296 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1298 livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1299 deadtuples -= trans->tuples_updated + trans->tuples_deleted;
1301 /* count stuff inserted by already-aborted subxacts, too */
1302 deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
1303 /* Since ANALYZE's counts are estimates, we could have underflowed */
1304 livetuples = Max(livetuples, 0);
1305 deadtuples = Max(deadtuples, 0);
1308 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1309 msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1310 msg.m_tableoid = RelationGetRelid(rel);
1311 msg.m_adopt_counts = adopt_counts;
1312 msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1313 msg.m_analyzetime = GetCurrentTimestamp();
1314 msg.m_live_tuples = livetuples;
1315 msg.m_dead_tuples = deadtuples;
1316 pgstat_send(&msg, sizeof(msg));
1320 * pgstat_report_recovery_conflict() -
1322 * Tell the collector about a Hot Standby recovery conflict.
1326 pgstat_report_recovery_conflict(int reason)
1328 PgStat_MsgRecoveryConflict msg;
1330 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1333 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
1334 msg.m_databaseid = MyDatabaseId;
1335 msg.m_reason = reason;
1336 pgstat_send(&msg, sizeof(msg));
1342 * Send some junk data to the collector to increase traffic.
1348 PgStat_MsgDummy msg;
1350 if (pgStatSock == PGINVALID_SOCKET)
1353 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1354 pgstat_send(&msg, sizeof(msg));
1358 * pgstat_send_inquiry() -
1360 * Notify collector that we need fresh data.
1361 * ts specifies the minimum acceptable timestamp for the stats file.
1365 pgstat_send_inquiry(TimestampTz ts)
1367 PgStat_MsgInquiry msg;
1369 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
1370 msg.inquiry_time = ts;
1371 pgstat_send(&msg, sizeof(msg));
1376 * Initialize function call usage data.
1377 * Called by the executor before invoking a function.
1380 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
1381 PgStat_FunctionCallUsage *fcu)
1383 PgStat_BackendFunctionEntry *htabent;
1386 if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1388 /* stats not wanted */
1393 if (!pgStatFunctions)
1395 /* First time through - initialize function stat table */
1398 memset(&hash_ctl, 0, sizeof(hash_ctl));
1399 hash_ctl.keysize = sizeof(Oid);
1400 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1401 hash_ctl.hash = oid_hash;
1402 pgStatFunctions = hash_create("Function stat entries",
1403 PGSTAT_FUNCTION_HASH_SIZE,
1405 HASH_ELEM | HASH_FUNCTION);
1408 /* Get the stats entry for this function, create if necessary */
1409 htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1410 HASH_ENTER, &found);
1412 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1414 fcu->fs = &htabent->f_counts;
1416 /* save stats for this function, later used to compensate for recursion */
1417 fcu->save_f_time = htabent->f_counts.f_time;
1419 /* save current backend-wide total time */
1420 fcu->save_total = total_func_time;
1422 /* get clock time as of function start */
1423 INSTR_TIME_SET_CURRENT(fcu->f_start);
1427 * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
1428 * for specified function
1430 * If no entry, return NULL, don't create a new one
1432 PgStat_BackendFunctionEntry *
1433 find_funcstat_entry(Oid func_id)
1435 if (pgStatFunctions == NULL)
1438 return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
1444 * Calculate function call usage and update stat counters.
1445 * Called by the executor after invoking a function.
1447 * In the case of a set-returning function that runs in value-per-call mode,
1448 * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1449 * calls for what the user considers a single call of the function. The
1450 * finalize flag should be TRUE on the last call.
1453 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1455 PgStat_FunctionCounts *fs = fcu->fs;
1457 instr_time f_others;
1460 /* stats not wanted? */
1464 /* total elapsed time in this function call */
1465 INSTR_TIME_SET_CURRENT(f_total);
1466 INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1468 /* self usage: elapsed minus anything already charged to other calls */
1469 f_others = total_func_time;
1470 INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1472 INSTR_TIME_SUBTRACT(f_self, f_others);
1474 /* update backend-wide total time */
1475 INSTR_TIME_ADD(total_func_time, f_self);
1478 * Compute the new total f_time as the total elapsed time added to the
1479 * pre-call value of f_time. This is necessary to avoid double-counting
1480 * any time taken by recursive calls of myself. (We do not need any
1481 * similar kluge for self time, since that already excludes any recursive
1484 INSTR_TIME_ADD(f_total, fcu->save_f_time);
1486 /* update counters in function stats table */
1489 fs->f_time = f_total;
1490 INSTR_TIME_ADD(fs->f_time_self, f_self);
1492 /* indicate that we have something to send */
1493 have_function_stats = true;
1498 * pgstat_initstats() -
1500 * Initialize a relcache entry to count access statistics.
1501 * Called whenever a relation is opened.
1503 * We assume that a relcache entry's pgstat_info field is zeroed by
1504 * relcache.c when the relcache entry is made; thereafter it is long-lived
1505 * data. We can avoid repeated searches of the TabStatus arrays when the
1506 * same relation is touched repeatedly within a transaction.
1510 pgstat_initstats(Relation rel)
1512 Oid rel_id = rel->rd_id;
1513 char relkind = rel->rd_rel->relkind;
1515 /* We only count stats for things that have storage */
1516 if (!(relkind == RELKIND_RELATION ||
1517 relkind == RELKIND_INDEX ||
1518 relkind == RELKIND_TOASTVALUE ||
1519 relkind == RELKIND_SEQUENCE))
1521 rel->pgstat_info = NULL;
1525 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1527 /* We're not counting at all */
1528 rel->pgstat_info = NULL;
1533 * If we already set up this relation in the current transaction, nothing
1536 if (rel->pgstat_info != NULL &&
1537 rel->pgstat_info->t_id == rel_id)
1540 /* Else find or make the PgStat_TableStatus entry, and update link */
1541 rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1545 * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1547 static PgStat_TableStatus *
1548 get_tabstat_entry(Oid rel_id, bool isshared)
1550 PgStat_TableStatus *entry;
1551 TabStatusArray *tsa;
1552 TabStatusArray *prev_tsa;
1556 * Search the already-used tabstat slots for this relation.
1559 for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1561 for (i = 0; i < tsa->tsa_used; i++)
1563 entry = &tsa->tsa_entries[i];
1564 if (entry->t_id == rel_id)
1568 if (tsa->tsa_used < TABSTAT_QUANTUM)
1571 * It must not be present, but we found a free slot instead. Fine,
1572 * let's use this one. We assume the entry was already zeroed,
1573 * either at creation or after last use.
1575 entry = &tsa->tsa_entries[tsa->tsa_used++];
1576 entry->t_id = rel_id;
1577 entry->t_shared = isshared;
1583 * We ran out of tabstat slots, so allocate more. Be sure they're zeroed.
1585 tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1586 sizeof(TabStatusArray));
1588 prev_tsa->tsa_next = tsa;
1590 pgStatTabList = tsa;
1593 * Use the first entry of the new TabStatusArray.
1595 entry = &tsa->tsa_entries[tsa->tsa_used++];
1596 entry->t_id = rel_id;
1597 entry->t_shared = isshared;
1602 * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
1604 * If no entry, return NULL, don't create a new one
1606 PgStat_TableStatus *
1607 find_tabstat_entry(Oid rel_id)
1609 PgStat_TableStatus *entry;
1610 TabStatusArray *tsa;
1613 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
1615 for (i = 0; i < tsa->tsa_used; i++)
1617 entry = &tsa->tsa_entries[i];
1618 if (entry->t_id == rel_id)
1628 * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1630 static PgStat_SubXactStatus *
1631 get_tabstat_stack_level(int nest_level)
1633 PgStat_SubXactStatus *xact_state;
1635 xact_state = pgStatXactStack;
1636 if (xact_state == NULL || xact_state->nest_level != nest_level)
1638 xact_state = (PgStat_SubXactStatus *)
1639 MemoryContextAlloc(TopTransactionContext,
1640 sizeof(PgStat_SubXactStatus));
1641 xact_state->nest_level = nest_level;
1642 xact_state->prev = pgStatXactStack;
1643 xact_state->first = NULL;
1644 pgStatXactStack = xact_state;
1650 * add_tabstat_xact_level - add a new (sub)transaction state record
1653 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1655 PgStat_SubXactStatus *xact_state;
1656 PgStat_TableXactStatus *trans;
1659 * If this is the first rel to be modified at the current nest level, we
1660 * first have to push a transaction stack entry.
1662 xact_state = get_tabstat_stack_level(nest_level);
1664 /* Now make a per-table stack entry */
1665 trans = (PgStat_TableXactStatus *)
1666 MemoryContextAllocZero(TopTransactionContext,
1667 sizeof(PgStat_TableXactStatus));
1668 trans->nest_level = nest_level;
1669 trans->upper = pgstat_info->trans;
1670 trans->parent = pgstat_info;
1671 trans->next = xact_state->first;
1672 xact_state->first = trans;
1673 pgstat_info->trans = trans;
1677 * pgstat_count_heap_insert - count a tuple insertion
1680 pgstat_count_heap_insert(Relation rel)
1682 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1684 if (pgstat_info != NULL)
1686 /* We have to log the effect at the proper transactional level */
1687 int nest_level = GetCurrentTransactionNestLevel();
1689 if (pgstat_info->trans == NULL ||
1690 pgstat_info->trans->nest_level != nest_level)
1691 add_tabstat_xact_level(pgstat_info, nest_level);
1693 pgstat_info->trans->tuples_inserted++;
1698 * pgstat_count_heap_update - count a tuple update
1701 pgstat_count_heap_update(Relation rel, bool hot)
1703 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1705 if (pgstat_info != NULL)
1707 /* We have to log the effect at the proper transactional level */
1708 int nest_level = GetCurrentTransactionNestLevel();
1710 if (pgstat_info->trans == NULL ||
1711 pgstat_info->trans->nest_level != nest_level)
1712 add_tabstat_xact_level(pgstat_info, nest_level);
1714 pgstat_info->trans->tuples_updated++;
1716 /* t_tuples_hot_updated is nontransactional, so just advance it */
1718 pgstat_info->t_counts.t_tuples_hot_updated++;
1723 * pgstat_count_heap_delete - count a tuple deletion
1726 pgstat_count_heap_delete(Relation rel)
1728 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1730 if (pgstat_info != NULL)
1732 /* We have to log the effect at the proper transactional level */
1733 int nest_level = GetCurrentTransactionNestLevel();
1735 if (pgstat_info->trans == NULL ||
1736 pgstat_info->trans->nest_level != nest_level)
1737 add_tabstat_xact_level(pgstat_info, nest_level);
1739 pgstat_info->trans->tuples_deleted++;
1744 * pgstat_update_heap_dead_tuples - update dead-tuples count
1746 * The semantics of this are that we are reporting the nontransactional
1747 * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
1748 * rather than increasing, and the change goes straight into the per-table
1749 * counter, not into transactional state.
1752 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1754 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1756 if (pgstat_info != NULL)
1757 pgstat_info->t_counts.t_delta_dead_tuples -= delta;
1764 * Called from access/transam/xact.c at top-level transaction commit/abort.
1768 AtEOXact_PgStat(bool isCommit)
1770 PgStat_SubXactStatus *xact_state;
1773 * Count transaction commit or abort. (We use counters, not just bools,
1774 * in case the reporting message isn't sent right away.)
1779 pgStatXactRollback++;
1782 * Transfer transactional insert/update counts into the base tabstat
1783 * entries. We don't bother to free any of the transactional state, since
1784 * it's all in TopTransactionContext and will go away anyway.
1786 xact_state = pgStatXactStack;
1787 if (xact_state != NULL)
1789 PgStat_TableXactStatus *trans;
1791 Assert(xact_state->nest_level == 1);
1792 Assert(xact_state->prev == NULL);
1793 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1795 PgStat_TableStatus *tabstat;
1797 Assert(trans->nest_level == 1);
1798 Assert(trans->upper == NULL);
1799 tabstat = trans->parent;
1800 Assert(tabstat->trans == trans);
1801 /* count attempted actions regardless of commit/abort */
1802 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
1803 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
1804 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
1807 /* insert adds a live tuple, delete removes one */
1808 tabstat->t_counts.t_delta_live_tuples +=
1809 trans->tuples_inserted - trans->tuples_deleted;
1810 /* update and delete each create a dead tuple */
1811 tabstat->t_counts.t_delta_dead_tuples +=
1812 trans->tuples_updated + trans->tuples_deleted;
1813 /* insert, update, delete each count as one change event */
1814 tabstat->t_counts.t_changed_tuples +=
1815 trans->tuples_inserted + trans->tuples_updated +
1816 trans->tuples_deleted;
1820 /* inserted tuples are dead, deleted tuples are unaffected */
1821 tabstat->t_counts.t_delta_dead_tuples +=
1822 trans->tuples_inserted + trans->tuples_updated;
1823 /* an aborted xact generates no changed_tuple events */
1825 tabstat->trans = NULL;
1828 pgStatXactStack = NULL;
1830 /* Make sure any stats snapshot is thrown away */
1831 pgstat_clear_snapshot();
1835 * AtEOSubXact_PgStat
1837 * Called from access/transam/xact.c at subtransaction commit/abort.
1841 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1843 PgStat_SubXactStatus *xact_state;
1846 * Transfer transactional insert/update counts into the next higher
1847 * subtransaction state.
1849 xact_state = pgStatXactStack;
1850 if (xact_state != NULL &&
1851 xact_state->nest_level >= nestDepth)
1853 PgStat_TableXactStatus *trans;
1854 PgStat_TableXactStatus *next_trans;
1856 /* delink xact_state from stack immediately to simplify reuse case */
1857 pgStatXactStack = xact_state->prev;
1859 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1861 PgStat_TableStatus *tabstat;
1863 next_trans = trans->next;
1864 Assert(trans->nest_level == nestDepth);
1865 tabstat = trans->parent;
1866 Assert(tabstat->trans == trans);
1869 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1871 trans->upper->tuples_inserted += trans->tuples_inserted;
1872 trans->upper->tuples_updated += trans->tuples_updated;
1873 trans->upper->tuples_deleted += trans->tuples_deleted;
1874 tabstat->trans = trans->upper;
1880 * When there isn't an immediate parent state, we can just
1881 * reuse the record instead of going through a
1882 * palloc/pfree pushup (this works since it's all in
1883 * TopTransactionContext anyway). We have to re-link it
1884 * into the parent level, though, and that might mean
1885 * pushing a new entry into the pgStatXactStack.
1887 PgStat_SubXactStatus *upper_xact_state;
1889 upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1890 trans->next = upper_xact_state->first;
1891 upper_xact_state->first = trans;
1892 trans->nest_level = nestDepth - 1;
1898 * On abort, update top-level tabstat counts, then forget the
1902 /* count attempted actions regardless of commit/abort */
1903 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
1904 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
1905 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
1906 /* inserted tuples are dead, deleted tuples are unaffected */
1907 tabstat->t_counts.t_delta_dead_tuples +=
1908 trans->tuples_inserted + trans->tuples_updated;
1909 tabstat->trans = trans->upper;
1920 * Save the transactional stats state at 2PC transaction prepare.
1922 * In this phase we just generate 2PC records for all the pending
1923 * transaction-dependent stats work.
1926 AtPrepare_PgStat(void)
1928 PgStat_SubXactStatus *xact_state;
1930 xact_state = pgStatXactStack;
1931 if (xact_state != NULL)
1933 PgStat_TableXactStatus *trans;
1935 Assert(xact_state->nest_level == 1);
1936 Assert(xact_state->prev == NULL);
1937 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1939 PgStat_TableStatus *tabstat;
1940 TwoPhasePgStatRecord record;
1942 Assert(trans->nest_level == 1);
1943 Assert(trans->upper == NULL);
1944 tabstat = trans->parent;
1945 Assert(tabstat->trans == trans);
1947 record.tuples_inserted = trans->tuples_inserted;
1948 record.tuples_updated = trans->tuples_updated;
1949 record.tuples_deleted = trans->tuples_deleted;
1950 record.t_id = tabstat->t_id;
1951 record.t_shared = tabstat->t_shared;
1953 RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1954 &record, sizeof(TwoPhasePgStatRecord));
1960 * PostPrepare_PgStat
1961 * Clean up after successful PREPARE.
1963 * All we need do here is unlink the transaction stats state from the
1964 * nontransactional state. The nontransactional action counts will be
1965 * reported to the stats collector immediately, while the effects on live
1966 * and dead tuple counts are preserved in the 2PC state file.
1968 * Note: AtEOXact_PgStat is not called during PREPARE.
1971 PostPrepare_PgStat(void)
1973 PgStat_SubXactStatus *xact_state;
1976 * We don't bother to free any of the transactional state, since it's all
1977 * in TopTransactionContext and will go away anyway.
1979 xact_state = pgStatXactStack;
1980 if (xact_state != NULL)
1982 PgStat_TableXactStatus *trans;
1984 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1986 PgStat_TableStatus *tabstat;
1988 tabstat = trans->parent;
1989 tabstat->trans = NULL;
1992 pgStatXactStack = NULL;
1994 /* Make sure any stats snapshot is thrown away */
1995 pgstat_clear_snapshot();
1999 * 2PC processing routine for COMMIT PREPARED case.
2001 * Load the saved counts into our local pgstats state.
2004 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
2005 void *recdata, uint32 len)
2007 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2008 PgStat_TableStatus *pgstat_info;
2010 /* Find or create a tabstat entry for the rel */
2011 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2013 /* Same math as in AtEOXact_PgStat, commit case */
2014 pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2015 pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2016 pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2017 pgstat_info->t_counts.t_delta_live_tuples +=
2018 rec->tuples_inserted - rec->tuples_deleted;
2019 pgstat_info->t_counts.t_delta_dead_tuples +=
2020 rec->tuples_updated + rec->tuples_deleted;
2021 pgstat_info->t_counts.t_changed_tuples +=
2022 rec->tuples_inserted + rec->tuples_updated +
2023 rec->tuples_deleted;
2027 * 2PC processing routine for ROLLBACK PREPARED case.
2029 * Load the saved counts into our local pgstats state, but treat them
2033 pgstat_twophase_postabort(TransactionId xid, uint16 info,
2034 void *recdata, uint32 len)
2036 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2037 PgStat_TableStatus *pgstat_info;
2039 /* Find or create a tabstat entry for the rel */
2040 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2042 /* Same math as in AtEOXact_PgStat, abort case */
2043 pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2044 pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2045 pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2046 pgstat_info->t_counts.t_delta_dead_tuples +=
2047 rec->tuples_inserted + rec->tuples_updated;
2052 * pgstat_fetch_stat_dbentry() -
2054 * Support function for the SQL-callable pgstat* functions. Returns
2055 * the collected statistics for one database or NULL. NULL doesn't mean
2056 * that the database doesn't exist, it is just not yet known by the
2057 * collector, so the caller is better off to report ZERO instead.
2060 PgStat_StatDBEntry *
2061 pgstat_fetch_stat_dbentry(Oid dbid)
2064 * If not done for this transaction, read the statistics collector stats
2065 * file into some hash tables.
2067 backend_read_statsfile();
2070 * Lookup the requested database; return NULL if not found
2072 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2079 * pgstat_fetch_stat_tabentry() -
2081 * Support function for the SQL-callable pgstat* functions. Returns
2082 * the collected statistics for one table or NULL. NULL doesn't mean
2083 * that the table doesn't exist, it is just not yet known by the
2084 * collector, so the caller is better off to report ZERO instead.
2087 PgStat_StatTabEntry *
2088 pgstat_fetch_stat_tabentry(Oid relid)
2091 PgStat_StatDBEntry *dbentry;
2092 PgStat_StatTabEntry *tabentry;
2095 * If not done for this transaction, read the statistics collector stats
2096 * file into some hash tables.
2098 backend_read_statsfile();
2101 * Lookup our database, then look in its table hash table.
2103 dbid = MyDatabaseId;
2104 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2107 if (dbentry != NULL && dbentry->tables != NULL)
2109 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2117 * If we didn't find it, maybe it's a shared table.
2120 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2123 if (dbentry != NULL && dbentry->tables != NULL)
2125 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2137 * pgstat_fetch_stat_funcentry() -
2139 * Support function for the SQL-callable pgstat* functions. Returns
2140 * the collected statistics for one function or NULL.
2143 PgStat_StatFuncEntry *
2144 pgstat_fetch_stat_funcentry(Oid func_id)
2146 PgStat_StatDBEntry *dbentry;
2147 PgStat_StatFuncEntry *funcentry = NULL;
2149 /* load the stats file if needed */
2150 backend_read_statsfile();
2152 /* Lookup our database, then find the requested function. */
2153 dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
2154 if (dbentry != NULL && dbentry->functions != NULL)
2156 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2166 * pgstat_fetch_stat_beentry() -
2168 * Support function for the SQL-callable pgstat* functions. Returns
2169 * our local copy of the current-activity entry for one backend.
2171 * NB: caller is responsible for a check if the user is permitted to see
2172 * this info (especially the querystring).
2176 pgstat_fetch_stat_beentry(int beid)
2178 pgstat_read_current_status();
2180 if (beid < 1 || beid > localNumBackends)
2183 return &localBackendStatusTable[beid - 1];
2188 * pgstat_fetch_stat_numbackends() -
2190 * Support function for the SQL-callable pgstat* functions. Returns
2191 * the maximum current backend id.
2195 pgstat_fetch_stat_numbackends(void)
2197 pgstat_read_current_status();
2199 return localNumBackends;
2204 * pgstat_fetch_global() -
2206 * Support function for the SQL-callable pgstat* functions. Returns
2207 * a pointer to the global statistics struct.
2210 PgStat_GlobalStats *
2211 pgstat_fetch_global(void)
2213 backend_read_statsfile();
2215 return &globalStats;
2219 /* ------------------------------------------------------------
2220 * Functions for management of the shared-memory PgBackendStatus array
2221 * ------------------------------------------------------------
2224 static PgBackendStatus *BackendStatusArray = NULL;
2225 static PgBackendStatus *MyBEEntry = NULL;
2226 static char *BackendAppnameBuffer = NULL;
2227 static char *BackendActivityBuffer = NULL;
2231 * Report shared-memory space needed by CreateSharedBackendStatus.
2234 BackendStatusShmemSize(void)
2238 size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2239 size = add_size(size,
2240 mul_size(NAMEDATALEN, MaxBackends));
2241 size = add_size(size,
2242 mul_size(pgstat_track_activity_query_size, MaxBackends));
2247 * Initialize the shared status array and activity/appname string buffers
2248 * during postmaster startup.
2251 CreateSharedBackendStatus(void)
2258 /* Create or attach to the shared array */
2259 size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2260 BackendStatusArray = (PgBackendStatus *)
2261 ShmemInitStruct("Backend Status Array", size, &found);
2266 * We're the first - initialize.
2268 MemSet(BackendStatusArray, 0, size);
2271 /* Create or attach to the shared appname buffer */
2272 size = mul_size(NAMEDATALEN, MaxBackends);
2273 BackendAppnameBuffer = (char *)
2274 ShmemInitStruct("Backend Application Name Buffer", size, &found);
2278 MemSet(BackendAppnameBuffer, 0, size);
2280 /* Initialize st_appname pointers. */
2281 buffer = BackendAppnameBuffer;
2282 for (i = 0; i < MaxBackends; i++)
2284 BackendStatusArray[i].st_appname = buffer;
2285 buffer += NAMEDATALEN;
2289 /* Create or attach to the shared activity buffer */
2290 size = mul_size(pgstat_track_activity_query_size, MaxBackends);
2291 BackendActivityBuffer = (char *)
2292 ShmemInitStruct("Backend Activity Buffer", size, &found);
2296 MemSet(BackendActivityBuffer, 0, size);
2298 /* Initialize st_activity pointers. */
2299 buffer = BackendActivityBuffer;
2300 for (i = 0; i < MaxBackends; i++)
2302 BackendStatusArray[i].st_activity = buffer;
2303 buffer += pgstat_track_activity_query_size;
2310 * pgstat_initialize() -
2312 * Initialize pgstats state, and set up our on-proc-exit hook.
2313 * Called from InitPostgres. MyBackendId must be set,
2314 * but we must not have started any transaction yet (since the
2315 * exit hook must run after the last transaction exit).
2316 * NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
2320 pgstat_initialize(void)
2322 /* Initialize MyBEEntry */
2323 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2324 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2326 /* Set up a process-exit hook to clean up */
2327 on_shmem_exit(pgstat_beshutdown_hook, 0);
2331 * pgstat_bestart() -
2333 * Initialize this backend's entry in the PgBackendStatus array.
2334 * Called from InitPostgres.
2335 * MyDatabaseId, session userid, and application_name must be set
2336 * (hence, this cannot be combined with pgstat_initialize).
2340 pgstat_bestart(void)
2342 TimestampTz proc_start_timestamp;
2344 SockAddr clientaddr;
2345 volatile PgBackendStatus *beentry;
2348 * To minimize the time spent modifying the PgBackendStatus entry, fetch
2349 * all the needed data first.
2351 * If we have a MyProcPort, use its session start time (for consistency,
2352 * and to save a kernel call).
2355 proc_start_timestamp = MyProcPort->SessionStartTime;
2357 proc_start_timestamp = GetCurrentTimestamp();
2358 userid = GetSessionUserId();
2361 * We may not have a MyProcPort (eg, if this is the autovacuum process).
2362 * If so, use all-zeroes client address, which is dealt with specially in
2363 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2366 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2368 MemSet(&clientaddr, 0, sizeof(clientaddr));
2371 * Initialize my status entry, following the protocol of bumping
2372 * st_changecount before and after; and make sure it's even afterwards. We
2373 * use a volatile pointer here to ensure the compiler doesn't try to get
2376 beentry = MyBEEntry;
2379 beentry->st_changecount++;
2380 } while ((beentry->st_changecount & 1) == 0);
2382 beentry->st_procpid = MyProcPid;
2383 beentry->st_proc_start_timestamp = proc_start_timestamp;
2384 beentry->st_activity_start_timestamp = 0;
2385 beentry->st_xact_start_timestamp = 0;
2386 beentry->st_databaseid = MyDatabaseId;
2387 beentry->st_userid = userid;
2388 beentry->st_clientaddr = clientaddr;
2389 beentry->st_waiting = false;
2390 beentry->st_appname[0] = '\0';
2391 beentry->st_activity[0] = '\0';
2392 /* Also make sure the last byte in each string area is always 0 */
2393 beentry->st_appname[NAMEDATALEN - 1] = '\0';
2394 beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2396 beentry->st_changecount++;
2397 Assert((beentry->st_changecount & 1) == 0);
2399 /* Update app name to current GUC setting */
2400 if (application_name)
2401 pgstat_report_appname(application_name);
2405 * Shut down a single backend's statistics reporting at process exit.
2407 * Flush any remaining statistics counts out to the collector.
2408 * Without this, operations triggered during backend exit (such as
2409 * temp table deletions) won't be counted.
2411 * Lastly, clear out our entry in the PgBackendStatus array.
2414 pgstat_beshutdown_hook(int code, Datum arg)
2416 volatile PgBackendStatus *beentry = MyBEEntry;
2419 * If we got as far as discovering our own database ID, we can report what
2420 * we did to the collector. Otherwise, we'd be sending an invalid
2421 * database ID, so forget it. (This means that accesses to pg_database
2422 * during failed backend starts might never get counted.)
2424 if (OidIsValid(MyDatabaseId))
2425 pgstat_report_stat(true);
2428 * Clear my status entry, following the protocol of bumping st_changecount
2429 * before and after. We use a volatile pointer here to ensure the
2430 * compiler doesn't try to get cute.
2432 beentry->st_changecount++;
2434 beentry->st_procpid = 0; /* mark invalid */
2436 beentry->st_changecount++;
2437 Assert((beentry->st_changecount & 1) == 0);
2442 * pgstat_report_activity() -
2444 * Called from tcop/postgres.c to report what the backend is actually doing
2445 * (usually "<IDLE>" or the start of the query to be executed).
2449 pgstat_report_activity(const char *cmd_str)
2451 volatile PgBackendStatus *beentry = MyBEEntry;
2452 TimestampTz start_timestamp;
2455 TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
2457 if (!pgstat_track_activities || !beentry)
2461 * To minimize the time spent modifying the entry, fetch all the needed
2464 start_timestamp = GetCurrentStatementStartTimestamp();
2466 len = strlen(cmd_str);
2467 len = pg_mbcliplen(cmd_str, len, pgstat_track_activity_query_size - 1);
2470 * Update my status entry, following the protocol of bumping
2471 * st_changecount before and after. We use a volatile pointer here to
2472 * ensure the compiler doesn't try to get cute.
2474 beentry->st_changecount++;
2476 beentry->st_activity_start_timestamp = start_timestamp;
2477 memcpy((char *) beentry->st_activity, cmd_str, len);
2478 beentry->st_activity[len] = '\0';
2480 beentry->st_changecount++;
2481 Assert((beentry->st_changecount & 1) == 0);
2485 * pgstat_report_appname() -
2487 * Called to update our application name.
2491 pgstat_report_appname(const char *appname)
2493 volatile PgBackendStatus *beentry = MyBEEntry;
2499 /* This should be unnecessary if GUC did its job, but be safe */
2500 len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
2503 * Update my status entry, following the protocol of bumping
2504 * st_changecount before and after. We use a volatile pointer here to
2505 * ensure the compiler doesn't try to get cute.
2507 beentry->st_changecount++;
2509 memcpy((char *) beentry->st_appname, appname, len);
2510 beentry->st_appname[len] = '\0';
2512 beentry->st_changecount++;
2513 Assert((beentry->st_changecount & 1) == 0);
2517 * Report current transaction start timestamp as the specified value.
2518 * Zero means there is no active transaction.
2521 pgstat_report_xact_timestamp(TimestampTz tstamp)
2523 volatile PgBackendStatus *beentry = MyBEEntry;
2525 if (!pgstat_track_activities || !beentry)
2529 * Update my status entry, following the protocol of bumping
2530 * st_changecount before and after. We use a volatile pointer here to
2531 * ensure the compiler doesn't try to get cute.
2533 beentry->st_changecount++;
2534 beentry->st_xact_start_timestamp = tstamp;
2535 beentry->st_changecount++;
2536 Assert((beentry->st_changecount & 1) == 0);
2540 * pgstat_report_waiting() -
2542 * Called from lock manager to report beginning or end of a lock wait.
2544 * NB: this *must* be able to survive being called before MyBEEntry has been
2549 pgstat_report_waiting(bool waiting)
2551 volatile PgBackendStatus *beentry = MyBEEntry;
2553 if (!pgstat_track_activities || !beentry)
2557 * Since this is a single-byte field in a struct that only this process
2558 * may modify, there seems no need to bother with the st_changecount
2559 * protocol. The update must appear atomic in any case.
2561 beentry->st_waiting = waiting;
2566 * pgstat_read_current_status() -
2568 * Copy the current contents of the PgBackendStatus array to local memory,
2569 * if not already done in this transaction.
2573 pgstat_read_current_status(void)
2575 volatile PgBackendStatus *beentry;
2576 PgBackendStatus *localtable;
2577 PgBackendStatus *localentry;
2582 Assert(!pgStatRunningInCollector);
2583 if (localBackendStatusTable)
2584 return; /* already done */
2586 pgstat_setup_memcxt();
2588 localtable = (PgBackendStatus *)
2589 MemoryContextAlloc(pgStatLocalContext,
2590 sizeof(PgBackendStatus) * MaxBackends);
2591 localappname = (char *)
2592 MemoryContextAlloc(pgStatLocalContext,
2593 NAMEDATALEN * MaxBackends);
2594 localactivity = (char *)
2595 MemoryContextAlloc(pgStatLocalContext,
2596 pgstat_track_activity_query_size * MaxBackends);
2597 localNumBackends = 0;
2599 beentry = BackendStatusArray;
2600 localentry = localtable;
2601 for (i = 1; i <= MaxBackends; i++)
2604 * Follow the protocol of retrying if st_changecount changes while we
2605 * copy the entry, or if it's odd. (The check for odd is needed to
2606 * cover the case where we are able to completely copy the entry while
2607 * the source backend is between increment steps.) We use a volatile
2608 * pointer here to ensure the compiler doesn't try to get cute.
2612 int save_changecount = beentry->st_changecount;
2614 localentry->st_procpid = beentry->st_procpid;
2615 if (localentry->st_procpid > 0)
2617 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2620 * strcpy is safe even if the string is modified concurrently,
2621 * because there's always a \0 at the end of the buffer.
2623 strcpy(localappname, (char *) beentry->st_appname);
2624 localentry->st_appname = localappname;
2625 strcpy(localactivity, (char *) beentry->st_activity);
2626 localentry->st_activity = localactivity;
2629 if (save_changecount == beentry->st_changecount &&
2630 (save_changecount & 1) == 0)
2633 /* Make sure we can break out of loop if stuck... */
2634 CHECK_FOR_INTERRUPTS();
2638 /* Only valid entries get included into the local array */
2639 if (localentry->st_procpid > 0)
2642 localappname += NAMEDATALEN;
2643 localactivity += pgstat_track_activity_query_size;
2648 /* Set the pointer only after completion of a valid table */
2649 localBackendStatusTable = localtable;
2654 * pgstat_get_backend_current_activity() -
2656 * Return a string representing the current activity of the backend with
2657 * the specified PID. This looks directly at the BackendStatusArray,
2658 * and so will provide current information regardless of the age of our
2659 * transaction's snapshot of the status array.
2661 * It is the caller's responsibility to invoke this only for backends whose
2662 * state is expected to remain stable while the result is in use. The
2663 * only current use is in deadlock reporting, where we can expect that
2664 * the target backend is blocked on a lock. (There are corner cases
2665 * where the target's wait could get aborted while we are looking at it,
2666 * but the very worst consequence is to return a pointer to a string
2667 * that's been changed, so we won't worry too much.)
2669 * Note: return strings for special cases match pg_stat_get_backend_activity.
2673 pgstat_get_backend_current_activity(int pid, bool checkUser)
2675 PgBackendStatus *beentry;
2678 beentry = BackendStatusArray;
2679 for (i = 1; i <= MaxBackends; i++)
2682 * Although we expect the target backend's entry to be stable, that
2683 * doesn't imply that anyone else's is. To avoid identifying the
2684 * wrong backend, while we check for a match to the desired PID we
2685 * must follow the protocol of retrying if st_changecount changes
2686 * while we examine the entry, or if it's odd. (This might be
2687 * unnecessary, since fetching or storing an int is almost certainly
2688 * atomic, but let's play it safe.) We use a volatile pointer here to
2689 * ensure the compiler doesn't try to get cute.
2691 volatile PgBackendStatus *vbeentry = beentry;
2696 int save_changecount = vbeentry->st_changecount;
2698 found = (vbeentry->st_procpid == pid);
2700 if (save_changecount == vbeentry->st_changecount &&
2701 (save_changecount & 1) == 0)
2704 /* Make sure we can break out of loop if stuck... */
2705 CHECK_FOR_INTERRUPTS();
2710 /* Now it is safe to use the non-volatile pointer */
2711 if (checkUser && !superuser() && beentry->st_userid != GetUserId())
2712 return "<insufficient privilege>";
2713 else if (*(beentry->st_activity) == '\0')
2714 return "<command string not enabled>";
2716 return beentry->st_activity;
2722 /* If we get here, caller is in error ... */
2723 return "<backend information not available>";
2727 /* ------------------------------------------------------------
2728 * Local support functions follow
2729 * ------------------------------------------------------------
2734 * pgstat_setheader() -
2736 * Set common header fields in a statistics message
2740 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2742 hdr->m_type = mtype;
2749 * Send out one statistics message to the collector
2753 pgstat_send(void *msg, int len)
2757 if (pgStatSock == PGINVALID_SOCKET)
2760 ((PgStat_MsgHdr *) msg)->m_size = len;
2762 /* We'll retry after EINTR, but ignore all other failures */
2765 rc = send(pgStatSock, msg, len, 0);
2766 } while (rc < 0 && errno == EINTR);
2768 #ifdef USE_ASSERT_CHECKING
2769 /* In debug builds, log send failures ... */
2771 elog(LOG, "could not send to statistics collector: %m");
2776 * pgstat_send_bgwriter() -
2778 * Send bgwriter statistics to the collector
2782 pgstat_send_bgwriter(void)
2784 /* We assume this initializes to zeroes */
2785 static const PgStat_MsgBgWriter all_zeroes;
2788 * This function can be called even if nothing at all has happened. In
2789 * this case, avoid sending a completely empty message to the stats
2792 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2796 * Prepare and send the message
2798 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2799 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2802 * Clear out the statistics buffer, so it can be re-used.
2804 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2809 * PgstatCollectorMain() -
2811 * Start up the statistics collector process. This is the body of the
2812 * postmaster child process.
2814 * The argc/argv parameters are valid only in EXEC_BACKEND case.
2817 NON_EXEC_STATIC void
2818 PgstatCollectorMain(int argc, char *argv[])
2825 struct pollfd input_fd;
2827 struct timeval sel_timeout;
2832 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
2834 MyProcPid = getpid(); /* reset MyProcPid */
2836 MyStartTime = time(NULL); /* record Start Time for logging */
2839 * If possible, make this process a group leader, so that the postmaster
2840 * can signal any child processes too. (pgstat probably never has any
2841 * child processes, but for consistency we make all postmaster child
2842 * processes do this.)
2846 elog(FATAL, "setsid() failed: %m");
2850 * Ignore all signals usually bound to some action in the postmaster,
2853 pqsignal(SIGHUP, pgstat_sighup_handler);
2854 pqsignal(SIGINT, SIG_IGN);
2855 pqsignal(SIGTERM, SIG_IGN);
2856 pqsignal(SIGQUIT, pgstat_exit);
2857 pqsignal(SIGALRM, SIG_IGN);
2858 pqsignal(SIGPIPE, SIG_IGN);
2859 pqsignal(SIGUSR1, SIG_IGN);
2860 pqsignal(SIGUSR2, SIG_IGN);
2861 pqsignal(SIGCHLD, SIG_DFL);
2862 pqsignal(SIGTTIN, SIG_DFL);
2863 pqsignal(SIGTTOU, SIG_DFL);
2864 pqsignal(SIGCONT, SIG_DFL);
2865 pqsignal(SIGWINCH, SIG_DFL);
2866 PG_SETMASK(&UnBlockSig);
2869 * Identify myself via ps
2871 init_ps_display("stats collector process", "", "", "");
2874 * Arrange to write the initial status file right away
2876 last_statrequest = GetCurrentTimestamp();
2877 last_statwrite = last_statrequest - 1;
2880 * Read in an existing statistics stats file or initialize the stats to
2883 pgStatRunningInCollector = true;
2884 pgStatDBHash = pgstat_read_statsfile(InvalidOid, true);
2887 * Setup the descriptor set for select(2). Since only one bit in the set
2888 * ever changes, we need not repeat FD_ZERO each time.
2890 #if !defined(HAVE_POLL) && !defined(WIN32)
2895 * Loop to process messages until we get SIGQUIT or detect ungraceful
2896 * death of our parent postmaster.
2898 * For performance reasons, we don't want to do a PostmasterIsAlive() test
2899 * after every message; instead, do it only when select()/poll() is
2900 * interrupted by timeout. In essence, we'll stay alive as long as
2901 * backends keep sending us stuff often, even if the postmaster is gone.
2908 * Quit if we get SIGQUIT from the postmaster.
2914 * Reload configuration if we got SIGHUP from the postmaster.
2918 ProcessConfigFile(PGC_SIGHUP);
2923 * Write the stats file if a new request has arrived that is not
2924 * satisfied by existing file.
2926 if (last_statwrite < last_statrequest)
2927 pgstat_write_statsfile(false);
2930 * Wait for a message to arrive; but not for more than
2931 * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2932 * shut down after an ungraceful postmaster termination; so it needn't
2933 * be very fast. However, on some systems SIGQUIT won't interrupt the
2934 * poll/select call, so this also limits speed of response to SIGQUIT,
2935 * which is more important.)
2937 * We use poll(2) if available, otherwise select(2). Win32 has its own
2942 input_fd.fd = pgStatSock;
2943 input_fd.events = POLLIN | POLLERR;
2944 input_fd.revents = 0;
2946 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2951 (errcode_for_socket_access(),
2952 errmsg("poll() failed in statistics collector: %m")));
2955 got_data = (input_fd.revents != 0);
2956 #else /* !HAVE_POLL */
2958 FD_SET(pgStatSock, &rfds);
2961 * timeout struct is modified by select() on some operating systems,
2962 * so re-fill it each time.
2964 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2965 sel_timeout.tv_usec = 0;
2967 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2972 (errcode_for_socket_access(),
2973 errmsg("select() failed in statistics collector: %m")));
2976 got_data = FD_ISSET(pgStatSock, &rfds);
2977 #endif /* HAVE_POLL */
2979 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2980 PGSTAT_SELECT_TIMEOUT * 1000);
2984 * If there is a message on the socket, read it and check for
2989 len = recv(pgStatSock, (char *) &msg,
2990 sizeof(PgStat_Msg), 0);
2996 (errcode_for_socket_access(),
2997 errmsg("could not read statistics message: %m")));
3001 * We ignore messages that are smaller than our common header
3003 if (len < sizeof(PgStat_MsgHdr))
3007 * The received length must match the length in the header
3009 if (msg.msg_hdr.m_size != len)
3013 * O.K. - we accept this message. Process it.
3015 switch (msg.msg_hdr.m_type)
3017 case PGSTAT_MTYPE_DUMMY:
3020 case PGSTAT_MTYPE_INQUIRY:
3021 pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
3024 case PGSTAT_MTYPE_TABSTAT:
3025 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
3028 case PGSTAT_MTYPE_TABPURGE:
3029 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
3032 case PGSTAT_MTYPE_DROPDB:
3033 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
3036 case PGSTAT_MTYPE_RESETCOUNTER:
3037 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
3041 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
3042 pgstat_recv_resetsharedcounter(
3043 (PgStat_MsgResetsharedcounter *) &msg,
3047 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
3048 pgstat_recv_resetsinglecounter(
3049 (PgStat_MsgResetsinglecounter *) &msg,
3053 case PGSTAT_MTYPE_AUTOVAC_START:
3054 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
3057 case PGSTAT_MTYPE_VACUUM:
3058 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
3061 case PGSTAT_MTYPE_ANALYZE:
3062 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
3065 case PGSTAT_MTYPE_BGWRITER:
3066 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
3069 case PGSTAT_MTYPE_FUNCSTAT:
3070 pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
3073 case PGSTAT_MTYPE_FUNCPURGE:
3074 pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
3077 case PGSTAT_MTYPE_RECOVERYCONFLICT:
3078 pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
3088 * We can only get here if the select/poll timeout elapsed. Check
3089 * for postmaster death.
3091 if (!PostmasterIsAlive(true))
3094 } /* end of message-processing loop */
3097 * Save the final stats to reuse at next startup.
3099 pgstat_write_statsfile(true);
3105 /* SIGQUIT signal handler for collector process */
3107 pgstat_exit(SIGNAL_ARGS)
3112 /* SIGHUP handler for collector process */
3114 pgstat_sighup_handler(SIGNAL_ARGS)
3121 * Lookup the hash table entry for the specified database. If no hash
3122 * table entry exists, initialize it, if the create parameter is true.
3123 * Else, return NULL.
3125 static PgStat_StatDBEntry *
3126 pgstat_get_db_entry(Oid databaseid, bool create)
3128 PgStat_StatDBEntry *result;
3130 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
3132 /* Lookup or create the hash table entry for this database */
3133 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
3137 if (!create && !found)
3140 /* If not found, initialize the new one. */
3145 result->tables = NULL;
3146 result->functions = NULL;
3147 result->n_xact_commit = 0;
3148 result->n_xact_rollback = 0;
3149 result->n_blocks_fetched = 0;
3150 result->n_blocks_hit = 0;
3151 result->n_tuples_returned = 0;
3152 result->n_tuples_fetched = 0;
3153 result->n_tuples_inserted = 0;
3154 result->n_tuples_updated = 0;
3155 result->n_tuples_deleted = 0;
3156 result->last_autovac_time = 0;
3157 result->n_conflict_tablespace = 0;
3158 result->n_conflict_lock = 0;
3159 result->n_conflict_snapshot = 0;
3160 result->n_conflict_bufferpin = 0;
3161 result->n_conflict_startup_deadlock = 0;
3163 memset(&hash_ctl, 0, sizeof(hash_ctl));
3164 hash_ctl.keysize = sizeof(Oid);
3165 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3166 hash_ctl.hash = oid_hash;
3167 result->tables = hash_create("Per-database table",
3168 PGSTAT_TAB_HASH_SIZE,
3170 HASH_ELEM | HASH_FUNCTION);
3172 hash_ctl.keysize = sizeof(Oid);
3173 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3174 hash_ctl.hash = oid_hash;
3175 result->functions = hash_create("Per-database function",
3176 PGSTAT_FUNCTION_HASH_SIZE,
3178 HASH_ELEM | HASH_FUNCTION);
3186 * Lookup the hash table entry for the specified table. If no hash
3187 * table entry exists, initialize it, if the create parameter is true.
3188 * Else, return NULL.
3190 static PgStat_StatTabEntry *
3191 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
3193 PgStat_StatTabEntry *result;
3195 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
3197 /* Lookup or create the hash table entry for this table */
3198 result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3202 if (!create && !found)
3205 /* If not found, initialize the new one. */
3208 result->numscans = 0;
3209 result->tuples_returned = 0;
3210 result->tuples_fetched = 0;
3211 result->tuples_inserted = 0;
3212 result->tuples_updated = 0;
3213 result->tuples_deleted = 0;
3214 result->tuples_hot_updated = 0;
3215 result->n_live_tuples = 0;
3216 result->n_dead_tuples = 0;
3217 result->changes_since_analyze = 0;
3218 result->blocks_fetched = 0;
3219 result->blocks_hit = 0;
3221 result->vacuum_timestamp = 0;
3222 result->autovac_vacuum_timestamp = 0;
3223 result->analyze_timestamp = 0;
3224 result->autovac_analyze_timestamp = 0;
3225 result->vacuum_count = 0;
3226 result->autovac_vacuum_count = 0;
3227 result->analyze_count = 0;
3228 result->autovac_analyze_count = 0;
3236 * pgstat_write_statsfile() -
3239 * If writing to the permanent file (happens when the collector is
3240 * shutting down only), remove the temporary file so that backends
3241 * starting up under a new postmaster can't read the old data before
3242 * the new collector is ready.
3246 pgstat_write_statsfile(bool permanent)
3248 HASH_SEQ_STATUS hstat;
3249 HASH_SEQ_STATUS tstat;
3250 HASH_SEQ_STATUS fstat;
3251 PgStat_StatDBEntry *dbentry;
3252 PgStat_StatTabEntry *tabentry;
3253 PgStat_StatFuncEntry *funcentry;
3256 const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
3257 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3260 * Open the statistics temp file to write out the current values.
3262 fpout = AllocateFile(tmpfile, PG_BINARY_W);
3266 (errcode_for_file_access(),
3267 errmsg("could not open temporary statistics file \"%s\": %m",
3273 * Set the timestamp of the stats file.
3275 globalStats.stats_timestamp = GetCurrentTimestamp();
3278 * Write the file header --- currently just a format ID.
3280 format_id = PGSTAT_FILE_FORMAT_ID;
3281 fwrite(&format_id, sizeof(format_id), 1, fpout);
3284 * Write global stats struct
3286 fwrite(&globalStats, sizeof(globalStats), 1, fpout);
3289 * Walk through the database table.
3291 hash_seq_init(&hstat, pgStatDBHash);
3292 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
3295 * Write out the DB entry including the number of live backends. We
3296 * don't write the tables or functions pointers, since they're of no
3297 * use to any other process.
3300 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
3303 * Walk through the database's access stats per table.
3305 hash_seq_init(&tstat, dbentry->tables);
3306 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
3309 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
3313 * Walk through the database's function stats table.
3315 hash_seq_init(&fstat, dbentry->functions);
3316 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
3319 fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
3323 * Mark the end of this DB
3329 * No more output to be done. Close the temp file and replace the old
3330 * pgstat.stat with it. The ferror() check replaces testing for error
3331 * after each individual fputc or fwrite above.
3338 (errcode_for_file_access(),
3339 errmsg("could not write temporary statistics file \"%s\": %m",
3344 else if (FreeFile(fpout) < 0)
3347 (errcode_for_file_access(),
3348 errmsg("could not close temporary statistics file \"%s\": %m",
3352 else if (rename(tmpfile, statfile) < 0)
3355 (errcode_for_file_access(),
3356 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
3357 tmpfile, statfile)));
3363 * Successful write, so update last_statwrite.
3365 last_statwrite = globalStats.stats_timestamp;
3368 * If there is clock skew between backends and the collector, we could
3369 * receive a stats request time that's in the future. If so, complain
3370 * and reset last_statrequest. Resetting ensures that no inquiry
3371 * message can cause more than one stats file write to occur.
3373 if (last_statrequest > last_statwrite)
3378 /* Copy because timestamptz_to_str returns a static buffer */
3379 reqtime = pstrdup(timestamptz_to_str(last_statrequest));
3380 mytime = pstrdup(timestamptz_to_str(last_statwrite));
3381 elog(LOG, "last_statrequest %s is later than collector's time %s",
3386 last_statrequest = last_statwrite;
3391 unlink(pgstat_stat_filename);
3396 * pgstat_read_statsfile() -
3398 * Reads in an existing statistics collector file and initializes the
3399 * databases' hash table (whose entries point to the tables' hash tables).
3403 pgstat_read_statsfile(Oid onlydb, bool permanent)
3405 PgStat_StatDBEntry *dbentry;
3406 PgStat_StatDBEntry dbbuf;
3407 PgStat_StatTabEntry *tabentry;
3408 PgStat_StatTabEntry tabbuf;
3409 PgStat_StatFuncEntry funcbuf;
3410 PgStat_StatFuncEntry *funcentry;
3413 HTAB *tabhash = NULL;
3414 HTAB *funchash = NULL;
3418 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3421 * The tables will live in pgStatLocalContext.
3423 pgstat_setup_memcxt();
3426 * Create the DB hashtable
3428 memset(&hash_ctl, 0, sizeof(hash_ctl));
3429 hash_ctl.keysize = sizeof(Oid);
3430 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
3431 hash_ctl.hash = oid_hash;
3432 hash_ctl.hcxt = pgStatLocalContext;
3433 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
3434 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3437 * Clear out global statistics so they start from zero in case we can't
3438 * load an existing statsfile.
3440 memset(&globalStats, 0, sizeof(globalStats));
3443 * Try to open the status file. If it doesn't exist, the backends simply
3444 * return zero for anything and the collector simply starts from scratch
3445 * with empty counters.
3447 * ENOENT is a possibility if the stats collector is not running or has
3448 * not yet written the stats file the first time. Any other failure
3449 * condition is suspicious.
3451 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3453 if (errno != ENOENT)
3454 ereport(pgStatRunningInCollector ? LOG : WARNING,
3455 (errcode_for_file_access(),
3456 errmsg("could not open statistics file \"%s\": %m",
3462 * Verify it's of the expected format.
3464 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3465 || format_id != PGSTAT_FILE_FORMAT_ID)
3467 ereport(pgStatRunningInCollector ? LOG : WARNING,
3468 (errmsg("corrupted statistics file \"%s\"", statfile)));
3473 * Read global stats struct
3475 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
3477 ereport(pgStatRunningInCollector ? LOG : WARNING,
3478 (errmsg("corrupted statistics file \"%s\"", statfile)));
3483 * We found an existing collector stats file. Read it and put all the
3484 * hashtable entries into place.
3488 switch (fgetc(fpin))
3491 * 'D' A PgStat_StatDBEntry struct describing a database
3492 * follows. Subsequently, zero to many 'T' and 'F' entries
3493 * will follow until a 'd' is encountered.
3496 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
3497 fpin) != offsetof(PgStat_StatDBEntry, tables))
3499 ereport(pgStatRunningInCollector ? LOG : WARNING,
3500 (errmsg("corrupted statistics file \"%s\"",
3506 * Add to the DB hash
3508 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
3509 (void *) &dbbuf.databaseid,
3514 ereport(pgStatRunningInCollector ? LOG : WARNING,
3515 (errmsg("corrupted statistics file \"%s\"",
3520 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
3521 dbentry->tables = NULL;
3522 dbentry->functions = NULL;
3525 * Don't collect tables if not the requested DB (or the
3526 * shared-table info)
3528 if (onlydb != InvalidOid)
3530 if (dbbuf.databaseid != onlydb &&
3531 dbbuf.databaseid != InvalidOid)
3535 memset(&hash_ctl, 0, sizeof(hash_ctl));
3536 hash_ctl.keysize = sizeof(Oid);
3537 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3538 hash_ctl.hash = oid_hash;
3539 hash_ctl.hcxt = pgStatLocalContext;
3540 dbentry->tables = hash_create("Per-database table",
3541 PGSTAT_TAB_HASH_SIZE,
3543 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3545 hash_ctl.keysize = sizeof(Oid);
3546 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3547 hash_ctl.hash = oid_hash;
3548 hash_ctl.hcxt = pgStatLocalContext;
3549 dbentry->functions = hash_create("Per-database function",
3550 PGSTAT_FUNCTION_HASH_SIZE,
3552 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3555 * Arrange that following records add entries to this
3556 * database's hash tables.
3558 tabhash = dbentry->tables;
3559 funchash = dbentry->functions;
3563 * 'd' End of this database.
3571 * 'T' A PgStat_StatTabEntry follows.
3574 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
3575 fpin) != sizeof(PgStat_StatTabEntry))
3577 ereport(pgStatRunningInCollector ? LOG : WARNING,
3578 (errmsg("corrupted statistics file \"%s\"",
3584 * Skip if table belongs to a not requested database.
3586 if (tabhash == NULL)
3589 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
3590 (void *) &tabbuf.tableid,
3591 HASH_ENTER, &found);
3595 ereport(pgStatRunningInCollector ? LOG : WARNING,
3596 (errmsg("corrupted statistics file \"%s\"",
3601 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
3605 * 'F' A PgStat_StatFuncEntry follows.
3608 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
3609 fpin) != sizeof(PgStat_StatFuncEntry))
3611 ereport(pgStatRunningInCollector ? LOG : WARNING,
3612 (errmsg("corrupted statistics file \"%s\"",
3618 * Skip if function belongs to a not requested database.
3620 if (funchash == NULL)
3623 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
3624 (void *) &funcbuf.functionid,
3625 HASH_ENTER, &found);
3629 ereport(pgStatRunningInCollector ? LOG : WARNING,
3630 (errmsg("corrupted statistics file \"%s\"",
3635 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
3639 * 'E' The EOF marker of a complete stats file.
3645 ereport(pgStatRunningInCollector ? LOG : WARNING,
3646 (errmsg("corrupted statistics file \"%s\"",
3656 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
3662 * pgstat_read_statsfile_timestamp() -
3664 * Attempt to fetch the timestamp of an existing stats file.
3665 * Returns TRUE if successful (timestamp is stored at *ts).
3669 pgstat_read_statsfile_timestamp(bool permanent, TimestampTz *ts)
3671 PgStat_GlobalStats myGlobalStats;
3674 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3677 * Try to open the status file. As above, anything but ENOENT is worthy
3678 * of complaining about.
3680 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3682 if (errno != ENOENT)
3683 ereport(pgStatRunningInCollector ? LOG : WARNING,
3684 (errcode_for_file_access(),
3685 errmsg("could not open statistics file \"%s\": %m",
3691 * Verify it's of the expected format.
3693 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3694 || format_id != PGSTAT_FILE_FORMAT_ID)
3696 ereport(pgStatRunningInCollector ? LOG : WARNING,
3697 (errmsg("corrupted statistics file \"%s\"", statfile)));
3703 * Read global stats struct
3705 if (fread(&myGlobalStats, 1, sizeof(myGlobalStats), fpin) != sizeof(myGlobalStats))
3707 ereport(pgStatRunningInCollector ? LOG : WARNING,
3708 (errmsg("corrupted statistics file \"%s\"", statfile)));
3713 *ts = myGlobalStats.stats_timestamp;
3720 * If not already done, read the statistics collector stats file into
3721 * some hash tables. The results will be kept until pgstat_clear_snapshot()
3722 * is called (typically, at end of transaction).
3725 backend_read_statsfile(void)
3730 /* already read it? */
3733 Assert(!pgStatRunningInCollector);
3736 * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL msec
3737 * before now. This indirectly ensures that the collector needn't write
3738 * the file more often than PGSTAT_STAT_INTERVAL. In an autovacuum
3739 * worker, however, we want a lower delay to avoid using stale data, so we
3740 * use PGSTAT_RETRY_DELAY (since the number of worker is low, this
3741 * shouldn't be a problem).
3743 * Note that we don't recompute min_ts after sleeping; so we might end up
3744 * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In practice
3745 * that shouldn't happen, though, as long as the sleep time is less than
3746 * PGSTAT_STAT_INTERVAL; and we don't want to lie to the collector about
3747 * what our cutoff time really is.
3749 if (IsAutoVacuumWorkerProcess())
3750 min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
3751 -PGSTAT_RETRY_DELAY);
3753 min_ts = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
3754 -PGSTAT_STAT_INTERVAL);
3757 * Loop until fresh enough stats file is available or we ran out of time.
3758 * The stats inquiry message is sent repeatedly in case collector drops
3761 for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
3763 TimestampTz file_ts = 0;
3765 CHECK_FOR_INTERRUPTS();
3767 if (pgstat_read_statsfile_timestamp(false, &file_ts) &&
3771 /* Not there or too old, so kick the collector and wait a bit */
3772 pgstat_send_inquiry(min_ts);
3773 pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
3776 if (count >= PGSTAT_POLL_LOOP_COUNT)
3777 elog(WARNING, "pgstat wait timeout");
3779 /* Autovacuum launcher wants stats about all databases */
3780 if (IsAutoVacuumLauncherProcess())
3781 pgStatDBHash = pgstat_read_statsfile(InvalidOid, false);
3783 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId, false);
3788 * pgstat_setup_memcxt() -
3790 * Create pgStatLocalContext, if not already done.
3794 pgstat_setup_memcxt(void)
3796 if (!pgStatLocalContext)
3797 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
3798 "Statistics snapshot",
3799 ALLOCSET_SMALL_MINSIZE,
3800 ALLOCSET_SMALL_INITSIZE,
3801 ALLOCSET_SMALL_MAXSIZE);
3806 * pgstat_clear_snapshot() -
3808 * Discard any data collected in the current transaction. Any subsequent
3809 * request will cause new snapshots to be read.
3811 * This is also invoked during transaction commit or abort to discard
3812 * the no-longer-wanted snapshot.
3816 pgstat_clear_snapshot(void)
3818 /* Release memory, if any was allocated */
3819 if (pgStatLocalContext)
3820 MemoryContextDelete(pgStatLocalContext);
3822 /* Reset variables */
3823 pgStatLocalContext = NULL;
3824 pgStatDBHash = NULL;
3825 localBackendStatusTable = NULL;
3826 localNumBackends = 0;
3831 * pgstat_recv_inquiry() -
3833 * Process stat inquiry requests.
3837 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
3839 if (msg->inquiry_time > last_statrequest)
3840 last_statrequest = msg->inquiry_time;
3845 * pgstat_recv_tabstat() -
3847 * Count what the backend has done.
3851 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
3853 PgStat_StatDBEntry *dbentry;
3854 PgStat_StatTabEntry *tabentry;
3858 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3861 * Update database-wide stats.
3863 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
3864 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
3867 * Process all table entries in the message.
3869 for (i = 0; i < msg->m_nentries; i++)
3871 PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
3873 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3874 (void *) &(tabmsg->t_id),
3875 HASH_ENTER, &found);
3880 * If it's a new table entry, initialize counters to the values we
3883 tabentry->numscans = tabmsg->t_counts.t_numscans;
3884 tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
3885 tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
3886 tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
3887 tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
3888 tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
3889 tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
3890 tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
3891 tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
3892 tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
3893 tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
3894 tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
3896 tabentry->vacuum_timestamp = 0;
3897 tabentry->autovac_vacuum_timestamp = 0;
3898 tabentry->analyze_timestamp = 0;
3899 tabentry->autovac_analyze_timestamp = 0;
3904 * Otherwise add the values to the existing entry.
3906 tabentry->numscans += tabmsg->t_counts.t_numscans;
3907 tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
3908 tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
3909 tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
3910 tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
3911 tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
3912 tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
3913 tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
3914 tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
3915 tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
3916 tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
3917 tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
3920 /* Clamp n_live_tuples in case of negative delta_live_tuples */
3921 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
3922 /* Likewise for n_dead_tuples */
3923 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
3926 * Add per-table stats to the per-database entry, too.
3928 dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
3929 dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
3930 dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
3931 dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
3932 dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
3933 dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
3934 dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
3940 * pgstat_recv_tabpurge() -
3942 * Arrange for dead table removal.
3946 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3948 PgStat_StatDBEntry *dbentry;
3951 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3954 * No need to purge if we don't even know the database.
3956 if (!dbentry || !dbentry->tables)
3960 * Process all table entries in the message.
3962 for (i = 0; i < msg->m_nentries; i++)
3964 /* Remove from hashtable if present; we don't care if it's not. */
3965 (void) hash_search(dbentry->tables,
3966 (void *) &(msg->m_tableid[i]),
3973 * pgstat_recv_dropdb() -
3975 * Arrange for dead database removal
3979 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3981 PgStat_StatDBEntry *dbentry;
3984 * Lookup the database in the hashtable.
3986 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3989 * If found, remove it.
3993 if (dbentry->tables != NULL)
3994 hash_destroy(dbentry->tables);
3995 if (dbentry->functions != NULL)
3996 hash_destroy(dbentry->functions);
3998 if (hash_search(pgStatDBHash,
3999 (void *) &(dbentry->databaseid),
4000 HASH_REMOVE, NULL) == NULL)
4002 (errmsg("database hash table corrupted "
4003 "during cleanup --- abort")));
4009 * pgstat_recv_resetcounter() -
4011 * Reset the statistics for the specified database.
4015 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
4018 PgStat_StatDBEntry *dbentry;
4021 * Lookup the database in the hashtable. Nothing to do if not there.
4023 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4029 * We simply throw away all the database's table entries by recreating a
4030 * new hash table for them.
4032 if (dbentry->tables != NULL)
4033 hash_destroy(dbentry->tables);
4034 if (dbentry->functions != NULL)
4035 hash_destroy(dbentry->functions);
4037 dbentry->tables = NULL;
4038 dbentry->functions = NULL;
4041 * Reset database-level stats too. This should match the initialization
4042 * code in pgstat_get_db_entry().
4044 dbentry->n_xact_commit = 0;
4045 dbentry->n_xact_rollback = 0;
4046 dbentry->n_blocks_fetched = 0;
4047 dbentry->n_blocks_hit = 0;
4048 dbentry->n_tuples_returned = 0;
4049 dbentry->n_tuples_fetched = 0;
4050 dbentry->n_tuples_inserted = 0;
4051 dbentry->n_tuples_updated = 0;
4052 dbentry->n_tuples_deleted = 0;
4053 dbentry->last_autovac_time = 0;
4055 memset(&hash_ctl, 0, sizeof(hash_ctl));
4056 hash_ctl.keysize = sizeof(Oid);
4057 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4058 hash_ctl.hash = oid_hash;
4059 dbentry->tables = hash_create("Per-database table",
4060 PGSTAT_TAB_HASH_SIZE,
4062 HASH_ELEM | HASH_FUNCTION);
4064 hash_ctl.keysize = sizeof(Oid);
4065 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4066 hash_ctl.hash = oid_hash;
4067 dbentry->functions = hash_create("Per-database function",
4068 PGSTAT_FUNCTION_HASH_SIZE,
4070 HASH_ELEM | HASH_FUNCTION);
4074 * pgstat_recv_resetshared() -
4076 * Reset some shared statistics of the cluster.
4080 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
4082 if (msg->m_resettarget == RESET_BGWRITER)
4084 /* Reset the global background writer statistics for the cluster. */
4085 memset(&globalStats, 0, sizeof(globalStats));
4089 * Presumably the sender of this message validated the target, don't
4090 * complain here if it's not valid
4095 * pgstat_recv_resetsinglecounter() -
4097 * Reset a statistics for a single object
4101 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
4103 PgStat_StatDBEntry *dbentry;
4105 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4111 /* Remove object if it exists, ignore it if not */
4112 if (msg->m_resettype == RESET_TABLE)
4113 (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid), HASH_REMOVE, NULL);
4114 else if (msg->m_resettype == RESET_FUNCTION)
4115 (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid), HASH_REMOVE, NULL);
4119 * pgstat_recv_autovac() -
4121 * Process an autovacuum signalling message.
4125 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
4127 PgStat_StatDBEntry *dbentry;
4130 * Store the last autovacuum time in the database's hashtable entry.
4132 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4134 dbentry->last_autovac_time = msg->m_start_time;
4138 * pgstat_recv_vacuum() -
4140 * Process a VACUUM message.
4144 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
4146 PgStat_StatDBEntry *dbentry;
4147 PgStat_StatTabEntry *tabentry;
4150 * Store the data in the table's hashtable entry.
4152 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4154 tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
4156 if (msg->m_adopt_counts)
4157 tabentry->n_live_tuples = msg->m_tuples;
4158 /* Resetting dead_tuples to 0 is an approximation ... */
4159 tabentry->n_dead_tuples = 0;
4161 if (msg->m_autovacuum)
4163 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
4164 tabentry->autovac_vacuum_count++;
4168 tabentry->vacuum_timestamp = msg->m_vacuumtime;
4169 tabentry->vacuum_count++;
4174 * pgstat_recv_analyze() -
4176 * Process an ANALYZE message.
4180 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
4182 PgStat_StatDBEntry *dbentry;
4183 PgStat_StatTabEntry *tabentry;
4186 * Store the data in the table's hashtable entry.
4188 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4190 tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
4192 if (msg->m_adopt_counts)
4194 tabentry->n_live_tuples = msg->m_live_tuples;
4195 tabentry->n_dead_tuples = msg->m_dead_tuples;
4199 * We reset changes_since_analyze to zero, forgetting any changes that
4200 * occurred while the ANALYZE was in progress.
4202 tabentry->changes_since_analyze = 0;
4204 if (msg->m_autovacuum)
4206 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
4207 tabentry->autovac_analyze_count++;
4211 tabentry->analyze_timestamp = msg->m_analyzetime;
4212 tabentry->analyze_count++;
4218 * pgstat_recv_bgwriter() -
4220 * Process a BGWRITER message.
4224 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
4226 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
4227 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
4228 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
4229 globalStats.buf_written_clean += msg->m_buf_written_clean;
4230 globalStats.maxwritten_clean += msg->m_maxwritten_clean;
4231 globalStats.buf_written_backend += msg->m_buf_written_backend;
4232 globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
4233 globalStats.buf_alloc += msg->m_buf_alloc;
4237 * pgstat_recv_recoveryconflict() -
4239 * Process as RECOVERYCONFLICT message.
4243 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
4245 PgStat_StatDBEntry *dbentry;
4246 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4248 switch (msg->m_reason)
4250 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
4252 * Since we drop the information about the database as soon
4253 * as it replicates, there is no point in counting these
4257 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
4258 dbentry->n_conflict_tablespace++;
4260 case PROCSIG_RECOVERY_CONFLICT_LOCK:
4261 dbentry->n_conflict_lock++;
4263 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
4264 dbentry->n_conflict_snapshot++;
4266 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
4267 dbentry->n_conflict_bufferpin++;
4269 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
4270 dbentry->n_conflict_startup_deadlock++;
4276 * pgstat_recv_funcstat() -
4278 * Count what the backend has done.
4282 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
4284 PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
4285 PgStat_StatDBEntry *dbentry;
4286 PgStat_StatFuncEntry *funcentry;
4290 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
4293 * Process all function entries in the message.
4295 for (i = 0; i < msg->m_nentries; i++, funcmsg++)
4297 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
4298 (void *) &(funcmsg->f_id),
4299 HASH_ENTER, &found);
4304 * If it's a new function entry, initialize counters to the values
4307 funcentry->f_numcalls = funcmsg->f_numcalls;
4308 funcentry->f_time = funcmsg->f_time;
4309 funcentry->f_time_self = funcmsg->f_time_self;
4314 * Otherwise add the values to the existing entry.
4316 funcentry->f_numcalls += funcmsg->f_numcalls;
4317 funcentry->f_time += funcmsg->f_time;
4318 funcentry->f_time_self += funcmsg->f_time_self;
4324 * pgstat_recv_funcpurge() -
4326 * Arrange for dead function removal.
4330 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
4332 PgStat_StatDBEntry *dbentry;
4335 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
4338 * No need to purge if we don't even know the database.
4340 if (!dbentry || !dbentry->functions)
4344 * Process all function entries in the message.
4346 for (i = 0; i < msg->m_nentries; i++)
4348 /* Remove from hashtable if present; we don't care if it's not. */
4349 (void) hash_search(dbentry->functions,
4350 (void *) &(msg->m_functionid[i]),