pgstat.c 69.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/* ----------
 * pgstat.c
 *
 *	All the statistics collector stuff hacked up in one big, ugly file.
 *
 *	TODO:	- Separate collector, postmaster and backend stuff
 *			  into different files.
 *
 *			- Add some automatic call for pgstat vacuuming.
 *
 *			- 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-2006, PostgreSQL Global Development Group
15
 *
16
 *	$PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.131 2006/06/27 03:45:16 alvherre Exp $
17 18
 * ----------
 */
P
Peter Eisentraut 已提交
19 20
#include "postgres.h"

21 22 23 24 25
#include <unistd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
B
Bruce Momjian 已提交
26
#include <netdb.h>
27 28 29
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
30
#include <time.h>
31

32 33
#include "pgstat.h"

34
#include "access/heapam.h"
35
#include "access/xact.h"
36
#include "catalog/pg_database.h"
B
Bruce Momjian 已提交
37
#include "libpq/libpq.h"
38
#include "libpq/pqsignal.h"
39
#include "mb/pg_wchar.h"
40
#include "miscadmin.h"
41
#include "postmaster/autovacuum.h"
42
#include "postmaster/fork_process.h"
43
#include "postmaster/postmaster.h"
44
#include "storage/backendid.h"
45
#include "storage/fd.h"
46
#include "storage/ipc.h"
47
#include "storage/pg_shmem.h"
48
#include "storage/pmsignal.h"
49
#include "storage/procarray.h"
50
#include "tcop/tcopprot.h"
51
#include "utils/hsearch.h"
52
#include "utils/memutils.h"
53
#include "utils/ps_status.h"
54
#include "utils/rel.h"
55 56 57
#include "utils/syscache.h"


58
/* ----------
59
 * Paths for the statistics files (relative to installation's $PGDATA).
60 61
 * ----------
 */
62 63
#define PGSTAT_STAT_FILENAME	"global/pgstat.stat"
#define PGSTAT_STAT_TMPFILE		"global/pgstat.tmp"
64 65 66 67 68

/* ----------
 * Timer definitions.
 * ----------
 */
69 70
#define PGSTAT_STAT_INTERVAL	500		/* How often to write the status file;
										 * in milliseconds. */
71

72 73 74
#define PGSTAT_RESTART_INTERVAL 60		/* How often to attempt to restart a
										 * failed statistics collector; in
										 * seconds. */
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

/* ----------
 * Amount of space reserved in pgstat_recvbuffer().
 * ----------
 */
#define PGSTAT_RECVBUFFERSZ		((int) (1024 * sizeof(PgStat_Msg)))

/* ----------
 * The initial size hints for the hash tables used in the collector.
 * ----------
 */
#define PGSTAT_DB_HASH_SIZE		16
#define PGSTAT_TAB_HASH_SIZE	512


90
/* ----------
91
 * GUC parameters
92 93
 * ----------
 */
94
bool		pgstat_collect_startcollector = true;
95
bool		pgstat_collect_resetonpmstart = false;
96 97
bool		pgstat_collect_tuplelevel = false;
bool		pgstat_collect_blocklevel = false;
98
bool		pgstat_collect_querystring = false;
99 100 101 102 103

/* ----------
 * Local data
 * ----------
 */
B
Bruce Momjian 已提交
104
NON_EXEC_STATIC int pgStatSock = -1;
B
Bruce Momjian 已提交
105
NON_EXEC_STATIC int pgStatPipe[2] = {-1, -1};
106

B
Bruce Momjian 已提交
107
static struct sockaddr_storage pgStatAddr;
108

109
static pid_t pgStatCollectorPid = 0;
110

111
static time_t last_pgstat_start_time;
112

113
static bool pgStatRunningInCollector = false;
114

115 116 117 118 119 120 121
/*
 * Place where backends store per-table info to be sent to the collector.
 * We store shared relations separately from non-shared ones, to be able to
 * send them in separate messages.
 */
typedef struct TabStatArray
{
B
Bruce Momjian 已提交
122 123
	int			tsa_alloc;		/* num allocated */
	int			tsa_used;		/* num actually used */
124 125
	PgStat_MsgTabstat **tsa_messages;	/* the array itself */
} TabStatArray;
B
Bruce Momjian 已提交
126

127 128
#define TABSTAT_QUANTUM		4	/* we alloc this many at a time */

B
Bruce Momjian 已提交
129 130
static TabStatArray RegularTabStat = {0, 0, NULL};
static TabStatArray SharedTabStat = {0, 0, NULL};
131

132 133
static int	pgStatXactCommit = 0;
static int	pgStatXactRollback = 0;
134

135 136
static TransactionId pgStatDBHashXact = InvalidTransactionId;
static HTAB *pgStatDBHash = NULL;
137 138 139
static TransactionId pgStatLocalStatusXact = InvalidTransactionId;
static PgBackendStatus *localBackendStatusTable = NULL;
static int	localNumBackends = 0;
140

141
static volatile bool	need_statwrite;
142

143

144 145 146 147
/* ----------
 * Local function forward declarations
 * ----------
 */
148
#ifdef EXEC_BACKEND
149 150 151 152 153

typedef enum STATS_PROCESS_TYPE
{
	STAT_PROC_BUFFER,
	STAT_PROC_COLLECTOR
B
Bruce Momjian 已提交
154
}	STATS_PROCESS_TYPE;
155

156
static pid_t pgstat_forkexec(STATS_PROCESS_TYPE procType);
157
static void pgstat_parseArgs(int argc, char *argv[]);
158
#endif
159 160 161

NON_EXEC_STATIC void PgstatBufferMain(int argc, char *argv[]);
NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
162
static void force_statwrite(SIGNAL_ARGS);
163
static void pgstat_recvbuffer(void);
164
static void pgstat_exit(SIGNAL_ARGS);
165
static void pgstat_die(SIGNAL_ARGS);
166
static void pgstat_beshutdown_hook(int code, Datum arg);
167

168
static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
169 170
static void pgstat_drop_database(Oid databaseid);
static void pgstat_write_statsfile(void);
171
static void pgstat_read_statsfile(HTAB **dbhash, Oid onlydb);
172
static void backend_read_statsfile(void);
173
static void pgstat_read_current_status(void);
174

175
static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
176 177 178 179 180 181
static void pgstat_send(void *msg, int len);

static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
182 183 184
static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
185 186 187 188 189 190 191 192 193 194 195


/* ------------------------------------------------------------
 * Public functions called from postmaster follow
 * ------------------------------------------------------------
 */

/* ----------
 * pgstat_init() -
 *
 *	Called from postmaster at startup. Create the resources required
196 197 198
 *	by the statistics collector process.  If unable to do so, do not
 *	fail --- better to let the postmaster start with stats collection
 *	disabled.
199 200
 * ----------
 */
