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-2005, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.108 2005/09/24 17:53:14 tgl Exp $
23 #include <sys/param.h>
25 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
34 #include "access/heapam.h"
35 #include "access/xact.h"
36 #include "catalog/pg_database.h"
37 #include "libpq/libpq.h"
38 #include "libpq/pqsignal.h"
39 #include "mb/pg_wchar.h"
40 #include "miscadmin.h"
41 #include "postmaster/autovacuum.h"
42 #include "postmaster/fork_process.h"
43 #include "postmaster/postmaster.h"
44 #include "storage/backendid.h"
45 #include "storage/fd.h"
46 #include "storage/ipc.h"
47 #include "storage/pg_shmem.h"
48 #include "storage/pmsignal.h"
49 #include "storage/procarray.h"
50 #include "tcop/tcopprot.h"
51 #include "utils/hsearch.h"
52 #include "utils/memutils.h"
53 #include "utils/ps_status.h"
54 #include "utils/rel.h"
55 #include "utils/syscache.h"
59 * Paths for the statistics files (relative to installation's $PGDATA).
62 #define PGSTAT_STAT_FILENAME "global/pgstat.stat"
63 #define PGSTAT_STAT_TMPFILE "global/pgstat.tmp"
69 #define PGSTAT_STAT_INTERVAL 500 /* How often to write the status
70 * file; in milliseconds. */
72 #define PGSTAT_DESTROY_DELAY 10000 /* How long to keep destroyed
73 * objects known, to give delayed
74 * UDP packets time to arrive; in
77 #define PGSTAT_DESTROY_COUNT (PGSTAT_DESTROY_DELAY / PGSTAT_STAT_INTERVAL)
79 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart
80 * a failed statistics collector;
84 * Amount of space reserved in pgstat_recvbuffer().
87 #define PGSTAT_RECVBUFFERSZ ((int) (1024 * sizeof(PgStat_Msg)))
90 * The initial size hints for the hash tables used in the collector.
93 #define PGSTAT_DB_HASH_SIZE 16
94 #define PGSTAT_BE_HASH_SIZE 512
95 #define PGSTAT_TAB_HASH_SIZE 512
102 bool pgstat_collect_startcollector = true;
103 bool pgstat_collect_resetonpmstart = false;
104 bool pgstat_collect_querystring = false;
105 bool pgstat_collect_tuplelevel = false;
106 bool pgstat_collect_blocklevel = false;
112 NON_EXEC_STATIC int pgStatSock = -1;
113 NON_EXEC_STATIC int pgStatPipe[2] = {-1,-1};
114 static struct sockaddr_storage pgStatAddr;
115 static pid_t pgStatCollectorPid = 0;
117 static time_t last_pgstat_start_time;
119 static long pgStatNumMessages = 0;
121 static bool pgStatRunningInCollector = FALSE;
124 * Place where backends store per-table info to be sent to the collector.
125 * We store shared relations separately from non-shared ones, to be able to
126 * send them in separate messages.
128 typedef struct TabStatArray
130 int tsa_alloc; /* num allocated */
131 int tsa_used; /* num actually used */
132 PgStat_MsgTabstat **tsa_messages; /* the array itself */
135 #define TABSTAT_QUANTUM 4 /* we alloc this many at a time */
137 static TabStatArray RegularTabStat = { 0, 0, NULL };
138 static TabStatArray SharedTabStat = { 0, 0, NULL };
140 static int pgStatXactCommit = 0;
141 static int pgStatXactRollback = 0;
143 static TransactionId pgStatDBHashXact = InvalidTransactionId;
144 static HTAB *pgStatDBHash = NULL;
145 static HTAB *pgStatBeDead = NULL;
146 static PgStat_StatBeEntry *pgStatBeTable = NULL;
147 static int pgStatNumBackends = 0;
151 * Local function forward declarations
156 typedef enum STATS_PROCESS_TYPE
160 } STATS_PROCESS_TYPE;
162 static pid_t pgstat_forkexec(STATS_PROCESS_TYPE procType);
163 static void pgstat_parseArgs(int argc, char *argv[]);
166 NON_EXEC_STATIC void PgstatBufferMain(int argc, char *argv[]);
167 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
168 static void pgstat_recvbuffer(void);
169 static void pgstat_exit(SIGNAL_ARGS);
170 static void pgstat_die(SIGNAL_ARGS);
171 static void pgstat_beshutdown_hook(int code, Datum arg);
173 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
174 static int pgstat_add_backend(PgStat_MsgHdr *msg);
175 static void pgstat_sub_backend(int procpid);
176 static void pgstat_drop_database(Oid databaseid);
177 static void pgstat_write_statsfile(void);
178 static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
179 PgStat_StatBeEntry **betab,
181 static void backend_read_statsfile(void);
183 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
184 static void pgstat_send(void *msg, int len);
186 static void pgstat_recv_bestart(PgStat_MsgBestart *msg, int len);
187 static void pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len);
188 static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len);
189 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
190 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
191 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
192 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
193 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
194 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
195 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
198 /* ------------------------------------------------------------
199 * Public functions called from postmaster follow
200 * ------------------------------------------------------------
206 * Called from postmaster at startup. Create the resources required
207 * by the statistics collector process. If unable to do so, do not
208 * fail --- better to let the postmaster start with stats collection
215 ACCEPT_TYPE_ARG3 alen;
216 struct addrinfo *addrs = NULL,
225 #define TESTBYTEVAL ((char) 199)
228 * Force start of collector daemon if something to collect
230 if (pgstat_collect_querystring ||
231 pgstat_collect_tuplelevel ||
232 pgstat_collect_blocklevel)
233 pgstat_collect_startcollector = true;
236 * If we don't have to start a collector or should reset the collected
237 * statistics on postmaster start, simply remove the stats file.
239 if (!pgstat_collect_startcollector || pgstat_collect_resetonpmstart)
243 * Nothing else required if collector will not get started
245 if (!pgstat_collect_startcollector)
249 * Create the UDP socket for sending and receiving statistic messages
251 hints.ai_flags = AI_PASSIVE;
252 hints.ai_family = PF_UNSPEC;
253 hints.ai_socktype = SOCK_DGRAM;
254 hints.ai_protocol = 0;
255 hints.ai_addrlen = 0;
256 hints.ai_addr = NULL;
257 hints.ai_canonname = NULL;
258 hints.ai_next = NULL;
259 ret = getaddrinfo_all("localhost", NULL, &hints, &addrs);
263 (errmsg("could not resolve \"localhost\": %s",
264 gai_strerror(ret))));
269 * On some platforms, getaddrinfo_all() may return multiple addresses
270 * only one of which will actually work (eg, both IPv6 and IPv4
271 * addresses when kernel will reject IPv6). Worse, the failure may
272 * occur at the bind() or perhaps even connect() stage. So we must
273 * loop through the results till we find a working combination. We
274 * will generate LOG messages, but no error, for bogus combinations.
276 for (addr = addrs; addr; addr = addr->ai_next)
278 #ifdef HAVE_UNIX_SOCKETS
279 /* Ignore AF_UNIX sockets, if any are returned. */
280 if (addr->ai_family == AF_UNIX)
287 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
290 (errcode_for_socket_access(),
291 errmsg("could not create socket for statistics collector: %m")));
296 * Bind it to a kernel assigned port on localhost and get the
297 * assigned port via getsockname().
299 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
302 (errcode_for_socket_access(),
303 errmsg("could not bind socket for statistics collector: %m")));
304 closesocket(pgStatSock);
309 alen = sizeof(pgStatAddr);
310 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
313 (errcode_for_socket_access(),
314 errmsg("could not get address of socket for statistics collector: %m")));
315 closesocket(pgStatSock);
321 * Connect the socket to its own address. This saves a few cycles
322 * by not having to respecify the target address on every send.
323 * This also provides a kernel-level check that only packets from
324 * this same address will be received.
326 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
329 (errcode_for_socket_access(),
330 errmsg("could not connect socket for statistics collector: %m")));
331 closesocket(pgStatSock);
337 * Try to send and receive a one-byte test message on the socket.
338 * This is to catch situations where the socket can be created but
339 * will not actually pass data (for instance, because kernel
340 * packet filtering rules prevent it).
342 test_byte = TESTBYTEVAL;
343 if (send(pgStatSock, &test_byte, 1, 0) != 1)
346 (errcode_for_socket_access(),
347 errmsg("could not send test message on socket for statistics collector: %m")));
348 closesocket(pgStatSock);
354 * There could possibly be a little delay before the message can
355 * be received. We arbitrarily allow up to half a second before
356 * deciding it's broken.
358 for (;;) /* need a loop to handle EINTR */
361 FD_SET(pgStatSock, &rset);
364 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
365 if (sel_res >= 0 || errno != EINTR)
371 (errcode_for_socket_access(),
372 errmsg("select() failed in statistics collector: %m")));
373 closesocket(pgStatSock);
377 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
380 * This is the case we actually think is likely, so take pains
381 * to give a specific message for it.
383 * errno will not be set meaningfully here, so don't use it.
386 (errcode(ERRCODE_CONNECTION_FAILURE),
387 errmsg("test message did not get through on socket for statistics collector")));
388 closesocket(pgStatSock);
393 test_byte++; /* just make sure variable is changed */
395 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
398 (errcode_for_socket_access(),
399 errmsg("could not receive test message on socket for statistics collector: %m")));
400 closesocket(pgStatSock);
405 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
408 (errcode(ERRCODE_INTERNAL_ERROR),
409 errmsg("incorrect test message transmission on socket for statistics collector")));
410 closesocket(pgStatSock);
415 /* If we get here, we have a working socket */
419 /* Did we find a working address? */
420 if (!addr || pgStatSock < 0)
424 * Set the socket to non-blocking IO. This ensures that if the
425 * collector falls behind (despite the buffering process), statistics
426 * messages will be discarded; backends won't block waiting to send
427 * messages to the collector.
429 if (!pg_set_noblock(pgStatSock))
432 (errcode_for_socket_access(),
433 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
437 freeaddrinfo_all(hints.ai_family, addrs);
443 (errmsg("disabling statistics collector for lack of working socket")));
446 freeaddrinfo_all(hints.ai_family, addrs);
449 closesocket(pgStatSock);
452 /* Adjust GUC variables to suppress useless activity */
453 pgstat_collect_startcollector = false;
454 pgstat_collect_querystring = false;
455 pgstat_collect_tuplelevel = false;
456 pgstat_collect_blocklevel = false;
460 * pgstat_reset_all() -
462 * Remove the stats file. This is used on server start if the
463 * stats_reset_on_server_start feature is enabled, or if WAL
464 * recovery is needed after a crash.
467 pgstat_reset_all(void)
469 unlink(PGSTAT_STAT_FILENAME);
475 * pgstat_forkexec() -
477 * Format up the arglist for, then fork and exec, statistics
478 * (buffer and collector) processes
481 pgstat_forkexec(STATS_PROCESS_TYPE procType)
487 char pgstatBuf[2][32];
489 av[ac++] = "postgres";
493 case STAT_PROC_BUFFER:
494 av[ac++] = "-forkbuf";
497 case STAT_PROC_COLLECTOR:
498 av[ac++] = "-forkcol";
505 av[ac++] = NULL; /* filled in by postmaster_forkexec */
507 /* postgres_exec_path is not passed by write_backend_variables */
508 av[ac++] = postgres_exec_path;
510 /* Add to the arg list */
511 Assert(bufc <= lengthof(pgstatBuf));
512 for (i = 0; i < bufc; i++)
513 av[ac++] = pgstatBuf[i];
516 Assert(ac < lengthof(av));
518 return postmaster_forkexec(ac, av);
523 * pgstat_parseArgs() -
525 * Extract data from the arglist for exec'ed statistics
526 * (buffer and collector) processes
529 pgstat_parseArgs(int argc, char *argv[])
534 StrNCpy(postgres_exec_path, argv[argc++], MAXPGPATH);
536 #endif /* EXEC_BACKEND */
542 * Called from postmaster at startup or after an existing collector
543 * died. Attempt to fire up a fresh statistics collector.
545 * Returns PID of child process, or 0 if fail.
547 * Note: if fail, we will be called again from the postmaster main loop.
557 * Do nothing if no collector needed
559 if (!pgstat_collect_startcollector)
563 * Do nothing if too soon since last collector start. This is a
564 * safety valve to protect against continuous respawn attempts if the
565 * collector is dying immediately at launch. Note that since we will
566 * be re-called from the postmaster main loop, we will get another
569 curtime = time(NULL);
570 if ((unsigned int) (curtime - last_pgstat_start_time) <
571 (unsigned int) PGSTAT_RESTART_INTERVAL)
573 last_pgstat_start_time = curtime;
576 * Check that the socket is there, else pgstat_init failed.
581 (errmsg("statistics collector startup skipped")));
584 * We can only get here if someone tries to manually turn
585 * pgstat_collect_startcollector on after it had been off.
587 pgstat_collect_startcollector = false;
592 * Okay, fork off the collector.
595 switch ((pgStatPid = pgstat_forkexec(STAT_PROC_BUFFER)))
597 switch ((pgStatPid = fork_process()))
602 (errmsg("could not fork statistics buffer: %m")));
607 /* in postmaster child ... */
608 /* Close the postmaster's sockets */
609 ClosePostmasterPorts(false);
611 /* Drop our connection to postmaster's shared memory, as well */
612 PGSharedMemoryDetach();
614 PgstatBufferMain(0, NULL);
619 return (int) pgStatPid;
622 /* shouldn't get here */
630 * Called from postmaster to tell collector a backend terminated.
634 pgstat_beterm(int pid)
636 PgStat_MsgBeterm msg;
641 /* can't use pgstat_setheader() because it's not called in a backend */
642 MemSet(&(msg.m_hdr), 0, sizeof(msg.m_hdr));
643 msg.m_hdr.m_type = PGSTAT_MTYPE_BETERM;
644 msg.m_hdr.m_procpid = pid;
646 pgstat_send(&msg, sizeof(msg));
651 * pgstat_report_autovac() -
653 * Called from autovacuum.c to report startup of an autovacuum process.
654 * We are called before InitPostgres is done, so can't rely on MyDatabaseId;
655 * the db OID must be passed in, instead.
659 pgstat_report_autovac(Oid dboid)
661 PgStat_MsgAutovacStart msg;
666 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
667 msg.m_databaseid = dboid;
668 msg.m_start_time = GetCurrentTimestamp();
670 pgstat_send(&msg, sizeof(msg));
673 /* ------------------------------------------------------------
674 * Public functions used by backends follow
675 *------------------------------------------------------------
682 * Tell the collector that this new backend is soon ready to process
683 * queries. Called from InitPostgres.
689 PgStat_MsgBestart msg;
695 * We may not have a MyProcPort (eg, if this is the autovacuum process).
696 * For the moment, punt and don't send BESTART --- would be better to
697 * work out a clean way of handling "unknown clientaddr".
701 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_BESTART);
702 msg.m_databaseid = MyDatabaseId;
703 msg.m_userid = GetSessionUserId();
704 memcpy(&msg.m_clientaddr, &MyProcPort->raddr, sizeof(msg.m_clientaddr));
705 pgstat_send(&msg, sizeof(msg));
709 * Set up a process-exit hook to ensure we flush the last batch of
710 * statistics to the collector.
712 on_shmem_exit(pgstat_beshutdown_hook, 0);
716 * pgstat_report_vacuum() -
718 * Tell the collector about the table we just vacuumed.
722 pgstat_report_vacuum(Oid tableoid, bool shared,
723 bool analyze, PgStat_Counter tuples)
725 PgStat_MsgVacuum msg;
730 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
731 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
732 msg.m_tableoid = tableoid;
733 msg.m_analyze = analyze;
734 msg.m_tuples = tuples;
735 pgstat_send(&msg, sizeof(msg));
739 * pgstat_report_analyze() -
741 * Tell the collector about the table we just analyzed.
745 pgstat_report_analyze(Oid tableoid, bool shared, PgStat_Counter livetuples,
746 PgStat_Counter deadtuples)
748 PgStat_MsgAnalyze msg;
753 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
754 msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
755 msg.m_tableoid = tableoid;
756 msg.m_live_tuples = livetuples;
757 msg.m_dead_tuples = deadtuples;
758 pgstat_send(&msg, sizeof(msg));
762 * Flush any remaining statistics counts out to the collector at process
763 * exit. Without this, operations triggered during backend exit (such as
764 * temp table deletions) won't be counted.
767 pgstat_beshutdown_hook(int code, Datum arg)
769 pgstat_report_tabstat();
774 * pgstat_report_activity() -
776 * Called from tcop/postgres.c to tell the collector what the backend
777 * is actually doing (usually "<IDLE>" or the start of the query to
782 pgstat_report_activity(const char *what)
784 PgStat_MsgActivity msg;
787 if (!pgstat_collect_querystring || pgStatSock < 0)
791 len = pg_mbcliplen(what, len, PGSTAT_ACTIVITY_SIZE - 1);
793 memcpy(msg.m_what, what, len);
794 msg.m_what[len] = '\0';
795 len += offsetof(PgStat_MsgActivity, m_what) +1;
797 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ACTIVITY);
798 pgstat_send(&msg, len);
803 * pgstat_report_tabstat() -
805 * Called from tcop/postgres.c to send the so far collected
806 * per table access statistics to the collector.
810 pgstat_report_tabstat(void)
814 if (pgStatSock < 0 ||
815 !(pgstat_collect_querystring ||
816 pgstat_collect_tuplelevel ||
817 pgstat_collect_blocklevel))
819 /* Not reporting stats, so just flush whatever we have */
820 RegularTabStat.tsa_used = 0;
821 SharedTabStat.tsa_used = 0;
826 * For each message buffer used during the last query set the header
827 * fields and send it out.
829 for (i = 0; i < RegularTabStat.tsa_used; i++)
831 PgStat_MsgTabstat *tsmsg = RegularTabStat.tsa_messages[i];
835 n = tsmsg->m_nentries;
836 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
837 n * sizeof(PgStat_TableEntry);
839 tsmsg->m_xact_commit = pgStatXactCommit;
840 tsmsg->m_xact_rollback = pgStatXactRollback;
841 pgStatXactCommit = 0;
842 pgStatXactRollback = 0;
844 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
845 tsmsg->m_databaseid = MyDatabaseId;
846 pgstat_send(tsmsg, len);
848 RegularTabStat.tsa_used = 0;
850 /* Ditto, for shared relations */
851 for (i = 0; i < SharedTabStat.tsa_used; i++)
853 PgStat_MsgTabstat *tsmsg = SharedTabStat.tsa_messages[i];
857 n = tsmsg->m_nentries;
858 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
859 n * sizeof(PgStat_TableEntry);
861 /* We don't report transaction commit/abort here */
862 tsmsg->m_xact_commit = 0;
863 tsmsg->m_xact_rollback = 0;
865 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
866 tsmsg->m_databaseid = InvalidOid;
867 pgstat_send(tsmsg, len);
869 SharedTabStat.tsa_used = 0;
874 * pgstat_vacuum_tabstat() -
876 * Will tell the collector about objects he can get rid of.
880 pgstat_vacuum_tabstat(void)
888 HASH_SEQ_STATUS hstat;
889 PgStat_StatDBEntry *dbentry;
890 PgStat_StatTabEntry *tabentry;
893 PgStat_MsgTabpurge msg;
901 * If not done for this transaction, read the statistics collector
902 * stats file into some hash tables.
904 backend_read_statsfile();
907 * Lookup our own database entry; if not found, nothing to do.
909 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
910 (void *) &MyDatabaseId,
914 if (dbentry->tables == NULL)
918 * Initialize our messages table counter to zero
923 * Check for all tables listed in stats hashtable if they still exist.
925 hash_seq_init(&hstat, dbentry->tables);
926 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
929 * Check if this relation is still alive by looking up it's
930 * pg_class tuple in the system catalog cache.
932 reltup = SearchSysCache(RELOID,
933 ObjectIdGetDatum(tabentry->tableid),
935 if (HeapTupleIsValid(reltup))
937 ReleaseSysCache(reltup);
942 * Add this table's Oid to the message
944 msg.m_tableid[msg.m_nentries++] = tabentry->tableid;
948 * If the message is full, send it out and reinitialize to zero
950 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
952 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
953 +msg.m_nentries * sizeof(Oid);
955 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
956 msg.m_databaseid = MyDatabaseId;
957 pgstat_send(&msg, len);
966 if (msg.m_nentries > 0)
968 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
969 +msg.m_nentries * sizeof(Oid);
971 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
972 msg.m_databaseid = MyDatabaseId;
973 pgstat_send(&msg, len);
977 * Read pg_database and remember the Oid's of all existing databases
981 dbidlist = (Oid *) palloc(sizeof(Oid) * dbidalloc);
983 dbrel = heap_open(DatabaseRelationId, AccessShareLock);
984 dbscan = heap_beginscan(dbrel, SnapshotNow, 0, NULL);
985 while ((dbtup = heap_getnext(dbscan, ForwardScanDirection)) != NULL)
987 if (dbidused >= dbidalloc)
990 dbidlist = (Oid *) repalloc((char *) dbidlist,
991 sizeof(Oid) * dbidalloc);
993 dbidlist[dbidused++] = HeapTupleGetOid(dbtup);
995 heap_endscan(dbscan);
996 heap_close(dbrel, AccessShareLock);
999 * Search the database hash table for dead databases and tell the
1000 * collector to drop them as well.
1002 hash_seq_init(&hstat, pgStatDBHash);
1003 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
1005 Oid dbid = dbentry->databaseid;
1007 for (i = 0; i < dbidused; i++)
1009 if (dbidlist[i] == dbid)
1016 if (dbid != InvalidOid)
1018 pgstat_drop_database(dbid);
1024 * Free the dbid list.
1029 * Tell the caller how many removeable objects we found
1036 * pgstat_drop_database() -
1038 * Tell the collector that we just dropped a database.
1039 * This is the only message that shouldn't get lost in space. Otherwise
1040 * the collector will keep the statistics for the dead DB until his
1041 * stats file got removed while the postmaster is down.
1045 pgstat_drop_database(Oid databaseid)
1047 PgStat_MsgDropdb msg;
1052 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1053 msg.m_databaseid = databaseid;
1054 pgstat_send(&msg, sizeof(msg));
1059 * pgstat_reset_counters() -
1061 * Tell the statistics collector to reset counters for our database.
1065 pgstat_reset_counters(void)
1067 PgStat_MsgResetcounter msg;
1074 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1075 errmsg("must be superuser to reset statistics counters")));
1077 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1078 msg.m_databaseid = MyDatabaseId;
1079 pgstat_send(&msg, sizeof(msg));
1086 * Send some junk data to the collector to increase traffic.
1092 PgStat_MsgDummy msg;
1097 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1098 pgstat_send(&msg, sizeof(msg));
1102 * Enlarge a TabStatArray
1105 more_tabstat_space(TabStatArray *tsarr)
1107 PgStat_MsgTabstat *newMessages;
1108 PgStat_MsgTabstat **msgArray;
1112 AssertArg(PointerIsValid(tsarr));
1114 newAlloc = tsarr->tsa_alloc + TABSTAT_QUANTUM;
1116 /* Create (another) quantum of message buffers */
1117 newMessages = (PgStat_MsgTabstat *)
1118 MemoryContextAllocZero(TopMemoryContext,
1119 sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1121 /* Create or enlarge the pointer array */
1122 if (tsarr->tsa_messages == NULL)
1123 msgArray = (PgStat_MsgTabstat **)
1124 MemoryContextAlloc(TopMemoryContext,
1125 sizeof(PgStat_MsgTabstat *) * newAlloc);
1127 msgArray = (PgStat_MsgTabstat **)
1128 repalloc(tsarr->tsa_messages,
1129 sizeof(PgStat_MsgTabstat *) * newAlloc);
1131 for (i = 0; i < TABSTAT_QUANTUM; i++)
1132 msgArray[tsarr->tsa_alloc + i] = newMessages++;
1133 tsarr->tsa_messages = msgArray;
1134 tsarr->tsa_alloc = newAlloc;
1136 Assert(tsarr->tsa_used < tsarr->tsa_alloc);
1140 * pgstat_initstats() -
1142 * Called from various places usually dealing with initialization
1143 * of Relation or Scan structures. The data placed into these
1144 * structures from here tell where later to count for buffer reads,
1145 * scans and tuples fetched.
1149 pgstat_initstats(PgStat_Info *stats, Relation rel)
1151 Oid rel_id = rel->rd_id;
1152 PgStat_TableEntry *useent;
1153 TabStatArray *tsarr;
1154 PgStat_MsgTabstat *tsmsg;
1159 * Initialize data not to count at all.
1161 stats->tabentry = NULL;
1162 stats->no_stats = FALSE;
1163 stats->heap_scan_counted = FALSE;
1164 stats->index_scan_counted = FALSE;
1166 if (pgStatSock < 0 ||
1167 !(pgstat_collect_tuplelevel ||
1168 pgstat_collect_blocklevel))
1170 stats->no_stats = TRUE;
1174 tsarr = rel->rd_rel->relisshared ? &SharedTabStat : &RegularTabStat;
1177 * Search the already-used message slots for this relation.
1179 for (mb = 0; mb < tsarr->tsa_used; mb++)
1181 tsmsg = tsarr->tsa_messages[mb];
1183 for (i = tsmsg->m_nentries; --i >= 0;)
1185 if (tsmsg->m_entry[i].t_id == rel_id)
1187 stats->tabentry = (void *) &(tsmsg->m_entry[i]);
1192 if (tsmsg->m_nentries >= PGSTAT_NUM_TABENTRIES)
1196 * Not found, but found a message buffer with an empty slot
1197 * instead. Fine, let's use this one.
1199 i = tsmsg->m_nentries++;
1200 useent = &tsmsg->m_entry[i];
1201 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1202 useent->t_id = rel_id;
1203 stats->tabentry = (void *) useent;
1208 * If we ran out of message buffers, we just allocate more.
1210 if (tsarr->tsa_used >= tsarr->tsa_alloc)
1211 more_tabstat_space(tsarr);
1214 * Use the first entry of the next message buffer.
1216 mb = tsarr->tsa_used++;
1217 tsmsg = tsarr->tsa_messages[mb];
1218 tsmsg->m_nentries = 1;
1219 useent = &tsmsg->m_entry[0];
1220 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1221 useent->t_id = rel_id;
1222 stats->tabentry = (void *) useent;
1227 * pgstat_count_xact_commit() -
1229 * Called from access/transam/xact.c to count transaction commits.
1233 pgstat_count_xact_commit(void)
1235 if (!(pgstat_collect_querystring ||
1236 pgstat_collect_tuplelevel ||
1237 pgstat_collect_blocklevel))
1243 * If there was no relation activity yet, just make one existing
1244 * message buffer used without slots, causing the next report to tell
1245 * new xact-counters.
1247 if (RegularTabStat.tsa_alloc == 0)
1248 more_tabstat_space(&RegularTabStat);
1250 if (RegularTabStat.tsa_used == 0)
1252 RegularTabStat.tsa_used++;
1253 RegularTabStat.tsa_messages[0]->m_nentries = 0;
1259 * pgstat_count_xact_rollback() -
1261 * Called from access/transam/xact.c to count transaction rollbacks.
1265 pgstat_count_xact_rollback(void)
1267 if (!(pgstat_collect_querystring ||
1268 pgstat_collect_tuplelevel ||
1269 pgstat_collect_blocklevel))
1272 pgStatXactRollback++;
1275 * If there was no relation activity yet, just make one existing
1276 * message buffer used without slots, causing the next report to tell
1277 * new xact-counters.
1279 if (RegularTabStat.tsa_alloc == 0)
1280 more_tabstat_space(&RegularTabStat);
1282 if (RegularTabStat.tsa_used == 0)
1284 RegularTabStat.tsa_used++;
1285 RegularTabStat.tsa_messages[0]->m_nentries = 0;
1291 * pgstat_fetch_stat_dbentry() -
1293 * Support function for the SQL-callable pgstat* functions. Returns
1294 * the collected statistics for one database or NULL. NULL doesn't mean
1295 * that the database doesn't exist, it is just not yet known by the
1296 * collector, so the caller is better off to report ZERO instead.
1299 PgStat_StatDBEntry *
1300 pgstat_fetch_stat_dbentry(Oid dbid)
1303 * If not done for this transaction, read the statistics collector
1304 * stats file into some hash tables.
1306 backend_read_statsfile();
1309 * Lookup the requested database; return NULL if not found
1311 return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1318 * pgstat_fetch_stat_tabentry() -
1320 * Support function for the SQL-callable pgstat* functions. Returns
1321 * the collected statistics for one table or NULL. NULL doesn't mean
1322 * that the table doesn't exist, it is just not yet known by the
1323 * collector, so the caller is better off to report ZERO instead.
1326 PgStat_StatTabEntry *
1327 pgstat_fetch_stat_tabentry(Oid relid)
1330 PgStat_StatDBEntry *dbentry;
1331 PgStat_StatTabEntry *tabentry;
1334 * If not done for this transaction, read the statistics collector
1335 * stats file into some hash tables.
1337 backend_read_statsfile();
1340 * Lookup our database, then look in its table hash table.
1342 dbid = MyDatabaseId;
1343 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1346 if (dbentry != NULL && dbentry->tables != NULL)
1348 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1356 * If we didn't find it, maybe it's a shared table.
1359 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1362 if (dbentry != NULL && dbentry->tables != NULL)
1364 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1376 * pgstat_fetch_stat_beentry() -
1378 * Support function for the SQL-callable pgstat* functions. Returns
1379 * the actual activity slot of one active backend. The caller is
1380 * responsible for a check if the actual user is permitted to see
1381 * that info (especially the querystring).
1384 PgStat_StatBeEntry *
1385 pgstat_fetch_stat_beentry(int beid)
1387 backend_read_statsfile();
1389 if (beid < 1 || beid > pgStatNumBackends)
1392 return &pgStatBeTable[beid - 1];
1397 * pgstat_fetch_stat_numbackends() -
1399 * Support function for the SQL-callable pgstat* functions. Returns
1400 * the maximum current backend id.
1404 pgstat_fetch_stat_numbackends(void)
1406 backend_read_statsfile();
1408 return pgStatNumBackends;
1413 /* ------------------------------------------------------------
1414 * Local support functions follow
1415 * ------------------------------------------------------------
1420 * pgstat_setheader() -
1422 * Set common header fields in a statistics message
1426 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
1428 hdr->m_type = mtype;
1429 hdr->m_backendid = MyBackendId;
1430 hdr->m_procpid = MyProcPid;
1437 * Send out one statistics message to the collector
1441 pgstat_send(void *msg, int len)
1446 ((PgStat_MsgHdr *) msg)->m_size = len;
1448 #ifdef USE_ASSERT_CHECKING
1449 if (send(pgStatSock, msg, len, 0) < 0)
1450 elog(LOG, "could not send to statistics collector: %m");
1452 send(pgStatSock, msg, len, 0);
1453 /* We deliberately ignore any error from send() */
1459 * PgstatBufferMain() -
1461 * Start up the statistics buffer process. This is the body of the
1462 * postmaster child process.
1464 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1467 NON_EXEC_STATIC void
1468 PgstatBufferMain(int argc, char *argv[])
1470 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
1472 MyProcPid = getpid(); /* reset MyProcPid */
1474 /* Lose the postmaster's on-exit routines */
1478 * Ignore all signals usually bound to some action in the postmaster,
1479 * except for SIGCHLD and SIGQUIT --- see pgstat_recvbuffer.
1481 pqsignal(SIGHUP, SIG_IGN);
1482 pqsignal(SIGINT, SIG_IGN);
1483 pqsignal(SIGTERM, SIG_IGN);
1484 pqsignal(SIGQUIT, pgstat_exit);
1485 pqsignal(SIGALRM, SIG_IGN);
1486 pqsignal(SIGPIPE, SIG_IGN);
1487 pqsignal(SIGUSR1, SIG_IGN);
1488 pqsignal(SIGUSR2, SIG_IGN);
1489 pqsignal(SIGCHLD, pgstat_die);
1490 pqsignal(SIGTTIN, SIG_DFL);
1491 pqsignal(SIGTTOU, SIG_DFL);
1492 pqsignal(SIGCONT, SIG_DFL);
1493 pqsignal(SIGWINCH, SIG_DFL);
1494 /* unblock will happen in pgstat_recvbuffer */
1497 pgstat_parseArgs(argc, argv);
1501 * Start a buffering process to read from the socket, so we have a
1502 * little more time to process incoming messages.
1504 * NOTE: the process structure is: postmaster is parent of buffer process
1505 * is parent of collector process. This way, the buffer can detect
1506 * collector failure via SIGCHLD, whereas otherwise it wouldn't notice
1507 * collector failure until it tried to write on the pipe. That would
1508 * mean that after the postmaster started a new collector, we'd have
1509 * two buffer processes competing to read from the UDP socket --- not
1512 if (pgpipe(pgStatPipe) < 0)
1514 (errcode_for_socket_access(),
1515 errmsg("could not create pipe for statistics buffer: %m")));
1517 /* child becomes collector process */
1519 pgStatCollectorPid = pgstat_forkexec(STAT_PROC_COLLECTOR);
1521 pgStatCollectorPid = fork();
1523 switch (pgStatCollectorPid)
1527 (errmsg("could not fork statistics collector: %m")));
1529 #ifndef EXEC_BACKEND
1531 /* child becomes collector process */
1532 PgstatCollectorMain(0, NULL);
1537 /* parent becomes buffer process */
1538 closesocket(pgStatPipe[0]);
1539 pgstat_recvbuffer();
1546 * PgstatCollectorMain() -
1548 * Start up the statistics collector itself. This is the body of the
1549 * postmaster grandchild process.
1551 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1554 NON_EXEC_STATIC void
1555 PgstatCollectorMain(int argc, char *argv[])
1562 struct timeval timeout;
1563 struct timeval next_statwrite;
1564 bool need_statwrite;
1567 MyProcPid = getpid(); /* reset MyProcPid */
1570 * Reset signal handling. With the exception of restoring default
1571 * SIGCHLD and SIGQUIT handling, this is a no-op in the
1572 * non-EXEC_BACKEND case because we'll have inherited these settings
1573 * from the buffer process; but it's not a no-op for EXEC_BACKEND.
1575 pqsignal(SIGHUP, SIG_IGN);
1576 pqsignal(SIGINT, SIG_IGN);
1577 pqsignal(SIGTERM, SIG_IGN);
1579 pqsignal(SIGQUIT, SIG_IGN);
1581 /* kluge to allow buffer process to kill collector; FIXME */
1582 pqsignal(SIGQUIT, pgstat_exit);
1584 pqsignal(SIGALRM, SIG_IGN);
1585 pqsignal(SIGPIPE, SIG_IGN);
1586 pqsignal(SIGUSR1, SIG_IGN);
1587 pqsignal(SIGUSR2, SIG_IGN);
1588 pqsignal(SIGCHLD, SIG_DFL);
1589 pqsignal(SIGTTIN, SIG_DFL);
1590 pqsignal(SIGTTOU, SIG_DFL);
1591 pqsignal(SIGCONT, SIG_DFL);
1592 pqsignal(SIGWINCH, SIG_DFL);
1593 PG_SETMASK(&UnBlockSig);
1596 pgstat_parseArgs(argc, argv);
1599 /* Close unwanted files */
1600 closesocket(pgStatPipe[1]);
1601 closesocket(pgStatSock);
1604 * Identify myself via ps
1606 init_ps_display("stats collector process", "", "");
1610 * Arrange to write the initial status file right away
1612 gettimeofday(&next_statwrite, NULL);
1613 need_statwrite = TRUE;
1616 * Read in an existing statistics stats file or initialize the stats
1619 pgStatRunningInCollector = TRUE;
1620 pgstat_read_statsfile(&pgStatDBHash, InvalidOid, NULL, NULL);
1623 * Create the dead backend hashtable
1625 memset(&hash_ctl, 0, sizeof(hash_ctl));
1626 hash_ctl.keysize = sizeof(int);
1627 hash_ctl.entrysize = sizeof(PgStat_StatBeDead);
1628 hash_ctl.hash = tag_hash;
1629 pgStatBeDead = hash_create("Dead Backends", PGSTAT_BE_HASH_SIZE,
1630 &hash_ctl, HASH_ELEM | HASH_FUNCTION);
1633 * Create the known backends table
1635 pgStatBeTable = (PgStat_StatBeEntry *)
1636 palloc0(sizeof(PgStat_StatBeEntry) * MaxBackends);
1638 readPipe = pgStatPipe[0];
1641 * Process incoming messages and handle all the reporting stuff until
1642 * there are no more messages.
1647 * If we need to write the status file again (there have been
1648 * changes in the statistics since we wrote it last) calculate the
1649 * timeout until we have to do so.
1655 gettimeofday(&now, NULL);
1656 /* avoid assuming that tv_sec is signed */
1657 if (now.tv_sec > next_statwrite.tv_sec ||
1658 (now.tv_sec == next_statwrite.tv_sec &&
1659 now.tv_usec >= next_statwrite.tv_usec))
1662 timeout.tv_usec = 0;
1666 timeout.tv_sec = next_statwrite.tv_sec - now.tv_sec;
1667 timeout.tv_usec = next_statwrite.tv_usec - now.tv_usec;
1668 if (timeout.tv_usec < 0)
1671 timeout.tv_usec += 1000000;
1677 * Setup the descriptor set for select(2)
1680 FD_SET(readPipe, &rfds);
1683 * Now wait for something to do.
1685 nready = select(readPipe + 1, &rfds, NULL, NULL,
1686 (need_statwrite) ? &timeout : NULL);
1692 (errcode_for_socket_access(),
1693 errmsg("select() failed in statistics collector: %m")));
1697 * If there are no descriptors ready, our timeout for writing the
1698 * stats file happened.
1702 pgstat_write_statsfile();
1703 need_statwrite = FALSE;
1709 * Check if there is a new statistics message to collect.
1711 if (FD_ISSET(readPipe, &rfds))
1714 * We may need to issue multiple read calls in case the buffer
1715 * process didn't write the message in a single write, which
1716 * is possible since it dumps its buffer bytewise. In any
1717 * case, we'd need two reads since we don't know the message
1721 int targetlen = sizeof(PgStat_MsgHdr); /* initial */
1722 bool pipeEOF = false;
1724 while (nread < targetlen)
1726 len = piperead(readPipe, ((char *) &msg) + nread,
1733 (errcode_for_socket_access(),
1734 errmsg("could not read from statistics collector pipe: %m")));
1736 if (len == 0) /* EOF on the pipe! */
1742 if (nread == sizeof(PgStat_MsgHdr))
1744 /* we have the header, compute actual msg length */
1745 targetlen = msg.msg_hdr.m_size;
1746 if (targetlen < (int) sizeof(PgStat_MsgHdr) ||
1747 targetlen > (int) sizeof(msg))
1750 * Bogus message length implies that we got out of
1751 * sync with the buffer process somehow. Abort so
1752 * that we can restart both processes.
1755 (errmsg("invalid statistics message length")));
1761 * EOF on the pipe implies that the buffer process exited.
1762 * Fall out of outer loop.
1768 * Distribute the message to the specific function handling
1771 switch (msg.msg_hdr.m_type)
1773 case PGSTAT_MTYPE_DUMMY:
1776 case PGSTAT_MTYPE_BESTART:
1777 pgstat_recv_bestart((PgStat_MsgBestart *) &msg, nread);
1780 case PGSTAT_MTYPE_BETERM:
1781 pgstat_recv_beterm((PgStat_MsgBeterm *) &msg, nread);
1784 case PGSTAT_MTYPE_TABSTAT:
1785 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, nread);
1788 case PGSTAT_MTYPE_TABPURGE:
1789 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, nread);
1792 case PGSTAT_MTYPE_ACTIVITY:
1793 pgstat_recv_activity((PgStat_MsgActivity *) &msg, nread);
1796 case PGSTAT_MTYPE_DROPDB:
1797 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, nread);
1800 case PGSTAT_MTYPE_RESETCOUNTER:
1801 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
1805 case PGSTAT_MTYPE_AUTOVAC_START:
1806 pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, nread);
1809 case PGSTAT_MTYPE_VACUUM:
1810 pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, nread);
1813 case PGSTAT_MTYPE_ANALYZE:
1814 pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, nread);
1822 * Globally count messages.
1824 pgStatNumMessages++;
1827 * If this is the first message after we wrote the stats file
1828 * the last time, setup the timeout that it'd be written.
1830 if (!need_statwrite)
1832 gettimeofday(&next_statwrite, NULL);
1833 next_statwrite.tv_usec += ((PGSTAT_STAT_INTERVAL) * 1000);
1834 next_statwrite.tv_sec += (next_statwrite.tv_usec / 1000000);
1835 next_statwrite.tv_usec %= 1000000;
1836 need_statwrite = TRUE;
1841 * Note that we do NOT check for postmaster exit inside the loop;
1842 * only EOF on the buffer pipe causes us to fall out. This
1843 * ensures we don't exit prematurely if there are still a few
1844 * messages in the buffer or pipe at postmaster shutdown.
1849 * Okay, we saw EOF on the buffer pipe, so there are no more messages
1850 * to process. If the buffer process quit because of postmaster
1851 * shutdown, we want to save the final stats to reuse at next startup.
1852 * But if the buffer process failed, it seems best not to (there may
1853 * even now be a new collector firing up, and we don't want it to read
1854 * a partially-rewritten stats file).
1856 if (!PostmasterIsAlive(false))
1857 pgstat_write_statsfile();
1862 * pgstat_recvbuffer() -
1864 * This is the body of the separate buffering process. Its only
1865 * purpose is to receive messages from the UDP socket as fast as
1866 * possible and forward them over a pipe into the collector itself.
1867 * If the collector is slow to absorb messages, they are buffered here.
1871 pgstat_recvbuffer(void)
1875 struct timeval timeout;
1876 int writePipe = pgStatPipe[1];
1882 PgStat_Msg input_buffer;
1884 int msg_send = 0; /* next send index in buffer */
1885 int msg_recv = 0; /* next receive index */
1886 int msg_have = 0; /* number of bytes stored */
1887 bool overflow = false;
1890 * Identify myself via ps
1892 init_ps_display("stats buffer process", "", "");
1896 * We want to die if our child collector process does. There are two
1897 * ways we might notice that it has died: receive SIGCHLD, or get a
1898 * write failure on the pipe leading to the child. We can set SIGPIPE
1899 * to kill us here. Our SIGCHLD handler was already set up before we
1900 * forked (must do it that way, else it's a race condition).
1902 pqsignal(SIGPIPE, SIG_DFL);
1903 PG_SETMASK(&UnBlockSig);
1906 * Set the write pipe to nonblock mode, so that we cannot block when
1907 * the collector falls behind.
1909 if (!pg_set_noblock(writePipe))
1911 (errcode_for_socket_access(),
1912 errmsg("could not set statistics collector pipe to nonblocking mode: %m")));
1915 * Allocate the message buffer
1917 msgbuffer = (char *) palloc(PGSTAT_RECVBUFFERSZ);
1929 * As long as we have buffer space we add the socket to the read
1932 if (msg_have <= (int) (PGSTAT_RECVBUFFERSZ - sizeof(PgStat_Msg)))
1934 FD_SET(pgStatSock, &rfds);
1943 (errmsg("statistics buffer is full")));
1949 * If we have messages to write out, we add the pipe to the write
1954 FD_SET(writePipe, &wfds);
1955 if (writePipe > maxfd)
1960 * Wait for some work to do; but not for more than 10 seconds.
1961 * (This determines how quickly we will shut down after an
1962 * ungraceful postmaster termination; so it needn't be very fast.)
1964 timeout.tv_sec = 10;
1965 timeout.tv_usec = 0;
1967 nready = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
1973 (errcode_for_socket_access(),
1974 errmsg("select() failed in statistics buffer: %m")));
1978 * If there is a message on the socket, read it and check for
1981 if (FD_ISSET(pgStatSock, &rfds))
1983 len = recv(pgStatSock, (char *) &input_buffer,
1984 sizeof(PgStat_Msg), 0);
1987 (errcode_for_socket_access(),
1988 errmsg("could not read statistics message: %m")));
1991 * We ignore messages that are smaller than our common header
1993 if (len < sizeof(PgStat_MsgHdr))
1997 * The received length must match the length in the header
1999 if (input_buffer.msg_hdr.m_size != len)
2003 * O.K. - we accept this message. Copy it to the circular
2009 xfr = PGSTAT_RECVBUFFERSZ - msg_recv;
2013 memcpy(msgbuffer + msg_recv,
2014 ((char *) &input_buffer) + frm,
2017 if (msg_recv == PGSTAT_RECVBUFFERSZ)
2026 * If the collector is ready to receive, write some data into his
2027 * pipe. We may or may not be able to write all that we have.
2029 * NOTE: if what we have is less than PIPE_BUF bytes but more than
2030 * the space available in the pipe buffer, most kernels will
2031 * refuse to write any of it, and will return EAGAIN. This means
2032 * we will busy-loop until the situation changes (either because
2033 * the collector caught up, or because more data arrives so that
2034 * we have more than PIPE_BUF bytes buffered). This is not good,
2035 * but is there any way around it? We have no way to tell when
2036 * the collector has caught up...
2038 if (FD_ISSET(writePipe, &wfds))
2040 xfr = PGSTAT_RECVBUFFERSZ - msg_send;
2044 len = pipewrite(writePipe, msgbuffer + msg_send, xfr);
2047 if (errno == EINTR || errno == EAGAIN)
2048 continue; /* not enough space in pipe */
2050 (errcode_for_socket_access(),
2051 errmsg("could not write to statistics collector pipe: %m")));
2053 /* NB: len < xfr is okay */
2055 if (msg_send == PGSTAT_RECVBUFFERSZ)
2061 * Make sure we forwarded all messages before we check for
2062 * postmaster termination.
2064 if (msg_have != 0 || FD_ISSET(pgStatSock, &rfds))
2068 * If the postmaster has terminated, we die too. (This is no
2069 * longer the normal exit path, however.)
2071 if (!PostmasterIsAlive(true))
2076 /* SIGQUIT signal handler for buffer process */
2078 pgstat_exit(SIGNAL_ARGS)
2081 * For now, we just nail the doors shut and get out of town. It might
2082 * be cleaner to allow any pending messages to be sent, but that
2083 * creates a tradeoff against speed of exit.
2087 * If running in bufferer, kill our collector as well. On some broken
2088 * win32 systems, it does not shut down automatically because of issues
2089 * with socket inheritance. XXX so why not fix the socket inheritance...
2092 if (pgStatCollectorPid > 0)
2093 kill(pgStatCollectorPid, SIGQUIT);
2098 /* SIGCHLD signal handler for buffer process */
2100 pgstat_die(SIGNAL_ARGS)
2107 * pgstat_add_backend() -
2109 * Support function to keep our backend list up to date.
2113 pgstat_add_backend(PgStat_MsgHdr *msg)
2115 PgStat_StatBeEntry *beentry;
2116 PgStat_StatBeDead *deadbe;
2119 * Check that the backend ID is valid
2121 if (msg->m_backendid < 1 || msg->m_backendid > MaxBackends)
2124 (errmsg("invalid server process ID %d", msg->m_backendid)));
2129 * Get the slot for this backendid.
2131 beentry = &pgStatBeTable[msg->m_backendid - 1];
2134 * If the slot contains the PID of this backend, everything is
2135 * fine and we have nothing to do. Note that all the slots are
2136 * zero'd out when the collector is started. We assume that a slot
2137 * is "empty" iff procpid == 0.
2139 if (beentry->procpid > 0 && beentry->procpid == msg->m_procpid)
2143 * Lookup if this backend is known to be dead. This can be caused due
2144 * to messages arriving in the wrong order - e.g. postmaster's BETERM
2145 * message might have arrived before we received all the backends
2146 * stats messages, or even a new backend with the same backendid was
2147 * faster in sending his BESTART.
2149 * If the backend is known to be dead, we ignore this add.
2151 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2152 (void *) &(msg->m_procpid),
2158 * Backend isn't known to be dead. If it's slot is currently used, we
2159 * have to kick out the old backend.
2161 if (beentry->procpid > 0)
2162 pgstat_sub_backend(beentry->procpid);
2164 /* Must be able to distinguish between empty and non-empty slots */
2165 Assert(msg->m_procpid > 0);
2167 /* Put this new backend into the slot */
2168 beentry->procpid = msg->m_procpid;
2169 beentry->start_timestamp = GetCurrentTimestamp();
2170 beentry->activity_start_timestamp = 0;
2171 beentry->activity[0] = '\0';
2174 * We can't initialize the rest of the data in this slot until we
2175 * see the BESTART message. Therefore, we set the database and
2176 * user to sentinel values, to indicate "undefined". There is no
2177 * easy way to do this for the client address, so make sure to
2178 * check that the database or user are defined before accessing
2179 * the client address.
2181 beentry->userid = InvalidOid;
2182 beentry->databaseid = InvalidOid;
2188 * Lookup the hash table entry for the specified database. If no hash
2189 * table entry exists, initialize it, if the create parameter is true.
2190 * Else, return NULL.
2192 static PgStat_StatDBEntry *
2193 pgstat_get_db_entry(Oid databaseid, bool create)
2195 PgStat_StatDBEntry *result;
2197 HASHACTION action = (create ? HASH_ENTER : HASH_FIND);
2199 /* Lookup or create the hash table entry for this database */
2200 result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2204 if (!create && !found)
2207 /* If not found, initialize the new one. */
2212 result->tables = NULL;
2213 result->n_xact_commit = 0;
2214 result->n_xact_rollback = 0;
2215 result->n_blocks_fetched = 0;
2216 result->n_blocks_hit = 0;
2217 result->destroy = 0;
2218 result->last_autovac_time = 0;
2220 memset(&hash_ctl, 0, sizeof(hash_ctl));
2221 hash_ctl.keysize = sizeof(Oid);
2222 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2223 hash_ctl.hash = oid_hash;
2224 result->tables = hash_create("Per-database table",
2225 PGSTAT_TAB_HASH_SIZE,
2227 HASH_ELEM | HASH_FUNCTION);
2234 * pgstat_sub_backend() -
2236 * Remove a backend from the actual backends list.
2240 pgstat_sub_backend(int procpid)
2243 PgStat_StatBeDead *deadbe;
2247 * Search in the known-backends table for the slot containing this
2250 for (i = 0; i < MaxBackends; i++)
2252 if (pgStatBeTable[i].procpid == procpid)
2255 * That's him. Add an entry to the known to be dead backends.
2256 * Due to possible misorder in the arrival of UDP packets it's
2257 * possible that even if we know the backend is dead, there
2258 * could still be messages queued that arrive later. Those
2259 * messages must not cause our number of backends statistics
2260 * to get screwed up, so we remember for a couple of seconds
2261 * that this PID is dead and ignore them (only the counting of
2262 * backends, not the table access stats they sent).
2264 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2271 deadbe->backendid = i + 1;
2272 deadbe->destroy = PGSTAT_DESTROY_COUNT;
2276 * Declare the backend slot empty.
2278 pgStatBeTable[i].procpid = 0;
2284 * No big problem if not found. This can happen if UDP messages arrive
2285 * out of order here.
2291 * pgstat_write_statsfile() -
2297 pgstat_write_statsfile(void)
2299 HASH_SEQ_STATUS hstat;
2300 HASH_SEQ_STATUS tstat;
2301 PgStat_StatDBEntry *dbentry;
2302 PgStat_StatTabEntry *tabentry;
2303 PgStat_StatBeDead *deadbe;
2309 * Open the statistics temp file to write out the current values.
2311 fpout = fopen(PGSTAT_STAT_TMPFILE, PG_BINARY_W);
2315 (errcode_for_file_access(),
2316 errmsg("could not open temporary statistics file \"%s\": %m",
2317 PGSTAT_STAT_TMPFILE)));
2322 * Write the file header --- currently just a format ID.
2324 format_id = PGSTAT_FILE_FORMAT_ID;
2325 fwrite(&format_id, sizeof(format_id), 1, fpout);
2328 * Walk through the database table.
2330 hash_seq_init(&hstat, pgStatDBHash);
2331 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2334 * If this database is marked destroyed, count down and do so if
2337 if (dbentry->destroy > 0)
2339 if (--(dbentry->destroy) == 0)
2341 if (dbentry->tables != NULL)
2342 hash_destroy(dbentry->tables);
2344 if (hash_search(pgStatDBHash,
2345 (void *) &(dbentry->databaseid),
2346 HASH_REMOVE, NULL) == NULL)
2348 (errmsg("database hash table corrupted "
2349 "during cleanup --- abort")));
2353 * Don't include statistics for it.
2359 * Write out the DB line including the number of live backends.
2362 fwrite(dbentry, sizeof(PgStat_StatDBEntry), 1, fpout);
2365 * Walk through the databases access stats per table.
2367 hash_seq_init(&tstat, dbentry->tables);
2368 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2371 * If table entry marked for destruction, same as above for
2372 * the database entry.
2374 if (tabentry->destroy > 0)
2376 if (--(tabentry->destroy) == 0)
2378 if (hash_search(dbentry->tables,
2379 (void *) &(tabentry->tableid),
2380 HASH_REMOVE, NULL) == NULL)
2383 (errmsg("tables hash table for "
2384 "database %u corrupted during "
2385 "cleanup --- abort",
2386 dbentry->databaseid)));
2393 * At least we think this is still a live table. Print its
2397 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2401 * Mark the end of this DB
2407 * Write out the known running backends to the stats file.
2411 fwrite(&i, sizeof(i), 1, fpout);
2413 for (i = 0; i < MaxBackends; i++)
2415 if (pgStatBeTable[i].procpid > 0)
2418 fwrite(&pgStatBeTable[i], sizeof(PgStat_StatBeEntry), 1, fpout);
2423 * No more output to be done. Close the temp file and replace the old
2424 * pgstat.stat with it.
2427 if (fclose(fpout) < 0)
2430 (errcode_for_file_access(),
2431 errmsg("could not close temporary statistics file \"%s\": %m",
2432 PGSTAT_STAT_TMPFILE)));
2436 if (rename(PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME) < 0)
2439 (errcode_for_file_access(),
2440 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2441 PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME)));
2446 * Clear out the dead backends table
2448 hash_seq_init(&hstat, pgStatBeDead);
2449 while ((deadbe = (PgStat_StatBeDead *) hash_seq_search(&hstat)) != NULL)
2452 * Count down the destroy delay and remove entries where it
2455 if (--(deadbe->destroy) <= 0)
2457 if (hash_search(pgStatBeDead,
2458 (void *) &(deadbe->procpid),
2459 HASH_REMOVE, NULL) == NULL)
2462 (errmsg("dead-server-process hash table corrupted "
2463 "during cleanup --- abort")));
2471 * pgstat_read_statsfile() -
2473 * Reads in an existing statistics collector and initializes the
2474 * databases' hash table (whose entries point to the tables' hash tables)
2475 * and the current backend table.
2479 pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
2480 PgStat_StatBeEntry **betab, int *numbackends)
2482 PgStat_StatDBEntry *dbentry;
2483 PgStat_StatDBEntry dbbuf;
2484 PgStat_StatTabEntry *tabentry;
2485 PgStat_StatTabEntry tabbuf;
2486 PgStat_StatBeEntry *beentry;
2488 HTAB *tabhash = NULL;
2491 int maxbackends = 0;
2492 int havebackends = 0;
2495 MemoryContext use_mcxt;
2499 * If running in the collector or the autovacuum process, we use the
2500 * DynaHashCxt memory context. If running in a backend, we use the
2501 * TopTransactionContext instead, so the caller must only know the last
2502 * XactId when this call happened to know if his tables are still valid or
2505 * Also, if running in a regular backend, we check backend entries against
2506 * the PGPROC array so that we can detect stale entries. This lets us
2507 * discard entries whose BETERM message got lost for some reason.
2509 if (pgStatRunningInCollector || IsAutoVacuumProcess())
2517 use_mcxt = TopTransactionContext;
2518 mcxt_flags = HASH_CONTEXT;
2523 * Create the DB hashtable
2525 memset(&hash_ctl, 0, sizeof(hash_ctl));
2526 hash_ctl.keysize = sizeof(Oid);
2527 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2528 hash_ctl.hash = oid_hash;
2529 hash_ctl.hcxt = use_mcxt;
2530 *dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2531 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2534 * Initialize the number of known backends to zero, just in case we do
2535 * a silent error return below.
2537 if (numbackends != NULL)
2543 * Try to open the status file. If it doesn't exist, the backends
2544 * simply return zero for anything and the collector simply starts
2545 * from scratch with empty counters.
2547 if ((fpin = AllocateFile(PGSTAT_STAT_FILENAME, PG_BINARY_R)) == NULL)
2551 * Verify it's of the expected format.
2553 if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
2554 || format_id != PGSTAT_FILE_FORMAT_ID)
2556 ereport(pgStatRunningInCollector ? LOG : WARNING,
2557 (errmsg("corrupted pgstat.stat file")));
2562 * We found an existing collector stats file. Read it and put all the
2563 * hashtable entries into place.
2567 switch (fgetc(fpin))
2570 * 'D' A PgStat_StatDBEntry struct describing a database
2571 * follows. Subsequently, zero to many 'T' entries will
2572 * follow until a 'd' is encountered.
2575 if (fread(&dbbuf, 1, sizeof(dbbuf), fpin) != sizeof(dbbuf))
2577 ereport(pgStatRunningInCollector ? LOG : WARNING,
2578 (errmsg("corrupted pgstat.stat file")));
2583 * Add to the DB hash
2585 dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
2586 (void *) &dbbuf.databaseid,
2591 ereport(pgStatRunningInCollector ? LOG : WARNING,
2592 (errmsg("corrupted pgstat.stat file")));
2596 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2597 dbentry->tables = NULL;
2598 dbentry->destroy = 0;
2599 dbentry->n_backends = 0;
2602 * Don't collect tables if not the requested DB (or the
2603 * shared-table info)
2605 if (onlydb != InvalidOid)
2607 if (dbbuf.databaseid != onlydb &&
2608 dbbuf.databaseid != InvalidOid)
2612 memset(&hash_ctl, 0, sizeof(hash_ctl));
2613 hash_ctl.keysize = sizeof(Oid);
2614 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2615 hash_ctl.hash = oid_hash;
2616 hash_ctl.hcxt = use_mcxt;
2617 dbentry->tables = hash_create("Per-database table",
2618 PGSTAT_TAB_HASH_SIZE,
2620 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2623 * Arrange that following 'T's add entries to this
2624 * databases tables hash table.
2626 tabhash = dbentry->tables;
2630 * 'd' End of this database.
2637 * 'T' A PgStat_StatTabEntry follows.
2640 if (fread(&tabbuf, 1, sizeof(tabbuf), fpin) != sizeof(tabbuf))
2642 ereport(pgStatRunningInCollector ? LOG : WARNING,
2643 (errmsg("corrupted pgstat.stat file")));
2648 * Skip if table belongs to a not requested database.
2650 if (tabhash == NULL)
2653 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2654 (void *) &tabbuf.tableid,
2655 HASH_ENTER, &found);
2659 ereport(pgStatRunningInCollector ? LOG : WARNING,
2660 (errmsg("corrupted pgstat.stat file")));
2664 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2668 * 'M' The maximum number of backends to expect follows.
2671 if (betab == NULL || numbackends == NULL)
2673 if (fread(&maxbackends, 1, sizeof(maxbackends), fpin) !=
2674 sizeof(maxbackends))
2676 ereport(pgStatRunningInCollector ? LOG : WARNING,
2677 (errmsg("corrupted pgstat.stat file")));
2680 if (maxbackends == 0)
2684 * Allocate space (in TopTransactionContext too) for the
2687 if (use_mcxt == NULL)
2688 *betab = (PgStat_StatBeEntry *)
2689 palloc(sizeof(PgStat_StatBeEntry) * maxbackends);
2691 *betab = (PgStat_StatBeEntry *)
2692 MemoryContextAlloc(use_mcxt,
2693 sizeof(PgStat_StatBeEntry) * maxbackends);
2697 * 'B' A PgStat_StatBeEntry follows.
2700 if (betab == NULL || numbackends == NULL || *betab == NULL)
2703 if (havebackends >= maxbackends)
2707 * Read it directly into the table.
2709 beentry = &(*betab)[havebackends];
2711 if (fread(beentry, 1, sizeof(PgStat_StatBeEntry), fpin) !=
2712 sizeof(PgStat_StatBeEntry))
2714 ereport(pgStatRunningInCollector ? LOG : WARNING,
2715 (errmsg("corrupted pgstat.stat file")));
2720 * If possible, check PID to verify still running
2722 if (check_pids && !IsBackendPid(beentry->procpid))
2725 * Note: we could send a BETERM message to tell the
2726 * collector to drop the entry, but I'm a bit worried
2727 * about race conditions. For now, just silently ignore
2728 * dead entries; they'll get recycled eventually anyway.
2731 /* Don't accept the entry */
2732 memset(beentry, 0, sizeof(PgStat_StatBeEntry));
2737 * Count backends per database here.
2739 dbentry = (PgStat_StatDBEntry *)
2740 hash_search(*dbhash,
2741 &(beentry->databaseid),
2745 dbentry->n_backends++;
2748 *numbackends = havebackends;
2753 * 'E' The EOF marker of a complete stats file.
2759 ereport(pgStatRunningInCollector ? LOG : WARNING,
2760 (errmsg("corrupted pgstat.stat file")));
2770 * If not done for this transaction, read the statistics collector
2771 * stats file into some hash tables.
2773 * Because we store the hash tables in TopTransactionContext, the result
2774 * is good for the entire current main transaction.
2776 * Inside the autovacuum process, the statfile is assumed to be valid
2777 * "forever", that is one iteration, within one database. This means
2778 * we only consider the statistics as they were when the autovacuum
2779 * iteration started.
2782 backend_read_statsfile(void)
2784 if (IsAutoVacuumProcess())
2786 /* already read it? */
2789 Assert(!pgStatRunningInCollector);
2790 pgstat_read_statsfile(&pgStatDBHash, InvalidOid,
2791 &pgStatBeTable, &pgStatNumBackends);
2795 TransactionId topXid = GetTopTransactionId();
2797 if (!TransactionIdEquals(pgStatDBHashXact, topXid))
2799 Assert(!pgStatRunningInCollector);
2800 pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId,
2801 &pgStatBeTable, &pgStatNumBackends);
2802 pgStatDBHashXact = topXid;
2809 * pgstat_recv_bestart() -
2811 * Process a backend startup message.
2815 pgstat_recv_bestart(PgStat_MsgBestart *msg, int len)
2817 PgStat_StatBeEntry *entry;
2820 * If the backend is known dead, we ignore the message -- we don't
2821 * want to update the backend entry's state since this BESTART
2822 * message refers to an old, dead backend
2824 if (pgstat_add_backend(&msg->m_hdr) != 0)
2827 entry = &(pgStatBeTable[msg->m_hdr.m_backendid - 1]);
2828 entry->userid = msg->m_userid;
2829 memcpy(&entry->clientaddr, &msg->m_clientaddr, sizeof(entry->clientaddr));
2830 entry->databaseid = msg->m_databaseid;
2835 * pgstat_recv_beterm() -
2837 * Process a backend termination message.
2841 pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len)
2843 pgstat_sub_backend(msg->m_hdr.m_procpid);
2847 * pgstat_recv_autovac() -
2849 * Process an autovacuum signalling message.
2853 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
2855 PgStat_StatDBEntry *dbentry;
2858 * Lookup the database in the hashtable. Don't create the entry if it
2859 * doesn't exist, because autovacuum may be processing a template
2860 * database. If this isn't the case, the database is most likely to
2861 * have an entry already. (If it doesn't, not much harm is done
2862 * anyway -- it'll get created as soon as somebody actually uses
2865 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2866 if (dbentry == NULL)
2870 * Store the last autovacuum time in the database entry.
2872 dbentry->last_autovac_time = msg->m_start_time;
2876 * pgstat_recv_vacuum() -
2878 * Process a VACUUM message.
2882 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
2884 PgStat_StatDBEntry *dbentry;
2885 PgStat_StatTabEntry *tabentry;
2890 * If we don't know about the database, ignore the message, because it
2891 * may be autovacuum processing a template database. But if the message
2892 * is for database InvalidOid, don't ignore it, because we are getting
2893 * a message from vacuuming a shared relation.
2895 create = (msg->m_databaseid == InvalidOid);
2897 dbentry = pgstat_get_db_entry(msg->m_databaseid, create);
2898 if (dbentry == NULL)
2901 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
2902 HASH_ENTER, &found);
2905 * If we are creating the entry, initialize it.
2909 tabentry->numscans = 0;
2911 tabentry->tuples_returned = 0;
2912 tabentry->tuples_fetched = 0;
2913 tabentry->tuples_inserted = 0;
2914 tabentry->tuples_updated = 0;
2915 tabentry->tuples_deleted = 0;
2917 tabentry->n_live_tuples = msg->m_tuples;
2918 tabentry->n_dead_tuples = 0;
2921 tabentry->last_anl_tuples = msg->m_tuples;
2923 tabentry->last_anl_tuples = 0;
2925 tabentry->blocks_fetched = 0;
2926 tabentry->blocks_hit = 0;
2928 tabentry->destroy = 0;
2932 tabentry->n_live_tuples = msg->m_tuples;
2933 tabentry->n_dead_tuples = 0;
2935 tabentry->last_anl_tuples = msg->m_tuples;
2940 * pgstat_recv_analyze() -
2942 * Process an ANALYZE message.
2946 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
2948 PgStat_StatDBEntry *dbentry;
2949 PgStat_StatTabEntry *tabentry;
2953 * Note that we do create the database entry here, as opposed to what
2954 * we do on AutovacStart and Vacuum messages. This is because
2955 * autovacuum never executes ANALYZE on template databases.
2957 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
2959 tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
2960 HASH_ENTER, &found);
2963 * If we are creating the entry, initialize it.
2967 tabentry->numscans = 0;
2969 tabentry->tuples_returned = 0;
2970 tabentry->tuples_fetched = 0;
2971 tabentry->tuples_inserted = 0;
2972 tabentry->tuples_updated = 0;
2973 tabentry->tuples_deleted = 0;
2975 tabentry->n_live_tuples = msg->m_live_tuples;
2976 tabentry->n_dead_tuples = msg->m_dead_tuples;
2977 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
2979 tabentry->blocks_fetched = 0;
2980 tabentry->blocks_hit = 0;
2982 tabentry->destroy = 0;
2986 tabentry->n_live_tuples = msg->m_live_tuples;
2987 tabentry->n_dead_tuples = msg->m_dead_tuples;
2988 tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
2993 * pgstat_recv_activity() -
2995 * Remember what the backend is doing.
2999 pgstat_recv_activity(PgStat_MsgActivity *msg, int len)
3001 PgStat_StatBeEntry *entry;
3004 * Here we check explicitly for 0 return, since we don't want to
3005 * mangle the activity of an active backend by a delayed packet from a
3008 if (pgstat_add_backend(&msg->m_hdr) != 0)
3011 entry = &(pgStatBeTable[msg->m_hdr.m_backendid - 1]);
3013 StrNCpy(entry->activity, msg->m_what, PGSTAT_ACTIVITY_SIZE);
3015 entry->activity_start_timestamp = GetCurrentTimestamp();
3020 * pgstat_recv_tabstat() -
3022 * Count what the backend has done.
3026 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
3028 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
3029 PgStat_StatDBEntry *dbentry;
3030 PgStat_StatTabEntry *tabentry;
3035 * Make sure the backend is counted for.
3037 if (pgstat_add_backend(&msg->m_hdr) < 0)
3040 dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3043 * If the database is marked for destroy, this is a delayed UDP packet
3044 * and not worth being counted.
3046 if (dbentry->destroy > 0)
3049 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
3050 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
3053 * Process all table entries in the message.
3055 for (i = 0; i < msg->m_nentries; i++)
3057 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3058 (void *) &(tabmsg[i].t_id),
3059 HASH_ENTER, &found);
3064 * If it's a new table entry, initialize counters to the
3065 * values we just got.
3067 tabentry->numscans = tabmsg[i].t_numscans;
3068 tabentry->tuples_returned = tabmsg[i].t_tuples_returned;
3069 tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched;
3070 tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted;
3071 tabentry->tuples_updated = tabmsg[i].t_tuples_updated;
3072 tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted;
3074 tabentry->n_live_tuples = tabmsg[i].t_tuples_inserted;
3075 tabentry->n_dead_tuples = tabmsg[i].t_tuples_updated +
3076 tabmsg[i].t_tuples_deleted;
3077 tabentry->last_anl_tuples = 0;
3079 tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched;
3080 tabentry->blocks_hit = tabmsg[i].t_blocks_hit;
3082 tabentry->destroy = 0;
3087 * Otherwise add the values to the existing entry.
3089 tabentry->numscans += tabmsg[i].t_numscans;
3090 tabentry->tuples_returned += tabmsg[i].t_tuples_returned;
3091 tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched;
3092 tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted;
3093 tabentry->tuples_updated += tabmsg[i].t_tuples_updated;
3094 tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted;
3096 tabentry->n_live_tuples += tabmsg[i].t_tuples_inserted;
3097 tabentry->n_dead_tuples += tabmsg[i].t_tuples_updated +
3098 tabmsg[i].t_tuples_deleted;
3100 tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched;
3101 tabentry->blocks_hit += tabmsg[i].t_blocks_hit;
3105 * And add the block IO to the database entry.
3107 dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched;
3108 dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit;
3114 * pgstat_recv_tabpurge() -
3116 * Arrange for dead table removal.
3120 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3122 PgStat_StatDBEntry *dbentry;
3123 PgStat_StatTabEntry *tabentry;
3127 * Make sure the backend is counted for.
3129 if (pgstat_add_backend(&msg->m_hdr) < 0)
3132 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3135 * No need to purge if we don't even know the database.
3137 if (!dbentry || !dbentry->tables)
3141 * If the database is marked for destroy, this is a delayed UDP packet
3142 * and the tables will go away at DB destruction.
3144 if (dbentry->destroy > 0)
3148 * Process all table entries in the message.
3150 for (i = 0; i < msg->m_nentries; i++)
3152 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3153 (void *) &(msg->m_tableid[i]),
3156 tabentry->destroy = PGSTAT_DESTROY_COUNT;
3162 * pgstat_recv_dropdb() -
3164 * Arrange for dead database removal
3168 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3170 PgStat_StatDBEntry *dbentry;
3173 * Make sure the backend is counted for.
3175 if (pgstat_add_backend(&msg->m_hdr) < 0)
3179 * Lookup the database in the hashtable.
3181 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3184 * Mark the database for destruction.
3187 dbentry->destroy = PGSTAT_DESTROY_COUNT;
3192 * pgstat_recv_resetcounter() -
3194 * Reset the statistics for the specified database.
3198 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3201 PgStat_StatDBEntry *dbentry;
3204 * Make sure the backend is counted for.
3206 if (pgstat_add_backend(&msg->m_hdr) < 0)
3210 * Lookup the database in the hashtable. Nothing to do if not there.
3212 dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3218 * We simply throw away all the database's table entries by
3219 * recreating a new hash table for them.
3221 if (dbentry->tables != NULL)
3222 hash_destroy(dbentry->tables);
3224 dbentry->tables = NULL;
3225 dbentry->n_xact_commit = 0;
3226 dbentry->n_xact_rollback = 0;
3227 dbentry->n_blocks_fetched = 0;
3228 dbentry->n_blocks_hit = 0;
3229 dbentry->destroy = 0;
3231 memset(&hash_ctl, 0, sizeof(hash_ctl));
3232 hash_ctl.keysize = sizeof(Oid);
3233 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3234 hash_ctl.hash = oid_hash;
3235 dbentry->tables = hash_create("Per-database table",
3236 PGSTAT_TAB_HASH_SIZE,
3238 HASH_ELEM | HASH_FUNCTION);