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-2004, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.82 2004/10/25 00:46:41 neilc 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/catname.h"
37 #include "catalog/pg_database.h"
38 #include "catalog/pg_shadow.h"
39 #include "libpq/libpq.h"
40 #include "libpq/pqsignal.h"
41 #include "mb/pg_wchar.h"
42 #include "miscadmin.h"
43 #include "postmaster/postmaster.h"
44 #include "storage/backendid.h"
45 #include "storage/ipc.h"
46 #include "storage/pg_shmem.h"
47 #include "storage/pmsignal.h"
48 #include "tcop/tcopprot.h"
49 #include "utils/hsearch.h"
50 #include "utils/memutils.h"
51 #include "utils/ps_status.h"
52 #include "utils/rel.h"
53 #include "utils/syscache.h"
57 * Paths for the statistics files. The %s is replaced with the
58 * installation's $PGDATA.
61 #define PGSTAT_STAT_FILENAME "%s/global/pgstat.stat"
62 #define PGSTAT_STAT_TMPFILE "%s/global/pgstat.tmp.%d"
68 #define PGSTAT_STAT_INTERVAL 500 /* How often to write the status
69 * file; in milliseconds. */
71 #define PGSTAT_DESTROY_DELAY 10000 /* How long to keep destroyed
72 * objects known, to give delayed
73 * UDP packets time to arrive; in
76 #define PGSTAT_DESTROY_COUNT (PGSTAT_DESTROY_DELAY / PGSTAT_STAT_INTERVAL)
78 #define PGSTAT_RESTART_INTERVAL 60 /* How often to attempt to restart
79 * a failed statistics collector;
83 * Amount of space reserved in pgstat_recvbuffer().
86 #define PGSTAT_RECVBUFFERSZ ((int) (1024 * sizeof(PgStat_Msg)))
89 * The initial size hints for the hash tables used in the collector.
92 #define PGSTAT_DB_HASH_SIZE 16
93 #define PGSTAT_BE_HASH_SIZE 512
94 #define PGSTAT_TAB_HASH_SIZE 512
101 bool pgstat_collect_startcollector = true;
102 bool pgstat_collect_resetonpmstart = true;
103 bool pgstat_collect_querystring = false;
104 bool pgstat_collect_tuplelevel = false;
105 bool pgstat_collect_blocklevel = false;
111 NON_EXEC_STATIC int pgStatSock = -1;
112 static int pgStatPipe[2];
113 static struct sockaddr_storage pgStatAddr;
115 static time_t last_pgstat_start_time;
117 static long pgStatNumMessages = 0;
119 static bool pgStatRunningInCollector = FALSE;
121 static int pgStatTabstatAlloc = 0;
122 static int pgStatTabstatUsed = 0;
123 static PgStat_MsgTabstat **pgStatTabstatMessages = NULL;
125 #define TABSTAT_QUANTUM 4 /* we alloc this many at a time */
127 static int pgStatXactCommit = 0;
128 static int pgStatXactRollback = 0;
130 static TransactionId pgStatDBHashXact = InvalidTransactionId;
131 static HTAB *pgStatDBHash = NULL;
132 static HTAB *pgStatBeDead = NULL;
133 static PgStat_StatBeEntry *pgStatBeTable = NULL;
134 static int pgStatNumBackends = 0;
136 static char pgStat_fname[MAXPGPATH];
137 static char pgStat_tmpfname[MAXPGPATH];
141 * Local function forward declarations
146 typedef enum STATS_PROCESS_TYPE
150 } STATS_PROCESS_TYPE;
152 static pid_t pgstat_forkexec(STATS_PROCESS_TYPE procType);
153 static void pgstat_parseArgs(int argc, char *argv[]);
156 NON_EXEC_STATIC void PgstatBufferMain(int argc, char *argv[]);
157 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
158 static void pgstat_recvbuffer(void);
159 static void pgstat_exit(SIGNAL_ARGS);
160 static void pgstat_die(SIGNAL_ARGS);
162 static int pgstat_add_backend(PgStat_MsgHdr *msg);
163 static void pgstat_sub_backend(int procpid);
164 static void pgstat_drop_database(Oid databaseid);
165 static void pgstat_write_statsfile(void);
166 static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
167 PgStat_StatBeEntry **betab,
169 static void backend_read_statsfile(void);
171 static void pgstat_setheader(PgStat_MsgHdr *hdr, int mtype);
172 static void pgstat_send(void *msg, int len);
174 static void pgstat_recv_bestart(PgStat_MsgBestart *msg, int len);
175 static void pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len);
176 static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len);
177 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
178 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
179 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
180 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
183 /* ------------------------------------------------------------
184 * Public functions called from postmaster follow
185 * ------------------------------------------------------------
191 * Called from postmaster at startup. Create the resources required
192 * by the statistics collector process. If unable to do so, do not
193 * fail --- better to let the postmaster start with stats collection
200 ACCEPT_TYPE_ARG3 alen;
201 struct addrinfo *addrs = NULL,
210 #define TESTBYTEVAL ((char) 199)
213 * Force start of collector daemon if something to collect
215 if (pgstat_collect_querystring ||
216 pgstat_collect_tuplelevel ||
217 pgstat_collect_blocklevel)
218 pgstat_collect_startcollector = true;
221 * Initialize the filename for the status reports. (In the
222 * EXEC_BACKEND case, this only sets the value in the postmaster. The
223 * collector subprocess will recompute the value for itself, and
224 * individual backends must do so also if they want to access the
227 snprintf(pgStat_fname, MAXPGPATH, PGSTAT_STAT_FILENAME, DataDir);
230 * If we don't have to start a collector or should reset the collected
231 * statistics on postmaster start, simply remove the file.
233 if (!pgstat_collect_startcollector || pgstat_collect_resetonpmstart)
234 unlink(pgStat_fname);
237 * Nothing else required if collector will not get started
239 if (!pgstat_collect_startcollector)
243 * Create the UDP socket for sending and receiving statistic messages
245 hints.ai_flags = AI_PASSIVE;
246 hints.ai_family = PF_UNSPEC;
247 hints.ai_socktype = SOCK_DGRAM;
248 hints.ai_protocol = 0;
249 hints.ai_addrlen = 0;
250 hints.ai_addr = NULL;
251 hints.ai_canonname = NULL;
252 hints.ai_next = NULL;
253 ret = getaddrinfo_all("localhost", NULL, &hints, &addrs);
257 (errmsg("could not resolve \"localhost\": %s",
258 gai_strerror(ret))));
263 * On some platforms, getaddrinfo_all() may return multiple addresses
264 * only one of which will actually work (eg, both IPv6 and IPv4
265 * addresses when kernel will reject IPv6). Worse, the failure may
266 * occur at the bind() or perhaps even connect() stage. So we must
267 * loop through the results till we find a working combination. We
268 * will generate LOG messages, but no error, for bogus combinations.
270 for (addr = addrs; addr; addr = addr->ai_next)
272 #ifdef HAVE_UNIX_SOCKETS
273 /* Ignore AF_UNIX sockets, if any are returned. */
274 if (addr->ai_family == AF_UNIX)
281 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
284 (errcode_for_socket_access(),
285 errmsg("could not create socket for statistics collector: %m")));
290 * Bind it to a kernel assigned port on localhost and get the
291 * assigned port via getsockname().
293 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
296 (errcode_for_socket_access(),
297 errmsg("could not bind socket for statistics collector: %m")));
298 closesocket(pgStatSock);
303 alen = sizeof(pgStatAddr);
304 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
307 (errcode_for_socket_access(),
308 errmsg("could not get address of socket for statistics collector: %m")));
309 closesocket(pgStatSock);
315 * Connect the socket to its own address. This saves a few cycles
316 * by not having to respecify the target address on every send.
317 * This also provides a kernel-level check that only packets from
318 * this same address will be received.
320 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
323 (errcode_for_socket_access(),
324 errmsg("could not connect socket for statistics collector: %m")));
325 closesocket(pgStatSock);
331 * Try to send and receive a one-byte test message on the socket.
332 * This is to catch situations where the socket can be created but
333 * will not actually pass data (for instance, because kernel
334 * packet filtering rules prevent it).
336 test_byte = TESTBYTEVAL;
337 if (send(pgStatSock, &test_byte, 1, 0) != 1)
340 (errcode_for_socket_access(),
341 errmsg("could not send test message on socket for statistics collector: %m")));
342 closesocket(pgStatSock);
348 * There could possibly be a little delay before the message can
349 * be received. We arbitrarily allow up to half a second before
350 * deciding it's broken.
352 for (;;) /* need a loop to handle EINTR */
355 FD_SET(pgStatSock, &rset);
358 sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
359 if (sel_res >= 0 || errno != EINTR)
365 (errcode_for_socket_access(),
366 errmsg("select() failed in statistics collector: %m")));
367 closesocket(pgStatSock);
371 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
374 * This is the case we actually think is likely, so take pains
375 * to give a specific message for it.
377 * errno will not be set meaningfully here, so don't use it.
380 (ERRCODE_CONNECTION_FAILURE,
381 errmsg("test message did not get through on socket for statistics collector")));
382 closesocket(pgStatSock);
387 test_byte++; /* just make sure variable is changed */
389 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
392 (errcode_for_socket_access(),
393 errmsg("could not receive test message on socket for statistics collector: %m")));
394 closesocket(pgStatSock);
399 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
402 (ERRCODE_INTERNAL_ERROR,
403 errmsg("incorrect test message transmission on socket for statistics collector")));
404 closesocket(pgStatSock);
409 /* If we get here, we have a working socket */
413 /* Did we find a working address? */
414 if (!addr || pgStatSock < 0)
417 (errcode_for_socket_access(),
418 errmsg("disabling statistics collector for lack of working socket")));
423 * Set the socket to non-blocking IO. This ensures that if the
424 * collector falls behind (despite the buffering process), statistics
425 * messages will be discarded; backends won't block waiting to send
426 * messages to the collector.
428 if (!set_noblock(pgStatSock))
431 (errcode_for_socket_access(),
432 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
436 freeaddrinfo_all(hints.ai_family, addrs);
442 freeaddrinfo_all(hints.ai_family, addrs);
445 closesocket(pgStatSock);
448 /* Adjust GUC variables to suppress useless activity */
449 pgstat_collect_startcollector = false;
450 pgstat_collect_querystring = false;
451 pgstat_collect_tuplelevel = false;
452 pgstat_collect_blocklevel = false;
459 * pgstat_forkexec() -
461 * Format up the arglist for, then fork and exec, statistics
462 * (buffer and collector) processes
465 pgstat_forkexec(STATS_PROCESS_TYPE procType)
471 char pgstatBuf[2][32];
473 av[ac++] = "postgres";
477 case STAT_PROC_BUFFER:
478 av[ac++] = "-forkbuf";
481 case STAT_PROC_COLLECTOR:
482 av[ac++] = "-forkcol";
489 av[ac++] = NULL; /* filled in by postmaster_forkexec */
491 /* postgres_exec_path is not passed by write_backend_variables */
492 av[ac++] = postgres_exec_path;
494 /* Pipe file ids (those not passed by write_backend_variables) */
495 snprintf(pgstatBuf[bufc++], 32, "%d", pgStatPipe[0]);
496 snprintf(pgstatBuf[bufc++], 32, "%d", pgStatPipe[1]);
498 /* Add to the arg list */
499 Assert(bufc <= lengthof(pgstatBuf));
500 for (i = 0; i < bufc; i++)
501 av[ac++] = pgstatBuf[i];
504 Assert(ac < lengthof(av));
506 return postmaster_forkexec(ac, av);
511 * pgstat_parseArgs() -
513 * Extract data from the arglist for exec'ed statistics
514 * (buffer and collector) processes
517 pgstat_parseArgs(int argc, char *argv[])
522 StrNCpy(postgres_exec_path, argv[argc++], MAXPGPATH);
523 pgStatPipe[0] = atoi(argv[argc++]);
524 pgStatPipe[1] = atoi(argv[argc++]);
526 #endif /* EXEC_BACKEND */
532 * Called from postmaster at startup or after an existing collector
533 * died. Attempt to fire up a fresh statistics collector.
535 * Returns PID of child process, or 0 if fail.
537 * Note: if fail, we will be called again from the postmaster main loop.
547 * Do nothing if no collector needed
549 if (!pgstat_collect_startcollector)
553 * Do nothing if too soon since last collector start. This is a
554 * safety valve to protect against continuous respawn attempts if the
555 * collector is dying immediately at launch. Note that since we will
556 * be re-called from the postmaster main loop, we will get another
559 curtime = time(NULL);
560 if ((unsigned int) (curtime - last_pgstat_start_time) <
561 (unsigned int) PGSTAT_RESTART_INTERVAL)
563 last_pgstat_start_time = curtime;
566 * Check that the socket is there, else pgstat_init failed.
571 (errmsg("statistics collector startup skipped")));
574 * We can only get here if someone tries to manually turn
575 * pgstat_collect_startcollector on after it had been off.
577 pgstat_collect_startcollector = false;
582 * Okay, fork off the collector.
589 /* Specific beos actions before backend startup */
590 beos_before_backend_startup();
594 switch ((pgStatPid = pgstat_forkexec(STAT_PROC_BUFFER)))
596 switch ((pgStatPid = fork()))
601 /* Specific beos actions */
602 beos_backend_startup_failed();
605 (errmsg("could not fork statistics buffer: %m")));
610 /* in postmaster child ... */
612 /* Specific beos actions after backend startup */
613 beos_backend_startup();
615 /* Close the postmaster's sockets */
616 ClosePostmasterPorts(false);
618 /* Drop our connection to postmaster's shared memory, as well */
619 PGSharedMemoryDetach();
621 PgstatBufferMain(0, NULL);
626 return (int) pgStatPid;
629 /* shouldn't get here */
637 * Called from postmaster to tell collector a backend terminated.
641 pgstat_beterm(int pid)
643 PgStat_MsgBeterm msg;
648 MemSet(&(msg.m_hdr), 0, sizeof(msg.m_hdr));
649 msg.m_hdr.m_type = PGSTAT_MTYPE_BETERM;
650 msg.m_hdr.m_procpid = pid;
652 pgstat_send(&msg, sizeof(msg));
656 /* ------------------------------------------------------------
657 * Public functions used by backends follow
658 *------------------------------------------------------------
665 * Tell the collector that this new backend is soon ready to process
666 * queries. Called from tcop/postgres.c before entering the mainloop.
672 PgStat_MsgBestart msg;
677 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_BESTART);
678 pgstat_send(&msg, sizeof(msg));
683 * pgstat_report_activity() -
685 * Called in tcop/postgres.c to tell the collector what the backend
686 * is actually doing (usually "<IDLE>" or the start of the query to
691 pgstat_report_activity(const char *what)
693 PgStat_MsgActivity msg;
696 if (!pgstat_collect_querystring || pgStatSock < 0)
700 len = pg_mbcliplen((const unsigned char *) what, len,
701 PGSTAT_ACTIVITY_SIZE - 1);
703 memcpy(msg.m_what, what, len);
704 msg.m_what[len] = '\0';
705 len += offsetof(PgStat_MsgActivity, m_what) +1;
707 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ACTIVITY);
708 pgstat_send(&msg, len);
713 * pgstat_report_tabstat() -
715 * Called from tcop/postgres.c to send the so far collected
716 * per table access statistics to the collector.
720 pgstat_report_tabstat(void)
724 if (pgStatSock < 0 ||
725 !(pgstat_collect_querystring ||
726 pgstat_collect_tuplelevel ||
727 pgstat_collect_blocklevel))
729 /* Not reporting stats, so just flush whatever we have */
730 pgStatTabstatUsed = 0;
735 * For each message buffer used during the last query set the header
736 * fields and send it out.
738 for (i = 0; i < pgStatTabstatUsed; i++)
740 PgStat_MsgTabstat *tsmsg = pgStatTabstatMessages[i];
744 n = tsmsg->m_nentries;
745 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
746 n * sizeof(PgStat_TableEntry);
748 tsmsg->m_xact_commit = pgStatXactCommit;
749 tsmsg->m_xact_rollback = pgStatXactRollback;
750 pgStatXactCommit = 0;
751 pgStatXactRollback = 0;
753 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
754 pgstat_send(tsmsg, len);
757 pgStatTabstatUsed = 0;
762 * pgstat_vacuum_tabstat() -
764 * Will tell the collector about objects he can get rid of.
768 pgstat_vacuum_tabstat(void)
776 HASH_SEQ_STATUS hstat;
777 PgStat_StatDBEntry *dbentry;
778 PgStat_StatTabEntry *tabentry;
781 PgStat_MsgTabpurge msg;
789 * If not done for this transaction, read the statistics collector
790 * stats file into some hash tables.
792 backend_read_statsfile();
795 * Lookup our own database entry
797 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
798 (void *) &MyDatabaseId,
803 if (dbentry->tables == NULL)
807 * Initialize our messages table counter to zero
812 * Check for all tables if they still exist.
814 hash_seq_init(&hstat, dbentry->tables);
815 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
818 * Check if this relation is still alive by looking up it's
819 * pg_class tuple in the system catalog cache.
821 reltup = SearchSysCache(RELOID,
822 ObjectIdGetDatum(tabentry->tableid),
824 if (HeapTupleIsValid(reltup))
826 ReleaseSysCache(reltup);
831 * Add this tables Oid to the message
833 msg.m_tableid[msg.m_nentries++] = tabentry->tableid;
837 * If the message is full, send it out and reinitialize ot zero
839 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
841 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
842 +msg.m_nentries * sizeof(Oid);
844 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
845 pgstat_send(&msg, len);
854 if (msg.m_nentries > 0)
856 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
857 +msg.m_nentries * sizeof(Oid);
859 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
860 pgstat_send(&msg, len);
864 * Read pg_database and remember the Oid's of all existing databases
868 dbidlist = (Oid *) palloc(sizeof(Oid) * dbidalloc);
870 dbrel = heap_openr(DatabaseRelationName, AccessShareLock);
871 dbscan = heap_beginscan(dbrel, SnapshotNow, 0, NULL);
872 while ((dbtup = heap_getnext(dbscan, ForwardScanDirection)) != NULL)
874 if (dbidused >= dbidalloc)
877 dbidlist = (Oid *) repalloc((char *) dbidlist,
878 sizeof(Oid) * dbidalloc);
880 dbidlist[dbidused++] = HeapTupleGetOid(dbtup);
882 heap_endscan(dbscan);
883 heap_close(dbrel, AccessShareLock);
886 * Search the database hash table for dead databases and tell the
887 * collector to drop them as well.
889 hash_seq_init(&hstat, pgStatDBHash);
890 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
892 Oid dbid = dbentry->databaseid;
894 for (i = 0; i < dbidused; i++)
896 if (dbidlist[i] == dbid)
903 if (dbid != InvalidOid)
906 pgstat_drop_database(dbid);
911 * Free the dbid list.
913 pfree((char *) dbidlist);
916 * Tell the caller how many removeable objects we found
923 * pgstat_drop_database() -
925 * Tell the collector that we just dropped a database.
926 * This is the only message that shouldn't get lost in space. Otherwise
927 * the collector will keep the statistics for the dead DB until his
928 * stats file got removed while the postmaster is down.
932 pgstat_drop_database(Oid databaseid)
934 PgStat_MsgDropdb msg;
939 msg.m_databaseid = databaseid;
941 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
942 pgstat_send(&msg, sizeof(msg));
947 * pgstat_reset_counters() -
949 * Tell the statistics collector to reset counters for our database.
953 pgstat_reset_counters(void)
955 PgStat_MsgResetcounter msg;
962 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
963 errmsg("must be superuser to reset statistics counters")));
965 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
966 pgstat_send(&msg, sizeof(msg));
973 * Send some junk data to the collector to increase traffic.
984 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
985 pgstat_send(&msg, sizeof(msg));
989 * Create or enlarge the pgStatTabstatMessages array
992 more_tabstat_space(void)
994 PgStat_MsgTabstat *newMessages;
995 PgStat_MsgTabstat **msgArray;
996 int newAlloc = pgStatTabstatAlloc + TABSTAT_QUANTUM;
999 /* Create (another) quantum of message buffers */
1000 newMessages = (PgStat_MsgTabstat *)
1001 malloc(sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1002 if (newMessages == NULL)
1005 (errcode(ERRCODE_OUT_OF_MEMORY),
1006 errmsg("out of memory")));
1010 /* Create or enlarge the pointer array */
1011 if (pgStatTabstatMessages == NULL)
1012 msgArray = (PgStat_MsgTabstat **)
1013 malloc(sizeof(PgStat_MsgTabstat *) * newAlloc);
1015 msgArray = (PgStat_MsgTabstat **)
1016 realloc(pgStatTabstatMessages,
1017 sizeof(PgStat_MsgTabstat *) * newAlloc);
1018 if (msgArray == NULL)
1022 (errcode(ERRCODE_OUT_OF_MEMORY),
1023 errmsg("out of memory")));
1027 MemSet(newMessages, 0, sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1028 for (i = 0; i < TABSTAT_QUANTUM; i++)
1029 msgArray[pgStatTabstatAlloc + i] = newMessages++;
1030 pgStatTabstatMessages = msgArray;
1031 pgStatTabstatAlloc = newAlloc;
1037 * pgstat_initstats() -
1039 * Called from various places usually dealing with initialization
1040 * of Relation or Scan structures. The data placed into these
1041 * structures from here tell where later to count for buffer reads,
1042 * scans and tuples fetched.
1046 pgstat_initstats(PgStat_Info *stats, Relation rel)
1048 Oid rel_id = rel->rd_id;
1049 PgStat_TableEntry *useent;
1050 PgStat_MsgTabstat *tsmsg;
1055 * Initialize data not to count at all.
1057 stats->tabentry = NULL;
1058 stats->no_stats = FALSE;
1059 stats->heap_scan_counted = FALSE;
1060 stats->index_scan_counted = FALSE;
1062 if (pgStatSock < 0 ||
1063 !(pgstat_collect_tuplelevel ||
1064 pgstat_collect_blocklevel))
1066 stats->no_stats = TRUE;
1071 * Search the already-used message slots for this relation.
1073 for (mb = 0; mb < pgStatTabstatUsed; mb++)
1075 tsmsg = pgStatTabstatMessages[mb];
1077 for (i = tsmsg->m_nentries; --i >= 0;)
1079 if (tsmsg->m_entry[i].t_id == rel_id)
1081 stats->tabentry = (void *) &(tsmsg->m_entry[i]);
1086 if (tsmsg->m_nentries >= PGSTAT_NUM_TABENTRIES)
1090 * Not found, but found a message buffer with an empty slot
1091 * instead. Fine, let's use this one.
1093 i = tsmsg->m_nentries++;
1094 useent = &tsmsg->m_entry[i];
1095 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1096 useent->t_id = rel_id;
1097 stats->tabentry = (void *) useent;
1102 * If we ran out of message buffers, we just allocate more.
1104 if (pgStatTabstatUsed >= pgStatTabstatAlloc)
1106 if (!more_tabstat_space())
1108 stats->no_stats = TRUE;
1111 Assert(pgStatTabstatUsed < pgStatTabstatAlloc);
1115 * Use the first entry of the next message buffer.
1117 mb = pgStatTabstatUsed++;
1118 tsmsg = pgStatTabstatMessages[mb];
1119 tsmsg->m_nentries = 1;
1120 useent = &tsmsg->m_entry[0];
1121 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1122 useent->t_id = rel_id;
1123 stats->tabentry = (void *) useent;
1128 * pgstat_count_xact_commit() -
1130 * Called from access/transam/xact.c to count transaction commits.
1134 pgstat_count_xact_commit(void)
1136 if (!(pgstat_collect_querystring ||
1137 pgstat_collect_tuplelevel ||
1138 pgstat_collect_blocklevel))
1144 * If there was no relation activity yet, just make one existing
1145 * message buffer used without slots, causing the next report to tell
1146 * new xact-counters.
1148 if (pgStatTabstatAlloc == 0)
1150 if (!more_tabstat_space())
1153 if (pgStatTabstatUsed == 0)
1155 pgStatTabstatUsed++;
1156 pgStatTabstatMessages[0]->m_nentries = 0;
1162 * pgstat_count_xact_rollback() -
1164 * Called from access/transam/xact.c to count transaction rollbacks.
1168 pgstat_count_xact_rollback(void)
1170 if (!(pgstat_collect_querystring ||
1171 pgstat_collect_tuplelevel ||
1172 pgstat_collect_blocklevel))
1175 pgStatXactRollback++;
1178 * If there was no relation activity yet, just make one existing
1179 * message buffer used without slots, causing the next report to tell
1180 * new xact-counters.
1182 if (pgStatTabstatAlloc == 0)
1184 if (!more_tabstat_space())
1187 if (pgStatTabstatUsed == 0)
1189 pgStatTabstatUsed++;
1190 pgStatTabstatMessages[0]->m_nentries = 0;
1196 * pgstat_fetch_stat_dbentry() -
1198 * Support function for the SQL-callable pgstat* functions. Returns
1199 * the collected statistics for one database or NULL. NULL doesn't mean
1200 * that the database doesn't exist, it is just not yet known by the
1201 * collector, so the caller is better off to report ZERO instead.
1204 PgStat_StatDBEntry *
1205 pgstat_fetch_stat_dbentry(Oid dbid)
1207 PgStat_StatDBEntry *dbentry;
1210 * If not done for this transaction, read the statistics collector
1211 * stats file into some hash tables.
1213 backend_read_statsfile();
1216 * Lookup the requested database
1218 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1221 if (dbentry == NULL)
1229 * pgstat_fetch_stat_tabentry() -
1231 * Support function for the SQL-callable pgstat* functions. Returns
1232 * the collected statistics for one table or NULL. NULL doesn't mean
1233 * that the table doesn't exist, it is just not yet known by the
1234 * collector, so the caller is better off to report ZERO instead.
1237 PgStat_StatTabEntry *
1238 pgstat_fetch_stat_tabentry(Oid relid)
1240 PgStat_StatDBEntry *dbentry;
1241 PgStat_StatTabEntry *tabentry;
1244 * If not done for this transaction, read the statistics collector
1245 * stats file into some hash tables.
1247 backend_read_statsfile();
1250 * Lookup our database.
1252 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1253 (void *) &MyDatabaseId,
1255 if (dbentry == NULL)
1259 * Now inside the DB's table hash table lookup the requested one.
1261 if (dbentry->tables == NULL)
1263 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1266 if (tabentry == NULL)
1274 * pgstat_fetch_stat_beentry() -
1276 * Support function for the SQL-callable pgstat* functions. Returns
1277 * the actual activity slot of one active backend. The caller is
1278 * responsible for a check if the actual user is permitted to see
1279 * that info (especially the querystring).
1282 PgStat_StatBeEntry *
1283 pgstat_fetch_stat_beentry(int beid)
1285 backend_read_statsfile();
1287 if (beid < 1 || beid > pgStatNumBackends)
1290 return &pgStatBeTable[beid - 1];
1295 * pgstat_fetch_stat_numbackends() -
1297 * Support function for the SQL-callable pgstat* functions. Returns
1298 * the maximum current backend id.
1302 pgstat_fetch_stat_numbackends(void)
1304 backend_read_statsfile();
1306 return pgStatNumBackends;
1311 /* ------------------------------------------------------------
1312 * Local support functions follow
1313 * ------------------------------------------------------------
1318 * pgstat_setheader() -
1320 * Set common header fields in a statistics message
1324 pgstat_setheader(PgStat_MsgHdr *hdr, int mtype)
1326 hdr->m_type = mtype;
1327 hdr->m_backendid = MyBackendId;
1328 hdr->m_procpid = MyProcPid;
1329 hdr->m_databaseid = MyDatabaseId;
1330 hdr->m_userid = GetSessionUserId();
1337 * Send out one statistics message to the collector
1341 pgstat_send(void *msg, int len)
1346 ((PgStat_MsgHdr *) msg)->m_size = len;
1348 send(pgStatSock, msg, len, 0);
1349 /* We deliberately ignore any error from send() */
1354 * PgstatBufferMain() -
1356 * Start up the statistics buffer process. This is the body of the
1357 * postmaster child process.
1359 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1362 NON_EXEC_STATIC void
1363 PgstatBufferMain(int argc, char *argv[])
1365 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
1367 MyProcPid = getpid(); /* reset MyProcPid */
1369 /* Lose the postmaster's on-exit routines */
1373 * Ignore all signals usually bound to some action in the postmaster,
1374 * except for SIGCHLD and SIGQUIT --- see pgstat_recvbuffer.
1376 pqsignal(SIGHUP, SIG_IGN);
1377 pqsignal(SIGINT, SIG_IGN);
1378 pqsignal(SIGTERM, SIG_IGN);
1379 pqsignal(SIGQUIT, pgstat_exit);
1380 pqsignal(SIGALRM, SIG_IGN);
1381 pqsignal(SIGPIPE, SIG_IGN);
1382 pqsignal(SIGUSR1, SIG_IGN);
1383 pqsignal(SIGUSR2, SIG_IGN);
1384 pqsignal(SIGCHLD, pgstat_die);
1385 pqsignal(SIGTTIN, SIG_DFL);
1386 pqsignal(SIGTTOU, SIG_DFL);
1387 pqsignal(SIGCONT, SIG_DFL);
1388 pqsignal(SIGWINCH, SIG_DFL);
1389 /* unblock will happen in pgstat_recvbuffer */
1392 pgstat_parseArgs(argc, argv);
1396 * Start a buffering process to read from the socket, so we have a
1397 * little more time to process incoming messages.
1399 * NOTE: the process structure is: postmaster is parent of buffer process
1400 * is parent of collector process. This way, the buffer can detect
1401 * collector failure via SIGCHLD, whereas otherwise it wouldn't notice
1402 * collector failure until it tried to write on the pipe. That would
1403 * mean that after the postmaster started a new collector, we'd have
1404 * two buffer processes competing to read from the UDP socket --- not
1407 if (pgpipe(pgStatPipe) < 0)
1409 (errcode_for_socket_access(),
1410 errmsg("could not create pipe for statistics buffer: %m")));
1413 /* child becomes collector process */
1414 switch (pgstat_forkexec(STAT_PROC_COLLECTOR))
1421 (errmsg("could not fork statistics collector: %m")));
1423 #ifndef EXEC_BACKEND
1425 /* child becomes collector process */
1426 PgstatCollectorMain(0, NULL);
1431 /* parent becomes buffer process */
1432 closesocket(pgStatPipe[0]);
1433 pgstat_recvbuffer();
1440 * PgstatCollectorMain() -
1442 * Start up the statistics collector itself. This is the body of the
1443 * postmaster grandchild process.
1445 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1448 NON_EXEC_STATIC void
1449 PgstatCollectorMain(int argc, char *argv[])
1456 struct timeval timeout;
1457 struct timeval next_statwrite;
1458 bool need_statwrite;
1461 MyProcPid = getpid(); /* reset MyProcPid */
1464 * Reset signal handling. With the exception of restoring default
1465 * SIGCHLD and SIGQUIT handling, this is a no-op in the
1466 * non-EXEC_BACKEND case because we'll have inherited these settings
1467 * from the buffer process; but it's not a no-op for EXEC_BACKEND.
1469 pqsignal(SIGHUP, SIG_IGN);
1470 pqsignal(SIGINT, SIG_IGN);
1471 pqsignal(SIGTERM, SIG_IGN);
1472 pqsignal(SIGQUIT, SIG_IGN);
1473 pqsignal(SIGALRM, SIG_IGN);
1474 pqsignal(SIGPIPE, SIG_IGN);
1475 pqsignal(SIGUSR1, SIG_IGN);
1476 pqsignal(SIGUSR2, SIG_IGN);
1477 pqsignal(SIGCHLD, SIG_DFL);
1478 pqsignal(SIGTTIN, SIG_DFL);
1479 pqsignal(SIGTTOU, SIG_DFL);
1480 pqsignal(SIGCONT, SIG_DFL);
1481 pqsignal(SIGWINCH, SIG_DFL);
1482 PG_SETMASK(&UnBlockSig);
1485 pgstat_parseArgs(argc, argv);
1488 /* Close unwanted files */
1489 closesocket(pgStatPipe[1]);
1490 closesocket(pgStatSock);
1493 * Identify myself via ps
1495 init_ps_display("stats collector process", "", "");
1499 * Initialize filenames needed for status reports.
1501 snprintf(pgStat_fname, MAXPGPATH, PGSTAT_STAT_FILENAME, DataDir);
1502 /* tmpfname need only be set correctly in this process */
1503 snprintf(pgStat_tmpfname, MAXPGPATH, PGSTAT_STAT_TMPFILE,
1504 DataDir, (int)getpid());
1507 * Arrange to write the initial status file right away
1509 gettimeofday(&next_statwrite, NULL);
1510 need_statwrite = TRUE;
1513 * Read in an existing statistics stats file or initialize the stats
1516 pgStatRunningInCollector = TRUE;
1517 pgstat_read_statsfile(&pgStatDBHash, InvalidOid, NULL, NULL);
1520 * Create the dead backend hashtable
1522 memset(&hash_ctl, 0, sizeof(hash_ctl));
1523 hash_ctl.keysize = sizeof(int);
1524 hash_ctl.entrysize = sizeof(PgStat_StatBeDead);
1525 hash_ctl.hash = tag_hash;
1526 pgStatBeDead = hash_create("Dead Backends", PGSTAT_BE_HASH_SIZE,
1527 &hash_ctl, HASH_ELEM | HASH_FUNCTION);
1530 * Create the known backends table
1532 pgStatBeTable = (PgStat_StatBeEntry *) malloc(
1533 sizeof(PgStat_StatBeEntry) * MaxBackends);
1534 if (pgStatBeTable == NULL)
1536 (errcode(ERRCODE_OUT_OF_MEMORY),
1537 errmsg("out of memory in statistics collector --- abort")));
1538 memset(pgStatBeTable, 0, sizeof(PgStat_StatBeEntry) * MaxBackends);
1540 readPipe = pgStatPipe[0];
1543 * Process incoming messages and handle all the reporting stuff until
1544 * there are no more messages.
1549 * If we need to write the status file again (there have been
1550 * changes in the statistics since we wrote it last) calculate the
1551 * timeout until we have to do so.
1557 gettimeofday(&now, NULL);
1558 /* avoid assuming that tv_sec is signed */
1559 if (now.tv_sec > next_statwrite.tv_sec ||
1560 (now.tv_sec == next_statwrite.tv_sec &&
1561 now.tv_usec >= next_statwrite.tv_usec))
1564 timeout.tv_usec = 0;
1568 timeout.tv_sec = next_statwrite.tv_sec - now.tv_sec;
1569 timeout.tv_usec = next_statwrite.tv_usec - now.tv_usec;
1570 if (timeout.tv_usec < 0)
1573 timeout.tv_usec += 1000000;
1579 * Setup the descriptor set for select(2)
1582 FD_SET(readPipe, &rfds);
1585 * Now wait for something to do.
1587 nready = select(readPipe + 1, &rfds, NULL, NULL,
1588 (need_statwrite) ? &timeout : NULL);
1594 (errcode_for_socket_access(),
1595 errmsg("select() failed in statistics collector: %m")));
1599 * If there are no descriptors ready, our timeout for writing the
1600 * stats file happened.
1604 pgstat_write_statsfile();
1605 need_statwrite = FALSE;
1611 * Check if there is a new statistics message to collect.
1613 if (FD_ISSET(readPipe, &rfds))
1616 * We may need to issue multiple read calls in case the buffer
1617 * process didn't write the message in a single write, which
1618 * is possible since it dumps its buffer bytewise. In any
1619 * case, we'd need two reads since we don't know the message
1623 int targetlen = sizeof(PgStat_MsgHdr); /* initial */
1624 bool pipeEOF = false;
1626 while (nread < targetlen)
1628 len = piperead(readPipe, ((char *) &msg) + nread,
1635 (errcode_for_socket_access(),
1636 errmsg("could not read from statistics collector pipe: %m")));
1638 if (len == 0) /* EOF on the pipe! */
1644 if (nread == sizeof(PgStat_MsgHdr))
1646 /* we have the header, compute actual msg length */
1647 targetlen = msg.msg_hdr.m_size;
1648 if (targetlen < (int) sizeof(PgStat_MsgHdr) ||
1649 targetlen > (int) sizeof(msg))
1652 * Bogus message length implies that we got out of
1653 * sync with the buffer process somehow. Abort so
1654 * that we can restart both processes.
1657 (errmsg("invalid statistics message length")));
1663 * EOF on the pipe implies that the buffer process exited.
1664 * Fall out of outer loop.
1670 * Distribute the message to the specific function handling
1673 switch (msg.msg_hdr.m_type)
1675 case PGSTAT_MTYPE_DUMMY:
1678 case PGSTAT_MTYPE_BESTART:
1679 pgstat_recv_bestart((PgStat_MsgBestart *) &msg, nread);
1682 case PGSTAT_MTYPE_BETERM:
1683 pgstat_recv_beterm((PgStat_MsgBeterm *) &msg, nread);
1686 case PGSTAT_MTYPE_TABSTAT:
1687 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, nread);
1690 case PGSTAT_MTYPE_TABPURGE:
1691 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, nread);
1694 case PGSTAT_MTYPE_ACTIVITY:
1695 pgstat_recv_activity((PgStat_MsgActivity *) &msg, nread);
1698 case PGSTAT_MTYPE_DROPDB:
1699 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, nread);
1702 case PGSTAT_MTYPE_RESETCOUNTER:
1703 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
1712 * Globally count messages.
1714 pgStatNumMessages++;
1717 * If this is the first message after we wrote the stats file
1718 * the last time, setup the timeout that it'd be written.
1720 if (!need_statwrite)
1722 gettimeofday(&next_statwrite, NULL);
1723 next_statwrite.tv_usec += ((PGSTAT_STAT_INTERVAL) * 1000);
1724 next_statwrite.tv_sec += (next_statwrite.tv_usec / 1000000);
1725 next_statwrite.tv_usec %= 1000000;
1726 need_statwrite = TRUE;
1731 * Note that we do NOT check for postmaster exit inside the loop;
1732 * only EOF on the buffer pipe causes us to fall out. This
1733 * ensures we don't exit prematurely if there are still a few
1734 * messages in the buffer or pipe at postmaster shutdown.
1739 * Okay, we saw EOF on the buffer pipe, so there are no more messages
1740 * to process. If the buffer process quit because of postmaster
1741 * shutdown, we want to save the final stats to reuse at next startup.
1742 * But if the buffer process failed, it seems best not to (there may
1743 * even now be a new collector firing up, and we don't want it to read
1744 * a partially-rewritten stats file).
1746 if (!PostmasterIsAlive(false))
1747 pgstat_write_statsfile();
1752 * pgstat_recvbuffer() -
1754 * This is the body of the separate buffering process. Its only
1755 * purpose is to receive messages from the UDP socket as fast as
1756 * possible and forward them over a pipe into the collector itself.
1757 * If the collector is slow to absorb messages, they are buffered here.
1761 pgstat_recvbuffer(void)
1765 struct timeval timeout;
1766 int writePipe = pgStatPipe[1];
1772 PgStat_Msg input_buffer;
1774 int msg_send = 0; /* next send index in buffer */
1775 int msg_recv = 0; /* next receive index */
1776 int msg_have = 0; /* number of bytes stored */
1777 bool overflow = false;
1780 * Identify myself via ps
1782 init_ps_display("stats buffer process", "", "");
1786 * We want to die if our child collector process does. There are two
1787 * ways we might notice that it has died: receive SIGCHLD, or get a
1788 * write failure on the pipe leading to the child. We can set SIGPIPE
1789 * to kill us here. Our SIGCHLD handler was already set up before we
1790 * forked (must do it that way, else it's a race condition).
1792 pqsignal(SIGPIPE, SIG_DFL);
1793 PG_SETMASK(&UnBlockSig);
1796 * Set the write pipe to nonblock mode, so that we cannot block when
1797 * the collector falls behind.
1799 if (!set_noblock(writePipe))
1801 (errcode_for_socket_access(),
1802 errmsg("could not set statistics collector pipe to nonblocking mode: %m")));
1805 * Allocate the message buffer
1807 msgbuffer = (char *) malloc(PGSTAT_RECVBUFFERSZ);
1808 if (msgbuffer == NULL)
1810 (errcode(ERRCODE_OUT_OF_MEMORY),
1811 errmsg("out of memory in statistics collector --- abort")));
1823 * As long as we have buffer space we add the socket to the read
1826 if (msg_have <= (int) (PGSTAT_RECVBUFFERSZ - sizeof(PgStat_Msg)))
1828 FD_SET(pgStatSock, &rfds);
1837 (errmsg("statistics buffer is full")));
1843 * If we have messages to write out, we add the pipe to the write
1848 FD_SET(writePipe, &wfds);
1849 if (writePipe > maxfd)
1854 * Wait for some work to do; but not for more than 10 seconds.
1855 * (This determines how quickly we will shut down after an
1856 * ungraceful postmaster termination; so it needn't be very fast.)
1858 timeout.tv_sec = 10;
1859 timeout.tv_usec = 0;
1861 nready = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
1867 (errcode_for_socket_access(),
1868 errmsg("select() failed in statistics buffer: %m")));
1872 * If there is a message on the socket, read it and check for
1875 if (FD_ISSET(pgStatSock, &rfds))
1877 len = recv(pgStatSock, (char *) &input_buffer,
1878 sizeof(PgStat_Msg), 0);
1881 (errcode_for_socket_access(),
1882 errmsg("could not read statistics message: %m")));
1885 * We ignore messages that are smaller than our common header
1887 if (len < sizeof(PgStat_MsgHdr))
1891 * The received length must match the length in the header
1893 if (input_buffer.msg_hdr.m_size != len)
1897 * O.K. - we accept this message. Copy it to the circular
1903 xfr = PGSTAT_RECVBUFFERSZ - msg_recv;
1907 memcpy(msgbuffer + msg_recv,
1908 ((char *) &input_buffer) + frm,
1911 if (msg_recv == PGSTAT_RECVBUFFERSZ)
1920 * If the collector is ready to receive, write some data into his
1921 * pipe. We may or may not be able to write all that we have.
1923 * NOTE: if what we have is less than PIPE_BUF bytes but more than
1924 * the space available in the pipe buffer, most kernels will
1925 * refuse to write any of it, and will return EAGAIN. This means
1926 * we will busy-loop until the situation changes (either because
1927 * the collector caught up, or because more data arrives so that
1928 * we have more than PIPE_BUF bytes buffered). This is not good,
1929 * but is there any way around it? We have no way to tell when
1930 * the collector has caught up...
1932 if (FD_ISSET(writePipe, &wfds))
1934 xfr = PGSTAT_RECVBUFFERSZ - msg_send;
1938 len = pipewrite(writePipe, msgbuffer + msg_send, xfr);
1941 if (errno == EINTR || errno == EAGAIN)
1942 continue; /* not enough space in pipe */
1944 (errcode_for_socket_access(),
1945 errmsg("could not write to statistics collector pipe: %m")));
1947 /* NB: len < xfr is okay */
1949 if (msg_send == PGSTAT_RECVBUFFERSZ)
1955 * Make sure we forwarded all messages before we check for
1956 * postmaster termination.
1958 if (msg_have != 0 || FD_ISSET(pgStatSock, &rfds))
1962 * If the postmaster has terminated, we die too. (This is no
1963 * longer the normal exit path, however.)
1965 if (!PostmasterIsAlive(true))
1970 /* SIGQUIT signal handler for buffer process */
1972 pgstat_exit(SIGNAL_ARGS)
1975 * For now, we just nail the doors shut and get out of town. It might
1976 * be cleaner to allow any pending messages to be sent, but that
1977 * creates a tradeoff against speed of exit.
1982 /* SIGCHLD signal handler for buffer process */
1984 pgstat_die(SIGNAL_ARGS)
1991 * pgstat_add_backend() -
1993 * Support function to keep our backend list up to date.
1997 pgstat_add_backend(PgStat_MsgHdr *msg)
1999 PgStat_StatDBEntry *dbentry;
2000 PgStat_StatBeEntry *beentry;
2001 PgStat_StatBeDead *deadbe;
2005 * Check that the backend ID is valid
2007 if (msg->m_backendid < 1 || msg->m_backendid > MaxBackends)
2010 (errmsg("invalid server process ID %d", msg->m_backendid)));
2015 * Get the slot for this backendid.
2017 beentry = &pgStatBeTable[msg->m_backendid - 1];
2018 if (beentry->databaseid != InvalidOid)
2021 * If the slot contains the PID of this backend, everything is
2022 * fine and we got nothing to do.
2024 if (beentry->procpid == msg->m_procpid)
2029 * Lookup if this backend is known to be dead. This can be caused due
2030 * to messages arriving in the wrong order - i.e. Postmaster's BETERM
2031 * message might have arrived before we received all the backends
2032 * stats messages, or even a new backend with the same backendid was
2033 * faster in sending his BESTART.
2035 * If the backend is known to be dead, we ignore this add.
2037 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2038 (void *) &(msg->m_procpid),
2044 * Backend isn't known to be dead. If it's slot is currently used, we
2045 * have to kick out the old backend.
2047 if (beentry->databaseid != InvalidOid)
2048 pgstat_sub_backend(beentry->procpid);
2051 * Put this new backend into the slot.
2053 beentry->databaseid = msg->m_databaseid;
2054 beentry->procpid = msg->m_procpid;
2055 beentry->userid = msg->m_userid;
2056 beentry->activity_start_sec = 0;
2057 beentry->activity_start_usec = 0;
2058 MemSet(beentry->activity, 0, PGSTAT_ACTIVITY_SIZE);
2061 * Lookup or create the database entry for this backends DB.
2063 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2064 (void *) &(msg->m_databaseid),
2065 HASH_ENTER, &found);
2066 if (dbentry == NULL)
2068 (errcode(ERRCODE_OUT_OF_MEMORY),
2069 errmsg("out of memory in statistics collector --- abort")));
2072 * If not found, initialize the new one.
2078 dbentry->tables = NULL;
2079 dbentry->n_xact_commit = 0;
2080 dbentry->n_xact_rollback = 0;
2081 dbentry->n_blocks_fetched = 0;
2082 dbentry->n_blocks_hit = 0;
2083 dbentry->n_connects = 0;
2084 dbentry->destroy = 0;
2086 memset(&hash_ctl, 0, sizeof(hash_ctl));
2087 hash_ctl.keysize = sizeof(Oid);
2088 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2089 hash_ctl.hash = tag_hash;
2090 dbentry->tables = hash_create("Per-database table",
2091 PGSTAT_TAB_HASH_SIZE,
2093 HASH_ELEM | HASH_FUNCTION);
2097 * Count number of connects to the database
2099 dbentry->n_connects++;
2106 * pgstat_sub_backend() -
2108 * Remove a backend from the actual backends list.
2112 pgstat_sub_backend(int procpid)
2115 PgStat_StatBeDead *deadbe;
2119 * Search in the known-backends table for the slot containing this
2122 for (i = 0; i < MaxBackends; i++)
2124 if (pgStatBeTable[i].databaseid != InvalidOid &&
2125 pgStatBeTable[i].procpid == procpid)
2128 * That's him. Add an entry to the known to be dead backends.
2129 * Due to possible misorder in the arrival of UDP packets it's
2130 * possible that even if we know the backend is dead, there
2131 * could still be messages queued that arrive later. Those
2132 * messages must not cause our number of backends statistics
2133 * to get screwed up, so we remember for a couple of seconds
2134 * that this PID is dead and ignore them (only the counting of
2135 * backends, not the table access stats they sent).
2137 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2143 (errcode(ERRCODE_OUT_OF_MEMORY),
2144 errmsg("out of memory in statistics collector --- abort")));
2148 deadbe->backendid = i + 1;
2149 deadbe->destroy = PGSTAT_DESTROY_COUNT;
2153 * Declare the backend slot empty.
2155 pgStatBeTable[i].databaseid = InvalidOid;
2161 * No big problem if not found. This can happen if UDP messages arrive
2162 * out of order here.
2168 * pgstat_write_statsfile() -
2174 pgstat_write_statsfile(void)
2176 HASH_SEQ_STATUS hstat;
2177 HASH_SEQ_STATUS tstat;
2178 PgStat_StatDBEntry *dbentry;
2179 PgStat_StatTabEntry *tabentry;
2180 PgStat_StatBeDead *deadbe;
2185 * Open the statistics temp file to write out the current values.
2187 fpout = fopen(pgStat_tmpfname, PG_BINARY_W);
2191 (errcode_for_file_access(),
2192 errmsg("could not open temporary statistics file \"%s\": %m",
2198 * Walk through the database table.
2200 hash_seq_init(&hstat, pgStatDBHash);
2201 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2204 * If this database is marked destroyed, count down and do so if
2207 if (dbentry->destroy > 0)
2209 if (--(dbentry->destroy) == 0)
2211 if (dbentry->tables != NULL)
2212 hash_destroy(dbentry->tables);
2214 if (hash_search(pgStatDBHash,
2215 (void *) &(dbentry->databaseid),
2216 HASH_REMOVE, NULL) == NULL)
2218 (errmsg("database hash table corrupted "
2219 "during cleanup --- abort")));
2223 * Don't include statistics for it.
2229 * Write out the DB line including the number of life backends.
2232 fwrite(dbentry, sizeof(PgStat_StatDBEntry), 1, fpout);
2235 * Walk through the databases access stats per table.
2237 hash_seq_init(&tstat, dbentry->tables);
2238 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2241 * If table entry marked for destruction, same as above for
2242 * the database entry.
2244 if (tabentry->destroy > 0)
2246 if (--(tabentry->destroy) == 0)
2248 if (hash_search(dbentry->tables,
2249 (void *) &(tabentry->tableid),
2250 HASH_REMOVE, NULL) == NULL)
2253 (errmsg("tables hash table for "
2254 "database %u corrupted during "
2255 "cleanup --- abort",
2256 dbentry->databaseid)));
2263 * At least we think this is still a life table. Print it's
2267 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2271 * Mark the end of this DB
2277 * Write out the known running backends to the stats file.
2281 fwrite(&i, sizeof(i), 1, fpout);
2283 for (i = 0; i < MaxBackends; i++)
2285 if (pgStatBeTable[i].databaseid != InvalidOid)
2288 fwrite(&pgStatBeTable[i], sizeof(PgStat_StatBeEntry), 1, fpout);
2293 * No more output to be done. Close the temp file and replace the old
2294 * pgstat.stat with it.
2297 if (fclose(fpout) < 0)
2300 (errcode_for_file_access(),
2301 errmsg("could not close temporary statistics file \"%s\": %m",
2306 if (rename(pgStat_tmpfname, pgStat_fname) < 0)
2309 (errcode_for_file_access(),
2310 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2311 pgStat_tmpfname, pgStat_fname)));
2316 * Clear out the dead backends table
2318 hash_seq_init(&hstat, pgStatBeDead);
2319 while ((deadbe = (PgStat_StatBeDead *) hash_seq_search(&hstat)) != NULL)
2322 * Count down the destroy delay and remove entries where it
2325 if (--(deadbe->destroy) <= 0)
2327 if (hash_search(pgStatBeDead,
2328 (void *) &(deadbe->procpid),
2329 HASH_REMOVE, NULL) == NULL)
2332 (errmsg("dead-server-process hash table corrupted "
2333 "during cleanup --- abort")));
2341 * pgstat_read_statsfile() -
2343 * Reads in an existing statistics collector and initializes the
2344 * databases hash table (who's entries point to the tables hash tables)
2345 * and the current backend table.
2349 pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
2350 PgStat_StatBeEntry **betab, int *numbackends)
2352 PgStat_StatDBEntry *dbentry;
2353 PgStat_StatDBEntry dbbuf;
2354 PgStat_StatTabEntry *tabentry;
2355 PgStat_StatTabEntry tabbuf;
2357 HTAB *tabhash = NULL;
2359 int maxbackends = 0;
2360 int havebackends = 0;
2362 MemoryContext use_mcxt;
2366 * If running in the collector we use the DynaHashCxt memory context.
2367 * If running in a backend, we use the TopTransactionContext instead,
2368 * so the caller must only know the last XactId when this call
2369 * happened to know if his tables are still valid or already gone!
2371 if (pgStatRunningInCollector)
2378 use_mcxt = TopTransactionContext;
2379 mcxt_flags = HASH_CONTEXT;
2383 * Create the DB hashtable
2385 memset(&hash_ctl, 0, sizeof(hash_ctl));
2386 hash_ctl.keysize = sizeof(Oid);
2387 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2388 hash_ctl.hash = tag_hash;
2389 hash_ctl.hcxt = use_mcxt;
2390 *dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2391 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2394 * Initialize the number of known backends to zero, just in case we do
2395 * a silent error return below.
2397 if (numbackends != NULL)
2403 * In EXEC_BACKEND case, we won't have inherited pgStat_fname from
2404 * postmaster, so compute it first time through.
2407 if (pgStat_fname[0] == '\0')
2409 Assert(DataDir != NULL);
2410 snprintf(pgStat_fname, MAXPGPATH, PGSTAT_STAT_FILENAME, DataDir);
2415 * Try to open the status file. If it doesn't exist, the backends
2416 * simply return zero for anything and the collector simply starts
2417 * from scratch with empty counters.
2419 if ((fpin = fopen(pgStat_fname, PG_BINARY_R)) == NULL)
2423 * We found an existing collector stats file. Read it and put all the
2424 * hashtable entries into place.
2428 switch (fgetc(fpin))
2431 * 'D' A PgStat_StatDBEntry struct describing a database
2432 * follows. Subsequently, zero to many 'T' entries will
2433 * follow until a 'd' is encountered.
2436 if (fread(&dbbuf, 1, sizeof(dbbuf), fpin) != sizeof(dbbuf))
2438 ereport(pgStatRunningInCollector ? LOG : WARNING,
2439 (errmsg("corrupted pgstat.stat file")));
2445 * Add to the DB hash
2447 dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
2448 (void *) &dbbuf.databaseid,
2451 if (dbentry == NULL)
2455 (errcode(ERRCODE_OUT_OF_MEMORY),
2456 errmsg("out of memory")));
2460 ereport(pgStatRunningInCollector ? LOG : WARNING,
2461 (errmsg("corrupted pgstat.stat file")));
2466 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2467 dbentry->tables = NULL;
2468 dbentry->destroy = 0;
2469 dbentry->n_backends = 0;
2472 * Don't collect tables if not the requested DB
2474 if (onlydb != InvalidOid && onlydb != dbbuf.databaseid)
2477 memset(&hash_ctl, 0, sizeof(hash_ctl));
2478 hash_ctl.keysize = sizeof(Oid);
2479 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2480 hash_ctl.hash = tag_hash;
2481 hash_ctl.hcxt = use_mcxt;
2484 dbentry->tables = hash_create("Per-database table",
2485 PGSTAT_TAB_HASH_SIZE,
2487 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2497 * Arrange that following 'T's add entries to this
2498 * databases tables hash table.
2500 tabhash = dbentry->tables;
2504 * 'd' End of this database.
2511 * 'T' A PgStat_StatTabEntry follows.
2514 if (fread(&tabbuf, 1, sizeof(tabbuf), fpin) != sizeof(tabbuf))
2516 ereport(pgStatRunningInCollector ? LOG : WARNING,
2517 (errmsg("corrupted pgstat.stat file")));
2523 * Skip if table belongs to a not requested database.
2525 if (tabhash == NULL)
2528 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2529 (void *) &tabbuf.tableid,
2530 HASH_ENTER, &found);
2531 if (tabentry == NULL)
2535 (errcode(ERRCODE_OUT_OF_MEMORY),
2536 errmsg("out of memory")));
2541 ereport(pgStatRunningInCollector ? LOG : WARNING,
2542 (errmsg("corrupted pgstat.stat file")));
2547 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2551 * 'M' The maximum number of backends to expect follows.
2554 if (betab == NULL || numbackends == NULL)
2559 if (fread(&maxbackends, 1, sizeof(maxbackends), fpin) !=
2560 sizeof(maxbackends))
2562 ereport(pgStatRunningInCollector ? LOG : WARNING,
2563 (errmsg("corrupted pgstat.stat file")));
2567 if (maxbackends == 0)
2574 * Allocate space (in TopTransactionContext too) for the
2577 if (use_mcxt == NULL)
2578 *betab = (PgStat_StatBeEntry *) malloc(
2579 sizeof(PgStat_StatBeEntry) * maxbackends);
2581 *betab = (PgStat_StatBeEntry *) MemoryContextAlloc(
2583 sizeof(PgStat_StatBeEntry) * maxbackends);
2587 * 'B' A PgStat_StatBeEntry follows.
2590 if (betab == NULL || numbackends == NULL)
2602 * Read it directly into the table.
2604 if (fread(&(*betab)[havebackends], 1,
2605 sizeof(PgStat_StatBeEntry), fpin) !=
2606 sizeof(PgStat_StatBeEntry))
2608 ereport(pgStatRunningInCollector ? LOG : WARNING,
2609 (errmsg("corrupted pgstat.stat file")));
2615 * Count backends per database here.
2617 dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
2618 (void *) &((*betab)[havebackends].databaseid),
2621 dbentry->n_backends++;
2624 if (numbackends != 0)
2625 *numbackends = havebackends;
2626 if (havebackends >= maxbackends)
2634 * 'E' The EOF marker of a complete stats file.
2641 ereport(pgStatRunningInCollector ? LOG : WARNING,
2642 (errmsg("corrupted pgstat.stat file")));
2652 * If not done for this transaction, read the statistics collector
2653 * stats file into some hash tables.
2655 * Because we store the hash tables in TopTransactionContext, the result
2656 * is good for the entire current main transaction.
2659 backend_read_statsfile(void)
2661 TransactionId topXid = GetTopTransactionId();
2663 if (!TransactionIdEquals(pgStatDBHashXact, topXid))
2665 Assert(!pgStatRunningInCollector);
2666 pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId,
2667 &pgStatBeTable, &pgStatNumBackends);
2668 pgStatDBHashXact = topXid;
2674 * pgstat_recv_bestart() -
2676 * Process a backend startup message.
2680 pgstat_recv_bestart(PgStat_MsgBestart *msg, int len)
2682 pgstat_add_backend(&msg->m_hdr);
2687 * pgstat_recv_beterm() -
2689 * Process a backend termination message.
2693 pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len)
2695 pgstat_sub_backend(msg->m_hdr.m_procpid);
2700 * pgstat_recv_activity() -
2702 * Remember what the backend is doing.
2706 pgstat_recv_activity(PgStat_MsgActivity *msg, int len)
2708 PgStat_StatBeEntry *entry;
2711 * Here we check explicitly for 0 return, since we don't want to
2712 * mangle the activity of an active backend by a delayed packet from a
2715 if (pgstat_add_backend(&msg->m_hdr) != 0)
2718 entry = &(pgStatBeTable[msg->m_hdr.m_backendid - 1]);
2720 StrNCpy(entry->activity, msg->m_what, PGSTAT_ACTIVITY_SIZE);
2722 entry->activity_start_sec =
2723 GetCurrentAbsoluteTimeUsec(&entry->activity_start_usec);
2728 * pgstat_recv_tabstat() -
2730 * Count what the backend has done.
2734 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
2736 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
2737 PgStat_StatDBEntry *dbentry;
2738 PgStat_StatTabEntry *tabentry;
2743 * Make sure the backend is counted for.
2745 if (pgstat_add_backend(&msg->m_hdr) < 0)
2749 * Lookup the database in the hashtable.
2751 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2752 (void *) &(msg->m_hdr.m_databaseid),
2758 * If the database is marked for destroy, this is a delayed UDP packet
2759 * and not worth being counted.
2761 if (dbentry->destroy > 0)
2764 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
2765 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2768 * Process all table entries in the message.
2770 for (i = 0; i < msg->m_nentries; i++)
2772 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2773 (void *) &(tabmsg[i].t_id),
2774 HASH_ENTER, &found);
2775 if (tabentry == NULL)
2777 (errcode(ERRCODE_OUT_OF_MEMORY),
2778 errmsg("out of memory in statistics collector --- abort")));
2783 * If it's a new table entry, initialize counters to the
2784 * values we just got.
2786 tabentry->numscans = tabmsg[i].t_numscans;
2787 tabentry->tuples_returned = tabmsg[i].t_tuples_returned;
2788 tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched;
2789 tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted;
2790 tabentry->tuples_updated = tabmsg[i].t_tuples_updated;
2791 tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted;
2792 tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched;
2793 tabentry->blocks_hit = tabmsg[i].t_blocks_hit;
2795 tabentry->destroy = 0;
2800 * Otherwise add the values to the existing entry.
2802 tabentry->numscans += tabmsg[i].t_numscans;
2803 tabentry->tuples_returned += tabmsg[i].t_tuples_returned;
2804 tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched;
2805 tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted;
2806 tabentry->tuples_updated += tabmsg[i].t_tuples_updated;
2807 tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted;
2808 tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched;
2809 tabentry->blocks_hit += tabmsg[i].t_blocks_hit;
2813 * And add the block IO to the database entry.
2815 dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched;
2816 dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit;
2822 * pgstat_recv_tabpurge() -
2824 * Arrange for dead table removal.
2828 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
2830 PgStat_StatDBEntry *dbentry;
2831 PgStat_StatTabEntry *tabentry;
2835 * Make sure the backend is counted for.
2837 if (pgstat_add_backend(&msg->m_hdr) < 0)
2841 * Lookup the database in the hashtable.
2843 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2844 (void *) &(msg->m_hdr.m_databaseid),
2850 * If the database is marked for destroy, this is a delayed UDP packet
2851 * and the tables will go away at DB destruction.
2853 if (dbentry->destroy > 0)
2857 * Process all table entries in the message.
2859 for (i = 0; i < msg->m_nentries; i++)
2861 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2862 (void *) &(msg->m_tableid[i]),
2865 tabentry->destroy = PGSTAT_DESTROY_COUNT;
2871 * pgstat_recv_dropdb() -
2873 * Arrange for dead database removal
2877 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
2879 PgStat_StatDBEntry *dbentry;
2882 * Make sure the backend is counted for.
2884 if (pgstat_add_backend(&msg->m_hdr) < 0)
2888 * Lookup the database in the hashtable.
2890 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2891 (void *) &(msg->m_databaseid),
2897 * Mark the database for destruction.
2899 dbentry->destroy = PGSTAT_DESTROY_COUNT;
2904 * pgstat_recv_dropdb() -
2906 * Arrange for dead database removal
2910 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
2913 PgStat_StatDBEntry *dbentry;
2916 * Make sure the backend is counted for.
2918 if (pgstat_add_backend(&msg->m_hdr) < 0)
2922 * Lookup the database in the hashtable.
2924 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2925 (void *) &(msg->m_hdr.m_databaseid),
2931 * We simply throw away all the databases table entries by recreating
2932 * a new hash table for them.
2934 if (dbentry->tables != NULL)
2935 hash_destroy(dbentry->tables);
2937 dbentry->tables = NULL;
2938 dbentry->n_xact_commit = 0;
2939 dbentry->n_xact_rollback = 0;
2940 dbentry->n_blocks_fetched = 0;
2941 dbentry->n_blocks_hit = 0;
2942 dbentry->n_connects = 0;
2943 dbentry->destroy = 0;
2945 memset(&hash_ctl, 0, sizeof(hash_ctl));
2946 hash_ctl.keysize = sizeof(Oid);
2947 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2948 hash_ctl.hash = tag_hash;
2949 dbentry->tables = hash_create("Per-database table",
2950 PGSTAT_TAB_HASH_SIZE,
2952 HASH_ELEM | HASH_FUNCTION);