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