201
void
202 203
pgstat_init(void)
{
B
Bruce Momjian 已提交
204 205 206 207
	ACCEPT_TYPE_ARG3 alen;
	struct addrinfo *addrs = NULL,
			   *addr,
				hints;
B
Bruce Momjian 已提交
208
	int			ret;
B
Bruce Momjian 已提交
209
	fd_set		rset;
210
	struct timeval tv;
B
Bruce Momjian 已提交
211 212
	char		test_byte;
	int			sel_res;
213 214
	int			tries = 0;
	
215
#define TESTBYTEVAL ((char) 199)
216

217
	/*
218 219 220
	 * Force start of collector daemon if something to collect.  Note that
	 * pgstat_collect_querystring is now an independent facility that does
	 * not require the collector daemon.
221
	 */
222
	if (pgstat_collect_tuplelevel ||
223
		pgstat_collect_blocklevel)
224 225 226
		pgstat_collect_startcollector = true;

	/*
227
	 * If we don't have to start a collector or should reset the collected
228
	 * statistics on postmaster start, simply remove the stats file.
229 230
	 */
	if (!pgstat_collect_startcollector || pgstat_collect_resetonpmstart)
231
		pgstat_reset_all();
232 233 234 235 236

	/*
	 * Nothing else required if collector will not get started
	 */
	if (!pgstat_collect_startcollector)
237
		return;
238

239
	/*
240
	 * Create the UDP socket for sending and receiving statistic messages
241
	 */
B
Bruce Momjian 已提交
242 243 244 245 246 247 248 249
	hints.ai_flags = AI_PASSIVE;
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = 0;
	hints.ai_addrlen = 0;
	hints.ai_addr = NULL;
	hints.ai_canonname = NULL;
	hints.ai_next = NULL;
250
	ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
251
	if (ret || !addrs)
B
Bruce Momjian 已提交
252
	{
253
		ereport(LOG,
254
				(errmsg("could not resolve \"localhost\": %s",
255
						gai_strerror(ret))));
B
Bruce Momjian 已提交
256 257
		goto startup_failed;
	}
B
Bruce Momjian 已提交
258

259
	/*
260 261 262
	 * On some platforms, pg_getaddrinfo_all() may return multiple addresses
	 * only one of which will actually work (eg, both IPv6 and IPv4 addresses
	 * when kernel will reject IPv6).  Worse, the failure may occur at the
263
	 * bind() or perhaps even connect() stage.	So we must loop through the
264 265
	 * results till we find a working combination. We will generate LOG
	 * messages, but no error, for bogus combinations.
266
	 */
267 268 269 270 271 272 273
	for (addr = addrs; addr; addr = addr->ai_next)
	{
#ifdef HAVE_UNIX_SOCKETS
		/* Ignore AF_UNIX sockets, if any are returned. */
		if (addr->ai_family == AF_UNIX)
			continue;
#endif
B
Bruce Momjian 已提交
274

275 276 277 278
		if (++tries > 1)
			ereport(LOG,
				(errmsg("trying another address for the statistics collector")));
		
279 280 281 282 283 284 285
		/*
		 * Create the socket.
		 */
		if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
		{
			ereport(LOG,
					(errcode_for_socket_access(),
B
Bruce Momjian 已提交
286
			errmsg("could not create socket for statistics collector: %m")));
287 288 289 290
			continue;
		}

		/*
B
Bruce Momjian 已提交
291 292
		 * Bind it to a kernel assigned port on localhost and get the assigned
		 * port via getsockname().
293 294 295 296 297
		 */
		if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
		{
			ereport(LOG,
					(errcode_for_socket_access(),
B
Bruce Momjian 已提交
298
			  errmsg("could not bind socket for statistics collector: %m")));
299 300 301 302 303 304
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

		alen = sizeof(pgStatAddr);
B
Bruce Momjian 已提交
305
		if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
306 307 308 309 310 311 312 313 314 315
		{
			ereport(LOG,
					(errcode_for_socket_access(),
					 errmsg("could not get address of socket for statistics collector: %m")));
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

		/*
B
Bruce Momjian 已提交
316 317 318 319
		 * Connect the socket to its own address.  This saves a few cycles by
		 * not having to respecify the target address on every send. This also
		 * provides a kernel-level check that only packets from this same
		 * address will be received.
320
		 */
B
Bruce Momjian 已提交
321
		if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
322 323 324
		{
			ereport(LOG,
					(errcode_for_socket_access(),
B
Bruce Momjian 已提交
325
			errmsg("could not connect socket for statistics collector: %m")));
326 327 328 329
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}
B
Bruce Momjian 已提交
330

331
		/*
B
Bruce Momjian 已提交
332 333 334 335
		 * Try to send and receive a one-byte test message on the socket. This
		 * is to catch situations where the socket can be created but will not
		 * actually pass data (for instance, because kernel packet filtering
		 * rules prevent it).
336 337 338 339 340 341 342 343 344 345 346 347 348
		 */
		test_byte = TESTBYTEVAL;
		if (send(pgStatSock, &test_byte, 1, 0) != 1)
		{
			ereport(LOG,
					(errcode_for_socket_access(),
					 errmsg("could not send test message on socket for statistics collector: %m")));
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

		/*
B
Bruce Momjian 已提交
349 350 351
		 * There could possibly be a little delay before the message can be
		 * received.  We arbitrarily allow up to half a second before deciding
		 * it's broken.
352 353 354 355 356 357 358
		 */
		for (;;)				/* need a loop to handle EINTR */
		{
			FD_ZERO(&rset);
			FD_SET(pgStatSock, &rset);
			tv.tv_sec = 0;
			tv.tv_usec = 500000;
B
Bruce Momjian 已提交
359
			sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
360 361 362 363 364 365 366
			if (sel_res >= 0 || errno != EINTR)
				break;
		}
		if (sel_res < 0)
		{
			ereport(LOG,
					(errcode_for_socket_access(),
B
Bruce Momjian 已提交
367
					 errmsg("select() failed in statistics collector: %m")));
368 369 370 371 372 373 374
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}
		if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
		{
			/*
B
Bruce Momjian 已提交
375 376
			 * This is the case we actually think is likely, so take pains to
			 * give a specific message for it.
377 378 379 380
			 *
			 * errno will not be set meaningfully here, so don't use it.
			 */
			ereport(LOG,
381
					(errcode(ERRCODE_CONNECTION_FAILURE),
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
					 errmsg("test message did not get through on socket for statistics collector")));
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

		test_byte++;			/* just make sure variable is changed */

		if (recv(pgStatSock, &test_byte, 1, 0) != 1)
		{
			ereport(LOG,
					(errcode_for_socket_access(),
					 errmsg("could not receive test message on socket for statistics collector: %m")));
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

B
Bruce Momjian 已提交
400
		if (test_byte != TESTBYTEVAL)	/* strictly paranoia ... */
401 402
		{
			ereport(LOG,
403
					(errcode(ERRCODE_INTERNAL_ERROR),
404 405 406 407 408 409
					 errmsg("incorrect test message transmission on socket for statistics collector")));
			closesocket(pgStatSock);
			pgStatSock = -1;
			continue;
		}

410 411
		/* If we get here, we have a working socket */
		break;
412 413
	}

414 415
	/* Did we find a working address? */
	if (!addr || pgStatSock < 0)
416
		goto startup_failed;
417 418

	/*
B
Bruce Momjian 已提交
419 420 421 422
	 * Set the socket to non-blocking IO.  This ensures that if the collector
	 * falls behind (despite the buffering process), statistics messages will
	 * be discarded; backends won't block waiting to send messages to the
	 * collector.
423
	 */
424
	if (!pg_set_noblock(pgStatSock))
425
	{
426 427
		ereport(LOG,
				(errcode_for_socket_access(),
B
Bruce Momjian 已提交
428
				 errmsg("could not set statistics collector socket to nonblocking mode: %m")));
429
		goto startup_failed;
430 431
	}

432
	pg_freeaddrinfo_all(hints.ai_family, addrs);
433

434
	return;
435 436

startup_failed:
437
	ereport(LOG,
B
Bruce Momjian 已提交
438
	  (errmsg("disabling statistics collector for lack of working socket")));
439

440
	if (addrs)
441
		pg_freeaddrinfo_all(hints.ai_family, addrs);
B
Bruce Momjian 已提交
442

443
	if (pgStatSock >= 0)
444
		closesocket(pgStatSock);
445 446 447
	pgStatSock = -1;

	/* Adjust GUC variables to suppress useless activity */
448
	pgstat_collect_startcollector = false;
449 450
	pgstat_collect_tuplelevel = false;
	pgstat_collect_blocklevel = false;
451 452
}

453 454 455
/*
 * pgstat_reset_all() -
 *
B
Bruce Momjian 已提交
456
 * Remove the stats file.  This is used on server start if the
457 458 459 460 461 462 463 464
 * stats_reset_on_server_start feature is enabled, or if WAL
 * recovery is needed after a crash.
 */
void
pgstat_reset_all(void)
{
	unlink(PGSTAT_STAT_FILENAME);
}
465

466 467
#ifdef EXEC_BACKEND

468
/*
469
 * pgstat_forkexec() -
470
 *
471
 * Format up the arglist for, then fork and exec, statistics
472 473
 * (buffer and collector) processes
 */
474 475
static pid_t
pgstat_forkexec(STATS_PROCESS_TYPE procType)
476
{
B
Bruce Momjian 已提交
477 478 479 480 481
	char	   *av[10];
	int			ac = 0,
				bufc = 0,
				i;
	char		pgstatBuf[2][32];
482 483

	av[ac++] = "postgres";
484

485 486 487
	switch (procType)
	{
		case STAT_PROC_BUFFER:
488
			av[ac++] = "--forkbuf";
489 490 491
			break;

		case STAT_PROC_COLLECTOR:
492
			av[ac++] = "--forkcol";
493 494 495 496 497 498
			break;

		default:
			Assert(false);
	}

499 500 501 502 503
	av[ac++] = NULL;			/* filled in by postmaster_forkexec */

	/* postgres_exec_path is not passed by write_backend_variables */
	av[ac++] = postgres_exec_path;

504 505 506 507 508
	/* Add to the arg list */
	Assert(bufc <= lengthof(pgstatBuf));
	for (i = 0; i < bufc; i++)
		av[ac++] = pgstatBuf[i];

509 510
	av[ac] = NULL;
	Assert(ac < lengthof(av));
511

512
	return postmaster_forkexec(ac, av);
513 514 515
}


516
/*
517 518
 * pgstat_parseArgs() -
 *
519
 * Extract data from the arglist for exec'ed statistics
520 521 522
 * (buffer and collector) processes
 */
static void
523
pgstat_parseArgs(int argc, char *argv[])
524
{
525
	Assert(argc == 4);
526

527
	argc = 3;
B
Bruce Momjian 已提交
528
	StrNCpy(postgres_exec_path, argv[argc++], MAXPGPATH);
529
}
B
Bruce Momjian 已提交
530
#endif   /* EXEC_BACKEND */
531

532

533 534 535 536
/* ----------
 * pgstat_start() -
 *
 *	Called from postmaster at startup or after an existing collector
537
 *	died.  Attempt to fire up a fresh statistics collector.
538
 *
539 540
 *	Returns PID of child process, or 0 if fail.
 *
541
 *	Note: if fail, we will be called again from the postmaster main loop.
542 543
 * ----------
 */
544
int
545
pgstat_start(void)
546
{
547
	time_t		curtime;
548
	pid_t		pgStatPid;
549

550 551 552
	/*
	 * Do nothing if no collector needed
	 */
553 554
	if (!pgstat_collect_startcollector)
		return 0;
555

556
	/*
B
Bruce Momjian 已提交
557 558 559 560
	 * Do nothing if too soon since last collector start.  This is a safety
	 * valve to protect against continuous respawn attempts if the collector
	 * is dying immediately at launch.	Note that since we will be re-called
	 * from the postmaster main loop, we will get another chance later.
561 562 563 564
	 */
	curtime = time(NULL);
	if ((unsigned int) (curtime - last_pgstat_start_time) <
		(unsigned int) PGSTAT_RESTART_INTERVAL)
565
		return 0;
566 567 568 569
	last_pgstat_start_time = curtime;

	/*
	 * Check that the socket is there, else pgstat_init failed.
570 571 572
	 */
	if (pgStatSock < 0)
	{
573 574
		ereport(LOG,
				(errmsg("statistics collector startup skipped")));
B
Bruce Momjian 已提交
575

576 577 578 579 580
		/*
		 * We can only get here if someone tries to manually turn
		 * pgstat_collect_startcollector on after it had been off.
		 */
		pgstat_collect_startcollector = false;
581
		return 0;
582 583 584
	}

	/*
585
	 * Okay, fork off the collector.
586
	 */
587
#ifdef EXEC_BACKEND
588
	switch ((pgStatPid = pgstat_forkexec(STAT_PROC_BUFFER)))
589
#else
590
	switch ((pgStatPid = fork_process()))
591
#endif
592 593
	{
		case -1:
594 595
			ereport(LOG,
					(errmsg("could not fork statistics buffer: %m")));
596
			return 0;
597

598
#ifndef EXEC_BACKEND
599
		case 0:
600
			/* in postmaster child ... */
601
			/* Close the postmaster's sockets */
602
			ClosePostmasterPorts(false);
603

604 605 606
			/* Lose the postmaster's on-exit routines */
			on_exit_reset();

607 608 609
			/* Drop our connection to postmaster's shared memory, as well */
			PGSharedMemoryDetach();

610
			PgstatBufferMain(0, NULL);
611
			break;
612
#endif
613 614

		default:
615
			return (int) pgStatPid;
616 617
	}

618 619
	/* shouldn't get here */
	return 0;
620 621 622 623 624
}


/* ------------------------------------------------------------
 * Public functions used by backends follow
625
 *------------------------------------------------------------
626 627 628 629 630 631 632 633 634 635 636 637 638
 */


/* ----------
 * pgstat_report_tabstat() -
 *
 *	Called from tcop/postgres.c to send the so far collected
 *	per table access statistics to the collector.
 * ----------
 */
void
pgstat_report_tabstat(void)
{
639
	int			i;
640

641
	if (pgStatSock < 0 ||
642
		(!pgstat_collect_tuplelevel &&
643
		 !pgstat_collect_blocklevel))
644 645
	{
		/* Not reporting stats, so just flush whatever we have */
646 647
		RegularTabStat.tsa_used = 0;
		SharedTabStat.tsa_used = 0;
648
		return;
649
	}
650 651

	/*
652 653
	 * For each message buffer used during the last query set the header
	 * fields and send it out.
654
	 */
655
	for (i = 0; i < RegularTabStat.tsa_used; i++)
656
	{
657
		PgStat_MsgTabstat *tsmsg = RegularTabStat.tsa_messages[i];
658 659 660 661
		int			n;
		int			len;

		n = tsmsg->m_nentries;
662 663
		len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
			n * sizeof(PgStat_TableEntry);
664

665 666
		tsmsg->m_xact_commit = pgStatXactCommit;
		tsmsg->m_xact_rollback = pgStatXactRollback;
667
		pgStatXactCommit = 0;
668 669
		pgStatXactRollback = 0;

670
		pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
671
		tsmsg->m_databaseid = MyDatabaseId;
672
		pgstat_send(tsmsg, len);
673
	}
674 675 676 677 678 679 680 681 682 683 684 685
	RegularTabStat.tsa_used = 0;

	/* Ditto, for shared relations */
	for (i = 0; i < SharedTabStat.tsa_used; i++)
	{
		PgStat_MsgTabstat *tsmsg = SharedTabStat.tsa_messages[i];
		int			n;
		int			len;

		n = tsmsg->m_nentries;
		len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
			n * sizeof(PgStat_TableEntry);
686

687 688 689 690 691 692 693 694 695
		/* We don't report transaction commit/abort here */
		tsmsg->m_xact_commit = 0;
		tsmsg->m_xact_rollback = 0;

		pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
		tsmsg->m_databaseid = InvalidOid;
		pgstat_send(tsmsg, len);
	}
	SharedTabStat.tsa_used = 0;
696 697 698 699 700 701 702 703 704
}


/* ----------
 * pgstat_vacuum_tabstat() -
 *
 *	Will tell the collector about objects he can get rid of.
 * ----------
 */
705
void
706 707
pgstat_vacuum_tabstat(void)
{
708 709 710 711 712
	List	   *oidlist;
	Relation	rel;
	HeapScanDesc scan;
	HeapTuple	tup;
	PgStat_MsgTabpurge msg;
713 714 715 716
	HASH_SEQ_STATUS hstat;
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;
	int			len;
717 718

	if (pgStatSock < 0)
719
		return;
720 721

	/*
B
Bruce Momjian 已提交
722 723
	 * If not done for this transaction, read the statistics collector stats
	 * file into some hash tables.
724
	 */
725
	backend_read_statsfile();
726 727

	/*
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	 * Read pg_database and make a list of OIDs of all existing databases
	 */
	oidlist = NIL;
	rel = heap_open(DatabaseRelationId, AccessShareLock);
	scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
	while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
	{
		oidlist = lappend_oid(oidlist, HeapTupleGetOid(tup));
	}
	heap_endscan(scan);
	heap_close(rel, AccessShareLock);

	/*
	 * Search the database hash table for dead databases and tell the
	 * collector to drop them.
	 */
	hash_seq_init(&hstat, pgStatDBHash);
	while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
	{
		Oid			dbid = dbentry->databaseid;

		if (!list_member_oid(oidlist, dbid))
			pgstat_drop_database(dbid);
	}

	/* Clean up */
	list_free(oidlist);

	/*
	 * Lookup our own database entry; if not found, nothing more to do.
758
	 */
759 760 761
	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
												 (void *) &MyDatabaseId,
												 HASH_FIND, NULL);
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
	if (dbentry == NULL || dbentry->tables == NULL)
		return;

	/*
	 * Similarly to above, make a list of all known relations in this DB.
	 */
	oidlist = NIL;
	rel = heap_open(RelationRelationId, AccessShareLock);
	scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
	while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
	{
		oidlist = lappend_oid(oidlist, HeapTupleGetOid(tup));
	}
	heap_endscan(scan);
	heap_close(rel, AccessShareLock);
777 778 779 780 781 782 783

	/*
	 * Initialize our messages table counter to zero
	 */
	msg.m_nentries = 0;

	/*
784
	 * Check for all tables listed in stats hashtable if they still exist.
785
	 */
786
	hash_seq_init(&hstat, dbentry->tables);
787
	while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
788
	{
789
		if (list_member_oid(oidlist, tabentry->tableid))
790 791 792
			continue;

		/*
793
		 * Not there, so add this table's Oid to the message
794 795 796 797
		 */
		msg.m_tableid[msg.m_nentries++] = tabentry->tableid;

		/*
798
		 * If the message is full, send it out and reinitialize to empty
799 800 801
		 */
		if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
		{
802
			len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
B
Bruce Momjian 已提交
803
				+msg.m_nentries * sizeof(Oid);
804 805

			pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
806
			msg.m_databaseid = MyDatabaseId;
807 808 809 810 811 812 813 814 815 816 817
			pgstat_send(&msg, len);

			msg.m_nentries = 0;
		}
	}

	/*
	 * Send the rest
	 */
	if (msg.m_nentries > 0)
	{
818
		len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
B
Bruce Momjian 已提交
819
			+msg.m_nentries * sizeof(Oid);
820 821

		pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
822
		msg.m_databaseid = MyDatabaseId;
823 824 825
		pgstat_send(&msg, len);
	}

826 827
	/* Clean up */
	list_free(oidlist);
828 829 830 831 832 833 834
}


/* ----------
 * pgstat_drop_database() -
 *
 *	Tell the collector that we just dropped a database.
835 836
 *	(If the message gets lost, we will still clean the dead DB eventually
 *	via future invocations of pgstat_vacuum_tabstat().)
837 838 839 840 841
 * ----------
 */
static void
pgstat_drop_database(Oid databaseid)
{
842
	PgStat_MsgDropdb msg;
843 844 845 846 847

	if (pgStatSock < 0)
		return;

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
848
	msg.m_databaseid = databaseid;
849 850 851 852
	pgstat_send(&msg, sizeof(msg));
}


853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
/* ----------
 * pgstat_drop_relation() -
 *
 *	Tell the collector that we just dropped a relation.
 *	(If the message gets lost, we will still clean the dead entry eventually
 *	via future invocations of pgstat_vacuum_tabstat().)
 * ----------
 */
void
pgstat_drop_relation(Oid relid)
{
	PgStat_MsgTabpurge msg;
	int			len;

	if (pgStatSock < 0)
		return;

	msg.m_tableid[0] = relid;
	msg.m_nentries = 1;

	len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) + sizeof(Oid);

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
	msg.m_databaseid = MyDatabaseId;
	pgstat_send(&msg, len);
}


881 882 883 884 885 886 887 888 889
/* ----------
 * pgstat_reset_counters() -
 *
 *	Tell the statistics collector to reset counters for our database.
 * ----------
 */
void
pgstat_reset_counters(void)
{
890
	PgStat_MsgResetcounter msg;
891 892 893 894 895

	if (pgStatSock < 0)
		return;

	if (!superuser())
896 897
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
898
				 errmsg("must be superuser to reset statistics counters")));
899 900

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
901
	msg.m_databaseid = MyDatabaseId;
902 903 904 905
	pgstat_send(&msg, sizeof(msg));
}


906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
/* ----------
 * pgstat_report_autovac() -
 *
 *	Called from autovacuum.c to report startup of an autovacuum process.
 *	We are called before InitPostgres is done, so can't rely on MyDatabaseId;
 *	the db OID must be passed in, instead.
 * ----------
 */
void
pgstat_report_autovac(Oid dboid)
{
	PgStat_MsgAutovacStart msg;

	if (pgStatSock < 0)
		return;

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
	msg.m_databaseid = dboid;
	msg.m_start_time = GetCurrentTimestamp();

	pgstat_send(&msg, sizeof(msg));
}


/* ---------
 * pgstat_report_vacuum() -
 *
 *	Tell the collector about the table we just vacuumed.
 * ---------
 */
void
pgstat_report_vacuum(Oid tableoid, bool shared,
					 bool analyze, PgStat_Counter tuples)
{
	PgStat_MsgVacuum msg;

	if (pgStatSock < 0 ||
		!pgstat_collect_tuplelevel)
		return;

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
	msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
	msg.m_tableoid = tableoid;
	msg.m_analyze = analyze;
	msg.m_autovacuum = IsAutoVacuumProcess(); /* is this autovacuum? */
	msg.m_vacuumtime = GetCurrentTimestamp();
	msg.m_tuples = tuples;
	pgstat_send(&msg, sizeof(msg));
}

/* --------
 * pgstat_report_analyze() -
 *
 *	Tell the collector about the table we just analyzed.
 * --------
 */
void
pgstat_report_analyze(Oid tableoid, bool shared, PgStat_Counter livetuples,
					  PgStat_Counter deadtuples)
{
	PgStat_MsgAnalyze msg;

	if (pgStatSock < 0 ||
		!pgstat_collect_tuplelevel)
		return;

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
	msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
	msg.m_tableoid = tableoid;
	msg.m_autovacuum = IsAutoVacuumProcess(); /* is this autovacuum? */
	msg.m_analyzetime = GetCurrentTimestamp();
	msg.m_live_tuples = livetuples;
	msg.m_dead_tuples = deadtuples;
	pgstat_send(&msg, sizeof(msg));
}


983 984 985 986 987 988 989 990 991
/* ----------
 * pgstat_ping() -
 *
 *	Send some junk data to the collector to increase traffic.
 * ----------
 */
void
pgstat_ping(void)
{
992
	PgStat_MsgDummy msg;
993 994 995 996 997 998 999 1000

	if (pgStatSock < 0)
		return;

	pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
	pgstat_send(&msg, sizeof(msg));
}

1001
/*
1002
 * Enlarge a TabStatArray
1003
 */
1004
static void
1005
more_tabstat_space(TabStatArray *tsarr)
1006 1007 1008
{
	PgStat_MsgTabstat *newMessages;
	PgStat_MsgTabstat **msgArray;
1009
	int			newAlloc;
1010 1011
	int			i;

1012 1013 1014 1015
	AssertArg(PointerIsValid(tsarr));

	newAlloc = tsarr->tsa_alloc + TABSTAT_QUANTUM;

1016 1017
	/* Create (another) quantum of message buffers */
	newMessages = (PgStat_MsgTabstat *)
1018 1019
		MemoryContextAllocZero(TopMemoryContext,
							   sizeof(PgStat_MsgTabstat) * TABSTAT_QUANTUM);
1020 1021

	/* Create or enlarge the pointer array */
1022
	if (tsarr->tsa_messages == NULL)
1023
		msgArray = (PgStat_MsgTabstat **)
1024 1025
			MemoryContextAlloc(TopMemoryContext,
							   sizeof(PgStat_MsgTabstat *) * newAlloc);
1026 1027
	else
		msgArray = (PgStat_MsgTabstat **)
1028
			repalloc(tsarr->tsa_messages,
1029
					 sizeof(PgStat_MsgTabstat *) * newAlloc);
1030 1031

	for (i = 0; i < TABSTAT_QUANTUM; i++)
1032 1033 1034
		msgArray[tsarr->tsa_alloc + i] = newMessages++;
	tsarr->tsa_messages = msgArray;
	tsarr->tsa_alloc = newAlloc;
1035

1036
	Assert(tsarr->tsa_used < tsarr->tsa_alloc);
1037
}
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

/* ----------
 * pgstat_initstats() -
 *
 *	Called from various places usually dealing with initialization
 *	of Relation or Scan structures. The data placed into these
 *	structures from here tell where later to count for buffer reads,
 *	scans and tuples fetched.
 * ----------
 */
void
pgstat_initstats(PgStat_Info *stats, Relation rel)
{
1051
	Oid			rel_id = rel->rd_id;
1052
	PgStat_TableEntry *useent;
B
Bruce Momjian 已提交
1053
	TabStatArray *tsarr;
1054
	PgStat_MsgTabstat *tsmsg;
1055 1056
	int			mb;
	int			i;
1057 1058 1059 1060

	/*
	 * Initialize data not to count at all.
	 */
1061
	stats->tabentry = NULL;
1062

1063 1064 1065
	if (pgStatSock < 0 ||
		!(pgstat_collect_tuplelevel ||
		  pgstat_collect_blocklevel))
1066 1067
		return;

1068 1069
	tsarr = rel->rd_rel->relisshared ? &SharedTabStat : &RegularTabStat;

1070
	/*
1071
	 * Search the already-used message slots for this relation.
1072
	 */
1073
	for (mb = 0; mb < tsarr->tsa_used; mb++)
1074
	{
1075
		tsmsg = tsarr->tsa_messages[mb];
1076

B
Bruce Momjian 已提交
1077
		for (i = tsmsg->m_nentries; --i >= 0;)
1078
		{
1079
			if (tsmsg->m_entry[i].t_id == rel_id)
1080
			{
1081
				stats->tabentry = (void *) &(tsmsg->m_entry[i]);
1082 1083 1084 1085
				return;
			}
		}

1086
		if (tsmsg->m_nentries >= PGSTAT_NUM_TABENTRIES)
1087
			continue;
1088

1089
		/*
B
Bruce Momjian 已提交
1090 1091
		 * Not found, but found a message buffer with an empty slot instead.
		 * Fine, let's use this one.
1092
		 */
1093 1094
		i = tsmsg->m_nentries++;
		useent = &tsmsg->m_entry[i];
1095
		MemSet(useent, 0, sizeof(PgStat_TableEntry));
1096
		useent->t_id = rel_id;
1097
		stats->tabentry = (void *) useent;
1098 1099 1100 1101 1102 1103
		return;
	}

	/*
	 * If we ran out of message buffers, we just allocate more.
	 */
1104 1105
	if (tsarr->tsa_used >= tsarr->tsa_alloc)
		more_tabstat_space(tsarr);
1106 1107 1108 1109

	/*
	 * Use the first entry of the next message buffer.
	 */
1110 1111
	mb = tsarr->tsa_used++;
	tsmsg = tsarr->tsa_messages[mb];
1112 1113
	tsmsg->m_nentries = 1;
	useent = &tsmsg->m_entry[0];
1114
	MemSet(useent, 0, sizeof(PgStat_TableEntry));
1115
	useent->t_id = rel_id;
1116
	stats->tabentry = (void *) useent;
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
}


/* ----------
 * pgstat_count_xact_commit() -
 *
 *	Called from access/transam/xact.c to count transaction commits.
 * ----------
 */
void
pgstat_count_xact_commit(void)
{
1129
	if	(!pgstat_collect_tuplelevel &&
1130
		 !pgstat_collect_blocklevel)
1131 1132
		return;

1133 1134 1135
	pgStatXactCommit++;

	/*
B
Bruce Momjian 已提交
1136 1137 1138
	 * If there was no relation activity yet, just make one existing message
	 * buffer used without slots, causing the next report to tell new
	 * xact-counters.
1139
	 */
1140 1141
	if (RegularTabStat.tsa_alloc == 0)
		more_tabstat_space(&RegularTabStat);
1142

1143
	if (RegularTabStat.tsa_used == 0)
1144
	{
1145 1146
		RegularTabStat.tsa_used++;
		RegularTabStat.tsa_messages[0]->m_nentries = 0;
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	}
}


/* ----------
 * pgstat_count_xact_rollback() -
 *
 *	Called from access/transam/xact.c to count transaction rollbacks.
 * ----------
 */
void
pgstat_count_xact_rollback(void)
{
1160
	if	(!pgstat_collect_tuplelevel &&
1161
		 !pgstat_collect_blocklevel)
1162 1163
		return;

1164 1165 1166
	pgStatXactRollback++;

	/*
B
Bruce Momjian 已提交
1167 1168 1169
	 * If there was no relation activity yet, just make one existing message
	 * buffer used without slots, causing the next report to tell new
	 * xact-counters.
1170
	 */
1171 1172
	if (RegularTabStat.tsa_alloc == 0)
		more_tabstat_space(&RegularTabStat);
1173

1174
	if (RegularTabStat.tsa_used == 0)
1175
	{
1176 1177
		RegularTabStat.tsa_used++;
		RegularTabStat.tsa_messages[0]->m_nentries = 0;
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	}
}


/* ----------
 * pgstat_fetch_stat_dbentry() -
 *
 *	Support function for the SQL-callable pgstat* functions. Returns
 *	the collected statistics for one database or NULL. NULL doesn't mean
 *	that the database doesn't exist, it is just not yet known by the
 *	collector, so the caller is better off to report ZERO instead.
 * ----------
 */
PgStat_StatDBEntry *
pgstat_fetch_stat_dbentry(Oid dbid)
{
	/*
B
Bruce Momjian 已提交
1195 1196
	 * If not done for this transaction, read the statistics collector stats
	 * file into some hash tables.
1197
	 */
1198
	backend_read_statsfile();
1199 1200

	/*
1201
	 * Lookup the requested database; return NULL if not found
1202
	 */
1203 1204 1205
	return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
											  (void *) &dbid,
											  HASH_FIND, NULL);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
}


