1 /* ----------
2  * pgstat.c
3  *
4  *	All the statistics collector stuff hacked up in one big, ugly file.
5  *
6  *	TODO:	- Separate collector, postmaster and backend stuff
7  *			  into different files.
8  *
9  *			- Add some automatic call for pgstat vacuuming.
10  *
11  *			- Add a pgstat config column to pg_database, so this
12  *			  entire thing can be enabled/disabled on a per db basis.
13  *
14  *	Copyright (c) 2001-2016, PostgreSQL Global Development Group
15  *
16  *	src/backend/postmaster/pgstat.c
17  * ----------
18  */
19 #include "postgres.h"
20 
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <sys/param.h>
24 #include <sys/time.h>
25 #include <sys/socket.h>
26 #include <netdb.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <signal.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_SELECT_H
32 #include <sys/select.h>
33 #endif
34 
35 #include "pgstat.h"
36 
37 #include "access/heapam.h"
38 #include "access/htup_details.h"
39 #include "access/transam.h"
40 #include "access/twophase_rmgr.h"
41 #include "access/xact.h"
42 #include "catalog/pg_database.h"
43 #include "catalog/pg_proc.h"
44 #include "libpq/ip.h"
45 #include "libpq/libpq.h"
46 #include "libpq/pqsignal.h"
47 #include "mb/pg_wchar.h"
48 #include "miscadmin.h"
49 #include "pg_trace.h"
50 #include "postmaster/autovacuum.h"
51 #include "postmaster/fork_process.h"
52 #include "postmaster/postmaster.h"
53 #include "storage/backendid.h"
54 #include "storage/dsm.h"
55 #include "storage/fd.h"
56 #include "storage/ipc.h"
57 #include "storage/latch.h"
58 #include "storage/lmgr.h"
59 #include "storage/pg_shmem.h"
60 #include "storage/procsignal.h"
61 #include "storage/sinvaladt.h"
62 #include "utils/ascii.h"
63 #include "utils/guc.h"
64 #include "utils/memutils.h"
65 #include "utils/ps_status.h"
66 #include "utils/rel.h"
67 #include "utils/snapmgr.h"
68 #include "utils/timestamp.h"
69 #include "utils/tqual.h"
70 
71 
72 /* ----------
73  * Timer definitions.
74  * ----------
75  */
76 #define PGSTAT_STAT_INTERVAL	500		/* Minimum time between stats file
77 										 * updates; in milliseconds. */
78 
79 #define PGSTAT_RETRY_DELAY		10		/* How long to wait between checks for
80 										 * a new file; in milliseconds. */
81 
82 #define PGSTAT_MAX_WAIT_TIME	10000	/* Maximum time to wait for a stats
83 										 * file update; in milliseconds. */
84 
85 #define PGSTAT_INQ_INTERVAL		640		/* How often to ping the collector for
86 										 * a new file; in milliseconds. */
87 
88 #define PGSTAT_RESTART_INTERVAL 60		/* How often to attempt to restart a
89 										 * failed statistics collector; in
90 										 * seconds. */
91 
92 #define PGSTAT_POLL_LOOP_COUNT	(PGSTAT_MAX_WAIT_TIME / PGSTAT_RETRY_DELAY)
93 #define PGSTAT_INQ_LOOP_COUNT	(PGSTAT_INQ_INTERVAL / PGSTAT_RETRY_DELAY)
94 
95 /* Minimum receive buffer size for the collector's socket. */
96 #define PGSTAT_MIN_RCVBUF		(100 * 1024)
97 
98 
99 /* ----------
100  * The initial size hints for the hash tables used in the collector.
101  * ----------
102  */
103 #define PGSTAT_DB_HASH_SIZE		16
104 #define PGSTAT_TAB_HASH_SIZE	512
105 #define PGSTAT_FUNCTION_HASH_SIZE	512
106 
107 
108 /* ----------
109  * GUC parameters
110  * ----------
111  */
112 bool		pgstat_track_activities = false;
113 bool		pgstat_track_counts = false;
114 int			pgstat_track_functions = TRACK_FUNC_OFF;
115 int			pgstat_track_activity_query_size = 1024;
116 
117 /* ----------
118  * Built from GUC parameter
119  * ----------
120  */
121 char	   *pgstat_stat_directory = NULL;
122 char	   *pgstat_stat_filename = NULL;
123 char	   *pgstat_stat_tmpname = NULL;
124 
125 /*
126  * BgWriter global statistics counters (unused in other processes).
127  * Stored directly in a stats message structure so it can be sent
128  * without needing to copy things around.  We assume this inits to zeroes.
129  */
130 PgStat_MsgBgWriter BgWriterStats;
131 
132 /* ----------
133  * Local data
134  * ----------
135  */
136 NON_EXEC_STATIC pgsocket pgStatSock = PGINVALID_SOCKET;
137 
138 static struct sockaddr_storage pgStatAddr;
139 
140 static time_t last_pgstat_start_time;
141 
142 static bool pgStatRunningInCollector = false;
143 
144 /*
145  * Structures in which backends store per-table info that's waiting to be
146  * sent to the collector.
147  *
148  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
149  * for the life of the backend.  Also, we zero out the t_id fields of the
150  * contained PgStat_TableStatus structs whenever they are not actively in use.
151  * This allows relcache pgstat_info pointers to be treated as long-lived data,
152  * avoiding repeated searches in pgstat_initstats() when a relation is
153  * repeatedly opened during a transaction.
154  */
155 #define TABSTAT_QUANTUM		100 /* we alloc this many at a time */
156 
157 typedef struct TabStatusArray
158 {
159 	struct TabStatusArray *tsa_next;	/* link to next array, if any */
160 	int			tsa_used;		/* # entries currently used */
161 	PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];	/* per-table data */
162 } TabStatusArray;
163 
164 static TabStatusArray *pgStatTabList = NULL;
165 
166 /*
167  * Backends store per-function info that's waiting to be sent to the collector
168  * in this hash table (indexed by function OID).
169  */
170 static HTAB *pgStatFunctions = NULL;
171 
172 /*
173  * Indicates if backend has some function stats that it hasn't yet
174  * sent to the collector.
175  */
176 static bool have_function_stats = false;
177 
178 /*
179  * Tuple insertion/deletion counts for an open transaction can't be propagated
180  * into PgStat_TableStatus counters until we know if it is going to commit
181  * or abort.  Hence, we keep these counts in per-subxact structs that live
182  * in TopTransactionContext.  This data structure is designed on the assumption
183  * that subxacts won't usually modify very many tables.
184  */
185 typedef struct PgStat_SubXactStatus
186 {
187 	int			nest_level;		/* subtransaction nest level */
188 	struct PgStat_SubXactStatus *prev;	/* higher-level subxact if any */
189 	PgStat_TableXactStatus *first;		/* head of list for this subxact */
190 } PgStat_SubXactStatus;
191 
192 static PgStat_SubXactStatus *pgStatXactStack = NULL;
193 
194 static int	pgStatXactCommit = 0;
195 static int	pgStatXactRollback = 0;
196 PgStat_Counter pgStatBlockReadTime = 0;
197 PgStat_Counter pgStatBlockWriteTime = 0;
198 
199 /* Record that's written to 2PC state file when pgstat state is persisted */
200 typedef struct TwoPhasePgStatRecord
201 {
202 	PgStat_Counter tuples_inserted;		/* tuples inserted in xact */
203 	PgStat_Counter tuples_updated;		/* tuples updated in xact */
204 	PgStat_Counter tuples_deleted;		/* tuples deleted in xact */
205 	PgStat_Counter inserted_pre_trunc;	/* tuples inserted prior to truncate */
206 	PgStat_Counter updated_pre_trunc;	/* tuples updated prior to truncate */
207 	PgStat_Counter deleted_pre_trunc;	/* tuples deleted prior to truncate */
208 	Oid			t_id;			/* table's OID */
209 	bool		t_shared;		/* is it a shared catalog? */
210 	bool		t_truncated;	/* was the relation truncated? */
211 } TwoPhasePgStatRecord;
212 
213 /*
214  * Info about current "snapshot" of stats file
215  */
216 static MemoryContext pgStatLocalContext = NULL;
217 static HTAB *pgStatDBHash = NULL;
218 static LocalPgBackendStatus *localBackendStatusTable = NULL;
219 static int	localNumBackends = 0;
220 
221 /*
222  * Cluster wide statistics, kept in the stats collector.
223  * Contains statistics that are not collected per database
224  * or per table.
225  */
226 static PgStat_ArchiverStats archiverStats;
227 static PgStat_GlobalStats globalStats;
228 
229 /*
230  * List of OIDs of databases we need to write out.  If an entry is InvalidOid,
231  * it means to write only the shared-catalog stats ("DB 0"); otherwise, we
232  * will write both that DB's data and the shared stats.
233  */
234 static List *pending_write_requests = NIL;
235 
236 /* Signal handler flags */
237 static volatile bool need_exit = false;
238 static volatile bool got_SIGHUP = false;
239 
240 /*
241  * Total time charged to functions so far in the current backend.
242  * We use this to help separate "self" and "other" time charges.
243  * (We assume this initializes to zero.)
244  */
245 static instr_time total_func_time;
246 
247 
248 /* ----------
249  * Local function forward declarations
250  * ----------
251  */
252 #ifdef EXEC_BACKEND
253 static pid_t pgstat_forkexec(void);
254 #endif
255 
256 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]) pg_attribute_noreturn();
257 static void pgstat_exit(SIGNAL_ARGS);
258 static void pgstat_beshutdown_hook(int code, Datum arg);
259 static void pgstat_sighup_handler(SIGNAL_ARGS);
260 
261 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
262 static PgStat_StatTabEntry *pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry,
263 					 Oid tableoid, bool create);
264 static void pgstat_write_statsfiles(bool permanent, bool allDbs);
265 static void pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent);
266 static HTAB *pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep);
267 static void pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash, bool permanent);
268 static void backend_read_statsfile(void);
269 static void pgstat_read_current_status(void);
270 
271 static bool pgstat_write_statsfile_needed(void);
272 static bool pgstat_db_requested(Oid databaseid);
273 
274 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
275 static void pgstat_send_funcstats(void);
276 static HTAB *pgstat_collect_oids(Oid catalogid);
277 
278 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
279 
280 static void pgstat_setup_memcxt(void);
281 
282 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
283 static void pgstat_send(void *msg, int len);
284 
285 static void pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len);
286 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
287 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
288 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
289 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
290 static void pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len);
291 static void pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len);
292 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
293 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
294 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
295 static void pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len);
296 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
297 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
298 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
299 static void pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len);
300 static void pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len);
301 static void pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len);
302 
303 /* ------------------------------------------------------------
304  * Public functions called from postmaster follow
305  * ------------------------------------------------------------
306  */
307 
308 /* ----------
309  * pgstat_init() -
310  *
311  *	Called from postmaster at startup. Create the resources required
312  *	by the statistics collector process.  If unable to do so, do not
313  *	fail --- better to let the postmaster start with stats collection
314  *	disabled.
315  * ----------
316  */
317 void
pgstat_init(void)318 pgstat_init(void)
319 {
320 	ACCEPT_TYPE_ARG3 alen;
321 	struct addrinfo *addrs = NULL,
322 			   *addr,
323 				hints;
324 	int			ret;
325 	fd_set		rset;
326 	struct timeval tv;
327 	char		test_byte;
328 	int			sel_res;
329 	int			tries = 0;
330 
331 #define TESTBYTEVAL ((char) 199)
332 
333 	/*
334 	 * This static assertion verifies that we didn't mess up the calculations
335 	 * involved in selecting maximum payload sizes for our UDP messages.
336 	 * Because the only consequence of overrunning PGSTAT_MAX_MSG_SIZE would
337 	 * be silent performance loss from fragmentation, it seems worth having a
338 	 * compile-time cross-check that we didn't.
339 	 */
340 	StaticAssertStmt(sizeof(PgStat_Msg) <= PGSTAT_MAX_MSG_SIZE,
341 				   "maximum stats message size exceeds PGSTAT_MAX_MSG_SIZE");
342 
343 	/*
344 	 * Create the UDP socket for sending and receiving statistic messages
345 	 */
346 	hints.ai_flags = AI_PASSIVE;
347 	hints.ai_family = AF_UNSPEC;
348 	hints.ai_socktype = SOCK_DGRAM;
349 	hints.ai_protocol = 0;
350 	hints.ai_addrlen = 0;
351 	hints.ai_addr = NULL;
352 	hints.ai_canonname = NULL;
353 	hints.ai_next = NULL;
354 	ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
355 	if (ret || !addrs)
356 	{
357 		ereport(LOG,
358 				(errmsg("could not resolve \"localhost\": %s",
359 						gai_strerror(ret))));
360 		goto startup_failed;
361 	}
362 
363 	/*
364 	 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
365 	 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
366 	 * when kernel will reject IPv6).  Worse, the failure may occur at the
367 	 * bind() or perhaps even connect() stage.  So we must loop through the
368 	 * results till we find a working combination. We will generate LOG
369 	 * messages, but no error, for bogus combinations.
370 	 */
371 	for (addr = addrs; addr; addr = addr->ai_next)
372 	{
373 #ifdef HAVE_UNIX_SOCKETS
374 		/* Ignore AF_UNIX sockets, if any are returned. */
375 		if (addr->ai_family == AF_UNIX)
376 			continue;
377 #endif
378 
379 		if (++tries > 1)
380 			ereport(LOG,
381 			(errmsg("trying another address for the statistics collector")));
382 
383 		/*
384 		 * Create the socket.
385 		 */
386 		if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) == PGINVALID_SOCKET)
387 		{
388 			ereport(LOG,
389 					(errcode_for_socket_access(),
390 			errmsg("could not create socket for statistics collector: %m")));
391 			continue;
392 		}
393 
394 		/*
395 		 * Bind it to a kernel assigned port on localhost and get the assigned
396 		 * port via getsockname().
397 		 */
398 		if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
399 		{
400 			ereport(LOG,
401 					(errcode_for_socket_access(),
402 			  errmsg("could not bind socket for statistics collector: %m")));
403 			closesocket(pgStatSock);
404 			pgStatSock = PGINVALID_SOCKET;
405 			continue;
406 		}
407 
408 		alen = sizeof(pgStatAddr);
409 		if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
410 		{
411 			ereport(LOG,
412 					(errcode_for_socket_access(),
413 					 errmsg("could not get address of socket for statistics collector: %m")));
414 			closesocket(pgStatSock);
415 			pgStatSock = PGINVALID_SOCKET;
416 			continue;
417 		}
418 
419 		/*
420 		 * Connect the socket to its own address.  This saves a few cycles by
421 		 * not having to respecify the target address on every send. This also
422 		 * provides a kernel-level check that only packets from this same
423 		 * address will be received.
424 		 */
425 		if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
426 		{
427 			ereport(LOG,
428 					(errcode_for_socket_access(),
429 			errmsg("could not connect socket for statistics collector: %m")));
430 			closesocket(pgStatSock);
431 			pgStatSock = PGINVALID_SOCKET;
432 			continue;
433 		}
434 
435 		/*
436 		 * Try to send and receive a one-byte test message on the socket. This
437 		 * is to catch situations where the socket can be created but will not
438 		 * actually pass data (for instance, because kernel packet filtering
439 		 * rules prevent it).
440 		 */
441 		test_byte = TESTBYTEVAL;
442 
443 retry1:
444 		if (send(pgStatSock, &test_byte, 1, 0) != 1)
445 		{
446 			if (errno == EINTR)
447 				goto retry1;	/* if interrupted, just retry */
448 			ereport(LOG,
449 					(errcode_for_socket_access(),
450 					 errmsg("could not send test message on socket for statistics collector: %m")));
451 			closesocket(pgStatSock);
452 			pgStatSock = PGINVALID_SOCKET;
453 			continue;
454 		}
455 
456 		/*
457 		 * There could possibly be a little delay before the message can be
458 		 * received.  We arbitrarily allow up to half a second before deciding
459 		 * it's broken.
460 		 */
461 		for (;;)				/* need a loop to handle EINTR */
462 		{
463 			FD_ZERO(&rset);
464 			FD_SET(pgStatSock, &rset);
465 
466 			tv.tv_sec = 0;
467 			tv.tv_usec = 500000;
468 			sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
469 			if (sel_res >= 0 || errno != EINTR)
470 				break;
471 		}
472 		if (sel_res < 0)
473 		{
474 			ereport(LOG,
475 					(errcode_for_socket_access(),
476 					 errmsg("select() failed in statistics collector: %m")));
477 			closesocket(pgStatSock);
478 			pgStatSock = PGINVALID_SOCKET;
479 			continue;
480 		}
481 		if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
482 		{
483 			/*
484 			 * This is the case we actually think is likely, so take pains to
485 			 * give a specific message for it.
486 			 *
487 			 * errno will not be set meaningfully here, so don't use it.
488 			 */
489 			ereport(LOG,
490 					(errcode(ERRCODE_CONNECTION_FAILURE),
491 					 errmsg("test message did not get through on socket for statistics collector")));
492 			closesocket(pgStatSock);
493 			pgStatSock = PGINVALID_SOCKET;
494 			continue;
495 		}
496 
497 		test_byte++;			/* just make sure variable is changed */
498 
499 retry2:
500 		if (recv(pgStatSock, &test_byte, 1, 0) != 1)
501 		{
502 			if (errno == EINTR)
503 				goto retry2;	/* if interrupted, just retry */
504 			ereport(LOG,
505 					(errcode_for_socket_access(),
506 					 errmsg("could not receive test message on socket for statistics collector: %m")));
507 			closesocket(pgStatSock);
508 			pgStatSock = PGINVALID_SOCKET;
509 			continue;
510 		}
511 
512 		if (test_byte != TESTBYTEVAL)	/* strictly paranoia ... */
513 		{
514 			ereport(LOG,
515 					(errcode(ERRCODE_INTERNAL_ERROR),
516 					 errmsg("incorrect test message transmission on socket for statistics collector")));
517 			closesocket(pgStatSock);
518 			pgStatSock = PGINVALID_SOCKET;
519 			continue;
520 		}
521 
522 		/* If we get here, we have a working socket */
523 		break;
524 	}
525 
526 	/* Did we find a working address? */
527 	if (!addr || pgStatSock == PGINVALID_SOCKET)
528 		goto startup_failed;
529 
530 	/*
531 	 * Set the socket to non-blocking IO.  This ensures that if the collector
532 	 * falls behind, statistics messages will be discarded; backends won't
533 	 * block waiting to send messages to the collector.
534 	 */
535 	if (!pg_set_noblock(pgStatSock))
536 	{
537 		ereport(LOG,
538 				(errcode_for_socket_access(),
539 				 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
540 		goto startup_failed;
541 	}
542 
543 	/*
544 	 * Try to ensure that the socket's receive buffer is at least
545 	 * PGSTAT_MIN_RCVBUF bytes, so that it won't easily overflow and lose
546 	 * data.  Use of UDP protocol means that we are willing to lose data under
547 	 * heavy load, but we don't want it to happen just because of ridiculously
548 	 * small default buffer sizes (such as 8KB on older Windows versions).
549 	 */
550 	{
551 		int			old_rcvbuf;
552 		int			new_rcvbuf;
553 		ACCEPT_TYPE_ARG3 rcvbufsize = sizeof(old_rcvbuf);
554 
555 		if (getsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
556 					   (char *) &old_rcvbuf, &rcvbufsize) < 0)
557 		{
558 			elog(LOG, "getsockopt(SO_RCVBUF) failed: %m");
559 			/* if we can't get existing size, always try to set it */
560 			old_rcvbuf = 0;
561 		}
562 
563 		new_rcvbuf = PGSTAT_MIN_RCVBUF;
564 		if (old_rcvbuf < new_rcvbuf)
565 		{
566 			if (setsockopt(pgStatSock, SOL_SOCKET, SO_RCVBUF,
567 						   (char *) &new_rcvbuf, sizeof(new_rcvbuf)) < 0)
568 				elog(LOG, "setsockopt(SO_RCVBUF) failed: %m");
569 		}
570 	}
571 
572 	pg_freeaddrinfo_all(hints.ai_family, addrs);
573 
574 	return;
575 
576 startup_failed:
577 	ereport(LOG,
578 	  (errmsg("disabling statistics collector for lack of working socket")));
579 
580 	if (addrs)
581 		pg_freeaddrinfo_all(hints.ai_family, addrs);
582 
583 	if (pgStatSock != PGINVALID_SOCKET)
584 		closesocket(pgStatSock);
585 	pgStatSock = PGINVALID_SOCKET;
586 
587 	/*
588 	 * Adjust GUC variables to suppress useless activity, and for debugging
589 	 * purposes (seeing track_counts off is a clue that we failed here). We
590 	 * use PGC_S_OVERRIDE because there is no point in trying to turn it back
591 	 * on from postgresql.conf without a restart.
592 	 */
593 	SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
594 }
595 
596 /*
597  * subroutine for pgstat_reset_all
598  */
599 static void
pgstat_reset_remove_files(const char * directory)600 pgstat_reset_remove_files(const char *directory)
601 {
602 	DIR		   *dir;
603 	struct dirent *entry;
604 	char		fname[MAXPGPATH * 2];
605 
606 	dir = AllocateDir(directory);
607 	while ((entry = ReadDir(dir, directory)) != NULL)
608 	{
609 		int			nchars;
610 		Oid			tmp_oid;
611 
612 		/*
613 		 * Skip directory entries that don't match the file names we write.
614 		 * See get_dbstat_filename for the database-specific pattern.
615 		 */
616 		if (strncmp(entry->d_name, "global.", 7) == 0)
617 			nchars = 7;
618 		else
619 		{
620 			nchars = 0;
621 			(void) sscanf(entry->d_name, "db_%u.%n",
622 						  &tmp_oid, &nchars);
623 			if (nchars <= 0)
624 				continue;
625 			/* %u allows leading whitespace, so reject that */
626 			if (strchr("0123456789", entry->d_name[3]) == NULL)
627 				continue;
628 		}
629 
630 		if (strcmp(entry->d_name + nchars, "tmp") != 0 &&
631 			strcmp(entry->d_name + nchars, "stat") != 0)
632 			continue;
633 
634 		snprintf(fname, sizeof(fname), "%s/%s", directory,
635 				 entry->d_name);
636 		unlink(fname);
637 	}
638 	FreeDir(dir);
639 }
640 
641 /*
642  * pgstat_reset_all() -
643  *
644  * Remove the stats files.  This is currently used only if WAL
645  * recovery is needed after a crash.
646  */
647 void
pgstat_reset_all(void)648 pgstat_reset_all(void)
649 {
650 	pgstat_reset_remove_files(pgstat_stat_directory);
651 	pgstat_reset_remove_files(PGSTAT_STAT_PERMANENT_DIRECTORY);
652 }
653 
654 #ifdef EXEC_BACKEND
655 
656 /*
657  * pgstat_forkexec() -
658  *
659  * Format up the arglist for, then fork and exec, statistics collector process
660  */
661 static pid_t
pgstat_forkexec(void)662 pgstat_forkexec(void)
663 {
664 	char	   *av[10];
665 	int			ac = 0;
666 
667 	av[ac++] = "postgres";
668 	av[ac++] = "--forkcol";
669 	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
670 
671 	av[ac] = NULL;
672 	Assert(ac < lengthof(av));
673 
674 	return postmaster_forkexec(ac, av);
675 }
676 #endif   /* EXEC_BACKEND */
677 
678 
679 /*
680  * pgstat_start() -
681  *
682  *	Called from postmaster at startup or after an existing collector
683  *	died.  Attempt to fire up a fresh statistics collector.
684  *
685  *	Returns PID of child process, or 0 if fail.
686  *
687  *	Note: if fail, we will be called again from the postmaster main loop.
688  */
689 int
pgstat_start(void)690 pgstat_start(void)
691 {
692 	time_t		curtime;
693 	pid_t		pgStatPid;
694 
695 	/*
696 	 * Check that the socket is there, else pgstat_init failed and we can do
697 	 * nothing useful.
698 	 */
699 	if (pgStatSock == PGINVALID_SOCKET)
700 		return 0;
701 
702 	/*
703 	 * Do nothing if too soon since last collector start.  This is a safety
704 	 * valve to protect against continuous respawn attempts if the collector
705 	 * is dying immediately at launch.  Note that since we will be re-called
706 	 * from the postmaster main loop, we will get another chance later.
707 	 */
708 	curtime = time(NULL);
709 	if ((unsigned int) (curtime - last_pgstat_start_time) <
710 		(unsigned int) PGSTAT_RESTART_INTERVAL)
711 		return 0;
712 	last_pgstat_start_time = curtime;
713 
714 	/*
715 	 * Okay, fork off the collector.
716 	 */
717 #ifdef EXEC_BACKEND
718 	switch ((pgStatPid = pgstat_forkexec()))
719 #else
720 	switch ((pgStatPid = fork_process()))
721 #endif
722 	{
723 		case -1:
724 			ereport(LOG,
725 					(errmsg("could not fork statistics collector: %m")));
726 			return 0;
727 
728 #ifndef EXEC_BACKEND
729 		case 0:
730 			/* in postmaster child ... */
731 			InitPostmasterChild();
732 
733 			/* Close the postmaster's sockets */
734 			ClosePostmasterPorts(false);
735 
736 			/* Drop our connection to postmaster's shared memory, as well */
737 			dsm_detach_all();
738 			PGSharedMemoryDetach();
739 
740 			PgstatCollectorMain(0, NULL);
741 			break;
742 #endif
743 
744 		default:
745 			return (int) pgStatPid;
746 	}
747 
748 	/* shouldn't get here */
749 	return 0;
750 }
751 
752 void
allow_immediate_pgstat_restart(void)753 allow_immediate_pgstat_restart(void)
754 {
755 	last_pgstat_start_time = 0;
756 }
757 
758 /* ------------------------------------------------------------
759  * Public functions used by backends follow
760  *------------------------------------------------------------
761  */
762 
763 
764 /* ----------
765  * pgstat_report_stat() -
766  *
767  *	Called from tcop/postgres.c to send the so far collected per-table
768  *	and function usage statistics to the collector.  Note that this is
769  *	called only when not within a transaction, so it is fair to use
770  *	transaction stop time as an approximation of current time.
771  * ----------
772  */
773 void
pgstat_report_stat(bool force)774 pgstat_report_stat(bool force)
775 {
776 	/* we assume this inits to all zeroes: */
777 	static const PgStat_TableCounts all_zeroes;
778 	static TimestampTz last_report = 0;
779 
780 	TimestampTz now;
781 	PgStat_MsgTabstat regular_msg;
782 	PgStat_MsgTabstat shared_msg;
783 	TabStatusArray *tsa;
784 	int			i;
785 
786 	/* Don't expend a clock check if nothing to do */
787 	if ((pgStatTabList == NULL || pgStatTabList->tsa_used == 0) &&
788 		pgStatXactCommit == 0 && pgStatXactRollback == 0 &&
789 		!have_function_stats)
790 		return;
791 
792 	/*
793 	 * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
794 	 * msec since we last sent one, or the caller wants to force stats out.
795 	 */
796 	now = GetCurrentTransactionStopTimestamp();
797 	if (!force &&
798 		!TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
799 		return;
800 	last_report = now;
801 
802 	/*
803 	 * Scan through the TabStatusArray struct(s) to find tables that actually
804 	 * have counts, and build messages to send.  We have to separate shared
805 	 * relations from regular ones because the databaseid field in the message
806 	 * header has to depend on that.
807 	 */
808 	regular_msg.m_databaseid = MyDatabaseId;
809 	shared_msg.m_databaseid = InvalidOid;
810 	regular_msg.m_nentries = 0;
811 	shared_msg.m_nentries = 0;
812 
813 	for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
814 	{
815 		for (i = 0; i < tsa->tsa_used; i++)
816 		{
817 			PgStat_TableStatus *entry = &tsa->tsa_entries[i];
818 			PgStat_MsgTabstat *this_msg;
819 			PgStat_TableEntry *this_ent;
820 
821 			/* Shouldn't have any pending transaction-dependent counts */
822 			Assert(entry->trans == NULL);
823 
824 			/*
825 			 * Ignore entries that didn't accumulate any actual counts, such
826 			 * as indexes that were opened by the planner but not used.
827 			 */
828 			if (memcmp(&entry->t_counts, &all_zeroes,
829 					   sizeof(PgStat_TableCounts)) == 0)
830 				continue;
831 
832 			/*
833 			 * OK, insert data into the appropriate message, and send if full.
834 			 */
835 			this_msg = entry->t_shared ? &shared_msg : &regular_msg;
836 			this_ent = &this_msg->m_entry[this_msg->m_nentries];
837 			this_ent->t_id = entry->t_id;
838 			memcpy(&this_ent->t_counts, &entry->t_counts,
839 				   sizeof(PgStat_TableCounts));
840 			if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
841 			{
842 				pgstat_send_tabstat(this_msg);
843 				this_msg->m_nentries = 0;
844 			}
845 		}
846 		/* zero out TableStatus structs after use */
847 		MemSet(tsa->tsa_entries, 0,
848 			   tsa->tsa_used * sizeof(PgStat_TableStatus));
849 		tsa->tsa_used = 0;
850 	}
851 
852 	/*
853 	 * Send partial messages.  Make sure that any pending xact commit/abort
854 	 * gets counted, even if there are no table stats to send.
855 	 */
856 	if (regular_msg.m_nentries > 0 ||
857 		pgStatXactCommit > 0 || pgStatXactRollback > 0)
858 		pgstat_send_tabstat(&regular_msg);
859 	if (shared_msg.m_nentries > 0)
860 		pgstat_send_tabstat(&shared_msg);
861 
862 	/* Now, send function statistics */
863 	pgstat_send_funcstats();
864 }
865 
866 /*
867  * Subroutine for pgstat_report_stat: finish and send a tabstat message
868  */
869 static void
pgstat_send_tabstat(PgStat_MsgTabstat * tsmsg)870 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
871 {
872 	int			n;
873 	int			len;
874 
875 	/* It's unlikely we'd get here with no socket, but maybe not impossible */
876 	if (pgStatSock == PGINVALID_SOCKET)
877 		return;
878 
879 	/*
880 	 * Report and reset accumulated xact commit/rollback and I/O timings
881 	 * whenever we send a normal tabstat message
882 	 */
883 	if (OidIsValid(tsmsg->m_databaseid))
884 	{
885 		tsmsg->m_xact_commit = pgStatXactCommit;
886 		tsmsg->m_xact_rollback = pgStatXactRollback;
887 		tsmsg->m_block_read_time = pgStatBlockReadTime;
888 		tsmsg->m_block_write_time = pgStatBlockWriteTime;
889 		pgStatXactCommit = 0;
890 		pgStatXactRollback = 0;
891 		pgStatBlockReadTime = 0;
892 		pgStatBlockWriteTime = 0;
893 	}
894 	else
895 	{
896 		tsmsg->m_xact_commit = 0;
897 		tsmsg->m_xact_rollback = 0;
898 		tsmsg->m_block_read_time = 0;
899 		tsmsg->m_block_write_time = 0;
900 	}
901 
902 	n = tsmsg->m_nentries;
903 	len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
904 		n * sizeof(PgStat_TableEntry);
905 
906 	pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
907 	pgstat_send(tsmsg, len);
908 }
909 
910 /*
911  * Subroutine for pgstat_report_stat: populate and send a function stat message
912  */
913 static void
pgstat_send_funcstats(void)914 pgstat_send_funcstats(void)
915 {
916 	/* we assume this inits to all zeroes: */
917 	static const PgStat_FunctionCounts all_zeroes;
918 
919 	PgStat_MsgFuncstat msg;
920 	PgStat_BackendFunctionEntry *entry;
921 	HASH_SEQ_STATUS fstat;
922 
923 	if (pgStatFunctions == NULL)
924 		return;
925 
926 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
927 	msg.m_databaseid = MyDatabaseId;
928 	msg.m_nentries = 0;
929 
930 	hash_seq_init(&fstat, pgStatFunctions);
931 	while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
932 	{
933 		PgStat_FunctionEntry *m_ent;
934 
935 		/* Skip it if no counts accumulated since last time */
936 		if (memcmp(&entry->f_counts, &all_zeroes,
937 				   sizeof(PgStat_FunctionCounts)) == 0)
938 			continue;
939 
940 		/* need to convert format of time accumulators */
941 		m_ent = &msg.m_entry[msg.m_nentries];
942 		m_ent->f_id = entry->f_id;
943 		m_ent->f_numcalls = entry->f_counts.f_numcalls;
944 		m_ent->f_total_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_total_time);
945 		m_ent->f_self_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_self_time);
946 
947 		if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
948 		{
949 			pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
950 						msg.m_nentries * sizeof(PgStat_FunctionEntry));
951 			msg.m_nentries = 0;
952 		}
953 
954 		/* reset the entry's counts */
955 		MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
956 	}
957 
958 	if (msg.m_nentries > 0)
959 		pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
960 					msg.m_nentries * sizeof(PgStat_FunctionEntry));
961 
962 	have_function_stats = false;
963 }
964 
965 
966 /* ----------
967  * pgstat_vacuum_stat() -
968  *
969  *	Will tell the collector about objects he can get rid of.
970  * ----------
971  */
972 void
pgstat_vacuum_stat(void)973 pgstat_vacuum_stat(void)
974 {
975 	HTAB	   *htab;
976 	PgStat_MsgTabpurge msg;
977 	PgStat_MsgFuncpurge f_msg;
978 	HASH_SEQ_STATUS hstat;
979 	PgStat_StatDBEntry *dbentry;
980 	PgStat_StatTabEntry *tabentry;
981 	PgStat_StatFuncEntry *funcentry;
982 	int			len;
983 
984 	if (pgStatSock == PGINVALID_SOCKET)
985 		return;
986 
987 	/*
988 	 * If not done for this transaction, read the statistics collector stats
989 	 * file into some hash tables.
990 	 */
991 	backend_read_statsfile();
992 
993 	/*
994 	 * Read pg_database and make a list of OIDs of all existing databases
995 	 */
996 	htab = pgstat_collect_oids(DatabaseRelationId);
997 
998 	/*
999 	 * Search the database hash table for dead databases and tell the
1000 	 * collector to drop them.
1001 	 */
1002 	hash_seq_init(&hstat, pgStatDBHash);
1003 	while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
1004 	{
1005 		Oid			dbid = dbentry->databaseid;
1006 
1007 		CHECK_FOR_INTERRUPTS();
1008 
1009 		/* the DB entry for shared tables (with InvalidOid) is never dropped */
1010 		if (OidIsValid(dbid) &&
1011 			hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
1012 			pgstat_drop_database(dbid);
1013 	}
1014 
1015 	/* Clean up */
1016 	hash_destroy(htab);
1017 
1018 	/*
1019 	 * Lookup our own database entry; if not found, nothing more to do.
1020 	 */
1021 	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1022 												 (void *) &MyDatabaseId,
1023 												 HASH_FIND, NULL);
1024 	if (dbentry == NULL || dbentry->tables == NULL)
1025 		return;
1026 
1027 	/*
1028 	 * Similarly to above, make a list of all known relations in this DB.
1029 	 */
1030 	htab = pgstat_collect_oids(RelationRelationId);
1031 
1032 	/*
1033 	 * Initialize our messages table counter to zero
1034 	 */
1035 	msg.m_nentries = 0;
1036 
1037 	/*
1038 	 * Check for all tables listed in stats hashtable if they still exist.
1039 	 */
1040 	hash_seq_init(&hstat, dbentry->tables);
1041 	while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
1042 	{
1043 		Oid			tabid = tabentry->tableid;
1044 
1045 		CHECK_FOR_INTERRUPTS();
1046 
1047 		if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
1048 			continue;
1049 
1050 		/*
1051 		 * Not there, so add this table's Oid to the message
1052 		 */
1053 		msg.m_tableid[msg.m_nentries++] = tabid;
1054 
1055 		/*
1056 		 * If the message is full, send it out and reinitialize to empty
1057 		 */
1058 		if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
1059 		{
1060 			len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1061 				+msg.m_nentries * sizeof(Oid);
1062 
1063 			pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1064 			msg.m_databaseid = MyDatabaseId;
1065 			pgstat_send(&msg, len);
1066 
1067 			msg.m_nentries = 0;
1068 		}
1069 	}
1070 
1071 	/*
1072 	 * Send the rest
1073 	 */
1074 	if (msg.m_nentries > 0)
1075 	{
1076 		len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
1077 			+msg.m_nentries * sizeof(Oid);
1078 
1079 		pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1080 		msg.m_databaseid = MyDatabaseId;
1081 		pgstat_send(&msg, len);
1082 	}
1083 
1084 	/* Clean up */
1085 	hash_destroy(htab);
1086 
1087 	/*
1088 	 * Now repeat the above steps for functions.  However, we needn't bother
1089 	 * in the common case where no function stats are being collected.
1090 	 */
1091 	if (dbentry->functions != NULL &&
1092 		hash_get_num_entries(dbentry->functions) > 0)
1093 	{
1094 		htab = pgstat_collect_oids(ProcedureRelationId);
1095 
1096 		pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
1097 		f_msg.m_databaseid = MyDatabaseId;
1098 		f_msg.m_nentries = 0;
1099 
1100 		hash_seq_init(&hstat, dbentry->functions);
1101 		while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
1102 		{
1103 			Oid			funcid = funcentry->functionid;
1104 
1105 			CHECK_FOR_INTERRUPTS();
1106 
1107 			if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
1108 				continue;
1109 
1110 			/*
1111 			 * Not there, so add this function's Oid to the message
1112 			 */
1113 			f_msg.m_functionid[f_msg.m_nentries++] = funcid;
1114 
1115 			/*
1116 			 * If the message is full, send it out and reinitialize to empty
1117 			 */
1118 			if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
1119 			{
1120 				len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1121 					+f_msg.m_nentries * sizeof(Oid);
1122 
1123 				pgstat_send(&f_msg, len);
1124 
1125 				f_msg.m_nentries = 0;
1126 			}
1127 		}
1128 
1129 		/*
1130 		 * Send the rest
1131 		 */
1132 		if (f_msg.m_nentries > 0)
1133 		{
1134 			len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
1135 				+f_msg.m_nentries * sizeof(Oid);
1136 
1137 			pgstat_send(&f_msg, len);
1138 		}
1139 
1140 		hash_destroy(htab);
1141 	}
1142 }
1143 
1144 
1145 /* ----------
1146  * pgstat_collect_oids() -
1147  *
1148  *	Collect the OIDs of all objects listed in the specified system catalog
1149  *	into a temporary hash table.  Caller should hash_destroy the result
1150  *	when done with it.  (However, we make the table in CurrentMemoryContext
1151  *	so that it will be freed properly in event of an error.)
1152  * ----------
1153  */
1154 static HTAB *
pgstat_collect_oids(Oid catalogid)1155 pgstat_collect_oids(Oid catalogid)
1156 {
1157 	HTAB	   *htab;
1158 	HASHCTL		hash_ctl;
1159 	Relation	rel;
1160 	HeapScanDesc scan;
1161 	HeapTuple	tup;
1162 	Snapshot	snapshot;
1163 
1164 	memset(&hash_ctl, 0, sizeof(hash_ctl));
1165 	hash_ctl.keysize = sizeof(Oid);
1166 	hash_ctl.entrysize = sizeof(Oid);
1167 	hash_ctl.hcxt = CurrentMemoryContext;
1168 	htab = hash_create("Temporary table of OIDs",
1169 					   PGSTAT_TAB_HASH_SIZE,
1170 					   &hash_ctl,
1171 					   HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1172 
1173 	rel = heap_open(catalogid, AccessShareLock);
1174 	snapshot = RegisterSnapshot(GetLatestSnapshot());
1175 	scan = heap_beginscan(rel, snapshot, 0, NULL);
1176 	while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1177 	{
1178 		Oid			thisoid = HeapTupleGetOid(tup);
1179 
1180 		CHECK_FOR_INTERRUPTS();
1181 
1182 		(void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1183 	}
1184 	heap_endscan(scan);
1185 	UnregisterSnapshot(snapshot);
1186 	heap_close(rel, AccessShareLock);
1187 
1188 	return htab;
1189 }
1190 
1191 
1192 /* ----------
1193  * pgstat_drop_database() -
1194  *
1195  *	Tell the collector that we just dropped a database.
1196  *	(If the message gets lost, we will still clean the dead DB eventually
1197  *	via future invocations of pgstat_vacuum_stat().)
1198  * ----------
1199  */
1200 void
pgstat_drop_database(Oid databaseid)1201 pgstat_drop_database(Oid databaseid)
1202 {
1203 	PgStat_MsgDropdb msg;
1204 
1205 	if (pgStatSock == PGINVALID_SOCKET)
1206 		return;
1207 
1208 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1209 	msg.m_databaseid = databaseid;
1210 	pgstat_send(&msg, sizeof(msg));
1211 }
1212 
1213 
1214 /* ----------
1215  * pgstat_drop_relation() -
1216  *
1217  *	Tell the collector that we just dropped a relation.
1218  *	(If the message gets lost, we will still clean the dead entry eventually
1219  *	via future invocations of pgstat_vacuum_stat().)
1220  *
1221  *	Currently not used for lack of any good place to call it; we rely
1222  *	entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1223  * ----------
1224  */
1225 #ifdef NOT_USED
1226 void
pgstat_drop_relation(Oid relid)1227 pgstat_drop_relation(Oid relid)
1228 {
1229 	PgStat_MsgTabpurge msg;
1230 	int			len;
1231 
1232 	if (pgStatSock == PGINVALID_SOCKET)
1233 		return;
1234 
1235 	msg.m_tableid[0] = relid;
1236 	msg.m_nentries = 1;
1237 
1238 	len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
1239 
1240 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1241 	msg.m_databaseid = MyDatabaseId;
1242 	pgstat_send(&msg, len);
1243 }
1244 #endif   /* NOT_USED */
1245 
1246 
1247 /* ----------
1248  * pgstat_reset_counters() -
1249  *
1250  *	Tell the statistics collector to reset counters for our database.
1251  *
1252  *	Permission checking for this function is managed through the normal
1253  *	GRANT system.
1254  * ----------
1255  */
1256 void
pgstat_reset_counters(void)1257 pgstat_reset_counters(void)
1258 {
1259 	PgStat_MsgResetcounter msg;
1260 
1261 	if (pgStatSock == PGINVALID_SOCKET)
1262 		return;
1263 
1264 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1265 	msg.m_databaseid = MyDatabaseId;
1266 	pgstat_send(&msg, sizeof(msg));
1267 }
1268 
1269 /* ----------
1270  * pgstat_reset_shared_counters() -
1271  *
1272  *	Tell the statistics collector to reset cluster-wide shared counters.
1273  *
1274  *	Permission checking for this function is managed through the normal
1275  *	GRANT system.
1276  * ----------
1277  */
1278 void
pgstat_reset_shared_counters(const char * target)1279 pgstat_reset_shared_counters(const char *target)
1280 {
1281 	PgStat_MsgResetsharedcounter msg;
1282 
1283 	if (pgStatSock == PGINVALID_SOCKET)
1284 		return;
1285 
1286 	if (strcmp(target, "archiver") == 0)
1287 		msg.m_resettarget = RESET_ARCHIVER;
1288 	else if (strcmp(target, "bgwriter") == 0)
1289 		msg.m_resettarget = RESET_BGWRITER;
1290 	else
1291 		ereport(ERROR,
1292 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1293 				 errmsg("unrecognized reset target: \"%s\"", target),
1294 				 errhint("Target must be \"archiver\" or \"bgwriter\".")));
1295 
1296 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSHAREDCOUNTER);
1297 	pgstat_send(&msg, sizeof(msg));
1298 }
1299 
1300 /* ----------
1301  * pgstat_reset_single_counter() -
1302  *
1303  *	Tell the statistics collector to reset a single counter.
1304  *
1305  *	Permission checking for this function is managed through the normal
1306  *	GRANT system.
1307  * ----------
1308  */
1309 void
pgstat_reset_single_counter(Oid objoid,PgStat_Single_Reset_Type type)1310 pgstat_reset_single_counter(Oid objoid, PgStat_Single_Reset_Type type)
1311 {
1312 	PgStat_MsgResetsinglecounter msg;
1313 
1314 	if (pgStatSock == PGINVALID_SOCKET)
1315 		return;
1316 
1317 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETSINGLECOUNTER);
1318 	msg.m_databaseid = MyDatabaseId;
1319 	msg.m_resettype = type;
1320 	msg.m_objectid = objoid;
1321 
1322 	pgstat_send(&msg, sizeof(msg));
1323 }
1324 
1325 /* ----------
1326  * pgstat_report_autovac() -
1327  *
1328  *	Called from autovacuum.c to report startup of an autovacuum process.
1329  *	We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1330  *	the db OID must be passed in, instead.
1331  * ----------
1332  */
1333 void
pgstat_report_autovac(Oid dboid)1334 pgstat_report_autovac(Oid dboid)
1335 {
1336 	PgStat_MsgAutovacStart msg;
1337 
1338 	if (pgStatSock == PGINVALID_SOCKET)
1339 		return;
1340 
1341 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1342 	msg.m_databaseid = dboid;
1343 	msg.m_start_time = GetCurrentTimestamp();
1344 
1345 	pgstat_send(&msg, sizeof(msg));
1346 }
1347 
1348 
1349 /* ---------
1350  * pgstat_report_vacuum() -
1351  *
1352  *	Tell the collector about the table we just vacuumed.
1353  * ---------
1354  */
1355 void
pgstat_report_vacuum(Oid tableoid,bool shared,PgStat_Counter livetuples,PgStat_Counter deadtuples)1356 pgstat_report_vacuum(Oid tableoid, bool shared,
1357 					 PgStat_Counter livetuples, PgStat_Counter deadtuples)
1358 {
1359 	PgStat_MsgVacuum msg;
1360 
1361 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1362 		return;
1363 
1364 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1365 	msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1366 	msg.m_tableoid = tableoid;
1367 	msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1368 	msg.m_vacuumtime = GetCurrentTimestamp();
1369 	msg.m_live_tuples = livetuples;
1370 	msg.m_dead_tuples = deadtuples;
1371 	pgstat_send(&msg, sizeof(msg));
1372 }
1373 
1374 /* --------
1375  * pgstat_report_analyze() -
1376  *
1377  *	Tell the collector about the table we just analyzed.
1378  *
1379  * Caller must provide new live- and dead-tuples estimates, as well as a
1380  * flag indicating whether to reset the changes_since_analyze counter.
1381  * --------
1382  */
1383 void
pgstat_report_analyze(Relation rel,PgStat_Counter livetuples,PgStat_Counter deadtuples,bool resetcounter)1384 pgstat_report_analyze(Relation rel,
1385 					  PgStat_Counter livetuples, PgStat_Counter deadtuples,
1386 					  bool resetcounter)
1387 {
1388 	PgStat_MsgAnalyze msg;
1389 
1390 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1391 		return;
1392 
1393 	/*
1394 	 * Unlike VACUUM, ANALYZE might be running inside a transaction that has
1395 	 * already inserted and/or deleted rows in the target table. ANALYZE will
1396 	 * have counted such rows as live or dead respectively. Because we will
1397 	 * report our counts of such rows at transaction end, we should subtract
1398 	 * off these counts from what we send to the collector now, else they'll
1399 	 * be double-counted after commit.  (This approach also ensures that the
1400 	 * collector ends up with the right numbers if we abort instead of
1401 	 * committing.)
1402 	 */
1403 	if (rel->pgstat_info != NULL)
1404 	{
1405 		PgStat_TableXactStatus *trans;
1406 
1407 		for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1408 		{
1409 			livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1410 			deadtuples -= trans->tuples_updated + trans->tuples_deleted;
1411 		}
1412 		/* count stuff inserted by already-aborted subxacts, too */
1413 		deadtuples -= rel->pgstat_info->t_counts.t_delta_dead_tuples;
1414 		/* Since ANALYZE's counts are estimates, we could have underflowed */
1415 		livetuples = Max(livetuples, 0);
1416 		deadtuples = Max(deadtuples, 0);
1417 	}
1418 
1419 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1420 	msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1421 	msg.m_tableoid = RelationGetRelid(rel);
1422 	msg.m_autovacuum = IsAutoVacuumWorkerProcess();
1423 	msg.m_resetcounter = resetcounter;
1424 	msg.m_analyzetime = GetCurrentTimestamp();
1425 	msg.m_live_tuples = livetuples;
1426 	msg.m_dead_tuples = deadtuples;
1427 	pgstat_send(&msg, sizeof(msg));
1428 }
1429 
1430 /* --------
1431  * pgstat_report_recovery_conflict() -
1432  *
1433  *	Tell the collector about a Hot Standby recovery conflict.
1434  * --------
1435  */
1436 void
pgstat_report_recovery_conflict(int reason)1437 pgstat_report_recovery_conflict(int reason)
1438 {
1439 	PgStat_MsgRecoveryConflict msg;
1440 
1441 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1442 		return;
1443 
1444 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RECOVERYCONFLICT);
1445 	msg.m_databaseid = MyDatabaseId;
1446 	msg.m_reason = reason;
1447 	pgstat_send(&msg, sizeof(msg));
1448 }
1449 
1450 /* --------
1451  * pgstat_report_deadlock() -
1452  *
1453  *	Tell the collector about a deadlock detected.
1454  * --------
1455  */
1456 void
pgstat_report_deadlock(void)1457 pgstat_report_deadlock(void)
1458 {
1459 	PgStat_MsgDeadlock msg;
1460 
1461 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1462 		return;
1463 
1464 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DEADLOCK);
1465 	msg.m_databaseid = MyDatabaseId;
1466 	pgstat_send(&msg, sizeof(msg));
1467 }
1468 
1469 /* --------
1470  * pgstat_report_tempfile() -
1471  *
1472  *	Tell the collector about a temporary file.
1473  * --------
1474  */
1475 void
pgstat_report_tempfile(size_t filesize)1476 pgstat_report_tempfile(size_t filesize)
1477 {
1478 	PgStat_MsgTempFile msg;
1479 
1480 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1481 		return;
1482 
1483 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TEMPFILE);
1484 	msg.m_databaseid = MyDatabaseId;
1485 	msg.m_filesize = filesize;
1486 	pgstat_send(&msg, sizeof(msg));
1487 }
1488 
1489 
1490 /* ----------
1491  * pgstat_ping() -
1492  *
1493  *	Send some junk data to the collector to increase traffic.
1494  * ----------
1495  */
1496 void
pgstat_ping(void)1497 pgstat_ping(void)
1498 {
1499 	PgStat_MsgDummy msg;
1500 
1501 	if (pgStatSock == PGINVALID_SOCKET)
1502 		return;
1503 
1504 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1505 	pgstat_send(&msg, sizeof(msg));
1506 }
1507 
1508 /* ----------
1509  * pgstat_send_inquiry() -
1510  *
1511  *	Notify collector that we need fresh data.
1512  * ----------
1513  */
1514 static void
pgstat_send_inquiry(TimestampTz clock_time,TimestampTz cutoff_time,Oid databaseid)1515 pgstat_send_inquiry(TimestampTz clock_time, TimestampTz cutoff_time, Oid databaseid)
1516 {
1517 	PgStat_MsgInquiry msg;
1518 
1519 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_INQUIRY);
1520 	msg.clock_time = clock_time;
1521 	msg.cutoff_time = cutoff_time;
1522 	msg.databaseid = databaseid;
1523 	pgstat_send(&msg, sizeof(msg));
1524 }
1525 
1526 
1527 /*
1528  * Initialize function call usage data.
1529  * Called by the executor before invoking a function.
1530  */
1531 void
pgstat_init_function_usage(FunctionCallInfoData * fcinfo,PgStat_FunctionCallUsage * fcu)1532 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
1533 						   PgStat_FunctionCallUsage *fcu)
1534 {
1535 	PgStat_BackendFunctionEntry *htabent;
1536 	bool		found;
1537 
1538 	if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1539 	{
1540 		/* stats not wanted */
1541 		fcu->fs = NULL;
1542 		return;
1543 	}
1544 
1545 	if (!pgStatFunctions)
1546 	{
1547 		/* First time through - initialize function stat table */
1548 		HASHCTL		hash_ctl;
1549 
1550 		memset(&hash_ctl, 0, sizeof(hash_ctl));
1551 		hash_ctl.keysize = sizeof(Oid);
1552 		hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1553 		pgStatFunctions = hash_create("Function stat entries",
1554 									  PGSTAT_FUNCTION_HASH_SIZE,
1555 									  &hash_ctl,
1556 									  HASH_ELEM | HASH_BLOBS);
1557 	}
1558 
1559 	/* Get the stats entry for this function, create if necessary */
1560 	htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1561 						  HASH_ENTER, &found);
1562 	if (!found)
1563 		MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1564 
1565 	fcu->fs = &htabent->f_counts;
1566 
1567 	/* save stats for this function, later used to compensate for recursion */
1568 	fcu->save_f_total_time = htabent->f_counts.f_total_time;
1569 
1570 	/* save current backend-wide total time */
1571 	fcu->save_total = total_func_time;
1572 
1573 	/* get clock time as of function start */
1574 	INSTR_TIME_SET_CURRENT(fcu->f_start);
1575 }
1576 
1577 /*
1578  * find_funcstat_entry - find any existing PgStat_BackendFunctionEntry entry
1579  *		for specified function
1580  *
1581  * If no entry, return NULL, don't create a new one
1582  */
1583 PgStat_BackendFunctionEntry *
find_funcstat_entry(Oid func_id)1584 find_funcstat_entry(Oid func_id)
1585 {
1586 	if (pgStatFunctions == NULL)
1587 		return NULL;
1588 
1589 	return (PgStat_BackendFunctionEntry *) hash_search(pgStatFunctions,
1590 													   (void *) &func_id,
1591 													   HASH_FIND, NULL);
1592 }
1593 
1594 /*
1595  * Calculate function call usage and update stat counters.
1596  * Called by the executor after invoking a function.
1597  *
1598  * In the case of a set-returning function that runs in value-per-call mode,
1599  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1600  * calls for what the user considers a single call of the function.  The
1601  * finalize flag should be TRUE on the last call.
1602  */
1603 void
pgstat_end_function_usage(PgStat_FunctionCallUsage * fcu,bool finalize)1604 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1605 {
1606 	PgStat_FunctionCounts *fs = fcu->fs;
1607 	instr_time	f_total;
1608 	instr_time	f_others;
1609 	instr_time	f_self;
1610 
1611 	/* stats not wanted? */
1612 	if (fs == NULL)
1613 		return;
1614 
1615 	/* total elapsed time in this function call */
1616 	INSTR_TIME_SET_CURRENT(f_total);
1617 	INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1618 
1619 	/* self usage: elapsed minus anything already charged to other calls */
1620 	f_others = total_func_time;
1621 	INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1622 	f_self = f_total;
1623 	INSTR_TIME_SUBTRACT(f_self, f_others);
1624 
1625 	/* update backend-wide total time */
1626 	INSTR_TIME_ADD(total_func_time, f_self);
1627 
1628 	/*
1629 	 * Compute the new f_total_time as the total elapsed time added to the
1630 	 * pre-call value of f_total_time.  This is necessary to avoid
1631 	 * double-counting any time taken by recursive calls of myself.  (We do
1632 	 * not need any similar kluge for self time, since that already excludes
1633 	 * any recursive calls.)
1634 	 */
1635 	INSTR_TIME_ADD(f_total, fcu->save_f_total_time);
1636 
1637 	/* update counters in function stats table */
1638 	if (finalize)
1639 		fs->f_numcalls++;
1640 	fs->f_total_time = f_total;
1641 	INSTR_TIME_ADD(fs->f_self_time, f_self);
1642 
1643 	/* indicate that we have something to send */
1644 	have_function_stats = true;
1645 }
1646 
1647 
1648 /* ----------
1649  * pgstat_initstats() -
1650  *
1651  *	Initialize a relcache entry to count access statistics.
1652  *	Called whenever a relation is opened.
1653  *
1654  *	We assume that a relcache entry's pgstat_info field is zeroed by
1655  *	relcache.c when the relcache entry is made; thereafter it is long-lived
1656  *	data.  We can avoid repeated searches of the TabStatus arrays when the
1657  *	same relation is touched repeatedly within a transaction.
1658  * ----------
1659  */
1660 void
pgstat_initstats(Relation rel)1661 pgstat_initstats(Relation rel)
1662 {
1663 	Oid			rel_id = rel->rd_id;
1664 	char		relkind = rel->rd_rel->relkind;
1665 
1666 	/* We only count stats for things that have storage */
1667 	if (!(relkind == RELKIND_RELATION ||
1668 		  relkind == RELKIND_MATVIEW ||
1669 		  relkind == RELKIND_INDEX ||
1670 		  relkind == RELKIND_TOASTVALUE ||
1671 		  relkind == RELKIND_SEQUENCE))
1672 	{
1673 		rel->pgstat_info = NULL;
1674 		return;
1675 	}
1676 
1677 	if (pgStatSock == PGINVALID_SOCKET || !pgstat_track_counts)
1678 	{
1679 		/* We're not counting at all */
1680 		rel->pgstat_info = NULL;
1681 		return;
1682 	}
1683 
1684 	/*
1685 	 * If we already set up this relation in the current transaction, nothing
1686 	 * to do.
1687 	 */
1688 	if (rel->pgstat_info != NULL &&
1689 		rel->pgstat_info->t_id == rel_id)
1690 		return;
1691 
1692 	/* Else find or make the PgStat_TableStatus entry, and update link */
1693 	rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1694 }
1695 
1696 /*
1697  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1698  */
1699 static PgStat_TableStatus *
get_tabstat_entry(Oid rel_id,bool isshared)1700 get_tabstat_entry(Oid rel_id, bool isshared)
1701 {
1702 	PgStat_TableStatus *entry;
1703 	TabStatusArray *tsa;
1704 	TabStatusArray *prev_tsa;
1705 	int			i;
1706 
1707 	/*
1708 	 * Search the already-used tabstat slots for this relation.
1709 	 */
1710 	prev_tsa = NULL;
1711 	for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1712 	{
1713 		for (i = 0; i < tsa->tsa_used; i++)
1714 		{
1715 			entry = &tsa->tsa_entries[i];
1716 			if (entry->t_id == rel_id)
1717 				return entry;
1718 		}
1719 
1720 		if (tsa->tsa_used < TABSTAT_QUANTUM)
1721 		{
1722 			/*
1723 			 * It must not be present, but we found a free slot instead. Fine,
1724 			 * let's use this one.  We assume the entry was already zeroed,
1725 			 * either at creation or after last use.
1726 			 */
1727 			entry = &tsa->tsa_entries[tsa->tsa_used++];
1728 			entry->t_id = rel_id;
1729 			entry->t_shared = isshared;
1730 			return entry;
1731 		}
1732 	}
1733 
1734 	/*
1735 	 * We ran out of tabstat slots, so allocate more.  Be sure they're zeroed.
1736 	 */
1737 	tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1738 													sizeof(TabStatusArray));
1739 	if (prev_tsa)
1740 		prev_tsa->tsa_next = tsa;
1741 	else
1742 		pgStatTabList = tsa;
1743 
1744 	/*
1745 	 * Use the first entry of the new TabStatusArray.
1746 	 */
1747 	entry = &tsa->tsa_entries[tsa->tsa_used++];
1748 	entry->t_id = rel_id;
1749 	entry->t_shared = isshared;
1750 	return entry;
1751 }
1752 
1753 /*
1754  * find_tabstat_entry - find any existing PgStat_TableStatus entry for rel
1755  *
1756  * If no entry, return NULL, don't create a new one
1757  */
1758 PgStat_TableStatus *
find_tabstat_entry(Oid rel_id)1759 find_tabstat_entry(Oid rel_id)
1760 {
1761 	PgStat_TableStatus *entry;
1762 	TabStatusArray *tsa;
1763 	int			i;
1764 
1765 	for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
1766 	{
1767 		for (i = 0; i < tsa->tsa_used; i++)
1768 		{
1769 			entry = &tsa->tsa_entries[i];
1770 			if (entry->t_id == rel_id)
1771 				return entry;
1772 		}
1773 	}
1774 
1775 	/* Not present */
1776 	return NULL;
1777 }
1778 
1779 /*
1780  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1781  */
1782 static PgStat_SubXactStatus *
get_tabstat_stack_level(int nest_level)1783 get_tabstat_stack_level(int nest_level)
1784 {
1785 	PgStat_SubXactStatus *xact_state;
1786 
1787 	xact_state = pgStatXactStack;
1788 	if (xact_state == NULL || xact_state->nest_level != nest_level)
1789 	{
1790 		xact_state = (PgStat_SubXactStatus *)
1791 			MemoryContextAlloc(TopTransactionContext,
1792 							   sizeof(PgStat_SubXactStatus));
1793 		xact_state->nest_level = nest_level;
1794 		xact_state->prev = pgStatXactStack;
1795 		xact_state->first = NULL;
1796 		pgStatXactStack = xact_state;
1797 	}
1798 	return xact_state;
1799 }
1800 
1801 /*
1802  * add_tabstat_xact_level - add a new (sub)transaction state record
1803  */
1804 static void
add_tabstat_xact_level(PgStat_TableStatus * pgstat_info,int nest_level)1805 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1806 {
1807 	PgStat_SubXactStatus *xact_state;
1808 	PgStat_TableXactStatus *trans;
1809 
1810 	/*
1811 	 * If this is the first rel to be modified at the current nest level, we
1812 	 * first have to push a transaction stack entry.
1813 	 */
1814 	xact_state = get_tabstat_stack_level(nest_level);
1815 
1816 	/* Now make a per-table stack entry */
1817 	trans = (PgStat_TableXactStatus *)
1818 		MemoryContextAllocZero(TopTransactionContext,
1819 							   sizeof(PgStat_TableXactStatus));
1820 	trans->nest_level = nest_level;
1821 	trans->upper = pgstat_info->trans;
1822 	trans->parent = pgstat_info;
1823 	trans->next = xact_state->first;
1824 	xact_state->first = trans;
1825 	pgstat_info->trans = trans;
1826 }
1827 
1828 /*
1829  * pgstat_count_heap_insert - count a tuple insertion of n tuples
1830  */
1831 void
pgstat_count_heap_insert(Relation rel,int n)1832 pgstat_count_heap_insert(Relation rel, int n)
1833 {
1834 	PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1835 
1836 	if (pgstat_info != NULL)
1837 	{
1838 		/* We have to log the effect at the proper transactional level */
1839 		int			nest_level = GetCurrentTransactionNestLevel();
1840 
1841 		if (pgstat_info->trans == NULL ||
1842 			pgstat_info->trans->nest_level != nest_level)
1843 			add_tabstat_xact_level(pgstat_info, nest_level);
1844 
1845 		pgstat_info->trans->tuples_inserted += n;
1846 	}
1847 }
1848 
1849 /*
1850  * pgstat_count_heap_update - count a tuple update
1851  */
1852 void
pgstat_count_heap_update(Relation rel,bool hot)1853 pgstat_count_heap_update(Relation rel, bool hot)
1854 {
1855 	PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1856 
1857 	if (pgstat_info != NULL)
1858 	{
1859 		/* We have to log the effect at the proper transactional level */
1860 		int			nest_level = GetCurrentTransactionNestLevel();
1861 
1862 		if (pgstat_info->trans == NULL ||
1863 			pgstat_info->trans->nest_level != nest_level)
1864 			add_tabstat_xact_level(pgstat_info, nest_level);
1865 
1866 		pgstat_info->trans->tuples_updated++;
1867 
1868 		/* t_tuples_hot_updated is nontransactional, so just advance it */
1869 		if (hot)
1870 			pgstat_info->t_counts.t_tuples_hot_updated++;
1871 	}
1872 }
1873 
1874 /*
1875  * pgstat_count_heap_delete - count a tuple deletion
1876  */
1877 void
pgstat_count_heap_delete(Relation rel)1878 pgstat_count_heap_delete(Relation rel)
1879 {
1880 	PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1881 
1882 	if (pgstat_info != NULL)
1883 	{
1884 		/* We have to log the effect at the proper transactional level */
1885 		int			nest_level = GetCurrentTransactionNestLevel();
1886 
1887 		if (pgstat_info->trans == NULL ||
1888 			pgstat_info->trans->nest_level != nest_level)
1889 			add_tabstat_xact_level(pgstat_info, nest_level);
1890 
1891 		pgstat_info->trans->tuples_deleted++;
1892 	}
1893 }
1894 
1895 /*
1896  * pgstat_truncate_save_counters
1897  *
1898  * Whenever a table is truncated, we save its i/u/d counters so that they can
1899  * be cleared, and if the (sub)xact that executed the truncate later aborts,
1900  * the counters can be restored to the saved (pre-truncate) values.  Note we do
1901  * this on the first truncate in any particular subxact level only.
1902  */
1903 static void
pgstat_truncate_save_counters(PgStat_TableXactStatus * trans)1904 pgstat_truncate_save_counters(PgStat_TableXactStatus *trans)
1905 {
1906 	if (!trans->truncated)
1907 	{
1908 		trans->inserted_pre_trunc = trans->tuples_inserted;
1909 		trans->updated_pre_trunc = trans->tuples_updated;
1910 		trans->deleted_pre_trunc = trans->tuples_deleted;
1911 		trans->truncated = true;
1912 	}
1913 }
1914 
1915 /*
1916  * pgstat_truncate_restore_counters - restore counters when a truncate aborts
1917  */
1918 static void
pgstat_truncate_restore_counters(PgStat_TableXactStatus * trans)1919 pgstat_truncate_restore_counters(PgStat_TableXactStatus *trans)
1920 {
1921 	if (trans->truncated)
1922 	{
1923 		trans->tuples_inserted = trans->inserted_pre_trunc;
1924 		trans->tuples_updated = trans->updated_pre_trunc;
1925 		trans->tuples_deleted = trans->deleted_pre_trunc;
1926 	}
1927 }
1928 
1929 /*
1930  * pgstat_count_truncate - update tuple counters due to truncate
1931  */
1932 void
pgstat_count_truncate(Relation rel)1933 pgstat_count_truncate(Relation rel)
1934 {
1935 	PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1936 
1937 	if (pgstat_info != NULL)
1938 	{
1939 		/* We have to log the effect at the proper transactional level */
1940 		int			nest_level = GetCurrentTransactionNestLevel();
1941 
1942 		if (pgstat_info->trans == NULL ||
1943 			pgstat_info->trans->nest_level != nest_level)
1944 			add_tabstat_xact_level(pgstat_info, nest_level);
1945 
1946 		pgstat_truncate_save_counters(pgstat_info->trans);
1947 		pgstat_info->trans->tuples_inserted = 0;
1948 		pgstat_info->trans->tuples_updated = 0;
1949 		pgstat_info->trans->tuples_deleted = 0;
1950 	}
1951 }
1952 
1953 /*
1954  * pgstat_update_heap_dead_tuples - update dead-tuples count
1955  *
1956  * The semantics of this are that we are reporting the nontransactional
1957  * recovery of "delta" dead tuples; so t_delta_dead_tuples decreases
1958  * rather than increasing, and the change goes straight into the per-table
1959  * counter, not into transactional state.
1960  */
1961 void
pgstat_update_heap_dead_tuples(Relation rel,int delta)1962 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1963 {
1964 	PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1965 
1966 	if (pgstat_info != NULL)
1967 		pgstat_info->t_counts.t_delta_dead_tuples -= delta;
1968 }
1969 
1970 
1971 /* ----------
1972  * AtEOXact_PgStat
1973  *
1974  *	Called from access/transam/xact.c at top-level transaction commit/abort.
1975  * ----------
1976  */
1977 void
AtEOXact_PgStat(bool isCommit,bool parallel)1978 AtEOXact_PgStat(bool isCommit, bool parallel)
1979 {
1980 	PgStat_SubXactStatus *xact_state;
1981 
1982 	/* Don't count parallel worker transaction stats */
1983 	if (!parallel)
1984 	{
1985 		/*
1986 		 * Count transaction commit or abort.  (We use counters, not just
1987 		 * bools, in case the reporting message isn't sent right away.)
1988 		 */
1989 		if (isCommit)
1990 			pgStatXactCommit++;
1991 		else
1992 			pgStatXactRollback++;
1993 	}
1994 
1995 	/*
1996 	 * Transfer transactional insert/update counts into the base tabstat
1997 	 * entries.  We don't bother to free any of the transactional state, since
1998 	 * it's all in TopTransactionContext and will go away anyway.
1999 	 */
2000 	xact_state = pgStatXactStack;
2001 	if (xact_state != NULL)
2002 	{
2003 		PgStat_TableXactStatus *trans;
2004 
2005 		Assert(xact_state->nest_level == 1);
2006 		Assert(xact_state->prev == NULL);
2007 		for (trans = xact_state->first; trans != NULL; trans = trans->next)
2008 		{
2009 			PgStat_TableStatus *tabstat;
2010 
2011 			Assert(trans->nest_level == 1);
2012 			Assert(trans->upper == NULL);
2013 			tabstat = trans->parent;
2014 			Assert(tabstat->trans == trans);
2015 			/* restore pre-truncate stats (if any) in case of aborted xact */
2016 			if (!isCommit)
2017 				pgstat_truncate_restore_counters(trans);
2018 			/* count attempted actions regardless of commit/abort */
2019 			tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2020 			tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2021 			tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2022 			if (isCommit)
2023 			{
2024 				tabstat->t_counts.t_truncated = trans->truncated;
2025 				if (trans->truncated)
2026 				{
2027 					/* forget live/dead stats seen by backend thus far */
2028 					tabstat->t_counts.t_delta_live_tuples = 0;
2029 					tabstat->t_counts.t_delta_dead_tuples = 0;
2030 				}
2031 				/* insert adds a live tuple, delete removes one */
2032 				tabstat->t_counts.t_delta_live_tuples +=
2033 					trans->tuples_inserted - trans->tuples_deleted;
2034 				/* update and delete each create a dead tuple */
2035 				tabstat->t_counts.t_delta_dead_tuples +=
2036 					trans->tuples_updated + trans->tuples_deleted;
2037 				/* insert, update, delete each count as one change event */
2038 				tabstat->t_counts.t_changed_tuples +=
2039 					trans->tuples_inserted + trans->tuples_updated +
2040 					trans->tuples_deleted;
2041 			}
2042 			else
2043 			{
2044 				/* inserted tuples are dead, deleted tuples are unaffected */
2045 				tabstat->t_counts.t_delta_dead_tuples +=
2046 					trans->tuples_inserted + trans->tuples_updated;
2047 				/* an aborted xact generates no changed_tuple events */
2048 			}
2049 			tabstat->trans = NULL;
2050 		}
2051 	}
2052 	pgStatXactStack = NULL;
2053 
2054 	/* Make sure any stats snapshot is thrown away */
2055 	pgstat_clear_snapshot();
2056 }
2057 
2058 /* ----------
2059  * AtEOSubXact_PgStat
2060  *
2061  *	Called from access/transam/xact.c at subtransaction commit/abort.
2062  * ----------
2063  */
2064 void
AtEOSubXact_PgStat(bool isCommit,int nestDepth)2065 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
2066 {
2067 	PgStat_SubXactStatus *xact_state;
2068 
2069 	/*
2070 	 * Transfer transactional insert/update counts into the next higher
2071 	 * subtransaction state.
2072 	 */
2073 	xact_state = pgStatXactStack;
2074 	if (xact_state != NULL &&
2075 		xact_state->nest_level >= nestDepth)
2076 	{
2077 		PgStat_TableXactStatus *trans;
2078 		PgStat_TableXactStatus *next_trans;
2079 
2080 		/* delink xact_state from stack immediately to simplify reuse case */
2081 		pgStatXactStack = xact_state->prev;
2082 
2083 		for (trans = xact_state->first; trans != NULL; trans = next_trans)
2084 		{
2085 			PgStat_TableStatus *tabstat;
2086 
2087 			next_trans = trans->next;
2088 			Assert(trans->nest_level == nestDepth);
2089 			tabstat = trans->parent;
2090 			Assert(tabstat->trans == trans);
2091 			if (isCommit)
2092 			{
2093 				if (trans->upper && trans->upper->nest_level == nestDepth - 1)
2094 				{
2095 					if (trans->truncated)
2096 					{
2097 						/* propagate the truncate status one level up */
2098 						pgstat_truncate_save_counters(trans->upper);
2099 						/* replace upper xact stats with ours */
2100 						trans->upper->tuples_inserted = trans->tuples_inserted;
2101 						trans->upper->tuples_updated = trans->tuples_updated;
2102 						trans->upper->tuples_deleted = trans->tuples_deleted;
2103 					}
2104 					else
2105 					{
2106 						trans->upper->tuples_inserted += trans->tuples_inserted;
2107 						trans->upper->tuples_updated += trans->tuples_updated;
2108 						trans->upper->tuples_deleted += trans->tuples_deleted;
2109 					}
2110 					tabstat->trans = trans->upper;
2111 					pfree(trans);
2112 				}
2113 				else
2114 				{
2115 					/*
2116 					 * When there isn't an immediate parent state, we can just
2117 					 * reuse the record instead of going through a
2118 					 * palloc/pfree pushup (this works since it's all in
2119 					 * TopTransactionContext anyway).  We have to re-link it
2120 					 * into the parent level, though, and that might mean
2121 					 * pushing a new entry into the pgStatXactStack.
2122 					 */
2123 					PgStat_SubXactStatus *upper_xact_state;
2124 
2125 					upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
2126 					trans->next = upper_xact_state->first;
2127 					upper_xact_state->first = trans;
2128 					trans->nest_level = nestDepth - 1;
2129 				}
2130 			}
2131 			else
2132 			{
2133 				/*
2134 				 * On abort, update top-level tabstat counts, then forget the
2135 				 * subtransaction
2136 				 */
2137 
2138 				/* first restore values obliterated by truncate */
2139 				pgstat_truncate_restore_counters(trans);
2140 				/* count attempted actions regardless of commit/abort */
2141 				tabstat->t_counts.t_tuples_inserted += trans->tuples_inserted;
2142 				tabstat->t_counts.t_tuples_updated += trans->tuples_updated;
2143 				tabstat->t_counts.t_tuples_deleted += trans->tuples_deleted;
2144 				/* inserted tuples are dead, deleted tuples are unaffected */
2145 				tabstat->t_counts.t_delta_dead_tuples +=
2146 					trans->tuples_inserted + trans->tuples_updated;
2147 				tabstat->trans = trans->upper;
2148 				pfree(trans);
2149 			}
2150 		}
2151 		pfree(xact_state);
2152 	}
2153 }
2154 
2155 
2156 /*
2157  * AtPrepare_PgStat
2158  *		Save the transactional stats state at 2PC transaction prepare.
2159  *
2160  * In this phase we just generate 2PC records for all the pending
2161  * transaction-dependent stats work.
2162  */
2163 void
AtPrepare_PgStat(void)2164 AtPrepare_PgStat(void)
2165 {
2166 	PgStat_SubXactStatus *xact_state;
2167 
2168 	xact_state = pgStatXactStack;
2169 	if (xact_state != NULL)
2170 	{
2171 		PgStat_TableXactStatus *trans;
2172 
2173 		Assert(xact_state->nest_level == 1);
2174 		Assert(xact_state->prev == NULL);
2175 		for (trans = xact_state->first; trans != NULL; trans = trans->next)
2176 		{
2177 			PgStat_TableStatus *tabstat;
2178 			TwoPhasePgStatRecord record;
2179 
2180 			Assert(trans->nest_level == 1);
2181 			Assert(trans->upper == NULL);
2182 			tabstat = trans->parent;
2183 			Assert(tabstat->trans == trans);
2184 
2185 			record.tuples_inserted = trans->tuples_inserted;
2186 			record.tuples_updated = trans->tuples_updated;
2187 			record.tuples_deleted = trans->tuples_deleted;
2188 			record.inserted_pre_trunc = trans->inserted_pre_trunc;
2189 			record.updated_pre_trunc = trans->updated_pre_trunc;
2190 			record.deleted_pre_trunc = trans->deleted_pre_trunc;
2191 			record.t_id = tabstat->t_id;
2192 			record.t_shared = tabstat->t_shared;
2193 			record.t_truncated = trans->truncated;
2194 
2195 			RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
2196 								   &record, sizeof(TwoPhasePgStatRecord));
2197 		}
2198 	}
2199 }
2200 
2201 /*
2202  * PostPrepare_PgStat
2203  *		Clean up after successful PREPARE.
2204  *
2205  * All we need do here is unlink the transaction stats state from the
2206  * nontransactional state.  The nontransactional action counts will be
2207  * reported to the stats collector immediately, while the effects on live
2208  * and dead tuple counts are preserved in the 2PC state file.
2209  *
2210  * Note: AtEOXact_PgStat is not called during PREPARE.
2211  */
2212 void
PostPrepare_PgStat(void)2213 PostPrepare_PgStat(void)
2214 {
2215 	PgStat_SubXactStatus *xact_state;
2216 
2217 	/*
2218 	 * We don't bother to free any of the transactional state, since it's all
2219 	 * in TopTransactionContext and will go away anyway.
2220 	 */
2221 	xact_state = pgStatXactStack;
2222 	if (xact_state != NULL)
2223 	{
2224 		PgStat_TableXactStatus *trans;
2225 
2226 		for (trans = xact_state->first; trans != NULL; trans = trans->next)
2227 		{
2228 			PgStat_TableStatus *tabstat;
2229 
2230 			tabstat = trans->parent;
2231 			tabstat->trans = NULL;
2232 		}
2233 	}
2234 	pgStatXactStack = NULL;
2235 
2236 	/* Make sure any stats snapshot is thrown away */
2237 	pgstat_clear_snapshot();
2238 }
2239 
2240 /*
2241  * 2PC processing routine for COMMIT PREPARED case.
2242  *
2243  * Load the saved counts into our local pgstats state.
2244  */
2245 void
pgstat_twophase_postcommit(TransactionId xid,uint16 info,void * recdata,uint32 len)2246 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
2247 						   void *recdata, uint32 len)
2248 {
2249 	TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2250 	PgStat_TableStatus *pgstat_info;
2251 
2252 	/* Find or create a tabstat entry for the rel */
2253 	pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2254 
2255 	/* Same math as in AtEOXact_PgStat, commit case */
2256 	pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2257 	pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2258 	pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2259 	pgstat_info->t_counts.t_truncated = rec->t_truncated;
2260 	if (rec->t_truncated)
2261 	{
2262 		/* forget live/dead stats seen by backend thus far */
2263 		pgstat_info->t_counts.t_delta_live_tuples = 0;
2264 		pgstat_info->t_counts.t_delta_dead_tuples = 0;
2265 	}
2266 	pgstat_info->t_counts.t_delta_live_tuples +=
2267 		rec->tuples_inserted - rec->tuples_deleted;
2268 	pgstat_info->t_counts.t_delta_dead_tuples +=
2269 		rec->tuples_updated + rec->tuples_deleted;
2270 	pgstat_info->t_counts.t_changed_tuples +=
2271 		rec->tuples_inserted + rec->tuples_updated +
2272 		rec->tuples_deleted;
2273 }
2274 
2275 /*
2276  * 2PC processing routine for ROLLBACK PREPARED case.
2277  *
2278  * Load the saved counts into our local pgstats state, but treat them
2279  * as aborted.
2280  */
2281 void
pgstat_twophase_postabort(TransactionId xid,uint16 info,void * recdata,uint32 len)2282 pgstat_twophase_postabort(TransactionId xid, uint16 info,
2283 						  void *recdata, uint32 len)
2284 {
2285 	TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
2286 	PgStat_TableStatus *pgstat_info;
2287 
2288 	/* Find or create a tabstat entry for the rel */
2289 	pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
2290 
2291 	/* Same math as in AtEOXact_PgStat, abort case */
2292 	if (rec->t_truncated)
2293 	{
2294 		rec->tuples_inserted = rec->inserted_pre_trunc;
2295 		rec->tuples_updated = rec->updated_pre_trunc;
2296 		rec->tuples_deleted = rec->deleted_pre_trunc;
2297 	}
2298 	pgstat_info->t_counts.t_tuples_inserted += rec->tuples_inserted;
2299 	pgstat_info->t_counts.t_tuples_updated += rec->tuples_updated;
2300 	pgstat_info->t_counts.t_tuples_deleted += rec->tuples_deleted;
2301 	pgstat_info->t_counts.t_delta_dead_tuples +=
2302 		rec->tuples_inserted + rec->tuples_updated;
2303 }
2304 
2305 
2306 /* ----------
2307  * pgstat_fetch_stat_dbentry() -
2308  *
2309  *	Support function for the SQL-callable pgstat* functions. Returns
2310  *	the collected statistics for one database or NULL. NULL doesn't mean
2311  *	that the database doesn't exist, it is just not yet known by the
2312  *	collector, so the caller is better off to report ZERO instead.
2313  * ----------
2314  */
2315 PgStat_StatDBEntry *
pgstat_fetch_stat_dbentry(Oid dbid)2316 pgstat_fetch_stat_dbentry(Oid dbid)
2317 {
2318 	/*
2319 	 * If not done for this transaction, read the statistics collector stats
2320 	 * file into some hash tables.
2321 	 */
2322 	backend_read_statsfile();
2323 
2324 	/*
2325 	 * Lookup the requested database; return NULL if not found
2326 	 */
2327 	return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2328 											  (void *) &dbid,
2329 											  HASH_FIND, NULL);
2330 }
2331 
2332 
2333 /* ----------
2334  * pgstat_fetch_stat_tabentry() -
2335  *
2336  *	Support function for the SQL-callable pgstat* functions. Returns
2337  *	the collected statistics for one table or NULL. NULL doesn't mean
2338  *	that the table doesn't exist, it is just not yet known by the
2339  *	collector, so the caller is better off to report ZERO instead.
2340  * ----------
2341  */
2342 PgStat_StatTabEntry *
pgstat_fetch_stat_tabentry(Oid relid)2343 pgstat_fetch_stat_tabentry(Oid relid)
2344 {
2345 	Oid			dbid;
2346 	PgStat_StatDBEntry *dbentry;
2347 	PgStat_StatTabEntry *tabentry;
2348 
2349 	/*
2350 	 * If not done for this transaction, read the statistics collector stats
2351 	 * file into some hash tables.
2352 	 */
2353 	backend_read_statsfile();
2354 
2355 	/*
2356 	 * Lookup our database, then look in its table hash table.
2357 	 */
2358 	dbid = MyDatabaseId;
2359 	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2360 												 (void *) &dbid,
2361 												 HASH_FIND, NULL);
2362 	if (dbentry != NULL && dbentry->tables != NULL)
2363 	{
2364 		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2365 													   (void *) &relid,
2366 													   HASH_FIND, NULL);
2367 		if (tabentry)
2368 			return tabentry;
2369 	}
2370 
2371 	/*
2372 	 * If we didn't find it, maybe it's a shared table.
2373 	 */
2374 	dbid = InvalidOid;
2375 	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2376 												 (void *) &dbid,
2377 												 HASH_FIND, NULL);
2378 	if (dbentry != NULL && dbentry->tables != NULL)
2379 	{
2380 		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
2381 													   (void *) &relid,
2382 													   HASH_FIND, NULL);
2383 		if (tabentry)
2384 			return tabentry;
2385 	}
2386 
2387 	return NULL;
2388 }
2389 
2390 
2391 /* ----------
2392  * pgstat_fetch_stat_funcentry() -
2393  *
2394  *	Support function for the SQL-callable pgstat* functions. Returns
2395  *	the collected statistics for one function or NULL.
2396  * ----------
2397  */
2398 PgStat_StatFuncEntry *
pgstat_fetch_stat_funcentry(Oid func_id)2399 pgstat_fetch_stat_funcentry(Oid func_id)
2400 {
2401 	PgStat_StatDBEntry *dbentry;
2402 	PgStat_StatFuncEntry *funcentry = NULL;
2403 
2404 	/* load the stats file if needed */
2405 	backend_read_statsfile();
2406 
2407 	/* Lookup our database, then find the requested function.  */
2408 	dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
2409 	if (dbentry != NULL && dbentry->functions != NULL)
2410 	{
2411 		funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
2412 														 (void *) &func_id,
2413 														 HASH_FIND, NULL);
2414 	}
2415 
2416 	return funcentry;
2417 }
2418 
2419 
2420 /* ----------
2421  * pgstat_fetch_stat_beentry() -
2422  *
2423  *	Support function for the SQL-callable pgstat* functions. Returns
2424  *	our local copy of the current-activity entry for one backend.
2425  *
2426  *	NB: caller is responsible for a check if the user is permitted to see
2427  *	this info (especially the querystring).
2428  * ----------
2429  */
2430 PgBackendStatus *
pgstat_fetch_stat_beentry(int beid)2431 pgstat_fetch_stat_beentry(int beid)
2432 {
2433 	pgstat_read_current_status();
2434 
2435 	if (beid < 1 || beid > localNumBackends)
2436 		return NULL;
2437 
2438 	return &localBackendStatusTable[beid - 1].backendStatus;
2439 }
2440 
2441 
2442 /* ----------
2443  * pgstat_fetch_stat_local_beentry() -
2444  *
2445  *	Like pgstat_fetch_stat_beentry() but with locally computed additions (like
2446  *	xid and xmin values of the backend)
2447  *
2448  *	NB: caller is responsible for a check if the user is permitted to see
2449  *	this info (especially the querystring).
2450  * ----------
2451  */
2452 LocalPgBackendStatus *
pgstat_fetch_stat_local_beentry(int beid)2453 pgstat_fetch_stat_local_beentry(int beid)
2454 {
2455 	pgstat_read_current_status();
2456 
2457 	if (beid < 1 || beid > localNumBackends)
2458 		return NULL;
2459 
2460 	return &localBackendStatusTable[beid - 1];
2461 }
2462 
2463 
2464 /* ----------
2465  * pgstat_fetch_stat_numbackends() -
2466  *
2467  *	Support function for the SQL-callable pgstat* functions. Returns
2468  *	the maximum current backend id.
2469  * ----------
2470  */
2471 int
pgstat_fetch_stat_numbackends(void)2472 pgstat_fetch_stat_numbackends(void)
2473 {
2474 	pgstat_read_current_status();
2475 
2476 	return localNumBackends;
2477 }
2478 
2479 /*
2480  * ---------
2481  * pgstat_fetch_stat_archiver() -
2482  *
2483  *	Support function for the SQL-callable pgstat* functions. Returns
2484  *	a pointer to the archiver statistics struct.
2485  * ---------
2486  */
2487 PgStat_ArchiverStats *
pgstat_fetch_stat_archiver(void)2488 pgstat_fetch_stat_archiver(void)
2489 {
2490 	backend_read_statsfile();
2491 
2492 	return &archiverStats;
2493 }
2494 
2495 
2496 /*
2497  * ---------
2498  * pgstat_fetch_global() -
2499  *
2500  *	Support function for the SQL-callable pgstat* functions. Returns
2501  *	a pointer to the global statistics struct.
2502  * ---------
2503  */
2504 PgStat_GlobalStats *
pgstat_fetch_global(void)2505 pgstat_fetch_global(void)
2506 {
2507 	backend_read_statsfile();
2508 
2509 	return &globalStats;
2510 }
2511 
2512 
2513 /* ------------------------------------------------------------
2514  * Functions for management of the shared-memory PgBackendStatus array
2515  * ------------------------------------------------------------
2516  */
2517 
2518 static PgBackendStatus *BackendStatusArray = NULL;
2519 static PgBackendStatus *MyBEEntry = NULL;
2520 static char *BackendAppnameBuffer = NULL;
2521 static char *BackendClientHostnameBuffer = NULL;
2522 static char *BackendActivityBuffer = NULL;
2523 static Size BackendActivityBufferSize = 0;
2524 #ifdef USE_SSL
2525 static PgBackendSSLStatus *BackendSslStatusBuffer = NULL;
2526 #endif
2527 
2528 
2529 /*
2530  * Report shared-memory space needed by CreateSharedBackendStatus.
2531  */
2532 Size
BackendStatusShmemSize(void)2533 BackendStatusShmemSize(void)
2534 {
2535 	Size		size;
2536 
2537 	/* BackendStatusArray: */
2538 	size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2539 	/* BackendAppnameBuffer: */
2540 	size = add_size(size,
2541 					mul_size(NAMEDATALEN, MaxBackends));
2542 	/* BackendClientHostnameBuffer: */
2543 	size = add_size(size,
2544 					mul_size(NAMEDATALEN, MaxBackends));
2545 	/* BackendActivityBuffer: */
2546 	size = add_size(size,
2547 					mul_size(pgstat_track_activity_query_size, MaxBackends));
2548 #ifdef USE_SSL
2549 	/* BackendSslStatusBuffer: */
2550 	size = add_size(size,
2551 					mul_size(sizeof(PgBackendSSLStatus), MaxBackends));
2552 #endif
2553 	return size;
2554 }
2555 
2556 /*
2557  * Initialize the shared status array and several string buffers
2558  * during postmaster startup.
2559  */
2560 void
CreateSharedBackendStatus(void)2561 CreateSharedBackendStatus(void)
2562 {
2563 	Size		size;
2564 	bool		found;
2565 	int			i;
2566 	char	   *buffer;
2567 
2568 	/* Create or attach to the shared array */
2569 	size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2570 	BackendStatusArray = (PgBackendStatus *)
2571 		ShmemInitStruct("Backend Status Array", size, &found);
2572 
2573 	if (!found)
2574 	{
2575 		/*
2576 		 * We're the first - initialize.
2577 		 */
2578 		MemSet(BackendStatusArray, 0, size);
2579 	}
2580 
2581 	/* Create or attach to the shared appname buffer */
2582 	size = mul_size(NAMEDATALEN, MaxBackends);
2583 	BackendAppnameBuffer = (char *)
2584 		ShmemInitStruct("Backend Application Name Buffer", size, &found);
2585 
2586 	if (!found)
2587 	{
2588 		MemSet(BackendAppnameBuffer, 0, size);
2589 
2590 		/* Initialize st_appname pointers. */
2591 		buffer = BackendAppnameBuffer;
2592 		for (i = 0; i < MaxBackends; i++)
2593 		{
2594 			BackendStatusArray[i].st_appname = buffer;
2595 			buffer += NAMEDATALEN;
2596 		}
2597 	}
2598 
2599 	/* Create or attach to the shared client hostname buffer */
2600 	size = mul_size(NAMEDATALEN, MaxBackends);
2601 	BackendClientHostnameBuffer = (char *)
2602 		ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
2603 
2604 	if (!found)
2605 	{
2606 		MemSet(BackendClientHostnameBuffer, 0, size);
2607 
2608 		/* Initialize st_clienthostname pointers. */
2609 		buffer = BackendClientHostnameBuffer;
2610 		for (i = 0; i < MaxBackends; i++)
2611 		{
2612 			BackendStatusArray[i].st_clienthostname = buffer;
2613 			buffer += NAMEDATALEN;
2614 		}
2615 	}
2616 
2617 	/* Create or attach to the shared activity buffer */
2618 	BackendActivityBufferSize = mul_size(pgstat_track_activity_query_size,
2619 										 MaxBackends);
2620 	BackendActivityBuffer = (char *)
2621 		ShmemInitStruct("Backend Activity Buffer",
2622 						BackendActivityBufferSize,
2623 						&found);
2624 
2625 	if (!found)
2626 	{
2627 		MemSet(BackendActivityBuffer, 0, BackendActivityBufferSize);
2628 
2629 		/* Initialize st_activity pointers. */
2630 		buffer = BackendActivityBuffer;
2631 		for (i = 0; i < MaxBackends; i++)
2632 		{
2633 			BackendStatusArray[i].st_activity = buffer;
2634 			buffer += pgstat_track_activity_query_size;
2635 		}
2636 	}
2637 
2638 #ifdef USE_SSL
2639 	/* Create or attach to the shared SSL status buffer */
2640 	size = mul_size(sizeof(PgBackendSSLStatus), MaxBackends);
2641 	BackendSslStatusBuffer = (PgBackendSSLStatus *)
2642 		ShmemInitStruct("Backend SSL Status Buffer", size, &found);
2643 
2644 	if (!found)
2645 	{
2646 		PgBackendSSLStatus *ptr;
2647 
2648 		MemSet(BackendSslStatusBuffer, 0, size);
2649 
2650 		/* Initialize st_sslstatus pointers. */
2651 		ptr = BackendSslStatusBuffer;
2652 		for (i = 0; i < MaxBackends; i++)
2653 		{
2654 			BackendStatusArray[i].st_sslstatus = ptr;
2655 			ptr++;
2656 		}
2657 	}
2658 #endif
2659 }
2660 
2661 
2662 /* ----------
2663  * pgstat_initialize() -
2664  *
2665  *	Initialize pgstats state, and set up our on-proc-exit hook.
2666  *	Called from InitPostgres.  MyBackendId must be set,
2667  *	but we must not have started any transaction yet (since the
2668  *	exit hook must run after the last transaction exit).
2669  *	NOTE: MyDatabaseId isn't set yet; so the shutdown hook has to be careful.
2670  * ----------
2671  */
2672 void
pgstat_initialize(void)2673 pgstat_initialize(void)
2674 {
2675 	/* Initialize MyBEEntry */
2676 	Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2677 	MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2678 
2679 	/* Set up a process-exit hook to clean up */
2680 	on_shmem_exit(pgstat_beshutdown_hook, 0);
2681 }
2682 
2683 /* ----------
2684  * pgstat_bestart() -
2685  *
2686  *	Initialize this backend's entry in the PgBackendStatus array.
2687  *	Called from InitPostgres.
2688  *	Apart from auxiliary processes, MyBackendId, MyDatabaseId,
2689  *	session userid, and application_name must be set for a
2690  *	backend (hence, this cannot be combined with pgstat_initialize).
2691  *	Note also that we must be inside a transaction if this isn't an aux
2692  *	process, as we may need to do encoding conversion on some strings.
2693  * ----------
2694  */
2695 void
pgstat_bestart(void)2696 pgstat_bestart(void)
2697 {
2698 	volatile PgBackendStatus *vbeentry = MyBEEntry;
2699 	PgBackendStatus lbeentry;
2700 #ifdef USE_SSL
2701 	PgBackendSSLStatus lsslstatus;
2702 #endif
2703 
2704 	/* pgstats state must be initialized from pgstat_initialize() */
2705 	Assert(vbeentry != NULL);
2706 
2707 	/*
2708 	 * To minimize the time spent modifying the PgBackendStatus entry, and
2709 	 * avoid risk of errors inside the critical section, we first copy the
2710 	 * shared-memory struct to a local variable, then modify the data in the
2711 	 * local variable, then copy the local variable back to shared memory.
2712 	 * Only the last step has to be inside the critical section.
2713 	 *
2714 	 * Most of the data we copy from shared memory is just going to be
2715 	 * overwritten, but the struct's not so large that it's worth the
2716 	 * maintenance hassle to copy only the needful fields.
2717 	 */
2718 	memcpy(&lbeentry,
2719 		   (char *) vbeentry,
2720 		   sizeof(PgBackendStatus));
2721 
2722 	/* This struct can just start from zeroes each time, though */
2723 #ifdef USE_SSL
2724 	memset(&lsslstatus, 0, sizeof(lsslstatus));
2725 #endif
2726 
2727 	/*
2728 	 * Now fill in all the fields of lbeentry, except for strings that are
2729 	 * out-of-line data.  Those have to be handled separately, below.
2730 	 */
2731 	lbeentry.st_procpid = MyProcPid;
2732 
2733 	/*
2734 	 * If we have a MyProcPort, use its session start time (for consistency,
2735 	 * and to save a kernel call).
2736 	 */
2737 	if (MyProcPort)
2738 		lbeentry.st_proc_start_timestamp = MyProcPort->SessionStartTime;
2739 	else
2740 		lbeentry.st_proc_start_timestamp = GetCurrentTimestamp();
2741 
2742 	lbeentry.st_activity_start_timestamp = 0;
2743 	lbeentry.st_state_start_timestamp = 0;
2744 	lbeentry.st_xact_start_timestamp = 0;
2745 	lbeentry.st_databaseid = MyDatabaseId;
2746 	lbeentry.st_userid = GetSessionUserId();
2747 
2748 	/*
2749 	 * We may not have a MyProcPort (eg, if this is the autovacuum process).
2750 	 * If so, use all-zeroes client address, which is dealt with specially in
2751 	 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2752 	 */
2753 	if (MyProcPort)
2754 		memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
2755 			   sizeof(lbeentry.st_clientaddr));
2756 	else
2757 		MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
2758 
2759 #ifdef USE_SSL
2760 	if (MyProcPort && MyProcPort->ssl != NULL)
2761 	{
2762 		lbeentry.st_ssl = true;
2763 		lsslstatus.ssl_bits = be_tls_get_cipher_bits(MyProcPort);
2764 		lsslstatus.ssl_compression = be_tls_get_compression(MyProcPort);
2765 		be_tls_get_version(MyProcPort, lsslstatus.ssl_version, NAMEDATALEN);
2766 		be_tls_get_cipher(MyProcPort, lsslstatus.ssl_cipher, NAMEDATALEN);
2767 		be_tls_get_peerdn_name(MyProcPort, lsslstatus.ssl_clientdn, NAMEDATALEN);
2768 	}
2769 	else
2770 	{
2771 		lbeentry.st_ssl = false;
2772 	}
2773 #else
2774 	lbeentry.st_ssl = false;
2775 #endif
2776 
2777 	lbeentry.st_state = STATE_UNDEFINED;
2778 	lbeentry.st_progress_command = PROGRESS_COMMAND_INVALID;
2779 	lbeentry.st_progress_command_target = InvalidOid;
2780 
2781 	/*
2782 	 * we don't zero st_progress_param here to save cycles; nobody should
2783 	 * examine it until st_progress_command has been set to something other
2784 	 * than PROGRESS_COMMAND_INVALID
2785 	 */
2786 
2787 	/*
2788 	 * We're ready to enter the critical section that fills the shared-memory
2789 	 * status entry.  We follow the protocol of bumping st_changecount before
2790 	 * and after; and make sure it's even afterwards.  We use a volatile
2791 	 * pointer here to ensure the compiler doesn't try to get cute.
2792 	 */
2793 	PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
2794 
2795 	/* make sure we'll memcpy the same st_changecount back */
2796 	lbeentry.st_changecount = vbeentry->st_changecount;
2797 
2798 	memcpy((char *) vbeentry,
2799 		   &lbeentry,
2800 		   sizeof(PgBackendStatus));
2801 
2802 	/*
2803 	 * We can write the out-of-line strings and structs using the pointers
2804 	 * that are in lbeentry; this saves some de-volatilizing messiness.
2805 	 */
2806 	lbeentry.st_appname[0] = '\0';
2807 	if (MyProcPort && MyProcPort->remote_hostname)
2808 		strlcpy(lbeentry.st_clienthostname, MyProcPort->remote_hostname,
2809 				NAMEDATALEN);
2810 	else
2811 		lbeentry.st_clienthostname[0] = '\0';
2812 	lbeentry.st_activity[0] = '\0';
2813 	/* Also make sure the last byte in each string area is always 0 */
2814 	lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
2815 	lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
2816 	lbeentry.st_activity[pgstat_track_activity_query_size - 1] = '\0';
2817 
2818 #ifdef USE_SSL
2819 	memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
2820 #endif
2821 
2822 	PGSTAT_END_WRITE_ACTIVITY(vbeentry);
2823 
2824 	/* Update app name to current GUC setting */
2825 	if (application_name)
2826 		pgstat_report_appname(application_name);
2827 }
2828 
2829 /*
2830  * Shut down a single backend's statistics reporting at process exit.
2831  *
2832  * Flush any remaining statistics counts out to the collector.
2833  * Without this, operations triggered during backend exit (such as
2834  * temp table deletions) won't be counted.
2835  *
2836  * Lastly, clear out our entry in the PgBackendStatus array.
2837  */
2838 static void
pgstat_beshutdown_hook(int code,Datum arg)2839 pgstat_beshutdown_hook(int code, Datum arg)
2840 {
2841 	volatile PgBackendStatus *beentry = MyBEEntry;
2842 
2843 	/*
2844 	 * If we got as far as discovering our own database ID, we can report what
2845 	 * we did to the collector.  Otherwise, we'd be sending an invalid
2846 	 * database ID, so forget it.  (This means that accesses to pg_database
2847 	 * during failed backend starts might never get counted.)
2848 	 */
2849 	if (OidIsValid(MyDatabaseId))
2850 		pgstat_report_stat(true);
2851 
2852 	/*
2853 	 * Clear my status entry, following the protocol of bumping st_changecount
2854 	 * before and after.  We use a volatile pointer here to ensure the
2855 	 * compiler doesn't try to get cute.
2856 	 */
2857 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
2858 
2859 	beentry->st_procpid = 0;	/* mark invalid */
2860 
2861 	PGSTAT_END_WRITE_ACTIVITY(beentry);
2862 }
2863 
2864 
2865 /* ----------
2866  * pgstat_report_activity() -
2867  *
2868  *	Called from tcop/postgres.c to report what the backend is actually doing
2869  *	(but note cmd_str can be NULL for certain cases).
2870  *
2871  * All updates of the status entry follow the protocol of bumping
2872  * st_changecount before and after.  We use a volatile pointer here to
2873  * ensure the compiler doesn't try to get cute.
2874  * ----------
2875  */
2876 void
pgstat_report_activity(BackendState state,const char * cmd_str)2877 pgstat_report_activity(BackendState state, const char *cmd_str)
2878 {
2879 	volatile PgBackendStatus *beentry = MyBEEntry;
2880 	TimestampTz start_timestamp;
2881 	TimestampTz current_timestamp;
2882 	int			len = 0;
2883 
2884 	TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
2885 
2886 	if (!beentry)
2887 		return;
2888 
2889 	if (!pgstat_track_activities)
2890 	{
2891 		if (beentry->st_state != STATE_DISABLED)
2892 		{
2893 			volatile PGPROC *proc = MyProc;
2894 
2895 			/*
2896 			 * track_activities is disabled, but we last reported a
2897 			 * non-disabled state.  As our final update, change the state and
2898 			 * clear fields we will not be updating anymore.
2899 			 */
2900 			PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
2901 			beentry->st_state = STATE_DISABLED;
2902 			beentry->st_state_start_timestamp = 0;
2903 			beentry->st_activity[0] = '\0';
2904 			beentry->st_activity_start_timestamp = 0;
2905 			/* st_xact_start_timestamp and wait_event_info are also disabled */
2906 			beentry->st_xact_start_timestamp = 0;
2907 			proc->wait_event_info = 0;
2908 			PGSTAT_END_WRITE_ACTIVITY(beentry);
2909 		}
2910 		return;
2911 	}
2912 
2913 	/*
2914 	 * To minimize the time spent modifying the entry, and avoid risk of
2915 	 * errors inside the critical section, fetch all the needed data first.
2916 	 */
2917 	start_timestamp = GetCurrentStatementStartTimestamp();
2918 	if (cmd_str != NULL)
2919 	{
2920 		len = pg_mbcliplen(cmd_str, strlen(cmd_str),
2921 						   pgstat_track_activity_query_size - 1);
2922 	}
2923 	current_timestamp = GetCurrentTimestamp();
2924 
2925 	/*
2926 	 * Now update the status entry
2927 	 */
2928 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
2929 
2930 	beentry->st_state = state;
2931 	beentry->st_state_start_timestamp = current_timestamp;
2932 
2933 	if (cmd_str != NULL)
2934 	{
2935 		memcpy((char *) beentry->st_activity, cmd_str, len);
2936 		beentry->st_activity[len] = '\0';
2937 		beentry->st_activity_start_timestamp = start_timestamp;
2938 	}
2939 
2940 	PGSTAT_END_WRITE_ACTIVITY(beentry);
2941 }
2942 
2943 /*-----------
2944  * pgstat_progress_start_command() -
2945  *
2946  * Set st_progress_command (and st_progress_command_target) in own backend
2947  * entry.  Also, zero-initialize st_progress_param array.
2948  *-----------
2949  */
2950 void
pgstat_progress_start_command(ProgressCommandType cmdtype,Oid relid)2951 pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
2952 {
2953 	volatile PgBackendStatus *beentry = MyBEEntry;
2954 
2955 	if (!beentry || !pgstat_track_activities)
2956 		return;
2957 
2958 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
2959 	beentry->st_progress_command = cmdtype;
2960 	beentry->st_progress_command_target = relid;
2961 	MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param));
2962 	PGSTAT_END_WRITE_ACTIVITY(beentry);
2963 }
2964 
2965 /*-----------
2966  * pgstat_progress_update_param() -
2967  *
2968  * Update index'th member in st_progress_param[] of own backend entry.
2969  *-----------
2970  */
2971 void
pgstat_progress_update_param(int index,int64 val)2972 pgstat_progress_update_param(int index, int64 val)
2973 {
2974 	volatile PgBackendStatus *beentry = MyBEEntry;
2975 
2976 	Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
2977 
2978 	if (!beentry || !pgstat_track_activities)
2979 		return;
2980 
2981 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
2982 	beentry->st_progress_param[index] = val;
2983 	PGSTAT_END_WRITE_ACTIVITY(beentry);
2984 }
2985 
2986 /*-----------
2987  * pgstat_progress_update_multi_param() -
2988  *
2989  * Update multiple members in st_progress_param[] of own backend entry.
2990  * This is atomic; readers won't see intermediate states.
2991  *-----------
2992  */
2993 void
pgstat_progress_update_multi_param(int nparam,const int * index,const int64 * val)2994 pgstat_progress_update_multi_param(int nparam, const int *index,
2995 								   const int64 *val)
2996 {
2997 	volatile PgBackendStatus *beentry = MyBEEntry;
2998 	int			i;
2999 
3000 	if (!beentry || !pgstat_track_activities || nparam == 0)
3001 		return;
3002 
3003 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3004 
3005 	for (i = 0; i < nparam; ++i)
3006 	{
3007 		Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
3008 
3009 		beentry->st_progress_param[index[i]] = val[i];
3010 	}
3011 
3012 	PGSTAT_END_WRITE_ACTIVITY(beentry);
3013 }
3014 
3015 /*-----------
3016  * pgstat_progress_end_command() -
3017  *
3018  * Reset st_progress_command (and st_progress_command_target) in own backend
3019  * entry.  This signals the end of the command.
3020  *-----------
3021  */
3022 void
pgstat_progress_end_command(void)3023 pgstat_progress_end_command(void)
3024 {
3025 	volatile PgBackendStatus *beentry = MyBEEntry;
3026 
3027 	if (!beentry || !pgstat_track_activities)
3028 		return;
3029 
3030 	if (beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
3031 		return;
3032 
3033 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3034 	beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
3035 	beentry->st_progress_command_target = InvalidOid;
3036 	PGSTAT_END_WRITE_ACTIVITY(beentry);
3037 }
3038 
3039 /* ----------
3040  * pgstat_report_appname() -
3041  *
3042  *	Called to update our application name.
3043  * ----------
3044  */
3045 void
pgstat_report_appname(const char * appname)3046 pgstat_report_appname(const char *appname)
3047 {
3048 	volatile PgBackendStatus *beentry = MyBEEntry;
3049 	int			len;
3050 
3051 	if (!beentry)
3052 		return;
3053 
3054 	/* This should be unnecessary if GUC did its job, but be safe */
3055 	len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
3056 
3057 	/*
3058 	 * Update my status entry, following the protocol of bumping
3059 	 * st_changecount before and after.  We use a volatile pointer here to
3060 	 * ensure the compiler doesn't try to get cute.
3061 	 */
3062 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3063 
3064 	memcpy((char *) beentry->st_appname, appname, len);
3065 	beentry->st_appname[len] = '\0';
3066 
3067 	PGSTAT_END_WRITE_ACTIVITY(beentry);
3068 }
3069 
3070 /*
3071  * Report current transaction start timestamp as the specified value.
3072  * Zero means there is no active transaction.
3073  */
3074 void
pgstat_report_xact_timestamp(TimestampTz tstamp)3075 pgstat_report_xact_timestamp(TimestampTz tstamp)
3076 {
3077 	volatile PgBackendStatus *beentry = MyBEEntry;
3078 
3079 	if (!pgstat_track_activities || !beentry)
3080 		return;
3081 
3082 	/*
3083 	 * Update my status entry, following the protocol of bumping
3084 	 * st_changecount before and after.  We use a volatile pointer here to
3085 	 * ensure the compiler doesn't try to get cute.
3086 	 */
3087 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
3088 
3089 	beentry->st_xact_start_timestamp = tstamp;
3090 
3091 	PGSTAT_END_WRITE_ACTIVITY(beentry);
3092 }
3093 
3094 /* ----------
3095  * pgstat_read_current_status() -
3096  *
3097  *	Copy the current contents of the PgBackendStatus array to local memory,
3098  *	if not already done in this transaction.
3099  * ----------
3100  */
3101 static void
pgstat_read_current_status(void)3102 pgstat_read_current_status(void)
3103 {
3104 	volatile PgBackendStatus *beentry;
3105 	LocalPgBackendStatus *localtable;
3106 	LocalPgBackendStatus *localentry;
3107 	char	   *localappname,
3108 			   *localclienthostname,
3109 			   *localactivity;
3110 #ifdef USE_SSL
3111 	PgBackendSSLStatus *localsslstatus;
3112 #endif
3113 	int			i;
3114 
3115 	Assert(!pgStatRunningInCollector);
3116 	if (localBackendStatusTable)
3117 		return;					/* already done */
3118 
3119 	pgstat_setup_memcxt();
3120 
3121 	localtable = (LocalPgBackendStatus *)
3122 		MemoryContextAlloc(pgStatLocalContext,
3123 						   sizeof(LocalPgBackendStatus) * MaxBackends);
3124 	localappname = (char *)
3125 		MemoryContextAlloc(pgStatLocalContext,
3126 						   NAMEDATALEN * MaxBackends);
3127 	localclienthostname = (char *)
3128 		MemoryContextAlloc(pgStatLocalContext,
3129 						   NAMEDATALEN * MaxBackends);
3130 	localactivity = (char *)
3131 		MemoryContextAlloc(pgStatLocalContext,
3132 						   pgstat_track_activity_query_size * MaxBackends);
3133 #ifdef USE_SSL
3134 	localsslstatus = (PgBackendSSLStatus *)
3135 		MemoryContextAlloc(pgStatLocalContext,
3136 						   sizeof(PgBackendSSLStatus) * MaxBackends);
3137 #endif
3138 
3139 	localNumBackends = 0;
3140 
3141 	beentry = BackendStatusArray;
3142 	localentry = localtable;
3143 	for (i = 1; i <= MaxBackends; i++)
3144 	{
3145 		/*
3146 		 * Follow the protocol of retrying if st_changecount changes while we
3147 		 * copy the entry, or if it's odd.  (The check for odd is needed to
3148 		 * cover the case where we are able to completely copy the entry while
3149 		 * the source backend is between increment steps.)	We use a volatile
3150 		 * pointer here to ensure the compiler doesn't try to get cute.
3151 		 */
3152 		for (;;)
3153 		{
3154 			int			before_changecount;
3155 			int			after_changecount;
3156 
3157 			pgstat_begin_read_activity(beentry, before_changecount);
3158 
3159 			localentry->backendStatus.st_procpid = beentry->st_procpid;
3160 			/* Skip all the data-copying work if entry is not in use */
3161 			if (localentry->backendStatus.st_procpid > 0)
3162 			{
3163 				memcpy(&localentry->backendStatus, (char *) beentry, sizeof(PgBackendStatus));
3164 
3165 				/*
3166 				 * For each PgBackendStatus field that is a pointer, copy the
3167 				 * pointed-to data, then adjust the local copy of the pointer
3168 				 * field to point at the local copy of the data.
3169 				 *
3170 				 * strcpy is safe even if the string is modified concurrently,
3171 				 * because there's always a \0 at the end of the buffer.
3172 				 */
3173 				strcpy(localappname, (char *) beentry->st_appname);
3174 				localentry->backendStatus.st_appname = localappname;
3175 				strcpy(localclienthostname, (char *) beentry->st_clienthostname);
3176 				localentry->backendStatus.st_clienthostname = localclienthostname;
3177 				strcpy(localactivity, (char *) beentry->st_activity);
3178 				localentry->backendStatus.st_activity = localactivity;
3179 #ifdef USE_SSL
3180 				if (beentry->st_ssl)
3181 				{
3182 					memcpy(localsslstatus, beentry->st_sslstatus, sizeof(PgBackendSSLStatus));
3183 					localentry->backendStatus.st_sslstatus = localsslstatus;
3184 				}
3185 #endif
3186 			}
3187 
3188 			pgstat_end_read_activity(beentry, after_changecount);
3189 
3190 			if (pgstat_read_activity_complete(before_changecount,
3191 											  after_changecount))
3192 				break;
3193 
3194 			/* Make sure we can break out of loop if stuck... */
3195 			CHECK_FOR_INTERRUPTS();
3196 		}
3197 
3198 		beentry++;
3199 		/* Only valid entries get included into the local array */
3200 		if (localentry->backendStatus.st_procpid > 0)
3201 		{
3202 			BackendIdGetTransactionIds(i,
3203 									   &localentry->backend_xid,
3204 									   &localentry->backend_xmin);
3205 
3206 			localentry++;
3207 			localappname += NAMEDATALEN;
3208 			localclienthostname += NAMEDATALEN;
3209 			localactivity += pgstat_track_activity_query_size;
3210 #ifdef USE_SSL
3211 			localsslstatus++;
3212 #endif
3213 			localNumBackends++;
3214 		}
3215 	}
3216 
3217 	/* Set the pointer only after completion of a valid table */
3218 	localBackendStatusTable = localtable;
3219 }
3220 
3221 /* ----------
3222  * pgstat_get_wait_event_type() -
3223  *
3224  *	Return a string representing the current wait event type, backend is
3225  *	waiting on.
3226  */
3227 const char *
pgstat_get_wait_event_type(uint32 wait_event_info)3228 pgstat_get_wait_event_type(uint32 wait_event_info)
3229 {
3230 	uint8		classId;
3231 	const char *event_type;
3232 
3233 	/* report process as not waiting. */
3234 	if (wait_event_info == 0)
3235 		return NULL;
3236 
3237 	wait_event_info = wait_event_info >> 24;
3238 	classId = wait_event_info & 0XFF;
3239 
3240 	switch (classId)
3241 	{
3242 		case WAIT_LWLOCK_NAMED:
3243 			event_type = "LWLockNamed";
3244 			break;
3245 		case WAIT_LWLOCK_TRANCHE:
3246 			event_type = "LWLockTranche";
3247 			break;
3248 		case WAIT_LOCK:
3249 			event_type = "Lock";
3250 			break;
3251 		case WAIT_BUFFER_PIN:
3252 			event_type = "BufferPin";
3253 			break;
3254 		default:
3255 			event_type = "???";
3256 			break;
3257 	}
3258 
3259 	return event_type;
3260 }
3261 
3262 /* ----------
3263  * pgstat_get_wait_event() -
3264  *
3265  *	Return a string representing the current wait event, backend is
3266  *	waiting on.
3267  */
3268 const char *
pgstat_get_wait_event(uint32 wait_event_info)3269 pgstat_get_wait_event(uint32 wait_event_info)
3270 {
3271 	uint8		classId;
3272 	uint16		eventId;
3273 	const char *event_name;
3274 
3275 	/* report process as not waiting. */
3276 	if (wait_event_info == 0)
3277 		return NULL;
3278 
3279 	eventId = wait_event_info & ((1 << 24) - 1);
3280 	wait_event_info = wait_event_info >> 24;
3281 	classId = wait_event_info & 0XFF;
3282 
3283 	switch (classId)
3284 	{
3285 		case WAIT_LWLOCK_NAMED:
3286 		case WAIT_LWLOCK_TRANCHE:
3287 			event_name = GetLWLockIdentifier(classId, eventId);
3288 			break;
3289 		case WAIT_LOCK:
3290 			event_name = GetLockNameFromTagType(eventId);
3291 			break;
3292 		case WAIT_BUFFER_PIN:
3293 			event_name = "BufferPin";
3294 			break;
3295 		default:
3296 			event_name = "unknown wait event";
3297 			break;
3298 	}
3299 
3300 	return event_name;
3301 }
3302 
3303 /* ----------
3304  * pgstat_get_backend_current_activity() -
3305  *
3306  *	Return a string representing the current activity of the backend with
3307  *	the specified PID.  This looks directly at the BackendStatusArray,
3308  *	and so will provide current information regardless of the age of our
3309  *	transaction's snapshot of the status array.
3310  *
3311  *	It is the caller's responsibility to invoke this only for backends whose
3312  *	state is expected to remain stable while the result is in use.  The
3313  *	only current use is in deadlock reporting, where we can expect that
3314  *	the target backend is blocked on a lock.  (There are corner cases
3315  *	where the target's wait could get aborted while we are looking at it,
3316  *	but the very worst consequence is to return a pointer to a string
3317  *	that's been changed, so we won't worry too much.)
3318  *
3319  *	Note: return strings for special cases match pg_stat_get_backend_activity.
3320  * ----------
3321  */
3322 const char *
pgstat_get_backend_current_activity(int pid,bool checkUser)3323 pgstat_get_backend_current_activity(int pid, bool checkUser)
3324 {
3325 	PgBackendStatus *beentry;
3326 	int			i;
3327 
3328 	beentry = BackendStatusArray;
3329 	for (i = 1; i <= MaxBackends; i++)
3330 	{
3331 		/*
3332 		 * Although we expect the target backend's entry to be stable, that
3333 		 * doesn't imply that anyone else's is.  To avoid identifying the
3334 		 * wrong backend, while we check for a match to the desired PID we
3335 		 * must follow the protocol of retrying if st_changecount changes
3336 		 * while we examine the entry, or if it's odd.  (This might be
3337 		 * unnecessary, since fetching or storing an int is almost certainly
3338 		 * atomic, but let's play it safe.)  We use a volatile pointer here to
3339 		 * ensure the compiler doesn't try to get cute.
3340 		 */
3341 		volatile PgBackendStatus *vbeentry = beentry;
3342 		bool		found;
3343 
3344 		for (;;)
3345 		{
3346 			int			before_changecount;
3347 			int			after_changecount;
3348 
3349 			pgstat_begin_read_activity(vbeentry, before_changecount);
3350 
3351 			found = (vbeentry->st_procpid == pid);
3352 
3353 			pgstat_end_read_activity(vbeentry, after_changecount);
3354 
3355 			if (pgstat_read_activity_complete(before_changecount,
3356 											  after_changecount))
3357 				break;
3358 
3359 			/* Make sure we can break out of loop if stuck... */
3360 			CHECK_FOR_INTERRUPTS();
3361 		}
3362 
3363 		if (found)
3364 		{
3365 			/* Now it is safe to use the non-volatile pointer */
3366 			if (checkUser && !superuser() && beentry->st_userid != GetUserId())
3367 				return "<insufficient privilege>";
3368 			else if (*(beentry->st_activity) == '\0')
3369 				return "<command string not enabled>";
3370 			else
3371 				return beentry->st_activity;
3372 		}
3373 
3374 		beentry++;
3375 	}
3376 
3377 	/* If we get here, caller is in error ... */
3378 	return "<backend information not available>";
3379 }
3380 
3381 /* ----------
3382  * pgstat_get_crashed_backend_activity() -
3383  *
3384  *	Return a string representing the current activity of the backend with
3385  *	the specified PID.  Like the function above, but reads shared memory with
3386  *	the expectation that it may be corrupt.  On success, copy the string
3387  *	into the "buffer" argument and return that pointer.  On failure,
3388  *	return NULL.
3389  *
3390  *	This function is only intended to be used by the postmaster to report the
3391  *	query that crashed a backend.  In particular, no attempt is made to
3392  *	follow the correct concurrency protocol when accessing the
3393  *	BackendStatusArray.  But that's OK, in the worst case we'll return a
3394  *	corrupted message.  We also must take care not to trip on ereport(ERROR).
3395  * ----------
3396  */
3397 const char *
pgstat_get_crashed_backend_activity(int pid,char * buffer,int buflen)3398 pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
3399 {
3400 	volatile PgBackendStatus *beentry;
3401 	int			i;
3402 
3403 	beentry = BackendStatusArray;
3404 
3405 	/*
3406 	 * We probably shouldn't get here before shared memory has been set up,
3407 	 * but be safe.
3408 	 */
3409 	if (beentry == NULL || BackendActivityBuffer == NULL)
3410 		return NULL;
3411 
3412 	for (i = 1; i <= MaxBackends; i++)
3413 	{
3414 		if (beentry->st_procpid == pid)
3415 		{
3416 			/* Read pointer just once, so it can't change after validation */
3417 			const char *activity = beentry->st_activity;
3418 			const char *activity_last;
3419 
3420 			/*
3421 			 * We mustn't access activity string before we verify that it
3422 			 * falls within the BackendActivityBuffer. To make sure that the
3423 			 * entire string including its ending is contained within the
3424 			 * buffer, subtract one activity length from the buffer size.
3425 			 */
3426 			activity_last = BackendActivityBuffer + BackendActivityBufferSize
3427 				- pgstat_track_activity_query_size;
3428 
3429 			if (activity < BackendActivityBuffer ||
3430 				activity > activity_last)
3431 				return NULL;
3432 
3433 			/* If no string available, no point in a report */
3434 			if (activity[0] == '\0')
3435 				return NULL;
3436 
3437 			/*
3438 			 * Copy only ASCII-safe characters so we don't run into encoding
3439 			 * problems when reporting the message; and be sure not to run off
3440 			 * the end of memory.
3441 			 */
3442 			ascii_safe_strlcpy(buffer, activity,
3443 							   Min(buflen, pgstat_track_activity_query_size));
3444 
3445 			return buffer;
3446 		}
3447 
3448 		beentry++;
3449 	}
3450 
3451 	/* PID not found */
3452 	return NULL;
3453 }
3454 
3455 
3456 /* ------------------------------------------------------------
3457  * Local support functions follow
3458  * ------------------------------------------------------------
3459  */
3460 
3461 
3462 /* ----------
3463  * pgstat_setheader() -
3464  *
3465  *		Set common header fields in a statistics message
3466  * ----------
3467  */
3468 static void
pgstat_setheader(PgStat_MsgHdr * hdr,StatMsgType mtype)3469 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
3470 {
3471 	hdr->m_type = mtype;
3472 }
3473 
3474 
3475 /* ----------
3476  * pgstat_send() -
3477  *
3478  *		Send out one statistics message to the collector
3479  * ----------
3480  */
3481 static void
pgstat_send(void * msg,int len)3482 pgstat_send(void *msg, int len)
3483 {
3484 	int			rc;
3485 
3486 	if (pgStatSock == PGINVALID_SOCKET)
3487 		return;
3488 
3489 	((PgStat_MsgHdr *) msg)->m_size = len;
3490 
3491 	/* We'll retry after EINTR, but ignore all other failures */
3492 	do
3493 	{
3494 		rc = send(pgStatSock, msg, len, 0);
3495 	} while (rc < 0 && errno == EINTR);
3496 
3497 #ifdef USE_ASSERT_CHECKING
3498 	/* In debug builds, log send failures ... */
3499 	if (rc < 0)
3500 		elog(LOG, "could not send to statistics collector: %m");
3501 #endif
3502 }
3503 
3504 /* ----------
3505  * pgstat_send_archiver() -
3506  *
3507  *	Tell the collector about the WAL file that we successfully
3508  *	archived or failed to archive.
3509  * ----------
3510  */
3511 void
pgstat_send_archiver(const char * xlog,bool failed)3512 pgstat_send_archiver(const char *xlog, bool failed)
3513 {
3514 	PgStat_MsgArchiver msg;
3515 
3516 	/*
3517 	 * Prepare and send the message
3518 	 */
3519 	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ARCHIVER);
3520 	msg.m_failed = failed;
3521 	StrNCpy(msg.m_xlog, xlog, sizeof(msg.m_xlog));
3522 	msg.m_timestamp = GetCurrentTimestamp();
3523 	pgstat_send(&msg, sizeof(msg));
3524 }
3525 
3526 /* ----------
3527  * pgstat_send_bgwriter() -
3528  *
3529  *		Send bgwriter statistics to the collector
3530  * ----------
3531  */
3532 void
pgstat_send_bgwriter(void)3533 pgstat_send_bgwriter(void)
3534 {
3535 	/* We assume this initializes to zeroes */
3536 	static const PgStat_MsgBgWriter all_zeroes;
3537 
3538 	/*
3539 	 * This function can be called even if nothing at all has happened. In
3540 	 * this case, avoid sending a completely empty message to the stats
3541 	 * collector.
3542 	 */
3543 	if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
3544 		return;
3545 
3546 	/*
3547 	 * Prepare and send the message
3548 	 */
3549 	pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
3550 	pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
3551 
3552 	/*
3553 	 * Clear out the statistics buffer, so it can be re-used.
3554 	 */
3555 	MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
3556 }
3557 
3558 
3559 /* ----------
3560  * PgstatCollectorMain() -
3561  *
3562  *	Start up the statistics collector process.  This is the body of the
3563  *	postmaster child process.
3564  *
3565  *	The argc/argv parameters are valid only in EXEC_BACKEND case.
3566  * ----------
3567  */
3568 NON_EXEC_STATIC void
PgstatCollectorMain(int argc,char * argv[])3569 PgstatCollectorMain(int argc, char *argv[])
3570 {
3571 	int			len;
3572 	PgStat_Msg	msg;
3573 	int			wr;
3574 
3575 	/*
3576 	 * Ignore all signals usually bound to some action in the postmaster,
3577 	 * except SIGHUP and SIGQUIT.  Note we don't need a SIGUSR1 handler to
3578 	 * support latch operations, because we only use a local latch.
3579 	 */
3580 	pqsignal(SIGHUP, pgstat_sighup_handler);
3581 	pqsignal(SIGINT, SIG_IGN);
3582 	pqsignal(SIGTERM, SIG_IGN);
3583 	pqsignal(SIGQUIT, pgstat_exit);
3584 	pqsignal(SIGALRM, SIG_IGN);
3585 	pqsignal(SIGPIPE, SIG_IGN);
3586 	pqsignal(SIGUSR1, SIG_IGN);
3587 	pqsignal(SIGUSR2, SIG_IGN);
3588 	pqsignal(SIGCHLD, SIG_DFL);
3589 	pqsignal(SIGTTIN, SIG_DFL);
3590 	pqsignal(SIGTTOU, SIG_DFL);
3591 	pqsignal(SIGCONT, SIG_DFL);
3592 	pqsignal(SIGWINCH, SIG_DFL);
3593 	PG_SETMASK(&UnBlockSig);
3594 
3595 	/*
3596 	 * Identify myself via ps
3597 	 */
3598 	init_ps_display("stats collector process", "", "", "");
3599 
3600 	/*
3601 	 * Read in existing stats files or initialize the stats to zero.
3602 	 */
3603 	pgStatRunningInCollector = true;
3604 	pgStatDBHash = pgstat_read_statsfiles(InvalidOid, true, true);
3605 
3606 	/*
3607 	 * Loop to process messages until we get SIGQUIT or detect ungraceful
3608 	 * death of our parent postmaster.
3609 	 *
3610 	 * For performance reasons, we don't want to do ResetLatch/WaitLatch after
3611 	 * every message; instead, do that only after a recv() fails to obtain a
3612 	 * message.  (This effectively means that if backends are sending us stuff
3613 	 * like mad, we won't notice postmaster death until things slack off a
3614 	 * bit; which seems fine.)	To do that, we have an inner loop that
3615 	 * iterates as long as recv() succeeds.  We do recognize got_SIGHUP inside
3616 	 * the inner loop, which means that such interrupts will get serviced but
3617 	 * the latch won't get cleared until next time there is a break in the
3618 	 * action.
3619 	 */
3620 	for (;;)
3621 	{
3622 		/* Clear any already-pending wakeups */
3623 		ResetLatch(MyLatch);
3624 
3625 		/*
3626 		 * Quit if we get SIGQUIT from the postmaster.
3627 		 */
3628 		if (need_exit)
3629 			break;
3630 
3631 		/*
3632 		 * Inner loop iterates as long as we keep getting messages, or until
3633 		 * need_exit becomes set.
3634 		 */
3635 		while (!need_exit)
3636 		{
3637 			/*
3638 			 * Reload configuration if we got SIGHUP from the postmaster.
3639 			 */
3640 			if (got_SIGHUP)
3641 			{
3642 				got_SIGHUP = false;
3643 				ProcessConfigFile(PGC_SIGHUP);
3644 			}
3645 
3646 			/*
3647 			 * Write the stats file(s) if a new request has arrived that is
3648 			 * not satisfied by existing file(s).
3649 			 */
3650 			if (pgstat_write_statsfile_needed())
3651 				pgstat_write_statsfiles(false, false);
3652 
3653 			/*
3654 			 * Try to receive and process a message.  This will not block,
3655 			 * since the socket is set to non-blocking mode.
3656 			 *
3657 			 * XXX On Windows, we have to force pgwin32_recv to cooperate,
3658 			 * despite the previous use of pg_set_noblock() on the socket.
3659 			 * This is extremely broken and should be fixed someday.
3660 			 */
3661 #ifdef WIN32
3662 			pgwin32_noblock = 1;
3663 #endif
3664 
3665 			len = recv(pgStatSock, (char *) &msg,
3666 					   sizeof(PgStat_Msg), 0);
3667 
3668 #ifdef WIN32
3669 			pgwin32_noblock = 0;
3670 #endif
3671 
3672 			if (len < 0)
3673 			{
3674 				if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
3675 					break;		/* out of inner loop */
3676 				ereport(ERROR,
3677 						(errcode_for_socket_access(),
3678 						 errmsg("could not read statistics message: %m")));
3679 			}
3680 
3681 			/*
3682 			 * We ignore messages that are smaller than our common header
3683 			 */
3684 			if (len < sizeof(PgStat_MsgHdr))
3685 				continue;
3686 
3687 			/*
3688 			 * The received length must match the length in the header
3689 			 */
3690 			if (msg.msg_hdr.m_size != len)
3691 				continue;
3692 
3693 			/*
3694 			 * O.K. - we accept this message.  Process it.
3695 			 */
3696 			switch (msg.msg_hdr.m_type)
3697 			{
3698 				case PGSTAT_MTYPE_DUMMY:
3699 					break;
3700 
3701 				case PGSTAT_MTYPE_INQUIRY:
3702 					pgstat_recv_inquiry((PgStat_MsgInquiry *) &msg, len);
3703 					break;
3704 
3705 				case PGSTAT_MTYPE_TABSTAT:
3706 					pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
3707 					break;
3708 
3709 				case PGSTAT_MTYPE_TABPURGE:
3710 					pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
3711 					break;
3712 
3713 				case PGSTAT_MTYPE_DROPDB:
3714 					pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
3715 					break;
3716 
3717 				case PGSTAT_MTYPE_RESETCOUNTER:
3718 					pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
3719 											 len);
3720 					break;
3721 
3722 				case PGSTAT_MTYPE_RESETSHAREDCOUNTER:
3723 					pgstat_recv_resetsharedcounter(
3724 									   (PgStat_MsgResetsharedcounter *) &msg,
3725 												   len);
3726 					break;
3727 
3728 				case PGSTAT_MTYPE_RESETSINGLECOUNTER:
3729 					pgstat_recv_resetsinglecounter(
3730 									   (PgStat_MsgResetsinglecounter *) &msg,
3731 												   len);
3732 					break;
3733 
3734 				case PGSTAT_MTYPE_AUTOVAC_START:
3735 					pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
3736 					break;
3737 
3738 				case PGSTAT_MTYPE_VACUUM:
3739 					pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
3740 					break;
3741 
3742 				case PGSTAT_MTYPE_ANALYZE:
3743 					pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
3744 					break;
3745 
3746 				case PGSTAT_MTYPE_ARCHIVER:
3747 					pgstat_recv_archiver((PgStat_MsgArchiver *) &msg, len);
3748 					break;
3749 
3750 				case PGSTAT_MTYPE_BGWRITER:
3751 					pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
3752 					break;
3753 
3754 				case PGSTAT_MTYPE_FUNCSTAT:
3755 					pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
3756 					break;
3757 
3758 				case PGSTAT_MTYPE_FUNCPURGE:
3759 					pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
3760 					break;
3761 
3762 				case PGSTAT_MTYPE_RECOVERYCONFLICT:
3763 					pgstat_recv_recoveryconflict((PgStat_MsgRecoveryConflict *) &msg, len);
3764 					break;
3765 
3766 				case PGSTAT_MTYPE_DEADLOCK:
3767 					pgstat_recv_deadlock((PgStat_MsgDeadlock *) &msg, len);
3768 					break;
3769 
3770 				case PGSTAT_MTYPE_TEMPFILE:
3771 					pgstat_recv_tempfile((PgStat_MsgTempFile *) &msg, len);
3772 					break;
3773 
3774 				default:
3775 					break;
3776 			}
3777 		}						/* end of inner message-processing loop */
3778 
3779 		/* Sleep until there's something to do */
3780 #ifndef WIN32
3781 		wr = WaitLatchOrSocket(MyLatch,
3782 					 WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
3783 							   pgStatSock,
3784 							   -1L);
3785 #else
3786 
3787 		/*
3788 		 * Windows, at least in its Windows Server 2003 R2 incarnation,
3789 		 * sometimes loses FD_READ events.  Waking up and retrying the recv()
3790 		 * fixes that, so don't sleep indefinitely.  This is a crock of the
3791 		 * first water, but until somebody wants to debug exactly what's
3792 		 * happening there, this is the best we can do.  The two-second
3793 		 * timeout matches our pre-9.2 behavior, and needs to be short enough
3794 		 * to not provoke "using stale statistics" complaints from
3795 		 * backend_read_statsfile.
3796 		 */
3797 		wr = WaitLatchOrSocket(MyLatch,
3798 		WL_LATCH_SET | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE | WL_TIMEOUT,
3799 							   pgStatSock,
3800 							   2 * 1000L /* msec */ );
3801 #endif
3802 
3803 		/*
3804 		 * Emergency bailout if postmaster has died.  This is to avoid the
3805 		 * necessity for manual cleanup of all postmaster children.
3806 		 */
3807 		if (wr & WL_POSTMASTER_DEATH)
3808 			break;
3809 	}							/* end of outer loop */
3810 
3811 	/*
3812 	 * Save the final stats to reuse at next startup.
3813 	 */
3814 	pgstat_write_statsfiles(true, true);
3815 
3816 	exit(0);
3817 }
3818 
3819 
3820 /* SIGQUIT signal handler for collector process */
3821 static void
pgstat_exit(SIGNAL_ARGS)3822 pgstat_exit(SIGNAL_ARGS)
3823 {
3824 	int			save_errno = errno;
3825 
3826 	need_exit = true;
3827 	SetLatch(MyLatch);
3828 
3829 	errno = save_errno;
3830 }
3831 
3832 /* SIGHUP handler for collector process */
3833 static void
pgstat_sighup_handler(SIGNAL_ARGS)3834 pgstat_sighup_handler(SIGNAL_ARGS)
3835 {
3836 	int			save_errno = errno;
3837 
3838 	got_SIGHUP = true;
3839 	SetLatch(MyLatch);
3840 
3841 	errno = save_errno;
3842 }
3843 
3844 /*
3845  * Subroutine to clear stats in a database entry
3846  *
3847  * Tables and functions hashes are initialized to empty.
3848  */
3849 static void
reset_dbentry_counters(PgStat_StatDBEntry * dbentry)3850 reset_dbentry_counters(PgStat_StatDBEntry *dbentry)
3851 {
3852 	HASHCTL		hash_ctl;
3853 
3854 	dbentry->n_xact_commit = 0;
3855 	dbentry->n_xact_rollback = 0;
3856 	dbentry->n_blocks_fetched = 0;
3857 	dbentry->n_blocks_hit = 0;
3858 	dbentry->n_tuples_returned = 0;
3859 	dbentry->n_tuples_fetched = 0;
3860 	dbentry->n_tuples_inserted = 0;
3861 	dbentry->n_tuples_updated = 0;
3862 	dbentry->n_tuples_deleted = 0;
3863 	dbentry->last_autovac_time = 0;
3864 	dbentry->n_conflict_tablespace = 0;
3865 	dbentry->n_conflict_lock = 0;
3866 	dbentry->n_conflict_snapshot = 0;
3867 	dbentry->n_conflict_bufferpin = 0;
3868 	dbentry->n_conflict_startup_deadlock = 0;
3869 	dbentry->n_temp_files = 0;
3870 	dbentry->n_temp_bytes = 0;
3871 	dbentry->n_deadlocks = 0;
3872 	dbentry->n_block_read_time = 0;
3873 	dbentry->n_block_write_time = 0;
3874 
3875 	dbentry->stat_reset_timestamp = GetCurrentTimestamp();
3876 	dbentry->stats_timestamp = 0;
3877 
3878 	memset(&hash_ctl, 0, sizeof(hash_ctl));
3879 	hash_ctl.keysize = sizeof(Oid);
3880 	hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3881 	dbentry->tables = hash_create("Per-database table",
3882 								  PGSTAT_TAB_HASH_SIZE,
3883 								  &hash_ctl,
3884 								  HASH_ELEM | HASH_BLOBS);
3885 
3886 	hash_ctl.keysize = sizeof(Oid);
3887 	hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3888 	dbentry->functions = hash_create("Per-database function",
3889 									 PGSTAT_FUNCTION_HASH_SIZE,
3890 									 &hash_ctl,
3891 									 HASH_ELEM | HASH_BLOBS);
3892 }
3893 
3894 /*
3895  * Lookup the hash table entry for the specified database. If no hash
3896  * table entry exists, initialize it, if the create parameter is true.
3897  * Else, return NULL.
3898  */
3899 static PgStat_StatDBEntry *
pgstat_get_db_entry(Oid databaseid,bool create)3900 pgstat_get_db_entry(Oid databaseid, bool create)
3901 {
3902 	PgStat_StatDBEntry *result;
3903 	bool		found;
3904 	HASHACTION	action = (create ? HASH_ENTER : HASH_FIND);
3905 
3906 	/* Lookup or create the hash table entry for this database */
3907 	result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
3908 												&databaseid,
3909 												action, &found);
3910 
3911 	if (!create && !found)
3912 		return NULL;
3913 
3914 	/*
3915 	 * If not found, initialize the new one.  This creates empty hash tables
3916 	 * for tables and functions, too.
3917 	 */
3918 	if (!found)
3919 		reset_dbentry_counters(result);
3920 
3921 	return result;
3922 }
3923 
3924 
3925 /*
3926  * Lookup the hash table entry for the specified table. If no hash
3927  * table entry exists, initialize it, if the create parameter is true.
3928  * Else, return NULL.
3929  */
3930 static PgStat_StatTabEntry *
pgstat_get_tab_entry(PgStat_StatDBEntry * dbentry,Oid tableoid,bool create)3931 pgstat_get_tab_entry(PgStat_StatDBEntry *dbentry, Oid tableoid, bool create)
3932 {
3933 	PgStat_StatTabEntry *result;
3934 	bool		found;
3935 	HASHACTION	action = (create ? HASH_ENTER : HASH_FIND);
3936 
3937 	/* Lookup or create the hash table entry for this table */
3938 	result = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3939 												 &tableoid,
3940 												 action, &found);
3941 
3942 	if (!create && !found)
3943 		return NULL;
3944 
3945 	/* If not found, initialize the new one. */
3946 	if (!found)
3947 	{
3948 		result->numscans = 0;
3949 		result->tuples_returned = 0;
3950 		result->tuples_fetched = 0;
3951 		result->tuples_inserted = 0;
3952 		result->tuples_updated = 0;
3953 		result->tuples_deleted = 0;
3954 		result->tuples_hot_updated = 0;
3955 		result->n_live_tuples = 0;
3956 		result->n_dead_tuples = 0;
3957 		result->changes_since_analyze = 0;
3958 		result->blocks_fetched = 0;
3959 		result->blocks_hit = 0;
3960 		result->vacuum_timestamp = 0;
3961 		result->vacuum_count = 0;
3962 		result->autovac_vacuum_timestamp = 0;
3963 		result->autovac_vacuum_count = 0;
3964 		result->analyze_timestamp = 0;
3965 		result->analyze_count = 0;
3966 		result->autovac_analyze_timestamp = 0;
3967 		result->autovac_analyze_count = 0;
3968 	}
3969 
3970 	return result;
3971 }
3972 
3973 
3974 /* ----------
3975  * pgstat_write_statsfiles() -
3976  *		Write the global statistics file, as well as requested DB files.
3977  *
3978  *	'permanent' specifies writing to the permanent files not temporary ones.
3979  *	When true (happens only when the collector is shutting down), also remove
3980  *	the temporary files so that backends starting up under a new postmaster
3981  *	can't read old data before the new collector is ready.
3982  *
3983  *	When 'allDbs' is false, only the requested databases (listed in
3984  *	pending_write_requests) will be written; otherwise, all databases
3985  *	will be written.
3986  * ----------
3987  */
3988 static void
pgstat_write_statsfiles(bool permanent,bool allDbs)3989 pgstat_write_statsfiles(bool permanent, bool allDbs)
3990 {
3991 	HASH_SEQ_STATUS hstat;
3992 	PgStat_StatDBEntry *dbentry;
3993 	FILE	   *fpout;
3994 	int32		format_id;
3995 	const char *tmpfile = permanent ? PGSTAT_STAT_PERMANENT_TMPFILE : pgstat_stat_tmpname;
3996 	const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
3997 	int			rc;
3998 
3999 	elog(DEBUG2, "writing stats file \"%s\"", statfile);
4000 
4001 	/*
4002 	 * Open the statistics temp file to write out the current values.
4003 	 */
4004 	fpout = AllocateFile(tmpfile, PG_BINARY_W);
4005 	if (fpout == NULL)
4006 	{
4007 		ereport(LOG,
4008 				(errcode_for_file_access(),
4009 				 errmsg("could not open temporary statistics file \"%s\": %m",
4010 						tmpfile)));
4011 		return;
4012 	}
4013 
4014 	/*
4015 	 * Set the timestamp of the stats file.
4016 	 */
4017 	globalStats.stats_timestamp = GetCurrentTimestamp();
4018 
4019 	/*
4020 	 * Write the file header --- currently just a format ID.
4021 	 */
4022 	format_id = PGSTAT_FILE_FORMAT_ID;
4023 	rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4024 	(void) rc;					/* we'll check for error with ferror */
4025 
4026 	/*
4027 	 * Write global stats struct
4028 	 */
4029 	rc = fwrite(&globalStats, sizeof(globalStats), 1, fpout);
4030 	(void) rc;					/* we'll check for error with ferror */
4031 
4032 	/*
4033 	 * Write archiver stats struct
4034 	 */
4035 	rc = fwrite(&archiverStats, sizeof(archiverStats), 1, fpout);
4036 	(void) rc;					/* we'll check for error with ferror */
4037 
4038 	/*
4039 	 * Walk through the database table.
4040 	 */
4041 	hash_seq_init(&hstat, pgStatDBHash);
4042 	while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
4043 	{
4044 		/*
4045 		 * Write out the table and function stats for this DB into the
4046 		 * appropriate per-DB stat file, if required.
4047 		 */
4048 		if (allDbs || pgstat_db_requested(dbentry->databaseid))
4049 		{
4050 			/* Make DB's timestamp consistent with the global stats */
4051 			dbentry->stats_timestamp = globalStats.stats_timestamp;
4052 
4053 			pgstat_write_db_statsfile(dbentry, permanent);
4054 		}
4055 
4056 		/*
4057 		 * Write out the DB entry. We don't write the tables or functions
4058 		 * pointers, since they're of no use to any other process.
4059 		 */
4060 		fputc('D', fpout);
4061 		rc = fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
4062 		(void) rc;				/* we'll check for error with ferror */
4063 	}
4064 
4065 	/*
4066 	 * No more output to be done. Close the temp file and replace the old
4067 	 * pgstat.stat with it.  The ferror() check replaces testing for error
4068 	 * after each individual fputc or fwrite above.
4069 	 */
4070 	fputc('E', fpout);
4071 
4072 	if (ferror(fpout))
4073 	{
4074 		ereport(LOG,
4075 				(errcode_for_file_access(),
4076 			   errmsg("could not write temporary statistics file \"%s\": %m",
4077 					  tmpfile)));
4078 		FreeFile(fpout);
4079 		unlink(tmpfile);
4080 	}
4081 	else if (FreeFile(fpout) < 0)
4082 	{
4083 		ereport(LOG,
4084 				(errcode_for_file_access(),
4085 			   errmsg("could not close temporary statistics file \"%s\": %m",
4086 					  tmpfile)));
4087 		unlink(tmpfile);
4088 	}
4089 	else if (rename(tmpfile, statfile) < 0)
4090 	{
4091 		ereport(LOG,
4092 				(errcode_for_file_access(),
4093 				 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
4094 						tmpfile, statfile)));
4095 		unlink(tmpfile);
4096 	}
4097 
4098 	if (permanent)
4099 		unlink(pgstat_stat_filename);
4100 
4101 	/*
4102 	 * Now throw away the list of requests.  Note that requests sent after we
4103 	 * started the write are still waiting on the network socket.
4104 	 */
4105 	list_free(pending_write_requests);
4106 	pending_write_requests = NIL;
4107 }
4108 
4109 /*
4110  * return the filename for a DB stat file; filename is the output buffer,
4111  * of length len.
4112  */
4113 static void
get_dbstat_filename(bool permanent,bool tempname,Oid databaseid,char * filename,int len)4114 get_dbstat_filename(bool permanent, bool tempname, Oid databaseid,
4115 					char *filename, int len)
4116 {
4117 	int			printed;
4118 
4119 	/* NB -- pgstat_reset_remove_files knows about the pattern this uses */
4120 	printed = snprintf(filename, len, "%s/db_%u.%s",
4121 					   permanent ? PGSTAT_STAT_PERMANENT_DIRECTORY :
4122 					   pgstat_stat_directory,
4123 					   databaseid,
4124 					   tempname ? "tmp" : "stat");
4125 	if (printed >= len)
4126 		elog(ERROR, "overlength pgstat path");
4127 }
4128 
4129 /* ----------
4130  * pgstat_write_db_statsfile() -
4131  *		Write the stat file for a single database.
4132  *
4133  *	If writing to the permanent file (happens when the collector is
4134  *	shutting down only), remove the temporary file so that backends
4135  *	starting up under a new postmaster can't read the old data before
4136  *	the new collector is ready.
4137  * ----------
4138  */
4139 static void
pgstat_write_db_statsfile(PgStat_StatDBEntry * dbentry,bool permanent)4140 pgstat_write_db_statsfile(PgStat_StatDBEntry *dbentry, bool permanent)
4141 {
4142 	HASH_SEQ_STATUS tstat;
4143 	HASH_SEQ_STATUS fstat;
4144 	PgStat_StatTabEntry *tabentry;
4145 	PgStat_StatFuncEntry *funcentry;
4146 	FILE	   *fpout;
4147 	int32		format_id;
4148 	Oid			dbid = dbentry->databaseid;
4149 	int			rc;
4150 	char		tmpfile[MAXPGPATH];
4151 	char		statfile[MAXPGPATH];
4152 
4153 	get_dbstat_filename(permanent, true, dbid, tmpfile, MAXPGPATH);
4154 	get_dbstat_filename(permanent, false, dbid, statfile, MAXPGPATH);
4155 
4156 	elog(DEBUG2, "writing stats file \"%s\"", statfile);
4157 
4158 	/*
4159 	 * Open the statistics temp file to write out the current values.
4160 	 */
4161 	fpout = AllocateFile(tmpfile, PG_BINARY_W);
4162 	if (fpout == NULL)
4163 	{
4164 		ereport(LOG,
4165 				(errcode_for_file_access(),
4166 				 errmsg("could not open temporary statistics file \"%s\": %m",
4167 						tmpfile)));
4168 		return;
4169 	}
4170 
4171 	/*
4172 	 * Write the file header --- currently just a format ID.
4173 	 */
4174 	format_id = PGSTAT_FILE_FORMAT_ID;
4175 	rc = fwrite(&format_id, sizeof(format_id), 1, fpout);
4176 	(void) rc;					/* we'll check for error with ferror */
4177 
4178 	/*
4179 	 * Walk through the database's access stats per table.
4180 	 */
4181 	hash_seq_init(&tstat, dbentry->tables);
4182 	while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
4183 	{
4184 		fputc('T', fpout);
4185 		rc = fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
4186 		(void) rc;				/* we'll check for error with ferror */
4187 	}
4188 
4189 	/*
4190 	 * Walk through the database's function stats table.
4191 	 */
4192 	hash_seq_init(&fstat, dbentry->functions);
4193 	while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
4194 	{
4195 		fputc('F', fpout);
4196 		rc = fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
4197 		(void) rc;				/* we'll check for error with ferror */
4198 	}
4199 
4200 	/*
4201 	 * No more output to be done. Close the temp file and replace the old
4202 	 * pgstat.stat with it.  The ferror() check replaces testing for error
4203 	 * after each individual fputc or fwrite above.
4204 	 */
4205 	fputc('E', fpout);
4206 
4207 	if (ferror(fpout))
4208 	{
4209 		ereport(LOG,
4210 				(errcode_for_file_access(),
4211 			   errmsg("could not write temporary statistics file \"%s\": %m",
4212 					  tmpfile)));
4213 		FreeFile(fpout);
4214 		unlink(tmpfile);
4215 	}
4216 	else if (FreeFile(fpout) < 0)
4217 	{
4218 		ereport(LOG,
4219 				(errcode_for_file_access(),
4220 			   errmsg("could not close temporary statistics file \"%s\": %m",
4221 					  tmpfile)));
4222 		unlink(tmpfile);
4223 	}
4224 	else if (rename(tmpfile, statfile) < 0)
4225 	{
4226 		ereport(LOG,
4227 				(errcode_for_file_access(),
4228 				 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
4229 						tmpfile, statfile)));
4230 		unlink(tmpfile);
4231 	}
4232 
4233 	if (permanent)
4234 	{
4235 		get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
4236 
4237 		elog(DEBUG2, "removing temporary stats file \"%s\"", statfile);
4238 		unlink(statfile);
4239 	}
4240 }
4241 
4242 /* ----------
4243  * pgstat_read_statsfiles() -
4244  *
4245  *	Reads in some existing statistics collector files and returns the
4246  *	databases hash table that is the top level of the data.
4247  *
4248  *	If 'onlydb' is not InvalidOid, it means we only want data for that DB
4249  *	plus the shared catalogs ("DB 0").  We'll still populate the DB hash
4250  *	table for all databases, but we don't bother even creating table/function
4251  *	hash tables for other databases.
4252  *
4253  *	'permanent' specifies reading from the permanent files not temporary ones.
4254  *	When true (happens only when the collector is starting up), remove the
4255  *	files after reading; the in-memory status is now authoritative, and the
4256  *	files would be out of date in case somebody else reads them.
4257  *
4258  *	If a 'deep' read is requested, table/function stats are read, otherwise
4259  *	the table/function hash tables remain empty.
4260  * ----------
4261  */
4262 static HTAB *
pgstat_read_statsfiles(Oid onlydb,bool permanent,bool deep)4263 pgstat_read_statsfiles(Oid onlydb, bool permanent, bool deep)
4264 {
4265 	PgStat_StatDBEntry *dbentry;
4266 	PgStat_StatDBEntry dbbuf;
4267 	HASHCTL		hash_ctl;
4268 	HTAB	   *dbhash;
4269 	FILE	   *fpin;
4270 	int32		format_id;
4271 	bool		found;
4272 	const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4273 
4274 	/*
4275 	 * The tables will live in pgStatLocalContext.
4276 	 */
4277 	pgstat_setup_memcxt();
4278 
4279 	/*
4280 	 * Create the DB hashtable
4281 	 */
4282 	memset(&hash_ctl, 0, sizeof(hash_ctl));
4283 	hash_ctl.keysize = sizeof(Oid);
4284 	hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
4285 	hash_ctl.hcxt = pgStatLocalContext;
4286 	dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
4287 						 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
4288 
4289 	/*
4290 	 * Clear out global and archiver statistics so they start from zero in
4291 	 * case we can't load an existing statsfile.
4292 	 */
4293 	memset(&globalStats, 0, sizeof(globalStats));
4294 	memset(&archiverStats, 0, sizeof(archiverStats));
4295 
4296 	/*
4297 	 * Set the current timestamp (will be kept only in case we can't load an
4298 	 * existing statsfile).
4299 	 */
4300 	globalStats.stat_reset_timestamp = GetCurrentTimestamp();
4301 	archiverStats.stat_reset_timestamp = globalStats.stat_reset_timestamp;
4302 
4303 	/*
4304 	 * Try to open the stats file. If it doesn't exist, the backends simply
4305 	 * return zero for anything and the collector simply starts from scratch
4306 	 * with empty counters.
4307 	 *
4308 	 * ENOENT is a possibility if the stats collector is not running or has
4309 	 * not yet written the stats file the first time.  Any other failure
4310 	 * condition is suspicious.
4311 	 */
4312 	if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4313 	{
4314 		if (errno != ENOENT)
4315 			ereport(pgStatRunningInCollector ? LOG : WARNING,
4316 					(errcode_for_file_access(),
4317 					 errmsg("could not open statistics file \"%s\": %m",
4318 							statfile)));
4319 		return dbhash;
4320 	}
4321 
4322 	/*
4323 	 * Verify it's of the expected format.
4324 	 */
4325 	if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4326 		format_id != PGSTAT_FILE_FORMAT_ID)
4327 	{
4328 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4329 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4330 		goto done;
4331 	}
4332 
4333 	/*
4334 	 * Read global stats struct
4335 	 */
4336 	if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
4337 	{
4338 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4339 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4340 		memset(&globalStats, 0, sizeof(globalStats));
4341 		goto done;
4342 	}
4343 
4344 	/*
4345 	 * In the collector, disregard the timestamp we read from the permanent
4346 	 * stats file; we should be willing to write a temp stats file immediately
4347 	 * upon the first request from any backend.  This only matters if the old
4348 	 * file's timestamp is less than PGSTAT_STAT_INTERVAL ago, but that's not
4349 	 * an unusual scenario.
4350 	 */
4351 	if (pgStatRunningInCollector)
4352 		globalStats.stats_timestamp = 0;
4353 
4354 	/*
4355 	 * Read archiver stats struct
4356 	 */
4357 	if (fread(&archiverStats, 1, sizeof(archiverStats), fpin) != sizeof(archiverStats))
4358 	{
4359 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4360 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4361 		memset(&archiverStats, 0, sizeof(archiverStats));
4362 		goto done;
4363 	}
4364 
4365 	/*
4366 	 * We found an existing collector stats file. Read it and put all the
4367 	 * hashtable entries into place.
4368 	 */
4369 	for (;;)
4370 	{
4371 		switch (fgetc(fpin))
4372 		{
4373 				/*
4374 				 * 'D'	A PgStat_StatDBEntry struct describing a database
4375 				 * follows.
4376 				 */
4377 			case 'D':
4378 				if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
4379 						  fpin) != offsetof(PgStat_StatDBEntry, tables))
4380 				{
4381 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4382 							(errmsg("corrupted statistics file \"%s\"",
4383 									statfile)));
4384 					goto done;
4385 				}
4386 
4387 				/*
4388 				 * Add to the DB hash
4389 				 */
4390 				dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
4391 												  (void *) &dbbuf.databaseid,
4392 															 HASH_ENTER,
4393 															 &found);
4394 				if (found)
4395 				{
4396 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4397 							(errmsg("corrupted statistics file \"%s\"",
4398 									statfile)));
4399 					goto done;
4400 				}
4401 
4402 				memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
4403 				dbentry->tables = NULL;
4404 				dbentry->functions = NULL;
4405 
4406 				/*
4407 				 * In the collector, disregard the timestamp we read from the
4408 				 * permanent stats file; we should be willing to write a temp
4409 				 * stats file immediately upon the first request from any
4410 				 * backend.
4411 				 */
4412 				if (pgStatRunningInCollector)
4413 					dbentry->stats_timestamp = 0;
4414 
4415 				/*
4416 				 * Don't create tables/functions hashtables for uninteresting
4417 				 * databases.
4418 				 */
4419 				if (onlydb != InvalidOid)
4420 				{
4421 					if (dbbuf.databaseid != onlydb &&
4422 						dbbuf.databaseid != InvalidOid)
4423 						break;
4424 				}
4425 
4426 				memset(&hash_ctl, 0, sizeof(hash_ctl));
4427 				hash_ctl.keysize = sizeof(Oid);
4428 				hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
4429 				hash_ctl.hcxt = pgStatLocalContext;
4430 				dbentry->tables = hash_create("Per-database table",
4431 											  PGSTAT_TAB_HASH_SIZE,
4432 											  &hash_ctl,
4433 									  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
4434 
4435 				hash_ctl.keysize = sizeof(Oid);
4436 				hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
4437 				hash_ctl.hcxt = pgStatLocalContext;
4438 				dbentry->functions = hash_create("Per-database function",
4439 												 PGSTAT_FUNCTION_HASH_SIZE,
4440 												 &hash_ctl,
4441 									  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
4442 
4443 				/*
4444 				 * If requested, read the data from the database-specific
4445 				 * file.  Otherwise we just leave the hashtables empty.
4446 				 */
4447 				if (deep)
4448 					pgstat_read_db_statsfile(dbentry->databaseid,
4449 											 dbentry->tables,
4450 											 dbentry->functions,
4451 											 permanent);
4452 
4453 				break;
4454 
4455 			case 'E':
4456 				goto done;
4457 
4458 			default:
4459 				ereport(pgStatRunningInCollector ? LOG : WARNING,
4460 						(errmsg("corrupted statistics file \"%s\"",
4461 								statfile)));
4462 				goto done;
4463 		}
4464 	}
4465 
4466 done:
4467 	FreeFile(fpin);
4468 
4469 	/* If requested to read the permanent file, also get rid of it. */
4470 	if (permanent)
4471 	{
4472 		elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4473 		unlink(statfile);
4474 	}
4475 
4476 	return dbhash;
4477 }
4478 
4479 
4480 /* ----------
4481  * pgstat_read_db_statsfile() -
4482  *
4483  *	Reads in the existing statistics collector file for the given database,
4484  *	filling the passed-in tables and functions hash tables.
4485  *
4486  *	As in pgstat_read_statsfiles, if the permanent file is requested, it is
4487  *	removed after reading.
4488  *
4489  *	Note: this code has the ability to skip storing per-table or per-function
4490  *	data, if NULL is passed for the corresponding hashtable.  That's not used
4491  *	at the moment though.
4492  * ----------
4493  */
4494 static void
pgstat_read_db_statsfile(Oid databaseid,HTAB * tabhash,HTAB * funchash,bool permanent)4495 pgstat_read_db_statsfile(Oid databaseid, HTAB *tabhash, HTAB *funchash,
4496 						 bool permanent)
4497 {
4498 	PgStat_StatTabEntry *tabentry;
4499 	PgStat_StatTabEntry tabbuf;
4500 	PgStat_StatFuncEntry funcbuf;
4501 	PgStat_StatFuncEntry *funcentry;
4502 	FILE	   *fpin;
4503 	int32		format_id;
4504 	bool		found;
4505 	char		statfile[MAXPGPATH];
4506 
4507 	get_dbstat_filename(permanent, false, databaseid, statfile, MAXPGPATH);
4508 
4509 	/*
4510 	 * Try to open the stats file. If it doesn't exist, the backends simply
4511 	 * return zero for anything and the collector simply starts from scratch
4512 	 * with empty counters.
4513 	 *
4514 	 * ENOENT is a possibility if the stats collector is not running or has
4515 	 * not yet written the stats file the first time.  Any other failure
4516 	 * condition is suspicious.
4517 	 */
4518 	if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4519 	{
4520 		if (errno != ENOENT)
4521 			ereport(pgStatRunningInCollector ? LOG : WARNING,
4522 					(errcode_for_file_access(),
4523 					 errmsg("could not open statistics file \"%s\": %m",
4524 							statfile)));
4525 		return;
4526 	}
4527 
4528 	/*
4529 	 * Verify it's of the expected format.
4530 	 */
4531 	if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4532 		format_id != PGSTAT_FILE_FORMAT_ID)
4533 	{
4534 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4535 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4536 		goto done;
4537 	}
4538 
4539 	/*
4540 	 * We found an existing collector stats file. Read it and put all the
4541 	 * hashtable entries into place.
4542 	 */
4543 	for (;;)
4544 	{
4545 		switch (fgetc(fpin))
4546 		{
4547 				/*
4548 				 * 'T'	A PgStat_StatTabEntry follows.
4549 				 */
4550 			case 'T':
4551 				if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
4552 						  fpin) != sizeof(PgStat_StatTabEntry))
4553 				{
4554 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4555 							(errmsg("corrupted statistics file \"%s\"",
4556 									statfile)));
4557 					goto done;
4558 				}
4559 
4560 				/*
4561 				 * Skip if table data not wanted.
4562 				 */
4563 				if (tabhash == NULL)
4564 					break;
4565 
4566 				tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
4567 													(void *) &tabbuf.tableid,
4568 														 HASH_ENTER, &found);
4569 
4570 				if (found)
4571 				{
4572 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4573 							(errmsg("corrupted statistics file \"%s\"",
4574 									statfile)));
4575 					goto done;
4576 				}
4577 
4578 				memcpy(tabentry, &tabbuf, sizeof(tabbuf));
4579 				break;
4580 
4581 				/*
4582 				 * 'F'	A PgStat_StatFuncEntry follows.
4583 				 */
4584 			case 'F':
4585 				if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
4586 						  fpin) != sizeof(PgStat_StatFuncEntry))
4587 				{
4588 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4589 							(errmsg("corrupted statistics file \"%s\"",
4590 									statfile)));
4591 					goto done;
4592 				}
4593 
4594 				/*
4595 				 * Skip if function data not wanted.
4596 				 */
4597 				if (funchash == NULL)
4598 					break;
4599 
4600 				funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
4601 												(void *) &funcbuf.functionid,
4602 														 HASH_ENTER, &found);
4603 
4604 				if (found)
4605 				{
4606 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4607 							(errmsg("corrupted statistics file \"%s\"",
4608 									statfile)));
4609 					goto done;
4610 				}
4611 
4612 				memcpy(funcentry, &funcbuf, sizeof(funcbuf));
4613 				break;
4614 
4615 				/*
4616 				 * 'E'	The EOF marker of a complete stats file.
4617 				 */
4618 			case 'E':
4619 				goto done;
4620 
4621 			default:
4622 				ereport(pgStatRunningInCollector ? LOG : WARNING,
4623 						(errmsg("corrupted statistics file \"%s\"",
4624 								statfile)));
4625 				goto done;
4626 		}
4627 	}
4628 
4629 done:
4630 	FreeFile(fpin);
4631 
4632 	if (permanent)
4633 	{
4634 		elog(DEBUG2, "removing permanent stats file \"%s\"", statfile);
4635 		unlink(statfile);
4636 	}
4637 }
4638 
4639 /* ----------
4640  * pgstat_read_db_statsfile_timestamp() -
4641  *
4642  *	Attempt to determine the timestamp of the last db statfile write.
4643  *	Returns TRUE if successful; the timestamp is stored in *ts.
4644  *
4645  *	This needs to be careful about handling databases for which no stats file
4646  *	exists, such as databases without a stat entry or those not yet written:
4647  *
4648  *	- if there's a database entry in the global file, return the corresponding
4649  *	stats_timestamp value.
4650  *
4651  *	- if there's no db stat entry (e.g. for a new or inactive database),
4652  *	there's no stats_timestamp value, but also nothing to write so we return
4653  *	the timestamp of the global statfile.
4654  * ----------
4655  */
4656 static bool
pgstat_read_db_statsfile_timestamp(Oid databaseid,bool permanent,TimestampTz * ts)4657 pgstat_read_db_statsfile_timestamp(Oid databaseid, bool permanent,
4658 								   TimestampTz *ts)
4659 {
4660 	PgStat_StatDBEntry dbentry;
4661 	PgStat_GlobalStats myGlobalStats;
4662 	PgStat_ArchiverStats myArchiverStats;
4663 	FILE	   *fpin;
4664 	int32		format_id;
4665 	const char *statfile = permanent ? PGSTAT_STAT_PERMANENT_FILENAME : pgstat_stat_filename;
4666 
4667 	/*
4668 	 * Try to open the stats file.  As above, anything but ENOENT is worthy of
4669 	 * complaining about.
4670 	 */
4671 	if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
4672 	{
4673 		if (errno != ENOENT)
4674 			ereport(pgStatRunningInCollector ? LOG : WARNING,
4675 					(errcode_for_file_access(),
4676 					 errmsg("could not open statistics file \"%s\": %m",
4677 							statfile)));
4678 		return false;
4679 	}
4680 
4681 	/*
4682 	 * Verify it's of the expected format.
4683 	 */
4684 	if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id) ||
4685 		format_id != PGSTAT_FILE_FORMAT_ID)
4686 	{
4687 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4688 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4689 		FreeFile(fpin);
4690 		return false;
4691 	}
4692 
4693 	/*
4694 	 * Read global stats struct
4695 	 */
4696 	if (fread(&myGlobalStats, 1, sizeof(myGlobalStats),
4697 			  fpin) != sizeof(myGlobalStats))
4698 	{
4699 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4700 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4701 		FreeFile(fpin);
4702 		return false;
4703 	}
4704 
4705 	/*
4706 	 * Read archiver stats struct
4707 	 */
4708 	if (fread(&myArchiverStats, 1, sizeof(myArchiverStats),
4709 			  fpin) != sizeof(myArchiverStats))
4710 	{
4711 		ereport(pgStatRunningInCollector ? LOG : WARNING,
4712 				(errmsg("corrupted statistics file \"%s\"", statfile)));
4713 		FreeFile(fpin);
4714 		return false;
4715 	}
4716 
4717 	/* By default, we're going to return the timestamp of the global file. */
4718 	*ts = myGlobalStats.stats_timestamp;
4719 
4720 	/*
4721 	 * We found an existing collector stats file.  Read it and look for a
4722 	 * record for the requested database.  If found, use its timestamp.
4723 	 */
4724 	for (;;)
4725 	{
4726 		switch (fgetc(fpin))
4727 		{
4728 				/*
4729 				 * 'D'	A PgStat_StatDBEntry struct describing a database
4730 				 * follows.
4731 				 */
4732 			case 'D':
4733 				if (fread(&dbentry, 1, offsetof(PgStat_StatDBEntry, tables),
4734 						  fpin) != offsetof(PgStat_StatDBEntry, tables))
4735 				{
4736 					ereport(pgStatRunningInCollector ? LOG : WARNING,
4737 							(errmsg("corrupted statistics file \"%s\"",
4738 									statfile)));
4739 					goto done;
4740 				}
4741 
4742 				/*
4743 				 * If this is the DB we're looking for, save its timestamp and
4744 				 * we're done.
4745 				 */
4746 				if (dbentry.databaseid == databaseid)
4747 				{
4748 					*ts = dbentry.stats_timestamp;
4749 					goto done;
4750 				}
4751 
4752 				break;
4753 
4754 			case 'E':
4755 				goto done;
4756 
4757 			default:
4758 				ereport(pgStatRunningInCollector ? LOG : WARNING,
4759 						(errmsg("corrupted statistics file \"%s\"",
4760 								statfile)));
4761 				goto done;
4762 		}
4763 	}
4764 
4765 done:
4766 	FreeFile(fpin);
4767 	return true;
4768 }
4769 
4770 /*
4771  * If not already done, read the statistics collector stats file into
4772  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
4773  * is called (typically, at end of transaction).
4774  */
4775 static void
backend_read_statsfile(void)4776 backend_read_statsfile(void)
4777 {
4778 	TimestampTz min_ts = 0;
4779 	TimestampTz ref_ts = 0;
4780 	Oid			inquiry_db;
4781 	int			count;
4782 
4783 	/* already read it? */
4784 	if (pgStatDBHash)
4785 		return;
4786 	Assert(!pgStatRunningInCollector);
4787 
4788 	/*
4789 	 * In a normal backend, we check staleness of the data for our own DB, and
4790 	 * so we send MyDatabaseId in inquiry messages.  In the autovac launcher,
4791 	 * check staleness of the shared-catalog data, and send InvalidOid in
4792 	 * inquiry messages so as not to force writing unnecessary data.
4793 	 */
4794 	if (IsAutoVacuumLauncherProcess())
4795 		inquiry_db = InvalidOid;
4796 	else
4797 		inquiry_db = MyDatabaseId;
4798 
4799 	/*
4800 	 * Loop until fresh enough stats file is available or we ran out of time.
4801 	 * The stats inquiry message is sent repeatedly in case collector drops
4802 	 * it; but not every single time, as that just swamps the collector.
4803 	 */
4804 	for (count = 0; count < PGSTAT_POLL_LOOP_COUNT; count++)
4805 	{
4806 		bool		ok;
4807 		TimestampTz file_ts = 0;
4808 		TimestampTz cur_ts;
4809 
4810 		CHECK_FOR_INTERRUPTS();
4811 
4812 		ok = pgstat_read_db_statsfile_timestamp(inquiry_db, false, &file_ts);
4813 
4814 		cur_ts = GetCurrentTimestamp();
4815 		/* Calculate min acceptable timestamp, if we didn't already */
4816 		if (count == 0 || cur_ts < ref_ts)
4817 		{
4818 			/*
4819 			 * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL
4820 			 * msec before now.  This indirectly ensures that the collector
4821 			 * needn't write the file more often than PGSTAT_STAT_INTERVAL. In
4822 			 * an autovacuum worker, however, we want a lower delay to avoid
4823 			 * using stale data, so we use PGSTAT_RETRY_DELAY (since the
4824 			 * number of workers is low, this shouldn't be a problem).
4825 			 *
4826 			 * We don't recompute min_ts after sleeping, except in the
4827 			 * unlikely case that cur_ts went backwards.  So we might end up
4828 			 * accepting a file a bit older than PGSTAT_STAT_INTERVAL.  In
4829 			 * practice that shouldn't happen, though, as long as the sleep
4830 			 * time is less than PGSTAT_STAT_INTERVAL; and we don't want to
4831 			 * tell the collector that our cutoff time is less than what we'd
4832 			 * actually accept.
4833 			 */
4834 			ref_ts = cur_ts;
4835 			if (IsAutoVacuumWorkerProcess())
4836 				min_ts = TimestampTzPlusMilliseconds(ref_ts,
4837 													 -PGSTAT_RETRY_DELAY);
4838 			else
4839 				min_ts = TimestampTzPlusMilliseconds(ref_ts,
4840 													 -PGSTAT_STAT_INTERVAL);
4841 		}
4842 
4843 		/*
4844 		 * If the file timestamp is actually newer than cur_ts, we must have
4845 		 * had a clock glitch (system time went backwards) or there is clock
4846 		 * skew between our processor and the stats collector's processor.
4847 		 * Accept the file, but send an inquiry message anyway to make
4848 		 * pgstat_recv_inquiry do a sanity check on the collector's time.
4849 		 */
4850 		if (ok && file_ts > cur_ts)
4851 		{
4852 			/*
4853 			 * A small amount of clock skew between processors isn't terribly
4854 			 * surprising, but a large difference is worth logging.  We
4855 			 * arbitrarily define "large" as 1000 msec.
4856 			 */
4857 			if (file_ts >= TimestampTzPlusMilliseconds(cur_ts, 1000))
4858 			{
4859 				char	   *filetime;
4860 				char	   *mytime;
4861 
4862 				/* Copy because timestamptz_to_str returns a static buffer */
4863 				filetime = pstrdup(timestamptz_to_str(file_ts));
4864 				mytime = pstrdup(timestamptz_to_str(cur_ts));
4865 				elog(LOG, "stats collector's time %s is later than backend local time %s",
4866 					 filetime, mytime);
4867 				pfree(filetime);
4868 				pfree(mytime);
4869 			}
4870 
4871 			pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
4872 			break;
4873 		}
4874 
4875 		/* Normal acceptance case: file is not older than cutoff time */
4876 		if (ok && file_ts >= min_ts)
4877 			break;
4878 
4879 		/* Not there or too old, so kick the collector and wait a bit */
4880 		if ((count % PGSTAT_INQ_LOOP_COUNT) == 0)
4881 			pgstat_send_inquiry(cur_ts, min_ts, inquiry_db);
4882 
4883 		pg_usleep(PGSTAT_RETRY_DELAY * 1000L);
4884 	}
4885 
4886 	if (count >= PGSTAT_POLL_LOOP_COUNT)
4887 		ereport(LOG,
4888 				(errmsg("using stale statistics instead of current ones "
4889 						"because stats collector is not responding")));
4890 
4891 	/*
4892 	 * Autovacuum launcher wants stats about all databases, but a shallow read
4893 	 * is sufficient.  Regular backends want a deep read for just the tables
4894 	 * they can see (MyDatabaseId + shared catalogs).
4895 	 */
4896 	if (IsAutoVacuumLauncherProcess())
4897 		pgStatDBHash = pgstat_read_statsfiles(InvalidOid, false, false);
4898 	else
4899 		pgStatDBHash = pgstat_read_statsfiles(MyDatabaseId, false, true);
4900 }
4901 
4902 
4903 /* ----------
4904  * pgstat_setup_memcxt() -
4905  *
4906  *	Create pgStatLocalContext, if not already done.
4907  * ----------
4908  */
4909 static void
pgstat_setup_memcxt(void)4910 pgstat_setup_memcxt(void)
4911 {
4912 	if (!pgStatLocalContext)
4913 		pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
4914 												   "Statistics snapshot",
4915 												   ALLOCSET_SMALL_SIZES);
4916 }
4917 
4918 
4919 /* ----------
4920  * pgstat_clear_snapshot() -
4921  *
4922  *	Discard any data collected in the current transaction.  Any subsequent
4923  *	request will cause new snapshots to be read.
4924  *
4925  *	This is also invoked during transaction commit or abort to discard
4926  *	the no-longer-wanted snapshot.
4927  * ----------
4928  */
4929 void
pgstat_clear_snapshot(void)4930 pgstat_clear_snapshot(void)
4931 {
4932 	/* Release memory, if any was allocated */
4933 	if (pgStatLocalContext)
4934 		MemoryContextDelete(pgStatLocalContext);
4935 
4936 	/* Reset variables */
4937 	pgStatLocalContext = NULL;
4938 	pgStatDBHash = NULL;
4939 	localBackendStatusTable = NULL;
4940 	localNumBackends = 0;
4941 }
4942 
4943 
4944 /* ----------
4945  * pgstat_recv_inquiry() -
4946  *
4947  *	Process stat inquiry requests.
4948  * ----------
4949  */
4950 static void
pgstat_recv_inquiry(PgStat_MsgInquiry * msg,int len)4951 pgstat_recv_inquiry(PgStat_MsgInquiry *msg, int len)
4952 {
4953 	PgStat_StatDBEntry *dbentry;
4954 
4955 	elog(DEBUG2, "received inquiry for database %u", msg->databaseid);
4956 
4957 	/*
4958 	 * If there's already a write request for this DB, there's nothing to do.
4959 	 *
4960 	 * Note that if a request is found, we return early and skip the below
4961 	 * check for clock skew.  This is okay, since the only way for a DB
4962 	 * request to be present in the list is that we have been here since the
4963 	 * last write round.  It seems sufficient to check for clock skew once per
4964 	 * write round.
4965 	 */
4966 	if (list_member_oid(pending_write_requests, msg->databaseid))
4967 		return;
4968 
4969 	/*
4970 	 * Check to see if we last wrote this database at a time >= the requested
4971 	 * cutoff time.  If so, this is a stale request that was generated before
4972 	 * we updated the DB file, and we don't need to do so again.
4973 	 *
4974 	 * If the requestor's local clock time is older than stats_timestamp, we
4975 	 * should suspect a clock glitch, ie system time going backwards; though
4976 	 * the more likely explanation is just delayed message receipt.  It is
4977 	 * worth expending a GetCurrentTimestamp call to be sure, since a large
4978 	 * retreat in the system clock reading could otherwise cause us to neglect
4979 	 * to update the stats file for a long time.
4980 	 */
4981 	dbentry = pgstat_get_db_entry(msg->databaseid, false);
4982 	if (dbentry == NULL)
4983 	{
4984 		/*
4985 		 * We have no data for this DB.  Enter a write request anyway so that
4986 		 * the global stats will get updated.  This is needed to prevent
4987 		 * backend_read_statsfile from waiting for data that we cannot supply,
4988 		 * in the case of a new DB that nobody has yet reported any stats for.
4989 		 * See the behavior of pgstat_read_db_statsfile_timestamp.
4990 		 */
4991 	}
4992 	else if (msg->clock_time < dbentry->stats_timestamp)
4993 	{
4994 		TimestampTz cur_ts = GetCurrentTimestamp();
4995 
4996 		if (cur_ts < dbentry->stats_timestamp)
4997 		{
4998 			/*
4999 			 * Sure enough, time went backwards.  Force a new stats file write
5000 			 * to get back in sync; but first, log a complaint.
5001 			 */
5002 			char	   *writetime;
5003 			char	   *mytime;
5004 
5005 			/* Copy because timestamptz_to_str returns a static buffer */
5006 			writetime = pstrdup(timestamptz_to_str(dbentry->stats_timestamp));
5007 			mytime = pstrdup(timestamptz_to_str(cur_ts));
5008 			elog(LOG,
5009 				 "stats_timestamp %s is later than collector's time %s for database %u",
5010 				 writetime, mytime, dbentry->databaseid);
5011 			pfree(writetime);
5012 			pfree(mytime);
5013 		}
5014 		else
5015 		{
5016 			/*
5017 			 * Nope, it's just an old request.  Assuming msg's clock_time is
5018 			 * >= its cutoff_time, it must be stale, so we can ignore it.
5019 			 */
5020 			return;
5021 		}
5022 	}
5023 	else if (msg->cutoff_time <= dbentry->stats_timestamp)
5024 	{
5025 		/* Stale request, ignore it */
5026 		return;
5027 	}
5028 
5029 	/*
5030 	 * We need to write this DB, so create a request.
5031 	 */
5032 	pending_write_requests = lappend_oid(pending_write_requests,
5033 										 msg->databaseid);
5034 }
5035 
5036 
5037 /* ----------
5038  * pgstat_recv_tabstat() -
5039  *
5040  *	Count what the backend has done.
5041  * ----------
5042  */
5043 static void
pgstat_recv_tabstat(PgStat_MsgTabstat * msg,int len)5044 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
5045 {
5046 	PgStat_StatDBEntry *dbentry;
5047 	PgStat_StatTabEntry *tabentry;
5048 	int			i;
5049 	bool		found;
5050 
5051 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5052 
5053 	/*
5054 	 * Update database-wide stats.
5055 	 */
5056 	dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
5057 	dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
5058 	dbentry->n_block_read_time += msg->m_block_read_time;
5059 	dbentry->n_block_write_time += msg->m_block_write_time;
5060 
5061 	/*
5062 	 * Process all table entries in the message.
5063 	 */
5064 	for (i = 0; i < msg->m_nentries; i++)
5065 	{
5066 		PgStat_TableEntry *tabmsg = &(msg->m_entry[i]);
5067 
5068 		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
5069 													(void *) &(tabmsg->t_id),
5070 													   HASH_ENTER, &found);
5071 
5072 		if (!found)
5073 		{
5074 			/*
5075 			 * If it's a new table entry, initialize counters to the values we
5076 			 * just got.
5077 			 */
5078 			tabentry->numscans = tabmsg->t_counts.t_numscans;
5079 			tabentry->tuples_returned = tabmsg->t_counts.t_tuples_returned;
5080 			tabentry->tuples_fetched = tabmsg->t_counts.t_tuples_fetched;
5081 			tabentry->tuples_inserted = tabmsg->t_counts.t_tuples_inserted;
5082 			tabentry->tuples_updated = tabmsg->t_counts.t_tuples_updated;
5083 			tabentry->tuples_deleted = tabmsg->t_counts.t_tuples_deleted;
5084 			tabentry->tuples_hot_updated = tabmsg->t_counts.t_tuples_hot_updated;
5085 			tabentry->n_live_tuples = tabmsg->t_counts.t_delta_live_tuples;
5086 			tabentry->n_dead_tuples = tabmsg->t_counts.t_delta_dead_tuples;
5087 			tabentry->changes_since_analyze = tabmsg->t_counts.t_changed_tuples;
5088 			tabentry->blocks_fetched = tabmsg->t_counts.t_blocks_fetched;
5089 			tabentry->blocks_hit = tabmsg->t_counts.t_blocks_hit;
5090 
5091 			tabentry->vacuum_timestamp = 0;
5092 			tabentry->vacuum_count = 0;
5093 			tabentry->autovac_vacuum_timestamp = 0;
5094 			tabentry->autovac_vacuum_count = 0;
5095 			tabentry->analyze_timestamp = 0;
5096 			tabentry->analyze_count = 0;
5097 			tabentry->autovac_analyze_timestamp = 0;
5098 			tabentry->autovac_analyze_count = 0;
5099 		}
5100 		else
5101 		{
5102 			/*
5103 			 * Otherwise add the values to the existing entry.
5104 			 */
5105 			tabentry->numscans += tabmsg->t_counts.t_numscans;
5106 			tabentry->tuples_returned += tabmsg->t_counts.t_tuples_returned;
5107 			tabentry->tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5108 			tabentry->tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5109 			tabentry->tuples_updated += tabmsg->t_counts.t_tuples_updated;
5110 			tabentry->tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5111 			tabentry->tuples_hot_updated += tabmsg->t_counts.t_tuples_hot_updated;
5112 			/* If table was truncated, first reset the live/dead counters */
5113 			if (tabmsg->t_counts.t_truncated)
5114 			{
5115 				tabentry->n_live_tuples = 0;
5116 				tabentry->n_dead_tuples = 0;
5117 			}
5118 			tabentry->n_live_tuples += tabmsg->t_counts.t_delta_live_tuples;
5119 			tabentry->n_dead_tuples += tabmsg->t_counts.t_delta_dead_tuples;
5120 			tabentry->changes_since_analyze += tabmsg->t_counts.t_changed_tuples;
5121 			tabentry->blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5122 			tabentry->blocks_hit += tabmsg->t_counts.t_blocks_hit;
5123 		}
5124 
5125 		/* Clamp n_live_tuples in case of negative delta_live_tuples */
5126 		tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
5127 		/* Likewise for n_dead_tuples */
5128 		tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
5129 
5130 		/*
5131 		 * Add per-table stats to the per-database entry, too.
5132 		 */
5133 		dbentry->n_tuples_returned += tabmsg->t_counts.t_tuples_returned;
5134 		dbentry->n_tuples_fetched += tabmsg->t_counts.t_tuples_fetched;
5135 		dbentry->n_tuples_inserted += tabmsg->t_counts.t_tuples_inserted;
5136 		dbentry->n_tuples_updated += tabmsg->t_counts.t_tuples_updated;
5137 		dbentry->n_tuples_deleted += tabmsg->t_counts.t_tuples_deleted;
5138 		dbentry->n_blocks_fetched += tabmsg->t_counts.t_blocks_fetched;
5139 		dbentry->n_blocks_hit += tabmsg->t_counts.t_blocks_hit;
5140 	}
5141 }
5142 
5143 
5144 /* ----------
5145  * pgstat_recv_tabpurge() -
5146  *
5147  *	Arrange for dead table removal.
5148  * ----------
5149  */
5150 static void
pgstat_recv_tabpurge(PgStat_MsgTabpurge * msg,int len)5151 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
5152 {
5153 	PgStat_StatDBEntry *dbentry;
5154 	int			i;
5155 
5156 	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5157 
5158 	/*
5159 	 * No need to purge if we don't even know the database.
5160 	 */
5161 	if (!dbentry || !dbentry->tables)
5162 		return;
5163 
5164 	/*
5165 	 * Process all table entries in the message.
5166 	 */
5167 	for (i = 0; i < msg->m_nentries; i++)
5168 	{
5169 		/* Remove from hashtable if present; we don't care if it's not. */
5170 		(void) hash_search(dbentry->tables,
5171 						   (void *) &(msg->m_tableid[i]),
5172 						   HASH_REMOVE, NULL);
5173 	}
5174 }
5175 
5176 
5177 /* ----------
5178  * pgstat_recv_dropdb() -
5179  *
5180  *	Arrange for dead database removal
5181  * ----------
5182  */
5183 static void
pgstat_recv_dropdb(PgStat_MsgDropdb * msg,int len)5184 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
5185 {
5186 	Oid			dbid = msg->m_databaseid;
5187 	PgStat_StatDBEntry *dbentry;
5188 
5189 	/*
5190 	 * Lookup the database in the hashtable.
5191 	 */
5192 	dbentry = pgstat_get_db_entry(dbid, false);
5193 
5194 	/*
5195 	 * If found, remove it (along with the db statfile).
5196 	 */
5197 	if (dbentry)
5198 	{
5199 		char		statfile[MAXPGPATH];
5200 
5201 		get_dbstat_filename(false, false, dbid, statfile, MAXPGPATH);
5202 
5203 		elog(DEBUG2, "removing stats file \"%s\"", statfile);
5204 		unlink(statfile);
5205 
5206 		if (dbentry->tables != NULL)
5207 			hash_destroy(dbentry->tables);
5208 		if (dbentry->functions != NULL)
5209 			hash_destroy(dbentry->functions);
5210 
5211 		if (hash_search(pgStatDBHash,
5212 						(void *) &dbid,
5213 						HASH_REMOVE, NULL) == NULL)
5214 			ereport(ERROR,
5215 					(errmsg("database hash table corrupted during cleanup --- abort")));
5216 	}
5217 }
5218 
5219 
5220 /* ----------
5221  * pgstat_recv_resetcounter() -
5222  *
5223  *	Reset the statistics for the specified database.
5224  * ----------
5225  */
5226 static void
pgstat_recv_resetcounter(PgStat_MsgResetcounter * msg,int len)5227 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
5228 {
5229 	PgStat_StatDBEntry *dbentry;
5230 
5231 	/*
5232 	 * Lookup the database in the hashtable.  Nothing to do if not there.
5233 	 */
5234 	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5235 
5236 	if (!dbentry)
5237 		return;
5238 
5239 	/*
5240 	 * We simply throw away all the database's table entries by recreating a
5241 	 * new hash table for them.
5242 	 */
5243 	if (dbentry->tables != NULL)
5244 		hash_destroy(dbentry->tables);
5245 	if (dbentry->functions != NULL)
5246 		hash_destroy(dbentry->functions);
5247 
5248 	dbentry->tables = NULL;
5249 	dbentry->functions = NULL;
5250 
5251 	/*
5252 	 * Reset database-level stats, too.  This creates empty hash tables for
5253 	 * tables and functions.
5254 	 */
5255 	reset_dbentry_counters(dbentry);
5256 }
5257 
5258 /* ----------
5259  * pgstat_recv_resetshared() -
5260  *
5261  *	Reset some shared statistics of the cluster.
5262  * ----------
5263  */
5264 static void
pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter * msg,int len)5265 pgstat_recv_resetsharedcounter(PgStat_MsgResetsharedcounter *msg, int len)
5266 {
5267 	if (msg->m_resettarget == RESET_BGWRITER)
5268 	{
5269 		/* Reset the global background writer statistics for the cluster. */
5270 		memset(&globalStats, 0, sizeof(globalStats));
5271 		globalStats.stat_reset_timestamp = GetCurrentTimestamp();
5272 	}
5273 	else if (msg->m_resettarget == RESET_ARCHIVER)
5274 	{
5275 		/* Reset the archiver statistics for the cluster. */
5276 		memset(&archiverStats, 0, sizeof(archiverStats));
5277 		archiverStats.stat_reset_timestamp = GetCurrentTimestamp();
5278 	}
5279 
5280 	/*
5281 	 * Presumably the sender of this message validated the target, don't
5282 	 * complain here if it's not valid
5283 	 */
5284 }
5285 
5286 /* ----------
5287  * pgstat_recv_resetsinglecounter() -
5288  *
5289  *	Reset a statistics for a single object
5290  * ----------
5291  */
5292 static void
pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter * msg,int len)5293 pgstat_recv_resetsinglecounter(PgStat_MsgResetsinglecounter *msg, int len)
5294 {
5295 	PgStat_StatDBEntry *dbentry;
5296 
5297 	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5298 
5299 	if (!dbentry)
5300 		return;
5301 
5302 	/* Set the reset timestamp for the whole database */
5303 	dbentry->stat_reset_timestamp = GetCurrentTimestamp();
5304 
5305 	/* Remove object if it exists, ignore it if not */
5306 	if (msg->m_resettype == RESET_TABLE)
5307 		(void) hash_search(dbentry->tables, (void *) &(msg->m_objectid),
5308 						   HASH_REMOVE, NULL);
5309 	else if (msg->m_resettype == RESET_FUNCTION)
5310 		(void) hash_search(dbentry->functions, (void *) &(msg->m_objectid),
5311 						   HASH_REMOVE, NULL);
5312 }
5313 
5314 /* ----------
5315  * pgstat_recv_autovac() -
5316  *
5317  *	Process an autovacuum signalling message.
5318  * ----------
5319  */
5320 static void
pgstat_recv_autovac(PgStat_MsgAutovacStart * msg,int len)5321 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
5322 {
5323 	PgStat_StatDBEntry *dbentry;
5324 
5325 	/*
5326 	 * Store the last autovacuum time in the database's hashtable entry.
5327 	 */
5328 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5329 
5330 	dbentry->last_autovac_time = msg->m_start_time;
5331 }
5332 
5333 /* ----------
5334  * pgstat_recv_vacuum() -
5335  *
5336  *	Process a VACUUM message.
5337  * ----------
5338  */
5339 static void
pgstat_recv_vacuum(PgStat_MsgVacuum * msg,int len)5340 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
5341 {
5342 	PgStat_StatDBEntry *dbentry;
5343 	PgStat_StatTabEntry *tabentry;
5344 
5345 	/*
5346 	 * Store the data in the table's hashtable entry.
5347 	 */
5348 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5349 
5350 	tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
5351 
5352 	tabentry->n_live_tuples = msg->m_live_tuples;
5353 	tabentry->n_dead_tuples = msg->m_dead_tuples;
5354 
5355 	if (msg->m_autovacuum)
5356 	{
5357 		tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
5358 		tabentry->autovac_vacuum_count++;
5359 	}
5360 	else
5361 	{
5362 		tabentry->vacuum_timestamp = msg->m_vacuumtime;
5363 		tabentry->vacuum_count++;
5364 	}
5365 }
5366 
5367 /* ----------
5368  * pgstat_recv_analyze() -
5369  *
5370  *	Process an ANALYZE message.
5371  * ----------
5372  */
5373 static void
pgstat_recv_analyze(PgStat_MsgAnalyze * msg,int len)5374 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
5375 {
5376 	PgStat_StatDBEntry *dbentry;
5377 	PgStat_StatTabEntry *tabentry;
5378 
5379 	/*
5380 	 * Store the data in the table's hashtable entry.
5381 	 */
5382 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5383 
5384 	tabentry = pgstat_get_tab_entry(dbentry, msg->m_tableoid, true);
5385 
5386 	tabentry->n_live_tuples = msg->m_live_tuples;
5387 	tabentry->n_dead_tuples = msg->m_dead_tuples;
5388 
5389 	/*
5390 	 * If commanded, reset changes_since_analyze to zero.  This forgets any
5391 	 * changes that were committed while the ANALYZE was in progress, but we
5392 	 * have no good way to estimate how many of those there were.
5393 	 */
5394 	if (msg->m_resetcounter)
5395 		tabentry->changes_since_analyze = 0;
5396 
5397 	if (msg->m_autovacuum)
5398 	{
5399 		tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
5400 		tabentry->autovac_analyze_count++;
5401 	}
5402 	else
5403 	{
5404 		tabentry->analyze_timestamp = msg->m_analyzetime;
5405 		tabentry->analyze_count++;
5406 	}
5407 }
5408 
5409 
5410 /* ----------
5411  * pgstat_recv_archiver() -
5412  *
5413  *	Process a ARCHIVER message.
5414  * ----------
5415  */
5416 static void
pgstat_recv_archiver(PgStat_MsgArchiver * msg,int len)5417 pgstat_recv_archiver(PgStat_MsgArchiver *msg, int len)
5418 {
5419 	if (msg->m_failed)
5420 	{
5421 		/* Failed archival attempt */
5422 		++archiverStats.failed_count;
5423 		memcpy(archiverStats.last_failed_wal, msg->m_xlog,
5424 			   sizeof(archiverStats.last_failed_wal));
5425 		archiverStats.last_failed_timestamp = msg->m_timestamp;
5426 	}
5427 	else
5428 	{
5429 		/* Successful archival operation */
5430 		++archiverStats.archived_count;
5431 		memcpy(archiverStats.last_archived_wal, msg->m_xlog,
5432 			   sizeof(archiverStats.last_archived_wal));
5433 		archiverStats.last_archived_timestamp = msg->m_timestamp;
5434 	}
5435 }
5436 
5437 /* ----------
5438  * pgstat_recv_bgwriter() -
5439  *
5440  *	Process a BGWRITER message.
5441  * ----------
5442  */
5443 static void
pgstat_recv_bgwriter(PgStat_MsgBgWriter * msg,int len)5444 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
5445 {
5446 	globalStats.timed_checkpoints += msg->m_timed_checkpoints;
5447 	globalStats.requested_checkpoints += msg->m_requested_checkpoints;
5448 	globalStats.checkpoint_write_time += msg->m_checkpoint_write_time;
5449 	globalStats.checkpoint_sync_time += msg->m_checkpoint_sync_time;
5450 	globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
5451 	globalStats.buf_written_clean += msg->m_buf_written_clean;
5452 	globalStats.maxwritten_clean += msg->m_maxwritten_clean;
5453 	globalStats.buf_written_backend += msg->m_buf_written_backend;
5454 	globalStats.buf_fsync_backend += msg->m_buf_fsync_backend;
5455 	globalStats.buf_alloc += msg->m_buf_alloc;
5456 }
5457 
5458 /* ----------
5459  * pgstat_recv_recoveryconflict() -
5460  *
5461  *	Process a RECOVERYCONFLICT message.
5462  * ----------
5463  */
5464 static void
pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict * msg,int len)5465 pgstat_recv_recoveryconflict(PgStat_MsgRecoveryConflict *msg, int len)
5466 {
5467 	PgStat_StatDBEntry *dbentry;
5468 
5469 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5470 
5471 	switch (msg->m_reason)
5472 	{
5473 		case PROCSIG_RECOVERY_CONFLICT_DATABASE:
5474 
5475 			/*
5476 			 * Since we drop the information about the database as soon as it
5477 			 * replicates, there is no point in counting these conflicts.
5478 			 */
5479 			break;
5480 		case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
5481 			dbentry->n_conflict_tablespace++;
5482 			break;
5483 		case PROCSIG_RECOVERY_CONFLICT_LOCK:
5484 			dbentry->n_conflict_lock++;
5485 			break;
5486 		case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
5487 			dbentry->n_conflict_snapshot++;
5488 			break;
5489 		case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
5490 			dbentry->n_conflict_bufferpin++;
5491 			break;
5492 		case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
5493 			dbentry->n_conflict_startup_deadlock++;
5494 			break;
5495 	}
5496 }
5497 
5498 /* ----------
5499  * pgstat_recv_deadlock() -
5500  *
5501  *	Process a DEADLOCK message.
5502  * ----------
5503  */
5504 static void
pgstat_recv_deadlock(PgStat_MsgDeadlock * msg,int len)5505 pgstat_recv_deadlock(PgStat_MsgDeadlock *msg, int len)
5506 {
5507 	PgStat_StatDBEntry *dbentry;
5508 
5509 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5510 
5511 	dbentry->n_deadlocks++;
5512 }
5513 
5514 /* ----------
5515  * pgstat_recv_tempfile() -
5516  *
5517  *	Process a TEMPFILE message.
5518  * ----------
5519  */
5520 static void
pgstat_recv_tempfile(PgStat_MsgTempFile * msg,int len)5521 pgstat_recv_tempfile(PgStat_MsgTempFile *msg, int len)
5522 {
5523 	PgStat_StatDBEntry *dbentry;
5524 
5525 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5526 
5527 	dbentry->n_temp_bytes += msg->m_filesize;
5528 	dbentry->n_temp_files += 1;
5529 }
5530 
5531 /* ----------
5532  * pgstat_recv_funcstat() -
5533  *
5534  *	Count what the backend has done.
5535  * ----------
5536  */
5537 static void
pgstat_recv_funcstat(PgStat_MsgFuncstat * msg,int len)5538 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
5539 {
5540 	PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
5541 	PgStat_StatDBEntry *dbentry;
5542 	PgStat_StatFuncEntry *funcentry;
5543 	int			i;
5544 	bool		found;
5545 
5546 	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
5547 
5548 	/*
5549 	 * Process all function entries in the message.
5550 	 */
5551 	for (i = 0; i < msg->m_nentries; i++, funcmsg++)
5552 	{
5553 		funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
5554 												   (void *) &(funcmsg->f_id),
5555 														 HASH_ENTER, &found);
5556 
5557 		if (!found)
5558 		{
5559 			/*
5560 			 * If it's a new function entry, initialize counters to the values
5561 			 * we just got.
5562 			 */
5563 			funcentry->f_numcalls = funcmsg->f_numcalls;
5564 			funcentry->f_total_time = funcmsg->f_total_time;
5565 			funcentry->f_self_time = funcmsg->f_self_time;
5566 		}
5567 		else
5568 		{
5569 			/*
5570 			 * Otherwise add the values to the existing entry.
5571 			 */
5572 			funcentry->f_numcalls += funcmsg->f_numcalls;
5573 			funcentry->f_total_time += funcmsg->f_total_time;
5574 			funcentry->f_self_time += funcmsg->f_self_time;
5575 		}
5576 	}
5577 }
5578 
5579 /* ----------
5580  * pgstat_recv_funcpurge() -
5581  *
5582  *	Arrange for dead function removal.
5583  * ----------
5584  */
5585 static void
pgstat_recv_funcpurge(PgStat_MsgFuncpurge * msg,int len)5586 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
5587 {
5588 	PgStat_StatDBEntry *dbentry;
5589 	int			i;
5590 
5591 	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
5592 
5593 	/*
5594 	 * No need to purge if we don't even know the database.
5595 	 */
5596 	if (!dbentry || !dbentry->functions)
5597 		return;
5598 
5599 	/*
5600 	 * Process all function entries in the message.
5601 	 */
5602 	for (i = 0; i < msg->m_nentries; i++)
5603 	{
5604 		/* Remove from hashtable if present; we don't care if it's not. */
5605 		(void) hash_search(dbentry->functions,
5606 						   (void *) &(msg->m_functionid[i]),
5607 						   HASH_REMOVE, NULL);
5608 	}
5609 }
5610 
5611 /* ----------
5612  * pgstat_write_statsfile_needed() -
5613  *
5614  *	Do we need to write out any stats files?
5615  * ----------
5616  */
5617 static bool
pgstat_write_statsfile_needed(void)5618 pgstat_write_statsfile_needed(void)
5619 {
5620 	if (pending_write_requests != NIL)
5621 		return true;
5622 
5623 	/* Everything was written recently */
5624 	return false;
5625 }
5626 
5627 /* ----------
5628  * pgstat_db_requested() -
5629  *
5630  *	Checks whether stats for a particular DB need to be written to a file.
5631  * ----------
5632  */
5633 static bool
pgstat_db_requested(Oid databaseid)5634 pgstat_db_requested(Oid databaseid)
5635 {
5636 	/*
5637 	 * If any requests are outstanding at all, we should write the stats for
5638 	 * shared catalogs (the "database" with OID 0).  This ensures that
5639 	 * backends will see up-to-date stats for shared catalogs, even though
5640 	 * they send inquiry messages mentioning only their own DB.
5641 	 */
5642 	if (databaseid == InvalidOid && pending_write_requests != NIL)
5643 		return true;
5644 
5645 	/* Search to see if there's an open request to write this database. */
5646 	if (list_member_oid(pending_write_requests, databaseid))
5647 		return true;
5648 
5649 	return false;
5650 }
5651