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-2019, 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>
31 #ifdef HAVE_SYS_SELECT_H
32 #include <sys/select.h>
37 #include "access/heapam.h"
38 #include "access/htup_details.h"
39 #include "access/tableam.h"
40 #include "access/transam.h"
41 #include "access/twophase_rmgr.h"
42 #include "access/xact.h"
43 #include "catalog/pg_database.h"
44 #include "catalog/pg_proc.h"
45 #include "common/ip.h"
46 #include "libpq/libpq.h"
47 #include "libpq/pqsignal.h"
48 #include "mb/pg_wchar.h"
49 #include "miscadmin.h"
51 #include "postmaster/autovacuum.h"
52 #include "postmaster/fork_process.h"
53 #include "postmaster/postmaster.h"
54 #include "replication/walsender.h"
55 #include "storage/backendid.h"
56 #include "storage/dsm.h"
57 #include "storage/fd.h"
58 #include "storage/ipc.h"
59 #include "storage/latch.h"
60 #include "storage/lmgr.h"
61 #include "storage/pg_shmem.h"
62 #include "storage/procsignal.h"
63 #include "storage/sinvaladt.h"
64 #include "utils/ascii.h"
65 #include "utils/guc.h"
66 #include "utils/memutils.h"
67 #include "utils/ps_status.h"
68 #include "utils/rel.h"
69 #include "utils/snapmgr.h"
70 #include "utils/timestamp.h"
77 #define PGSTAT_STAT_INTERVAL 500 /* Minimum time between stats file
78 * updates; in milliseconds. */
80 #define PGSTAT_RETRY_DELAY 10 /* How long to wait between checks for a
81 * new file; in milliseconds. */
83 #define PGSTAT_MAX_WAIT_TIME 10000 /* Maximum time to wait for a stats
84 * file update; in milliseconds. */
86 #define PGSTAT_INQ_INTERVAL 640 /* How often to ping the collector for a
87 * new file; in milliseconds. */
89 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart a
90 * failed statistics collector; in
93 #define PGSTAT_POLL_LOOP_COUNT (PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
94 #define PGSTAT_INQ_LOOP_COUNT (PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
96 /* Minimum receive buffer size for the collector's socket. */
97 #define PGSTAT_MIN_RCVBUF (100 * 1024)
101 * The initial size hints for the hash tables used in the collector.
104 #define PGSTAT_DB_HASH_SIZE 16
105 #define PGSTAT_TAB_HASH_SIZE 512
106 #define PGSTAT_FUNCTION_HASH_SIZE 512
110 * Total number of backends including auxiliary
112 * We reserve a slot for each possible BackendId, plus one for each
113 * possible auxiliary process type. (This scheme assumes there is not
114 * more than one of any auxiliary process type at a time.) MaxBackends
115 * includes autovacuum workers and background workers as well.
118 #define NumBackendStatSlots (MaxBackends + NUM_AUXPROCTYPES)
125 bool pgstat_track_activities = false;
126 bool pgstat_track_counts = false;
127 int pgstat_track_functions = TRACK_FUNC_OFF;
128 int pgstat_track_activity_query_size = 1024;
131 * Built from GUC parameter
134 char *pgstat_stat_directory = NULL;
135 char *pgstat_stat_filename = NULL;
136 char *pgstat_stat_tmpname = NULL;
139 * BgWriter global statistics counters (unused in other processes).
140 * Stored directly in a stats message structure so it can be sent
141 * without needing to copy things around. We assume this inits to zeroes.
143 PgStat_MsgBgWriter BgWriterStats;
149 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
151 static struct sockaddr_storage pgStatAddr;
153 static time_t last_pgstat_start_time;
155 static bool pgStatRunningInCollector = false;
158 * Structures in which backends store per-table info that's waiting to be
159 * sent to the collector.
161 * NOTE: once allocated, TabStatusArray structures are never moved or deleted
162 * for the life of the backend. Also, we zero out the t_id fields of the
163 * contained PgStat_TableStatus structs whenever they are not actively in use.
164 * This allows relcache pgstat_info pointers to be treated as long-lived data,
165 * avoiding repeated searches in pgstat_initstats() when a relation is
166 * repeatedly opened during a transaction.
168 #define TABSTAT_QUANTUM 100 /* we alloc this many at a time */
170 typedef struct TabStatusArray
172 struct TabStatusArray *tsa_next; /* link to next array, if any */
173 int tsa_used; /* # entries currently used */
174 PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM]; /* per-table data */
177 static TabStatusArray *pgStatTabList = NULL;
180 * pgStatTabHash entry: map from relation OID to PgStat_TableStatus pointer
182 typedef struct TabStatHashEntry
185 PgStat_TableStatus *tsa_entry;
189 * Hash table for O(1) t_id -> tsa_entry lookup
191 static HTAB *pgStatTabHash = NULL;
194 * Backends store per-function info that's waiting to be sent to the collector
195 * in this hash table (indexed by function OID).
197 static HTAB *pgStatFunctions = NULL;
200 * Indicates if backend has some function stats that it hasn't yet
201 * sent to the collector.
203 static bool have_function_stats = false;
206 * Tuple insertion/deletion counts for an open transaction can't be propagated
207 * into PgStat_TableStatus counters until we know if it is going to commit
208 * or abort. Hence, we keep these counts in per-subxact structs that live
209 * in TopTransactionContext. This data structure is designed on the assumption
210 * that subxacts won't usually modify very many tables.
212 typedef struct PgStat_SubXactStatus
214 int nest_level; /* subtransaction nest level */
215 struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
216 PgStat_TableXactStatus *first; /* head of list for this subxact */
217 } PgStat_SubXactStatus;
219 static PgStat_SubXactStatus *pgStatXactStack = NULL;
221 static int pgStatXactCommit = 0;
222 static int pgStatXactRollback = 0;
223 PgStat_Counter pgStatBlockReadTime = 0;
224 PgStat_Counter pgStatBlockWriteTime = 0;
226 /* Record that's written to 2PC state file when pgstat state is persisted */
227 typedef struct TwoPhasePgStatRecord
229 PgStat_Counter tuples_inserted; /* tuples inserted in xact */
230 PgStat_Counter tuples_updated; /* tuples updated in xact */
231 PgStat_Counter tuples_deleted; /* tuples deleted in xact */
232 PgStat_Counter inserted_pre_trunc; /* tuples inserted prior to truncate */
233 PgStat_Counter updated_pre_trunc; /* tuples updated prior to truncate */
234 PgStat_Counter deleted_pre_trunc; /* tuples deleted prior to truncate */
235 Oid t_id; /* table's OID */
236 bool t_shared; /* is it a shared catalog? */
237 bool t_truncated; /* was the relation truncated? */
238 } TwoPhasePgStatRecord;
241 * Info about current "snapshot" of stats file
243 static MemoryContext pgStatLocalContext = NULL;
244 static HTAB *pgStatDBHash = NULL;
246 /* Status for backends including auxiliary */
247 static LocalPgBackendStatus *localBackendStatusTable = NULL;
249 /* Total number of backends including auxiliary */
250 static int localNumBackends = 0;
253 * Cluster wide statistics, kept in the stats collector.
254 * Contains statistics that are not collected per database
257 static PgStat_ArchiverStats archiverStats;
258 static PgStat_GlobalStats globalStats;
261 * List of OIDs of databases we need to write out. If an entry is InvalidOid,
262 * it means to write only the shared-catalog stats ("DB 0"); otherwise, we
263 * will write both that DB's data and the shared stats.
265 static List *pending_write_requests = NIL;
267 /* Signal handler flags */
268 static volatile bool need_exit = false;
269 static volatile bool got_SIGHUP = false;
272 * Total time charged to functions so far in the current backend.
273 * We use this to help separate "self" and "other" time charges.
274 * (We assume this initializes to zero.)
276 static instr_time total_func_time;
280 * Local function forward declarations
284 static pid_t pgstat_forkexec(void);
287 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) pg_attribute_noreturn();
288 static void pgstat_exit(SIGNAL_ARGS);
289 static void pgstat_beshutdown_hook(int code, Datum arg);
290 static void pgstat_sighup_handler(SIGNAL_ARGS);
292 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
293 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
294 Oid tableoid, bool create);
295 static void pgstat_write_statsfiles(bool permanent, bool allDbs);
296 static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
297 static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
298 static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
299 static void backend_read_statsfile(void);
300 static void pgstat_read_current_status(void);
302 static bool pgstat_write_statsfile_needed(void);
303 static bool pgstat_db_requested(Oid databaseid);
305 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
306 static void pgstat_send_funcstats(void);
307 static HTAB *pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid);
309 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
311 static void pgstat_setup_memcxt(void);
313 static const char *pgstat_get_wait_activity(WaitEventActivity w);
314 static const char *pgstat_get_wait_client(WaitEventClient w);
315 static const char *pgstat_get_wait_ipc(WaitEventIPC w);
316 static const char *pgstat_get_wait_timeout(WaitEventTimeout w);
317 static const char *pgstat_get_wait_io(WaitEventIO w);
319 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
320 static void pgstat_send(void *msg, int len);
322 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
323 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
324 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
325 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
326 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
327 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
328 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
329 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
330 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
331 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
332 static void pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len);
333 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
334 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
335 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
336 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
337 static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
338 static void pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len);
339 static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
341 /* ------------------------------------------------------------
342 * Public functions called from postmaster follow
343 * ------------------------------------------------------------
349 * Called from postmaster at startup. Create the resources required
350 * by the statistics collector process. If unable to do so, do not
351 * fail --- better to let the postmaster start with stats collection
358 ACCEPT_TYPE_ARG3 alen;
359 struct addrinfo *addrs = NULL,
369 #define TESTBYTEVAL ((char) 199)
372 * This static assertion verifies that we didn't mess up the calculations
373 * involved in selecting maximum payload sizes for our UDP messages.
374 * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
375 * be silent performance loss from fragmentation, it seems worth having a
376 * compile-time cross-check that we didn't.
378 StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,
379 "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
382 * Create the UDP socket for sending and receiving statistic messages
384 hints.ai_flags = AI_PASSIVE;
385 hints.ai_family = AF_UNSPEC;
386 hints.ai_socktype = SOCK_DGRAM;
387 hints.ai_protocol = 0;
388 hints.ai_addrlen = 0;
389 hints.ai_addr = NULL;
390 hints.ai_canonname = NULL;
391 hints.ai_next = NULL;
392 ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
396 (errmsg("could not resolve \"localhost\": %s",
397 gai_strerror(ret))));
402 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
403 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
404 * when kernel will reject IPv6). Worse, the failure may occur at the
405 * bind() or perhaps even connect() stage. So we must loop through the
406 * results till we find a working combination. We will generate LOG
407 * messages, but no error, for bogus combinations.
409 for (addr = addrs; addr; addr = addr->ai_next)
411 #ifdef HAVE_UNIX_SOCKETS
412 /* Ignore AF_UNIX sockets, if any are returned. */
413 if (addr->ai_family == AF_UNIX)
419 (errmsg("trying another address for the statistics collector")));
424 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
427 (errcode_for_socket_access(),
428 errmsg("could not create socket for statistics collector: %m")));
433 * Bind it to a kernel assigned port on localhost and get the assigned
434 * port via getsockname().
436 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
439 (errcode_for_socket_access(),
440 errmsg("could not bind socket for statistics collector: %m")));
441 closesocket(pgStatSock);
442 pgStatSock = PGINVALID_SOCKET;
446 alen = sizeof(pgStatAddr);
447 if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
450 (errcode_for_socket_access(),
451 errmsg("could not get address of socket for statistics collector: %m")));
452 closesocket(pgStatSock);
453 pgStatSock = PGINVALID_SOCKET;
458 * Connect the socket to its own address. This saves a few cycles by
459 * not having to respecify the target address on every send. This also
460 * provides a kernel-level check that only packets from this same
461 * address will be received.
463 if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
466 (errcode_for_socket_access(),
467 errmsg("could not connect socket for statistics collector: %m")));
468 closesocket(pgStatSock);
469 pgStatSock = PGINVALID_SOCKET;
474 * Try to send and receive a one-byte test message on the socket. This
475 * is to catch situations where the socket can be created but will not
476 * actually pass data (for instance, because kernel packet filtering
479 test_byte = TESTBYTEVAL;
482 if (send(pgStatSock, &test_byte, 1, 0) != 1)
485 goto retry1; /* if interrupted, just retry */
487 (errcode_for_socket_access(),
488 errmsg("could not send test message on socket for statistics collector: %m")));
489 closesocket(pgStatSock);
490 pgStatSock = PGINVALID_SOCKET;
495 * There could possibly be a little delay before the message can be
496 * received. We arbitrarily allow up to half a second before deciding
499 for (;;) /* need a loop to handle EINTR */
502 FD_SET(pgStatSock, &rset);
506 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
507 if (sel_res >= 0 || errno != EINTR)
513 (errcode_for_socket_access(),
514 errmsg("select() failed in statistics collector: %m")));
515 closesocket(pgStatSock);
516 pgStatSock = PGINVALID_SOCKET;
519 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
522 * This is the case we actually think is likely, so take pains to
523 * give a specific message for it.
525 * errno will not be set meaningfully here, so don't use it.
528 (errcode(ERRCODE_CONNECTION_FAILURE),
529 errmsg("test message did not get through on socket for statistics collector")));
530 closesocket(pgStatSock);
531 pgStatSock = PGINVALID_SOCKET;
535 test_byte++; /* just make sure variable is changed */
538 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
541 goto retry2; /* if interrupted, just retry */
543 (errcode_for_socket_access(),
544 errmsg("could not receive test message on socket for statistics collector: %m")));
545 closesocket(pgStatSock);
546 pgStatSock = PGINVALID_SOCKET;
550 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
553 (errcode(ERRCODE_INTERNAL_ERROR),
554 errmsg("incorrect test message transmission on socket for statistics collector")));
555 closesocket(pgStatSock);
556 pgStatSock = PGINVALID_SOCKET;
560 /* If we get here, we have a working socket */
564 /* Did we find a working address? */
565 if (!addr || pgStatSock == PGINVALID_SOCKET)
569 * Set the socket to non-blocking IO. This ensures that if the collector
570 * falls behind, statistics messages will be discarded; backends won't
571 * block waiting to send messages to the collector.
573 if (!pg_set_noblock(pgStatSock))
576 (errcode_for_socket_access(),
577 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
582 * Try to ensure that the socket's receive buffer is at least
583 * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
584 * data. Use of UDP protocol means that we are willing to lose data under
585 * heavy load, but we don't want it to happen just because of ridiculously
586 * small default buffer sizes (such as 8KB on older Windows versions).
591 ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
593 if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
594 (char *) &old_rcvbuf, &rcvbufsize) < 0)
596 elog(LOG, "getsockopt(SO_RCVBUF) failed: %m");
597 /* if we can't get existing size, always try to set it */
601 new_rcvbuf = PGSTAT_MIN_RCVBUF;
602 if (old_rcvbuf < new_rcvbuf)
604 if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
605 (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
606 elog(LOG, "setsockopt(SO_RCVBUF) failed: %m");
610 pg_freeaddrinfo_all(hints.ai_family, addrs);
616 (errmsg("disabling statistics collector for lack of working socket")));
619 pg_freeaddrinfo_all(hints.ai_family, addrs);
621 if (pgStatSock != PGINVALID_SOCKET)
622 closesocket(pgStatSock);
623 pgStatSock = PGINVALID_SOCKET;
626 * Adjust GUC variables to suppress useless activity, and for debugging
627 * purposes (seeing track_counts off is a clue that we failed here). We
628 * use PGC_S_OVERRIDE because there is no point in trying to turn it back
629 * on from postgresql.conf without a restart.
631 SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
635 * subroutine for pgstat_reset_all
638 pgstat_reset_remove_files(const char *directory)
641 struct dirent *entry;
642 char fname[MAXPGPATH * 2];
644 dir = AllocateDir(directory);
645 while ((entry = ReadDir(dir, directory)) != NULL)
651 * Skip directory entries that don't match the file names we write.
652 * See get_dbstat_filename for the database-specific pattern.
654 if (strncmp(entry->d_name, "global.", 7) == 0)
659 (void) sscanf(entry->d_name, "db_%u.%n",
663 /* %u allows leading whitespace, so reject that */
664 if (strchr("0123456789", entry->d_name[3]) == NULL)
668 if (strcmp(entry->d_name + nchars, "tmp") != 0 &&
669 strcmp(entry->d_name + nchars, "stat") != 0)
672 snprintf(fname, sizeof(fname), "%s/%s", directory,
680 * pgstat_reset_all() -
682 * Remove the stats files. This is currently used only if WAL
683 * recovery is needed after a crash.
686 pgstat_reset_all(void)
688 pgstat_reset_remove_files(pgstat_stat_directory);
689 pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
695 * pgstat_forkexec() -
697 * Format up the arglist for, then fork and exec, statistics collector process
700 pgstat_forkexec(void)
705 av[ac++] = "postgres";
706 av[ac++] = "--forkcol";
707 av[ac++] = NULL; /* filled in by postmaster_forkexec */
710 Assert(ac < lengthof(av));
712 return postmaster_forkexec(ac, av);
714 #endif /* EXEC_BACKEND */
720 * Called from postmaster at startup or after an existing collector
721 * died. Attempt to fire up a fresh statistics collector.
723 * Returns PID of child process, or 0 if fail.
725 * Note: if fail, we will be called again from the postmaster main loop.
734 * Check that the socket is there, else pgstat_init failed and we can do
737 if (pgStatSock == PGINVALID_SOCKET)
741 * Do nothing if too soon since last collector start. This is a safety
742 * valve to protect against continuous respawn attempts if the collector
743 * is dying immediately at launch. Note that since we will be re-called
744 * from the postmaster main loop, we will get another chance later.
746 curtime = time(NULL);
747 if ((unsigned int) (curtime - last_pgstat_start_time) <
748 (unsigned int) PGSTAT_RESTART_INTERVAL)
750 last_pgstat_start_time = curtime;
753 * Okay, fork off the collector.
756 switch ((pgStatPid = pgstat_forkexec()))
758 switch ((pgStatPid = fork_process()))
763 (errmsg("could not fork statistics collector: %m")));
768 /* in postmaster child ... */
769 InitPostmasterChild();
771 /* Close the postmaster's sockets */
772 ClosePostmasterPorts(false);
774 /* Drop our connection to postmaster's shared memory, as well */
776 PGSharedMemoryDetach();
778 PgstatCollectorMain(0, NULL);
783 return (int) pgStatPid;
786 /* shouldn't get here */
791 allow_immediate_pgstat_restart(void)
793 last_pgstat_start_time = 0;
796 /* ------------------------------------------------------------
797 * Public functions used by backends follow
798 *------------------------------------------------------------
803 * pgstat_report_stat() -
805 * Must be called by processes that performs DML: tcop/postgres.c, logical
806 * receiver processes, SPI worker, etc. to send the so far collected
807 * per-table and function usage statistics to the collector. Note that this
808 * is called only when not within a transaction, so it is fair to use
809 * transaction stop time as an approximation of current time.
813 pgstat_report_stat(bool force)
815 /* we assume this inits to all zeroes: */
816 static const PgStat_TableCounts all_zeroes;
817 static TimestampTz last_report = 0;
820 PgStat_MsgTabstat regular_msg;
821 PgStat_MsgTabstat shared_msg;
825 /* Don't expend a clock check if nothing to do */
826 if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
827 pgStatXactCommit == 0 && pgStatXactRollback == 0 &&
828 !have_function_stats)
832 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
833 * msec since we last sent one, or the caller wants to force stats out.
835 now = GetCurrentTransactionStopTimestamp();
837 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
842 * Destroy pgStatTabHash before we start invalidating PgStat_TableEntry
843 * entries it points to. (Should we fail partway through the loop below,
844 * it's okay to have removed the hashtable already --- the only
845 * consequence is we'd get multiple entries for the same table in the
846 * pgStatTabList, and that's safe.)
849 hash_destroy(pgStatTabHash);
850 pgStatTabHash = NULL;
853 * Scan through the TabStatusArray struct(s) to find tables that actually
854 * have counts, and build messages to send. We have to separate shared
855 * relations from regular ones because the databaseid field in the message
856 * header has to depend on that.
858 regular_msg.m_databaseid = MyDatabaseId;
859 shared_msg.m_databaseid = InvalidOid;
860 regular_msg.m_nentries = 0;
861 shared_msg.m_nentries = 0;
863 for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
865 for (i = 0; i < tsa->tsa_used; i++)
867 PgStat_TableStatus *entry = &tsa->tsa_entries[i];
868 PgStat_MsgTabstat *this_msg;
869 PgStat_TableEntry *this_ent;
871 /* Shouldn't have any pending transaction-dependent counts */
872 Assert(entry->trans == NULL);
875 * Ignore entries that didn't accumulate any actual counts, such
876 * as indexes that were opened by the planner but not used.
878 if (memcmp(&entry->t_counts, &all_zeroes,
879 sizeof(PgStat_TableCounts)) == 0)
883 * OK, insert data into the appropriate message, and send if full.
885 this_msg = entry->t_shared ? &shared_msg : ®ular_msg;
886 this_ent = &this_msg->m_entry[this_msg->m_nentries];
887 this_ent->t_id = entry->t_id;
888 memcpy(&this_ent->t_counts, &entry->t_counts,
889 sizeof(PgStat_TableCounts));
890 if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
892 pgstat_send_tabstat(this_msg);
893 this_msg->m_nentries = 0;
896 /* zero out TableStatus structs after use */
897 MemSet(tsa->tsa_entries, 0,
898 tsa->tsa_used * sizeof(PgStat_TableStatus));
903 * Send partial messages. Make sure that any pending xact commit/abort
904 * gets counted, even if there are no table stats to send.
906 if (regular_msg.m_nentries > 0 ||
907 pgStatXactCommit > 0 || pgStatXactRollback > 0)
908 pgstat_send_tabstat(®ular_msg);
909 if (shared_msg.m_nentries > 0)
910 pgstat_send_tabstat(&shared_msg);
912 /* Now, send function statistics */
913 pgstat_send_funcstats();
917 * Subroutine for pgstat_report_stat: finish and send a tabstat message
920 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
925 /* It's unlikely we'd get here with no socket, but maybe not impossible */
926 if (pgStatSock == PGINVALID_SOCKET)
930 * Report and reset accumulated xact commit/rollback and I/O timings
931 * whenever we send a normal tabstat message
933 if (OidIsValid(tsmsg->m_databaseid))
935 tsmsg->m_xact_commit = pgStatXactCommit;
936 tsmsg->m_xact_rollback = pgStatXactRollback;
937 tsmsg->m_block_read_time = pgStatBlockReadTime;
938 tsmsg->m_block_write_time = pgStatBlockWriteTime;
939 pgStatXactCommit = 0;
940 pgStatXactRollback = 0;
941 pgStatBlockReadTime = 0;
942 pgStatBlockWriteTime = 0;
946 tsmsg->m_xact_commit = 0;
947 tsmsg->m_xact_rollback = 0;
948 tsmsg->m_block_read_time = 0;
949 tsmsg->m_block_write_time = 0;
952 n = tsmsg->m_nentries;
953 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
954 n * sizeof(PgStat_TableEntry);
956 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
957 pgstat_send(tsmsg, len);
961 * Subroutine for pgstat_report_stat: populate and send a function stat message
964 pgstat_send_funcstats(void)
966 /* we assume this inits to all zeroes: */
967 static const PgStat_FunctionCounts all_zeroes;
969 PgStat_MsgFuncstat msg;
970 PgStat_BackendFunctionEntry *entry;
971 HASH_SEQ_STATUS fstat;
973 if (pgStatFunctions == NULL)
976 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
977 msg.m_databaseid = MyDatabaseId;
980 hash_seq_init(&fstat, pgStatFunctions);
981 while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
983 PgStat_FunctionEntry *m_ent;
985 /* Skip it if no counts accumulated since last time */
986 if (memcmp(&entry->f_counts, &all_zeroes,
987 sizeof(PgStat_FunctionCounts)) == 0)
990 /* need to convert format of time accumulators */
991 m_ent = &msg.m_entry[msg.m_nentries];
992 m_ent->f_id = entry->f_id;
993 m_ent->f_numcalls = entry->f_counts.f_numcalls;
994 m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
995 m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
997 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
999 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
1000 msg.m_nentries * sizeof(PgStat_FunctionEntry));
1004 /* reset the entry's counts */
1005 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
1008 if (msg.m_nentries > 0)
1009 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
1010 msg.m_nentries * sizeof(PgStat_FunctionEntry));
1012 have_function_stats = false;
1017 * pgstat_vacuum_stat() -
1019 * Will tell the collector about objects he can get rid of.
1023 pgstat_vacuum_stat(void)
1026 PgStat_MsgTabpurge msg;
1027 PgStat_MsgFuncpurge f_msg;
1028 HASH_SEQ_STATUS hstat;
1029 PgStat_StatDBEntry *dbentry;
1030 PgStat_StatTabEntry *tabentry;
1031 PgStat_StatFuncEntry *funcentry;
1034 if (pgStatSock == PGINVALID_SOCKET)
1038 * If not done for this transaction, read the statistics collector stats
1039 * file into some hash tables.
1041 backend_read_statsfile();
1044 * Read pg_database and make a list of OIDs of all existing databases
1046 htab = pgstat_collect_oids(DatabaseRelationId, Anum_pg_database_oid);
1049 * Search the database hash table for dead databases and tell the
1050 * collector to drop them.
1052 hash_seq_init(&hstat, pgStatDBHash);
1053 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
1055 Oid dbid = dbentry->databaseid;
1057 CHECK_FOR_INTERRUPTS();
1059 /* the DB entry for shared tables (with InvalidOid) is never dropped */
1060 if (OidIsValid(dbid) &&
1061 hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
1062 pgstat_drop_database(dbid);
1069 * Lookup our own database entry; if not found, nothing more to do.
1071 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1072 (void *) &MyDatabaseId,
1074 if (dbentry == NULL || dbentry->tables == NULL)
1078 * Similarly to above, make a list of all known relations in this DB.
1080 htab = pgstat_collect_oids(RelationRelationId, Anum_pg_class_oid);
1083 * Initialize our messages table counter to zero
1088 * Check for all tables listed in stats hashtable if they still exist.
1090 hash_seq_init(&hstat, dbentry->tables);
1091 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
1093 Oid tabid = tabentry->tableid;
1095 CHECK_FOR_INTERRUPTS();
1097 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
1101 * Not there, so add this table's Oid to the message
1103 msg.m_tableid[msg.m_nentries++] = tabid;
1106 * If the message is full, send it out and reinitialize to empty
1108 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
1110 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1111 + msg.m_nentries * sizeof(Oid);
1113 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1114 msg.m_databaseid = MyDatabaseId;
1115 pgstat_send(&msg, len);
1124 if (msg.m_nentries > 0)
1126 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1127 + msg.m_nentries * sizeof(Oid);
1129 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1130 msg.m_databaseid = MyDatabaseId;
1131 pgstat_send(&msg, len);
1138 * Now repeat the above steps for functions. However, we needn't bother
1139 * in the common case where no function stats are being collected.
1141 if (dbentry->functions != NULL &&
1142 hash_get_num_entries(dbentry->functions) > 0)
1144 htab = pgstat_collect_oids(ProcedureRelationId, Anum_pg_proc_oid);
1146 pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
1147 f_msg.m_databaseid = MyDatabaseId;
1148 f_msg.m_nentries = 0;
1150 hash_seq_init(&hstat, dbentry->functions);
1151 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
1153 Oid funcid = funcentry->functionid;
1155 CHECK_FOR_INTERRUPTS();
1157 if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
1161 * Not there, so add this function's Oid to the message
1163 f_msg.m_functionid[f_msg.m_nentries++] = funcid;
1166 * If the message is full, send it out and reinitialize to empty
1168 if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
1170 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1171 + f_msg.m_nentries * sizeof(Oid);
1173 pgstat_send(&f_msg, len);
1175 f_msg.m_nentries = 0;
1182 if (f_msg.m_nentries > 0)
1184 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1185 + f_msg.m_nentries * sizeof(Oid);
1187 pgstat_send(&f_msg, len);
1196 * pgstat_collect_oids() -
1198 * Collect the OIDs of all objects listed in the specified system catalog
1199 * into a temporary hash table. Caller should hash_destroy the result
1200 * when done with it. (However, we make the table in CurrentMemoryContext
1201 * so that it will be freed properly in event of an error.)
1205 pgstat_collect_oids(Oid catalogid, AttrNumber anum_oid)
1214 memset(&hash_ctl, 0, sizeof(hash_ctl));
1215 hash_ctl.keysize = sizeof(Oid);
1216 hash_ctl.entrysize = sizeof(Oid);
1217 hash_ctl.hcxt = CurrentMemoryContext;
1218 htab = hash_create("Temporary table of OIDs",
1219 PGSTAT_TAB_HASH_SIZE,
1221 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1223 rel = table_open(catalogid, AccessShareLock);
1224 snapshot = RegisterSnapshot(GetLatestSnapshot());
1225 scan = table_beginscan(rel, snapshot, 0, NULL);
1226 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1231 thisoid = heap_getattr(tup, anum_oid, RelationGetDescr(rel), &isnull);
1234 CHECK_FOR_INTERRUPTS();
1236 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1238 table_endscan(scan);
1239 UnregisterSnapshot(snapshot);
1240 table_close(rel, AccessShareLock);
1247 * pgstat_drop_database() -
1249 * Tell the collector that we just dropped a database.
1250 * (If the message gets lost, we will still clean the dead DB eventually
1251 * via future invocations of pgstat_vacuum_stat().)
1255 pgstat_drop_database(Oid databaseid)
1257 PgStat_MsgDropdb msg;
1259 if (pgStatSock == PGINVALID_SOCKET)
1262 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1263 msg.m_databaseid = databaseid;
1264 pgstat_send(&msg, sizeof(msg));
1269 * pgstat_drop_relation() -
1271 * Tell the collector that we just dropped a relation.
1272 * (If the message gets lost, we will still clean the dead entry eventually
1273 * via future invocations of pgstat_vacuum_stat().)
1275 * Currently not used for lack of any good place to call it; we rely
1276 * entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1281 pgstat_drop_relation(Oid relid)
1283 PgStat_MsgTabpurge msg;
1286 if (pgStatSock == PGINVALID_SOCKET)
1289 msg.m_tableid[0] = relid;
1292 len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) + sizeof(Oid);
1294 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1295 msg.m_databaseid = MyDatabaseId;
1296 pgstat_send(&msg, len);
1298 #endif /* NOT_USED */
1302 * pgstat_reset_counters() -
1304 * Tell the statistics collector to reset counters for our database.
1306 * Permission checking for this function is managed through the normal
1311 pgstat_reset_counters(void)
1313 PgStat_MsgResetcounter msg;
1315 if (pgStatSock == PGINVALID_SOCKET)
1318 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1319 msg.m_databaseid = MyDatabaseId;
1320 pgstat_send(&msg, sizeof(msg));
1324 * pgstat_reset_shared_counters() -
1326 * Tell the statistics collector to reset cluster-wide shared counters.
1328 * Permission checking for this function is managed through the normal
1333 pgstat_reset_shared_counters(const char *target)
1335 PgStat_MsgResetsharedcounter msg;
1337 if (pgStatSock == PGINVALID_SOCKET)
1340 if (strcmp(target, "archiver") == 0)
1341 msg.m_resettarget = RESET_ARCHIVER;
1342 else if (strcmp(target, "bgwriter") == 0)
1343 msg.m_resettarget = RESET_BGWRITER;
1346 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1347 errmsg("unrecognized reset target: \"%s\"", target),
1348 errhint("Target must be \"archiver\" or \"bgwriter\".")));
1350 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
1351 pgstat_send(&msg, sizeof(msg));
1355 * pgstat_reset_single_counter() -
1357 * Tell the statistics collector to reset a single counter.
1359 * Permission checking for this function is managed through the normal
1364 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
1366 PgStat_MsgResetsinglecounter msg;
1368 if (pgStatSock == PGINVALID_SOCKET)
1371 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
1372 msg.m_databaseid = MyDatabaseId;
1373 msg.m_resettype = type;
1374 msg.m_objectid = objoid;
1376 pgstat_send(&msg, sizeof(msg));
1380 * pgstat_report_autovac() -
1382 * Called from autovacuum.c to report startup of an autovacuum process.
1383 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1384 * the db OID must be passed in, instead.
1388 pgstat_report_autovac(Oid dboid)
1390 PgStat_MsgAutovacStart msg;
1392 if (pgStatSock == PGINVALID_SOCKET)
1395 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1396 msg.m_databaseid = dboid;
1397 msg.m_start_time = GetCurrentTimestamp();
1399 pgstat_send(&msg, sizeof(msg));
1404 * pgstat_report_vacuum() -
1406 * Tell the collector about the table we just vacuumed.
1410 pgstat_report_vacuum(Oid tableoid, bool shared,
1411 PgStat_Counter livetuples, PgStat_Counter deadtuples)
1413 PgStat_MsgVacuum msg;
1415 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1418 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1419 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1420 msg.m_tableoid = tableoid;
1421 msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1422 msg.m_vacuumtime = GetCurrentTimestamp();
1423 msg.m_live_tuples = livetuples;
1424 msg.m_dead_tuples = deadtuples;
1425 pgstat_send(&msg, sizeof(msg));
1429 * pgstat_report_analyze() -
1431 * Tell the collector about the table we just analyzed.
1433 * Caller must provide new live- and dead-tuples estimates, as well as a
1434 * flag indicating whether to reset the changes_since_analyze counter.
1438 pgstat_report_analyze(Relation rel,
1439 PgStat_Counter livetuples, PgStat_Counter deadtuples,
1442 PgStat_MsgAnalyze msg;
1444 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1448 * Unlike VACUUM, ANALYZE might be running inside a transaction that has
1449 * already inserted and/or deleted rows in the target table. ANALYZE will
1450 * have counted such rows as live or dead respectively. Because we will
1451 * report our counts of such rows at transaction end, we should subtract
1452 * off these counts from what we send to the collector now, else they'll
1453 * be double-counted after commit. (This approach also ensures that the
1454 * collector ends up with the right numbers if we abort instead of
1457 if (rel->pgstat_info != NULL)
1459 PgStat_TableXactStatus *trans;
1461 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1463 livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1464 deadtuples -= trans->tuples_updated + trans->tuples_deleted;
1466 /* count stuff inserted by already-aborted subxacts, too */
1467 deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
1468 /* Since ANALYZE's counts are estimates, we could have underflowed */
1469 livetuples = Max(livetuples, 0);
1470 deadtuples = Max(deadtuples, 0);
1473 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1474 msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1475 msg.m_tableoid = RelationGetRelid(rel);
1476 msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1477 msg.m_resetcounter = resetcounter;
1478 msg.m_analyzetime = GetCurrentTimestamp();
1479 msg.m_live_tuples = livetuples;
1480 msg.m_dead_tuples = deadtuples;
1481 pgstat_send(&msg, sizeof(msg));
1485 * pgstat_report_recovery_conflict() -
1487 * Tell the collector about a Hot Standby recovery conflict.
1491 pgstat_report_recovery_conflict(int reason)
1493 PgStat_MsgRecoveryConflict msg;
1495 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1498 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
1499 msg.m_databaseid = MyDatabaseId;
1500 msg.m_reason = reason;
1501 pgstat_send(&msg, sizeof(msg));
1505 * pgstat_report_deadlock() -
1507 * Tell the collector about a deadlock detected.
1511 pgstat_report_deadlock(void)
1513 PgStat_MsgDeadlock msg;
1515 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1518 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
1519 msg.m_databaseid = MyDatabaseId;
1520 pgstat_send(&msg, sizeof(msg));
1526 * pgstat_report_checksum_failures_in_db(dboid, failure_count) -
1528 * Tell the collector about one or more checksum failures.
1532 pgstat_report_checksum_failures_in_db(Oid dboid, int failurecount)
1534 PgStat_MsgChecksumFailure msg;
1536 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1539 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_CHECKSUMFAILURE);
1540 msg.m_databaseid = dboid;
1541 msg.m_failurecount = failurecount;
1542 pgstat_send(&msg, sizeof(msg));
1546 * pgstat_report_checksum_failure() -
1548 * Tell the collector about a checksum failure.
1552 pgstat_report_checksum_failure(void)
1554 pgstat_report_checksum_failures_in_db(MyDatabaseId, 1);
1558 * pgstat_report_tempfile() -
1560 * Tell the collector about a temporary file.
1564 pgstat_report_tempfile(size_t filesize)
1566 PgStat_MsgTempFile msg;
1568 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1571 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
1572 msg.m_databaseid = MyDatabaseId;
1573 msg.m_filesize = filesize;
1574 pgstat_send(&msg, sizeof(msg));
1581 * Send some junk data to the collector to increase traffic.
1587 PgStat_MsgDummy msg;
1589 if (pgStatSock == PGINVALID_SOCKET)
1592 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1593 pgstat_send(&msg, sizeof(msg));
1597 * pgstat_send_inquiry() -
1599 * Notify collector that we need fresh data.
1603 pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
1605 PgStat_MsgInquiry msg;
1607 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
1608 msg.clock_time = clock_time;
1609 msg.cutoff_time = cutoff_time;
1610 msg.databaseid = databaseid;
1611 pgstat_send(&msg, sizeof(msg));
1616 * Initialize function call usage data.
1617 * Called by the executor before invoking a function.
1620 pgstat_init_function_usage(FunctionCallInfo fcinfo,
1621 PgStat_FunctionCallUsage *fcu)
1623 PgStat_BackendFunctionEntry *htabent;
1626 if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1628 /* stats not wanted */
1633 if (!pgStatFunctions)
1635 /* First time through - initialize function stat table */
1638 memset(&hash_ctl, 0, sizeof(hash_ctl));
1639 hash_ctl.keysize = sizeof(Oid);
1640 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1641 pgStatFunctions = hash_create("Function stat entries",
1642 PGSTAT_FUNCTION_HASH_SIZE,
1644 HASH_ELEM | HASH_BLOBS);
1647 /* Get the stats entry for this function, create if necessary */
1648 htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1649 HASH_ENTER, &found);
1651 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1653 fcu->fs = &htabent->f_counts;
1655 /* save stats for this function, later used to compensate for recursion */
1656 fcu->save_f_total_time = htabent->f_counts.f_total_time;
1658 /* save current backend-wide total time */
1659 fcu->save_total = total_func_time;
1661 /* get clock time as of function start */
1662 INSTR_TIME_SET_CURRENT(fcu->f_start);
1666 * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
1667 * for specified function
1669 * If no entry, return NULL, don't create a new one
1671 PgStat_BackendFunctionEntry *
1672 find_funcstat_entry(Oid func_id)
1674 if (pgStatFunctions == NULL)
1677 return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
1683 * Calculate function call usage and update stat counters.
1684 * Called by the executor after invoking a function.
1686 * In the case of a set-returning function that runs in value-per-call mode,
1687 * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1688 * calls for what the user considers a single call of the function. The
1689 * finalize flag should be TRUE on the last call.
1692 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1694 PgStat_FunctionCounts *fs = fcu->fs;
1696 instr_time f_others;
1699 /* stats not wanted? */
1703 /* total elapsed time in this function call */
1704 INSTR_TIME_SET_CURRENT(f_total);
1705 INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1707 /* self usage: elapsed minus anything already charged to other calls */
1708 f_others = total_func_time;
1709 INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1711 INSTR_TIME_SUBTRACT(f_self, f_others);
1713 /* update backend-wide total time */
1714 INSTR_TIME_ADD(total_func_time, f_self);
1717 * Compute the new f_total_time as the total elapsed time added to the
1718 * pre-call value of f_total_time. This is necessary to avoid
1719 * double-counting any time taken by recursive calls of myself. (We do
1720 * not need any similar kluge for self time, since that already excludes
1721 * any recursive calls.)
1723 INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1725 /* update counters in function stats table */
1728 fs->f_total_time = f_total;
1729 INSTR_TIME_ADD(fs->f_self_time, f_self);
1731 /* indicate that we have something to send */
1732 have_function_stats = true;
1737 * pgstat_initstats() -
1739 * Initialize a relcache entry to count access statistics.
1740 * Called whenever a relation is opened.
1742 * We assume that a relcache entry's pgstat_info field is zeroed by
1743 * relcache.c when the relcache entry is made; thereafter it is long-lived
1744 * data. We can avoid repeated searches of the TabStatus arrays when the
1745 * same relation is touched repeatedly within a transaction.
1749 pgstat_initstats(Relation rel)
1751 Oid rel_id = rel->rd_id;
1752 char relkind = rel->rd_rel->relkind;
1754 /* We only count stats for things that have storage */
1755 if (!(relkind == RELKIND_RELATION ||
1756 relkind == RELKIND_MATVIEW ||
1757 relkind == RELKIND_INDEX ||
1758 relkind == RELKIND_TOASTVALUE ||
1759 relkind == RELKIND_SEQUENCE))
1761 rel->pgstat_info = NULL;
1765 if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1767 /* We're not counting at all */
1768 rel->pgstat_info = NULL;
1773 * If we already set up this relation in the current transaction, nothing
1776 if (rel->pgstat_info != NULL &&
1777 rel->pgstat_info->t_id == rel_id)
1780 /* Else find or make the PgStat_TableStatus entry, and update link */
1781 rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1785 * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1787 static PgStat_TableStatus *
1788 get_tabstat_entry(Oid rel_id, bool isshared)
1790 TabStatHashEntry *hash_entry;
1791 PgStat_TableStatus *entry;
1792 TabStatusArray *tsa;
1796 * Create hash table if we don't have it already.
1798 if (pgStatTabHash == NULL)
1802 memset(&ctl, 0, sizeof(ctl));
1803 ctl.keysize = sizeof(Oid);
1804 ctl.entrysize = sizeof(TabStatHashEntry);
1806 pgStatTabHash = hash_create("pgstat TabStatusArray lookup hash table",
1809 HASH_ELEM | HASH_BLOBS);
1813 * Find an entry or create a new one.
1815 hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_ENTER, &found);
1818 /* initialize new entry with null pointer */
1819 hash_entry->tsa_entry = NULL;
1823 * If entry is already valid, we're done.
1825 if (hash_entry->tsa_entry)
1826 return hash_entry->tsa_entry;
1829 * Locate the first pgStatTabList entry with free space, making a new list
1830 * entry if needed. Note that we could get an OOM failure here, but if so
1831 * we have left the hashtable and the list in a consistent state.
1833 if (pgStatTabList == NULL)
1835 /* Set up first pgStatTabList entry */
1836 pgStatTabList = (TabStatusArray *)
1837 MemoryContextAllocZero(TopMemoryContext,
1838 sizeof(TabStatusArray));
1841 tsa = pgStatTabList;
1842 while (tsa->tsa_used >= TABSTAT_QUANTUM)
1844 if (tsa->tsa_next == NULL)
1845 tsa->tsa_next = (TabStatusArray *)
1846 MemoryContextAllocZero(TopMemoryContext,
1847 sizeof(TabStatusArray));
1848 tsa = tsa->tsa_next;
1852 * Allocate a PgStat_TableStatus entry within this list entry. We assume
1853 * the entry was already zeroed, either at creation or after last use.
1855 entry = &tsa->tsa_entries[tsa->tsa_used++];
1856 entry->t_id = rel_id;
1857 entry->t_shared = isshared;
1860 * Now we can fill the entry in pgStatTabHash.
1862 hash_entry->tsa_entry = entry;
1868 * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
1870 * If no entry, return NULL, don't create a new one
1872 * Note: if we got an error in the most recent execution of pgstat_report_stat,
1873 * it's possible that an entry exists but there's no hashtable entry for it.
1874 * That's okay, we'll treat this case as "doesn't exist".
1876 PgStat_TableStatus *
1877 find_tabstat_entry(Oid rel_id)
1879 TabStatHashEntry *hash_entry;
1881 /* If hashtable doesn't exist, there are no entries at all */
1885 hash_entry = hash_search(pgStatTabHash, &rel_id, HASH_FIND, NULL);
1889 /* Note that this step could also return NULL, but that's correct */
1890 return hash_entry->tsa_entry;
1894 * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1896 static PgStat_SubXactStatus *
1897 get_tabstat_stack_level(int nest_level)
1899 PgStat_SubXactStatus *xact_state;
1901 xact_state = pgStatXactStack;
1902 if (xact_state == NULL || xact_state->nest_level != nest_level)
1904 xact_state = (PgStat_SubXactStatus *)
1905 MemoryContextAlloc(TopTransactionContext,
1906 sizeof(PgStat_SubXactStatus));
1907 xact_state->nest_level = nest_level;
1908 xact_state->prev = pgStatXactStack;
1909 xact_state->first = NULL;
1910 pgStatXactStack = xact_state;
1916 * add_tabstat_xact_level - add a new (sub)transaction state record
1919 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1921 PgStat_SubXactStatus *xact_state;
1922 PgStat_TableXactStatus *trans;
1925 * If this is the first rel to be modified at the current nest level, we
1926 * first have to push a transaction stack entry.
1928 xact_state = get_tabstat_stack_level(nest_level);
1930 /* Now make a per-table stack entry */
1931 trans = (PgStat_TableXactStatus *)
1932 MemoryContextAllocZero(TopTransactionContext,
1933 sizeof(PgStat_TableXactStatus));
1934 trans->nest_level = nest_level;
1935 trans->upper = pgstat_info->trans;
1936 trans->parent = pgstat_info;
1937 trans->next = xact_state->first;
1938 xact_state->first = trans;
1939 pgstat_info->trans = trans;
1943 * pgstat_count_heap_insert - count a tuple insertion of n tuples
1946 pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
1948 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1950 if (pgstat_info != NULL)
1952 /* We have to log the effect at the proper transactional level */
1953 int nest_level = GetCurrentTransactionNestLevel();
1955 if (pgstat_info->trans == NULL ||
1956 pgstat_info->trans->nest_level != nest_level)
1957 add_tabstat_xact_level(pgstat_info, nest_level);
1959 pgstat_info->trans->tuples_inserted += n;
1964 * pgstat_count_heap_update - count a tuple update
1967 pgstat_count_heap_update(Relation rel, bool hot)
1969 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1971 if (pgstat_info != NULL)
1973 /* We have to log the effect at the proper transactional level */
1974 int nest_level = GetCurrentTransactionNestLevel();
1976 if (pgstat_info->trans == NULL ||
1977 pgstat_info->trans->nest_level != nest_level)
1978 add_tabstat_xact_level(pgstat_info, nest_level);
1980 pgstat_info->trans->tuples_updated++;
1982 /* t_tuples_hot_updated is nontransactional, so just advance it */
1984 pgstat_info->t_counts.t_tuples_hot_updated++;
1989 * pgstat_count_heap_delete - count a tuple deletion
1992 pgstat_count_heap_delete(Relation rel)
1994 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1996 if (pgstat_info != NULL)
1998 /* We have to log the effect at the proper transactional level */
1999 int nest_level = GetCurrentTransactionNestLevel();
2001 if (pgstat_info->trans == NULL ||
2002 pgstat_info->trans->nest_level != nest_level)
2003 add_tabstat_xact_level(pgstat_info, nest_level);
2005 pgstat_info->trans->tuples_deleted++;
2010 * pgstat_truncate_save_counters
2012 * Whenever a table is truncated, we save its i/u/d counters so that they can
2013 * be cleared, and if the (sub)xact that executed the truncate later aborts,
2014 * the counters can be restored to the saved (pre-truncate) values. Note we do
2015 * this on the first truncate in any particular subxact level only.
2018 pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
2020 if (!trans->truncated)
2022 trans->inserted_pre_trunc = trans->tuples_inserted;
2023 trans->updated_pre_trunc = trans->tuples_updated;
2024 trans->deleted_pre_trunc = trans->tuples_deleted;
2025 trans->truncated = true;
2030 * pgstat_truncate_restore_counters - restore counters when a truncate aborts
2033 pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
2035 if (trans->truncated)
2037 trans->tuples_inserted = trans->inserted_pre_trunc;
2038 trans->tuples_updated = trans->updated_pre_trunc;
2039 trans->tuples_deleted = trans->deleted_pre_trunc;
2044 * pgstat_count_truncate - update tuple counters due to truncate
2047 pgstat_count_truncate(Relation rel)
2049 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2051 if (pgstat_info != NULL)
2053 /* We have to log the effect at the proper transactional level */
2054 int nest_level = GetCurrentTransactionNestLevel();
2056 if (pgstat_info->trans == NULL ||
2057 pgstat_info->trans->nest_level != nest_level)
2058 add_tabstat_xact_level(pgstat_info, nest_level);
2060 pgstat_truncate_save_counters(pgstat_info->trans);
2061 pgstat_info->trans->tuples_inserted = 0;
2062 pgstat_info->trans->tuples_updated = 0;
2063 pgstat_info->trans->tuples_deleted = 0;
2068 * pgstat_update_heap_dead_tuples - update dead-tuples count
2070 * The semantics of this are that we are reporting the nontransactional
2071 * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
2072 * rather than increasing, and the change goes straight into the per-table
2073 * counter, not into transactional state.
2076 pgstat_update_heap_dead_tuples(Relation rel, int delta)
2078 PgStat_TableStatus *pgstat_info = rel->pgstat_info;
2080 if (pgstat_info != NULL)
2081 pgstat_info->t_counts.t_delta_dead_tuples -= delta;
2088 * Called from access/transam/xact.c at top-level transaction commit/abort.
2092 AtEOXact_PgStat(bool isCommit)
2094 PgStat_SubXactStatus *xact_state;
2097 * Count transaction commit or abort. (We use counters, not just bools,
2098 * in case the reporting message isn't sent right away.)
2103 pgStatXactRollback++;
2106 * Transfer transactional insert/update counts into the base tabstat
2107 * entries. We don't bother to free any of the transactional state, since
2108 * it's all in TopTransactionContext and will go away anyway.
2110 xact_state = pgStatXactStack;
2111 if (xact_state != NULL)
2113 PgStat_TableXactStatus *trans;
2115 Assert(xact_state->nest_level == 1);
2116 Assert(xact_state->prev == NULL);
2117 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2119 PgStat_TableStatus *tabstat;
2121 Assert(trans->nest_level == 1);
2122 Assert(trans->upper == NULL);
2123 tabstat = trans->parent;
2124 Assert(tabstat->trans == trans);
2125 /* restore pre-truncate stats (if any) in case of aborted xact */
2127 pgstat_truncate_restore_counters(trans);
2128 /* count attempted actions regardless of commit/abort */
2129 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2130 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2131 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2134 tabstat->t_counts.t_truncated = trans->truncated;
2135 if (trans->truncated)
2137 /* forget live/dead stats seen by backend thus far */
2138 tabstat->t_counts.t_delta_live_tuples = 0;
2139 tabstat->t_counts.t_delta_dead_tuples = 0;
2141 /* insert adds a live tuple, delete removes one */
2142 tabstat->t_counts.t_delta_live_tuples +=
2143 trans->tuples_inserted - trans->tuples_deleted;
2144 /* update and delete each create a dead tuple */
2145 tabstat->t_counts.t_delta_dead_tuples +=
2146 trans->tuples_updated + trans->tuples_deleted;
2147 /* insert, update, delete each count as one change event */
2148 tabstat->t_counts.t_changed_tuples +=
2149 trans->tuples_inserted + trans->tuples_updated +
2150 trans->tuples_deleted;
2154 /* inserted tuples are dead, deleted tuples are unaffected */
2155 tabstat->t_counts.t_delta_dead_tuples +=
2156 trans->tuples_inserted + trans->tuples_updated;
2157 /* an aborted xact generates no changed_tuple events */
2159 tabstat->trans = NULL;
2162 pgStatXactStack = NULL;
2164 /* Make sure any stats snapshot is thrown away */
2165 pgstat_clear_snapshot();
2169 * AtEOSubXact_PgStat
2171 * Called from access/transam/xact.c at subtransaction commit/abort.
2175 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
2177 PgStat_SubXactStatus *xact_state;
2180 * Transfer transactional insert/update counts into the next higher
2181 * subtransaction state.
2183 xact_state = pgStatXactStack;
2184 if (xact_state != NULL &&
2185 xact_state->nest_level >= nestDepth)
2187 PgStat_TableXactStatus *trans;
2188 PgStat_TableXactStatus *next_trans;
2190 /* delink xact_state from stack immediately to simplify reuse case */
2191 pgStatXactStack = xact_state->prev;
2193 for (trans = xact_state->first; trans != NULL; trans = next_trans)
2195 PgStat_TableStatus *tabstat;
2197 next_trans = trans->next;
2198 Assert(trans->nest_level == nestDepth);
2199 tabstat = trans->parent;
2200 Assert(tabstat->trans == trans);
2203 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2205 if (trans->truncated)
2207 /* propagate the truncate status one level up */
2208 pgstat_truncate_save_counters(trans->upper);
2209 /* replace upper xact stats with ours */
2210 trans->upper->tuples_inserted = trans->tuples_inserted;
2211 trans->upper->tuples_updated = trans->tuples_updated;
2212 trans->upper->tuples_deleted = trans->tuples_deleted;
2216 trans->upper->tuples_inserted += trans->tuples_inserted;
2217 trans->upper->tuples_updated += trans->tuples_updated;
2218 trans->upper->tuples_deleted += trans->tuples_deleted;
2220 tabstat->trans = trans->upper;
2226 * When there isn't an immediate parent state, we can just
2227 * reuse the record instead of going through a
2228 * palloc/pfree pushup (this works since it's all in
2229 * TopTransactionContext anyway). We have to re-link it
2230 * into the parent level, though, and that might mean
2231 * pushing a new entry into the pgStatXactStack.
2233 PgStat_SubXactStatus *upper_xact_state;
2235 upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2236 trans->next = upper_xact_state->first;
2237 upper_xact_state->first = trans;
2238 trans->nest_level = nestDepth - 1;
2244 * On abort, update top-level tabstat counts, then forget the
2248 /* first restore values obliterated by truncate */
2249 pgstat_truncate_restore_counters(trans);
2250 /* count attempted actions regardless of commit/abort */
2251 tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2252 tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2253 tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2254 /* inserted tuples are dead, deleted tuples are unaffected */
2255 tabstat->t_counts.t_delta_dead_tuples +=
2256 trans->tuples_inserted + trans->tuples_updated;
2257 tabstat->trans = trans->upper;
2268 * Save the transactional stats state at 2PC transaction prepare.
2270 * In this phase we just generate 2PC records for all the pending
2271 * transaction-dependent stats work.
2274 AtPrepare_PgStat(void)
2276 PgStat_SubXactStatus *xact_state;
2278 xact_state = pgStatXactStack;
2279 if (xact_state != NULL)
2281 PgStat_TableXactStatus *trans;
2283 Assert(xact_state->nest_level == 1);
2284 Assert(xact_state->prev == NULL);
2285 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2287 PgStat_TableStatus *tabstat;
2288 TwoPhasePgStatRecord record;
2290 Assert(trans->nest_level == 1);
2291 Assert(trans->upper == NULL);
2292 tabstat = trans->parent;
2293 Assert(tabstat->trans == trans);
2295 record.tuples_inserted = trans->tuples_inserted;
2296 record.tuples_updated = trans->tuples_updated;
2297 record.tuples_deleted = trans->tuples_deleted;
2298 record.inserted_pre_trunc = trans->inserted_pre_trunc;
2299 record.updated_pre_trunc = trans->updated_pre_trunc;
2300 record.deleted_pre_trunc = trans->deleted_pre_trunc;
2301 record.t_id = tabstat->t_id;
2302 record.t_shared = tabstat->t_shared;
2303 record.t_truncated = trans->truncated;
2305 RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
2306 &record, sizeof(TwoPhasePgStatRecord));
2312 * PostPrepare_PgStat
2313 * Clean up after successful PREPARE.
2315 * All we need do here is unlink the transaction stats state from the
2316 * nontransactional state. The nontransactional action counts will be
2317 * reported to the stats collector immediately, while the effects on live
2318 * and dead tuple counts are preserved in the 2PC state file.
2320 * Note: AtEOXact_PgStat is not called during PREPARE.
2323 PostPrepare_PgStat(void)
2325 PgStat_SubXactStatus *xact_state;
2328 * We don't bother to free any of the transactional state, since it's all
2329 * in TopTransactionContext and will go away anyway.
2331 xact_state = pgStatXactStack;
2332 if (xact_state != NULL)
2334 PgStat_TableXactStatus *trans;
2336 for (trans = xact_state->first; trans != NULL; trans = trans->next)
2338 PgStat_TableStatus *tabstat;
2340 tabstat = trans->parent;
2341 tabstat->trans = NULL;
2344 pgStatXactStack = NULL;
2346 /* Make sure any stats snapshot is thrown away */
2347 pgstat_clear_snapshot();
2351 * 2PC processing routine for COMMIT PREPARED case.
2353 * Load the saved counts into our local pgstats state.
2356 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
2357 void *recdata, uint32 len)
2359 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2360 PgStat_TableStatus *pgstat_info;
2362 /* Find or create a tabstat entry for the rel */
2363 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2365 /* Same math as in AtEOXact_PgStat, commit case */
2366 pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2367 pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2368 pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2369 pgstat_info->t_counts.t_truncated = rec->t_truncated;
2370 if (rec->t_truncated)
2372 /* forget live/dead stats seen by backend thus far */
2373 pgstat_info->t_counts.t_delta_live_tuples = 0;
2374 pgstat_info->t_counts.t_delta_dead_tuples = 0;
2376 pgstat_info->t_counts.t_delta_live_tuples +=
2377 rec->tuples_inserted - rec->tuples_deleted;
2378 pgstat_info->t_counts.t_delta_dead_tuples +=
2379 rec->tuples_updated + rec->tuples_deleted;
2380 pgstat_info->t_counts.t_changed_tuples +=
2381 rec->tuples_inserted + rec->tuples_updated +
2382 rec->tuples_deleted;
2386 * 2PC processing routine for ROLLBACK PREPARED case.
2388 * Load the saved counts into our local pgstats state, but treat them
2392 pgstat_twophase_postabort(TransactionId xid, uint16 info,
2393 void *recdata, uint32 len)
2395 TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2396 PgStat_TableStatus *pgstat_info;
2398 /* Find or create a tabstat entry for the rel */
2399 pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2401 /* Same math as in AtEOXact_PgStat, abort case */
2402 if (rec->t_truncated)
2404 rec->tuples_inserted = rec->inserted_pre_trunc;
2405 rec->tuples_updated = rec->updated_pre_trunc;
2406 rec->tuples_deleted = rec->deleted_pre_trunc;
2408 pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2409 pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2410 pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2411 pgstat_info->t_counts.t_delta_dead_tuples +=
2412 rec->tuples_inserted + rec->tuples_updated;
2417 * pgstat_fetch_stat_dbentry() -
2419 * Support function for the SQL-callable pgstat* functions. Returns
2420 * the collected statistics for one database or NULL. NULL doesn't mean
2421 * that the database doesn't exist, it is just not yet known by the
2422 * collector, so the caller is better off to report ZERO instead.
2425 PgStat_StatDBEntry *
2426 pgstat_fetch_stat_dbentry(Oid dbid)
2429 * If not done for this transaction, read the statistics collector stats
2430 * file into some hash tables.
2432 backend_read_statsfile();
2435 * Lookup the requested database; return NULL if not found
2437 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2444 * pgstat_fetch_stat_tabentry() -
2446 * Support function for the SQL-callable pgstat* functions. Returns
2447 * the collected statistics for one table or NULL. NULL doesn't mean
2448 * that the table doesn't exist, it is just not yet known by the
2449 * collector, so the caller is better off to report ZERO instead.
2452 PgStat_StatTabEntry *
2453 pgstat_fetch_stat_tabentry(Oid relid)
2456 PgStat_StatDBEntry *dbentry;
2457 PgStat_StatTabEntry *tabentry;
2460 * If not done for this transaction, read the statistics collector stats
2461 * file into some hash tables.
2463 backend_read_statsfile();
2466 * Lookup our database, then look in its table hash table.
2468 dbid = MyDatabaseId;
2469 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2472 if (dbentry != NULL && dbentry->tables != NULL)
2474 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2482 * If we didn't find it, maybe it's a shared table.
2485 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2488 if (dbentry != NULL && dbentry->tables != NULL)
2490 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2502 * pgstat_fetch_stat_funcentry() -
2504 * Support function for the SQL-callable pgstat* functions. Returns
2505 * the collected statistics for one function or NULL.
2508 PgStat_StatFuncEntry *
2509 pgstat_fetch_stat_funcentry(Oid func_id)
2511 PgStat_StatDBEntry *dbentry;
2512 PgStat_StatFuncEntry *funcentry = NULL;
2514 /* load the stats file if needed */
2515 backend_read_statsfile();
2517 /* Lookup our database, then find the requested function. */
2518 dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
2519 if (dbentry != NULL && dbentry->functions != NULL)
2521 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2531 * pgstat_fetch_stat_beentry() -
2533 * Support function for the SQL-callable pgstat* functions. Returns
2534 * our local copy of the current-activity entry for one backend.
2536 * NB: caller is responsible for a check if the user is permitted to see
2537 * this info (especially the querystring).
2541 pgstat_fetch_stat_beentry(int beid)
2543 pgstat_read_current_status();
2545 if (beid < 1 || beid > localNumBackends)
2548 return &localBackendStatusTable[beid - 1].backendStatus;
2553 * pgstat_fetch_stat_local_beentry() -
2555 * Like pgstat_fetch_stat_beentry() but with locally computed additions (like
2556 * xid and xmin values of the backend)
2558 * NB: caller is responsible for a check if the user is permitted to see
2559 * this info (especially the querystring).
2562 LocalPgBackendStatus *
2563 pgstat_fetch_stat_local_beentry(int beid)
2565 pgstat_read_current_status();
2567 if (beid < 1 || beid > localNumBackends)
2570 return &localBackendStatusTable[beid - 1];
2575 * pgstat_fetch_stat_numbackends() -
2577 * Support function for the SQL-callable pgstat* functions. Returns
2578 * the maximum current backend id.
2582 pgstat_fetch_stat_numbackends(void)
2584 pgstat_read_current_status();
2586 return localNumBackends;
2591 * pgstat_fetch_stat_archiver() -
2593 * Support function for the SQL-callable pgstat* functions. Returns
2594 * a pointer to the archiver statistics struct.
2597 PgStat_ArchiverStats *
2598 pgstat_fetch_stat_archiver(void)
2600 backend_read_statsfile();
2602 return &archiverStats;
2608 * pgstat_fetch_global() -
2610 * Support function for the SQL-callable pgstat* functions. Returns
2611 * a pointer to the global statistics struct.
2614 PgStat_GlobalStats *
2615 pgstat_fetch_global(void)
2617 backend_read_statsfile();
2619 return &globalStats;
2623 /* ------------------------------------------------------------
2624 * Functions for management of the shared-memory PgBackendStatus array
2625 * ------------------------------------------------------------
2628 static PgBackendStatus *BackendStatusArray = NULL;
2629 static PgBackendStatus *MyBEEntry = NULL;
2630 static char *BackendAppnameBuffer = NULL;
2631 static char *BackendClientHostnameBuffer = NULL;
2632 static char *BackendActivityBuffer = NULL;
2633 static Size BackendActivityBufferSize = 0;
2635 static PgBackendSSLStatus *BackendSslStatusBuffer = NULL;
2640 * Report shared-memory space needed by CreateSharedBackendStatus.
2643 BackendStatusShmemSize(void)
2647 /* BackendStatusArray: */
2648 size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2649 /* BackendAppnameBuffer: */
2650 size = add_size(size,
2651 mul_size(NAMEDATALEN, NumBackendStatSlots));
2652 /* BackendClientHostnameBuffer: */
2653 size = add_size(size,
2654 mul_size(NAMEDATALEN, NumBackendStatSlots));
2655 /* BackendActivityBuffer: */
2656 size = add_size(size,
2657 mul_size(pgstat_track_activity_query_size, NumBackendStatSlots));
2659 /* BackendSslStatusBuffer: */
2660 size = add_size(size,
2661 mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots));
2667 * Initialize the shared status array and several string buffers
2668 * during postmaster startup.
2671 CreateSharedBackendStatus(void)
2678 /* Create or attach to the shared array */
2679 size = mul_size(sizeof(PgBackendStatus), NumBackendStatSlots);
2680 BackendStatusArray = (PgBackendStatus *)
2681 ShmemInitStruct("Backend Status Array", size, &found);
2686 * We're the first - initialize.
2688 MemSet(BackendStatusArray, 0, size);
2691 /* Create or attach to the shared appname buffer */
2692 size = mul_size(NAMEDATALEN, NumBackendStatSlots);
2693 BackendAppnameBuffer = (char *)
2694 ShmemInitStruct("Backend Application Name Buffer", size, &found);
2698 MemSet(BackendAppnameBuffer, 0, size);
2700 /* Initialize st_appname pointers. */
2701 buffer = BackendAppnameBuffer;
2702 for (i = 0; i < NumBackendStatSlots; i++)
2704 BackendStatusArray[i].st_appname = buffer;
2705 buffer += NAMEDATALEN;
2709 /* Create or attach to the shared client hostname buffer */
2710 size = mul_size(NAMEDATALEN, NumBackendStatSlots);
2711 BackendClientHostnameBuffer = (char *)
2712 ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2716 MemSet(BackendClientHostnameBuffer, 0, size);
2718 /* Initialize st_clienthostname pointers. */
2719 buffer = BackendClientHostnameBuffer;
2720 for (i = 0; i < NumBackendStatSlots; i++)
2722 BackendStatusArray[i].st_clienthostname = buffer;
2723 buffer += NAMEDATALEN;
2727 /* Create or attach to the shared activity buffer */
2728 BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
2729 NumBackendStatSlots);
2730 BackendActivityBuffer = (char *)
2731 ShmemInitStruct("Backend Activity Buffer",
2732 BackendActivityBufferSize,
2737 MemSet(BackendActivityBuffer, 0, BackendActivityBufferSize);
2739 /* Initialize st_activity pointers. */
2740 buffer = BackendActivityBuffer;
2741 for (i = 0; i < NumBackendStatSlots; i++)
2743 BackendStatusArray[i].st_activity_raw = buffer;
2744 buffer += pgstat_track_activity_query_size;
2749 /* Create or attach to the shared SSL status buffer */
2750 size = mul_size(sizeof(PgBackendSSLStatus), NumBackendStatSlots);
2751 BackendSslStatusBuffer = (PgBackendSSLStatus *)
2752 ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2756 PgBackendSSLStatus *ptr;
2758 MemSet(BackendSslStatusBuffer, 0, size);
2760 /* Initialize st_sslstatus pointers. */
2761 ptr = BackendSslStatusBuffer;
2762 for (i = 0; i < NumBackendStatSlots; i++)
2764 BackendStatusArray[i].st_sslstatus = ptr;
2773 * pgstat_initialize() -
2775 * Initialize pgstats state, and set up our on-proc-exit hook.
2776 * Called from InitPostgres and AuxiliaryProcessMain. For auxiliary process,
2777 * MyBackendId is invalid. Otherwise, MyBackendId must be set,
2778 * but we must not have started any transaction yet (since the
2779 * exit hook must run after the last transaction exit).
2780 * NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
2784 pgstat_initialize(void)
2786 /* Initialize MyBEEntry */
2787 if (MyBackendId != InvalidBackendId)
2789 Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2790 MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2794 /* Must be an auxiliary process */
2795 Assert(MyAuxProcType != NotAnAuxProcess);
2798 * Assign the MyBEEntry for an auxiliary process. Since it doesn't
2799 * have a BackendId, the slot is statically allocated based on the
2800 * auxiliary process type (MyAuxProcType). Backends use slots indexed
2801 * in the range from 1 to MaxBackends (inclusive), so we use
2802 * MaxBackends + AuxBackendType + 1 as the index of the slot for an
2803 * auxiliary process.
2805 MyBEEntry = &BackendStatusArray[MaxBackends + MyAuxProcType];
2808 /* Set up a process-exit hook to clean up */
2809 on_shmem_exit(pgstat_beshutdown_hook, 0);
2813 * pgstat_bestart() -
2815 * Initialize this backend's entry in the PgBackendStatus array.
2816 * Called from InitPostgres.
2818 * Apart from auxiliary processes, MyBackendId, MyDatabaseId,
2819 * session userid, and application_name must be set for a
2820 * backend (hence, this cannot be combined with pgstat_initialize).
2824 pgstat_bestart(void)
2826 SockAddr clientaddr;
2827 volatile PgBackendStatus *beentry;
2830 * To minimize the time spent modifying the PgBackendStatus entry, fetch
2831 * all the needed data first.
2835 * We may not have a MyProcPort (eg, if this is the autovacuum process).
2836 * If so, use all-zeroes client address, which is dealt with specially in
2837 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2840 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2842 MemSet(&clientaddr, 0, sizeof(clientaddr));
2845 * Initialize my status entry, following the protocol of bumping
2846 * st_changecount before and after; and make sure it's even afterwards. We
2847 * use a volatile pointer here to ensure the compiler doesn't try to get
2850 beentry = MyBEEntry;
2852 /* pgstats state must be initialized from pgstat_initialize() */
2853 Assert(beentry != NULL);
2855 if (MyBackendId != InvalidBackendId)
2857 if (IsAutoVacuumLauncherProcess())
2859 /* Autovacuum Launcher */
2860 beentry->st_backendType = B_AUTOVAC_LAUNCHER;
2862 else if (IsAutoVacuumWorkerProcess())
2864 /* Autovacuum Worker */
2865 beentry->st_backendType = B_AUTOVAC_WORKER;
2867 else if (am_walsender)
2870 beentry->st_backendType = B_WAL_SENDER;
2872 else if (IsBackgroundWorker)
2875 beentry->st_backendType = B_BG_WORKER;
2879 /* client-backend */
2880 beentry->st_backendType = B_BACKEND;
2885 /* Must be an auxiliary process */
2886 Assert(MyAuxProcType != NotAnAuxProcess);
2887 switch (MyAuxProcType)
2889 case StartupProcess:
2890 beentry->st_backendType = B_STARTUP;
2892 case BgWriterProcess:
2893 beentry->st_backendType = B_BG_WRITER;
2895 case CheckpointerProcess:
2896 beentry->st_backendType = B_CHECKPOINTER;
2898 case WalWriterProcess:
2899 beentry->st_backendType = B_WAL_WRITER;
2901 case WalReceiverProcess:
2902 beentry->st_backendType = B_WAL_RECEIVER;
2905 elog(FATAL, "unrecognized process type: %d",
2906 (int) MyAuxProcType);
2913 pgstat_increment_changecount_before(beentry);
2914 } while ((beentry->st_changecount & 1) == 0);
2916 beentry->st_procpid = MyProcPid;
2917 beentry->st_proc_start_timestamp = MyStartTimestamp;
2918 beentry->st_activity_start_timestamp = 0;
2919 beentry->st_state_start_timestamp = 0;
2920 beentry->st_xact_start_timestamp = 0;
2921 beentry->st_databaseid = MyDatabaseId;
2923 /* We have userid for client-backends, wal-sender and bgworker processes */
2924 if (beentry->st_backendType == B_BACKEND
2925 || beentry->st_backendType == B_WAL_SENDER
2926 || beentry->st_backendType == B_BG_WORKER)
2927 beentry->st_userid = GetSessionUserId();
2929 beentry->st_userid = InvalidOid;
2931 beentry->st_clientaddr = clientaddr;
2932 if (MyProcPort && MyProcPort->remote_hostname)
2933 strlcpy(beentry->st_clienthostname, MyProcPort->remote_hostname,
2936 beentry->st_clienthostname[0] = '\0';
2938 if (MyProcPort && MyProcPort->ssl != NULL)
2940 beentry->st_ssl = true;
2941 beentry->st_sslstatus->ssl_bits = be_tls_get_cipher_bits(MyProcPort);
2942 beentry->st_sslstatus->ssl_compression = be_tls_get_compression(MyProcPort);
2943 strlcpy(beentry->st_sslstatus->ssl_version, be_tls_get_version(MyProcPort), NAMEDATALEN);
2944 strlcpy(beentry->st_sslstatus->ssl_cipher, be_tls_get_cipher(MyProcPort), NAMEDATALEN);
2945 be_tls_get_peer_subject_name(MyProcPort, beentry->st_sslstatus->ssl_client_dn, NAMEDATALEN);
2946 be_tls_get_peer_serial(MyProcPort, beentry->st_sslstatus->ssl_client_serial, NAMEDATALEN);
2947 be_tls_get_peer_issuer_name(MyProcPort, beentry->st_sslstatus->ssl_issuer_dn, NAMEDATALEN);
2951 beentry->st_ssl = false;
2954 beentry->st_ssl = false;
2956 beentry->st_state = STATE_UNDEFINED;
2957 beentry->st_appname[0] = '\0';
2958 beentry->st_activity_raw[0] = '\0';
2959 /* Also make sure the last byte in each string area is always 0 */
2960 beentry->st_clienthostname[NAMEDATALEN - 1] = '\0';
2961 beentry->st_appname[NAMEDATALEN - 1] = '\0';
2962 beentry->st_activity_raw[pgstat_track_activity_query_size - 1] = '\0';
2963 beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
2964 beentry->st_progress_command_target = InvalidOid;
2967 * we don't zero st_progress_param here to save cycles; nobody should
2968 * examine it until st_progress_command has been set to something other
2969 * than PROGRESS_COMMAND_INVALID
2972 pgstat_increment_changecount_after(beentry);
2974 /* Update app name to current GUC setting */
2975 if (application_name)
2976 pgstat_report_appname(application_name);
2980 * Shut down a single backend's statistics reporting at process exit.
2982 * Flush any remaining statistics counts out to the collector.
2983 * Without this, operations triggered during backend exit (such as
2984 * temp table deletions) won't be counted.
2986 * Lastly, clear out our entry in the PgBackendStatus array.
2989 pgstat_beshutdown_hook(int code, Datum arg)
2991 volatile PgBackendStatus *beentry = MyBEEntry;
2994 * If we got as far as discovering our own database ID, we can report what
2995 * we did to the collector. Otherwise, we'd be sending an invalid
2996 * database ID, so forget it. (This means that accesses to pg_database
2997 * during failed backend starts might never get counted.)
2999 if (OidIsValid(MyDatabaseId))
3000 pgstat_report_stat(true);
3003 * Clear my status entry, following the protocol of bumping st_changecount
3004 * before and after. We use a volatile pointer here to ensure the
3005 * compiler doesn't try to get cute.
3007 pgstat_increment_changecount_before(beentry);
3009 beentry->st_procpid = 0; /* mark invalid */
3011 pgstat_increment_changecount_after(beentry);
3016 * pgstat_report_activity() -
3018 * Called from tcop/postgres.c to report what the backend is actually doing
3019 * (but note cmd_str can be NULL for certain cases).
3021 * All updates of the status entry follow the protocol of bumping
3022 * st_changecount before and after. We use a volatile pointer here to
3023 * ensure the compiler doesn't try to get cute.
3027 pgstat_report_activity(BackendState state, const char *cmd_str)
3029 volatile PgBackendStatus *beentry = MyBEEntry;
3030 TimestampTz start_timestamp;
3031 TimestampTz current_timestamp;
3034 TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
3039 if (!pgstat_track_activities)
3041 if (beentry->st_state != STATE_DISABLED)
3043 volatile PGPROC *proc = MyProc;
3046 * track_activities is disabled, but we last reported a
3047 * non-disabled state. As our final update, change the state and
3048 * clear fields we will not be updating anymore.
3050 pgstat_increment_changecount_before(beentry);
3051 beentry->st_state = STATE_DISABLED;
3052 beentry->st_state_start_timestamp = 0;
3053 beentry->st_activity_raw[0] = '\0';
3054 beentry->st_activity_start_timestamp = 0;
3055 /* st_xact_start_timestamp and wait_event_info are also disabled */
3056 beentry->st_xact_start_timestamp = 0;
3057 proc->wait_event_info = 0;
3058 pgstat_increment_changecount_after(beentry);
3064 * To minimize the time spent modifying the entry, fetch all the needed
3067 start_timestamp = GetCurrentStatementStartTimestamp();
3068 if (cmd_str != NULL)
3071 * Compute length of to-be-stored string unaware of multi-byte
3072 * characters. For speed reasons that'll get corrected on read, rather
3073 * than computed every write.
3075 len = Min(strlen(cmd_str), pgstat_track_activity_query_size - 1);
3077 current_timestamp = GetCurrentTimestamp();
3080 * Now update the status entry
3082 pgstat_increment_changecount_before(beentry);
3084 beentry->st_state = state;
3085 beentry->st_state_start_timestamp = current_timestamp;
3087 if (cmd_str != NULL)
3089 memcpy((char *) beentry->st_activity_raw, cmd_str, len);
3090 beentry->st_activity_raw[len] = '\0';
3091 beentry->st_activity_start_timestamp = start_timestamp;
3094 pgstat_increment_changecount_after(beentry);
3098 * pgstat_progress_start_command() -
3100 * Set st_progress_command (and st_progress_command_target) in own backend
3101 * entry. Also, zero-initialize st_progress_param array.
3105 pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
3107 volatile PgBackendStatus *beentry = MyBEEntry;
3109 if (!beentry || !pgstat_track_activities)
3112 pgstat_increment_changecount_before(beentry);
3113 beentry->st_progress_command = cmdtype;
3114 beentry->st_progress_command_target = relid;
3115 MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
3116 pgstat_increment_changecount_after(beentry);
3120 * pgstat_progress_update_param() -
3122 * Update index'th member in st_progress_param[] of own backend entry.
3126 pgstat_progress_update_param(int index, int64 val)
3128 volatile PgBackendStatus *beentry = MyBEEntry;
3130 Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
3132 if (!beentry || !pgstat_track_activities)
3135 pgstat_increment_changecount_before(beentry);
3136 beentry->st_progress_param[index] = val;
3137 pgstat_increment_changecount_after(beentry);
3141 * pgstat_progress_update_multi_param() -
3143 * Update multiple members in st_progress_param[] of own backend entry.
3144 * This is atomic; readers won't see intermediate states.
3148 pgstat_progress_update_multi_param(int nparam, const int *index,
3151 volatile PgBackendStatus *beentry = MyBEEntry;
3154 if (!beentry || !pgstat_track_activities || nparam == 0)
3157 pgstat_increment_changecount_before(beentry);
3159 for (i = 0; i < nparam; ++i)
3161 Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3163 beentry->st_progress_param[index[i]] = val[i];
3166 pgstat_increment_changecount_after(beentry);
3170 * pgstat_progress_end_command() -
3172 * Reset st_progress_command (and st_progress_command_target) in own backend
3173 * entry. This signals the end of the command.
3177 pgstat_progress_end_command(void)
3179 volatile PgBackendStatus *beentry = MyBEEntry;
3183 if (!pgstat_track_activities
3184 && beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
3187 pgstat_increment_changecount_before(beentry);
3188 beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
3189 beentry->st_progress_command_target = InvalidOid;
3190 pgstat_increment_changecount_after(beentry);
3194 * pgstat_report_appname() -
3196 * Called to update our application name.
3200 pgstat_report_appname(const char *appname)
3202 volatile PgBackendStatus *beentry = MyBEEntry;
3208 /* This should be unnecessary if GUC did its job, but be safe */
3209 len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
3212 * Update my status entry, following the protocol of bumping
3213 * st_changecount before and after. We use a volatile pointer here to
3214 * ensure the compiler doesn't try to get cute.
3216 pgstat_increment_changecount_before(beentry);
3218 memcpy((char *) beentry->st_appname, appname, len);
3219 beentry->st_appname[len] = '\0';
3221 pgstat_increment_changecount_after(beentry);
3225 * Report current transaction start timestamp as the specified value.
3226 * Zero means there is no active transaction.
3229 pgstat_report_xact_timestamp(TimestampTz tstamp)
3231 volatile PgBackendStatus *beentry = MyBEEntry;
3233 if (!pgstat_track_activities || !beentry)
3237 * Update my status entry, following the protocol of bumping
3238 * st_changecount before and after. We use a volatile pointer here to
3239 * ensure the compiler doesn't try to get cute.
3241 pgstat_increment_changecount_before(beentry);
3242 beentry->st_xact_start_timestamp = tstamp;
3243 pgstat_increment_changecount_after(beentry);
3247 * pgstat_read_current_status() -
3249 * Copy the current contents of the PgBackendStatus array to local memory,
3250 * if not already done in this transaction.
3254 pgstat_read_current_status(void)
3256 volatile PgBackendStatus *beentry;
3257 LocalPgBackendStatus *localtable;
3258 LocalPgBackendStatus *localentry;
3260 *localclienthostname,
3263 PgBackendSSLStatus *localsslstatus;
3267 Assert(!pgStatRunningInCollector);
3268 if (localBackendStatusTable)
3269 return; /* already done */
3271 pgstat_setup_memcxt();
3273 localtable = (LocalPgBackendStatus *)
3274 MemoryContextAlloc(pgStatLocalContext,
3275 sizeof(LocalPgBackendStatus) * NumBackendStatSlots);
3276 localappname = (char *)
3277 MemoryContextAlloc(pgStatLocalContext,
3278 NAMEDATALEN * NumBackendStatSlots);
3279 localclienthostname = (char *)
3280 MemoryContextAlloc(pgStatLocalContext,
3281 NAMEDATALEN * NumBackendStatSlots);
3282 localactivity = (char *)
3283 MemoryContextAlloc(pgStatLocalContext,
3284 pgstat_track_activity_query_size * NumBackendStatSlots);
3286 localsslstatus = (PgBackendSSLStatus *)
3287 MemoryContextAlloc(pgStatLocalContext,
3288 sizeof(PgBackendSSLStatus) * NumBackendStatSlots);
3291 localNumBackends = 0;
3293 beentry = BackendStatusArray;
3294 localentry = localtable;
3295 for (i = 1; i <= NumBackendStatSlots; i++)
3298 * Follow the protocol of retrying if st_changecount changes while we
3299 * copy the entry, or if it's odd. (The check for odd is needed to
3300 * cover the case where we are able to completely copy the entry while
3301 * the source backend is between increment steps.) We use a volatile
3302 * pointer here to ensure the compiler doesn't try to get cute.
3306 int before_changecount;
3307 int after_changecount;
3309 pgstat_save_changecount_before(beentry, before_changecount);
3311 localentry->backendStatus.st_procpid = beentry->st_procpid;
3312 if (localentry->backendStatus.st_procpid > 0)
3314 memcpy(&localentry->backendStatus, unvolatize(PgBackendStatus *, beentry), sizeof(PgBackendStatus));
3317 * strcpy is safe even if the string is modified concurrently,
3318 * because there's always a \0 at the end of the buffer.
3320 strcpy(localappname, (char *) beentry->st_appname);
3321 localentry->backendStatus.st_appname = localappname;
3322 strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3323 localentry->backendStatus.st_clienthostname = localclienthostname;
3324 strcpy(localactivity, (char *) beentry->st_activity_raw);
3325 localentry->backendStatus.st_activity_raw = localactivity;
3326 localentry->backendStatus.st_ssl = beentry->st_ssl;
3328 if (beentry->st_ssl)
3330 memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3331 localentry->backendStatus.st_sslstatus = localsslstatus;
3336 pgstat_save_changecount_after(beentry, after_changecount);
3337 if (before_changecount == after_changecount &&
3338 (before_changecount & 1) == 0)
3341 /* Make sure we can break out of loop if stuck... */
3342 CHECK_FOR_INTERRUPTS();
3346 /* Only valid entries get included into the local array */
3347 if (localentry->backendStatus.st_procpid > 0)
3349 BackendIdGetTransactionIds(i,
3350 &localentry->backend_xid,
3351 &localentry->backend_xmin);
3354 localappname += NAMEDATALEN;
3355 localclienthostname += NAMEDATALEN;
3356 localactivity += pgstat_track_activity_query_size;
3364 /* Set the pointer only after completion of a valid table */
3365 localBackendStatusTable = localtable;
3369 * pgstat_get_wait_event_type() -
3371 * Return a string representing the current wait event type, backend is
3375 pgstat_get_wait_event_type(uint32 wait_event_info)
3378 const char *event_type;
3380 /* report process as not waiting. */
3381 if (wait_event_info == 0)
3384 classId = wait_event_info & 0xFF000000;
3388 case PG_WAIT_LWLOCK:
3389 event_type = "LWLock";
3392 event_type = "Lock";
3394 case PG_WAIT_BUFFER_PIN:
3395 event_type = "BufferPin";
3397 case PG_WAIT_ACTIVITY:
3398 event_type = "Activity";
3400 case PG_WAIT_CLIENT:
3401 event_type = "Client";
3403 case PG_WAIT_EXTENSION:
3404 event_type = "Extension";
3409 case PG_WAIT_TIMEOUT:
3410 event_type = "Timeout";
3424 * pgstat_get_wait_event() -
3426 * Return a string representing the current wait event, backend is
3430 pgstat_get_wait_event(uint32 wait_event_info)
3434 const char *event_name;
3436 /* report process as not waiting. */
3437 if (wait_event_info == 0)
3440 classId = wait_event_info & 0xFF000000;
3441 eventId = wait_event_info & 0x0000FFFF;
3445 case PG_WAIT_LWLOCK:
3446 event_name = GetLWLockIdentifier(classId, eventId);
3449 event_name = GetLockNameFromTagType(eventId);
3451 case PG_WAIT_BUFFER_PIN:
3452 event_name = "BufferPin";
3454 case PG_WAIT_ACTIVITY:
3456 WaitEventActivity w = (WaitEventActivity) wait_event_info;
3458 event_name = pgstat_get_wait_activity(w);
3461 case PG_WAIT_CLIENT:
3463 WaitEventClient w = (WaitEventClient) wait_event_info;
3465 event_name = pgstat_get_wait_client(w);
3468 case PG_WAIT_EXTENSION:
3469 event_name = "Extension";
3473 WaitEventIPC w = (WaitEventIPC) wait_event_info;
3475 event_name = pgstat_get_wait_ipc(w);
3478 case PG_WAIT_TIMEOUT:
3480 WaitEventTimeout w = (WaitEventTimeout) wait_event_info;
3482 event_name = pgstat_get_wait_timeout(w);
3487 WaitEventIO w = (WaitEventIO) wait_event_info;
3489 event_name = pgstat_get_wait_io(w);
3493 event_name = "unknown wait event";
3501 * pgstat_get_wait_activity() -
3503 * Convert WaitEventActivity to string.
3507 pgstat_get_wait_activity(WaitEventActivity w)
3509 const char *event_name = "unknown wait event";
3513 case WAIT_EVENT_ARCHIVER_MAIN:
3514 event_name = "ArchiverMain";
3516 case WAIT_EVENT_AUTOVACUUM_MAIN:
3517 event_name = "AutoVacuumMain";
3519 case WAIT_EVENT_BGWRITER_HIBERNATE:
3520 event_name = "BgWriterHibernate";
3522 case WAIT_EVENT_BGWRITER_MAIN:
3523 event_name = "BgWriterMain";
3525 case WAIT_EVENT_CHECKPOINTER_MAIN:
3526 event_name = "CheckpointerMain";
3528 case WAIT_EVENT_LOGICAL_APPLY_MAIN:
3529 event_name = "LogicalApplyMain";
3531 case WAIT_EVENT_LOGICAL_LAUNCHER_MAIN:
3532 event_name = "LogicalLauncherMain";
3534 case WAIT_EVENT_PGSTAT_MAIN:
3535 event_name = "PgStatMain";
3537 case WAIT_EVENT_RECOVERY_WAL_ALL:
3538 event_name = "RecoveryWalAll";
3540 case WAIT_EVENT_RECOVERY_WAL_STREAM:
3541 event_name = "RecoveryWalStream";
3543 case WAIT_EVENT_SYSLOGGER_MAIN:
3544 event_name = "SysLoggerMain";
3546 case WAIT_EVENT_WAL_RECEIVER_MAIN:
3547 event_name = "WalReceiverMain";
3549 case WAIT_EVENT_WAL_SENDER_MAIN:
3550 event_name = "WalSenderMain";
3552 case WAIT_EVENT_WAL_WRITER_MAIN:
3553 event_name = "WalWriterMain";
3555 /* no default case, so that compiler will warn */
3562 * pgstat_get_wait_client() -
3564 * Convert WaitEventClient to string.
3568 pgstat_get_wait_client(WaitEventClient w)
3570 const char *event_name = "unknown wait event";
3574 case WAIT_EVENT_CLIENT_READ:
3575 event_name = "ClientRead";
3577 case WAIT_EVENT_CLIENT_WRITE:
3578 event_name = "ClientWrite";
3580 case WAIT_EVENT_LIBPQWALRECEIVER_CONNECT:
3581 event_name = "LibPQWalReceiverConnect";
3583 case WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE:
3584 event_name = "LibPQWalReceiverReceive";
3586 case WAIT_EVENT_SSL_OPEN_SERVER:
3587 event_name = "SSLOpenServer";
3589 case WAIT_EVENT_WAL_RECEIVER_WAIT_START:
3590 event_name = "WalReceiverWaitStart";
3592 case WAIT_EVENT_WAL_SENDER_WAIT_WAL:
3593 event_name = "WalSenderWaitForWAL";
3595 case WAIT_EVENT_WAL_SENDER_WRITE_DATA:
3596 event_name = "WalSenderWriteData";
3598 /* no default case, so that compiler will warn */
3605 * pgstat_get_wait_ipc() -
3607 * Convert WaitEventIPC to string.
3611 pgstat_get_wait_ipc(WaitEventIPC w)
3613 const char *event_name = "unknown wait event";
3617 case WAIT_EVENT_BGWORKER_SHUTDOWN:
3618 event_name = "BgWorkerShutdown";
3620 case WAIT_EVENT_BGWORKER_STARTUP:
3621 event_name = "BgWorkerStartup";
3623 case WAIT_EVENT_BTREE_PAGE:
3624 event_name = "BtreePage";
3626 case WAIT_EVENT_CHECKPOINT_DONE:
3627 event_name = "CheckpointDone";
3629 case WAIT_EVENT_CHECKPOINT_START:
3630 event_name = "CheckpointStart";
3632 case WAIT_EVENT_CLOG_GROUP_UPDATE:
3633 event_name = "ClogGroupUpdate";
3635 case WAIT_EVENT_EXECUTE_GATHER:
3636 event_name = "ExecuteGather";
3638 case WAIT_EVENT_HASH_BATCH_ALLOCATING:
3639 event_name = "Hash/Batch/Allocating";
3641 case WAIT_EVENT_HASH_BATCH_ELECTING:
3642 event_name = "Hash/Batch/Electing";
3644 case WAIT_EVENT_HASH_BATCH_LOADING:
3645 event_name = "Hash/Batch/Loading";
3647 case WAIT_EVENT_HASH_BUILD_ALLOCATING:
3648 event_name = "Hash/Build/Allocating";
3650 case WAIT_EVENT_HASH_BUILD_ELECTING:
3651 event_name = "Hash/Build/Electing";
3653 case WAIT_EVENT_HASH_BUILD_HASHING_INNER:
3654 event_name = "Hash/Build/HashingInner";
3656 case WAIT_EVENT_HASH_BUILD_HASHING_OUTER:
3657 event_name = "Hash/Build/HashingOuter";
3659 case WAIT_EVENT_HASH_GROW_BATCHES_ALLOCATING:
3660 event_name = "Hash/GrowBatches/Allocating";
3662 case WAIT_EVENT_HASH_GROW_BATCHES_DECIDING:
3663 event_name = "Hash/GrowBatches/Deciding";
3665 case WAIT_EVENT_HASH_GROW_BATCHES_ELECTING:
3666 event_name = "Hash/GrowBatches/Electing";
3668 case WAIT_EVENT_HASH_GROW_BATCHES_FINISHING:
3669 event_name = "Hash/GrowBatches/Finishing";
3671 case WAIT_EVENT_HASH_GROW_BATCHES_REPARTITIONING:
3672 event_name = "Hash/GrowBatches/Repartitioning";
3674 case WAIT_EVENT_HASH_GROW_BUCKETS_ALLOCATING:
3675 event_name = "Hash/GrowBuckets/Allocating";
3677 case WAIT_EVENT_HASH_GROW_BUCKETS_ELECTING:
3678 event_name = "Hash/GrowBuckets/Electing";
3680 case WAIT_EVENT_HASH_GROW_BUCKETS_REINSERTING:
3681 event_name = "Hash/GrowBuckets/Reinserting";
3683 case WAIT_EVENT_LOGICAL_SYNC_DATA:
3684 event_name = "LogicalSyncData";
3686 case WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE:
3687 event_name = "LogicalSyncStateChange";
3689 case WAIT_EVENT_MQ_INTERNAL:
3690 event_name = "MessageQueueInternal";
3692 case WAIT_EVENT_MQ_PUT_MESSAGE:
3693 event_name = "MessageQueuePutMessage";
3695 case WAIT_EVENT_MQ_RECEIVE:
3696 event_name = "MessageQueueReceive";
3698 case WAIT_EVENT_MQ_SEND:
3699 event_name = "MessageQueueSend";
3701 case WAIT_EVENT_PARALLEL_BITMAP_SCAN:
3702 event_name = "ParallelBitmapScan";
3704 case WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN:
3705 event_name = "ParallelCreateIndexScan";
3707 case WAIT_EVENT_PARALLEL_FINISH:
3708 event_name = "ParallelFinish";
3710 case WAIT_EVENT_PROCARRAY_GROUP_UPDATE:
3711 event_name = "ProcArrayGroupUpdate";
3713 case WAIT_EVENT_PROMOTE:
3714 event_name = "Promote";
3716 case WAIT_EVENT_REPLICATION_ORIGIN_DROP:
3717 event_name = "ReplicationOriginDrop";
3719 case WAIT_EVENT_REPLICATION_SLOT_DROP:
3720 event_name = "ReplicationSlotDrop";
3722 case WAIT_EVENT_SAFE_SNAPSHOT:
3723 event_name = "SafeSnapshot";
3725 case WAIT_EVENT_SYNC_REP:
3726 event_name = "SyncRep";
3728 /* no default case, so that compiler will warn */
3735 * pgstat_get_wait_timeout() -
3737 * Convert WaitEventTimeout to string.
3741 pgstat_get_wait_timeout(WaitEventTimeout w)
3743 const char *event_name = "unknown wait event";
3747 case WAIT_EVENT_BASE_BACKUP_THROTTLE:
3748 event_name = "BaseBackupThrottle";
3750 case WAIT_EVENT_PG_SLEEP:
3751 event_name = "PgSleep";
3753 case WAIT_EVENT_RECOVERY_APPLY_DELAY:
3754 event_name = "RecoveryApplyDelay";
3756 /* no default case, so that compiler will warn */
3763 * pgstat_get_wait_io() -
3765 * Convert WaitEventIO to string.
3769 pgstat_get_wait_io(WaitEventIO w)
3771 const char *event_name = "unknown wait event";
3775 case WAIT_EVENT_BUFFILE_READ:
3776 event_name = "BufFileRead";
3778 case WAIT_EVENT_BUFFILE_WRITE:
3779 event_name = "BufFileWrite";
3781 case WAIT_EVENT_CONTROL_FILE_READ:
3782 event_name = "ControlFileRead";
3784 case WAIT_EVENT_CONTROL_FILE_SYNC:
3785 event_name = "ControlFileSync";
3787 case WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE:
3788 event_name = "ControlFileSyncUpdate";
3790 case WAIT_EVENT_CONTROL_FILE_WRITE:
3791 event_name = "ControlFileWrite";
3793 case WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE:
3794 event_name = "ControlFileWriteUpdate";
3796 case WAIT_EVENT_COPY_FILE_READ:
3797 event_name = "CopyFileRead";
3799 case WAIT_EVENT_COPY_FILE_WRITE:
3800 event_name = "CopyFileWrite";
3802 case WAIT_EVENT_DATA_FILE_EXTEND:
3803 event_name = "DataFileExtend";
3805 case WAIT_EVENT_DATA_FILE_FLUSH:
3806 event_name = "DataFileFlush";
3808 case WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC:
3809 event_name = "DataFileImmediateSync";
3811 case WAIT_EVENT_DATA_FILE_PREFETCH:
3812 event_name = "DataFilePrefetch";
3814 case WAIT_EVENT_DATA_FILE_READ:
3815 event_name = "DataFileRead";
3817 case WAIT_EVENT_DATA_FILE_SYNC:
3818 event_name = "DataFileSync";
3820 case WAIT_EVENT_DATA_FILE_TRUNCATE:
3821 event_name = "DataFileTruncate";
3823 case WAIT_EVENT_DATA_FILE_WRITE:
3824 event_name = "DataFileWrite";
3826 case WAIT_EVENT_DSM_FILL_ZERO_WRITE:
3827 event_name = "DSMFillZeroWrite";
3829 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ:
3830 event_name = "LockFileAddToDataDirRead";
3832 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC:
3833 event_name = "LockFileAddToDataDirSync";
3835 case WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE:
3836 event_name = "LockFileAddToDataDirWrite";
3838 case WAIT_EVENT_LOCK_FILE_CREATE_READ:
3839 event_name = "LockFileCreateRead";
3841 case WAIT_EVENT_LOCK_FILE_CREATE_SYNC:
3842 event_name = "LockFileCreateSync";
3844 case WAIT_EVENT_LOCK_FILE_CREATE_WRITE:
3845 event_name = "LockFileCreateWrite";
3847 case WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ:
3848 event_name = "LockFileReCheckDataDirRead";
3850 case WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC:
3851 event_name = "LogicalRewriteCheckpointSync";
3853 case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC:
3854 event_name = "LogicalRewriteMappingSync";
3856 case WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE:
3857 event_name = "LogicalRewriteMappingWrite";
3859 case WAIT_EVENT_LOGICAL_REWRITE_SYNC:
3860 event_name = "LogicalRewriteSync";
3862 case WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE:
3863 event_name = "LogicalRewriteTruncate";
3865 case WAIT_EVENT_LOGICAL_REWRITE_WRITE:
3866 event_name = "LogicalRewriteWrite";
3868 case WAIT_EVENT_RELATION_MAP_READ:
3869 event_name = "RelationMapRead";
3871 case WAIT_EVENT_RELATION_MAP_SYNC:
3872 event_name = "RelationMapSync";
3874 case WAIT_EVENT_RELATION_MAP_WRITE:
3875 event_name = "RelationMapWrite";
3877 case WAIT_EVENT_REORDER_BUFFER_READ:
3878 event_name = "ReorderBufferRead";
3880 case WAIT_EVENT_REORDER_BUFFER_WRITE:
3881 event_name = "ReorderBufferWrite";
3883 case WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ:
3884 event_name = "ReorderLogicalMappingRead";
3886 case WAIT_EVENT_REPLICATION_SLOT_READ:
3887 event_name = "ReplicationSlotRead";
3889 case WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC:
3890 event_name = "ReplicationSlotRestoreSync";
3892 case WAIT_EVENT_REPLICATION_SLOT_SYNC:
3893 event_name = "ReplicationSlotSync";
3895 case WAIT_EVENT_REPLICATION_SLOT_WRITE:
3896 event_name = "ReplicationSlotWrite";
3898 case WAIT_EVENT_SLRU_FLUSH_SYNC:
3899 event_name = "SLRUFlushSync";
3901 case WAIT_EVENT_SLRU_READ:
3902 event_name = "SLRURead";
3904 case WAIT_EVENT_SLRU_SYNC:
3905 event_name = "SLRUSync";
3907 case WAIT_EVENT_SLRU_WRITE:
3908 event_name = "SLRUWrite";
3910 case WAIT_EVENT_SNAPBUILD_READ:
3911 event_name = "SnapbuildRead";
3913 case WAIT_EVENT_SNAPBUILD_SYNC:
3914 event_name = "SnapbuildSync";
3916 case WAIT_EVENT_SNAPBUILD_WRITE:
3917 event_name = "SnapbuildWrite";
3919 case WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC:
3920 event_name = "TimelineHistoryFileSync";
3922 case WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE:
3923 event_name = "TimelineHistoryFileWrite";
3925 case WAIT_EVENT_TIMELINE_HISTORY_READ:
3926 event_name = "TimelineHistoryRead";
3928 case WAIT_EVENT_TIMELINE_HISTORY_SYNC:
3929 event_name = "TimelineHistorySync";
3931 case WAIT_EVENT_TIMELINE_HISTORY_WRITE:
3932 event_name = "TimelineHistoryWrite";
3934 case WAIT_EVENT_TWOPHASE_FILE_READ:
3935 event_name = "TwophaseFileRead";
3937 case WAIT_EVENT_TWOPHASE_FILE_SYNC:
3938 event_name = "TwophaseFileSync";
3940 case WAIT_EVENT_TWOPHASE_FILE_WRITE:
3941 event_name = "TwophaseFileWrite";
3943 case WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ:
3944 event_name = "WALSenderTimelineHistoryRead";
3946 case WAIT_EVENT_WAL_BOOTSTRAP_SYNC:
3947 event_name = "WALBootstrapSync";
3949 case WAIT_EVENT_WAL_BOOTSTRAP_WRITE:
3950 event_name = "WALBootstrapWrite";
3952 case WAIT_EVENT_WAL_COPY_READ:
3953 event_name = "WALCopyRead";
3955 case WAIT_EVENT_WAL_COPY_SYNC:
3956 event_name = "WALCopySync";
3958 case WAIT_EVENT_WAL_COPY_WRITE:
3959 event_name = "WALCopyWrite";
3961 case WAIT_EVENT_WAL_INIT_SYNC:
3962 event_name = "WALInitSync";
3964 case WAIT_EVENT_WAL_INIT_WRITE:
3965 event_name = "WALInitWrite";
3967 case WAIT_EVENT_WAL_READ:
3968 event_name = "WALRead";
3970 case WAIT_EVENT_WAL_SYNC:
3971 event_name = "WALSync";
3973 case WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN:
3974 event_name = "WALSyncMethodAssign";
3976 case WAIT_EVENT_WAL_WRITE:
3977 event_name = "WALWrite";
3980 /* no default case, so that compiler will warn */
3988 * pgstat_get_backend_current_activity() -
3990 * Return a string representing the current activity of the backend with
3991 * the specified PID. This looks directly at the BackendStatusArray,
3992 * and so will provide current information regardless of the age of our
3993 * transaction's snapshot of the status array.
3995 * It is the caller's responsibility to invoke this only for backends whose
3996 * state is expected to remain stable while the result is in use. The
3997 * only current use is in deadlock reporting, where we can expect that
3998 * the target backend is blocked on a lock. (There are corner cases
3999 * where the target's wait could get aborted while we are looking at it,
4000 * but the very worst consequence is to return a pointer to a string
4001 * that's been changed, so we won't worry too much.)
4003 * Note: return strings for special cases match pg_stat_get_backend_activity.
4007 pgstat_get_backend_current_activity(int pid, bool checkUser)
4009 PgBackendStatus *beentry;
4012 beentry = BackendStatusArray;
4013 for (i = 1; i <= MaxBackends; i++)
4016 * Although we expect the target backend's entry to be stable, that
4017 * doesn't imply that anyone else's is. To avoid identifying the
4018 * wrong backend, while we check for a match to the desired PID we
4019 * must follow the protocol of retrying if st_changecount changes
4020 * while we examine the entry, or if it's odd. (This might be
4021 * unnecessary, since fetching or storing an int is almost certainly
4022 * atomic, but let's play it safe.) We use a volatile pointer here to
4023 * ensure the compiler doesn't try to get cute.
4025 volatile PgBackendStatus *vbeentry = beentry;
4030 int before_changecount;
4031 int after_changecount;
4033 pgstat_save_changecount_before(vbeentry, before_changecount);
4035 found = (vbeentry->st_procpid == pid);
4037 pgstat_save_changecount_after(vbeentry, after_changecount);
4039 if (before_changecount == after_changecount &&
4040 (before_changecount & 1) == 0)
4043 /* Make sure we can break out of loop if stuck... */
4044 CHECK_FOR_INTERRUPTS();
4049 /* Now it is safe to use the non-volatile pointer */
4050 if (checkUser && !superuser() && beentry->st_userid != GetUserId())
4051 return "<insufficient privilege>";
4052 else if (*(beentry->st_activity_raw) == '\0')
4053 return "<command string not enabled>";
4056 /* this'll leak a bit of memory, but that seems acceptable */
4057 return pgstat_clip_activity(beentry->st_activity_raw);
4064 /* If we get here, caller is in error ... */
4065 return "<backend information not available>";
4069 * pgstat_get_crashed_backend_activity() -
4071 * Return a string representing the current activity of the backend with
4072 * the specified PID. Like the function above, but reads shared memory with
4073 * the expectation that it may be corrupt. On success, copy the string
4074 * into the "buffer" argument and return that pointer. On failure,
4077 * This function is only intended to be used by the postmaster to report the
4078 * query that crashed a backend. In particular, no attempt is made to
4079 * follow the correct concurrency protocol when accessing the
4080 * BackendStatusArray. But that's OK, in the worst case we'll return a
4081 * corrupted message. We also must take care not to trip on ereport(ERROR).
4085 pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
4087 volatile PgBackendStatus *beentry;
4090 beentry = BackendStatusArray;
4093 * We probably shouldn't get here before shared memory has been set up,
4096 if (beentry == NULL || BackendActivityBuffer == NULL)
4099 for (i = 1; i <= MaxBackends; i++)
4101 if (beentry->st_procpid == pid)
4103 /* Read pointer just once, so it can't change after validation */
4104 const char *activity = beentry->st_activity_raw;
4105 const char *activity_last;
4108 * We mustn't access activity string before we verify that it
4109 * falls within the BackendActivityBuffer. To make sure that the
4110 * entire string including its ending is contained within the
4111 * buffer, subtract one activity length from the buffer size.
4113 activity_last = BackendActivityBuffer + BackendActivityBufferSize
4114 - pgstat_track_activity_query_size;
4116 if (activity < BackendActivityBuffer ||
4117 activity > activity_last)
4120 /* If no string available, no point in a report */
4121 if (activity[0] == '\0')
4125 * Copy only ASCII-safe characters so we don't run into encoding
4126 * problems when reporting the message; and be sure not to run off
4127 * the end of memory. As only ASCII characters are reported, it
4128 * doesn't seem necessary to perform multibyte aware clipping.
4130 ascii_safe_strlcpy(buffer, activity,
4131 Min(buflen, pgstat_track_activity_query_size));
4144 pgstat_get_backend_desc(BackendType backendType)
4146 const char *backendDesc = "unknown process type";
4148 switch (backendType)
4150 case B_AUTOVAC_LAUNCHER:
4151 backendDesc = "autovacuum launcher";
4153 case B_AUTOVAC_WORKER:
4154 backendDesc = "autovacuum worker";
4157 backendDesc = "client backend";
4160 backendDesc = "background worker";
4163 backendDesc = "background writer";
4165 case B_CHECKPOINTER:
4166 backendDesc = "checkpointer";
4169 backendDesc = "startup";
4171 case B_WAL_RECEIVER:
4172 backendDesc = "walreceiver";
4175 backendDesc = "walsender";
4178 backendDesc = "walwriter";
4185 /* ------------------------------------------------------------
4186 * Local support functions follow
4187 * ------------------------------------------------------------
4192 * pgstat_setheader() -
4194 * Set common header fields in a statistics message
4198 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
4200 hdr->m_type = mtype;
4207 * Send out one statistics message to the collector
4211 pgstat_send(void *msg, int len)
4215 if (pgStatSock == PGINVALID_SOCKET)
4218 ((PgStat_MsgHdr *) msg)->m_size = len;
4220 /* We'll retry after EINTR, but ignore all other failures */
4223 rc = send(pgStatSock, msg, len, 0);
4224 } while (rc < 0 && errno == EINTR);
4226 #ifdef USE_ASSERT_CHECKING
4227 /* In debug builds, log send failures ... */
4229 elog(LOG, "could not send to statistics collector: %m");
4234 * pgstat_send_archiver() -
4236 * Tell the collector about the WAL file that we successfully
4237 * archived or failed to archive.
4241 pgstat_send_archiver(const char *xlog, bool failed)
4243 PgStat_MsgArchiver msg;
4246 * Prepare and send the message
4248 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ARCHIVER);
4249 msg.m_failed = failed;
4250 StrNCpy(msg.m_xlog, xlog, sizeof(msg.m_xlog));
4251 msg.m_timestamp = GetCurrentTimestamp();
4252 pgstat_send(&msg, sizeof(msg));
4256 * pgstat_send_bgwriter() -
4258 * Send bgwriter statistics to the collector
4262 pgstat_send_bgwriter(void)
4264 /* We assume this initializes to zeroes */
4265 static const PgStat_MsgBgWriter all_zeroes;
4268 * This function can be called even if nothing at all has happened. In
4269 * this case, avoid sending a completely empty message to the stats
4272 if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
4276 * Prepare and send the message
4278 pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
4279 pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
4282 * Clear out the statistics buffer, so it can be re-used.
4284 MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
4289 * PgstatCollectorMain() -
4291 * Start up the statistics collector process. This is the body of the
4292 * postmaster child process.
4294 * The argc/argv parameters are valid only in EXEC_BACKEND case.
4297 NON_EXEC_STATIC void
4298 PgstatCollectorMain(int argc, char *argv[])
4305 * Ignore all signals usually bound to some action in the postmaster,
4306 * except SIGHUP and SIGQUIT. Note we don't need a SIGUSR1 handler to
4307 * support latch operations, because we only use a local latch.
4309 pqsignal(SIGHUP, pgstat_sighup_handler);
4310 pqsignal(SIGINT, SIG_IGN);
4311 pqsignal(SIGTERM, SIG_IGN);
4312 pqsignal(SIGQUIT, pgstat_exit);
4313 pqsignal(SIGALRM, SIG_IGN);
4314 pqsignal(SIGPIPE, SIG_IGN);
4315 pqsignal(SIGUSR1, SIG_IGN);
4316 pqsignal(SIGUSR2, SIG_IGN);
4317 /* Reset some signals that are accepted by postmaster but not here */
4318 pqsignal(SIGCHLD, SIG_DFL);
4319 PG_SETMASK(&UnBlockSig);
4322 * Identify myself via ps
4324 init_ps_display("stats collector", "", "", "");
4327 * Read in existing stats files or initialize the stats to zero.
4329 pgStatRunningInCollector = true;
4330 pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
4333 * Loop to process messages until we get SIGQUIT or detect ungraceful
4334 * death of our parent postmaster.
4336 * For performance reasons, we don't want to do ResetLatch/WaitLatch after
4337 * every message; instead, do that only after a recv() fails to obtain a
4338 * message. (This effectively means that if backends are sending us stuff
4339 * like mad, we won't notice postmaster death until things slack off a
4340 * bit; which seems fine.) To do that, we have an inner loop that
4341 * iterates as long as recv() succeeds. We do recognize got_SIGHUP inside
4342 * the inner loop, which means that such interrupts will get serviced but
4343 * the latch won't get cleared until next time there is a break in the
4348 /* Clear any already-pending wakeups */
4349 ResetLatch(MyLatch);
4352 * Quit if we get SIGQUIT from the postmaster.
4358 * Inner loop iterates as long as we keep getting messages, or until
4359 * need_exit becomes set.
4364 * Reload configuration if we got SIGHUP from the postmaster.
4369 ProcessConfigFile(PGC_SIGHUP);
4373 * Write the stats file(s) if a new request has arrived that is
4374 * not satisfied by existing file(s).
4376 if (pgstat_write_statsfile_needed())
4377 pgstat_write_statsfiles(false, false);
4380 * Try to receive and process a message. This will not block,
4381 * since the socket is set to non-blocking mode.
4383 * XXX On Windows, we have to force pgwin32_recv to cooperate,
4384 * despite the previous use of pg_set_noblock() on the socket.
4385 * This is extremely broken and should be fixed someday.
4388 pgwin32_noblock = 1;
4391 len = recv(pgStatSock, (char *) &msg,
4392 sizeof(PgStat_Msg), 0);
4395 pgwin32_noblock = 0;
4400 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
4401 break; /* out of inner loop */
4403 (errcode_for_socket_access(),
4404 errmsg("could not read statistics message: %m")));
4408 * We ignore messages that are smaller than our common header
4410 if (len < sizeof(PgStat_MsgHdr))
4414 * The received length must match the length in the header
4416 if (msg.msg_hdr.m_size != len)
4420 * O.K. - we accept this message. Process it.
4422 switch (msg.msg_hdr.m_type)
4424 case PGSTAT_MTYPE_DUMMY:
4427 case PGSTAT_MTYPE_INQUIRY:
4428 pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
4431 case PGSTAT_MTYPE_TABSTAT:
4432 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
4435 case PGSTAT_MTYPE_TABPURGE:
4436 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
4439 case PGSTAT_MTYPE_DROPDB:
4440 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
4443 case PGSTAT_MTYPE_RESETCOUNTER:
4444 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
4448 case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
4449 pgstat_recv_resetsharedcounter(
4450 (PgStat_MsgResetsharedcounter *) &msg,
4454 case PGSTAT_MTYPE_RESETSINGLECOUNTER:
4455 pgstat_recv_resetsinglecounter(
4456 (PgStat_MsgResetsinglecounter *) &msg,
4460 case PGSTAT_MTYPE_AUTOVAC_START:
4461 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
4464 case PGSTAT_MTYPE_VACUUM:
4465 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
4468 case PGSTAT_MTYPE_ANALYZE:
4469 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
4472 case PGSTAT_MTYPE_ARCHIVER:
4473 pgstat_recv_archiver((PgStat_MsgArchiver *) &msg, len);
4476 case PGSTAT_MTYPE_BGWRITER:
4477 pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
4480 case PGSTAT_MTYPE_FUNCSTAT:
4481 pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
4484 case PGSTAT_MTYPE_FUNCPURGE:
4485 pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
4488 case PGSTAT_MTYPE_RECOVERYCONFLICT:
4489 pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
4492 case PGSTAT_MTYPE_DEADLOCK:
4493 pgstat_recv_deadlock((PgStat_MsgDeadlock *) &msg, len);
4496 case PGSTAT_MTYPE_TEMPFILE:
4497 pgstat_recv_tempfile((PgStat_MsgTempFile *) &msg, len);
4500 case PGSTAT_MTYPE_CHECKSUMFAILURE:
4501 pgstat_recv_checksum_failure((PgStat_MsgChecksumFailure *) &msg, len);
4507 } /* end of inner message-processing loop */
4509 /* Sleep until there's something to do */
4511 wr = WaitLatchOrSocket(MyLatch,
4512 WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
4514 WAIT_EVENT_PGSTAT_MAIN);
4518 * Windows, at least in its Windows Server 2003 R2 incarnation,
4519 * sometimes loses FD_READ events. Waking up and retrying the recv()
4520 * fixes that, so don't sleep indefinitely. This is a crock of the
4521 * first water, but until somebody wants to debug exactly what's
4522 * happening there, this is the best we can do. The two-second
4523 * timeout matches our pre-9.2 behavior, and needs to be short enough
4524 * to not provoke "using stale statistics" complaints from
4525 * backend_read_statsfile.
4527 wr = WaitLatchOrSocket(MyLatch,
4528 WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
4530 2 * 1000L /* msec */ ,
4531 WAIT_EVENT_PGSTAT_MAIN);
4535 * Emergency bailout if postmaster has died. This is to avoid the
4536 * necessity for manual cleanup of all postmaster children.
4538 if (wr & WL_POSTMASTER_DEATH)
4540 } /* end of outer loop */
4543 * Save the final stats to reuse at next startup.
4545 pgstat_write_statsfiles(true, true);
4551 /* SIGQUIT signal handler for collector process */
4553 pgstat_exit(SIGNAL_ARGS)
4555 int save_errno = errno;
4563 /* SIGHUP handler for collector process */
4565 pgstat_sighup_handler(SIGNAL_ARGS)
4567 int save_errno = errno;
4576 * Subroutine to clear stats in a database entry
4578 * Tables and functions hashes are initialized to empty.
4581 reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
4585 dbentry->n_xact_commit = 0;
4586 dbentry->n_xact_rollback = 0;
4587 dbentry->n_blocks_fetched = 0;
4588 dbentry->n_blocks_hit = 0;
4589 dbentry->n_tuples_returned = 0;
4590 dbentry->n_tuples_fetched = 0;
4591 dbentry->n_tuples_inserted = 0;
4592 dbentry->n_tuples_updated = 0;
4593 dbentry->n_tuples_deleted = 0;
4594 dbentry->last_autovac_time = 0;
4595 dbentry->n_conflict_tablespace = 0;
4596 dbentry->n_conflict_lock = 0;
4597 dbentry->n_conflict_snapshot = 0;
4598 dbentry->n_conflict_bufferpin = 0;
4599 dbentry->n_conflict_startup_deadlock = 0;
4600 dbentry->n_temp_files = 0;
4601 dbentry->n_temp_bytes = 0;
4602 dbentry->n_deadlocks = 0;
4603 dbentry->n_checksum_failures = 0;
4604 dbentry->n_block_read_time = 0;
4605 dbentry->n_block_write_time = 0;
4607 dbentry->stat_reset_timestamp = GetCurrentTimestamp();
4608 dbentry->stats_timestamp = 0;
4610 memset(&hash_ctl, 0, sizeof(hash_ctl));
4611 hash_ctl.keysize = sizeof(Oid);
4612 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4613 dbentry->tables = hash_create("Per-database table",
4614 PGSTAT_TAB_HASH_SIZE,
4616 HASH_ELEM | HASH_BLOBS);
4618 hash_ctl.keysize = sizeof(Oid);
4619 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4620 dbentry->functions = hash_create("Per-database function",
4621 PGSTAT_FUNCTION_HASH_SIZE,
4623 HASH_ELEM | HASH_BLOBS);
4627 * Lookup the hash table entry for the specified database. If no hash
4628 * table entry exists, initialize it, if the create parameter is true.
4629 * Else, return NULL.
4631 static PgStat_StatDBEntry *
4632 pgstat_get_db_entry(Oid databaseid, bool create)
4634 PgStat_StatDBEntry *result;
4636 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4638 /* Lookup or create the hash table entry for this database */
4639 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
4643 if (!create && !found)
4647 * If not found, initialize the new one. This creates empty hash tables
4648 * for tables and functions, too.
4651 reset_dbentry_counters(result);
4658 * Lookup the hash table entry for the specified table. If no hash
4659 * table entry exists, initialize it, if the create parameter is true.
4660 * Else, return NULL.
4662 static PgStat_StatTabEntry *
4663 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
4665 PgStat_StatTabEntry *result;
4667 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
4669 /* Lookup or create the hash table entry for this table */
4670 result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
4674 if (!create && !found)
4677 /* If not found, initialize the new one. */
4680 result->numscans = 0;
4681 result->tuples_returned = 0;
4682 result->tuples_fetched = 0;
4683 result->tuples_inserted = 0;
4684 result->tuples_updated = 0;
4685 result->tuples_deleted = 0;
4686 result->tuples_hot_updated = 0;
4687 result->n_live_tuples = 0;
4688 result->n_dead_tuples = 0;
4689 result->changes_since_analyze = 0;
4690 result->blocks_fetched = 0;
4691 result->blocks_hit = 0;
4692 result->vacuum_timestamp = 0;
4693 result->vacuum_count = 0;
4694 result->autovac_vacuum_timestamp = 0;
4695 result->autovac_vacuum_count = 0;
4696 result->analyze_timestamp = 0;
4697 result->analyze_count = 0;
4698 result->autovac_analyze_timestamp = 0;
4699 result->autovac_analyze_count = 0;
4707 * pgstat_write_statsfiles() -
4708 * Write the global statistics file, as well as requested DB files.
4710 * 'permanent' specifies writing to the permanent files not temporary ones.
4711 * When true (happens only when the collector is shutting down), also remove
4712 * the temporary files so that backends starting up under a new postmaster
4713 * can't read old data before the new collector is ready.
4715 * When 'allDbs' is false, only the requested databases (listed in
4716 * pending_write_requests) will be written; otherwise, all databases
4721 pgstat_write_statsfiles(bool permanent, bool allDbs)
4723 HASH_SEQ_STATUS hstat;
4724 PgStat_StatDBEntry *dbentry;
4727 const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
4728 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4731 elog(DEBUG2, "writing stats file \"%s\"", statfile);
4734 * Open the statistics temp file to write out the current values.
4736 fpout = AllocateFile(tmpfile, PG_BINARY_W);
4740 (errcode_for_file_access(),
4741 errmsg("could not open temporary statistics file \"%s\": %m",
4747 * Set the timestamp of the stats file.
4749 globalStats.stats_timestamp = GetCurrentTimestamp();
4752 * Write the file header --- currently just a format ID.
4754 format_id = PGSTAT_FILE_FORMAT_ID;
4755 rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4756 (void) rc; /* we'll check for error with ferror */
4759 * Write global stats struct
4761 rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
4762 (void) rc; /* we'll check for error with ferror */
4765 * Write archiver stats struct
4767 rc = fwrite(&archiverStats, sizeof(archiverStats), 1, fpout);
4768 (void) rc; /* we'll check for error with ferror */
4771 * Walk through the database table.
4773 hash_seq_init(&hstat, pgStatDBHash);
4774 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
4777 * Write out the table and function stats for this DB into the
4778 * appropriate per-DB stat file, if required.
4780 if (allDbs || pgstat_db_requested(dbentry->databaseid))
4782 /* Make DB's timestamp consistent with the global stats */
4783 dbentry->stats_timestamp = globalStats.stats_timestamp;
4785 pgstat_write_db_statsfile(dbentry, permanent);
4789 * Write out the DB entry. We don't write the tables or functions
4790 * pointers, since they're of no use to any other process.
4793 rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
4794 (void) rc; /* we'll check for error with ferror */
4798 * No more output to be done. Close the temp file and replace the old
4799 * pgstat.stat with it. The ferror() check replaces testing for error
4800 * after each individual fputc or fwrite above.
4807 (errcode_for_file_access(),
4808 errmsg("could not write temporary statistics file \"%s\": %m",
4813 else if (FreeFile(fpout) < 0)
4816 (errcode_for_file_access(),
4817 errmsg("could not close temporary statistics file \"%s\": %m",
4821 else if (rename(tmpfile, statfile) < 0)
4824 (errcode_for_file_access(),
4825 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
4826 tmpfile, statfile)));
4831 unlink(pgstat_stat_filename);
4834 * Now throw away the list of requests. Note that requests sent after we
4835 * started the write are still waiting on the network socket.
4837 list_free(pending_write_requests);
4838 pending_write_requests = NIL;
4842 * return the filename for a DB stat file; filename is the output buffer,
4846 get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
4847 char *filename, int len)
4851 /* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4852 printed = snprintf(filename, len, "%s/db_%u.%s",
4853 permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4854 pgstat_stat_directory,
4856 tempname ? "tmp" : "stat");
4858 elog(ERROR, "overlength pgstat path");
4862 * pgstat_write_db_statsfile() -
4863 * Write the stat file for a single database.
4865 * If writing to the permanent file (happens when the collector is
4866 * shutting down only), remove the temporary file so that backends
4867 * starting up under a new postmaster can't read the old data before
4868 * the new collector is ready.
4872 pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
4874 HASH_SEQ_STATUS tstat;
4875 HASH_SEQ_STATUS fstat;
4876 PgStat_StatTabEntry *tabentry;
4877 PgStat_StatFuncEntry *funcentry;
4880 Oid dbid = dbentry->databaseid;
4882 char tmpfile[MAXPGPATH];
4883 char statfile[MAXPGPATH];
4885 get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
4886 get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
4888 elog(DEBUG2, "writing stats file \"%s\"", statfile);
4891 * Open the statistics temp file to write out the current values.
4893 fpout = AllocateFile(tmpfile, PG_BINARY_W);
4897 (errcode_for_file_access(),
4898 errmsg("could not open temporary statistics file \"%s\": %m",
4904 * Write the file header --- currently just a format ID.
4906 format_id = PGSTAT_FILE_FORMAT_ID;
4907 rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4908 (void) rc; /* we'll check for error with ferror */
4911 * Walk through the database's access stats per table.
4913 hash_seq_init(&tstat, dbentry->tables);
4914 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
4917 rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
4918 (void) rc; /* we'll check for error with ferror */
4922 * Walk through the database's function stats table.
4924 hash_seq_init(&fstat, dbentry->functions);
4925 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
4928 rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
4929 (void) rc; /* we'll check for error with ferror */
4933 * No more output to be done. Close the temp file and replace the old
4934 * pgstat.stat with it. The ferror() check replaces testing for error
4935 * after each individual fputc or fwrite above.
4942 (errcode_for_file_access(),
4943 errmsg("could not write temporary statistics file \"%s\": %m",
4948 else if (FreeFile(fpout) < 0)
4951 (errcode_for_file_access(),
4952 errmsg("could not close temporary statistics file \"%s\": %m",
4956 else if (rename(tmpfile, statfile) < 0)
4959 (errcode_for_file_access(),
4960 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
4961 tmpfile, statfile)));
4967 get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
4969 elog(DEBUG2, "removing temporary stats file \"%s\"", statfile);
4975 * pgstat_read_statsfiles() -
4977 * Reads in some existing statistics collector files and returns the
4978 * databases hash table that is the top level of the data.
4980 * If 'onlydb' is not InvalidOid, it means we only want data for that DB
4981 * plus the shared catalogs ("DB 0"). We'll still populate the DB hash
4982 * table for all databases, but we don't bother even creating table/function
4983 * hash tables for other databases.
4985 * 'permanent' specifies reading from the permanent files not temporary ones.
4986 * When true (happens only when the collector is starting up), remove the
4987 * files after reading; the in-memory status is now authoritative, and the
4988 * files would be out of date in case somebody else reads them.
4990 * If a 'deep' read is requested, table/function stats are read, otherwise
4991 * the table/function hash tables remain empty.
4995 pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
4997 PgStat_StatDBEntry *dbentry;
4998 PgStat_StatDBEntry dbbuf;
5004 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5007 * The tables will live in pgStatLocalContext.
5009 pgstat_setup_memcxt();
5012 * Create the DB hashtable
5014 memset(&hash_ctl, 0, sizeof(hash_ctl));
5015 hash_ctl.keysize = sizeof(Oid);
5016 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
5017 hash_ctl.hcxt = pgStatLocalContext;
5018 dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
5019 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5022 * Clear out global and archiver statistics so they start from zero in
5023 * case we can't load an existing statsfile.
5025 memset(&globalStats, 0, sizeof(globalStats));
5026 memset(&archiverStats, 0, sizeof(archiverStats));
5029 * Set the current timestamp (will be kept only in case we can't load an
5030 * existing statsfile).
5032 globalStats.stat_reset_timestamp = GetCurrentTimestamp();
5033 archiverStats.stat_reset_timestamp = globalStats.stat_reset_timestamp;
5036 * Try to open the stats file. If it doesn't exist, the backends simply
5037 * return zero for anything and the collector simply starts from scratch
5038 * with empty counters.
5040 * ENOENT is a possibility if the stats collector is not running or has
5041 * not yet written the stats file the first time. Any other failure
5042 * condition is suspicious.
5044 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5046 if (errno != ENOENT)
5047 ereport(pgStatRunningInCollector ? LOG : WARNING,
5048 (errcode_for_file_access(),
5049 errmsg("could not open statistics file \"%s\": %m",
5055 * Verify it's of the expected format.
5057 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5058 format_id != PGSTAT_FILE_FORMAT_ID)
5060 ereport(pgStatRunningInCollector ? LOG : WARNING,
5061 (errmsg("corrupted statistics file \"%s\"", statfile)));
5066 * Read global stats struct
5068 if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
5070 ereport(pgStatRunningInCollector ? LOG : WARNING,
5071 (errmsg("corrupted statistics file \"%s\"", statfile)));
5072 memset(&globalStats, 0, sizeof(globalStats));
5077 * In the collector, disregard the timestamp we read from the permanent
5078 * stats file; we should be willing to write a temp stats file immediately
5079 * upon the first request from any backend. This only matters if the old
5080 * file's timestamp is less than PGSTAT_STAT_INTERVAL ago, but that's not
5081 * an unusual scenario.
5083 if (pgStatRunningInCollector)
5084 globalStats.stats_timestamp = 0;
5087 * Read archiver stats struct
5089 if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
5091 ereport(pgStatRunningInCollector ? LOG : WARNING,
5092 (errmsg("corrupted statistics file \"%s\"", statfile)));
5093 memset(&archiverStats, 0, sizeof(archiverStats));
5098 * We found an existing collector stats file. Read it and put all the
5099 * hashtable entries into place.
5103 switch (fgetc(fpin))
5106 * 'D' A PgStat_StatDBEntry struct describing a database
5110 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
5111 fpin) != offsetof(PgStat_StatDBEntry, tables))
5113 ereport(pgStatRunningInCollector ? LOG : WARNING,
5114 (errmsg("corrupted statistics file \"%s\"",
5120 * Add to the DB hash
5122 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
5123 (void *) &dbbuf.databaseid,
5128 ereport(pgStatRunningInCollector ? LOG : WARNING,
5129 (errmsg("corrupted statistics file \"%s\"",
5134 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
5135 dbentry->tables = NULL;
5136 dbentry->functions = NULL;
5139 * In the collector, disregard the timestamp we read from the
5140 * permanent stats file; we should be willing to write a temp
5141 * stats file immediately upon the first request from any
5144 if (pgStatRunningInCollector)
5145 dbentry->stats_timestamp = 0;
5148 * Don't create tables/functions hashtables for uninteresting
5151 if (onlydb != InvalidOid)
5153 if (dbbuf.databaseid != onlydb &&
5154 dbbuf.databaseid != InvalidOid)
5158 memset(&hash_ctl, 0, sizeof(hash_ctl));
5159 hash_ctl.keysize = sizeof(Oid);
5160 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
5161 hash_ctl.hcxt = pgStatLocalContext;
5162 dbentry->tables = hash_create("Per-database table",
5163 PGSTAT_TAB_HASH_SIZE,
5165 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5167 hash_ctl.keysize = sizeof(Oid);
5168 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
5169 hash_ctl.hcxt = pgStatLocalContext;
5170 dbentry->functions = hash_create("Per-database function",
5171 PGSTAT_FUNCTION_HASH_SIZE,
5173 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5176 * If requested, read the data from the database-specific
5177 * file. Otherwise we just leave the hashtables empty.
5180 pgstat_read_db_statsfile(dbentry->databaseid,
5191 ereport(pgStatRunningInCollector ? LOG : WARNING,
5192 (errmsg("corrupted statistics file \"%s\"",
5201 /* If requested to read the permanent file, also get rid of it. */
5204 elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5213 * pgstat_read_db_statsfile() -
5215 * Reads in the existing statistics collector file for the given database,
5216 * filling the passed-in tables and functions hash tables.
5218 * As in pgstat_read_statsfiles, if the permanent file is requested, it is
5219 * removed after reading.
5221 * Note: this code has the ability to skip storing per-table or per-function
5222 * data, if NULL is passed for the corresponding hashtable. That's not used
5223 * at the moment though.
5227 pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
5230 PgStat_StatTabEntry *tabentry;
5231 PgStat_StatTabEntry tabbuf;
5232 PgStat_StatFuncEntry funcbuf;
5233 PgStat_StatFuncEntry *funcentry;
5237 char statfile[MAXPGPATH];
5239 get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
5242 * Try to open the stats file. If it doesn't exist, the backends simply
5243 * return zero for anything and the collector simply starts from scratch
5244 * with empty counters.
5246 * ENOENT is a possibility if the stats collector is not running or has
5247 * not yet written the stats file the first time. Any other failure
5248 * condition is suspicious.
5250 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5252 if (errno != ENOENT)
5253 ereport(pgStatRunningInCollector ? LOG : WARNING,
5254 (errcode_for_file_access(),
5255 errmsg("could not open statistics file \"%s\": %m",
5261 * Verify it's of the expected format.
5263 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5264 format_id != PGSTAT_FILE_FORMAT_ID)
5266 ereport(pgStatRunningInCollector ? LOG : WARNING,
5267 (errmsg("corrupted statistics file \"%s\"", statfile)));
5272 * We found an existing collector stats file. Read it and put all the
5273 * hashtable entries into place.
5277 switch (fgetc(fpin))
5280 * 'T' A PgStat_StatTabEntry follows.
5283 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
5284 fpin) != sizeof(PgStat_StatTabEntry))
5286 ereport(pgStatRunningInCollector ? LOG : WARNING,
5287 (errmsg("corrupted statistics file \"%s\"",
5293 * Skip if table data not wanted.
5295 if (tabhash == NULL)
5298 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
5299 (void *) &tabbuf.tableid,
5300 HASH_ENTER, &found);
5304 ereport(pgStatRunningInCollector ? LOG : WARNING,
5305 (errmsg("corrupted statistics file \"%s\"",
5310 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
5314 * 'F' A PgStat_StatFuncEntry follows.
5317 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
5318 fpin) != sizeof(PgStat_StatFuncEntry))
5320 ereport(pgStatRunningInCollector ? LOG : WARNING,
5321 (errmsg("corrupted statistics file \"%s\"",
5327 * Skip if function data not wanted.
5329 if (funchash == NULL)
5332 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
5333 (void *) &funcbuf.functionid,
5334 HASH_ENTER, &found);
5338 ereport(pgStatRunningInCollector ? LOG : WARNING,
5339 (errmsg("corrupted statistics file \"%s\"",
5344 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
5348 * 'E' The EOF marker of a complete stats file.
5354 ereport(pgStatRunningInCollector ? LOG : WARNING,
5355 (errmsg("corrupted statistics file \"%s\"",
5366 elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
5372 * pgstat_read_db_statsfile_timestamp() -
5374 * Attempt to determine the timestamp of the last db statfile write.
5375 * Returns true if successful; the timestamp is stored in *ts.
5377 * This needs to be careful about handling databases for which no stats file
5378 * exists, such as databases without a stat entry or those not yet written:
5380 * - if there's a database entry in the global file, return the corresponding
5381 * stats_timestamp value.
5383 * - if there's no db stat entry (e.g. for a new or inactive database),
5384 * there's no stats_timestamp value, but also nothing to write so we return
5385 * the timestamp of the global statfile.
5389 pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
5392 PgStat_StatDBEntry dbentry;
5393 PgStat_GlobalStats myGlobalStats;
5394 PgStat_ArchiverStats myArchiverStats;
5397 const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
5400 * Try to open the stats file. As above, anything but ENOENT is worthy of
5401 * complaining about.
5403 if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
5405 if (errno != ENOENT)
5406 ereport(pgStatRunningInCollector ? LOG : WARNING,
5407 (errcode_for_file_access(),
5408 errmsg("could not open statistics file \"%s\": %m",
5414 * Verify it's of the expected format.
5416 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
5417 format_id != PGSTAT_FILE_FORMAT_ID)
5419 ereport(pgStatRunningInCollector ? LOG : WARNING,
5420 (errmsg("corrupted statistics file \"%s\"", statfile)));
5426 * Read global stats struct
5428 if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
5429 fpin) != sizeof(myGlobalStats))
5431 ereport(pgStatRunningInCollector ? LOG : WARNING,
5432 (errmsg("corrupted statistics file \"%s\"", statfile)));
5438 * Read archiver stats struct
5440 if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
5441 fpin) != sizeof(myArchiverStats))
5443 ereport(pgStatRunningInCollector ? LOG : WARNING,
5444 (errmsg("corrupted statistics file \"%s\"", statfile)));
5449 /* By default, we're going to return the timestamp of the global file. */
5450 *ts = myGlobalStats.stats_timestamp;
5453 * We found an existing collector stats file. Read it and look for a
5454 * record for the requested database. If found, use its timestamp.
5458 switch (fgetc(fpin))
5461 * 'D' A PgStat_StatDBEntry struct describing a database
5465 if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
5466 fpin) != offsetof(PgStat_StatDBEntry, tables))
5468 ereport(pgStatRunningInCollector ? LOG : WARNING,
5469 (errmsg("corrupted statistics file \"%s\"",
5475 * If this is the DB we're looking for, save its timestamp and
5478 if (dbentry.databaseid == databaseid)
5480 *ts = dbentry.stats_timestamp;
5490 ereport(pgStatRunningInCollector ? LOG : WARNING,
5491 (errmsg("corrupted statistics file \"%s\"",
5503 * If not already done, read the statistics collector stats file into
5504 * some hash tables. The results will be kept until pgstat_clear_snapshot()
5505 * is called (typically, at end of transaction).
5508 backend_read_statsfile(void)
5510 TimestampTz min_ts = 0;
5511 TimestampTz ref_ts = 0;
5515 /* already read it? */
5518 Assert(!pgStatRunningInCollector);
5521 * In a normal backend, we check staleness of the data for our own DB, and
5522 * so we send MyDatabaseId in inquiry messages. In the autovac launcher,
5523 * check staleness of the shared-catalog data, and send InvalidOid in
5524 * inquiry messages so as not to force writing unnecessary data.
5526 if (IsAutoVacuumLauncherProcess())
5527 inquiry_db = InvalidOid;
5529 inquiry_db = MyDatabaseId;
5532 * Loop until fresh enough stats file is available or we ran out of time.
5533 * The stats inquiry message is sent repeatedly in case collector drops
5534 * it; but not every single time, as that just swamps the collector.
5536 for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
5539 TimestampTz file_ts = 0;
5542 CHECK_FOR_INTERRUPTS();
5544 ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
5546 cur_ts = GetCurrentTimestamp();
5547 /* Calculate min acceptable timestamp, if we didn't already */
5548 if (count == 0 || cur_ts < ref_ts)
5551 * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
5552 * msec before now. This indirectly ensures that the collector
5553 * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
5554 * an autovacuum worker, however, we want a lower delay to avoid
5555 * using stale data, so we use PGSTAT_RETRY_DELAY (since the
5556 * number of workers is low, this shouldn't be a problem).
5558 * We don't recompute min_ts after sleeping, except in the
5559 * unlikely case that cur_ts went backwards. So we might end up
5560 * accepting a file a bit older than PGSTAT_STAT_INTERVAL. In
5561 * practice that shouldn't happen, though, as long as the sleep
5562 * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
5563 * tell the collector that our cutoff time is less than what we'd
5567 if (IsAutoVacuumWorkerProcess())
5568 min_ts = TimestampTzPlusMilliseconds(ref_ts,
5569 -PGSTAT_RETRY_DELAY);
5571 min_ts = TimestampTzPlusMilliseconds(ref_ts,
5572 -PGSTAT_STAT_INTERVAL);
5576 * If the file timestamp is actually newer than cur_ts, we must have
5577 * had a clock glitch (system time went backwards) or there is clock
5578 * skew between our processor and the stats collector's processor.
5579 * Accept the file, but send an inquiry message anyway to make
5580 * pgstat_recv_inquiry do a sanity check on the collector's time.
5582 if (ok && file_ts > cur_ts)
5585 * A small amount of clock skew between processors isn't terribly
5586 * surprising, but a large difference is worth logging. We
5587 * arbitrarily define "large" as 1000 msec.
5589 if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
5594 /* Copy because timestamptz_to_str returns a static buffer */
5595 filetime = pstrdup(timestamptz_to_str(file_ts));
5596 mytime = pstrdup(timestamptz_to_str(cur_ts));
5597 elog(LOG, "stats collector's time %s is later than backend local time %s",
5603 pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5607 /* Normal acceptance case: file is not older than cutoff time */
5608 if (ok && file_ts >= min_ts)
5611 /* Not there or too old, so kick the collector and wait a bit */
5612 if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
5613 pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
5615 pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
5618 if (count >= PGSTAT_POLL_LOOP_COUNT)
5620 (errmsg("using stale statistics instead of current ones "
5621 "because stats collector is not responding")));
5624 * Autovacuum launcher wants stats about all databases, but a shallow read
5625 * is sufficient. Regular backends want a deep read for just the tables
5626 * they can see (MyDatabaseId + shared catalogs).
5628 if (IsAutoVacuumLauncherProcess())
5629 pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
5631 pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
5636 * pgstat_setup_memcxt() -
5638 * Create pgStatLocalContext, if not already done.
5642 pgstat_setup_memcxt(void)
5644 if (!pgStatLocalContext)
5645 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
5646 "Statistics snapshot",
5647 ALLOCSET_SMALL_SIZES);
5652 * pgstat_clear_snapshot() -
5654 * Discard any data collected in the current transaction. Any subsequent
5655 * request will cause new snapshots to be read.
5657 * This is also invoked during transaction commit or abort to discard
5658 * the no-longer-wanted snapshot.
5662 pgstat_clear_snapshot(void)
5664 /* Release memory, if any was allocated */
5665 if (pgStatLocalContext)
5666 MemoryContextDelete(pgStatLocalContext);
5668 /* Reset variables */
5669 pgStatLocalContext = NULL;
5670 pgStatDBHash = NULL;
5671 localBackendStatusTable = NULL;
5672 localNumBackends = 0;
5677 * pgstat_recv_inquiry() -
5679 * Process stat inquiry requests.
5683 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
5685 PgStat_StatDBEntry *dbentry;
5687 elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
5690 * If there's already a write request for this DB, there's nothing to do.
5692 * Note that if a request is found, we return early and skip the below
5693 * check for clock skew. This is okay, since the only way for a DB
5694 * request to be present in the list is that we have been here since the
5695 * last write round. It seems sufficient to check for clock skew once per
5698 if (list_member_oid(pending_write_requests, msg->databaseid))
5702 * Check to see if we last wrote this database at a time >= the requested
5703 * cutoff time. If so, this is a stale request that was generated before
5704 * we updated the DB file, and we don't need to do so again.
5706 * If the requestor's local clock time is older than stats_timestamp, we
5707 * should suspect a clock glitch, ie system time going backwards; though
5708 * the more likely explanation is just delayed message receipt. It is
5709 * worth expending a GetCurrentTimestamp call to be sure, since a large
5710 * retreat in the system clock reading could otherwise cause us to neglect
5711 * to update the stats file for a long time.
5713 dbentry = pgstat_get_db_entry(msg->databaseid, false);
5714 if (dbentry == NULL)
5717 * We have no data for this DB. Enter a write request anyway so that
5718 * the global stats will get updated. This is needed to prevent
5719 * backend_read_statsfile from waiting for data that we cannot supply,
5720 * in the case of a new DB that nobody has yet reported any stats for.
5721 * See the behavior of pgstat_read_db_statsfile_timestamp.
5724 else if (msg->clock_time < dbentry->stats_timestamp)
5726 TimestampTz cur_ts = GetCurrentTimestamp();
5728 if (cur_ts < dbentry->stats_timestamp)
5731 * Sure enough, time went backwards. Force a new stats file write
5732 * to get back in sync; but first, log a complaint.
5737 /* Copy because timestamptz_to_str returns a static buffer */
5738 writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
5739 mytime = pstrdup(timestamptz_to_str(cur_ts));
5741 "stats_timestamp %s is later than collector's time %s for database %u",
5742 writetime, mytime, dbentry->databaseid);
5749 * Nope, it's just an old request. Assuming msg's clock_time is
5750 * >= its cutoff_time, it must be stale, so we can ignore it.
5755 else if (msg->cutoff_time <= dbentry->stats_timestamp)
5757 /* Stale request, ignore it */
5762 * We need to write this DB, so create a request.
5764 pending_write_requests = lappend_oid(pending_write_requests,
5770 * pgstat_recv_tabstat() -
5772 * Count what the backend has done.
5776 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
5778 PgStat_StatDBEntry *dbentry;
5779 PgStat_StatTabEntry *tabentry;
5783 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5786 * Update database-wide stats.
5788 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
5789 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
5790 dbentry->n_block_read_time += msg->m_block_read_time;
5791 dbentry->n_block_write_time += msg->m_block_write_time;
5794 * Process all table entries in the message.
5796 for (i = 0; i < msg->m_nentries; i++)
5798 PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
5800 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
5801 (void *) &(tabmsg->t_id),
5802 HASH_ENTER, &found);
5807 * If it's a new table entry, initialize counters to the values we
5810 tabentry->numscans = tabmsg->t_counts.t_numscans;
5811 tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
5812 tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
5813 tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
5814 tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
5815 tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
5816 tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
5817 tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
5818 tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
5819 tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
5820 tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
5821 tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
5823 tabentry->vacuum_timestamp = 0;
5824 tabentry->vacuum_count = 0;
5825 tabentry->autovac_vacuum_timestamp = 0;
5826 tabentry->autovac_vacuum_count = 0;
5827 tabentry->analyze_timestamp = 0;
5828 tabentry->analyze_count = 0;
5829 tabentry->autovac_analyze_timestamp = 0;
5830 tabentry->autovac_analyze_count = 0;
5835 * Otherwise add the values to the existing entry.
5837 tabentry->numscans += tabmsg->t_counts.t_numscans;
5838 tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
5839 tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5840 tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5841 tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
5842 tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5843 tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
5844 /* If table was truncated, first reset the live/dead counters */
5845 if (tabmsg->t_counts.t_truncated)
5847 tabentry->n_live_tuples = 0;
5848 tabentry->n_dead_tuples = 0;
5850 tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
5851 tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
5852 tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
5853 tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5854 tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
5857 /* Clamp n_live_tuples in case of negative delta_live_tuples */
5858 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
5859 /* Likewise for n_dead_tuples */
5860 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
5863 * Add per-table stats to the per-database entry, too.
5865 dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
5866 dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5867 dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5868 dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
5869 dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5870 dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5871 dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
5877 * pgstat_recv_tabpurge() -
5879 * Arrange for dead table removal.
5883 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
5885 PgStat_StatDBEntry *dbentry;
5888 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5891 * No need to purge if we don't even know the database.
5893 if (!dbentry || !dbentry->tables)
5897 * Process all table entries in the message.
5899 for (i = 0; i < msg->m_nentries; i++)
5901 /* Remove from hashtable if present; we don't care if it's not. */
5902 (void) hash_search(dbentry->tables,
5903 (void *) &(msg->m_tableid[i]),
5910 * pgstat_recv_dropdb() -
5912 * Arrange for dead database removal
5916 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
5918 Oid dbid = msg->m_databaseid;
5919 PgStat_StatDBEntry *dbentry;
5922 * Lookup the database in the hashtable.
5924 dbentry = pgstat_get_db_entry(dbid, false);
5927 * If found, remove it (along with the db statfile).
5931 char statfile[MAXPGPATH];
5933 get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
5935 elog(DEBUG2, "removing stats file \"%s\"", statfile);
5938 if (dbentry->tables != NULL)
5939 hash_destroy(dbentry->tables);
5940 if (dbentry->functions != NULL)
5941 hash_destroy(dbentry->functions);
5943 if (hash_search(pgStatDBHash,
5945 HASH_REMOVE, NULL) == NULL)
5947 (errmsg("database hash table corrupted during cleanup --- abort")));
5953 * pgstat_recv_resetcounter() -
5955 * Reset the statistics for the specified database.
5959 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
5961 PgStat_StatDBEntry *dbentry;
5964 * Lookup the database in the hashtable. Nothing to do if not there.
5966 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5972 * We simply throw away all the database's table entries by recreating a
5973 * new hash table for them.
5975 if (dbentry->tables != NULL)
5976 hash_destroy(dbentry->tables);
5977 if (dbentry->functions != NULL)
5978 hash_destroy(dbentry->functions);
5980 dbentry->tables = NULL;
5981 dbentry->functions = NULL;
5984 * Reset database-level stats, too. This creates empty hash tables for
5985 * tables and functions.
5987 reset_dbentry_counters(dbentry);
5991 * pgstat_recv_resetshared() -
5993 * Reset some shared statistics of the cluster.
5997 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
5999 if (msg->m_resettarget == RESET_BGWRITER)
6001 /* Reset the global background writer statistics for the cluster. */
6002 memset(&globalStats, 0, sizeof(globalStats));
6003 globalStats.stat_reset_timestamp = GetCurrentTimestamp();
6005 else if (msg->m_resettarget == RESET_ARCHIVER)
6007 /* Reset the archiver statistics for the cluster. */
6008 memset(&archiverStats, 0, sizeof(archiverStats));
6009 archiverStats.stat_reset_timestamp = GetCurrentTimestamp();
6013 * Presumably the sender of this message validated the target, don't
6014 * complain here if it's not valid
6019 * pgstat_recv_resetsinglecounter() -
6021 * Reset a statistics for a single object
6025 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
6027 PgStat_StatDBEntry *dbentry;
6029 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
6034 /* Set the reset timestamp for the whole database */
6035 dbentry->stat_reset_timestamp = GetCurrentTimestamp();
6037 /* Remove object if it exists, ignore it if not */
6038 if (msg->m_resettype == RESET_TABLE)
6039 (void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
6041 else if (msg->m_resettype == RESET_FUNCTION)
6042 (void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
6047 * pgstat_recv_autovac() -
6049 * Process an autovacuum signalling message.
6053 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
6055 PgStat_StatDBEntry *dbentry;
6058 * Store the last autovacuum time in the database's hashtable entry.
6060 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6062 dbentry->last_autovac_time = msg->m_start_time;
6066 * pgstat_recv_vacuum() -
6068 * Process a VACUUM message.
6072 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
6074 PgStat_StatDBEntry *dbentry;
6075 PgStat_StatTabEntry *tabentry;
6078 * Store the data in the table's hashtable entry.
6080 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6082 tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
6084 tabentry->n_live_tuples = msg->m_live_tuples;
6085 tabentry->n_dead_tuples = msg->m_dead_tuples;
6087 if (msg->m_autovacuum)
6089 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
6090 tabentry->autovac_vacuum_count++;
6094 tabentry->vacuum_timestamp = msg->m_vacuumtime;
6095 tabentry->vacuum_count++;
6100 * pgstat_recv_analyze() -
6102 * Process an ANALYZE message.
6106 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
6108 PgStat_StatDBEntry *dbentry;
6109 PgStat_StatTabEntry *tabentry;
6112 * Store the data in the table's hashtable entry.
6114 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6116 tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
6118 tabentry->n_live_tuples = msg->m_live_tuples;
6119 tabentry->n_dead_tuples = msg->m_dead_tuples;
6122 * If commanded, reset changes_since_analyze to zero. This forgets any
6123 * changes that were committed while the ANALYZE was in progress, but we
6124 * have no good way to estimate how many of those there were.
6126 if (msg->m_resetcounter)
6127 tabentry->changes_since_analyze = 0;
6129 if (msg->m_autovacuum)
6131 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
6132 tabentry->autovac_analyze_count++;
6136 tabentry->analyze_timestamp = msg->m_analyzetime;
6137 tabentry->analyze_count++;
6143 * pgstat_recv_archiver() -
6145 * Process a ARCHIVER message.
6149 pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len)
6153 /* Failed archival attempt */
6154 ++archiverStats.failed_count;
6155 memcpy(archiverStats.last_failed_wal, msg->m_xlog,
6156 sizeof(archiverStats.last_failed_wal));
6157 archiverStats.last_failed_timestamp = msg->m_timestamp;
6161 /* Successful archival operation */
6162 ++archiverStats.archived_count;
6163 memcpy(archiverStats.last_archived_wal, msg->m_xlog,
6164 sizeof(archiverStats.last_archived_wal));
6165 archiverStats.last_archived_timestamp = msg->m_timestamp;
6170 * pgstat_recv_bgwriter() -
6172 * Process a BGWRITER message.
6176 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
6178 globalStats.timed_checkpoints += msg->m_timed_checkpoints;
6179 globalStats.requested_checkpoints += msg->m_requested_checkpoints;
6180 globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
6181 globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
6182 globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
6183 globalStats.buf_written_clean += msg->m_buf_written_clean;
6184 globalStats.maxwritten_clean += msg->m_maxwritten_clean;
6185 globalStats.buf_written_backend += msg->m_buf_written_backend;
6186 globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
6187 globalStats.buf_alloc += msg->m_buf_alloc;
6191 * pgstat_recv_recoveryconflict() -
6193 * Process a RECOVERYCONFLICT message.
6197 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
6199 PgStat_StatDBEntry *dbentry;
6201 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6203 switch (msg->m_reason)
6205 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
6208 * Since we drop the information about the database as soon as it
6209 * replicates, there is no point in counting these conflicts.
6212 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
6213 dbentry->n_conflict_tablespace++;
6215 case PROCSIG_RECOVERY_CONFLICT_LOCK:
6216 dbentry->n_conflict_lock++;
6218 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
6219 dbentry->n_conflict_snapshot++;
6221 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
6222 dbentry->n_conflict_bufferpin++;
6224 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
6225 dbentry->n_conflict_startup_deadlock++;
6231 * pgstat_recv_deadlock() -
6233 * Process a DEADLOCK message.
6237 pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
6239 PgStat_StatDBEntry *dbentry;
6241 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6243 dbentry->n_deadlocks++;
6247 * pgstat_recv_checksum_failure() -
6249 * Process a CHECKSUMFAILURE message.
6253 pgstat_recv_checksum_failure(PgStat_MsgChecksumFailure *msg, int len)
6255 PgStat_StatDBEntry *dbentry;
6257 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6259 dbentry->n_checksum_failures += msg->m_failurecount;
6263 * pgstat_recv_tempfile() -
6265 * Process a TEMPFILE message.
6269 pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
6271 PgStat_StatDBEntry *dbentry;
6273 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6275 dbentry->n_temp_bytes += msg->m_filesize;
6276 dbentry->n_temp_files += 1;
6280 * pgstat_recv_funcstat() -
6282 * Count what the backend has done.
6286 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
6288 PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
6289 PgStat_StatDBEntry *dbentry;
6290 PgStat_StatFuncEntry *funcentry;
6294 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
6297 * Process all function entries in the message.
6299 for (i = 0; i < msg->m_nentries; i++, funcmsg++)
6301 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
6302 (void *) &(funcmsg->f_id),
6303 HASH_ENTER, &found);
6308 * If it's a new function entry, initialize counters to the values
6311 funcentry->f_numcalls = funcmsg->f_numcalls;
6312 funcentry->f_total_time = funcmsg->f_total_time;
6313 funcentry->f_self_time = funcmsg->f_self_time;
6318 * Otherwise add the values to the existing entry.
6320 funcentry->f_numcalls += funcmsg->f_numcalls;
6321 funcentry->f_total_time += funcmsg->f_total_time;
6322 funcentry->f_self_time += funcmsg->f_self_time;
6328 * pgstat_recv_funcpurge() -
6330 * Arrange for dead function removal.
6334 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
6336 PgStat_StatDBEntry *dbentry;
6339 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
6342 * No need to purge if we don't even know the database.
6344 if (!dbentry || !dbentry->functions)
6348 * Process all function entries in the message.
6350 for (i = 0; i < msg->m_nentries; i++)
6352 /* Remove from hashtable if present; we don't care if it's not. */
6353 (void) hash_search(dbentry->functions,
6354 (void *) &(msg->m_functionid[i]),
6360 * pgstat_write_statsfile_needed() -
6362 * Do we need to write out any stats files?
6366 pgstat_write_statsfile_needed(void)
6368 if (pending_write_requests != NIL)
6371 /* Everything was written recently */
6376 * pgstat_db_requested() -
6378 * Checks whether stats for a particular DB need to be written to a file.
6382 pgstat_db_requested(Oid databaseid)
6385 * If any requests are outstanding at all, we should write the stats for
6386 * shared catalogs (the "database" with OID 0). This ensures that
6387 * backends will see up-to-date stats for shared catalogs, even though
6388 * they send inquiry messages mentioning only their own DB.
6390 if (databaseid == InvalidOid && pending_write_requests != NIL)
6393 /* Search to see if there's an open request to write this database. */
6394 if (list_member_oid(pending_write_requests, databaseid))
6401 * Convert a potentially unsafely truncated activity string (see
6402 * PgBackendStatus.st_activity_raw's documentation) into a correctly truncated
6405 * The returned string is allocated in the caller's memory context and may be
6409 pgstat_clip_activity(const char *raw_activity)
6416 * Some callers, like pgstat_get_backend_current_activity(), do not
6417 * guarantee that the buffer isn't concurrently modified. We try to take
6418 * care that the buffer is always terminated by a NUL byte regardless, but
6419 * let's still be paranoid about the string's length. In those cases the
6420 * underlying buffer is guaranteed to be pgstat_track_activity_query_size
6423 activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
6425 /* now double-guaranteed to be NUL terminated */
6426 rawlen = strlen(activity);
6429 * All supported server-encodings make it possible to determine the length
6430 * of a multi-byte character from its first byte (this is not the case for
6431 * client encodings, see GB18030). As st_activity is always stored using
6432 * server encoding, this allows us to perform multi-byte aware truncation,
6433 * even if the string earlier was truncated in the middle of a multi-byte
6436 cliplen = pg_mbcliplen(activity, rawlen,
6437 pgstat_track_activity_query_size - 1);
6439 activity[cliplen] = '\0';