/* ----------
 * pgstat_fetch_stat_tabentry() -
 *
 *	Support function for the SQL-callable pgstat* functions. Returns
 *	the collected statistics for one table or NULL. NULL doesn't mean
 *	that the table doesn't exist, it is just not yet known by the
 *	collector, so the caller is better off to report ZERO instead.
 * ----------
 */
PgStat_StatTabEntry *
pgstat_fetch_stat_tabentry(Oid relid)
{
1221
	Oid			dbid;
1222 1223
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;
1224 1225

	/*
B
Bruce Momjian 已提交
1226 1227
	 * If not done for this transaction, read the statistics collector stats
	 * file into some hash tables.
1228
	 */
1229
	backend_read_statsfile();
1230 1231

	/*
1232
	 * Lookup our database, then look in its table hash table.
1233
	 */
1234
	dbid = MyDatabaseId;
1235
	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1236
												 (void *) &dbid,
1237
												 HASH_FIND, NULL);
1238 1239 1240 1241 1242 1243 1244 1245
	if (dbentry != NULL && dbentry->tables != NULL)
	{
		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
													   (void *) &relid,
													   HASH_FIND, NULL);
		if (tabentry)
			return tabentry;
	}
1246 1247

	/*
1248
	 * If we didn't find it, maybe it's a shared table.
1249
	 */
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	dbid = InvalidOid;
	dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
												 (void *) &dbid,
												 HASH_FIND, NULL);
	if (dbentry != NULL && dbentry->tables != NULL)
	{
		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
													   (void *) &relid,
													   HASH_FIND, NULL);
		if (tabentry)
			return tabentry;
	}
