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-2003, PostgreSQL Global Development Group
16 * $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.77 2004/07/01 00:50:36 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/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;
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[]);
157 NON_EXEC_STATIC void PgstatBufferMain(int argc, char *argv[]);
158 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
159 static void pgstat_recvbuffer(void);
160 static void pgstat_exit(SIGNAL_ARGS);
161 static void pgstat_die(SIGNAL_ARGS);
163 static int pgstat_add_backend(PgStat_MsgHdr *msg);
164 static void pgstat_sub_backend(int procpid);
165 static void pgstat_drop_database(Oid databaseid);
166 static void pgstat_write_statsfile(void);
167 static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
168 PgStat_StatBeEntry **betab,
170 static void backend_read_statsfile(void);
172 static void pgstat_setheader(PgStat_MsgHdr *hdr, int mtype);
173 static void pgstat_send(void *msg, int len);
175 static void pgstat_recv_bestart(PgStat_MsgBestart *msg, int len);
176 static void pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len);
177 static void pgstat_recv_activity(PgStat_MsgActivity *msg, int len);
178 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
179 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
180 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
181 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
184 /* ------------------------------------------------------------
185 * Public functions called from postmaster follow
186 * ------------------------------------------------------------
192 * Called from postmaster at startup. Create the resources required
193 * by the statistics collector process. If unable to do so, do not
194 * fail --- better to let the postmaster start with stats collection
201 ACCEPT_TYPE_ARG3 alen;
202 struct addrinfo *addrs = NULL,
211 #define TESTBYTEVAL ((char) 199)
214 * Force start of collector daemon if something to collect
216 if (pgstat_collect_querystring ||
217 pgstat_collect_tuplelevel ||
218 pgstat_collect_blocklevel)
219 pgstat_collect_startcollector = true;
222 * Initialize the filename for the status reports. (In the EXEC_BACKEND
223 * case, this only sets the value in the postmaster. The collector
224 * subprocess will recompute the value for itself, and individual
225 * backends must do so also if they want to access the file.)
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 addresses
265 * when kernel will reject IPv6). Worse, the failure may occur at the
266 * bind() or perhaps even connect() stage. So we must loop through the
267 * results till we find a working combination. We will generate LOG
268 * 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)
280 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
283 (errcode_for_socket_access(),
284 errmsg("could not create socket for statistics collector: %m")));
289 * Bind it to a kernel assigned port on localhost and get the assigned
290 * port via getsockname().
292 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
295 (errcode_for_socket_access(),
296 errmsg("could not bind socket for statistics collector: %m")));
297 closesocket(pgStatSock);
302 alen = sizeof(pgStatAddr);
303 if (getsockname(pgStatSock, (struct sockaddr *) &pgStatAddr, &alen) < 0)
306 (errcode_for_socket_access(),
307 errmsg("could not get address of socket for statistics collector: %m")));
308 closesocket(pgStatSock);
314 * Connect the socket to its own address. This saves a few cycles by
315 * not having to respecify the target address on every send. This also
316 * provides a kernel-level check that only packets from this same
317 * address will be received.
319 if (connect(pgStatSock, (struct sockaddr *) &pgStatAddr, alen) < 0)
322 (errcode_for_socket_access(),
323 errmsg("could not connect socket for statistics collector: %m")));
324 closesocket(pgStatSock);
330 * Try to send and receive a one-byte test message on the socket.
331 * This is to catch situations where the socket can be created but
332 * will not actually pass data (for instance, because kernel packet
333 * filtering rules prevent it).
335 test_byte = TESTBYTEVAL;
336 if (send(pgStatSock, &test_byte, 1, 0) != 1)
339 (errcode_for_socket_access(),
340 errmsg("could not send test message on socket for statistics collector: %m")));
341 closesocket(pgStatSock);
347 * There could possibly be a little delay before the message can be
348 * received. We arbitrarily allow up to half a second before deciding
351 for (;;) /* need a loop to handle EINTR */
354 FD_SET(pgStatSock, &rset);
357 sel_res = select(pgStatSock+1, &rset, NULL, NULL, &tv);
358 if (sel_res >= 0 || errno != EINTR)
364 (errcode_for_socket_access(),
365 errmsg("select() failed in statistics collector: %m")));
366 closesocket(pgStatSock);
370 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
373 * This is the case we actually think is likely, so take pains to
374 * give a specific message for it.
376 * errno will not be set meaningfully here, so don't use it.
379 (ERRCODE_CONNECTION_FAILURE,
380 errmsg("test message did not get through on socket for statistics collector")));
381 closesocket(pgStatSock);
386 test_byte++; /* just make sure variable is changed */
388 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
391 (errcode_for_socket_access(),
392 errmsg("could not receive test message on socket for statistics collector: %m")));
393 closesocket(pgStatSock);
398 if (test_byte != TESTBYTEVAL) /* strictly paranoia ... */
401 (ERRCODE_INTERNAL_ERROR,
402 errmsg("incorrect test message transmission on socket for statistics collector")));
403 closesocket(pgStatSock);
408 /* If we get here, we have a working socket */
412 /* Did we find a working address? */
413 if (!addr || pgStatSock < 0)
416 (errcode_for_socket_access(),
417 errmsg("disabling statistics collector for lack of working socket")));
422 * Set the socket to non-blocking IO. This ensures that if the
423 * collector falls behind (despite the buffering process), statistics
424 * messages will be discarded; backends won't block waiting to send
425 * messages to the collector.
427 if (!set_noblock(pgStatSock))
430 (errcode_for_socket_access(),
431 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
435 freeaddrinfo_all(hints.ai_family, addrs);
441 freeaddrinfo_all(hints.ai_family, addrs);
444 closesocket(pgStatSock);
447 /* Adjust GUC variables to suppress useless activity */
448 pgstat_collect_startcollector = false;
449 pgstat_collect_querystring = false;
450 pgstat_collect_tuplelevel = false;
451 pgstat_collect_blocklevel = false;
458 * pgstat_forkexec() -
460 * Format up the arglist for, then fork and exec, statistics
461 * (buffer and collector) processes
464 pgstat_forkexec(STATS_PROCESS_TYPE procType)
467 int ac = 0, bufc = 0, i;
468 char pgstatBuf[2][32];
470 av[ac++] = "postgres";
474 case STAT_PROC_BUFFER:
475 av[ac++] = "-forkbuf";
478 case STAT_PROC_COLLECTOR:
479 av[ac++] = "-forkcol";
486 av[ac++] = NULL; /* filled in by postmaster_forkexec */
488 /* postgres_exec_path is not passed by write_backend_variables */
489 av[ac++] = postgres_exec_path;
491 /* Pipe file ids (those not passed by write_backend_variables) */
492 snprintf(pgstatBuf[bufc++],32,"%d",pgStatPipe[0]);
493 snprintf(pgstatBuf[bufc++],32,"%d",pgStatPipe[1]);
495 /* Add to the arg list */
496 Assert(bufc <= lengthof(pgstatBuf));
497 for (i = 0; i < bufc; i++)
498 av[ac++] = pgstatBuf[i];
501 Assert(ac < lengthof(av));
503 return postmaster_forkexec(ac, av);
508 * pgstat_parseArgs() -
510 * Extract data from the arglist for exec'ed statistics
511 * (buffer and collector) processes
514 pgstat_parseArgs(int argc, char *argv[])
519 StrNCpy(postgres_exec_path, argv[argc++], MAXPGPATH);
520 pgStatPipe[0] = atoi(argv[argc++]);
521 pgStatPipe[1] = atoi(argv[argc++]);
524 #endif /* EXEC_BACKEND */
530 * Called from postmaster at startup or after an existing collector
531 * died. Attempt to fire up a fresh statistics collector.
533 * Returns PID of child process, or 0 if fail.
535 * Note: if fail, we will be called again from the postmaster main loop.
545 * Do nothing if no collector needed
547 if (!pgstat_collect_startcollector)
551 * Do nothing if too soon since last collector start. This is a
552 * safety valve to protect against continuous respawn attempts if the
553 * collector is dying immediately at launch. Note that since we will
554 * be re-called from the postmaster main loop, we will get another
557 curtime = time(NULL);
558 if ((unsigned int) (curtime - last_pgstat_start_time) <
559 (unsigned int) PGSTAT_RESTART_INTERVAL)
561 last_pgstat_start_time = curtime;
564 * Check that the socket is there, else pgstat_init failed.
569 (errmsg("statistics collector startup skipped")));
572 * We can only get here if someone tries to manually turn
573 * pgstat_collect_startcollector on after it had been off.
575 pgstat_collect_startcollector = false;
580 * Okay, fork off the collector.
587 /* Specific beos actions before backend startup */
588 beos_before_backend_startup();
592 switch ((pgStatPid = pgstat_forkexec(STAT_PROC_BUFFER)))
594 switch ((pgStatPid = fork()))
599 /* Specific beos actions */
600 beos_backend_startup_failed();
603 (errmsg("could not fork statistics buffer: %m")));
608 /* in postmaster child ... */
610 /* Specific beos actions after backend startup */
611 beos_backend_startup();
613 /* Close the postmaster's sockets */
614 ClosePostmasterPorts();
616 /* Drop our connection to postmaster's shared memory, as well */
617 PGSharedMemoryDetach();
619 PgstatBufferMain(0, NULL);
624 return (int) pgStatPid;
627 /* shouldn't get here */
635 * Called from postmaster to tell collector a backend terminated.
639 pgstat_beterm(int pid)
641 PgStat_MsgBeterm msg;
646 MemSet(&(msg.m_hdr), 0, sizeof(msg.m_hdr));
647 msg.m_hdr.m_type = PGSTAT_MTYPE_BETERM;
648 msg.m_hdr.m_procpid = pid;
650 pgstat_send(&msg, sizeof(msg));
654 /* ------------------------------------------------------------
655 * Public functions used by backends follow
656 *------------------------------------------------------------
663 * Tell the collector that this new backend is soon ready to process
664 * queries. Called from tcop/postgres.c before entering the mainloop.
670 PgStat_MsgBestart msg;
675 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_BESTART);
676 pgstat_send(&msg, sizeof(msg));
681 * pgstat_report_activity() -
683 * Called in tcop/postgres.c to tell the collector what the backend
684 * is actually doing (usually "<IDLE>" or the start of the query to
689 pgstat_report_activity(const char *what)
691 PgStat_MsgActivity msg;
694 if (!pgstat_collect_querystring || pgStatSock < 0)
698 len = pg_mbcliplen((const unsigned char *) what, len,
699 PGSTAT_ACTIVITY_SIZE - 1);
701 memcpy(msg.m_what, what, len);
702 msg.m_what[len] = '\0';
703 len += offsetof(PgStat_MsgActivity, m_what) +1;
705 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ACTIVITY);
706 pgstat_send(&msg, len);
711 * pgstat_report_tabstat() -
713 * Called from tcop/postgres.c to send the so far collected
714 * per table access statistics to the collector.
718 pgstat_report_tabstat(void)
722 if (pgStatSock < 0 ||
723 !(pgstat_collect_querystring ||
724 pgstat_collect_tuplelevel ||
725 pgstat_collect_blocklevel))
727 /* Not reporting stats, so just flush whatever we have */
728 pgStatTabstatUsed = 0;
733 * For each message buffer used during the last query set the header
734 * fields and send it out.
736 for (i = 0; i < pgStatTabstatUsed; i++)
738 PgStat_MsgTabstat *tsmsg = pgStatTabstatMessages[i];
742 n = tsmsg->m_nentries;
743 len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
744 n * sizeof(PgStat_TableEntry);
746 tsmsg->m_xact_commit = pgStatXactCommit;
747 tsmsg->m_xact_rollback = pgStatXactRollback;
748 pgStatXactCommit = 0;
749 pgStatXactRollback = 0;
751 pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
752 pgstat_send(tsmsg, len);
755 pgStatTabstatUsed = 0;
760 * pgstat_vacuum_tabstat() -
762 * Will tell the collector about objects he can get rid of.
766 pgstat_vacuum_tabstat(void)
774 HASH_SEQ_STATUS hstat;
775 PgStat_StatDBEntry *dbentry;
776 PgStat_StatTabEntry *tabentry;
779 PgStat_MsgTabpurge msg;
787 * If not done for this transaction, read the statistics collector
788 * stats file into some hash tables.
790 backend_read_statsfile();
793 * Lookup our own database entry
795 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
796 (void *) &MyDatabaseId,
801 if (dbentry->tables == NULL)
805 * Initialize our messages table counter to zero
810 * Check for all tables if they still exist.
812 hash_seq_init(&hstat, dbentry->tables);
813 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
816 * Check if this relation is still alive by looking up it's
817 * pg_class tuple in the system catalog cache.
819 reltup = SearchSysCache(RELOID,
820 ObjectIdGetDatum(tabentry->tableid),
822 if (HeapTupleIsValid(reltup))
824 ReleaseSysCache(reltup);
829 * Add this tables Oid to the message
831 msg.m_tableid[msg.m_nentries++] = tabentry->tableid;
835 * If the message is full, send it out and reinitialize ot zero
837 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
839 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
840 +msg.m_nentries * sizeof(Oid);
842 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
843 pgstat_send(&msg, len);
852 if (msg.m_nentries > 0)
854 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
855 +msg.m_nentries * sizeof(Oid);
857 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
858 pgstat_send(&msg, len);
862 * Read pg_database and remember the Oid's of all existing databases
866 dbidlist = (Oid *) palloc(sizeof(Oid) * dbidalloc);
868 dbrel = heap_openr(DatabaseRelationName, AccessShareLock);
869 dbscan = heap_beginscan(dbrel, SnapshotNow, 0, NULL);
870 while ((dbtup = heap_getnext(dbscan, ForwardScanDirection)) != NULL)
872 if (dbidused >= dbidalloc)
875 dbidlist = (Oid *) repalloc((char *) dbidlist,
876 sizeof(Oid) * dbidalloc);
878 dbidlist[dbidused++] = HeapTupleGetOid(dbtup);
880 heap_endscan(dbscan);
881 heap_close(dbrel, AccessShareLock);
884 * Search the database hash table for dead databases and tell the
885 * collector to drop them as well.
887 hash_seq_init(&hstat, pgStatDBHash);
888 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
890 Oid dbid = dbentry->databaseid;
892 for (i = 0; i < dbidused; i++)
894 if (dbidlist[i] == dbid)
901 if (dbid != InvalidOid)
904 pgstat_drop_database(dbid);
909 * Free the dbid list.
911 pfree((char *) dbidlist);
914 * Tell the caller how many removeable objects we found
921 * pgstat_drop_database() -
923 * Tell the collector that we just dropped a database.
924 * This is the only message that shouldn't get lost in space. Otherwise
925 * the collector will keep the statistics for the dead DB until his
926 * stats file got removed while the postmaster is down.
930 pgstat_drop_database(Oid databaseid)
932 PgStat_MsgDropdb msg;
937 msg.m_databaseid = databaseid;
939 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
940 pgstat_send(&msg, sizeof(msg));
945 * pgstat_reset_counters() -
947 * Tell the statistics collector to reset counters for our database.
951 pgstat_reset_counters(void)
953 PgStat_MsgResetcounter msg;
960 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
961 errmsg("must be superuser to reset statistics counters")));
963 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
964 pgstat_send(&msg, sizeof(msg));
971 * Send some junk data to the collector to increase traffic.
982 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
983 pgstat_send(&msg, sizeof(msg));
987 * Create or enlarge the pgStatTabstatMessages array
990 more_tabstat_space(void)
992 PgStat_MsgTabstat *newMessages;
993 PgStat_MsgTabstat **msgArray;
994 int newAlloc = pgStatTabstatAlloc + TABSTAT_QUANTUM;
997 /* Create (another) quantum of message buffers */
998 newMessages = (PgStat_MsgTabstat *)
999 malloc(sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1000 if (newMessages == NULL)
1003 (errcode(ERRCODE_OUT_OF_MEMORY),
1004 errmsg("out of memory")));
1008 /* Create or enlarge the pointer array */
1009 if (pgStatTabstatMessages == NULL)
1010 msgArray = (PgStat_MsgTabstat **)
1011 malloc(sizeof(PgStat_MsgTabstat *) * newAlloc);
1013 msgArray = (PgStat_MsgTabstat **)
1014 realloc(pgStatTabstatMessages,
1015 sizeof(PgStat_MsgTabstat *) * newAlloc);
1016 if (msgArray == NULL)
1020 (errcode(ERRCODE_OUT_OF_MEMORY),
1021 errmsg("out of memory")));
1025 MemSet(newMessages, 0, sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1026 for (i = 0; i < TABSTAT_QUANTUM; i++)
1027 msgArray[pgStatTabstatAlloc + i] = newMessages++;
1028 pgStatTabstatMessages = msgArray;
1029 pgStatTabstatAlloc = newAlloc;
1035 * pgstat_initstats() -
1037 * Called from various places usually dealing with initialization
1038 * of Relation or Scan structures. The data placed into these
1039 * structures from here tell where later to count for buffer reads,
1040 * scans and tuples fetched.
1044 pgstat_initstats(PgStat_Info *stats, Relation rel)
1046 Oid rel_id = rel->rd_id;
1047 PgStat_TableEntry *useent;
1048 PgStat_MsgTabstat *tsmsg;
1053 * Initialize data not to count at all.
1055 stats->tabentry = NULL;
1056 stats->no_stats = FALSE;
1057 stats->heap_scan_counted = FALSE;
1058 stats->index_scan_counted = FALSE;
1060 if (pgStatSock < 0 ||
1061 !(pgstat_collect_tuplelevel ||
1062 pgstat_collect_blocklevel))
1064 stats->no_stats = TRUE;
1069 * Search the already-used message slots for this relation.
1071 for (mb = 0; mb < pgStatTabstatUsed; mb++)
1073 tsmsg = pgStatTabstatMessages[mb];
1075 for (i = tsmsg->m_nentries; --i >= 0; )
1077 if (tsmsg->m_entry[i].t_id == rel_id)
1079 stats->tabentry = (void *) &(tsmsg->m_entry[i]);
1084 if (tsmsg->m_nentries >= PGSTAT_NUM_TABENTRIES)
1088 * Not found, but found a message buffer with an empty slot
1089 * instead. Fine, let's use this one.
1091 i = tsmsg->m_nentries++;
1092 useent = &tsmsg->m_entry[i];
1093 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1094 useent->t_id = rel_id;
1095 stats->tabentry = (void *) useent;
1100 * If we ran out of message buffers, we just allocate more.
1102 if (pgStatTabstatUsed >= pgStatTabstatAlloc)
1104 if (!more_tabstat_space())
1106 stats->no_stats = TRUE;
1109 Assert(pgStatTabstatUsed < pgStatTabstatAlloc);
1113 * Use the first entry of the next message buffer.
1115 mb = pgStatTabstatUsed++;
1116 tsmsg = pgStatTabstatMessages[mb];
1117 tsmsg->m_nentries = 1;
1118 useent = &tsmsg->m_entry[0];
1119 MemSet(useent, 0, sizeof(PgStat_TableEntry));
1120 useent->t_id = rel_id;
1121 stats->tabentry = (void *) useent;
1126 * pgstat_count_xact_commit() -
1128 * Called from access/transam/xact.c to count transaction commits.
1132 pgstat_count_xact_commit(void)
1134 if (!(pgstat_collect_querystring ||
1135 pgstat_collect_tuplelevel ||
1136 pgstat_collect_blocklevel))
1142 * If there was no relation activity yet, just make one existing
1143 * message buffer used without slots, causing the next report to tell
1144 * new xact-counters.
1146 if (pgStatTabstatAlloc == 0)
1148 if (!more_tabstat_space())
1151 if (pgStatTabstatUsed == 0)
1153 pgStatTabstatUsed++;
1154 pgStatTabstatMessages[0]->m_nentries = 0;
1160 * pgstat_count_xact_rollback() -
1162 * Called from access/transam/xact.c to count transaction rollbacks.
1166 pgstat_count_xact_rollback(void)
1168 if (!(pgstat_collect_querystring ||
1169 pgstat_collect_tuplelevel ||
1170 pgstat_collect_blocklevel))
1173 pgStatXactRollback++;
1176 * If there was no relation activity yet, just make one existing
1177 * message buffer used without slots, causing the next report to tell
1178 * new xact-counters.
1180 if (pgStatTabstatAlloc == 0)
1182 if (!more_tabstat_space())
1185 if (pgStatTabstatUsed == 0)
1187 pgStatTabstatUsed++;
1188 pgStatTabstatMessages[0]->m_nentries = 0;
1194 * pgstat_fetch_stat_dbentry() -
1196 * Support function for the SQL-callable pgstat* functions. Returns
1197 * the collected statistics for one database or NULL. NULL doesn't mean
1198 * that the database doesn't exist, it is just not yet known by the
1199 * collector, so the caller is better off to report ZERO instead.
1202 PgStat_StatDBEntry *
1203 pgstat_fetch_stat_dbentry(Oid dbid)
1205 PgStat_StatDBEntry *dbentry;
1208 * If not done for this transaction, read the statistics collector
1209 * stats file into some hash tables.
1211 backend_read_statsfile();
1214 * Lookup the requested database
1216 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1219 if (dbentry == NULL)
1227 * pgstat_fetch_stat_tabentry() -
1229 * Support function for the SQL-callable pgstat* functions. Returns
1230 * the collected statistics for one table or NULL. NULL doesn't mean
1231 * that the table doesn't exist, it is just not yet known by the
1232 * collector, so the caller is better off to report ZERO instead.
1235 PgStat_StatTabEntry *
1236 pgstat_fetch_stat_tabentry(Oid relid)
1238 PgStat_StatDBEntry *dbentry;
1239 PgStat_StatTabEntry *tabentry;
1242 * If not done for this transaction, read the statistics collector
1243 * stats file into some hash tables.
1245 backend_read_statsfile();
1248 * Lookup our database.
1250 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1251 (void *) &MyDatabaseId,
1253 if (dbentry == NULL)
1257 * Now inside the DB's table hash table lookup the requested one.
1259 if (dbentry->tables == NULL)
1261 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1264 if (tabentry == NULL)
1272 * pgstat_fetch_stat_beentry() -
1274 * Support function for the SQL-callable pgstat* functions. Returns
1275 * the actual activity slot of one active backend. The caller is
1276 * responsible for a check if the actual user is permitted to see
1277 * that info (especially the querystring).
1280 PgStat_StatBeEntry *
1281 pgstat_fetch_stat_beentry(int beid)
1283 backend_read_statsfile();
1285 if (beid < 1 || beid > pgStatNumBackends)
1288 return &pgStatBeTable[beid - 1];
1293 * pgstat_fetch_stat_numbackends() -
1295 * Support function for the SQL-callable pgstat* functions. Returns
1296 * the maximum current backend id.
1300 pgstat_fetch_stat_numbackends(void)
1302 backend_read_statsfile();
1304 return pgStatNumBackends;
1309 /* ------------------------------------------------------------
1310 * Local support functions follow
1311 * ------------------------------------------------------------
1316 * pgstat_setheader() -
1318 * Set common header fields in a statistics message
1322 pgstat_setheader(PgStat_MsgHdr *hdr, int mtype)
1324 hdr->m_type = mtype;
1325 hdr->m_backendid = MyBackendId;
1326 hdr->m_procpid = MyProcPid;
1327 hdr->m_databaseid = MyDatabaseId;
1328 hdr->m_userid = GetSessionUserId();
1335 * Send out one statistics message to the collector
1339 pgstat_send(void *msg, int len)
1344 ((PgStat_MsgHdr *) msg)->m_size = len;
1346 send(pgStatSock, msg, len, 0);
1347 /* We deliberately ignore any error from send() */
1352 * PgstatBufferMain() -
1354 * Start up the statistics buffer process. This is the body of the
1355 * postmaster child process.
1357 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1360 NON_EXEC_STATIC void
1361 PgstatBufferMain(int argc, char *argv[])
1363 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
1365 MyProcPid = getpid(); /* reset MyProcPid */
1367 /* Lose the postmaster's on-exit routines */
1371 * Ignore all signals usually bound to some action in the postmaster,
1372 * except for SIGCHLD and SIGQUIT --- see pgstat_recvbuffer.
1374 pqsignal(SIGHUP, SIG_IGN);
1375 pqsignal(SIGINT, SIG_IGN);
1376 pqsignal(SIGTERM, SIG_IGN);
1377 pqsignal(SIGQUIT, pgstat_exit);
1378 pqsignal(SIGALRM, SIG_IGN);
1379 pqsignal(SIGPIPE, SIG_IGN);
1380 pqsignal(SIGUSR1, SIG_IGN);
1381 pqsignal(SIGUSR2, SIG_IGN);
1382 pqsignal(SIGCHLD, pgstat_die);
1383 pqsignal(SIGTTIN, SIG_DFL);
1384 pqsignal(SIGTTOU, SIG_DFL);
1385 pqsignal(SIGCONT, SIG_DFL);
1386 pqsignal(SIGWINCH, SIG_DFL);
1387 /* unblock will happen in pgstat_recvbuffer */
1390 pgstat_parseArgs(argc,argv);
1394 * Start a buffering process to read from the socket, so we have a
1395 * little more time to process incoming messages.
1397 * NOTE: the process structure is: postmaster is parent of buffer process
1398 * is parent of collector process. This way, the buffer can detect
1399 * collector failure via SIGCHLD, whereas otherwise it wouldn't notice
1400 * collector failure until it tried to write on the pipe. That would
1401 * mean that after the postmaster started a new collector, we'd have
1402 * two buffer processes competing to read from the UDP socket --- not
1405 if (pgpipe(pgStatPipe) < 0)
1408 (errcode_for_socket_access(),
1409 errmsg("could not create pipe for statistics buffer: %m")));
1414 /* child becomes collector process */
1415 switch (pgstat_forkexec(STAT_PROC_COLLECTOR))
1422 (errmsg("could not fork statistics collector: %m")));
1425 #ifndef EXEC_BACKEND
1427 /* child becomes collector process */
1428 PgstatCollectorMain(0, NULL);
1433 /* parent becomes buffer process */
1434 closesocket(pgStatPipe[0]);
1435 pgstat_recvbuffer();
1442 * PgstatCollectorMain() -
1444 * Start up the statistics collector itself. This is the body of the
1445 * postmaster grandchild process.
1447 * The argc/argv parameters are valid only in EXEC_BACKEND case.
1450 NON_EXEC_STATIC void
1451 PgstatCollectorMain(int argc, char *argv[])
1458 struct timeval timeout;
1459 struct timeval next_statwrite;
1460 bool need_statwrite;
1463 MyProcPid = getpid(); /* reset MyProcPid */
1466 * Reset signal handling. With the exception of restoring default
1467 * SIGCHLD and SIGQUIT handling, this is a no-op in the non-EXEC_BACKEND
1468 * case because we'll have inherited these settings from the buffer
1469 * process; but it's not a no-op for EXEC_BACKEND.
1471 pqsignal(SIGHUP, SIG_IGN);
1472 pqsignal(SIGINT, SIG_IGN);
1473 pqsignal(SIGTERM, SIG_IGN);
1474 pqsignal(SIGQUIT, SIG_IGN);
1475 pqsignal(SIGALRM, SIG_IGN);
1476 pqsignal(SIGPIPE, SIG_IGN);
1477 pqsignal(SIGUSR1, SIG_IGN);
1478 pqsignal(SIGUSR2, SIG_IGN);
1479 pqsignal(SIGCHLD, SIG_DFL);
1480 pqsignal(SIGTTIN, SIG_DFL);
1481 pqsignal(SIGTTOU, SIG_DFL);
1482 pqsignal(SIGCONT, SIG_DFL);
1483 pqsignal(SIGWINCH, SIG_DFL);
1484 PG_SETMASK(&UnBlockSig);
1487 pgstat_parseArgs(argc,argv);
1490 /* Close unwanted files */
1491 closesocket(pgStatPipe[1]);
1492 closesocket(pgStatSock);
1495 * Identify myself via ps
1497 init_ps_display("stats collector process", "", "");
1501 * Initialize filenames needed for status reports.
1503 snprintf(pgStat_fname, MAXPGPATH, PGSTAT_STAT_FILENAME, DataDir);
1504 /* tmpfname need only be set correctly in this process */
1505 snprintf(pgStat_tmpfname, MAXPGPATH, PGSTAT_STAT_TMPFILE,
1509 * Arrange to write the initial status file right away
1511 gettimeofday(&next_statwrite, NULL);
1512 need_statwrite = TRUE;
1515 * Read in an existing statistics stats file or initialize the stats
1518 pgStatRunningInCollector = TRUE;
1519 pgstat_read_statsfile(&pgStatDBHash, InvalidOid, NULL, NULL);
1522 * Create the dead backend hashtable
1524 memset(&hash_ctl, 0, sizeof(hash_ctl));
1525 hash_ctl.keysize = sizeof(int);
1526 hash_ctl.entrysize = sizeof(PgStat_StatBeDead);
1527 hash_ctl.hash = tag_hash;
1528 pgStatBeDead = hash_create("Dead Backends", PGSTAT_BE_HASH_SIZE,
1529 &hash_ctl, HASH_ELEM | HASH_FUNCTION);
1530 if (pgStatBeDead == NULL)
1532 /* assume the problem is out-of-memory */
1534 (errcode(ERRCODE_OUT_OF_MEMORY),
1535 errmsg("out of memory in statistics collector --- abort")));
1540 * Create the known backends table
1542 pgStatBeTable = (PgStat_StatBeEntry *) malloc(
1543 sizeof(PgStat_StatBeEntry) * MaxBackends);
1544 if (pgStatBeTable == NULL)
1547 (errcode(ERRCODE_OUT_OF_MEMORY),
1548 errmsg("out of memory in statistics collector --- abort")));
1551 memset(pgStatBeTable, 0, sizeof(PgStat_StatBeEntry) * MaxBackends);
1553 readPipe = pgStatPipe[0];
1556 * Process incoming messages and handle all the reporting stuff until
1557 * there are no more messages.
1562 * If we need to write the status file again (there have been
1563 * changes in the statistics since we wrote it last) calculate the
1564 * timeout until we have to do so.
1570 gettimeofday(&now, NULL);
1571 /* avoid assuming that tv_sec is signed */
1572 if (now.tv_sec > next_statwrite.tv_sec ||
1573 (now.tv_sec == next_statwrite.tv_sec &&
1574 now.tv_usec >= next_statwrite.tv_usec))
1577 timeout.tv_usec = 0;
1581 timeout.tv_sec = next_statwrite.tv_sec - now.tv_sec;
1582 timeout.tv_usec = next_statwrite.tv_usec - now.tv_usec;
1583 if (timeout.tv_usec < 0)
1586 timeout.tv_usec += 1000000;
1592 * Setup the descriptor set for select(2)
1595 FD_SET(readPipe, &rfds);
1598 * Now wait for something to do.
1600 nready = select(readPipe+1, &rfds, NULL, NULL,
1601 (need_statwrite) ? &timeout : NULL);
1607 (errcode_for_socket_access(),
1608 errmsg("select() failed in statistics collector: %m")));
1613 * If there are no descriptors ready, our timeout for writing the
1614 * stats file happened.
1618 pgstat_write_statsfile();
1619 need_statwrite = FALSE;
1625 * Check if there is a new statistics message to collect.
1627 if (FD_ISSET(readPipe, &rfds))
1630 * We may need to issue multiple read calls in case the buffer
1631 * process didn't write the message in a single write, which
1632 * is possible since it dumps its buffer bytewise. In any
1633 * case, we'd need two reads since we don't know the message
1637 int targetlen = sizeof(PgStat_MsgHdr); /* initial */
1638 bool pipeEOF = false;
1640 while (nread < targetlen)
1642 len = piperead(readPipe, ((char *) &msg) + nread,
1649 (errcode_for_socket_access(),
1650 errmsg("could not read from statistics collector pipe: %m")));
1653 if (len == 0) /* EOF on the pipe! */
1659 if (nread == sizeof(PgStat_MsgHdr))
1661 /* we have the header, compute actual msg length */
1662 targetlen = msg.msg_hdr.m_size;
1663 if (targetlen < (int) sizeof(PgStat_MsgHdr) ||
1664 targetlen > (int) sizeof(msg))
1667 * Bogus message length implies that we got out of
1668 * sync with the buffer process somehow. Abort so
1669 * that we can restart both processes.
1672 (errmsg("invalid statistics message length")));
1679 * EOF on the pipe implies that the buffer process exited.
1680 * Fall out of outer loop.
1686 * Distribute the message to the specific function handling
1689 switch (msg.msg_hdr.m_type)
1691 case PGSTAT_MTYPE_DUMMY:
1694 case PGSTAT_MTYPE_BESTART:
1695 pgstat_recv_bestart((PgStat_MsgBestart *) &msg, nread);
1698 case PGSTAT_MTYPE_BETERM:
1699 pgstat_recv_beterm((PgStat_MsgBeterm *) &msg, nread);
1702 case PGSTAT_MTYPE_TABSTAT:
1703 pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, nread);
1706 case PGSTAT_MTYPE_TABPURGE:
1707 pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, nread);
1710 case PGSTAT_MTYPE_ACTIVITY:
1711 pgstat_recv_activity((PgStat_MsgActivity *) &msg, nread);
1714 case PGSTAT_MTYPE_DROPDB:
1715 pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, nread);
1718 case PGSTAT_MTYPE_RESETCOUNTER:
1719 pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
1728 * Globally count messages.
1730 pgStatNumMessages++;
1733 * If this is the first message after we wrote the stats file
1734 * the last time, setup the timeout that it'd be written.
1736 if (!need_statwrite)
1738 gettimeofday(&next_statwrite, NULL);
1739 next_statwrite.tv_usec += ((PGSTAT_STAT_INTERVAL) * 1000);
1740 next_statwrite.tv_sec += (next_statwrite.tv_usec / 1000000);
1741 next_statwrite.tv_usec %= 1000000;
1742 need_statwrite = TRUE;
1747 * Note that we do NOT check for postmaster exit inside the loop;
1748 * only EOF on the buffer pipe causes us to fall out. This
1749 * ensures we don't exit prematurely if there are still a few
1750 * messages in the buffer or pipe at postmaster shutdown.
1755 * Okay, we saw EOF on the buffer pipe, so there are no more messages
1756 * to process. If the buffer process quit because of postmaster
1757 * shutdown, we want to save the final stats to reuse at next startup.
1758 * But if the buffer process failed, it seems best not to (there may
1759 * even now be a new collector firing up, and we don't want it to read
1760 * a partially-rewritten stats file).
1762 if (!PostmasterIsAlive(false))
1763 pgstat_write_statsfile();
1768 * pgstat_recvbuffer() -
1770 * This is the body of the separate buffering process. Its only
1771 * purpose is to receive messages from the UDP socket as fast as
1772 * possible and forward them over a pipe into the collector itself.
1773 * If the collector is slow to absorb messages, they are buffered here.
1777 pgstat_recvbuffer(void)
1781 struct timeval timeout;
1782 int writePipe = pgStatPipe[1];
1788 PgStat_Msg input_buffer;
1790 int msg_send = 0; /* next send index in buffer */
1791 int msg_recv = 0; /* next receive index */
1792 int msg_have = 0; /* number of bytes stored */
1793 bool overflow = false;
1796 * Identify myself via ps
1798 init_ps_display("stats buffer process", "", "");
1802 * We want to die if our child collector process does. There are two
1803 * ways we might notice that it has died: receive SIGCHLD, or get a
1804 * write failure on the pipe leading to the child. We can set SIGPIPE
1805 * to kill us here. Our SIGCHLD handler was already set up before we
1806 * forked (must do it that way, else it's a race condition).
1808 pqsignal(SIGPIPE, SIG_DFL);
1809 PG_SETMASK(&UnBlockSig);
1812 * Set the write pipe to nonblock mode, so that we cannot block when
1813 * the collector falls behind.
1815 if (!set_noblock(writePipe))
1818 (errcode_for_socket_access(),
1819 errmsg("could not set statistics collector pipe to nonblocking mode: %m")));
1824 * Allocate the message buffer
1826 msgbuffer = (char *) malloc(PGSTAT_RECVBUFFERSZ);
1827 if (msgbuffer == NULL)
1830 (errcode(ERRCODE_OUT_OF_MEMORY),
1831 errmsg("out of memory in statistics collector --- abort")));
1845 * As long as we have buffer space we add the socket to the read
1848 if (msg_have <= (int) (PGSTAT_RECVBUFFERSZ - sizeof(PgStat_Msg)))
1850 FD_SET(pgStatSock, &rfds);
1859 (errmsg("statistics buffer is full")));
1865 * If we have messages to write out, we add the pipe to the write
1870 FD_SET(writePipe, &wfds);
1871 if (writePipe > maxfd)
1876 * Wait for some work to do; but not for more than 10 seconds.
1877 * (This determines how quickly we will shut down after an
1878 * ungraceful postmaster termination; so it needn't be very fast.)
1880 timeout.tv_sec = 10;
1881 timeout.tv_usec = 0;
1883 nready = select(maxfd + 1, &rfds, &wfds, NULL, &timeout);
1889 (errcode_for_socket_access(),
1890 errmsg("select() failed in statistics buffer: %m")));
1895 * If there is a message on the socket, read it and check for
1898 if (FD_ISSET(pgStatSock, &rfds))
1900 len = recv(pgStatSock, (char *) &input_buffer,
1901 sizeof(PgStat_Msg), 0);
1905 (errcode_for_socket_access(),
1906 errmsg("could not read statistics message: %m")));
1911 * We ignore messages that are smaller than our common header
1913 if (len < sizeof(PgStat_MsgHdr))
1917 * The received length must match the length in the header
1919 if (input_buffer.msg_hdr.m_size != len)
1923 * O.K. - we accept this message. Copy it to the circular
1929 xfr = PGSTAT_RECVBUFFERSZ - msg_recv;
1933 memcpy(msgbuffer + msg_recv,
1934 ((char *) &input_buffer) + frm,
1937 if (msg_recv == PGSTAT_RECVBUFFERSZ)
1946 * If the collector is ready to receive, write some data into his
1947 * pipe. We may or may not be able to write all that we have.
1949 * NOTE: if what we have is less than PIPE_BUF bytes but more than
1950 * the space available in the pipe buffer, most kernels will
1951 * refuse to write any of it, and will return EAGAIN. This means
1952 * we will busy-loop until the situation changes (either because
1953 * the collector caught up, or because more data arrives so that
1954 * we have more than PIPE_BUF bytes buffered). This is not good,
1955 * but is there any way around it? We have no way to tell when
1956 * the collector has caught up...
1958 if (FD_ISSET(writePipe, &wfds))
1960 xfr = PGSTAT_RECVBUFFERSZ - msg_send;
1964 len = pipewrite(writePipe, msgbuffer + msg_send, xfr);
1967 if (errno == EINTR || errno == EAGAIN)
1968 continue; /* not enough space in pipe */
1970 (errcode_for_socket_access(),
1971 errmsg("could not write to statistics collector pipe: %m")));
1974 /* NB: len < xfr is okay */
1976 if (msg_send == PGSTAT_RECVBUFFERSZ)
1982 * Make sure we forwarded all messages before we check for
1983 * postmaster termination.
1985 if (msg_have != 0 || FD_ISSET(pgStatSock, &rfds))
1989 * If the postmaster has terminated, we die too. (This is no longer
1990 * the normal exit path, however.)
1992 if (!PostmasterIsAlive(true))
1997 /* SIGQUIT signal handler for buffer process */
1999 pgstat_exit(SIGNAL_ARGS)
2002 * For now, we just nail the doors shut and get out of town. It might
2003 * be cleaner to allow any pending messages to be sent, but that creates
2004 * a tradeoff against speed of exit.
2009 /* SIGCHLD signal handler for buffer process */
2011 pgstat_die(SIGNAL_ARGS)
2018 * pgstat_add_backend() -
2020 * Support function to keep our backend list up to date.
2024 pgstat_add_backend(PgStat_MsgHdr *msg)
2026 PgStat_StatDBEntry *dbentry;
2027 PgStat_StatBeEntry *beentry;
2028 PgStat_StatBeDead *deadbe;
2032 * Check that the backend ID is valid
2034 if (msg->m_backendid < 1 || msg->m_backendid > MaxBackends)
2037 (errmsg("invalid server process ID %d", msg->m_backendid)));
2042 * Get the slot for this backendid.
2044 beentry = &pgStatBeTable[msg->m_backendid - 1];
2045 if (beentry->databaseid != InvalidOid)
2048 * If the slot contains the PID of this backend, everything is
2049 * fine and we got nothing to do.
2051 if (beentry->procpid == msg->m_procpid)
2056 * Lookup if this backend is known to be dead. This can be caused due
2057 * to messages arriving in the wrong order - i.e. Postmaster's BETERM
2058 * message might have arrived before we received all the backends
2059 * stats messages, or even a new backend with the same backendid was
2060 * faster in sending his BESTART.
2062 * If the backend is known to be dead, we ignore this add.
2064 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2065 (void *) &(msg->m_procpid),
2071 * Backend isn't known to be dead. If it's slot is currently used, we
2072 * have to kick out the old backend.
2074 if (beentry->databaseid != InvalidOid)
2075 pgstat_sub_backend(beentry->procpid);
2078 * Put this new backend into the slot.
2080 beentry->databaseid = msg->m_databaseid;
2081 beentry->procpid = msg->m_procpid;
2082 beentry->userid = msg->m_userid;
2083 beentry->activity_start_sec = 0;
2084 beentry->activity_start_usec = 0;
2085 MemSet(beentry->activity, 0, PGSTAT_ACTIVITY_SIZE);
2088 * Lookup or create the database entry for this backends DB.
2090 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2091 (void *) &(msg->m_databaseid),
2092 HASH_ENTER, &found);
2093 if (dbentry == NULL)
2096 (errcode(ERRCODE_OUT_OF_MEMORY),
2097 errmsg("out of memory in statistics collector --- abort")));
2102 * If not found, initialize the new one.
2108 dbentry->tables = NULL;
2109 dbentry->n_xact_commit = 0;
2110 dbentry->n_xact_rollback = 0;
2111 dbentry->n_blocks_fetched = 0;
2112 dbentry->n_blocks_hit = 0;
2113 dbentry->n_connects = 0;
2114 dbentry->destroy = 0;
2116 memset(&hash_ctl, 0, sizeof(hash_ctl));
2117 hash_ctl.keysize = sizeof(Oid);
2118 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2119 hash_ctl.hash = tag_hash;
2120 dbentry->tables = hash_create("Per-database table",
2121 PGSTAT_TAB_HASH_SIZE,
2123 HASH_ELEM | HASH_FUNCTION);
2124 if (dbentry->tables == NULL)
2126 /* assume the problem is out-of-memory */
2128 (errcode(ERRCODE_OUT_OF_MEMORY),
2129 errmsg("out of memory in statistics collector --- abort")));
2135 * Count number of connects to the database
2137 dbentry->n_connects++;
2144 * pgstat_sub_backend() -
2146 * Remove a backend from the actual backends list.
2150 pgstat_sub_backend(int procpid)
2153 PgStat_StatBeDead *deadbe;
2157 * Search in the known-backends table for the slot containing this
2160 for (i = 0; i < MaxBackends; i++)
2162 if (pgStatBeTable[i].databaseid != InvalidOid &&
2163 pgStatBeTable[i].procpid == procpid)
2166 * That's him. Add an entry to the known to be dead backends.
2167 * Due to possible misorder in the arrival of UDP packets it's
2168 * possible that even if we know the backend is dead, there
2169 * could still be messages queued that arrive later. Those
2170 * messages must not cause our number of backends statistics
2171 * to get screwed up, so we remember for a couple of seconds
2172 * that this PID is dead and ignore them (only the counting of
2173 * backends, not the table access stats they sent).
2175 deadbe = (PgStat_StatBeDead *) hash_search(pgStatBeDead,
2182 (errcode(ERRCODE_OUT_OF_MEMORY),
2183 errmsg("out of memory in statistics collector --- abort")));
2188 deadbe->backendid = i + 1;
2189 deadbe->destroy = PGSTAT_DESTROY_COUNT;
2193 * Declare the backend slot empty.
2195 pgStatBeTable[i].databaseid = InvalidOid;
2201 * No big problem if not found. This can happen if UDP messages arrive
2202 * out of order here.
2208 * pgstat_write_statsfile() -
2214 pgstat_write_statsfile(void)
2216 HASH_SEQ_STATUS hstat;
2217 HASH_SEQ_STATUS tstat;
2218 PgStat_StatDBEntry *dbentry;
2219 PgStat_StatTabEntry *tabentry;
2220 PgStat_StatBeDead *deadbe;
2225 * Open the statistics temp file to write out the current values.
2227 fpout = fopen(pgStat_tmpfname, PG_BINARY_W);
2231 (errcode_for_file_access(),
2232 errmsg("could not open temporary statistics file \"%s\": %m",
2238 * Walk through the database table.
2240 hash_seq_init(&hstat, pgStatDBHash);
2241 while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2244 * If this database is marked destroyed, count down and do so if
2247 if (dbentry->destroy > 0)
2249 if (--(dbentry->destroy) == 0)
2251 if (dbentry->tables != NULL)
2252 hash_destroy(dbentry->tables);
2254 if (hash_search(pgStatDBHash,
2255 (void *) &(dbentry->databaseid),
2256 HASH_REMOVE, NULL) == NULL)
2259 (errmsg("database hash table corrupted "
2260 "during cleanup --- abort")));
2266 * Don't include statistics for it.
2272 * Write out the DB line including the number of life backends.
2275 fwrite(dbentry, sizeof(PgStat_StatDBEntry), 1, fpout);
2278 * Walk through the databases access stats per table.
2280 hash_seq_init(&tstat, dbentry->tables);
2281 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2284 * If table entry marked for destruction, same as above for
2285 * the database entry.
2287 if (tabentry->destroy > 0)
2289 if (--(tabentry->destroy) == 0)
2291 if (hash_search(dbentry->tables,
2292 (void *) &(tabentry->tableid),
2293 HASH_REMOVE, NULL) == NULL)
2296 (errmsg("tables hash table for "
2297 "database %u corrupted during "
2298 "cleanup --- abort",
2299 dbentry->databaseid)));
2307 * At least we think this is still a life table. Print it's
2311 fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2315 * Mark the end of this DB
2321 * Write out the known running backends to the stats file.
2325 fwrite(&i, sizeof(i), 1, fpout);
2327 for (i = 0; i < MaxBackends; i++)
2329 if (pgStatBeTable[i].databaseid != InvalidOid)
2332 fwrite(&pgStatBeTable[i], sizeof(PgStat_StatBeEntry), 1, fpout);
2337 * No more output to be done. Close the temp file and replace the old
2338 * pgstat.stat with it.
2341 if (fclose(fpout) < 0)
2344 (errcode_for_file_access(),
2345 errmsg("could not close temporary statistics file \"%s\": %m",
2350 if (rename(pgStat_tmpfname, pgStat_fname) < 0)
2353 (errcode_for_file_access(),
2354 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
2355 pgStat_tmpfname, pgStat_fname)));
2360 * Clear out the dead backends table
2362 hash_seq_init(&hstat, pgStatBeDead);
2363 while ((deadbe = (PgStat_StatBeDead *) hash_seq_search(&hstat)) != NULL)
2366 * Count down the destroy delay and remove entries where it
2369 if (--(deadbe->destroy) <= 0)
2371 if (hash_search(pgStatBeDead,
2372 (void *) &(deadbe->procpid),
2373 HASH_REMOVE, NULL) == NULL)
2376 (errmsg("dead-server-process hash table corrupted "
2377 "during cleanup --- abort")));
2386 * pgstat_read_statsfile() -
2388 * Reads in an existing statistics collector and initializes the
2389 * databases hash table (who's entries point to the tables hash tables)
2390 * and the current backend table.
2394 pgstat_read_statsfile(HTAB **dbhash, Oid onlydb,
2395 PgStat_StatBeEntry **betab, int *numbackends)
2397 PgStat_StatDBEntry *dbentry;
2398 PgStat_StatDBEntry dbbuf;
2399 PgStat_StatTabEntry *tabentry;
2400 PgStat_StatTabEntry tabbuf;
2402 HTAB *tabhash = NULL;
2404 int maxbackends = 0;
2405 int havebackends = 0;
2407 MemoryContext use_mcxt;
2411 * If running in the collector we use the DynaHashCxt memory context.
2412 * If running in a backend, we use the TopTransactionContext instead,
2413 * so the caller must only know the last XactId when this call
2414 * happened to know if his tables are still valid or already gone!
2416 if (pgStatRunningInCollector)
2423 use_mcxt = TopTransactionContext;
2424 mcxt_flags = HASH_CONTEXT;
2428 * Create the DB hashtable
2430 memset(&hash_ctl, 0, sizeof(hash_ctl));
2431 hash_ctl.keysize = sizeof(Oid);
2432 hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2433 hash_ctl.hash = tag_hash;
2434 hash_ctl.hcxt = use_mcxt;
2435 *dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
2436 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2437 if (*dbhash == NULL)
2439 /* assume the problem is out-of-memory */
2440 if (pgStatRunningInCollector)
2443 (errcode(ERRCODE_OUT_OF_MEMORY),
2444 errmsg("out of memory in statistics collector --- abort")));
2447 /* in backend, can do normal error */
2449 (errcode(ERRCODE_OUT_OF_MEMORY),
2450 errmsg("out of memory")));
2454 * Initialize the number of known backends to zero, just in case we do
2455 * a silent error return below.
2457 if (numbackends != NULL)
2463 * In EXEC_BACKEND case, we won't have inherited pgStat_fname from
2464 * postmaster, so compute it first time through.
2467 if (pgStat_fname[0] == '\0')
2469 Assert(DataDir != NULL);
2470 snprintf(pgStat_fname, MAXPGPATH, PGSTAT_STAT_FILENAME, DataDir);
2475 * Try to open the status file. If it doesn't exist, the backends
2476 * simply return zero for anything and the collector simply starts
2477 * from scratch with empty counters.
2479 if ((fpin = fopen(pgStat_fname, PG_BINARY_R)) == NULL)
2483 * We found an existing collector stats file. Read it and put all the
2484 * hashtable entries into place.
2488 switch (fgetc(fpin))
2491 * 'D' A PgStat_StatDBEntry struct describing a database
2492 * follows. Subsequently, zero to many 'T' entries will
2493 * follow until a 'd' is encountered.
2496 if (fread(&dbbuf, 1, sizeof(dbbuf), fpin) != sizeof(dbbuf))
2498 ereport(pgStatRunningInCollector ? LOG : WARNING,
2499 (errmsg("corrupted pgstat.stat file")));
2505 * Add to the DB hash
2507 dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
2508 (void *) &dbbuf.databaseid,
2511 if (dbentry == NULL)
2513 if (pgStatRunningInCollector)
2516 (errcode(ERRCODE_OUT_OF_MEMORY),
2517 errmsg("out of memory in statistics collector --- abort")));
2524 (errcode(ERRCODE_OUT_OF_MEMORY),
2525 errmsg("out of memory")));
2530 ereport(pgStatRunningInCollector ? LOG : WARNING,
2531 (errmsg("corrupted pgstat.stat file")));
2536 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2537 dbentry->tables = NULL;
2538 dbentry->destroy = 0;
2539 dbentry->n_backends = 0;
2542 * Don't collect tables if not the requested DB
2544 if (onlydb != InvalidOid && onlydb != dbbuf.databaseid)
2547 memset(&hash_ctl, 0, sizeof(hash_ctl));
2548 hash_ctl.keysize = sizeof(Oid);
2549 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2550 hash_ctl.hash = tag_hash;
2551 hash_ctl.hcxt = use_mcxt;
2552 dbentry->tables = hash_create("Per-database table",
2553 PGSTAT_TAB_HASH_SIZE,
2555 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2556 if (dbentry->tables == NULL)
2558 /* assume the problem is out-of-memory */
2559 if (pgStatRunningInCollector)
2562 (errcode(ERRCODE_OUT_OF_MEMORY),
2563 errmsg("out of memory in statistics collector --- abort")));
2566 /* in backend, can do normal error */
2569 (errcode(ERRCODE_OUT_OF_MEMORY),
2570 errmsg("out of memory")));
2574 * Arrange that following 'T's add entries to this
2575 * databases tables hash table.
2577 tabhash = dbentry->tables;
2581 * 'd' End of this database.
2588 * 'T' A PgStat_StatTabEntry follows.
2591 if (fread(&tabbuf, 1, sizeof(tabbuf), fpin) != sizeof(tabbuf))
2593 ereport(pgStatRunningInCollector ? LOG : WARNING,
2594 (errmsg("corrupted pgstat.stat file")));
2600 * Skip if table belongs to a not requested database.
2602 if (tabhash == NULL)
2605 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
2606 (void *) &tabbuf.tableid,
2607 HASH_ENTER, &found);
2608 if (tabentry == NULL)
2610 if (pgStatRunningInCollector)
2613 (errcode(ERRCODE_OUT_OF_MEMORY),
2614 errmsg("out of memory in statistics collector --- abort")));
2617 /* in backend, can do normal error */
2620 (errcode(ERRCODE_OUT_OF_MEMORY),
2621 errmsg("out of memory")));
2626 ereport(pgStatRunningInCollector ? LOG : WARNING,
2627 (errmsg("corrupted pgstat.stat file")));
2632 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
2636 * 'M' The maximum number of backends to expect follows.
2639 if (betab == NULL || numbackends == NULL)
2644 if (fread(&maxbackends, 1, sizeof(maxbackends), fpin) !=
2645 sizeof(maxbackends))
2647 ereport(pgStatRunningInCollector ? LOG : WARNING,
2648 (errmsg("corrupted pgstat.stat file")));
2652 if (maxbackends == 0)
2659 * Allocate space (in TopTransactionContext too) for the
2662 if (use_mcxt == NULL)
2663 *betab = (PgStat_StatBeEntry *) malloc(
2664 sizeof(PgStat_StatBeEntry) * maxbackends);
2666 *betab = (PgStat_StatBeEntry *) MemoryContextAlloc(
2668 sizeof(PgStat_StatBeEntry) * maxbackends);
2672 * 'B' A PgStat_StatBeEntry follows.
2675 if (betab == NULL || numbackends == NULL)
2687 * Read it directly into the table.
2689 if (fread(&(*betab)[havebackends], 1,
2690 sizeof(PgStat_StatBeEntry), fpin) !=
2691 sizeof(PgStat_StatBeEntry))
2693 ereport(pgStatRunningInCollector ? LOG : WARNING,
2694 (errmsg("corrupted pgstat.stat file")));
2700 * Count backends per database here.
2702 dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
2703 (void *) &((*betab)[havebackends].databaseid),
2706 dbentry->n_backends++;
2709 if (numbackends != 0)
2710 *numbackends = havebackends;
2711 if (havebackends >= maxbackends)
2719 * 'E' The EOF marker of a complete stats file.
2726 ereport(pgStatRunningInCollector ? LOG : WARNING,
2727 (errmsg("corrupted pgstat.stat file")));
2737 * If not done for this transaction, read the statistics collector
2738 * stats file into some hash tables.
2740 * Because we store the hash tables in TopTransactionContext, the result
2741 * is good for the entire current main transaction.
2744 backend_read_statsfile(void)
2746 TransactionId topXid = GetTopTransactionId();
2748 if (!TransactionIdEquals(pgStatDBHashXact, topXid))
2750 Assert(!pgStatRunningInCollector);
2751 pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId,
2752 &pgStatBeTable, &pgStatNumBackends);
2753 pgStatDBHashXact = topXid;
2759 * pgstat_recv_bestart() -
2761 * Process a backend startup message.
2765 pgstat_recv_bestart(PgStat_MsgBestart *msg, int len)
2767 pgstat_add_backend(&msg->m_hdr);
2772 * pgstat_recv_beterm() -
2774 * Process a backend termination message.
2778 pgstat_recv_beterm(PgStat_MsgBeterm *msg, int len)
2780 pgstat_sub_backend(msg->m_hdr.m_procpid);
2785 * pgstat_recv_activity() -
2787 * Remember what the backend is doing.
2791 pgstat_recv_activity(PgStat_MsgActivity *msg, int len)
2793 PgStat_StatBeEntry *entry;
2796 * Here we check explicitly for 0 return, since we don't want to
2797 * mangle the activity of an active backend by a delayed packet from a
2800 if (pgstat_add_backend(&msg->m_hdr) != 0)
2803 entry = &(pgStatBeTable[msg->m_hdr.m_backendid - 1]);
2805 StrNCpy(entry->activity, msg->m_what, PGSTAT_ACTIVITY_SIZE);
2807 entry->activity_start_sec =
2808 GetCurrentAbsoluteTimeUsec(&entry->activity_start_usec);
2813 * pgstat_recv_tabstat() -
2815 * Count what the backend has done.
2819 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
2821 PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
2822 PgStat_StatDBEntry *dbentry;
2823 PgStat_StatTabEntry *tabentry;
2828 * Make sure the backend is counted for.
2830 if (pgstat_add_backend(&msg->m_hdr) < 0)
2834 * Lookup the database in the hashtable.
2836 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2837 (void *) &(msg->m_hdr.m_databaseid),
2843 * If the database is marked for destroy, this is a delayed UDP packet
2844 * and not worth being counted.
2846 if (dbentry->destroy > 0)
2849 dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
2850 dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2853 * Process all table entries in the message.
2855 for (i = 0; i < msg->m_nentries; i++)
2857 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2858 (void *) &(tabmsg[i].t_id),
2859 HASH_ENTER, &found);
2860 if (tabentry == NULL)
2863 (errcode(ERRCODE_OUT_OF_MEMORY),
2864 errmsg("out of memory in statistics collector --- abort")));
2871 * If it's a new table entry, initialize counters to the
2872 * values we just got.
2874 tabentry->numscans = tabmsg[i].t_numscans;
2875 tabentry->tuples_returned = tabmsg[i].t_tuples_returned;
2876 tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched;
2877 tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted;
2878 tabentry->tuples_updated = tabmsg[i].t_tuples_updated;
2879 tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted;
2880 tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched;
2881 tabentry->blocks_hit = tabmsg[i].t_blocks_hit;
2883 tabentry->destroy = 0;
2888 * Otherwise add the values to the existing entry.
2890 tabentry->numscans += tabmsg[i].t_numscans;
2891 tabentry->tuples_returned += tabmsg[i].t_tuples_returned;
2892 tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched;
2893 tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted;
2894 tabentry->tuples_updated += tabmsg[i].t_tuples_updated;
2895 tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted;
2896 tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched;
2897 tabentry->blocks_hit += tabmsg[i].t_blocks_hit;
2901 * And add the block IO to the database entry.
2903 dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched;
2904 dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit;
2910 * pgstat_recv_tabpurge() -
2912 * Arrange for dead table removal.
2916 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
2918 PgStat_StatDBEntry *dbentry;
2919 PgStat_StatTabEntry *tabentry;
2923 * Make sure the backend is counted for.
2925 if (pgstat_add_backend(&msg->m_hdr) < 0)
2929 * Lookup the database in the hashtable.
2931 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2932 (void *) &(msg->m_hdr.m_databaseid),
2938 * If the database is marked for destroy, this is a delayed UDP packet
2939 * and the tables will go away at DB destruction.
2941 if (dbentry->destroy > 0)
2945 * Process all table entries in the message.
2947 for (i = 0; i < msg->m_nentries; i++)
2949 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2950 (void *) &(msg->m_tableid[i]),
2953 tabentry->destroy = PGSTAT_DESTROY_COUNT;
2959 * pgstat_recv_dropdb() -
2961 * Arrange for dead database removal
2965 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
2967 PgStat_StatDBEntry *dbentry;
2970 * Make sure the backend is counted for.
2972 if (pgstat_add_backend(&msg->m_hdr) < 0)
2976 * Lookup the database in the hashtable.
2978 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2979 (void *) &(msg->m_databaseid),
2985 * Mark the database for destruction.
2987 dbentry->destroy = PGSTAT_DESTROY_COUNT;
2992 * pgstat_recv_dropdb() -
2994 * Arrange for dead database removal
2998 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3001 PgStat_StatDBEntry *dbentry;
3004 * Make sure the backend is counted for.
3006 if (pgstat_add_backend(&msg->m_hdr) < 0)
3010 * Lookup the database in the hashtable.
3012 dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
3013 (void *) &(msg->m_hdr.m_databaseid),
3019 * We simply throw away all the databases table entries by recreating
3020 * a new hash table for them.
3022 if (dbentry->tables != NULL)
3023 hash_destroy(dbentry->tables);
3025 dbentry->tables = NULL;
3026 dbentry->n_xact_commit = 0;
3027 dbentry->n_xact_rollback = 0;
3028 dbentry->n_blocks_fetched = 0;
3029 dbentry->n_blocks_hit = 0;
3030 dbentry->n_connects = 0;
3031 dbentry->destroy = 0;
3033 memset(&hash_ctl, 0, sizeof(hash_ctl));
3034 hash_ctl.keysize = sizeof(Oid);
3035 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3036 hash_ctl.hash = tag_hash;
3037 dbentry->tables = hash_create("Per-database table",
3038 PGSTAT_TAB_HASH_SIZE,
3040 HASH_ELEM | HASH_FUNCTION);
3041 if (dbentry->tables == NULL)
3043 /* assume the problem is out-of-memory */
3045 (errcode(ERRCODE_OUT_OF_MEMORY),
3046 errmsg("out of memory in statistics collector --- abort")));