1262

1263
	return NULL;
1264 1265 1266 1267 1268 1269 1270
}


/* ----------
 * pgstat_fetch_stat_beentry() -
 *
 *	Support function for the SQL-callable pgstat* functions. Returns
1271 1272 1273 1274
 *	our local copy of the current-activity entry for one backend.
 *
 *	NB: caller is responsible for a check if the user is permitted to see
 *	this info (especially the querystring).
1275 1276
 * ----------
 */
1277
PgBackendStatus *
1278 1279
pgstat_fetch_stat_beentry(int beid)
{
1280
	pgstat_read_current_status();
1281

1282
	if (beid < 1 || beid > localNumBackends)
1283 1284
		return NULL;

1285
	return &localBackendStatusTable[beid - 1];
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
}


/* ----------
 * pgstat_fetch_stat_numbackends() -
 *
 *	Support function for the SQL-callable pgstat* functions. Returns
 *	the maximum current backend id.
 * ----------
 */
int
pgstat_fetch_stat_numbackends(void)
{
1299
	pgstat_read_current_status();
1300

1301
	return localNumBackends;
1302 1303 1304 1305
}


/* ------------------------------------------------------------
1306
 * Functions for management of the shared-memory PgBackendStatus array
1307 1308 1309
 * ------------------------------------------------------------
 */

1310 1311
static PgBackendStatus *BackendStatusArray = NULL;
static PgBackendStatus *MyBEEntry = NULL;
1312

1313 1314 1315

/*
 * Report shared-memory space needed by CreateSharedBackendStatus.
1316
 */
1317 1318
Size
BackendStatusShmemSize(void)
1319
{
1320
	Size		size;
1321

1322 1323 1324
	size = mul_size(sizeof(PgBackendStatus), MaxBackends);
	return size;
}
1325

1326 1327
/*
 * Initialize the shared status array during postmaster startup.
1328
 */
1329 1330
void
CreateSharedBackendStatus(void)
1331
{
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	Size		size = BackendStatusShmemSize();
	bool		found;

	/* Create or attach to the shared array */
	BackendStatusArray = (PgBackendStatus *)
		ShmemInitStruct("Backend Status Array", size, &found);

	if (!found)
	{
		/*
		 * We're the first - initialize.
		 */
		MemSet(BackendStatusArray, 0, size);
	}
}


/* ----------
 * pgstat_bestart() -
 *
 *	Initialize this backend's entry in the PgBackendStatus array,
 *	and set up an on-proc-exit hook that will clear it again.
 *	Called from InitPostgres.  MyBackendId and MyDatabaseId must be set.
 * ----------
 */
void
pgstat_bestart(void)
{
	volatile PgBackendStatus *beentry;
	TimestampTz proc_start_timestamp;
	Oid			userid;
	SockAddr	clientaddr;

	Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
	MyBEEntry = &BackendStatusArray[MyBackendId - 1];

	/*
	 * To minimize the time spent modifying the entry, fetch all the
	 * needed data first.
1371 1372 1373
	 *
	 * If we have a MyProcPort, use its session start time (for consistency,
	 * and to save a kernel call).
1374
	 */
1375 1376 1377 1378
	if (MyProcPort)
		proc_start_timestamp = MyProcPort->SessionStartTime;
	else
		proc_start_timestamp = GetCurrentTimestamp();
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	userid = GetSessionUserId();

	/*
	 * We may not have a MyProcPort (eg, if this is the autovacuum process).
	 * If so, use all-zeroes client address, which is dealt with specially in
	 * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
	 */
	if (MyProcPort)
		memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
	else
		MemSet(&clientaddr, 0, sizeof(clientaddr));

	/*
	 * Initialize my status entry, following the protocol of bumping
	 * st_changecount before and after; and make sure it's even afterwards.
	 * We use a volatile pointer here to ensure the compiler doesn't try to
	 * get cute.
	 */
	beentry = MyBEEntry;
	do {
		beentry->st_changecount++;
	} while ((beentry->st_changecount & 1) == 0);

	beentry->st_procpid = MyProcPid;
	beentry->st_proc_start_timestamp = proc_start_timestamp;
	beentry->st_activity_start_timestamp = 0;
	beentry->st_databaseid = MyDatabaseId;
	beentry->st_userid = userid;
	beentry->st_clientaddr = clientaddr;
	beentry->st_activity[0] = '\0';
	/* Also make sure the last byte in the string area is always 0 */
	beentry->st_activity[PGBE_ACTIVITY_SIZE - 1] = '\0';

	beentry->st_changecount++;
	Assert((beentry->st_changecount & 1) == 0);

	/*
	 * Set up a process-exit hook to clean up.
	 */
	on_shmem_exit(pgstat_beshutdown_hook, 0);
}

/*
 * Shut down a single backend's statistics reporting at process exit.
 *
 * Flush any remaining statistics counts out to the collector.
 * Without this, operations triggered during backend exit (such as
 * temp table deletions) won't be counted.
 *
 * Lastly, clear out our entry in the PgBackendStatus array.
 */
static void
pgstat_beshutdown_hook(int code, Datum arg)
{
	volatile PgBackendStatus *beentry;

	pgstat_report_tabstat();

	/*
	 * Clear my status entry, following the protocol of bumping
	 * st_changecount before and after.  We use a volatile pointer here
	 * to ensure the compiler doesn't try to get cute.
	 */
	beentry = MyBEEntry;
	beentry->st_changecount++;

	beentry->st_procpid = 0;	/* mark invalid */

	beentry->st_changecount++;
	Assert((beentry->st_changecount & 1) == 0);
}


/* ----------
 * pgstat_report_activity() -
 *
 *	Called from tcop/postgres.c to report what the backend is actually doing
 *	(usually "<IDLE>" or the start of the query to be executed).
 * ----------
 */
void
pgstat_report_activity(const char *cmd_str)
{
	volatile PgBackendStatus *beentry;
	TimestampTz start_timestamp;
	int			len;

	if (!pgstat_collect_querystring)
		return;

	/*
	 * To minimize the time spent modifying the entry, fetch all the
	 * needed data first.
	 */
1473
	start_timestamp = GetCurrentStatementStartTimestamp();
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

	len = strlen(cmd_str);
	len = pg_mbcliplen(cmd_str, len, PGBE_ACTIVITY_SIZE - 1);

	/*
	 * Update my status entry, following the protocol of bumping
	 * st_changecount before and after.  We use a volatile pointer here
	 * to ensure the compiler doesn't try to get cute.
	 */
	beentry = MyBEEntry;
	beentry->st_changecount++;

	beentry->st_activity_start_timestamp = start_timestamp;
	memcpy((char *) beentry->st_activity, cmd_str, len);
	beentry->st_activity[len] = '\0';

	beentry->st_changecount++;
	Assert((beentry->st_changecount & 1) == 0);
}


/* ----------
 * pgstat_read_current_status() -
 *
 *	Copy the current contents of the PgBackendStatus array to local memory,
 *	if not already done in this transaction.
 * ----------
 */
static void
pgstat_read_current_status(void)
{
	TransactionId topXid = GetTopTransactionId();
	volatile PgBackendStatus *beentry;
	PgBackendStatus *localentry;
	int			i;

	Assert(!pgStatRunningInCollector);
	if (TransactionIdEquals(pgStatLocalStatusXact, topXid))
		return;					/* already done */

	localBackendStatusTable = (PgBackendStatus *)
		MemoryContextAlloc(TopTransactionContext,
						   sizeof(PgBackendStatus) * MaxBackends);
	localNumBackends = 0;

	beentry = BackendStatusArray;
	localentry = localBackendStatusTable;
	for (i = 1; i <= MaxBackends; i++)
	{
		/*
		 * Follow the protocol of retrying if st_changecount changes while
		 * we copy the entry, or if it's odd.  (The check for odd is needed
		 * to cover the case where we are able to completely copy the entry
		 * while the source backend is between increment steps.)  We use a
		 * volatile pointer here to ensure the compiler doesn't try to get
		 * cute.
		 */
		for (;;)
		{
			int		save_changecount = beentry->st_changecount;

			/*
			 * XXX if PGBE_ACTIVITY_SIZE is really large, it might be best
			 * to use strcpy not memcpy for copying the activity string?
			 */
			memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));

			if (save_changecount == beentry->st_changecount &&
				(save_changecount & 1) == 0)
				break;

			/* Make sure we can break out of loop if stuck... */
			CHECK_FOR_INTERRUPTS();
		}

		beentry++;
		/* Only valid entries get included into the local array */
		if (localentry->st_procpid > 0)
		{
			localentry++;
			localNumBackends++;
		}
	}

	pgStatLocalStatusXact = topXid;
}


/* ------------------------------------------------------------
 * Local support functions follow
 * ------------------------------------------------------------
 */


/* ----------
 * pgstat_setheader() -
 *
 *		Set common header fields in a statistics message
 * ----------
 */
static void
pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
{
	hdr->m_type = mtype;
}


/* ----------
 * pgstat_send() -
 *
 *		Send out one statistics message to the collector
 * ----------
 */
static void
pgstat_send(void *msg, int len)
{
	if (pgStatSock < 0)
		return;
1592

1593
	((PgStat_MsgHdr *) msg)->m_size = len;
1594

1595 1596 1597 1598
#ifdef USE_ASSERT_CHECKING
	if (send(pgStatSock, msg, len, 0) < 0)
		elog(LOG, "could not send to statistics collector: %m");
#else
1599 1600
	send(pgStatSock, msg, len, 0);
	/* We deliberately ignore any error from send() */
1601
#endif
1602 1603 1604
}


1605 1606 1607 1608 1609 1610 1611 1612
/* ----------
 * PgstatBufferMain() -
 *
 *	Start up the statistics buffer process.  This is the body of the
 *	postmaster child process.
 *
 *	The argc/argv parameters are valid only in EXEC_BACKEND case.
 * ----------
1613
 */
1614 1615
NON_EXEC_STATIC void
PgstatBufferMain(int argc, char *argv[])
1616
{
1617
	IsUnderPostmaster = true;	/* we are a postmaster subprocess now */
1618

1619 1620
	MyProcPid = getpid();		/* reset MyProcPid */

1621
	/*
1622
	 * Ignore all signals usually bound to some action in the postmaster,
1623
	 * except for SIGCHLD and SIGQUIT --- see pgstat_recvbuffer.
1624
	 */
1625 1626 1627
	pqsignal(SIGHUP, SIG_IGN);
	pqsignal(SIGINT, SIG_IGN);
	pqsignal(SIGTERM, SIG_IGN);
1628
	pqsignal(SIGQUIT, pgstat_exit);
1629 1630 1631 1632
	pqsignal(SIGALRM, SIG_IGN);
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, SIG_IGN);
	pqsignal(SIGUSR2, SIG_IGN);
1633
	pqsignal(SIGCHLD, pgstat_die);
1634 1635 1636 1637
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);
1638
	/* unblock will happen in pgstat_recvbuffer */
1639 1640

#ifdef EXEC_BACKEND
B
Bruce Momjian 已提交
1641
	pgstat_parseArgs(argc, argv);
1642 1643
#endif

1644
	/*
B
Bruce Momjian 已提交
1645 1646
	 * Start a buffering process to read from the socket, so we have a little
	 * more time to process incoming messages.
1647
	 *
1648 1649 1650 1651 1652
	 * NOTE: the process structure is: postmaster is parent of buffer process
	 * is parent of collector process.	This way, the buffer can detect
	 * collector failure via SIGCHLD, whereas otherwise it wouldn't notice
	 * collector failure until it tried to write on the pipe.  That would mean
	 * that after the postmaster started a new collector, we'd have two buffer
B
Bruce Momjian 已提交
1653
	 * processes competing to read from the UDP socket --- not good.
1654
	 */
1655
	if (pgpipe(pgStatPipe) < 0)
1656
		ereport(ERROR,
1657
				(errcode_for_socket_access(),
B
Bruce Momjian 已提交
1658
				 errmsg("could not create pipe for statistics buffer: %m")));
1659

1660
	/* child becomes collector process */
1661 1662
#ifdef EXEC_BACKEND
	pgStatCollectorPid = pgstat_forkexec(STAT_PROC_COLLECTOR);
1663
#else
1664
	pgStatCollectorPid = fork();
1665
#endif
1666
	switch (pgStatCollectorPid)
1667
	{
1668
		case -1:
1669
			ereport(ERROR,
1670
					(errmsg("could not fork statistics collector: %m")));
1671

1672
#ifndef EXEC_BACKEND
1673
		case 0:
1674
			/* child becomes collector process */
1675
			PgstatCollectorMain(0, NULL);
1676
			break;
1677
#endif
1678 1679 1680

		default:
			/* parent becomes buffer process */
1681
			closesocket(pgStatPipe[0]);
1682
			pgstat_recvbuffer();
1683
	}
1684
	exit(0);
1685 1686 1687
}


1688 1689 1690 1691 1692 1693 1694 1695 1696
/* ----------
 * PgstatCollectorMain() -
 *
 *	Start up the statistics collector itself.  This is the body of the
 *	postmaster grandchild process.
 *
 *	The argc/argv parameters are valid only in EXEC_BACKEND case.
 * ----------
 */
1697
NON_EXEC_STATIC void
1698
PgstatCollectorMain(int argc, char *argv[])
1699 1700 1701 1702 1703
{
	PgStat_Msg	msg;
	fd_set		rfds;
	int			readPipe;
	int			len = 0;
1704
	struct itimerval timeout;
1705
	bool		need_timer = false;
1706

1707 1708 1709
	MyProcPid = getpid();		/* reset MyProcPid */

	/*
B
Bruce Momjian 已提交
1710 1711 1712 1713
	 * Reset signal handling.  With the exception of restoring default SIGCHLD
	 * and SIGQUIT handling, this is a no-op in the non-EXEC_BACKEND case
	 * because we'll have inherited these settings from the buffer process;
	 * but it's not a no-op for EXEC_BACKEND.
1714 1715 1716 1717
	 */
	pqsignal(SIGHUP, SIG_IGN);
	pqsignal(SIGINT, SIG_IGN);
	pqsignal(SIGTERM, SIG_IGN);
1718
#ifndef WIN32
1719
	pqsignal(SIGQUIT, SIG_IGN);
1720 1721 1722 1723
#else
	/* kluge to allow buffer process to kill collector; FIXME */
	pqsignal(SIGQUIT, pgstat_exit);
#endif
1724
	pqsignal(SIGALRM, force_statwrite);
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, SIG_IGN);
	pqsignal(SIGUSR2, SIG_IGN);
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);
	PG_SETMASK(&UnBlockSig);

1735
#ifdef EXEC_BACKEND
B
Bruce Momjian 已提交
1736
	pgstat_parseArgs(argc, argv);
1737 1738
#endif

1739
	/* Close unwanted files */
1740 1741
	closesocket(pgStatPipe[1]);
	closesocket(pgStatSock);
1742

1743 1744 1745
	/*
	 * Identify myself via ps
	 */
1746
	init_ps_display("stats collector process", "", "");
1747 1748
	set_ps_display("");

1749 1750 1751
	/*
	 * Arrange to write the initial status file right away
	 */
1752 1753
	need_statwrite = true;

1754 1755 1756 1757
	/* Preset the delay between status file writes */
	MemSet(&timeout, 0, sizeof(struct itimerval));
	timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
	timeout.it_value.tv_usec = PGSTAT_STAT_INTERVAL % 1000;
1758

1759
	/*
B
Bruce Momjian 已提交
1760 1761
	 * Read in an existing statistics stats file or initialize the stats to
	 * zero.
1762
	 */
1763
	pgStatRunningInCollector = true;
1764
	pgstat_read_statsfile(&pgStatDBHash, InvalidOid);
1765

1766 1767
	readPipe = pgStatPipe[0];

1768
	/*
1769 1770
	 * Process incoming messages and handle all the reporting stuff until
	 * there are no more messages.
1771 1772 1773
	 */
	for (;;)
	{
1774 1775 1776 1777 1778 1779
		/*
		 * If time to write the stats file, do so.  Note that the alarm
		 * interrupt isn't re-enabled immediately, but only after we next
		 * receive a stats message; so no cycles are wasted when there is
		 * nothing going on.
		 */
1780 1781
		if (need_statwrite)
		{
1782 1783 1784
			pgstat_write_statsfile();
			need_statwrite = false;
			need_timer = true;
1785 1786 1787 1788 1789 1790
		}

		/*
		 * Setup the descriptor set for select(2)
		 */
		FD_ZERO(&rfds);
1791
		FD_SET(readPipe, &rfds);
1792 1793 1794 1795

		/*
		 * Now wait for something to do.
		 */
1796
		if (select(readPipe + 1, &rfds, NULL, NULL, NULL) < 0)
1797
		{
1798 1799
			if (errno == EINTR)
				continue;
1800
			ereport(ERROR,
1801
					(errcode_for_socket_access(),
B
Bruce Momjian 已提交
1802
					 errmsg("select() failed in statistics collector: %m")));
1803 1804 1805 1806 1807
		}

		/*
		 * Check if there is a new statistics message to collect.
		 */
1808
		if (FD_ISSET(readPipe, &rfds))
1809 1810
		{
			/*
1811
			 * We may need to issue multiple read calls in case the buffer
B
Bruce Momjian 已提交
1812 1813 1814 1815
			 * process didn't write the message in a single write, which is
			 * possible since it dumps its buffer bytewise. In any case, we'd
			 * need two reads since we don't know the message length
			 * initially.
1816
			 */
1817 1818
			int			nread = 0;
			int			targetlen = sizeof(PgStat_MsgHdr);		/* initial */
1819
			bool		pipeEOF = false;
1820

1821
			while (nread < targetlen)
1822
			{
1823
				len = piperead(readPipe, ((char *) &msg) + nread,
B
Bruce Momjian 已提交
1824
							   targetlen - nread);
1825 1826
				if (len < 0)
				{
1827 1828
					if (errno == EINTR)
						continue;
1829
					ereport(ERROR,
1830
							(errcode_for_socket_access(),
1831
							 errmsg("could not read from statistics collector pipe: %m")));
1832
				}
1833
				if (len == 0)	/* EOF on the pipe! */
1834 1835
				{
					pipeEOF = true;
1836
					break;
1837
				}
1838 1839
				nread += len;
				if (nread == sizeof(PgStat_MsgHdr))
1840
				{
1841 1842 1843 1844 1845 1846
					/* we have the header, compute actual msg length */
					targetlen = msg.msg_hdr.m_size;
					if (targetlen < (int) sizeof(PgStat_MsgHdr) ||
						targetlen > (int) sizeof(msg))
					{
						/*
1847
						 * Bogus message length implies that we got out of
B
Bruce Momjian 已提交
1848 1849
						 * sync with the buffer process somehow. Abort so that
						 * we can restart both processes.
1850
						 */
1851
						ereport(ERROR,
B
Bruce Momjian 已提交
1852
							  (errmsg("invalid statistics message length")));
1853
					}
1854 1855
				}
			}
1856

1857
			/*
B
Bruce Momjian 已提交
1858 1859
			 * EOF on the pipe implies that the buffer process exited. Fall
			 * out of outer loop.
1860
			 */
1861
			if (pipeEOF)
1862
				break;
1863 1864

			/*
B
Bruce Momjian 已提交
1865
			 * Distribute the message to the specific function handling it.
1866 1867 1868 1869 1870 1871 1872
			 */
			switch (msg.msg_hdr.m_type)
			{
				case PGSTAT_MTYPE_DUMMY:
					break;

				case PGSTAT_MTYPE_TABSTAT:
1873
					pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, nread);
1874 1875 1876
					break;

				case PGSTAT_MTYPE_TABPURGE:
1877
					pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, nread);
1878 1879 1880
					break;

				case PGSTAT_MTYPE_DROPDB:
1881
					pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, nread);
1882 1883 1884
					break;

				case PGSTAT_MTYPE_RESETCOUNTER:
1885
					pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
1886
											 nread);
1887 1888
					break;

1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
				case PGSTAT_MTYPE_AUTOVAC_START:
					pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, nread);
					break;

				case PGSTAT_MTYPE_VACUUM:
					pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, nread);
					break;

				case PGSTAT_MTYPE_ANALYZE:
					pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, nread);
					break;

1901 1902 1903 1904
				default:
					break;
			}

1905 1906 1907 1908 1909
			/*
			 * If this is the first message after we wrote the stats file the
			 * last time, enable the alarm interrupt to make it be written
			 * again later.
			 */
1910
			if (need_timer)
1911
			{
1912
				if (setitimer(ITIMER_REAL, &timeout, NULL))
1913
					ereport(ERROR,
1914
						  (errmsg("could not set statistics collector timer: %m")));
1915
				need_timer = false;
1916
			}
1917 1918 1919
		}

		/*
B
Bruce Momjian 已提交
1920 1921 1922 1923
		 * Note that we do NOT check for postmaster exit inside the loop; only
		 * EOF on the buffer pipe causes us to fall out.  This ensures we
		 * don't exit prematurely if there are still a few messages in the
		 * buffer or pipe at postmaster shutdown.
1924 1925
		 */
	}
1926 1927

	/*
B
Bruce Momjian 已提交
1928 1929 1930 1931 1932 1933
	 * Okay, we saw EOF on the buffer pipe, so there are no more messages to
	 * process.  If the buffer process quit because of postmaster shutdown, we
	 * want to save the final stats to reuse at next startup. But if the
	 * buffer process failed, it seems best not to (there may even now be a
	 * new collector firing up, and we don't want it to read a
	 * partially-rewritten stats file).
1934
	 */
1935
	if (!PostmasterIsAlive(false))
1936
		pgstat_write_statsfile();
1937 1938 1939
}


1940
/* SIGALRM signal handler for collector process */
1941 1942 1943 1944 1945 1946 1947
static void
force_statwrite(SIGNAL_ARGS)
{
	need_statwrite = true;
}


1948 1949 1950
/* ----------
 * pgstat_recvbuffer() -
 *
1951
 *	This is the body of the separate buffering process. Its only
1952
 *	purpose is to receive messages from the UDP socket as fast as
1953 1954
 *	possible and forward them over a pipe into the collector itself.
 *	If the collector is slow to absorb messages, they are buffered here.
1955 1956 1957
 * ----------
 */
static void
1958
pgstat_recvbuffer(void)
1959
{
1960 1961
	fd_set		rfds;
	fd_set		wfds;
1962
	struct timeval timeout;
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
	int			writePipe = pgStatPipe[1];
	int			maxfd;
	int			len;
	int			xfr;
	int			frm;
	PgStat_Msg	input_buffer;
	char	   *msgbuffer;
	int			msg_send = 0;	/* next send index in buffer */
	int			msg_recv = 0;	/* next receive index */
	int			msg_have = 0;	/* number of bytes stored */
	bool		overflow = false;
1974

1975 1976 1977
	/*
	 * Identify myself via ps
	 */
1978
	init_ps_display("stats buffer process", "", "");
1979 1980
	set_ps_display("");

1981
	/*
B
Bruce Momjian 已提交
1982 1983 1984 1985 1986
	 * We want to die if our child collector process does.	There are two ways
	 * we might notice that it has died: receive SIGCHLD, or get a write
	 * failure on the pipe leading to the child.  We can set SIGPIPE to kill
	 * us here.  Our SIGCHLD handler was already set up before we forked (must
	 * do it that way, else it's a race condition).
1987 1988 1989 1990 1991
	 */
	pqsignal(SIGPIPE, SIG_DFL);
	PG_SETMASK(&UnBlockSig);

	/*
B
Bruce Momjian 已提交
1992 1993
	 * Set the write pipe to nonblock mode, so that we cannot block when the
	 * collector falls behind.
1994
	 */
1995
	if (!pg_set_noblock(writePipe))
1996
		ereport(ERROR,
1997
				(errcode_for_socket_access(),
B
Bruce Momjian 已提交
1998
				 errmsg("could not set statistics collector pipe to nonblocking mode: %m")));
1999

2000 2001 2002
	/*
	 * Allocate the message buffer
	 */
2003
	msgbuffer = (char *) palloc(PGSTAT_RECVBUFFERSZ);
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

	/*
	 * Loop forever
	 */
	for (;;)
	{
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		maxfd = -1;

		/*
2015 2016
		 * As long as we have buffer space we add the socket to the read
		 * descriptor set.
2017
		 */
2018
		if (msg_have <= (int) (PGSTAT_RECVBUFFERSZ - sizeof(PgStat_Msg)))
2019 2020 2021
		{
			FD_SET(pgStatSock, &rfds);
			maxfd = pgStatSock;
2022
			overflow = false;
2023 2024 2025
		}
		else
		{
2026
			if (!overflow)
2027
			{
2028 2029
				ereport(LOG,
						(errmsg("statistics buffer is full")));
2030
				overflow = true;
2031 2032 2033 2034
			}
		}

		/*
2035
		 * If we have messages to write out, we add the pipe to the write
2036
		 * descriptor set.
2037 2038 2039
		 */
		if (msg_have > 0)
		{
2040 2041 2042
			FD_SET(writePipe, &wfds);
			if (writePipe > maxfd)
				maxfd = writePipe;
2043 2044
		}

2045 2046 2047
		/*
		 * Wait for some work to do; but not for more than 10 seconds. (This
		 * determines how quickly we will shut down after an ungraceful
2048 2049 2050 2051
		 * postmaster termination; so it needn't be very fast.)
		 *
		 * struct timeout is modified by select() on some operating systems,
		 * so re-fill it each time.
2052 2053 2054 2055
		 */
		timeout.tv_sec = 10;
		timeout.tv_usec = 0;

2056
		if (select(maxfd + 1, &rfds, &wfds, NULL, &timeout) < 0)
2057
		{
2058 2059
			if (errno == EINTR)
				continue;
2060
			ereport(ERROR,
2061
					(errcode_for_socket_access(),
2062
					 errmsg("select() failed in statistics buffer: %m")));
2063 2064 2065 2066 2067 2068 2069 2070
		}

		/*
		 * If there is a message on the socket, read it and check for
		 * validity.
		 */
		if (FD_ISSET(pgStatSock, &rfds))
		{
2071 2072
			len = recv(pgStatSock, (char *) &input_buffer,
					   sizeof(PgStat_Msg), 0);
2073
			if (len < 0)
2074
				ereport(ERROR,
2075
						(errcode_for_socket_access(),
B
Bruce Momjian 已提交
2076
						 errmsg("could not read statistics message: %m")));
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

			/*
			 * We ignore messages that are smaller than our common header
			 */
			if (len < sizeof(PgStat_MsgHdr))
				continue;

			/*
			 * The received length must match the length in the header
			 */
2087
			if (input_buffer.msg_hdr.m_size != len)
2088 2089 2090
				continue;

			/*
2091 2092
			 * O.K. - we accept this message.  Copy it to the circular
			 * msgbuffer.
2093
			 */
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
			frm = 0;
			while (len > 0)
			{
				xfr = PGSTAT_RECVBUFFERSZ - msg_recv;
				if (xfr > len)
					xfr = len;
				Assert(xfr > 0);
				memcpy(msgbuffer + msg_recv,
					   ((char *) &input_buffer) + frm,
					   xfr);
				msg_recv += xfr;
				if (msg_recv == PGSTAT_RECVBUFFERSZ)
					msg_recv = 0;
				msg_have += xfr;
				frm += xfr;
				len -= xfr;
			}
2111 2112 2113
		}

		/*
2114 2115 2116
		 * If the collector is ready to receive, write some data into his
		 * pipe.  We may or may not be able to write all that we have.
		 *
B
Bruce Momjian 已提交
2117 2118 2119 2120 2121 2122 2123 2124
		 * NOTE: if what we have is less than PIPE_BUF bytes but more than the
		 * space available in the pipe buffer, most kernels will refuse to
		 * write any of it, and will return EAGAIN.  This means we will
		 * busy-loop until the situation changes (either because the collector
		 * caught up, or because more data arrives so that we have more than
		 * PIPE_BUF bytes buffered).  This is not good, but is there any way
		 * around it?  We have no way to tell when the collector has caught
		 * up...
2125
		 */
2126
		if (FD_ISSET(writePipe, &wfds))
2127
		{
2128 2129 2130 2131
			xfr = PGSTAT_RECVBUFFERSZ - msg_send;
			if (xfr > msg_have)
				xfr = msg_have;
			Assert(xfr > 0);
2132
			len = pipewrite(writePipe, msgbuffer + msg_send, xfr);
2133 2134
			if (len < 0)
			{
2135 2136
				if (errno == EINTR || errno == EAGAIN)
					continue;	/* not enough space in pipe */
2137
				ereport(ERROR,
2138
						(errcode_for_socket_access(),
B
Bruce Momjian 已提交
2139
				errmsg("could not write to statistics collector pipe: %m")));
2140
			}
2141 2142
			/* NB: len < xfr is okay */
			msg_send += len;
2143 2144
			if (msg_send == PGSTAT_RECVBUFFERSZ)
				msg_send = 0;
2145
			msg_have -= len;
2146 2147 2148
		}

		/*
B
Bruce Momjian 已提交
2149 2150
		 * Make sure we forwarded all messages before we check for postmaster
		 * termination.
2151
		 */
2152
		if (msg_have != 0 || FD_ISSET(pgStatSock, &rfds))
2153 2154 2155
			continue;

		/*
B
Bruce Momjian 已提交
2156 2157
		 * If the postmaster has terminated, we die too.  (This is no longer
		 * the normal exit path, however.)
2158
		 */
2159
		if (!PostmasterIsAlive(true))
2160 2161 2162 2163
			exit(0);
	}
}

2164 2165 2166 2167 2168
/* SIGQUIT signal handler for buffer process */
static void
pgstat_exit(SIGNAL_ARGS)
{
	/*
B
Bruce Momjian 已提交
2169 2170 2171
	 * For now, we just nail the doors shut and get out of town.  It might be
	 * cleaner to allow any pending messages to be sent, but that creates a
	 * tradeoff against speed of exit.
2172
	 */
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182

	/*
	 * If running in bufferer, kill our collector as well. On some broken
	 * win32 systems, it does not shut down automatically because of issues
	 * with socket inheritance.  XXX so why not fix the socket inheritance...
	 */
#ifdef WIN32
	if (pgStatCollectorPid > 0)
		kill(pgStatCollectorPid, SIGQUIT);
#endif
2183 2184 2185 2186
	exit(0);
}

/* SIGCHLD signal handler for buffer process */
2187 2188 2189 2190 2191 2192
static void
pgstat_die(SIGNAL_ARGS)
{
	exit(1);
}

2193

2194 2195
/*
 * Lookup the hash table entry for the specified database. If no hash
2196 2197
 * table entry exists, initialize it, if the create parameter is true.
 * Else, return NULL.
2198 2199
 */
static PgStat_StatDBEntry *
2200
pgstat_get_db_entry(Oid databaseid, bool create)
2201 2202
{
	PgStat_StatDBEntry *result;
B
Bruce Momjian 已提交
2203 2204
	bool		found;
	HASHACTION	action = (create ? HASH_ENTER : HASH_FIND);
2205 2206 2207 2208

	/* Lookup or create the hash table entry for this database */
	result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
												&databaseid,
2209 2210 2211 2212
												action, &found);

	if (!create && !found)
		return NULL;
2213

2214
	/* If not found, initialize the new one. */
2215 2216
	if (!found)
	{
2217
		HASHCTL		hash_ctl;
2218

2219 2220 2221 2222 2223
		result->tables = NULL;
		result->n_xact_commit = 0;
		result->n_xact_rollback = 0;
		result->n_blocks_fetched = 0;
		result->n_blocks_hit = 0;
2224
		result->last_autovac_time = 0;
2225 2226

		memset(&hash_ctl, 0, sizeof(hash_ctl));
2227
		hash_ctl.keysize = sizeof(Oid);
2228
		hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2229
		hash_ctl.hash = oid_hash;
2230
		result->tables = hash_create("Per-database table",
B
Bruce Momjian 已提交
2231 2232 2233
									 PGSTAT_TAB_HASH_SIZE,
									 &hash_ctl,
									 HASH_ELEM | HASH_FUNCTION);
2234 2235
	}

2236
	return result;
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
}


/* ----------
 * pgstat_write_statsfile() -
 *
 *	Tell the news.
 * ----------
 */
static void
pgstat_write_statsfile(void)
{
2249 2250 2251 2252 2253
	HASH_SEQ_STATUS hstat;
	HASH_SEQ_STATUS tstat;
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;
	FILE	   *fpout;
2254
	int32		format_id;
2255 2256

	/*
2257
	 * Open the statistics temp file to write out the current values.
2258
	 */
2259
	fpout = fopen(PGSTAT_STAT_TMPFILE, PG_BINARY_W);
2260 2261
	if (fpout == NULL)
	{
2262 2263
		ereport(LOG,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2264 2265
				 errmsg("could not open temporary statistics file \"%s\": %m",
						PGSTAT_STAT_TMPFILE)));
2266 2267 2268
		return;
	}

2269 2270 2271 2272 2273 2274
	/*
	 * Write the file header --- currently just a format ID.
	 */
	format_id = PGSTAT_FILE_FORMAT_ID;
	fwrite(&format_id, sizeof(format_id), 1, fpout);

2275 2276 2277 2278
	/*
	 * Walk through the database table.
	 */
	hash_seq_init(&hstat, pgStatDBHash);
2279
	while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2280 2281
	{
		/*
2282 2283 2284
		 * Write out the DB entry including the number of live backends.
		 * We don't write the tables pointer since it's of no use to any
		 * other process.
2285 2286
		 */
		fputc('D', fpout);
2287
		fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2288 2289

		/*
2290
		 * Walk through the database's access stats per table.
2291 2292
		 */
		hash_seq_init(&tstat, dbentry->tables);
2293
		while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2294 2295 2296 2297
		{
			fputc('T', fpout);
			fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
		}
2298

2299 2300 2301 2302 2303 2304 2305
		/*
		 * Mark the end of this DB
		 */
		fputc('d', fpout);
	}

	/*
2306
	 * No more output to be done. Close the temp file and replace the old
2307 2308
	 * pgstat.stat with it.  The ferror() check replaces testing for error
	 * after each individual fputc or fwrite above.
2309 2310
	 */
	fputc('E', fpout);
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321

	if (ferror(fpout))
	{
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not write temporary statistics file \"%s\": %m",
						PGSTAT_STAT_TMPFILE)));
		fclose(fpout);
		unlink(PGSTAT_STAT_TMPFILE);
	}
	else if (fclose(fpout) < 0)
2322
	{
2323 2324
		ereport(LOG,
				(errcode_for_file_access(),
B
Bruce Momjian 已提交
2325 2326
			   errmsg("could not close temporary statistics file \"%s\": %m",
					  PGSTAT_STAT_TMPFILE)));
2327
		unlink(PGSTAT_STAT_TMPFILE);
2328
	}
2329
	else if (rename(PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME) < 0)
2330
	{
2331 2332 2333 2334 2335
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
						PGSTAT_STAT_TMPFILE, PGSTAT_STAT_FILENAME)));
		unlink(PGSTAT_STAT_TMPFILE);
2336 2337 2338 2339 2340 2341 2342
	}
}


/* ----------
 * pgstat_read_statsfile() -
 *
2343 2344
 *	Reads in an existing statistics collector file and initializes the
 *	databases' hash table (whose entries point to the tables' hash tables).
2345 2346 2347
 * ----------
 */
static void
2348
pgstat_read_statsfile(HTAB **dbhash, Oid onlydb)
2349
{
2350 2351 2352 2353 2354 2355 2356
	PgStat_StatDBEntry *dbentry;
	PgStat_StatDBEntry dbbuf;
	PgStat_StatTabEntry *tabentry;
	PgStat_StatTabEntry tabbuf;
	HASHCTL		hash_ctl;
	HTAB	   *tabhash = NULL;
	FILE	   *fpin;
2357
	int32		format_id;
2358 2359 2360 2361 2362
	bool		found;
	MemoryContext use_mcxt;
	int			mcxt_flags;

	/*
2363
	 * If running in the collector or the autovacuum process, we use the
B
Bruce Momjian 已提交
2364
	 * DynaHashCxt memory context.	If running in a backend, we use the
2365 2366 2367
	 * TopTransactionContext instead, so the caller must only know the last
	 * XactId when this call happened to know if his tables are still valid or
	 * already gone!
2368
	 */
2369
	if (pgStatRunningInCollector || IsAutoVacuumProcess())
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
	{
		use_mcxt = NULL;
		mcxt_flags = 0;
	}
	else
	{
		use_mcxt = TopTransactionContext;
		mcxt_flags = HASH_CONTEXT;
	}

	/*
	 * Create the DB hashtable
	 */
	memset(&hash_ctl, 0, sizeof(hash_ctl));
2384
	hash_ctl.keysize = sizeof(Oid);
2385
	hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
2386
	hash_ctl.hash = oid_hash;
2387 2388 2389
	hash_ctl.hcxt = use_mcxt;
	*dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
						  HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2390 2391

	/*
B
Bruce Momjian 已提交
2392 2393 2394
	 * Try to open the status file. If it doesn't exist, the backends simply
	 * return zero for anything and the collector simply starts from scratch
	 * with empty counters.
2395
	 */
2396
	if ((fpin = AllocateFile(PGSTAT_STAT_FILENAME, PG_BINARY_R)) == NULL)
2397 2398
		return;

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
	/*
	 * Verify it's of the expected format.
	 */
	if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
		|| format_id != PGSTAT_FILE_FORMAT_ID)
	{
		ereport(pgStatRunningInCollector ? LOG : WARNING,
				(errmsg("corrupted pgstat.stat file")));
		goto done;
	}

2410
	/*
2411 2412
	 * We found an existing collector stats file. Read it and put all the
	 * hashtable entries into place.
2413 2414 2415 2416 2417
	 */
	for (;;)
	{
		switch (fgetc(fpin))
		{
2418 2419
				/*
				 * 'D'	A PgStat_StatDBEntry struct describing a database
B
Bruce Momjian 已提交
2420 2421
				 * follows. Subsequently, zero to many 'T' entries will follow
				 * until a 'd' is encountered.
2422
				 */
2423
			case 'D':
2424 2425
				if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
						  fpin) != offsetof(PgStat_StatDBEntry, tables))
2426
				{
2427 2428
					ereport(pgStatRunningInCollector ? LOG : WARNING,
							(errmsg("corrupted pgstat.stat file")));
2429
					goto done;
2430 2431 2432 2433 2434
				}

				/*
				 * Add to the DB hash
				 */
2435
				dbentry = (PgStat_StatDBEntry *) hash_search(*dbhash,
B
Bruce Momjian 已提交
2436
												  (void *) &dbbuf.databaseid,
2437 2438
															 HASH_ENTER,
															 &found);
2439 2440
				if (found)
				{
2441 2442
					ereport(pgStatRunningInCollector ? LOG : WARNING,
							(errmsg("corrupted pgstat.stat file")));
2443
					goto done;
2444 2445 2446
				}

				memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
2447
				dbentry->tables = NULL;
2448 2449

				/*
2450 2451
				 * Don't collect tables if not the requested DB (or the
				 * shared-table info)
2452
				 */
2453 2454 2455 2456
				if (onlydb != InvalidOid)
				{
					if (dbbuf.databaseid != onlydb &&
						dbbuf.databaseid != InvalidOid)
B
Bruce Momjian 已提交
2457
						break;
2458
				}
2459 2460

				memset(&hash_ctl, 0, sizeof(hash_ctl));
2461
				hash_ctl.keysize = sizeof(Oid);
2462
				hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2463
				hash_ctl.hash = oid_hash;
2464
				hash_ctl.hcxt = use_mcxt;
2465 2466 2467
				dbentry->tables = hash_create("Per-database table",
											  PGSTAT_TAB_HASH_SIZE,
											  &hash_ctl,
B
Bruce Momjian 已提交
2468
									 HASH_ELEM | HASH_FUNCTION | mcxt_flags);
2469 2470

				/*
2471
				 * Arrange that following 'T's add entries to this database's
B
Bruce Momjian 已提交
2472
				 * tables hash table.
2473 2474 2475 2476
				 */
				tabhash = dbentry->tables;
				break;

2477 2478 2479
				/*
				 * 'd'	End of this database.
				 */
2480 2481 2482 2483
			case 'd':
				tabhash = NULL;
				break;

2484 2485 2486
				/*
				 * 'T'	A PgStat_StatTabEntry follows.
				 */
2487
			case 'T':
2488 2489
				if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
						  fpin) != sizeof(PgStat_StatTabEntry))
2490
				{
2491 2492
					ereport(pgStatRunningInCollector ? LOG : WARNING,
							(errmsg("corrupted pgstat.stat file")));
2493
					goto done;
2494 2495 2496 2497 2498 2499 2500 2501
				}

				/*
				 * Skip if table belongs to a not requested database.
				 */
				if (tabhash == NULL)
					break;

2502
				tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
B
Bruce Momjian 已提交
2503 2504
													(void *) &tabbuf.tableid,
														 HASH_ENTER, &found);
2505 2506 2507

				if (found)
				{
2508 2509
					ereport(pgStatRunningInCollector ? LOG : WARNING,
							(errmsg("corrupted pgstat.stat file")));
2510
					goto done;
2511 2512 2513 2514 2515
				}

				memcpy(tabentry, &tabbuf, sizeof(tabbuf));
				break;

2516
				/*
2517
				 * 'E'	The EOF marker of a complete stats file.
2518
				 */
2519 2520
			case 'E':
				goto done;
2521

2522 2523 2524 2525 2526 2527
			default:
				ereport(pgStatRunningInCollector ? LOG : WARNING,
						(errmsg("corrupted pgstat.stat file")));
				goto done;
		}
	}
2528

2529 2530 2531
done:
	FreeFile(fpin);
}
2532

2533 2534 2535 2536
/*
 * If not done for this transaction, read the statistics collector
 * stats file into some hash tables.
 *
2537
 * Because we store the tables in TopTransactionContext, the result
2538
 * is good for the entire current main transaction.
2539 2540 2541 2542 2543
 *
 * Inside the autovacuum process, the statfile is assumed to be valid
 * "forever", that is one iteration, within one database.  This means
 * we only consider the statistics as they were when the autovacuum
 * iteration started.
2544 2545 2546 2547
 */
static void
backend_read_statsfile(void)
{
2548
	if (IsAutoVacuumProcess())
2549
	{
2550 2551 2552
		/* already read it? */
		if (pgStatDBHash)
			return;
2553
		Assert(!pgStatRunningInCollector);
2554
		pgstat_read_statsfile(&pgStatDBHash, InvalidOid);
2555 2556 2557 2558 2559 2560 2561 2562
	}
	else
	{
		TransactionId topXid = GetTopTransactionId();

		if (!TransactionIdEquals(pgStatDBHashXact, topXid))
		{
			Assert(!pgStatRunningInCollector);
2563
			pgstat_read_statsfile(&pgStatDBHash, MyDatabaseId);
2564 2565
			pgStatDBHashXact = topXid;
		}
2566 2567 2568
	}
}

2569 2570 2571 2572 2573 2574 2575 2576 2577
/* ----------
 * pgstat_recv_tabstat() -
 *
 *	Count what the backend has done.
 * ----------
 */
static void
pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
{
2578 2579 2580 2581 2582
	PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;
	int			i;
	bool		found;
2583

2584
	dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
2585 2586

	/*
2587
	 * Update database-wide stats.
2588
	 */
2589 2590
	dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
	dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
2591 2592 2593 2594 2595 2596

	/*
	 * Process all table entries in the message.
	 */
	for (i = 0; i < msg->m_nentries; i++)
	{
2597
		tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
B
Bruce Momjian 已提交
2598 2599
												  (void *) &(tabmsg[i].t_id),
													   HASH_ENTER, &found);
2600 2601 2602 2603

		if (!found)
		{
			/*
B
Bruce Momjian 已提交
2604 2605
			 * If it's a new table entry, initialize counters to the values we
			 * just got.
2606
			 */
2607 2608 2609 2610 2611 2612
			tabentry->numscans = tabmsg[i].t_numscans;
			tabentry->tuples_returned = tabmsg[i].t_tuples_returned;
			tabentry->tuples_fetched = tabmsg[i].t_tuples_fetched;
			tabentry->tuples_inserted = tabmsg[i].t_tuples_inserted;
			tabentry->tuples_updated = tabmsg[i].t_tuples_updated;
			tabentry->tuples_deleted = tabmsg[i].t_tuples_deleted;
B
Bruce Momjian 已提交
2613

2614 2615 2616
			tabentry->n_live_tuples = tabmsg[i].t_tuples_inserted;
			tabentry->n_dead_tuples = tabmsg[i].t_tuples_updated +
				tabmsg[i].t_tuples_deleted;
2617
			tabentry->last_anl_tuples = 0;
2618 2619 2620 2621
			tabentry->vacuum_timestamp = 0;
			tabentry->autovac_vacuum_timestamp = 0;
			tabentry->analyze_timestamp = 0;
			tabentry->autovac_analyze_timestamp = 0;
2622 2623 2624

			tabentry->blocks_fetched = tabmsg[i].t_blocks_fetched;
			tabentry->blocks_hit = tabmsg[i].t_blocks_hit;
2625 2626 2627 2628 2629 2630
		}
		else
		{
			/*
			 * Otherwise add the values to the existing entry.
			 */
2631 2632 2633 2634 2635 2636
			tabentry->numscans += tabmsg[i].t_numscans;
			tabentry->tuples_returned += tabmsg[i].t_tuples_returned;
			tabentry->tuples_fetched += tabmsg[i].t_tuples_fetched;
			tabentry->tuples_inserted += tabmsg[i].t_tuples_inserted;
			tabentry->tuples_updated += tabmsg[i].t_tuples_updated;
			tabentry->tuples_deleted += tabmsg[i].t_tuples_deleted;
2637

2638 2639
			tabentry->n_live_tuples += tabmsg[i].t_tuples_inserted -
				tabmsg[i].t_tuples_deleted;
2640 2641
			tabentry->n_dead_tuples += tabmsg[i].t_tuples_updated +
				tabmsg[i].t_tuples_deleted;
2642 2643 2644

			tabentry->blocks_fetched += tabmsg[i].t_blocks_fetched;
			tabentry->blocks_hit += tabmsg[i].t_blocks_hit;
2645 2646 2647 2648 2649
		}

		/*
		 * And add the block IO to the database entry.
		 */
2650 2651
		dbentry->n_blocks_fetched += tabmsg[i].t_blocks_fetched;
		dbentry->n_blocks_hit += tabmsg[i].t_blocks_hit;
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
	}
}


/* ----------
 * pgstat_recv_tabpurge() -
 *
 *	Arrange for dead table removal.
 * ----------
 */
static void
pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
{
2665 2666
	PgStat_StatDBEntry *dbentry;
	int			i;
2667

2668 2669 2670 2671 2672 2673 2674
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);

	/*
	 * No need to purge if we don't even know the database.
	 */
	if (!dbentry || !dbentry->tables)
		return;
2675 2676 2677 2678 2679 2680

	/*
	 * Process all table entries in the message.
	 */
	for (i = 0; i < msg->m_nentries; i++)
	{
2681 2682 2683 2684
		/* Remove from hashtable if present; we don't care if it's not. */
		(void) hash_search(dbentry->tables,
						   (void *) &(msg->m_tableid[i]),
						   HASH_REMOVE, NULL);
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
	}
}


/* ----------
 * pgstat_recv_dropdb() -
 *
 *	Arrange for dead database removal
 * ----------
 */
static void
pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
{
2698
	PgStat_StatDBEntry *dbentry;
2699 2700 2701 2702

	/*
	 * Lookup the database in the hashtable.
	 */
2703
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
2704 2705

	/*
2706
	 * If found, remove it.
2707
	 */
2708
	if (dbentry)
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
	{
		if (dbentry->tables != NULL)
			hash_destroy(dbentry->tables);

		if (hash_search(pgStatDBHash,
						(void *) &(dbentry->databaseid),
						HASH_REMOVE, NULL) == NULL)
			ereport(ERROR,
					(errmsg("database hash table corrupted "
							"during cleanup --- abort")));
	}
2720 2721 2722 2723
}


/* ----------
2724
 * pgstat_recv_resetcounter() -
2725
 *
2726
 *	Reset the statistics for the specified database.
2727 2728 2729 2730 2731
 * ----------
 */
static void
pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
{
2732 2733
	HASHCTL		hash_ctl;
	PgStat_StatDBEntry *dbentry;
2734 2735

	/*
2736
	 * Lookup the database in the hashtable.  Nothing to do if not there.
2737
	 */
2738 2739 2740 2741
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);

	if (!dbentry)
		return;
2742 2743

	/*
B
Bruce Momjian 已提交
2744 2745
	 * We simply throw away all the database's table entries by recreating a
	 * new hash table for them.
2746 2747 2748 2749
	 */
	if (dbentry->tables != NULL)
		hash_destroy(dbentry->tables);

2750 2751 2752 2753 2754
	dbentry->tables = NULL;
	dbentry->n_xact_commit = 0;
	dbentry->n_xact_rollback = 0;
	dbentry->n_blocks_fetched = 0;
	dbentry->n_blocks_hit = 0;
2755 2756

	memset(&hash_ctl, 0, sizeof(hash_ctl));
2757
	hash_ctl.keysize = sizeof(Oid);
2758
	hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2759
	hash_ctl.hash = oid_hash;
2760 2761 2762 2763
	dbentry->tables = hash_create("Per-database table",
								  PGSTAT_TAB_HASH_SIZE,
								  &hash_ctl,
								  HASH_ELEM | HASH_FUNCTION);
2764
}
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833

/* ----------
 * pgstat_recv_autovac() -
 *
 *	Process an autovacuum signalling message.
 * ----------
 */
static void
pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
{
	PgStat_StatDBEntry *dbentry;

	/*
	 * Lookup the database in the hashtable.  Don't create the entry if it
	 * doesn't exist, because autovacuum may be processing a template
	 * database.  If this isn't the case, the database is most likely to have
	 * an entry already.  (If it doesn't, not much harm is done anyway --
	 * it'll get created as soon as somebody actually uses the database.)
	 */
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
	if (dbentry == NULL)
		return;

	/*
	 * Store the last autovacuum time in the database entry.
	 */
	dbentry->last_autovac_time = msg->m_start_time;
}

/* ----------
 * pgstat_recv_vacuum() -
 *
 *	Process a VACUUM message.
 * ----------
 */
static void
pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
{
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;

	/*
	 * Don't create either the database or table entry if it doesn't already
	 * exist.  This avoids bloating the stats with entries for stuff that is
	 * only touched by vacuum and not by live operations.
	 */
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
	if (dbentry == NULL)
		return;

	tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
						   HASH_FIND, NULL);
	if (tabentry == NULL)
		return;

	if (msg->m_autovacuum) 
		tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
	else 
		tabentry->vacuum_timestamp = msg->m_vacuumtime; 
	tabentry->n_live_tuples = msg->m_tuples;
	tabentry->n_dead_tuples = 0;
	if (msg->m_analyze)
	{
		tabentry->last_anl_tuples = msg->m_tuples;
		if (msg->m_autovacuum)
			tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
		else
			tabentry->analyze_timestamp = msg->m_vacuumtime;
	}
2834 2835 2836 2837 2838 2839
	else
	{
		/* last_anl_tuples must never exceed n_live_tuples */
		tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
										msg->m_tuples);
	}
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
}

/* ----------
 * pgstat_recv_analyze() -
 *
 *	Process an ANALYZE message.
 * ----------
 */
static void
pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
{
	PgStat_StatDBEntry *dbentry;
	PgStat_StatTabEntry *tabentry;

	/*
	 * Don't create either the database or table entry if it doesn't already
	 * exist.  This avoids bloating the stats with entries for stuff that is
	 * only touched by analyze and not by live operations.
	 */
	dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
	if (dbentry == NULL)
		return;

	tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
						   HASH_FIND, NULL);
	if (tabentry == NULL)
		return;

	if (msg->m_autovacuum) 
		tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
	else 
		tabentry->analyze_timestamp = msg->m_analyzetime;
	tabentry->n_live_tuples = msg->m_live_tuples;
	tabentry->n_dead_tuples = msg->m_dead_tuples;
	tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
}